carlos / platform Public

edge: one client scrub list; read and strip Carlos-Page-Cache everywhere

assetVocabulary becomes clientScrubVocabulary and gains Carlos-Page-Cache.
Every client-boundary scrub iterates it (stripAssetResponseHeaders,
stripAssetTrailers, assetInformationalScrub, scrubBackhaulResponse,
stripAssetFillVocabulary, assetStoredHeader), keeping only what an
explicit keep set names. scrub_guard_test.go runs each scrub against each
entry on every surface and fails on any non-test site that names an entry
by itself beyond the counted request-side ones.

ServeHTTP attaches a page mark holder to every proxied instance request;
responseModifier records the final header's marker (takePageMark) before
the scrub; maybeStore refuses a Marked response. The activator and local
proxy calls write through assetInformationalScrub.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b5ae1ad1d308f184fb5785c48a7bf9794ad91b56 parent 00944be
8 files changed, +1,107 −57
  • internal/edge/assetadmit.go +4 −3
  • internal/edge/assetcatch.go +61 −43
  • internal/edge/assetserve.go +1 −1
  • internal/edge/cookiescope.go +9 −6
  • internal/edge/edge.go +23 −4
  • internal/edge/pagemark.go +110 −0
  • internal/edge/pagemark_test.go +481 −0
  • internal/edge/scrub_guard_test.go +418 −0

Intent

Human

<task-notification> <task-id>af7b7ab4db2ff9700</task-id> <tool-use-id>toolu_01XYDSAYiEEDjyh5pkCcC6mx</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/af7b7ab4db2ff9700.output</output-file> <status>completed</status> <summary>Agent "Implement Task 4: PagesOff switch" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE Commit: 00944be5 "registry: per-instance pages switch, mirrored on assets_off" Tests: the new tests failed to compile before the change and pass after it. Registry `Fingerprint|Forward|Upsert|RoundTrip|Column|Remote|Pages` and provision `Pages|Assets|RouteFor|Reconcile|Shape|Record` are green. The four named Task 4 tests are `TestSetPagesRoundTripsAndMovesFingerprint`, `TestConvergeAppliesPagesSwitch`, `TestForwardRowRefusesPagesOff` and `TestUpsertKeepsPagesOffUnlessTheTenantChanges`. Concerns: - The provision tests hit a read-only go-build cache entry inside the sandbox, so I ran that package outside it with the default GOCACHE. - Pages has no generation. A plain `Upsert` of a host whose tenant is unchanged therefore always keeps `pages_off`, and only `SetPages` can clear it. For assets the keep also depends on `asset_gen`. - I added `PagesOff: true` to the all-columns round-trip fixture in `registry_test.go`. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/edge-page-cache-1/.superpowers/sdd/2026-11-08-edge-page-cache-plan-1-home/task-4-report.md</result> <usage><subagent_tokens>77286</subagent_tokens><tool_uses>18</tool_uses><duration_ms>295124</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bw02tujta</task-id> <tool-use-id>toolu_01L9zJpe3AFma3f9Xgm2EVKz</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/d79ef2b4-4291-4945-bd45-b3f16796c4ba/tasks/bw02tujta.output</output-file> <status>completed</status> <summary>Background command "Run Astra review of Task 4" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 21.4 g CO₂e (2,783,713 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on edge-page-cache-1, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/edge/assetadmit.go b/internal/edge/assetadmit.go
index 2ff03170e..f344d082b 100644
--- a/internal/edge/assetadmit.go
+++ b/internal/edge/assetadmit.go
@@ -196,8 +196,9 @@ func assetTrailerVeto(trailer http.Header) bool {
// Transfer-Encoding, Upgrade, TE, Trailer, Proxy-*;
// - Date (regenerated), Age (recomputed), Content-Length (recomputed per
// representation);
-// - the purge headers, Carlos-Cache and every X-Carlos-* header, which belong
-// to the platform and are never the app's to store or replay.
+// - the purge headers, every X-Carlos-* header and the client scrub
+// vocabulary (Carlos-Cache, Carlos-Page-Cache), which belong to the
+// platform and are never the app's to store or replay.
func assetStoredHeader(h http.Header) http.Header {
out := h.Clone()
if out == nil {
@@ -224,7 +225,7 @@ func assetStoredHeader(h http.Header) http.Header {
delete(out, k)
case lk == "connection", lk == "keep-alive", lk == "transfer-encoding", lk == "upgrade",
lk == "te", lk == "trailer", lk == "date", lk == "age", lk == "content-length",
- lk == "carlos-purge", lk == "carlos-purge-host", lk == "carlos-cache":
+ lk == "carlos-purge", lk == "carlos-purge-host", isClientScrubVocabulary(k):
delete(out, k)
}
}
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go
index ec7e4b352..5612a963d 100644
--- a/internal/edge/assetcatch.go
+++ b/internal/edge/assetcatch.go
@@ -897,7 +897,7 @@ func (fw *assetFillWriter) finish(brokeOff bool) (*assetcache.Entry, error) {
if teeBody && len(trailers) > 0 {
h := fw.w.Header()
for k, vs := range trailers {
- if vs != nil && !isAssetVocabulary(strings.TrimPrefix(k, http.TrailerPrefix)) {
+ if vs != nil && !isClientScrubVocabulary(strings.TrimPrefix(k, http.TrailerPrefix)) {
h[k] = vs
}
}
@@ -960,14 +960,21 @@ func assetTrailers(snap, final http.Header) http.Header {
return t
}
-// assetVocabulary is the asset cache's header vocabulary: the fill,
-// acknowledgement and expiry headers and Carlos-Cache are the platform's to
-// set, never the app's (§5.3).
-var assetVocabulary = []string{assetFillHeader, assetAckHeader, assetExpiresHeader, assetCacheHeader}
-
-// isAssetVocabulary reports whether name is one of assetVocabulary.
-func isAssetVocabulary(name string) bool {
- for _, v := range assetVocabulary {
+// clientScrubVocabulary is the client boundary's one header list: names the
+// platform sets or reads, never the app's to send a visitor. The asset
+// cache's fill, acknowledgement and expiry headers and Carlos-Cache (§5.3),
+// and the page cache's marker, Carlos-Page-Cache (page cache design §4.1),
+// which this edge reads (takePageMark) and never passes on. Every scrub
+// iterates this list, keeping only what an explicit keep set names
+// (stripVocabularyExcept); none keeps a list of its own. A new entry is
+// scrubbed everywhere at once, and scrub_guard_test.go fails on a scrub
+// that names one by itself.
+var clientScrubVocabulary = []string{assetFillHeader, assetAckHeader, assetExpiresHeader, assetCacheHeader, pageCacheHeader}
+
+// isClientScrubVocabulary reports whether name is one of
+// clientScrubVocabulary.
+func isClientScrubVocabulary(name string) bool {
+ for _, v := range clientScrubVocabulary {
if strings.EqualFold(strings.TrimSpace(name), v) {
return true
}
@@ -975,32 +982,45 @@ func isAssetVocabulary(name string) bool {
return false
}
-// stripAssetResponseHeaders deletes the asset cache's vocabulary from an
+// stripVocabularyExcept deletes every clientScrubVocabulary entry from h
+// except those keep names.
+func stripVocabularyExcept(h http.Header, keep map[string]bool) {
+ for _, v := range clientScrubVocabulary {
+ if !keep[v] {
+ h.Del(v)
+ }
+ }
+}
+
+// backhaulFillKeep is what a far edge's own fill keeps on the home's
+// response for fillFromHome: the acknowledgement and the expiry.
+var backhaulFillKeep = map[string]bool{assetAckHeader: true, assetExpiresHeader: true}
+
+// fillVocabularyKeep is what stripAssetFillVocabulary keeps: Carlos-Cache,
+// which this edge set.
+var fillVocabularyKeep = map[string]bool{assetCacheHeader: true}
+
+// stripAssetResponseHeaders deletes the client scrub vocabulary from an
// app's response headers.
func stripAssetResponseHeaders(h http.Header) {
- for _, v := range assetVocabulary {
- h.Del(v)
- }
+ stripVocabularyExcept(h, nil)
}
-// stripAssetTrailers keeps the vocabulary out of an app's trailers, announced
-// or not. A ModifyResponse hook sees only the announced names (keys of
-// resp.Trailer without values), from which httputil.ReverseProxy builds the
-// Trailer header it sends on; the values, and any unannounced trailer, land
-// in resp.Trailer at EOF, and the proxy copies them out after closing the
-// body. So the names go now and the values when the body closes. A 101
-// keeps its body untouched: httputil needs it to be the raw connection.
+// stripAssetTrailers keeps the client scrub vocabulary out of an app's
+// trailers, announced or not. A ModifyResponse hook sees only the announced
+// names (keys of resp.Trailer without values), from which
+// httputil.ReverseProxy builds the Trailer header it sends on; the values,
+// and any unannounced trailer, land in resp.Trailer at EOF, and the proxy
+// copies them out after closing the body. So the names go now and the
+// values when the body closes. A 101 keeps its body untouched: httputil
+// needs it to be the raw connection.
func stripAssetTrailers(resp *http.Response) {
- for _, v := range assetVocabulary {
- resp.Trailer.Del(v)
- }
+ stripVocabularyExcept(resp.Trailer, nil)
if resp.StatusCode == http.StatusSwitchingProtocols || resp.Body == nil {
return
}
resp.Body = &trailerCookieBody{ReadCloser: resp.Body, close: func() {
- for _, v := range assetVocabulary {
- resp.Trailer.Del(v)
- }
+ stripVocabularyExcept(resp.Trailer, nil)
}}
}
@@ -1341,31 +1361,29 @@ func (e *Edge) farForward(w http.ResponseWriter, r *http.Request, host string) {
}
}
-// stripAssetFillVocabulary deletes a far fill's assertion, acknowledgement
-// and expiry from the header map about to be written to the client, once
-// fillFromHome has read them (backhaulProxy keeps the acknowledgement and
-// expiry on a fill's response for exactly that). Carlos-Cache, set by this
-// edge, stays.
+// stripAssetFillVocabulary deletes the client scrub vocabulary from a far
+// fill's header map about to be written to the client, once fillFromHome
+// has read the acknowledgement and expiry (backhaulProxy keeps them on a
+// fill's response for exactly that). Carlos-Cache, set by this edge, stays
+// (fillVocabularyKeep).
func stripAssetFillVocabulary(h http.Header) {
- h.Del(assetFillHeader)
- h.Del(assetAckHeader)
- h.Del(assetExpiresHeader)
+ stripVocabularyExcept(h, fillVocabularyKeep)
}
// scrubBackhaulResponse is the client boundary of every backhauled response
-// (backhaulProxy's ModifyResponse): the asset cache's vocabulary comes off
+// (backhaulProxy's ModifyResponse): the client scrub vocabulary comes off
// its headers and its trailers, announced or not, whatever version the home
// box runs, so an app's own values never reach a client through a hop
-// (design §5.3). Carlos-Cache goes too: the far edge sets its own on what it
-// catches. A far edge's own fill (assetFill) keeps the acknowledgement and
-// expiry headers for fillFromHome, which verifies and then deletes them.
+// (design §5.3), Carlos-Page-Cache from an older home among them.
+// Carlos-Cache goes too: the far edge sets its own on what it catches. A far
+// edge's own fill (assetFill) keeps the acknowledgement and expiry headers
+// (backhaulFillKeep) for fillFromHome, which verifies and then deletes them.
func scrubBackhaulResponse(resp *http.Response, assetFill bool) {
- resp.Header.Del(assetFillHeader)
- resp.Header.Del(assetCacheHeader)
- if !assetFill {
- resp.Header.Del(assetAckHeader)
- resp.Header.Del(assetExpiresHeader)
+ var keep map[string]bool
+ if assetFill {
+ keep = backhaulFillKeep
}
+ stripVocabularyExcept(resp.Header, keep)
stripAssetTrailers(resp)
}
diff --git a/internal/edge/assetserve.go b/internal/edge/assetserve.go
index 28d0972d7..4fa5a9161 100644
--- a/internal/edge/assetserve.go
+++ b/internal/edge/assetserve.go
@@ -52,7 +52,7 @@ func serveAssetEntry(w http.ResponseWriter, r *http.Request, e *assetcache.Entry
h.Del("X-Carlos-Version")
h.Del("Content-Length")
h.Set("Age", strconv.FormatInt(int64(e.Meta.Age(now)/time.Second), 10))
- h.Set("Carlos-Cache", result)
+ h.Set(assetCacheHeader, result)
if hasGzip && !varyNamesAcceptEncoding(h) {
h.Add("Vary", "Accept-Encoding")
}
diff --git a/internal/edge/cookiescope.go b/internal/edge/cookiescope.go
index 7223ec745..bfb0d3db6 100644
--- a/internal/edge/cookiescope.go
+++ b/internal/edge/cookiescope.go
@@ -71,12 +71,14 @@ func appsDomainFromEnv() string {
}
// responseModifier is the ModifyResponse hook for a tenant route's reverse
-// proxy: the Carlos-Purge channel (purgeModifier), the removal of any asset
-// cache header or trailer the app set (stripAssetResponseHeaders,
-// stripAssetTrailers: the edge's own are set after this, never inherited
-// from the app), the removal of any X-Carlos-Holder the app set, as a
-// header or a trailer (stripAppHolder), and the
-// cookie scoping above, in that order. None depends on another.
+// proxy: the Carlos-Purge channel (purgeModifier), the page cache marker
+// read into the request's holder (takePageMark), the removal of every
+// client scrub vocabulary header or trailer the app set
+// (stripAssetResponseHeaders, stripAssetTrailers: the edge's own are set
+// after this, never inherited from the app), the removal of any
+// X-Carlos-Holder the app set, as a header or a trailer (stripAppHolder),
+// and the cookie scoping above, in that order. Only the marker depends on
+// order: it is read before the scrub deletes it.
//
// X-Carlos-Holder names the box holding an HA host's lease (forwardha.go),
// and a forwarding box's holder cache follows it, so only the platform may
@@ -88,6 +90,7 @@ func (e *Edge) responseModifier(rt registry.Route) func(*http.Response) error {
if err := purge(resp); err != nil {
return err
}
+ takePageMark(resp)
stripAssetResponseHeaders(resp.Header)
stripAssetTrailers(resp)
stripAppHolder(resp)
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 7ef38b291..c0d6883cd 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -2660,6 +2660,13 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !e.planThrottleAdmit(w, r, up) {
return
}
+ // Every proxied request to an instance route carries a page mark holder
+ // (pagemark.go), whatever its method, before the activator or the proxy
+ // runs: the response hook records the app's Carlos-Page-Cache in it, and
+ // a marked response never enters the LRU (maybeStore).
+ if up.route.Kind == "instance" {
+ r = withPageMarkHolder(r)
+ }
// A forward row is never cached here (fleet public routes spec §4.8): the
// hub cannot see the fleet edge's gate, so a gated page stored here would
// be served without the cookie, and an app's Carlos-Purge stops at its
@@ -2711,23 +2718,28 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// The response is always recorded (even when not cacheable, in which
// case maybeStore is a no-op on rec.cacheable) so this branch stays a
// single shape regardless of method.
+ //
+ // Each writer handed on below is wrapped in assetInformationalScrub
+ // (as hopTo's is), outside the recorder so the recorder's Flush and
+ // Hijack still find the writers beneath it: a 1xx the activator or
+ // the proxy writes loses the client scrub vocabulary on every path.
rec := &recordingResponseWriter{ResponseWriter: w, request: r, cacheable: cacheable, genManaged: up.genManaged, maxBody: e.cacheMaxBody()}
- if e.act.ServeHTTP(rec, r, up.route, up.proxy) {
+ if e.act.ServeHTTP(assetInformationalScrub{rec}, r, up.route, up.proxy) {
e.maybeStore(key, rec)
return
}
- up.proxy.ServeHTTP(rec, r)
+ up.proxy.ServeHTTP(assetInformationalScrub{rec}, r)
e.maybeStore(key, rec)
return
}
if cacheable {
rec := &recordingResponseWriter{ResponseWriter: w, request: r, cacheable: true, maxBody: e.cacheMaxBody()}
- up.proxy.ServeHTTP(rec, r)
+ up.proxy.ServeHTTP(assetInformationalScrub{rec}, r)
e.maybeStore(key, rec)
return
}
- up.proxy.ServeHTTP(w, r)
+ up.proxy.ServeHTTP(assetInformationalScrub{w}, r)
}
// isUpgradeRequest reports whether r is a protocol-upgrade request (e.g. a
@@ -2908,6 +2920,13 @@ func (e *Edge) maybeStore(key CacheKey, rec *recordingResponseWriter) {
if e.cache == nil || !rec.cacheable || rec.truncated {
return
}
+ // A response that opted into the page cache (Carlos-Page-Cache: on, read
+ // by takePageMark) is the page cache's, never this LRU's: its lifetime
+ // may be a year, and it is cleared by the page cache's rules, not by a
+ // five-minute ceiling (page cache design §5.3).
+ if m := pageMarkOf(rec.request); m != nil && m.Marked {
+ return
+ }
if rec.status < 200 || rec.status >= 300 {
return
}
diff --git a/internal/edge/pagemark.go b/internal/edge/pagemark.go
new file mode 100644
index 000000000..8be335837
--- /dev/null
+++ b/internal/edge/pagemark.go
@@ -0,0 +1,110 @@
+package edge
+
+import (
+ "context"
+ "net/http"
+ "strings"
+)
+
+// pageCacheHeader is an app's opt-in to the page cache (edge page cache
+// design §4.1): "Carlos-Page-Cache: on", optionally with
+// `; ignore-cookies="a,b"` naming cookies that do not change the page. It is
+// the app's word to this edge, never the visitor's: every client-boundary
+// scrub removes it (clientScrubVocabulary), on every box, whether or not the
+// box caches pages.
+const pageCacheHeader = "Carlos-Page-Cache"
+
+// pageMark is what a request's final response said in Carlos-Page-Cache.
+// Marked: a well-formed opt-in, with Ignore its ignorable cookie names. Bad:
+// the header was there but was not one (two lines, an unknown word or
+// parameter, a list that does not parse); a Bad mark is not an opt-in, so
+// today's rules apply to the response. Neither: no marker.
+type pageMark struct {
+ Marked bool
+ Ignore []string
+ Bad bool
+}
+
+// pageMarkKey is the request-context key of a request's holder.
+type pageMarkKey struct{}
+
+// withPageMarkHolder returns r with a fresh, empty holder in its context.
+// ServeHTTP attaches one to every proxied request to an instance route,
+// before the activator or the proxy runs, so the outbound request the proxy
+// clones (and the response's Request) carries it to takePageMark.
+func withPageMarkHolder(r *http.Request) *http.Request {
+ return r.WithContext(context.WithValue(r.Context(), pageMarkKey{}, &pageMark{}))
+}
+
+// pageMarkOf returns r's holder, or nil when r has none. It is written by
+// takePageMark in the proxy's ModifyResponse and read once the proxy has
+// returned, on the same request's goroutine.
+func pageMarkOf(r *http.Request) *pageMark {
+ if r == nil {
+ return nil
+ }
+ m, _ := r.Context().Value(pageMarkKey{}).(*pageMark)
+ return m
+}
+
+// takePageMark records resp's Carlos-Page-Cache in its request's holder. It
+// reads the final response header only: never a trailer (which arrives after
+// the response could be judged) and never a 1xx (which never reaches
+// ModifyResponse, and is refused here besides). Each final response replaces
+// the record, so the holder describes the response that is delivered. With
+// no holder it does nothing; the scrub that follows removes the header
+// either way.
+func takePageMark(resp *http.Response) {
+ if resp == nil || resp.StatusCode < 200 {
+ return
+ }
+ m := pageMarkOf(resp.Request)
+ if m == nil {
+ return
+ }
+ *m = parsePageMark(resp.Header.Values(pageCacheHeader))
+}
+
+// parsePageMark reads the marker's lines. Exactly one line, the word "on",
+// then at most one ignore-cookies parameter whose value is a quoted,
+// comma-separated list of cookie names (HTTP tokens), each trimmed. Word and
+// parameter name are matched case-insensitively, as HTTP matches parameter
+// names; whitespace is allowed around ";" and inside the list, not around
+// "=". Anything else is Bad.
+func parsePageMark(values []string) pageMark {
+ if len(values) == 0 {
+ return pageMark{}
+ }
+ bad := pageMark{Bad: true}
+ if len(values) != 1 {
+ return bad
+ }
+ parts := strings.Split(values[0], ";")
+ if !strings.EqualFold(strings.TrimSpace(parts[0]), "on") {
+ return bad
+ }
+ m := pageMark{Marked: true}
+ seen := false
+ for _, p := range parts[1:] {
+ name, val, ok := strings.Cut(strings.TrimSpace(p), "=")
+ if !ok || seen || !strings.EqualFold(name, "ignore-cookies") {
+ return bad
+ }
+ seen = true
+ if len(val) < 2 || val[0] != '"' || val[len(val)-1] != '"' {
+ return bad
+ }
+ inner := val[1 : len(val)-1]
+ if strings.ContainsAny(inner, `"\`) {
+ return bad
+ }
+ for _, c := range strings.Split(inner, ",") {
+ c = strings.TrimSpace(c)
+ if !isToken(c) {
+ return bad
+ }
+ m.Ignore = append(m.Ignore, c)
+ }
+ }
+ return m
+}
diff --git a/internal/edge/pagemark_test.go b/internal/edge/pagemark_test.go
new file mode 100644
index 000000000..600f09480
--- /dev/null
+++ b/internal/edge/pagemark_test.go
@@ -0,0 +1,481 @@
+package edge
+
+import (
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httptrace"
+ "net/textproto"
+ "reflect"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// The page cache's response marker (edge page cache design §4.1; slice 1
+// plan Task 5): read once from the final response header into the request's
+// holder, stripped from every response on every box, and never an entry in
+// today's in-memory LRU.
+
+// markedResponse is a final response to a request carrying a fresh holder,
+// with the given Carlos-Page-Cache lines.
+func markedResponse(status int, values ...string) *http.Response {
+ req := withPageMarkHolder(httptest.NewRequest(http.MethodGet, "http://pm.example.com/", nil))
+ resp := &http.Response{StatusCode: status, Header: http.Header{}, Trailer: http.Header{}, Request: req}
+ for _, v := range values {
+ resp.Header.Add(pageCacheHeader, v)
+ }
+ return resp
+}
+
+func TestPageMarkParses(t *testing.T) {
+ marked := func(ignore ...string) pageMark { return pageMark{Marked: true, Ignore: ignore} }
+ bad := pageMark{Bad: true}
+ for _, tc := range []struct {
+ name string
+ values []string
+ want pageMark
+ }{
+ {"absent", nil, pageMark{}},
+ {"on", []string{"on"}, marked()},
+ {"on with space", []string{" on "}, marked()},
+ {"on in capitals", []string{"ON"}, marked()},
+ {"one ignored cookie", []string{`on; ignore-cookies="consent"`}, marked("consent")},
+ {"two ignored cookies", []string{`on; ignore-cookies="a,b"`}, marked("a", "b")},
+ {"spaced list", []string{`on ;ignore-cookies=" a , b "`}, marked("a", "b")},
+ {"parameter name in capitals", []string{`on; Ignore-Cookies="a"`}, marked("a")},
+ {"empty value", []string{""}, bad},
+ {"off", []string{"off"}, bad},
+ {"yes", []string{"yes"}, bad},
+ {"two lines", []string{"on", "on"}, bad},
+ {"comma list", []string{"on, on"}, bad},
+ {"trailing semicolon", []string{"on;"}, bad},
+ {"parameter first", []string{`ignore-cookies="a"; on`}, bad},
+ {"unquoted list", []string{"on; ignore-cookies=a"}, bad},
+ {"empty list", []string{`on; ignore-cookies=""`}, bad},
+ {"empty name", []string{`on; ignore-cookies="a,,b"`}, bad},
+ {"name with a space", []string{`on; ignore-cookies="a b"`}, bad},
+ {"name with a semicolon", []string{`on; ignore-cookies="a;b"`}, bad},
+ {"escaped quote", []string{`on; ignore-cookies="a\"b"`}, bad},
+ {"unterminated quote", []string{`on; ignore-cookies="a`}, bad},
+ {"space before equals", []string{`on; ignore-cookies ="a"`}, bad},
+ {"repeated parameter", []string{`on; ignore-cookies="a"; ignore-cookies="b"`}, bad},
+ {"unknown parameter", []string{`on; max="1"`}, bad},
+ {"bare parameter", []string{"on; ignore-cookies"}, bad},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ resp := markedResponse(http.StatusOK, tc.values...)
+ takePageMark(resp)
+ got := pageMarkOf(resp.Request)
+ if got == nil {
+ t.Fatal("the holder went missing")
+ }
+ if !reflect.DeepEqual(*got, tc.want) {
+ t.Fatalf("Carlos-Page-Cache %q = %+v, want %+v", tc.values, *got, tc.want)
+ }
+ })
+ }
+
+ t.Run("no holder", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "http://pm.example.com/", nil)
+ if m := pageMarkOf(req); m != nil {
+ t.Fatalf("a request with no holder reported %+v", *m)
+ }
+ resp := &http.Response{StatusCode: 200, Header: http.Header{pageCacheHeader: {"on"}}, Request: req}
+ takePageMark(resp) // must not panic
+ takePageMark(&http.Response{StatusCode: 200, Header: http.Header{pageCacheHeader: {"on"}}})
+ if m := pageMarkOf(req); m != nil {
+ t.Fatalf("takePageMark attached a holder: %+v", *m)
+ }
+ })
+ t.Run("informational", func(t *testing.T) {
+ resp := markedResponse(http.StatusEarlyHints, "on")
+ takePageMark(resp)
+ if m := pageMarkOf(resp.Request); m.Marked || m.Bad {
+ t.Fatalf("a 103 marked the page: %+v", *m)
+ }
+ })
+ t.Run("trailer only", func(t *testing.T) {
+ resp := markedResponse(http.StatusOK)
+ resp.Trailer.Set(pageCacheHeader, "on")
+ resp.Header.Set(http.TrailerPrefix+pageCacheHeader, "on")
+ takePageMark(resp)
+ if m := pageMarkOf(resp.Request); m.Marked || m.Bad {
+ t.Fatalf("a trailer marked the page: %+v", *m)
+ }
+ })
+ t.Run("read once, then stripped", func(t *testing.T) {
+ resp := markedResponse(http.StatusOK, `on; ignore-cookies="consent"`)
+ takePageMark(resp)
+ stripAssetResponseHeaders(resp.Header)
+ if v := resp.Header.Values(pageCacheHeader); len(v) > 0 {
+ t.Fatalf("the scrub left %q", v)
+ }
+ if m := pageMarkOf(resp.Request); !reflect.DeepEqual(*m, marked("consent")) {
+ t.Fatalf("after the scrub the holder says %+v", *m)
+ }
+ })
+ t.Run("each final response replaces the record", func(t *testing.T) {
+ resp := markedResponse(http.StatusOK, "on")
+ takePageMark(resp)
+ resp.Header.Del(pageCacheHeader)
+ takePageMark(resp)
+ if m := pageMarkOf(resp.Request); m.Marked || m.Bad {
+ t.Fatalf("an unmarked final response kept the earlier mark: %+v", *m)
+ }
+ })
+}
+
+// markApp answers GET and POST alike as a cacheable page carrying mark (when
+// not empty) as its Carlos-Page-Cache header.
+func markApp(mark string) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/html")
+ w.Header().Set("Cache-Control", "public, max-age=600")
+ if mark != "" {
+ w.Header().Set(pageCacheHeader, mark)
+ }
+ io.WriteString(w, "page "+r.URL.Path)
+ }
+}
+
+// wantNoPageMark fails when h carries the marker under any key, a trailer
+// key included.
+func wantNoPageMark(t *testing.T, where string, h http.Header) {
+ t.Helper()
+ for k, v := range h {
+ if strings.Contains(strings.ToLower(k), "page-cache") {
+ t.Errorf("%s carried %s %q", where, k, v)
+ }
+ if strings.EqualFold(k, "Trailer") {
+ for _, s := range v {
+ if strings.Contains(strings.ToLower(s), "page-cache") {
+ t.Errorf("%s announced the marker trailer: %q", where, s)
+ }
+ }
+ }
+ }
+}
+
+// pmStored returns the LRU's entry for GET host/path, or nil.
+func pmStored(e *Edge, host, path string) *CachedResponse {
+ resp, ok := e.cache.get(CacheKey{Host: host, Method: http.MethodGet, Path: path})
+ if !ok {
+ return nil
+ }
+ return resp
+}
+
+// On an edge with no page index, the visitor never sees the marker, on the
+// direct and the activator path, GET and POST, cached or not.
+func TestPageMarkStrippedFinalHeader(t *testing.T) {
+ for _, hibernate := range []bool{false, true} {
+ for _, method := range []string{http.MethodGet, http.MethodPost} {
+ for _, mark := range []string{"on", `on; ignore-cookies="consent"`, "garbage"} {
+ t.Run(fmt.Sprintf("hibernate=%v/%s/%s", hibernate, method, mark), func(t *testing.T) {
+ const host = "pm-final.example.com"
+ e, _ := purgeEdge(t, host, hibernate, markApp(mark))
+ for i := 0; i < 2; i++ {
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, httptest.NewRequest(method, "http://"+host+"/p", nil))
+ if rec.Code != http.StatusOK || rec.Body.String() != "page /p" {
+ t.Fatalf("answer %d = %d %q", i, rec.Code, rec.Body.String())
+ }
+ wantNoPageMark(t, fmt.Sprintf("answer %d", i), rec.Header())
+ }
+ if c := pmStored(e, host, "/p"); c != nil {
+ wantNoPageMark(t, "the LRU entry", c.Header)
+ }
+ })
+ }
+ }
+ }
+ // The local asset catch's miss and its hit off the store.
+ t.Run("asset catch", func(t *testing.T) {
+ s := newLAScene(t, assetOK(laBody, pageCacheHeader, "on"))
+ first := s.get(t, "/assets/app.js")
+ wantCache(t, first, "miss")
+ wantNoPageMark(t, "the miss", first.Header())
+ second := s.get(t, "/assets/app.js")
+ wantCache(t, second, "hit")
+ wantNoPageMark(t, "the hit", second.Header())
+ })
+}
+
+// pmApp sends the marker everywhere an app can: on a 103 beside a Link, on
+// the final headers, and as a trailer announced or not, with an X-Kept
+// trailer that must still flow.
+func pmApp(body string, announced bool) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ h := w.Header()
+ h.Set("Link", "</assets/app.js>; rel=preload")
+ h.Set(pageCacheHeader, "on")
+ w.WriteHeader(http.StatusEarlyHints)
+ h.Del("Link")
+ h.Set("Content-Type", "text/html")
+ h.Set("Cache-Control", "public, max-age=600")
+ h.Set(pageCacheHeader, "on")
+ prefix := http.TrailerPrefix
+ if announced {
+ h.Set("Trailer", "X-Kept, "+pageCacheHeader)
+ prefix = ""
+ }
+ io.WriteString(w, body)
+ w.(http.Flusher).Flush()
+ h.Set(prefix+"X-Kept", "1")
+ h.Set(prefix+pageCacheHeader, "on")
+ }
+}
+
+// pmFetch requests path from front as host, recording every 1xx.
+func pmFetch(t *testing.T, front *httptest.Server, method, host, path string) (*http.Response, []byte, []http.Header) {
+ t.Helper()
+ req, err := http.NewRequest(method, front.URL+path, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = host
+ var mu sync.Mutex
+ var early []http.Header
+ req = req.WithContext(httptrace.WithClientTrace(req.Context(), &httptrace.ClientTrace{
+ Got1xxResponse: func(code int, h textproto.MIMEHeader) error {
+ mu.Lock()
+ early = append(early, http.Header(h).Clone())
+ mu.Unlock()
+ return nil
+ },
+ }))
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ return resp, b, early
+}
+
+// A mock older home returns the marker on an ordinary backhaul, in a 103,
+// the final headers and a trailer. The visitor sees it nowhere, whether this
+// box's caches are armed (the far asset catch's paths) or not.
+func TestPageMarkStrippedThroughBackhaul(t *testing.T) {
+ for _, tc := range []struct {
+ name, path string
+ unarmed bool
+ noAck bool
+ fill bool // a fill forwards no 1xx
+ }{
+ {name: "unarmed", path: "/index.html", unarmed: true},
+ {name: "unarmed under a prefix", path: "/assets/app.js", unarmed: true},
+ {name: "armed, uncaught path", path: "/index.html"},
+ {name: "armed, caught non-canonical fallback", path: "/assets//app.js"},
+ {name: "armed, unacknowledged fill", path: "/assets/app.js", noAck: true, fill: true},
+ } {
+ for _, announced := range []bool{true, false} {
+ t.Run(fmt.Sprintf("%s/announced=%v", tc.name, announced), func(t *testing.T) {
+ s := newFarScene(t, pmApp(laBody, announced))
+ if tc.unarmed {
+ s.e.assets.Store(nil)
+ }
+ s.home.set(func(h *farHome) { h.ack = !tc.noAck })
+ front := httptest.NewServer(s.e)
+ t.Cleanup(front.Close)
+ resp, body, early := pmFetch(t, front, http.MethodGet, laHost, tc.path)
+ if string(body) != laBody {
+ t.Fatalf("body = %q", body)
+ }
+ if n := s.rec.get().n; n == 0 {
+ t.Fatal("the home was never asked: the test proves nothing")
+ }
+ switch {
+ case tc.fill && len(early) != 0:
+ t.Fatalf("1xx responses %v, want none from a fill", early)
+ case !tc.fill && (len(early) != 1 || early[0].Get("Link") == ""):
+ t.Fatalf("1xx responses %v, want the home's 103 with its Link", early)
+ }
+ for i, h := range early {
+ wantNoPageMark(t, fmt.Sprintf("1xx %d", i), h)
+ }
+ wantNoPageMark(t, "the final headers", resp.Header)
+ wantNoPageMark(t, "the trailers", resp.Trailer)
+ if got := resp.Trailer.Get("X-Kept"); got != "1" {
+ t.Errorf("X-Kept trailer = %q, want 1 (trailers %v)", got, resp.Trailer)
+ }
+ })
+ }
+ }
+}
+
+// An app's 103 carrying the marker reaches the visitor with its Link and
+// without the marker, on the cacheable GET path, the plain POST path and the
+// activator's.
+func TestPageMarkStripped103(t *testing.T) {
+ for _, hibernate := range []bool{false, true} {
+ for _, method := range []string{http.MethodGet, http.MethodPost} {
+ t.Run(fmt.Sprintf("hibernate=%v/%s", hibernate, method), func(t *testing.T) {
+ const host = "pm-103.example.com"
+ e, _ := purgeEdge(t, host, hibernate, pmApp("page", true))
+ front := httptest.NewServer(e)
+ t.Cleanup(front.Close)
+ resp, body, early := pmFetch(t, front, method, host, "/p")
+ if string(body) != "page" {
+ t.Fatalf("body = %q", body)
+ }
+ if len(early) != 1 || early[0].Get("Link") == "" {
+ t.Fatalf("1xx responses %v, want the app's 103 with its Link", early)
+ }
+ wantNoPageMark(t, "the 103", early[0])
+ wantNoPageMark(t, "the final headers", resp.Header)
+ })
+ }
+ }
+}
+
+// hintingActivator writes a 103 of its own, carrying the marker, before it
+// proxies: whatever writes to the writer ServeHTTP hands the activator, a
+// 1xx loses the client scrub vocabulary.
+type hintingActivator struct{ fakeActivator }
+
+func (a *hintingActivator) ServeHTTP(w http.ResponseWriter, r *http.Request, rt registry.Route, proxy http.Handler) bool {
+ w.Header().Set("Link", "</a.js>; rel=preload")
+ w.Header().Set(pageCacheHeader, "on")
+ w.WriteHeader(http.StatusEarlyHints)
+ w.Header().Del("Link")
+ return a.fakeActivator.ServeHTTP(w, r, rt, proxy)
+}
+
+func TestPageMarkStripped103FromTheActivatorsWriter(t *testing.T) {
+ for _, method := range []string{http.MethodGet, http.MethodPost} {
+ t.Run(method, func(t *testing.T) {
+ const host = "pm-act.example.com"
+ backend := httptest.NewServer(markApp(""))
+ t.Cleanup(backend.Close)
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: host, Kind: "instance", Addr: backend.Listener.Addr().String(), Status: "ready", Hibernate: true}); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ e, err := New(reg, &hintingActivator{})
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes))
+ front := httptest.NewServer(e)
+ t.Cleanup(front.Close)
+ _, body, early := pmFetch(t, front, method, host, "/p")
+ if string(body) != "page /p" {
+ t.Fatalf("body = %q", body)
+ }
+ if len(early) != 1 || early[0].Get("Link") == "" {
+ t.Fatalf("1xx responses %v, want the activator's 103 with its Link", early)
+ }
+ wantNoPageMark(t, "the 103", early[0])
+ })
+ }
+}
+
+// A marker sent as a trailer, announced or not, never reaches the visitor
+// and never marks the page: the response is still today's LRU entry.
+func TestPageMarkStrippedTrailers(t *testing.T) {
+ for _, announced := range []bool{true, false} {
+ t.Run(fmt.Sprintf("announced=%v", announced), func(t *testing.T) {
+ const host = "pm-trailer.example.com"
+ e, _ := purgeEdge(t, host, false, func(w http.ResponseWriter, r *http.Request) {
+ h := w.Header()
+ h.Set("Content-Type", "text/html")
+ h.Set("Cache-Control", "public, max-age=600")
+ prefix := http.TrailerPrefix
+ if announced {
+ h.Set("Trailer", "X-Kept, "+pageCacheHeader)
+ prefix = ""
+ }
+ io.WriteString(w, "page")
+ w.(http.Flusher).Flush()
+ h.Set(prefix+"X-Kept", "1")
+ h.Set(prefix+pageCacheHeader, "on")
+ })
+ front := httptest.NewServer(e)
+ t.Cleanup(front.Close)
+ resp, body, _ := pmFetch(t, front, http.MethodGet, host, "/p")
+ if string(body) != "page" {
+ t.Fatalf("body = %q", body)
+ }
+ wantNoPageMark(t, "the final headers", resp.Header)
+ wantNoPageMark(t, "the trailers", resp.Trailer)
+ if got := resp.Trailer.Get("X-Kept"); got != "1" {
+ t.Errorf("X-Kept trailer = %q, want 1 (trailers %v)", got, resp.Trailer)
+ }
+ c := pmStored(e, host, "/p")
+ if c == nil {
+ t.Fatal("a trailer marked the page: the response is not in the LRU")
+ }
+ wantNoPageMark(t, "the LRU entry", c.Header)
+ })
+ }
+}
+
+// A response carrying Carlos-Page-Cache: on is the page cache's, never the
+// five-minute LRU's, on the direct and the activator path.
+func TestMarkedResponseNeverEntersLRU(t *testing.T) {
+ for _, hibernate := range []bool{false, true} {
+ for _, mark := range []string{"on", `on; ignore-cookies="consent"`, " ON "} {
+ t.Run(fmt.Sprintf("hibernate=%v/%s", hibernate, mark), func(t *testing.T) {
+ const host = "pm-lru.example.com"
+ e, _ := purgeEdge(t, host, hibernate, markApp(mark))
+ for _, method := range []string{http.MethodGet, http.MethodHead} {
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, httptest.NewRequest(method, "http://"+host+"/p", nil))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("%s = %d", method, rec.Code)
+ }
+ wantNoPageMark(t, method, rec.Header())
+ if _, ok := e.cache.get(CacheKey{Host: host, Method: method, Path: "/p"}); ok {
+ t.Fatalf("a marked %s response entered the LRU", method)
+ }
+ }
+ })
+ }
+ }
+}
+
+// Without the marker (or with one that is not an opt-in) today's rules apply
+// unchanged: the response is stored and the next request is a hit.
+func TestUnmarkedResponseStillUsesLRU(t *testing.T) {
+ for _, hibernate := range []bool{false, true} {
+ for _, mark := range []string{"", "off", "on; ignore-cookies=consent"} {
+ t.Run(fmt.Sprintf("hibernate=%v/%q", hibernate, mark), func(t *testing.T) {
+ const host = "pm-unmarked.example.com"
+ var hits int
+ var mu sync.Mutex
+ e, _ := purgeEdge(t, host, hibernate, func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ hits++
+ mu.Unlock()
+ markApp(mark)(w, r)
+ })
+ for i := 0; i < 2; i++ {
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "http://"+host+"/p", nil))
+ if rec.Code != http.StatusOK || rec.Body.String() != "page /p" {
+ t.Fatalf("answer %d = %d %q", i, rec.Code, rec.Body.String())
+ }
+ wantNoPageMark(t, fmt.Sprintf("answer %d", i), rec.Header())
+ }
+ if pmStored(e, host, "/p") == nil {
+ t.Fatal("an unmarked response did not enter the LRU")
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if hits != 1 {
+ t.Fatalf("the app saw %d requests, want 1 (the second a hit)", hits)
+ }
+ })
+ }
+ }
+}
diff --git a/internal/edge/scrub_guard_test.go b/internal/edge/scrub_guard_test.go
new file mode 100644
index 000000000..c16099111
--- /dev/null
+++ b/internal/edge/scrub_guard_test.go
@@ -0,0 +1,418 @@
+package edge
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "io"
+ "maps"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// The client boundary has one header list, clientScrubVocabulary, and every
+// scrub iterates it (Paul's ruling "One list, every scrub"; plan R2-4, R3-5).
+// This guard holds that two ways:
+//
+// - the table below runs every client-boundary scrub against every entry
+// of the list, set as a header, as a trailer (announced and not) and on
+// a 1xx, and asserts it is gone from each surface that scrub answers
+// for;
+// - the source check fails when a non-test file in this package deletes,
+// lists or compares one of the list's names by itself, outside the few
+// request-side and fill-side sites counted in vocabularySites.
+//
+// A NEW CLIENT-BOUNDARY SCRUB MUST BE ADDED TO guardScrubs, and must iterate
+// clientScrubVocabulary (with an explicit keep set if it keeps anything)
+// rather than naming headers itself.
+
+type scrubSurface string
+
+const (
+ surfHeader scrubSurface = "final header"
+ surfAnnounced scrubSurface = "announced trailer"
+ surfUnannounced scrubSurface = "unannounced trailer"
+ surfInformational scrubSurface = "1xx header"
+)
+
+// guardScrub is one client-boundary scrub, in whichever of three shapes it
+// takes: on a header map (headers), on a final *http.Response (final), or as
+// a writer wrapper (writer). covers names the surfaces it is the boundary
+// for; keep the names it may leave on the final header.
+type guardScrub struct {
+ name string
+ covers []scrubSurface
+ keep []string
+ headers func(h http.Header)
+ final func(t *testing.T, resp *http.Response)
+ writer func(w http.ResponseWriter) http.ResponseWriter
+}
+
+func guardScrubs(t *testing.T) []guardScrub {
+ e, err := New(openReg(t), nil)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ t.Cleanup(e.probers.Stop)
+ modify := e.responseModifier(registry.Route{Host: "guard.example.com", Kind: "instance"})
+ return []guardScrub{
+ {name: "stripAssetResponseHeaders", covers: []scrubSurface{surfHeader, surfInformational},
+ headers: stripAssetResponseHeaders},
+ {name: "stripAssetFillVocabulary", covers: []scrubSurface{surfHeader}, keep: []string{assetCacheHeader},
+ headers: stripAssetFillVocabulary},
+ {name: "assetStoredHeader", covers: []scrubSurface{surfHeader},
+ headers: func(h http.Header) {
+ out := assetStoredHeader(h)
+ clear(h)
+ maps.Copy(h, out)
+ }},
+ {name: "stripAssetTrailers", covers: []scrubSurface{surfAnnounced, surfUnannounced},
+ final: func(_ *testing.T, resp *http.Response) { stripAssetTrailers(resp) }},
+ {name: "scrubBackhaulResponse", covers: []scrubSurface{surfHeader, surfAnnounced, surfUnannounced},
+ final: func(_ *testing.T, resp *http.Response) { scrubBackhaulResponse(resp, false) }},
+ {name: "scrubBackhaulResponse(assetFill)", covers: []scrubSurface{surfHeader, surfAnnounced, surfUnannounced},
+ keep: []string{assetAckHeader, assetExpiresHeader},
+ final: func(_ *testing.T, resp *http.Response) { scrubBackhaulResponse(resp, true) }},
+ {name: "responseModifier", covers: []scrubSurface{surfHeader, surfAnnounced, surfUnannounced},
+ final: func(t *testing.T, resp *http.Response) {
+ if err := modify(resp); err != nil {
+ t.Fatalf("responseModifier: %v", err)
+ }
+ }},
+ {name: "assetInformationalScrub", covers: []scrubSurface{surfInformational},
+ writer: func(w http.ResponseWriter) http.ResponseWriter { return assetInformationalScrub{w} }},
+ {name: "assetResultWriter", covers: []scrubSurface{surfInformational},
+ writer: func(w http.ResponseWriter) http.ResponseWriter {
+ return &assetResultWriter{ResponseWriter: w, result: "bypass"}
+ }},
+ }
+}
+
+// informationalCapture records the header block of each WriteHeader below
+// 200 it is handed.
+type informationalCapture struct {
+ h http.Header
+ early []http.Header
+}
+
+func (c *informationalCapture) Header() http.Header { return c.h }
+func (c *informationalCapture) Write(p []byte) (int, error) { return len(p), nil }
+func (c *informationalCapture) WriteHeader(code int) {
+ if code < 200 {
+ c.early = append(c.early, c.h.Clone())
+ }
+}
+
+// trailerAtEOF stands in for the transport: it fills resp.Trailer with the
+// trailer values when the body reaches EOF.
+type trailerAtEOF struct {
+ r io.Reader
+ atEOF func()
+ done bool
+}
+
+func (b *trailerAtEOF) Read(p []byte) (int, error) {
+ n, err := b.r.Read(p)
+ if err == io.EOF && !b.done {
+ b.done = true
+ b.atEOF()
+ }
+ return n, err
+}
+
+func (b *trailerAtEOF) Close() error { return nil }
+
+// guardResponse is a final response carrying name as a header and as a
+// trailer, announced (its key in resp.Trailer from the start) or not (it
+// arrives only at EOF).
+func guardResponse(name string, announced bool) *http.Response {
+ req := withPageMarkHolder(httptest.NewRequest(http.MethodGet, "http://guard.example.com/", nil))
+ resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Trailer: http.Header{}, Request: req}
+ resp.Header.Set(name, "app")
+ resp.Header.Set("X-Kept", "1")
+ if announced {
+ resp.Trailer[http.CanonicalHeaderKey(name)] = nil
+ }
+ resp.Body = &trailerAtEOF{r: strings.NewReader("body"), atEOF: func() {
+ resp.Trailer.Set(name, "app")
+ resp.Trailer.Set("X-Kept", "1")
+ }}
+ return resp
+}
+
+func TestEveryScrubRemovesEveryVocabularyEntry(t *testing.T) {
+ if len(clientScrubVocabulary) == 0 {
+ t.Fatal("the vocabulary is empty")
+ }
+ if !isClientScrubVocabulary(pageCacheHeader) {
+ t.Fatal("Carlos-Page-Cache is not on the client scrub list")
+ }
+ for _, name := range clientScrubVocabulary {
+ if !isClientScrubVocabulary(name) || !isClientScrubVocabulary(" "+strings.ToLower(name)+" ") {
+ t.Errorf("isClientScrubVocabulary(%q) = false", name)
+ }
+ }
+ for _, s := range guardScrubs(t) {
+ s := s
+ t.Run(s.name, func(t *testing.T) {
+ covers := map[scrubSurface]bool{}
+ for _, c := range s.covers {
+ covers[c] = true
+ }
+ keep := map[string]bool{}
+ for _, k := range s.keep {
+ if !isClientScrubVocabulary(k) {
+ t.Fatalf("keep names %q, which is not on the list", k)
+ }
+ keep[http.CanonicalHeaderKey(k)] = true
+ }
+ for _, name := range clientScrubVocabulary {
+ canon := http.CanonicalHeaderKey(name)
+ // A final response: the header and both trailer shapes.
+ for _, announced := range []bool{true, false} {
+ resp := guardResponse(name, announced)
+ switch {
+ case s.final != nil:
+ s.final(t, resp)
+ case s.headers != nil:
+ s.headers(resp.Header)
+ case s.writer != nil:
+ w := s.writer(&informationalCapture{h: http.Header{}})
+ maps.Copy(w.Header(), resp.Header)
+ w.WriteHeader(http.StatusOK)
+ resp.Header = w.Header()
+ }
+ if resp.Body != nil {
+ io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ }
+ if covers[surfHeader] && !keep[canon] {
+ if v := resp.Header.Values(name); len(v) > 0 {
+ t.Errorf("%s: %s left on the %s: %q", s.name, name, surfHeader, v)
+ }
+ }
+ surf := surfUnannounced
+ if announced {
+ surf = surfAnnounced
+ }
+ if covers[surf] {
+ if _, ok := resp.Trailer[canon]; ok {
+ t.Errorf("%s: %s left as an %s: %v", s.name, name, surf, resp.Trailer)
+ }
+ if resp.Trailer.Get("X-Kept") != "1" {
+ t.Errorf("%s: an ordinary %s stopped flowing: %v", s.name, surf, resp.Trailer)
+ }
+ }
+ }
+ // A 1xx block.
+ if covers[surfInformational] {
+ capture := &informationalCapture{h: http.Header{}}
+ var w http.ResponseWriter = capture
+ if s.writer != nil {
+ w = s.writer(capture)
+ }
+ w.Header().Set("Link", "</a.js>; rel=preload")
+ w.Header().Set(name, "app")
+ if s.headers != nil {
+ s.headers(w.Header())
+ }
+ w.WriteHeader(http.StatusEarlyHints)
+ if len(capture.early) != 1 || capture.early[0].Get("Link") == "" {
+ t.Fatalf("%s: 1xx blocks %v, want one with its Link", s.name, capture.early)
+ }
+ if v := capture.early[0].Values(name); len(v) > 0 {
+ t.Errorf("%s: %s left on the %s: %q", s.name, name, surfInformational, v)
+ }
+ }
+ }
+ })
+ }
+
+ t.Run("no scrub names the vocabulary itself", func(t *testing.T) {
+ checkVocabularySites(t)
+ })
+}
+
+// vocabularySites are the non-test places allowed to delete, list or
+// compare a vocabulary name by itself, with how often each does. None is a
+// client-boundary scrub of a response:
+//
+// - ServeHTTP and serveDemoTraffic delete a client's fill, acknowledgement
+// and expiry from the inbound REQUEST before any app or home sees it;
+// - serveAssetFillForHop deletes the far edge's assertion from the inbound
+// request, and replaces (ack) or withdraws (unack) the home's own
+// acknowledgement and expiry on a fill's response, which the app's
+// response reached already scrubbed;
+// - backhaulFillKeep and fillVocabularyKeep are the explicit keep sets the
+// scrubs pass to stripVocabularyExcept.
+var vocabularySites = map[string]map[string]int{
+ "ServeHTTP": {"assetAckHeader": 1, "assetExpiresHeader": 1, "assetFillHeader": 1},
+ "serveDemoTraffic": {"assetAckHeader": 1, "assetExpiresHeader": 1, "assetFillHeader": 1},
+ "serveAssetFillForHop": {"assetAckHeader": 2, "assetExpiresHeader": 2, "assetFillHeader": 1},
+ "backhaulFillKeep": {"assetAckHeader": 1, "assetExpiresHeader": 1},
+ "fillVocabularyKeep": {"assetCacheHeader": 1},
+}
+
+// checkVocabularySites parses this package's non-test sources and fails on
+// a vocabulary name used by itself in a Del or delete call, a composite
+// literal, an == or != comparison or a strings.EqualFold call, beyond the
+// counts in vocabularySites; and on any string literal spelling a
+// vocabulary value outside the constant that declares it.
+func checkVocabularySites(t *testing.T) {
+ t.Helper()
+ files, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ values := map[string]bool{}
+ for _, v := range clientScrubVocabulary {
+ values[strings.ToLower(v)] = true
+ }
+ isVocabLit := func(n ast.Node) bool {
+ lit, ok := n.(*ast.BasicLit)
+ if !ok || lit.Kind != token.STRING {
+ return false
+ }
+ s, err := strconv.Unquote(lit.Value)
+ return err == nil && values[strings.ToLower(strings.TrimSpace(s))]
+ }
+ fset := token.NewFileSet()
+ var parsed []*ast.File
+ for _, f := range files {
+ if strings.HasSuffix(f, "_test.go") {
+ continue
+ }
+ src, err := os.ReadFile(f)
+ if err != nil {
+ t.Fatal(err)
+ }
+ af, err := parser.ParseFile(fset, f, src, 0)
+ if err != nil {
+ t.Fatalf("parse %s: %v", f, err)
+ }
+ parsed = append(parsed, af)
+ }
+ // The vocabulary's constants: each const whose value is a vocabulary
+ // string. Their declarations are the only place those strings may be
+ // spelled out.
+ idents := map[string]bool{}
+ declared := map[*ast.BasicLit]bool{}
+ for _, af := range parsed {
+ for _, d := range af.Decls {
+ g, ok := d.(*ast.GenDecl)
+ if !ok || g.Tok != token.CONST {
+ continue
+ }
+ for _, spec := range g.Specs {
+ vs := spec.(*ast.ValueSpec)
+ for i, v := range vs.Values {
+ if isVocabLit(v) && i < len(vs.Names) {
+ idents[vs.Names[i].Name] = true
+ declared[v.(*ast.BasicLit)] = true
+ }
+ }
+ }
+ }
+ }
+ if len(idents) != len(clientScrubVocabulary) {
+ t.Fatalf("found constants %v for the %d vocabulary entries", idents, len(clientScrubVocabulary))
+ }
+ got := map[string]map[string]int{}
+ note := func(site string, e ast.Expr) {
+ id, ok := ast.Unparen(e).(*ast.Ident)
+ if !ok || !idents[id.Name] {
+ return
+ }
+ if got[site] == nil {
+ got[site] = map[string]int{}
+ }
+ got[site][id.Name]++
+ }
+ for _, af := range parsed {
+ for _, d := range af.Decls {
+ site := ""
+ switch d := d.(type) {
+ case *ast.FuncDecl:
+ site = d.Name.Name
+ case *ast.GenDecl:
+ if d.Tok == token.VAR {
+ for _, spec := range d.Specs {
+ for _, n := range spec.(*ast.ValueSpec).Names {
+ site = n.Name
+ }
+ }
+ }
+ }
+ if site == "clientScrubVocabulary" {
+ continue
+ }
+ ast.Inspect(d, func(n ast.Node) bool {
+ switch n := n.(type) {
+ case *ast.BasicLit:
+ if isVocabLit(n) && !declared[n] {
+ t.Errorf("%s: %s spells out a vocabulary name: use the constant, and clientScrubVocabulary to scrub it",
+ fset.Position(n.Pos()), n.Value)
+ }
+ case *ast.CallExpr:
+ switch fn := n.Fun.(type) {
+ case *ast.SelectorExpr:
+ if fn.Sel.Name == "Del" && len(n.Args) == 1 {
+ note(site, n.Args[0])
+ }
+ if x, ok := fn.X.(*ast.Ident); ok && x.Name == "strings" && fn.Sel.Name == "EqualFold" {
+ for _, a := range n.Args {
+ note(site, a)
+ }
+ }
+ case *ast.Ident:
+ if fn.Name == "delete" && len(n.Args) == 2 {
+ note(site, n.Args[1])
+ }
+ }
+ case *ast.CompositeLit:
+ for _, el := range n.Elts {
+ if kv, ok := el.(*ast.KeyValueExpr); ok {
+ note(site, kv.Key)
+ note(site, kv.Value)
+ } else {
+ note(site, el)
+ }
+ }
+ case *ast.BinaryExpr:
+ if n.Op == token.EQL || n.Op == token.NEQ {
+ note(site, n.X)
+ note(site, n.Y)
+ }
+ }
+ return true
+ })
+ }
+ }
+ sites := map[string]bool{}
+ for s := range got {
+ sites[s] = true
+ }
+ for s := range vocabularySites {
+ sites[s] = true
+ }
+ var names []string
+ for s := range sites {
+ names = append(names, s)
+ }
+ sort.Strings(names)
+ for _, s := range names {
+ if !maps.Equal(got[s], vocabularySites[s]) {
+ t.Errorf("%s names the vocabulary by itself %v, want %v: a client-boundary scrub iterates clientScrubVocabulary "+
+ "(with an explicit keep set) and goes in guardScrubs; a request-side site is counted in vocabularySites",
+ s, got[s], vocabularySites[s])
+ }
+ }
+}