carlos / platform Public

edge: static sites serve _headers on 200/206/304 by request path; static routes leave the shared cache (#195, #450)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 2939b9c9d16d40de0d77b254488bfcb378bfda1a parent 32c1b37
6 files changed, +928 −16
  • internal/edge/edge.go +16 −4
  • internal/edge/headerwriter.go +121 −0
  • internal/edge/static.go +52 −12
  • internal/edge/static_headers_golden_test.go +182 −0
  • internal/edge/static_headers_test.go +392 −0
  • internal/edge/testdata/static-headers-golden.json +165 −0

Intent

Human

<task-notification> <task-id>ad6f49ee546021a6b</task-id> <tool-use-id>toolu_01XTRZWcBRcqR67YbJ7KXcy8</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/0f246987-ca6b-4093-b104-f930443a8208/tasks/ad6f49ee546021a6b.output</output-file> <status>completed</status> <summary>Agent "Implement Task 1: _headers parser" 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: 32c1b374 edge: _headers limits cover every line and path line; Cache-Control quoted commas (git printed the packed-refs.lock warning; the commit landed). Tests: the covering run passes (`ok ... 1.433s`). `gofmt -l internal/edge` is empty and `go vet` is clean. With the old `headers.go` restored, the new limits tests fail, so they do catch both bugs. Fixes: 1. **Limits:** The 2,048-character check now applies to comments and blank lines too. A path-line counter counts every column-0 line, usable or not, so a valid path after 100 refused or headerless ones is refused with `more than 100 path lines`. `TestParseHeadersLimits` has the new cases. 2. **Quoted Cache-Control:** `splitOutsideQuotes` splits only at commas outside quotes. `no-cache="X-One, X-Two"` is accepted and stored intact. A malformed quote is refused. The new test is `TestParseHeadersCacheControlQuotes`. Concern: as before, the `go` commands ran with the sandbox disabled because the default go-build cache is read-only in the sandbox. Report (fix section appended): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/.superpowers/sdd/2026-10-29-static-headers/task-1-report.md</result> <usage><subagent_tokens>94381</subagent_tokens><tool_uses>6</tool_uses><duration_ms>84039</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bq95dr18t</task-id> <tool-use-id>toolu_01REgUG36f7Nb82sdbyhqReb</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/0f246987-ca6b-4093-b104-f930443a8208/tasks/bq95dr18t.output</output-file> <status>completed</status> <summary>Background command "Run the scoped Astra re-review of Task 1" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>bpl8epiq7</task-id> <tool-use-id>toolu_01X1YzppzHtKvFpujyF3FHEv</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/0f246987-ca6b-4093-b104-f930443a8208/tasks/bpl8epiq7.output</output-file> <status>completed</status> <summary>Background command "Wait for the copy review result" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 13.9 g CO₂e (1,733,752 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on static-headers, 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/edge.go b/internal/edge/edge.go
index 15b254516..0a8cb6e54 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -2059,6 +2059,17 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// exists to hold: the status host caches for itself; its responses never
// enter the shared response cache.
//
+ // Kind=="static" is exempt in both directions too, whether this box serves
+ // the tree or proxies the route to one that does (static-headers spec
+ // section 4.4). A _headers max-age would otherwise make its answers
+ // storable, and the cache is the wrong place for them:
+ // - a hit replays a stored 200 with no Age and no conditional handling,
+ // so a revalidation gets the whole file instead of a 304;
+ // - a hit replays the X-Carlos-Version frozen at store time, which the
+ // static deploy watch reads to know a deploy landed;
+ // - a static deploy does not purge it;
+ // - the tree is on a box's disk already, so a hit saves nothing.
+ //
// A gated row's verify request is exempt in both directions too: it must
// reach the import rather than a response cached for the legacy route,
// and the import's answer must not outlive a rollback.
@@ -2070,7 +2081,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
cacheable := e.cache != nil && (r.Method == http.MethodGet || r.Method == http.MethodHead) &&
- up.route.Kind != "status" && up.route.ImportGate == ""
+ up.route.Kind != "status" && up.route.Kind != "static" && up.route.ImportGate == ""
var key CacheKey
if cacheable {
key = CacheKey{Host: host, Method: r.Method, Path: r.URL.Path, RawQuery: r.URL.RawQuery}
@@ -2178,9 +2189,10 @@ func (e *Edge) cacheMaxBody() int {
// The stored TTL is clamped to DefaultCacheMaxTTL so a lost purge always
// self-heals within a bounded window.
//
-// One refusal is NOT made here because it has to be made earlier, where the
-// route is still in hand: Kind=="status" responses are never admitted at
-// all. See the cacheable computation in ServeHTTP for why.
+// Two refusals are NOT made here because they have to be made earlier, where
+// the route is still in hand: Kind=="status" and Kind=="static" responses
+// are never admitted at all. See the cacheable computation in ServeHTTP for
+// why.
func (e *Edge) maybeStore(key CacheKey, rec *recordingResponseWriter) {
if e.cache == nil || !rec.cacheable || rec.truncated {
return
diff --git a/internal/edge/headerwriter.go b/internal/edge/headerwriter.go
new file mode 100644
index 000000000..51274ab20
--- /dev/null
+++ b/internal/edge/headerwriter.go
@@ -0,0 +1,121 @@
+// The writer that puts a static site's _headers on its answers (headers.go
+// parses the file; serveFile installs this). The headers describe a file's
+// bytes, so they go on an answer that carries them, or refers to them, and
+// on nothing else: a 200, a 206 or a 304. Which of those an answer is gets
+// decided inside http.ServeContent, so the headers are applied when the
+// status is written, not before (spec section 4.3).
+package edge
+
+import "net/http"
+
+// headerWriter applies extra to the header block of an answer whose status
+// is 200, 206 or 304, and leaves every other answer's header block exactly as
+// the handler wrote it.
+//
+// It owns a PRIVATE header map, as gzipWriter does (AGENTS.md: a wrapper that
+// edits headers needs its own map). Setting extra on the shared map up front
+// is not enough: net/http's checkPreconditions writes a 412 straight to the
+// writer with whatever is already set, so immutable would ride an answer that
+// holds no file, and serveError clears Cache-Control on a 416 but would leave
+// Access-Control-Allow-Origin. So ServeContent's own edits (its 304 and error
+// deletions included) land on hdr, and the map below is made to match it at
+// the status, once extra has had its say or not.
+//
+// Deliberately does NOT implement io.ReaderFrom: io.Copy (and so
+// ServeContent) falls back to Write, which goes through the status hook. An
+// Unwrap method does not make a type assertion on ReaderFrom succeed, so the
+// writer below's ReadFrom is never reached around it.
+type headerWriter struct {
+ http.ResponseWriter
+ hdr, extra http.Header
+ wroteHdr bool
+}
+
+// newHeaderWriter wraps w to apply extra, a headerRules.lookup result. The
+// private map starts as a copy of w's, so what ServeHTTP set already (the
+// version, the default no-cache) is there for the handler to read and for
+// extra to replace.
+func newHeaderWriter(w http.ResponseWriter, extra http.Header) *headerWriter {
+ return &headerWriter{ResponseWriter: w, hdr: w.Header().Clone(), extra: extra}
+}
+
+// Header returns the PRIVATE map. See the type's doc comment.
+func (h *headerWriter) Header() http.Header { return h.hdr }
+
+// syncHeader replaces the map below with the private one. Wholesale, not a
+// merge, as gzipWriter.syncHeader: a header ServeContent DELETED (a 304's
+// Content-Type, a 416's Cache-Control) must be gone below too.
+func (h *headerWriter) syncHeader() {
+ down := h.ResponseWriter.Header()
+ for k := range down {
+ delete(down, k)
+ }
+ for k, v := range h.hdr {
+ down[k] = v
+ }
+}
+
+func (h *headerWriter) WriteHeader(status int) {
+ // A 1xx block precedes the final status and describes no bytes: sync and
+ // forward without latching or applying, as gzipWriter does.
+ if status < 200 {
+ h.syncHeader()
+ h.ResponseWriter.WriteHeader(status)
+ return
+ }
+ if h.wroteHdr {
+ h.ResponseWriter.WriteHeader(status) // superfluous; let the stdlib log it
+ return
+ }
+ h.wroteHdr = true
+ switch status {
+ case http.StatusOK, http.StatusPartialContent, http.StatusNotModified:
+ // Set, not Add: a matched Cache-Control replaces the default
+ // no-cache. lookup's keys are canonical and its map is ours.
+ for k, v := range h.extra {
+ h.hdr[k] = v
+ }
+ }
+ h.syncHeader()
+ h.ResponseWriter.WriteHeader(status)
+}
+
+func (h *headerWriter) Write(p []byte) (int, error) {
+ if !h.wroteHdr {
+ h.WriteHeader(http.StatusOK)
+ }
+ return h.ResponseWriter.Write(p)
+}
+
+// Flush is an implicit 200 like Write, so a flush before any body still
+// sends the answer's headers through the status hook rather than around it.
+func (h *headerWriter) Flush() {
+ if !h.wroteHdr {
+ h.WriteHeader(http.StatusOK)
+ }
+ if f, ok := h.ResponseWriter.(http.Flusher); ok {
+ f.Flush()
+ }
+}
+
+// Unwrap is for http.ResponseController.
+func (h *headerWriter) Unwrap() http.ResponseWriter { return h.ResponseWriter }
+
+// finish copies headers added to the private map after the status down to
+// the writer below: net/http sends those as trailers, and they landed on hdr,
+// where syncHeader has already been and gone. serveFile defers it.
+//
+// With no status written (serveFile always writes one, so this is a guard)
+// the private map is synced down without extra, as gzipWriter.finish does:
+// net/http's implicit 200 then carries what the handler set and none of the
+// rule's headers, since it carries none of the file's bytes.
+func (h *headerWriter) finish() {
+ if !h.wroteHdr {
+ h.syncHeader()
+ return
+ }
+ down := h.ResponseWriter.Header()
+ for k, v := range h.hdr {
+ down[k] = v
+ }
+}
diff --git a/internal/edge/static.go b/internal/edge/static.go
index a415c8987..f2ff754c4 100644
--- a/internal/edge/static.go
+++ b/internal/edge/static.go
@@ -147,6 +147,7 @@ type staticSite struct {
digest string // the served tree's manifest digest
name string // the served tree's directory: siteDirName(version, digest)
redirects *redirectRules // the served tree's _redirects; nil when it has none
+ headers *headerRules // the served tree's _headers; nil when it has none
// ratchet is #253's per-box ratchet for this process's pointer reads
// (Edge.staticRatchet); nil admits every verified pointer.
@@ -199,21 +200,24 @@ func (s *staticSite) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// its copy without asking, so a site last deployed a month ago kept
// showing the old page for days after the next deploy (discussion #195).
// no-cache is "store it, but ask first"; the ETag serveTree sets is what
- // makes asking cost a 304. It also keeps these responses out of the
- // edge's own shared cache, which admits only a positive lifetime — as
- // they always were, having named none. (net/http strips the header again
- // from the errors it writes itself, a 416 or a 400: neither is a status a
- // browser caches on a guess.)
+ // makes asking cost a 304. A _headers rule may replace it on an answer
+ // that carries a file (serveFile); the edge's own shared cache holds none
+ // of them either way, since Edge.ServeHTTP leaves static routes out of
+ // it. (net/http strips the header again from the errors it writes
+ // itself, a 416 or a 400: neither is a status a browser caches on a
+ // guess.)
w.Header().Set("Cache-Control", "no-cache")
s.serveTree(tree, w, r)
}
// servedTree is what one request is answered from: an extracted tree, the
-// version it holds, and the rules its _redirects declared. They travel
-// together so a request never pairs one version's files with another's rules.
+// version it holds, and the rules its _redirects and _headers declared. They
+// travel together so a request never pairs one version's files with another's
+// rules.
type servedTree struct {
dir, version string
redirects *redirectRules
+ headers *headerRules
}
// dir is where the tree named name lives once extracted.
@@ -272,6 +276,7 @@ func (s *staticSite) currentDir(ctx context.Context) (servedTree, error) {
}
s.version, s.digest, s.name = cp.Version, digest, name
s.redirects = s.loadRedirects(s.dir(name), cp.Version)
+ s.headers = s.loadHeaders(s.dir(name), cp.Version)
}
s.checkedAt = time.Now()
return s.served(), nil
@@ -279,7 +284,7 @@ func (s *staticSite) currentDir(ctx context.Context) (servedTree, error) {
// served is the tree currently being served. The caller holds mu.
func (s *staticSite) served() servedTree {
- return servedTree{dir: s.dir(s.name), version: s.version, redirects: s.redirects}
+ return servedTree{dir: s.dir(s.name), version: s.version, redirects: s.redirects, headers: s.headers}
}
// loadRedirects parses the _redirects at the root of an extracted tree, once
@@ -302,6 +307,25 @@ func (s *staticSite) loadRedirects(dir, version string) *redirectRules {
return rules
}
+// loadHeaders parses the _headers at the root of an extracted tree, once per
+// version swap, as loadRedirects does _redirects: no file is no rules, and a
+// line that does not parse is logged and skipped (ship refuses such a tree).
+func (s *staticSite) loadHeaders(dir, version string) *headerRules {
+ data, err := os.ReadFile(filepath.Join(dir, headersFile))
+ if errors.Is(err, fs.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ log.Printf("edge: static %s/%s: %s %s: %v — serving without its rules", s.app, s.channel, version, headersFile, err)
+ return nil
+ }
+ rules, err := parseHeaders(data)
+ if err != nil {
+ log.Printf("edge: static %s/%s: %s %s: %s", s.app, s.channel, version, headersFile, strings.ReplaceAll(err.Error(), "\n", "; "))
+ }
+ return rules
+}
+
// stale is the degraded path: keep serving the version we already verified
// and extracted — and name it, so the response header describes the CACHED
// tree rather than the head this handler could not reach — or fail if there
@@ -478,6 +502,11 @@ func (s *staticSite) serveTree(tree servedTree, w http.ResponseWriter, r *http.R
}
// Clean rooted at "/" so no request path can climb out of the tree.
p := path.Clean("/" + r.URL.Path)
+ // The _headers rules match the URL the browser holds, so they are looked
+ // up here, before a _redirects rewrite moves p: /1/fiesta.css rewritten
+ // onto /1.0.0/fiesta.css keeps /1/*'s short max-age rather than taking
+ // the exact release's immutable one (spec section 4.1).
+ extra := tree.headers.lookup(requestHost(r.Host), p)
status, rewritten := http.StatusOK, false
// guard is whether the guard still has this request to decide: it runs
// for r, and ServeHTTP's hard check on the request path noted nothing.
@@ -494,8 +523,9 @@ func (s *staticSite) serveTree(tree servedTree, w http.ResponseWriter, r *http.R
fp = filepath.Join(fp, "index.html")
fi, err = os.Stat(fp)
}
- // The _redirects file is configuration and answers nothing.
- found := err == nil && !fi.IsDir() && p != "/"+redirectsFile
+ // The _redirects and _headers files are configuration and answer
+ // nothing.
+ found := err == nil && !fi.IsDir() && p != "/"+redirectsFile && p != "/"+headersFile
if !rewritten {
// The probe tier, which ServeHTTP leaves to the tree: a path like
// /wp-login.php is a probe only when the site has no such page,
@@ -578,7 +608,7 @@ func (s *staticSite) serveTree(tree servedTree, w http.ResponseWriter, r *http.R
w.WriteHeader(http.StatusMovedPermanently)
return
}
- s.serveFile(fp, p, fi, status, w, r)
+ s.serveFile(fp, p, fi, status, extra, w, r)
return
}
}
@@ -596,7 +626,12 @@ func staticGuardPending(r *http.Request) bool {
// gets a content tag and net/http's conditional and range handling. Any other
// status — a _redirects 404 page — is the file's bytes under that status,
// with no validator: ServeContent knows only how to succeed.
-func (s *staticSite) serveFile(fp, p string, fi os.FileInfo, status int, w http.ResponseWriter, r *http.Request) {
+//
+// extra is the _headers rules' match for the request, nil for none. Only the
+// 200 path takes it, through a headerWriter that applies it if ServeContent
+// answers 200, 206 or 304 and leaves its 412s and 416s as they are: a 404 page
+// marked immutable would pin a typo in every browser for a year.
+func (s *staticSite) serveFile(fp, p string, fi os.FileInfo, status int, extra http.Header, w http.ResponseWriter, r *http.Request) {
f, err := os.Open(fp)
if err != nil {
// ServeFile's mapping, kept: a file that vanished since the Stat is
@@ -634,6 +669,11 @@ func (s *staticSite) serveFile(fp, p string, fi os.FileInfo, status int, w http.
}
return
}
+ if extra != nil {
+ hw := newHeaderWriter(w, extra)
+ defer hw.finish()
+ w = hw
+ }
// Stat the OPEN file: its identity is what a remembered tag is checked
// against, and it is the file whose bytes are about to be sent.
if ofi, err := f.Stat(); err == nil && !ofi.IsDir() {
diff --git a/internal/edge/static_headers_golden_test.go b/internal/edge/static_headers_golden_test.go
new file mode 100644
index 000000000..44aeb2ec1
--- /dev/null
+++ b/internal/edge/static_headers_golden_test.go
@@ -0,0 +1,182 @@
+package edge
+
+import (
+ "context"
+ "encoding/json"
+ "flag"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The guard for a tree with no _headers file (spec section 5): every header
+// of every answer stays what it was before the edge read _headers at all. The
+// golden was captured on the code before that change, through this file's own
+// fixture, so it compiles and runs without any of that change's code.
+
+var updateHeadersGolden = flag.Bool("update-headers-golden", false,
+ "rewrite testdata/static-headers-golden.json from the current code")
+
+const staticHeadersGolden = "testdata/static-headers-golden.json"
+
+// staticHeadersTree is the Fiesta-shaped tree the _headers tests serve, minus
+// its _headers file. fiesta.css is over minCompressSize, so a client that
+// accepts gzip gets it compressed.
+func staticHeadersTree() map[string]string {
+ return map[string]string{
+ "1.0.0/fiesta.css": strings.Repeat(".fiesta { color: red; }\n", 64),
+ "1.0.0/index.html": "fiesta 1.0.0",
+ "index.html": "home",
+ "_redirects": "/1/* /1.0.0/:splat 200\n",
+ }
+}
+
+// goldenStaticEdge serves files as a static site through the real edge, with
+// the shared response cache on as production runs it.
+func goldenStaticEdge(t *testing.T, files map[string]string) *httptest.Server {
+ t.Helper()
+ store := release.NewDirStore(filepath.Join(t.TempDir(), "store"))
+ priv, pub := testKeys(t)
+ shipSite(t, store, "site", "v1", files)
+ if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "canary/x", "v1"); err != nil {
+ t.Fatalf("Promote: %v", err)
+ }
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "canary/x", Status: "ready"}); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes))
+ e.EnableStatic(store, pub, filepath.Join(t.TempDir(), "cache"))
+ if err := e.Reload(); err != nil {
+ t.Fatalf("Reload: %v", err)
+ }
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ return srv
+}
+
+// staticClient neither follows redirects nor asks for gzip on its own, so a
+// response's headers reach the test as the edge wrote them: Go's transport
+// otherwise decompresses and drops Content-Encoding and Content-Length.
+var staticClient = &http.Client{
+ Transport: &http.Transport{DisableCompression: true},
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
+}
+
+// staticDo sends one request for path on site.example.com with the given
+// request headers and returns the response with its body read.
+func staticDo(t *testing.T, srv *httptest.Server, method, path string, hdr map[string]string) (*http.Response, string) {
+ t.Helper()
+ req, err := http.NewRequest(method, srv.URL+path, nil)
+ if err != nil {
+ t.Fatalf("new request: %v", err)
+ }
+ req.Host = "site.example.com"
+ for k, v := range hdr {
+ req.Header.Set(k, v)
+ }
+ resp, err := staticClient.Do(req)
+ if err != nil {
+ t.Fatalf("%s %s: %v", method, path, err)
+ }
+ defer resp.Body.Close()
+ b, err := io.ReadAll(resp.Body)
+ if err != nil {
+ t.Fatalf("read %s %s: %v", method, path, err)
+ }
+ return resp, string(b)
+}
+
+// goldenAnswer is one response as the golden records it: the status and
+// every header but Date.
+type goldenAnswer struct {
+ Status int `json:"status"`
+ Header http.Header `json:"header"`
+}
+
+func TestStaticWithoutHeadersIsUnchanged(t *testing.T) {
+ srv := goldenStaticEdge(t, staticHeadersTree())
+ got := map[string]goldenAnswer{}
+ record := func(name string, resp *http.Response) {
+ h := resp.Header.Clone()
+ h.Del("Date")
+ got[name] = goldenAnswer{Status: resp.StatusCode, Header: h}
+ }
+
+ resp, _ := staticDo(t, srv, "GET", "/1.0.0/fiesta.css", nil)
+ record("200", resp)
+ etag := resp.Header.Get("Etag")
+ if etag == "" {
+ t.Fatalf("GET /1.0.0/fiesta.css has no Etag: %v", resp.Header)
+ }
+ resp, _ = staticDo(t, srv, "GET", "/1.0.0/fiesta.css", map[string]string{"If-None-Match": etag})
+ record("304", resp)
+ resp, _ = staticDo(t, srv, "GET", "/1.0.0/fiesta.css", map[string]string{"Range": "bytes=0-3"})
+ record("206", resp)
+ resp, _ = staticDo(t, srv, "HEAD", "/1.0.0/fiesta.css", nil)
+ record("HEAD", resp)
+ resp, _ = staticDo(t, srv, "GET", "/1.0.0/fiesta.css", map[string]string{"If-Match": `"nope"`})
+ record("412", resp)
+ resp, _ = staticDo(t, srv, "GET", "/1.0.0/fiesta.css", map[string]string{"Range": "bytes=999999-"})
+ record("416", resp)
+ resp, _ = staticDo(t, srv, "GET", "/missing", nil)
+ record("404", resp)
+ resp, _ = staticDo(t, srv, "GET", "/1.0.0", nil)
+ record("301", resp)
+
+ if *updateHeadersGolden {
+ b, err := json.MarshalIndent(got, "", " ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Dir(staticHeadersGolden), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(staticHeadersGolden, append(b, '\n'), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ return
+ }
+ raw, err := os.ReadFile(staticHeadersGolden)
+ if err != nil {
+ t.Fatalf("read golden (run with -update-headers-golden on the code it pins): %v", err)
+ }
+ var want map[string]goldenAnswer
+ if err := json.Unmarshal(raw, &want); err != nil {
+ t.Fatalf("parse golden: %v", err)
+ }
+ for name, w := range want {
+ g, ok := got[name]
+ if !ok {
+ t.Errorf("%s: not captured", name)
+ continue
+ }
+ if g.Status != w.Status {
+ t.Errorf("%s: status %d, golden %d", name, g.Status, w.Status)
+ }
+ for k := range w.Header {
+ if gv, wv := strings.Join(g.Header.Values(k), "\n"), strings.Join(w.Header.Values(k), "\n"); gv != wv {
+ t.Errorf("%s: %s = %q, golden %q", name, k, gv, wv)
+ }
+ }
+ for k := range g.Header {
+ if _, ok := w.Header[k]; !ok {
+ t.Errorf("%s: %s = %q, not in the golden", name, k, g.Header.Values(k))
+ }
+ }
+ }
+ if len(got) != len(want) {
+ t.Errorf("captured %d answers, golden has %d", len(got), len(want))
+ }
+}
diff --git a/internal/edge/static_headers_test.go b/internal/edge/static_headers_test.go
new file mode 100644
index 000000000..b2e605707
--- /dev/null
+++ b/internal/edge/static_headers_test.go
@@ -0,0 +1,392 @@
+package edge
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The edge serving a static site's _headers (spec section 4), through the
+// real Edge.ServeHTTP with the shared response cache on.
+
+// fiestaHeaders is spec section 2's file.
+const fiestaHeaders = `# Exact releases never change.
+/1.0.0/*
+ Cache-Control: public, max-age=31536000, immutable
+ Access-Control-Allow-Origin: *
+
+# The floating major moves to each new 1.x.
+/1/*
+ Cache-Control: public, max-age=300
+ Access-Control-Allow-Origin: *
+`
+
+const (
+ ccImmutable = "public, max-age=31536000, immutable"
+ ccFloating = "public, max-age=300"
+)
+
+// fiestaTree is staticHeadersTree with fiestaHeaders shipped beside it.
+func fiestaTree() map[string]string {
+ files := staticHeadersTree()
+ files[headersFile] = fiestaHeaders
+ return files
+}
+
+// fiestaKey is the shared cache's key for a GET of /1.0.0/fiesta.css.
+var fiestaKey = CacheKey{Host: "site.example.com", Method: "GET", Path: "/1.0.0/fiesta.css"}
+
+// headersEdge serves files as a static site through the real edge with the
+// shared cache on, and returns the server and the directory the tree is
+// extracted into (it exists once the first request has been answered).
+func headersEdge(t *testing.T, files map[string]string) (srv *httptest.Server, treeDir string) {
+ t.Helper()
+ _, srv, treeDir = headersEdgeWith(t, files)
+ return srv, treeDir
+}
+
+// headersEdgeWith is headersEdge for tests that need the edge itself.
+func headersEdgeWith(t *testing.T, files map[string]string) (*Edge, *httptest.Server, string) {
+ t.Helper()
+ store := release.NewDirStore(filepath.Join(t.TempDir(), "store"))
+ priv, pub := testKeys(t)
+ shipSite(t, store, "site", "v1", files)
+ if err := release.Promote(context.Background(), store, priv, release.OpsAccount, "site", "canary/x", "v1"); err != nil {
+ t.Fatalf("Promote: %v", err)
+ }
+ rt := registry.Route{Host: "site.example.com", Kind: "static", App: "site", Channel: "canary/x", Status: "ready"}
+ reg := openReg(t)
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes))
+ cacheDir := filepath.Join(t.TempDir(), "cache")
+ e.EnableStatic(store, pub, cacheDir)
+ if err := e.Reload(); err != nil {
+ t.Fatalf("Reload: %v", err)
+ }
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ treeDir := filepath.Join(cacheDir, release.RouteAccount(rt), "site", siteDirOf(t, store, "site", "v1"))
+ return e, srv, treeDir
+}
+
+// wantHeaders fails unless resp carries the Cache-Control and
+// Access-Control-Allow-Origin given; "" means the header is absent.
+func wantHeaders(t *testing.T, what string, resp *http.Response, cc, acao string) {
+ t.Helper()
+ if got := resp.Header.Values("Cache-Control"); strings.Join(got, ", ") != cc || (cc == "" && got != nil) {
+ t.Errorf("%s: Cache-Control = %q, want %q", what, got, cc)
+ }
+ if got := resp.Header.Values("Access-Control-Allow-Origin"); strings.Join(got, ", ") != acao || (acao == "" && got != nil) {
+ t.Errorf("%s: Access-Control-Allow-Origin = %q, want %q", what, got, acao)
+ }
+}
+
+func TestStaticHeadersFiestaFile(t *testing.T) {
+ srv, _ := headersEdge(t, fiestaTree())
+
+ resp, exact := staticDo(t, srv, "GET", "/1.0.0/fiesta.css", nil)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("GET /1.0.0/fiesta.css = %d, want 200", resp.StatusCode)
+ }
+ wantHeaders(t, "/1.0.0/fiesta.css", resp, ccImmutable, "*")
+ if resp.Header.Get("Etag") == "" {
+ t.Errorf("/1.0.0/fiesta.css: no Etag")
+ }
+
+ // Rewritten onto the same file, but matched on the URL the browser
+ // holds: the floating major must not be frozen for a year.
+ resp, floating := staticDo(t, srv, "GET", "/1/fiesta.css", nil)
+ if resp.StatusCode != http.StatusOK || floating != exact {
+ t.Fatalf("GET /1/fiesta.css = %d (%d bytes), want 200 with /1.0.0/fiesta.css's %d bytes", resp.StatusCode, len(floating), len(exact))
+ }
+ wantHeaders(t, "/1/fiesta.css", resp, ccFloating, "*")
+
+ // A page no rule matches keeps the default.
+ resp, body := staticDo(t, srv, "GET", "/", nil)
+ if resp.StatusCode != http.StatusOK || body != "home" {
+ t.Fatalf("GET / = %d %q, want 200 %q", resp.StatusCode, body, "home")
+ }
+ wantHeaders(t, "/", resp, "no-cache", "")
+}
+
+func TestStaticHeadersRideTheRevalidationRangeAndHead(t *testing.T) {
+ srv, _ := headersEdge(t, fiestaTree())
+ resp, body := staticDo(t, srv, "GET", "/1.0.0/fiesta.css", nil)
+ etag := resp.Header.Get("Etag")
+ if resp.StatusCode != http.StatusOK || etag == "" {
+ t.Fatalf("GET = %d, Etag %q; want 200 with an Etag", resp.StatusCode, etag)
+ }
+
+ resp, _ = staticDo(t, srv, "GET", "/1.0.0/fiesta.css", map[string]string{"If-None-Match": etag})
+ if resp.StatusCode != http.StatusNotModified {
+ t.Fatalf("revalidation = %d, want 304", resp.StatusCode)
+ }
+ wantHeaders(t, "304", resp, ccImmutable, "*")
+
+ resp, part := staticDo(t, srv, "GET", "/1.0.0/fiesta.css", map[string]string{"Range": "bytes=0-3"})
+ if resp.StatusCode != http.StatusPartialContent || part != body[:4] {
+ t.Fatalf("range = %d %q, want 206 %q", resp.StatusCode, part, body[:4])
+ }
+ wantHeaders(t, "206", resp, ccImmutable, "*")
+
+ resp, _ = staticDo(t, srv, "HEAD", "/1.0.0/fiesta.css", nil)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("HEAD = %d, want 200", resp.StatusCode)
+ }
+ wantHeaders(t, "HEAD", resp, ccImmutable, "*")
+}
+
+// Each answer here sits under /1.0.0/* and holds no file's bytes, so it keeps
+// the headers it has with no _headers file (the golden's: no-cache, or none
+// where net/http clears it) and gets none of the rule's.
+func TestStaticHeadersStayOffErrorsAndRedirects(t *testing.T) {
+ srv, _ := headersEdge(t, fiestaTree())
+ for _, c := range []struct {
+ name, path string
+ hdr map[string]string
+ status int
+ cc string
+ }{
+ {"412", "/1.0.0/fiesta.css", map[string]string{"If-Match": `"nope"`}, http.StatusPreconditionFailed, "no-cache"},
+ {"416", "/1.0.0/fiesta.css", map[string]string{"Range": "bytes=999999-"}, http.StatusRequestedRangeNotSatisfiable, ""},
+ {"404", "/1.0.0/missing.css", nil, http.StatusNotFound, "no-cache"},
+ {"folder 301", "/1.0.0", nil, http.StatusMovedPermanently, "no-cache"},
+ {"index 301", "/1.0.0/index.html", nil, http.StatusMovedPermanently, "no-cache"},
+ } {
+ resp, _ := staticDo(t, srv, "GET", c.path, c.hdr)
+ if resp.StatusCode != c.status {
+ t.Errorf("%s: GET %s = %d, want %d", c.name, c.path, resp.StatusCode, c.status)
+ continue
+ }
+ wantHeaders(t, c.name, resp, c.cc, "")
+ }
+}
+
+func TestStaticHeadersDirectoryIndex(t *testing.T) {
+ srv, _ := headersEdge(t, fiestaTree())
+ resp, body := staticDo(t, srv, "GET", "/1.0.0/", nil)
+ if resp.StatusCode != http.StatusOK || body != "fiesta 1.0.0" {
+ t.Fatalf("GET /1.0.0/ = %d %q, want 200 %q", resp.StatusCode, body, "fiesta 1.0.0")
+ }
+ wantHeaders(t, "/1.0.0/", resp, ccImmutable, "*")
+}
+
+func TestStaticHeadersSurviveCompression(t *testing.T) {
+ srv, _ := headersEdge(t, fiestaTree())
+ resp, _ := staticDo(t, srv, "GET", "/1.0.0/fiesta.css", map[string]string{"Accept-Encoding": "gzip"})
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("GET = %d, want 200", resp.StatusCode)
+ }
+ if got := resp.Header.Get("Content-Encoding"); got != "gzip" {
+ t.Errorf("Content-Encoding = %q, want gzip", got)
+ }
+ if got := joinHeader(resp.Header, "Vary"); !strings.Contains(got, "Accept-Encoding") {
+ t.Errorf("Vary = %q, want Accept-Encoding", got)
+ }
+ wantHeaders(t, "gzip", resp, ccImmutable, "*")
+}
+
+func TestStaticHeadersFileIsNotServed(t *testing.T) {
+ srv, _ := headersEdge(t, fiestaTree())
+ resp, body := staticDo(t, srv, "GET", "/"+headersFile, nil)
+ if resp.StatusCode != http.StatusNotFound || strings.Contains(body, "max-age") {
+ t.Fatalf("GET /%s = %d %q, want a 404 that is not the file", headersFile, resp.StatusCode, body)
+ }
+}
+
+func TestHeaderWriterKeepsItsOwnMap(t *testing.T) {
+ extra := func() http.Header {
+ return http.Header{"Cache-Control": {ccImmutable}, "Access-Control-Allow-Origin": {"*"}}
+ }
+ below := func() *httptest.ResponseRecorder {
+ rec := httptest.NewRecorder()
+ rec.Header().Set("Cache-Control", "no-cache")
+ rec.Header().Set("X-Gone", "1")
+ return rec
+ }
+
+ // Edits stay private until the status is written; a deletion reaches
+ // the writer below then.
+ rec := below()
+ hw := newHeaderWriter(rec, extra())
+ hw.Header().Set("Etag", `"a"`)
+ hw.Header().Del("X-Gone")
+ if rec.Header().Get("Etag") != "" {
+ t.Fatalf("Etag reached the writer below before WriteHeader")
+ }
+ hw.WriteHeader(http.StatusOK)
+ if rec.Header().Get("Etag") != `"a"` {
+ t.Errorf("Etag = %q after WriteHeader, want %q", rec.Header().Get("Etag"), `"a"`)
+ }
+ if _, ok := rec.Header()["X-Gone"]; ok {
+ t.Errorf("X-Gone survived its deletion")
+ }
+
+ for status, applied := range map[int]bool{
+ http.StatusOK: true, http.StatusPartialContent: true, http.StatusNotModified: true,
+ http.StatusPreconditionFailed: false,
+ } {
+ rec := below()
+ newHeaderWriter(rec, extra()).WriteHeader(status)
+ cc, acao := rec.Header().Get("Cache-Control"), rec.Header().Get("Access-Control-Allow-Origin")
+ if applied && (cc != ccImmutable || acao != "*") {
+ t.Errorf("%d: Cache-Control %q, ACAO %q; want the extra headers", status, cc, acao)
+ }
+ if !applied && (cc != "no-cache" || acao != "") {
+ t.Errorf("%d: Cache-Control %q, ACAO %q; want them untouched", status, cc, acao)
+ }
+ }
+
+ // A Write and a Flush with no status first are an implicit 200.
+ rec = below()
+ hw = newHeaderWriter(rec, extra())
+ hw.Write([]byte("x"))
+ if rec.Code != http.StatusOK || rec.Header().Get("Cache-Control") != ccImmutable {
+ t.Errorf("Write: %d, Cache-Control %q; want 200 with the extra", rec.Code, rec.Header().Get("Cache-Control"))
+ }
+ rec = below()
+ hw = newHeaderWriter(rec, extra())
+ hw.Flush()
+ if !rec.Flushed || rec.Code != http.StatusOK || rec.Header().Get("Cache-Control") != ccImmutable {
+ t.Errorf("Flush: flushed %v, %d, Cache-Control %q; want a flushed 200 with the extra", rec.Flushed, rec.Code, rec.Header().Get("Cache-Control"))
+ }
+ if hw.Unwrap() != http.ResponseWriter(rec) {
+ t.Errorf("Unwrap is not the writer below")
+ }
+
+ // io.Copy must go through Write, never around the status hook.
+ if _, ok := any(hw).(io.ReaderFrom); ok {
+ t.Errorf("headerWriter implements io.ReaderFrom")
+ }
+
+ // A trailer set after the status reaches the writer below on finish.
+ rec = below()
+ hw = newHeaderWriter(rec, extra())
+ hw.Header().Set("Trailer", "X-T")
+ hw.WriteHeader(http.StatusOK)
+ hw.Write([]byte("body"))
+ hw.Header().Set("X-T", "late")
+ if rec.Header().Get("X-T") != "" {
+ t.Fatalf("trailer reached the writer below before finish")
+ }
+ hw.finish()
+ if got := rec.Result().Trailer.Get("X-T"); got != "late" {
+ t.Errorf("trailer X-T = %q after finish, want %q", got, "late")
+ }
+}
+
+func TestStaticWithMaxAgeIsNeverStoredInTheSharedCache(t *testing.T) {
+ e, srv, treeDir := headersEdgeWith(t, fiestaTree())
+ resp, first := staticDo(t, srv, "GET", "/1.0.0/fiesta.css", nil)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("first GET = %d, want 200", resp.StatusCode)
+ }
+ firstTag := resp.Header.Get("Etag")
+
+ // A new file renamed over the old one, so the tag cache sees a new file.
+ fp := filepath.Join(treeDir, "1.0.0", "fiesta.css")
+ tmp := fp + ".new"
+ if err := os.WriteFile(tmp, []byte(".fiesta { color: blue; }\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Rename(tmp, fp); err != nil {
+ t.Fatal(err)
+ }
+
+ resp, second := staticDo(t, srv, "GET", "/1.0.0/fiesta.css", nil)
+ if second == first || second != ".fiesta { color: blue; }\n" {
+ t.Fatalf("second GET served %d bytes, want the new file's %d (a stored hit?)", len(second), len(".fiesta { color: blue; }\n"))
+ }
+ if tag := resp.Header.Get("Etag"); tag == "" || tag == firstTag {
+ t.Errorf("second Etag = %q, first %q; want a new one", tag, firstTag)
+ }
+ if _, hit := e.cache.GetFor(fiestaKey, siteRequest()); hit {
+ t.Errorf("the shared cache holds %v", fiestaKey)
+ }
+}
+
+func TestStaticIgnoresASeededSharedCacheEntry(t *testing.T) {
+ e, srv, _ := headersEdgeWith(t, fiestaTree())
+ seedSentinel(e)
+ _, body := staticDo(t, srv, "GET", "/1.0.0/fiesta.css", nil)
+ if body != staticHeadersTree()["1.0.0/fiesta.css"] {
+ t.Fatalf("GET served %q, want the file's bytes", body)
+ }
+}
+
+func TestProxiedStaticRouteBypassesTheSharedCache(t *testing.T) {
+ var n atomic.Int32
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "public, max-age=300")
+ w.Header().Set("Content-Type", "text/plain")
+ fmt.Fprintf(w, "backend %d", n.Add(1))
+ }))
+ t.Cleanup(backend.Close)
+
+ reg := openReg(t)
+ addr := strings.TrimPrefix(backend.URL, "http://")
+ if err := reg.Upsert(registry.Route{Host: "site.example.com", Kind: "static", Addr: addr, Status: "ready"}); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes))
+ if err := e.Reload(); err != nil {
+ t.Fatalf("Reload: %v", err)
+ }
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+
+ for i := 1; i <= 2; i++ {
+ if _, body := staticDo(t, srv, "GET", "/1.0.0/fiesta.css", nil); body != fmt.Sprintf("backend %d", i) {
+ t.Fatalf("GET %d = %q, want %q", i, body, fmt.Sprintf("backend %d", i))
+ }
+ }
+ if got := n.Load(); got != 2 {
+ t.Errorf("backend counted %d requests, want 2", got)
+ }
+ if _, hit := e.cache.GetFor(fiestaKey, siteRequest()); hit {
+ t.Errorf("the shared cache holds %v", fiestaKey)
+ }
+
+ seedSentinel(e)
+ if _, body := staticDo(t, srv, "GET", "/1.0.0/fiesta.css", nil); body != "backend 3" {
+ t.Fatalf("GET after seeding = %q, want %q", body, "backend 3")
+ }
+}
+
+// siteRequest is a GET of /1.0.0/fiesta.css as staticDo's arrives at the
+// edge: Host site.example.com, nothing a stored variant could vary on.
+func siteRequest() *http.Request {
+ return httptest.NewRequest("GET", "http://site.example.com/1.0.0/fiesta.css", nil)
+}
+
+// seedSentinel stores a fresh entry for fiestaKey that no tree holds.
+func seedSentinel(e *Edge) {
+ e.cache.Put(fiestaKey, "", &CachedResponse{
+ StatusCode: 200,
+ Header: http.Header{"Cache-Control": {"max-age=300"}},
+ Body: []byte("sentinel"),
+ StoredAt: time.Now(),
+ TTL: time.Minute,
+ })
+}
diff --git a/internal/edge/testdata/static-headers-golden.json b/internal/edge/testdata/static-headers-golden.json
new file mode 100644
index 000000000..b3634c50e
--- /dev/null
+++ b/internal/edge/testdata/static-headers-golden.json
@@ -0,0 +1,165 @@
+{
+ "200": {
+ "status": 200,
+ "header": {
+ "Accept-Ranges": [
+ "bytes"
+ ],
+ "Cache-Control": [
+ "no-cache"
+ ],
+ "Content-Length": [
+ "1536"
+ ],
+ "Content-Type": [
+ "text/css; charset=utf-8"
+ ],
+ "Etag": [
+ "W/\"9219ce153461a243baf14213cbffe250\""
+ ],
+ "X-Carlos-Version": [
+ "v1"
+ ]
+ }
+ },
+ "206": {
+ "status": 206,
+ "header": {
+ "Accept-Ranges": [
+ "bytes"
+ ],
+ "Cache-Control": [
+ "no-cache"
+ ],
+ "Content-Length": [
+ "4"
+ ],
+ "Content-Range": [
+ "bytes 0-3/1536"
+ ],
+ "Content-Type": [
+ "text/css; charset=utf-8"
+ ],
+ "Etag": [
+ "W/\"9219ce153461a243baf14213cbffe250\""
+ ],
+ "X-Carlos-Version": [
+ "v1"
+ ]
+ }
+ },
+ "301": {
+ "status": 301,
+ "header": {
+ "Cache-Control": [
+ "no-cache"
+ ],
+ "Content-Length": [
+ "0"
+ ],
+ "Location": [
+ "./1.0.0/"
+ ],
+ "X-Carlos-Version": [
+ "v1"
+ ]
+ }
+ },
+ "304": {
+ "status": 304,
+ "header": {
+ "Cache-Control": [
+ "no-cache"
+ ],
+ "Etag": [
+ "W/\"9219ce153461a243baf14213cbffe250\""
+ ],
+ "X-Carlos-Version": [
+ "v1"
+ ]
+ }
+ },
+ "404": {
+ "status": 404,
+ "header": {
+ "Cache-Control": [
+ "no-cache"
+ ],
+ "Content-Length": [
+ "19"
+ ],
+ "Content-Type": [
+ "text/plain; charset=utf-8"
+ ],
+ "X-Carlos-Version": [
+ "v1"
+ ],
+ "X-Content-Type-Options": [
+ "nosniff"
+ ]
+ }
+ },
+ "412": {
+ "status": 412,
+ "header": {
+ "Cache-Control": [
+ "no-cache"
+ ],
+ "Content-Length": [
+ "0"
+ ],
+ "Content-Type": [
+ "text/css; charset=utf-8"
+ ],
+ "Etag": [
+ "W/\"9219ce153461a243baf14213cbffe250\""
+ ],
+ "X-Carlos-Version": [
+ "v1"
+ ]
+ }
+ },
+ "416": {
+ "status": 416,
+ "header": {
+ "Content-Length": [
+ "33"
+ ],
+ "Content-Range": [
+ "bytes */1536"
+ ],
+ "Content-Type": [
+ "text/plain; charset=utf-8"
+ ],
+ "X-Carlos-Version": [
+ "v1"
+ ],
+ "X-Content-Type-Options": [
+ "nosniff"
+ ]
+ }
+ },
+ "HEAD": {
+ "status": 200,
+ "header": {
+ "Accept-Ranges": [
+ "bytes"
+ ],
+ "Cache-Control": [
+ "no-cache"
+ ],
+ "Content-Length": [
+ "1536"
+ ],
+ "Content-Type": [
+ "text/css; charset=utf-8"
+ ],
+ "Etag": [
+ "W/\"9219ce153461a243baf14213cbffe250\""
+ ],
+ "X-Carlos-Version": [
+ "v1"
+ ]
+ }
+ }
+}