static-headers
Squashed from static-headers into main.
27 files changed,
+2,659
−82
docs/site/cli.md+50 −0docs/superpowers/notes/census-proposal-static-headers.md+29 −0docs/superpowers/notes/census-static-headers-claims.md+7 −0docs/superpowers/plans/2026-10-29-static-headers.md+128 −0docs/superpowers/reviews/ASTRA-CENSUS-static-headers.md+10 −0docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-R1.md+23 −0docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-R2.md+36 −0docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-branch-R1.md+9 −0docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-plan-R1.md+65 −0docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-plan-R2.md+22 −0docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-R1.md+80 −0docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-R2.md+96 −0docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-branch-R1.md+73 −0docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-plan-R1.md+57 −0docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-plan-R2.md+68 −0docs/superpowers/specs/2026-10-29-static-headers-design.md+333 −0internal/edge/edge.go+16 −4internal/edge/headers.go+311 −0internal/edge/headers_test.go+250 −0internal/edge/headerwriter.go+121 −0internal/edge/redirects.go+88 −66internal/edge/static.go+60 −12internal/edge/static_headers_golden_test.go+188 −0internal/edge/static_headers_test.go+359 −0internal/edge/testdata/static-headers-golden.json+165 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-static-headers.tsv+14 −0
CI passed — run details
diff --git a/docs/site/cli.md b/docs/site/cli.md| index 602e1b723..7554e1071 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -427,6 +427,56 @@ Each page then has one address, and relative links in the page resolve |
| against its own folder. If the site's `_redirects` rules name that path, or |
| redirect its slash form, the folder is served at the path as asked instead. |
| +#### Response headers for a static site |
| + |
| +Put a file named `_headers` at the top of the site directory to set response |
| +headers on the paths you choose. It uses the format Netlify and Cloudflare |
| +Pages use: a path on a line of its own, then the headers for it, each on an |
| +indented line below it. |
| + |
| +```text |
| +# Released versions never change. |
| +/1.0.0/* |
| + Cache-Control: public, max-age=31536000, immutable |
| + Access-Control-Allow-Origin: * |
| + |
| +# The latest 1.x moves with each release. |
| +/1/* |
| + Cache-Control: public, max-age=300 |
| + Access-Control-Allow-Origin: * |
| +``` |
| + |
| +`Access-Control-Allow-Origin: *` lets pages on other sites fetch these |
| +files, load them as JavaScript modules and pin them with integrity hashes. A |
| +plain stylesheet or script tag works without it. |
| + |
| +- A path works as a `_redirects` source does. `:name` matches one segment, a |
| + `*` at the end matches the rest of the path, and a URL with a host applies |
| + only to requests for that host. |
| +- Rules match the address the browser asked for, before any `_redirects` |
| + rewrite. If `/1/*` is rewritten to `/1.0.0/:splat`, a request for |
| + `/1/site.css` gets the headers for `/1/*`. |
| +- Every rule that matches applies. When two set the same header, the one |
| + lower in the file wins, so put general rules first and specific ones after |
| + them. |
| +- Headers are sent with a file served normally, including its 304 and range |
| + responses. Redirects, not-found pages and errors don't get them. |
| +- A `Cache-Control` rule replaces the `no-cache` every file gets by default. |
| + |
| +These headers can be set: |
| + |
| +| Header | Values | |
| +| --- | --- | |
| +| `Cache-Control` | any list of directives, such as `public, max-age=300` | |
| +| `Access-Control-Allow-Origin` | `*` | |
| +| `Access-Control-Expose-Headers` | a list of header names | |
| +| `Cross-Origin-Resource-Policy` | `same-origin`, `same-site` or `cross-origin` | |
| +| `Timing-Allow-Origin` | `*` | |
| + |
| +`carlos ship` and `carlos deploy` refuse a `_headers` file with a line they |
| +cannot use, and name the line. Any other header is refused too. A file can |
| +have up to 100 paths. The edge does not serve the `_headers` file itself. |
| + |
| #### Two builds at once |
| When a new build reaches an awake instance, it starts beside the old one, |
diff --git a/docs/superpowers/notes/census-proposal-static-headers.md b/docs/superpowers/notes/census-proposal-static-headers.md| new file mode 100644 |
| index 000000000..24e1fff3d |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-static-headers.md |
| @@ -0,0 +1,29 @@ |
| +# Census approval: static-headers |
| + |
| +Ruling `census-ruling-static-headers`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/edge/static.go` `PackDir` | body | unchanged (2) | also parses the root _headers file it has already read (the same ReadFile as every packed file) with parseHeaders, pure and in-memory, and refuses the pack when a line does not parse, exactly as it does for _redirects; no read added | |
| +| `internal/edge/static.go` `staticSite.serveFile` | body | unchanged (2) | takes the in-memory _headers lookup result (extra) and, on the 200 branch only, wraps the writer in headerWriter, which sets those header values on 200/206/304 at status time; the same Open and open-file Stat of the same resolved file; no read added, no root decision | |
| +| `internal/edge/static.go` `staticSite.serveTree` | body | unchanged (2) | computes the in-memory _headers lookup once on the cleaned request path and host and passes it to serveFile; the _headers file itself is never answered (found excludes it, as _redirects); the same index-aware Stat lookups inside the extracted tree; no read added | |
| +| `internal/edge/edge.go` `Edge.ServeHTTP` | sites | +registry:Kind, +whole:Route | the shared response cache is no longer looked up or filled for a static-kind route: one more read of the route row the edge already resolved (up.route.Kind == "static") in the cacheable expression; a refusal only, nothing new opened or followed | |
| + |
| +Envelopes re-pinned: `internal/edge`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/edge/static.go` `PackDir`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-static-redirects;identity=the carlos CLI (carlos ship and carlos deploy --kind static, on the member's own machine);basis=also parses the root _redirects file it has already read (the same ReadFile) and refuses the pack when a line does not parse; no read added, offsets unchanged |
| +- `internal/edge/static.go` `staticSite.serveFile`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input; serveTree's former Open and open-file Stat of the file serveTree resolved inside the extracted, digest-verified tree, unchanged, plus a non-200 branch that copies the same open file under a _redirects 404 status; no root decision |
| +- `internal/edge/static.go` `staticSite.serveTree`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=the same index-aware Stat lookup inside the extracted tree, now run at most twice (the request path, then once for a _redirects rewrite destination cleaned rooted inside the same tree); the Open moves to serveFile; the _redirects file itself is never answered; no root decision;rev3=census-ruling-edge-protection-2;basis=consults the edge protection matcher (internal/edgeguard, pure and in-memory) on the request path (probe tier, only when no file and no _redirects rule names it) and on a rewrite target (hard tier, only when the file is there), and may answer the guard's 404 block page through guardDecide before a redirect or the rewritten file; the _redirects lookup gains an in-memory names check; the same index-aware Stat lookups inside the extracted tree, unchanged; no read added;rev3=census-ruling-static-dir-slash;basis=A directory requested without its trailing slash now answers a 301 to a relative "./<base>/" (query kept) instead of serving its index.html, unless the request was rewritten, the path ends in "/", a _redirects rule names the path, or the rules would redirect its slash form (redirectsSlashForm, the existing in-memory resolve with exists=true). It opens and stats exactly the files it did before; the new branch only writes a Location header and a status, from the request path and the rules it already parsed. |
| +- `internal/edge/edge.go` `Edge.ServeHTTP`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with the import gate checked after the door's scope and a gated row left out of the response cache; serving only;rev3=census-ruling-edge-request-records;basis=one more call in the observer defer, observeRecords(up.route, ...), passing on the route the defer already holds; no new kind of read;rev3=census-ruling-design-edge-rate-limit-358;basis=calls rateAdmit twice, and an admitted request holds a slot on both paths: on the upgrade path before the activator or proxy (the handshake holds its slot through slotWriter, given back at the first final answer or at the reverse proxy's hijack on a 101, so an open WebSocket is not counted; released by a defer), and on the ordinary path after the response-cache check and before the activator and proxy (an admitted request holds a slot through slotWriter, released by a defer); a refusal is a 429 written there and returns; the upgrade path's comment now names slotWriter as its one wrapper; one comment on the door mark reworded; read sites unchanged (22: main's 21 plus edge-request-records' observeRecords pass of the route), offsets moved; no read added;rev3=census-ruling-plans-4c-box-throttle;basis=calls planThrottleAdmit before the response cache, and on an upgrade trackUpgrade then planUpgradeAdmit (plans 4c, Astra findings 1 and 2); the new reads live in those units (plans-4c-units decision). The same read sites here.;rev3=census-ruling-plans-4d-lapse;basis=calls planDisabledAdmit right after the import gate, passing the final upstream's route and the request host; a turned-off route gets the fixed disabled page before the meter, gate, cache and activator (plans 4d). The new read lives in that unit (plans-4d-units decision); one more whole-row pass here.;rev3=census-ruling-edge-protection-2;basis=runs the guard, a pure in-memory matcher on r.URL.Path and RawQuery (internal/edgeguard), once per request after the meter and observer defer and before the password gate, the upgrade branch, the cache and the activator, for a request that is not a door call, a backhauled door hop or a tunnel delivery; a matched block answers a 404 itself through guardDecide; the two new sites are one expression, up.route.Kind == "static" (a static route this box serves checks only the hard tier here and leaves the probe tier to serveTree), a read of the route row the edge already resolved; no new kind of read;rev3=census-ruling-edge-asset-cache-3;basis=the asset cache's three hooks (asset cache plan 3): the request's reserved asset headers are deleted at entry (the fill assertion kept only beside a verified hop); on the exact-remote and lookup-miss branches the far catch (serveAssetFar) is tried before backhaulTo and backhaul; after the observer defer and main's hard and probe checks, a verified hop with a valid fill assertion is answered by serveAssetFillForHop; after the upgrade branch and before gzip and the shared cache, the local catch (serveAssetLocal); the observer defer skips only the usage meter for an acknowledged home fill (out.unbilled); the new reads live in the new units of the edge-asset-cache-3-decisions overlay; the same route row and read sites (25); no read added;rev3=census-ruling-regional-domains-447;basis=#447 Task 5: straight after lookupUpstreamPath it calls regionalGate (regional.go), which for an entry built from a regional_domains row answers 503 to a hop or a deny entry before any arm that can leave the box (the exact-home backhaul, the far asset catch, the door dial, the miss backhaul), and lets a star match through only to the exact-home arm when ExactHome names another box for that distinct exact name; after the exact-home arm a regional deny entry the arm did not answer is refused (regionalRefuse, 503); refusals only, on the route map the edge already holds; read sites unchanged (25) |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/edge/static.go:staticSite.loadHeaders`: reads +file:ReadFile; written legacy, accepted-legacy, frozen |
| + |
| +Seal: `9df7f5aca9a502966c9643b7062829c1c25bfbd86fa20e92d764d66f676d2cd6` → `94b8ccf921f64be24a4773f72d55a8e24ceba3acfb40eefe3b56af6f5b008138`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-static-headers.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/notes/census-static-headers-claims.md b/docs/superpowers/notes/census-static-headers-claims.md| new file mode 100644 |
| index 000000000..9279c9b0e |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-static-headers-claims.md |
| @@ -0,0 +1,7 @@ |
| +# CLAIMS for the root-read census, branch static-headers (#195 item 2, #450). |
| +# Format (AGENTS.md "The census"): <file>:<unit><TAB><what changed>. Lines starting with # are ignored. |
| +internal/edge/static.go:PackDir also parses the root _headers file it has already read (the same ReadFile as every packed file) with parseHeaders, pure and in-memory, and refuses the pack when a line does not parse, exactly as it does for _redirects; no read added |
| +internal/edge/static.go:staticSite.serveFile takes the in-memory _headers lookup result (extra) and, on the 200 branch only, wraps the writer in headerWriter, which sets those header values on 200/206/304 at status time; the same Open and open-file Stat of the same resolved file; no read added, no root decision |
| +internal/edge/static.go:staticSite.serveTree computes the in-memory _headers lookup once on the cleaned request path and host and passes it to serveFile; the _headers file itself is never answered (found excludes it, as _redirects); the same index-aware Stat lookups inside the extracted tree; no read added |
| +internal/edge/edge.go:Edge.ServeHTTP the shared response cache is no longer looked up or filled for a static-kind route: one more read of the route row the edge already resolved (up.route.Kind == "static") in the cacheable expression; a refusal only, nothing new opened or followed |
| +internal/edge/static.go:staticSite.loadHeaders new: reads the _headers file at the root of the extracted, digest-verified tree once per version swap (ReadFile of filepath.Join(dir, headersFile), dir from the signed pointer and manifest digest as loadRedirects uses), parses it in memory; a missing file is no rules, a read or parse error is logged; the same shape as loadRedirects |
diff --git a/docs/superpowers/plans/2026-10-29-static-headers.md b/docs/superpowers/plans/2026-10-29-static-headers.md| new file mode 100644 |
| index 000000000..a3c3f6127 |
| --- /dev/null |
| +++ b/docs/superpowers/plans/2026-10-29-static-headers.md |
| @@ -0,0 +1,128 @@ |
| +# Static `_headers` Implementation Plan |
| + |
| +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. |
| + |
| +**Goal:** A static site sets `Cache-Control` and a short list of cross-origin headers by path with a `_headers` file at the root of its tree. |
| + |
| +**Architecture:** A new `internal/edge/headers.go` parses `_headers` with the path-pattern parser and matcher factored out of `redirects.go`. `PackDir` refuses a bad file at ship. The edge loads the rules once per version swap into `servedTree`. `serveTree` looks them up on the pre-rewrite path, and `serveFile` applies them through a status-time writer for 200/206/304 only. `Edge.ServeHTTP` takes static routes out of the shared response cache. |
| + |
| +**Tech Stack:** Go 1.26, `net/http`, the existing `internal/edge` test fixtures. |
| + |
| +**Plan rev 3** (Astra plan R1 NOT READY: 2 P1, 4 P2, all applied, marked *plan R1-n*; plan R2 READY AFTER FIXES, its one P2 applied as *plan R2-1*. Plan review closed.) |
| + |
| +**Spec:** `docs/superpowers/specs/2026-10-29-static-headers-design.md` (rev 4, review closed). Read it first; section numbers below are its. |
| + |
| +## Global Constraints |
| + |
| +- File name `_headers`, at the tree root. The edge never serves it (404). |
| +- Allowed headers, v1, exactly: `Cache-Control` (comma-separated `token` or `token=value` directives), `Access-Control-Allow-Origin` (`*` only), `Access-Control-Expose-Headers` (comma-separated header names), `Cross-Origin-Resource-Policy` (`same-origin`, `same-site`, `cross-origin`), `Timing-Allow-Origin` (`*`). Every other name is refused at ship with "not supported yet". |
| +- Limits: 100 path lines, 2,048 characters a line, 256 KiB a file. |
| +- A path pattern is exactly a `_redirects` source: same parser, same matcher, same refusals. |
| +- Match on the cleaned request path and `requestHost(r.Host)` before any `_redirects` rewrite. |
| +- Several matching rules: the last one in the file wins per header. No comma joining. |
| +- Applied at status time, only on 200, 206 and 304 from `serveFile`'s 200 branch. A matching `Cache-Control` replaces `no-cache`. Every other status is header-for-header what it is today. |
| +- The status-time writer owns a private header map (AGENTS.md), syncs down wholesale before forwarding the status, does not implement `io.ReaderFrom`, implements `Flush` (implicit 200 through the hook first) and `Unwrap`. |
| +- `cacheable` in `Edge.ServeHTTP` gains `up.route.Kind != "static"`. |
| +- A tree with no `_headers` file: every response header unchanged. |
| +- Tests locally: only the touched packages, with `-run` (`go test ./internal/edge/ -run 'X|Y' -count=1`). CI runs the full gate. Never `make test` locally. |
| +- Go: leave `GOCACHE` at its default. Scratch under `$TMPDIR`. |
| +- Copy: docs prose goes through the copy-review skill before it lands. No em dashes. Error fragments are out of copy review. |
| +- Commits end with the session's `Co-Authored-By` line. Each task closes its amadan task (983-990 on branch `static-headers`). |
| + |
| +## Review Focus |
| + |
| +1. A `_headers` file saved with CRLF line endings or a BOM (Windows editors). Expected: parsed as LF, as `_redirects` is. Test in Task 1. |
| +2. A header line indented with a tab, an indented `# note` line between header lines, or a trailing `# note` after a value. Expected: tab indents count; the indented comment line is ignored; the trailing `#` is part of the value, so none of the five validators accepts it and ship refuses the line rather than silently cutting it. Test in Task 1. |
| +3. A directory URL: `/1.0.0/` serving `1.0.0/index.html`, and `/1.0.0` without the slash (a 301 to `./1.0.0/`, which must carry no `_headers` headers). Test in Task 2. |
| +4. A `Range` request on an immutable file (`206`), and a `HEAD`. Expected: same headers as the 200. Test in Task 2. |
| +5. A compressed 200 (`Accept-Encoding: gzip`) through the real edge. Expected: the `_headers` values survive the gzip wrapper, and `Vary: Accept-Encoding` is still added. Test in Task 2. |
| + |
| +--- |
| + |
| +### Task 1: `_headers` parser, shared path patterns, and the ship refusal |
| + |
| +**Files:** |
| +- Create: `internal/edge/headers.go`, `internal/edge/headers_test.go` |
| +- Modify: `internal/edge/redirects.go` (factor the source half of `parseRedirectLine` and `redirectRule.match` out), `internal/edge/static.go` (`PackDir`) |
| + |
| +**Interfaces:** |
| +- Produces, in `redirects.go`: |
| + - `type pathPattern struct { host string; segs []string; splat bool }`; `redirectRule` embeds it in place of its own `host`, `segs`, `splat`. |
| + - `func parsePattern(field string) (pathPattern, error)`: the source parsing now inside `parseRedirectLine`, with the same error strings (they quote `field`). `parseRedirectLine` calls it. |
| + - `func (pp *pathPattern) match(host string, reqSegs []string) (map[string]string, bool)`: today's `redirectRule.match` body. |
| + - `func pathSegs(p string) []string`: `nil` for `"/"`, else `strings.Split(p[1:], "/")`; `resolve` and `names` use it. |
| +- Produces, in `headers.go`: |
| + - `const headersFile = "_headers"`; `headersMaxBytes = 256 << 10`, `headersMaxRules = 100`, `headersMaxLine = 2048`. |
| + - `type headerRule struct { line int; pathPattern; set http.Header }` |
| + - `type headerRules struct { rules []headerRule }` |
| + - `func parseHeaders(data []byte) (*headerRules, error)`: usable rules plus an `errors.Join` naming each bad line as `line N: ...`. A bad path line drops its header lines too (spec 3.4). |
| + - `func (hs *headerRules) lookup(host, p string) http.Header`: nil receiver or no match returns nil. Otherwise a fresh map, each matching rule's headers `Set` in file order (last wins). |
| + |
| +- [ ] **Step 1: Factor `pathPattern` out of `redirects.go`, before any new test exists** (plan R1-1: Go compiles every test file in the package, so this check must run while the package has none that name `parseHeaders`). No behaviour change. Run `go test ./internal/edge/ -run 'Redirect|SPAFallback|DirectorySlash|StaticWithoutRedirects' -count=1`. Expected: PASS, unchanged. Commit: `edge: factor the _redirects source pattern out for reuse`. |
| +- [ ] **Step 2: Write the failing tests** in `headers_test.go`: |
| + - `TestParseHeadersAcceptsTheSupportedForms`: the spec section 2 Fiesta file plus a host-URL path line, a tab-indented header line, a lowercase name (`cache-control: no-store`), CRLF line endings and a leading BOM. Assert 3 rules, `rules[0].set.Get("Cache-Control") == "public, max-age=31536000, immutable"`, and the lowercase name stored as `Cache-Control`. |
| + - `TestParseHeadersRefusesWhatItCannotServe`, table of input → substring of the error: `Set-Cookie: a=b` → `not supported yet`; `X-Carlos-Version: x` → `not supported yet`; `Access-Control-Allow-Origin: https://a.example` → `*`; `Cross-Origin-Resource-Policy: anywhere` → `cross-origin`; `Cache-Control: max-age=1, ,` → `Cache-Control`; a header line before any path line → `before a path`; a path line with no header lines → `no headers`; `/a/*/b` path → `* must be the last segment` (the shared parser's message); `! Cache-Control` → `not supported`; a value with a control byte → `value`; a line with no colon → `Name: value`. |
| + - `TestParseHeadersKeepsTheGoodLinesAroundABadOne`: a bad path line's header lines are not attached to the rule above it (`rules[0].set` has exactly its own header). |
| + - `TestParseHeadersLimits`: 101 path lines → `more than 100`; a 2,049-character line → `longer than 2048`; 256 KiB + 1 → `the limit is`. |
| + - `TestHeaderLookupLastRuleWins`: `/*` with `Access-Control-Allow-Origin: *` and `Cache-Control: no-store`, then `/1.0.0/*` with `Cache-Control: public, max-age=31536000, immutable`. `lookup("h", "/1.0.0/a.css")` has both headers, with the immutable value. `lookup("h", "/x")` has `no-store`. `(*headerRules)(nil).lookup` is nil. |
| + - `TestParseHeadersComments`: an indented ` # note` line between two header lines is ignored (the rule has both headers); ` Cache-Control: max-age=60 # note` is refused with an error naming `Cache-Control`. |
| + - `TestPackDirRefusesABadHeadersFile`, table-driven, shaped like `TestPackDirRefusesABadRedirectsFile` (`redirects_test.go:111`). One case per class (plan R1-5): unsupported header (`Set-Cookie: a=b`), bad value (`Access-Control-Allow-Origin: https://a.example`), header line before any path line, path line with no header lines, bad path (`/a/*/b`), 101 path lines, a 2,049-character line, a 256 KiB + 1 file. Each error names `_headers`, and `line` for the per-line cases or `limit` / `more than 100` for the size cases. A good file packs. |
| +- [ ] **Step 3: Run them and see them fail.** `go test ./internal/edge/ -run 'ParseHeaders|HeaderLookup|PackDirRefusesABadHeaders' -count=1`. Expected: build failure, `parseHeaders` undefined. |
| +- [ ] **Step 4: Implement `headers.go`.** Syntax as spec 3.1 (column 0 = path line; leading space or tab = header line split at the first `:`; blank and `#`-first lines skipped). One validator per allowed header, chosen by canonical name; an unknown name is `header %q is not supported yet`. Add the `_headers` branch to `PackDir` beside the `_redirects` one, same wording shape. |
| +- [ ] **Step 5: Run Step 3's command and Step 1's.** Expected: PASS. |
| +- [ ] **Step 6: Commit.** `git add internal/edge/headers.go internal/edge/headers_test.go internal/edge/static.go && git commit -m "edge: parse _headers for static sites; ship refuses a bad one (#195, #450)"`. Set amadan task 986 Done. |
| + |
| +### Task 2: The edge serves `_headers`, and static routes leave the shared cache |
| + |
| +**Files:** |
| +- Modify: `internal/edge/static.go` (`staticSite`, `servedTree`, `currentDir`, `served`, `serveTree`, `serveFile`), `internal/edge/edge.go` (the `cacheable` computation in `ServeHTTP`, and `maybeStore`'s doc comment) |
| + |
| +One task, not two (plan R1-2): with `_headers` giving a static file a positive `max-age`, the shared cache stores it and replays a 200 to a revalidation, so the 304 and 206 tests cannot pass until the cache exclusion is in. |
| +- Create: `internal/edge/headerwriter.go`; tests in `internal/edge/static_headers_test.go` |
| + |
| +**Interfaces:** |
| +- Consumes: `parseHeaders`, `(*headerRules).lookup`, `headersFile` (Task 1). |
| +- Produces: |
| + - `staticSite.headers *headerRules` and `servedTree.headers *headerRules`, set in `currentDir` beside `redirects` by `func (s *staticSite) loadHeaders(dir, version string) *headerRules`, the same shape as `loadRedirects`. |
| + - `serveFile(fp, p string, fi os.FileInfo, status int, extra http.Header, w http.ResponseWriter, r *http.Request)`: `extra` is the lookup result, nil for none. |
| + - `type headerWriter struct { http.ResponseWriter; hdr, extra http.Header; wroteHdr bool }` and `func newHeaderWriter(w http.ResponseWriter, extra http.Header) *headerWriter` (`hdr` = `w.Header().Clone()`). Methods: `Header()` returns `hdr`; `finish()` copies keys added to `hdr` after the status (trailers) down to the writer below, as `gzipWriter.syncTrailers` does (plan R1-3), called by `serveFile` in a `defer` once the writer exists; `WriteHeader(status)`: 1xx syncs and forwards without latching; on the first final status, if 200, 206 or 304, `Set` each `extra` key into `hdr`; then sync down wholesale (as `gzipWriter.syncHeader`) and forward. `Write` calls `WriteHeader(200)` first if needed, then forwards. `Flush` does the same implicit 200, then flushes below if it is an `http.Flusher`. `Unwrap() http.ResponseWriter`. No `ReadFrom`. |
| + |
| +- [ ] **Step 1: Write the failing tests** in `static_headers_test.go`. Build the fixture through the real edge, as `TestEdgeServesStaticRouteWhenEnabled` does (`static_test.go:225`: `openReg`, `New`, `EnableStatic`, `Reload`), with `e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes))` on. Ship `1.0.0/fiesta.css` (larger than `minCompressSize`, so the compressor takes it), `1.0.0/index.html`, `index.html`, a `_redirects` of `/1/* /1.0.0/:splat 200` and the spec section 2 `_headers`. Name it `headersEdge(t, files map[string]string) (srv *httptest.Server, treeDir string)`, where `treeDir` is the extracted tree: the `cacheDir` given to `EnableStatic`, then `release.RouteAccount(rt)`, the app, and `siteDirOf(t, store, app, version)`. |
| + - `TestStaticHeadersFiestaFile`: `GET /1.0.0/fiesta.css` → 200, `Cache-Control: public, max-age=31536000, immutable`, `Access-Control-Allow-Origin: *`, an `Etag`. `GET /1/fiesta.css` → 200, the same bytes, `Cache-Control: public, max-age=300`. `GET /index.html`'s page `/` → `Cache-Control: no-cache`, no `Access-Control-Allow-Origin`. |
| + - `TestStaticHeadersRideTheRevalidationRangeAndHead`: with the 200's `Etag` as `If-None-Match` → 304 with the immutable `Cache-Control` and `*`. `Range: bytes=0-3` → 206 with both. `HEAD` → both. |
| + - `TestStaticHeadersStayOffErrorsAndRedirects`, each under `/1.0.0/` and each asserting `Cache-Control: no-cache` or absent exactly as on `main` and no `Access-Control-Allow-Origin`: `If-Match: "nope"` → 412; `Range: bytes=999999-` → 416; `/1.0.0/missing.css` → 404; `/1.0.0` → 301; `/1.0.0/index.html` → 301. |
| + - `TestStaticHeadersDirectoryIndex`: `GET /1.0.0/` → 200 from `1.0.0/index.html` with the immutable headers. |
| + - `TestStaticHeadersSurviveCompression`: `GET /1.0.0/fiesta.css` with `Accept-Encoding: gzip` and a body over the compressor's minimum → `Content-Encoding: gzip`, `Vary: Accept-Encoding`, and both `_headers` values. |
| + - `TestStaticHeadersFileIsNotServed`: `GET /_headers` → 404. |
| + - `TestStaticWithoutHeadersIsUnchanged`: the same tree with no `_headers`. For `/1.0.0/fiesta.css` (200, 304, 206, HEAD, 412, 416), `/missing` (404) and `/1.0.0` (301), the full response header set minus `Date` equals a golden captured on `main` before this task's code change. This test lives in its own file, `internal/edge/static_headers_golden_test.go`, with its own fixture (the real edge, no `_headers`) and a `-update-headers-golden` flag, so it compiles before any of this task's code exists. The golden is `internal/edge/testdata/static-headers-golden.json`. |
| + - `TestHeaderWriterKeepsItsOwnMap`: unit test on `newHeaderWriter` over an `httptest.ResponseRecorder`. A `Header().Set` before `WriteHeader` does not appear on the recorder's map until `WriteHeader`. A `Header().Del` of a key the recorder had is gone after `WriteHeader(200)`. `extra` is applied on 200, 206 and 304, not on 412. A `Write` without `WriteHeader` applies `extra`. `Flush` before any write applies `extra`. The writer does not satisfy `io.ReaderFrom`. A trailer declared with `Trailer: X-T` and set on `Header()` after `WriteHeader(200)` reaches the recorder after `finish()`. |
| + - `TestStaticWithMaxAgeIsNeverStoredInTheSharedCache`: `GET /1.0.0/fiesta.css` twice; between them, replace `treeDir/1.0.0/fiesta.css` on disk with other bytes (write a new file and rename it over, so the tag cache sees a new file). Assert the second answer has the new bytes and a new `Etag`. Then assert the exact key (`CacheKey{Host: "site.example.com", Method: "GET", Path: "/1.0.0/fiesta.css"}`) is absent: `e.cache.GetFor(key, req)` reports no hit (store bypass, plan R1-4). |
| + - `TestStaticIgnoresASeededSharedCacheEntry`: `e.cache.Put(key, "", &CachedResponse{StatusCode: 200, Header: http.Header{"Cache-Control": {"max-age=300"}}, Body: []byte("sentinel"), StoredAt: time.Now(), TTL: time.Minute})`, then `GET` the same URL: the answer is the file's bytes, not `sentinel` (lookup bypass, plan R1-4). |
| + - `TestProxiedStaticRouteBypassesTheSharedCache`: a backend `httptest.Server` answering `Cache-Control: public, max-age=300` with a counter in its body; register `registry.Route{Host: "site.example.com", Kind: "static", Addr: <backend host:port>, Status: "ready"}` (it takes the address arm of `Reload`'s switch, ahead of `case t.Kind == "static"`); shared cache on. Two GETs: the backend counted 2 and the key is absent. Then seed a sentinel as above: the next GET returns the backend's body. |
| +- [ ] **Step 2: Capture the golden on the unchanged code.** With only `static_headers_golden_test.go` written (move `static_headers_test.go` aside under `$TMPDIR` for this one run), `go test ./internal/edge/ -run TestStaticWithoutHeadersIsUnchanged -update-headers-golden -count=1`. Put `static_headers_test.go` back, then run the rest and see them fail: `go test ./internal/edge/ -run 'StaticHeaders|HeaderWriter' -count=1`. Expected: build failure (`newHeaderWriter` undefined). |
| +- [ ] **Step 3: Implement `headerwriter.go`.** |
| +- [ ] **Step 4: Wire it in `static.go`.** Load in `currentDir` beside `loadRedirects`. In `serveTree`, compute `extra := tree.headers.lookup(requestHost(r.Host), p)` once, right after `p` is first cleaned and before the loop. Extend `found` to exclude `"/"+headersFile` as it excludes `_redirects`. Pass `extra` to `serveFile`. In `serveFile`, only in the `status == http.StatusOK` branch, after `os.Open` succeeds, `if extra != nil { hw := newHeaderWriter(w, extra); defer hw.finish(); w = hw }`. The non-200 branch (a `_redirects` 404 page) never gets it. |
| +- [ ] **Step 5: Run the new tests.** `go test ./internal/edge/ -run 'StaticHeaders|HeaderWriter|NeverStoredInTheSharedCache|SeededSharedCache|ProxiedStaticRoute' -count=1`. Expected: the header tests pass where no shared cache is involved; the revalidation, range and the three cache tests FAIL on stored hits. That is the evidence the exclusion is needed. |
| +- [ ] **Step 6: Add `&& up.route.Kind != "static"` to `cacheable`** in `Edge.ServeHTTP`, with a comment naming spec 4.4's four reasons in one line each, and add static to `maybeStore`'s "One refusal is NOT made here" paragraph. |
| +- [ ] **Step 7: Run the combined gate.** `go test ./internal/edge/ -run 'StaticHeaders|HeaderWriter|StaticWithoutHeaders|NeverStoredInTheSharedCache|SeededSharedCache|ProxiedStaticRoute|Static|Redirect|SPAFallback|DirectorySlash|TagCache|PackDir|Cache' -count=1`. Expected: PASS. |
| +- [ ] **Step 8: Commit.** `git add internal/edge/headerwriter.go internal/edge/static.go internal/edge/edge.go internal/edge/static_headers_test.go internal/edge/static_headers_golden_test.go internal/edge/testdata/static-headers-golden.json && git commit -m "edge: static sites serve _headers on 200/206/304 by request path; static routes leave the shared cache (#195, #450)"`. Set amadan task 987 Done. |
| +- [ ] **Step 9: Per-task review.** Cache headers, a response writer and the shared cache: its own Astra review (AGENTS.md stopping rule 3), briefed from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`, round 1 of 3, diff `<Task 1 tip>..HEAD`. |
| + |
| +### Task 3: Docs |
| + |
| +**Files:** |
| +- Modify: `docs/site/cli.md` (a `#### Response headers for a static site` section after the "Redirects for a static site" section, which ends before `#### Two builds at once`) |
| + |
| +- [ ] **Step 1: Draft the section** in `$TMPDIR`, not in the file: what the file is for, Fiesta's example from spec section 2 with neutral paths, the five headers and their allowed values, last-rule-wins and why, the request-path rule with the `/1/*` rewrite example, which responses carry them (and that 404s and redirects do not), the limits, that ship refuses a bad file and names the line, and that the edge does not serve `_headers`. Neutral examples only (no tenant names). |
| +- [ ] **Step 2: Copy review.** Invoke the copy-review skill on every human sentence in the draft. Apply Paul's edits verbatim. |
| +- [ ] **Step 3: Write the approved text into `docs/site/cli.md`** and run `go test ./internal/docsite/ -count=1`. Expected: PASS (headings and links resolve). |
| +- [ ] **Step 4: Commit.** `git add docs/site/cli.md && git commit -m "docs: _headers for static sites"`. Set amadan task 988 Done. |
| + |
| +### Task 4: Census, whole-branch review, merge |
| + |
| +- [ ] **Step 1: Push and read CI.** `git push origin static-headers` (sandbox off for the push). Read the amadan run. |
| +- [ ] **Step 2: Census.** If `TestPlan14RootReadCensus` fails: `make census-card`; write `docs/superpowers/notes/census-static-headers-claims.md` (`<file>:<unit><TAB><what changed>` per unit); `make census-propose NAME=static-headers CLAIMS=docs/superpowers/notes/census-static-headers-claims.md`; brief Astra with the card and `git diff origin/main...HEAD` for the named files; record the verdict, reviewer and tip on #280. The independent reviewer decides every census class, decisions included (AGENTS.md, "The census"; memory: never ask Paul for census rulings); a rejected claim is a finding for the author to fix within the review budget. (plan R2-1) |
| +- [ ] **Step 3: Whole-branch Astra review,** round 1 of 3, diff `origin/main...HEAD`, brief from the template. Stop at the first round with no P1; apply that round's P2s. |
| +- [ ] **Step 4: Final push and green tip** (plan R1-6). Commit the census overlay, card and claims and every review fix; `git push origin static-headers`; update the branch description (`amadan branch describe`); wait for the amadan CI run on that exact full SHA to be green. That SHA is the `-expect` value. |
| +- [ ] **Step 5: Merge, on Paul's go.** `amadan branch merge carlos/platform static-headers -squash -expect <tip>` with the full commit message (what, reviews, census, "Not released"). Never a bare `amadan branch merge`. Set amadan task 989 Done. |
| +- [ ] **Step 6: Tell the requesters.** Reply on #195 and #450: merged, not released; it reaches sites with the next release roll (dev, then flagship). Task 990 stays Started until the roll. |
diff --git a/docs/superpowers/reviews/ASTRA-CENSUS-static-headers.md b/docs/superpowers/reviews/ASTRA-CENSUS-static-headers.md| new file mode 100644 |
| index 000000000..e725b89ae |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-CENSUS-static-headers.md |
| @@ -0,0 +1,10 @@ |
| +Reviewed `ecf2dbee7ab1768851945ded35723d8477205916` against `origin/main`. For every item below, the diff settles both questions: no new root authority over tenant-, app-, or agent-controlled inputs, and no weakening of the recorded safeguards. |
| + |
| +- **APPROVE — `PackDir`:** parses bytes already read and adds a refusal for invalid headers; file selection is unchanged. [static.go:114](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/static.go:114) |
| +- **APPROVE — `staticSite.serveFile`:** retains the same file open and stat; the private writer applies headers only on 200/206/304. [static.go:635](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/static.go:635), [headerwriter.go:71](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/headerwriter.go:71) |
| +- **APPROVE — `staticSite.serveTree`:** header matching stays in memory; rooted path resolution and guard checks remain intact, and `_headers` becomes unservable. [static.go:504](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/static.go:504), [static.go:528](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/static.go:528) |
| +- **APPROVE — `Edge.ServeHTTP`:** the additional route-kind check only excludes static responses from shared-cache lookup and storage; existing admission gates remain. [edge.go:2083](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/edge.go:2083) |
| +- **APPROVE — `staticSite.loadHeaders`:** the new read targets fixed `_headers` inside the verified extraction directory; its caller runs as `carlos`, and parsed values confer no root authority. The `legacy / accepted-legacy` disposition fits. [static.go:279](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/static.go:279), [static.go:314](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/static.go:314), [carlos-edge.service:28](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/host/units/carlos-edge.service:28) |
| +- **APPROVE — `internal/edge` envelope:** the extracted redirect parser preserves validation and matching; the header allowlist excludes platform-owned fields, and writer changes affect response headers only. [redirects.go:199](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/redirects.go:199), [headers.go:63](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/headers.go:63), [headerwriter.go:38](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/headerwriter.go:38) |
| + |
| +CENSUS VERDICT: APPROVE ALL |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-R1.md b/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-R1.md| new file mode 100644 |
| index 000000000..78f94fc59 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-R1.md |
| @@ -0,0 +1,23 @@ |
| +1. **P1 — Section 4.3: a 412 retains `immutable`.** |
| + |
| + The design [sets headers before `ServeContent`](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/docs/superpowers/specs/2026-10-29-static-headers-design.md:185) and relies on its error handling. However, Go 1.26.10’s [`checkPreconditions`](/home/paulca/.local/go-dist/src/net/http/fs.go:652) writes 412 directly, without clearing headers. |
| + |
| + **Failure scenario:** request an existing `/1.0.0/fiesta.css` with `If-Match: "not-the-current-tag"`. The proposed implementation returns 412 with `Cache-Control: public, max-age=31536000, immutable`, despite serving no file bytes. This meets the brief’s explicit P1 criterion. Separately, [`serveError`](/home/paulca/.local/go-dist/src/net/http/fs.go:193) removes Cache-Control on a 416 but retains the four allowed cross-origin headers, contradicting the stated response scope. |
| + |
| + **Fix:** apply `_headers` overrides when the final status is known, only for 200, 206 and 304 from the successful-file branch. Preserve existing error behavior and the no-`_headers` behavior. Add production-wired tests for failing `If-Match`, unsatisfiable ranges, successful ranges, 304 and HEAD. |
| + |
| + **Fault family:** response-status isolation — file caching policy must not label an error response immutable. |
| + |
| +2. **P2 — Section 4.4: the blanket “no static response is stored today” claim is incorrect.** |
| + |
| + [`Reload`](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/edge.go:805) selects tunnel and fleet proxies before checking `Kind == "static"`; socket and address proxies also precede the [static handler](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/edge.go:891). Those responses never receive `staticSite.ServeHTTP`’s default `no-cache`. The current [cache eligibility check](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/edge.go:2072) admits these routes, and [`maybeStore`](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/edge.go:2184) can store their responses. |
| + |
| + **Failure scenario:** a ready static-kind route with a tunnel backend returns a cacheable 200 with `max-age=300`. Today subsequent requests can hit the shared cache; the proposed exclusion makes every request reach the backend, even without `_headers`. |
| + |
| + **Fix:** retain the approved static-kind exclusion, but qualify the no-op claim to responses produced by the local static-tree handler. Document the broader cache exclusion for proxied static-kind routes and test both lookup and storage bypass on that path. |
| + |
| + **Fault family:** compatibility accounting — route kind does not establish which handler produced the response. |
| + |
| +Reviewed the requested commit against the cited code and installed Go source. No files changed; no test suites run. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-R2.md b/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-R2.md| new file mode 100644 |
| index 000000000..06e07581a |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-R2.md |
| @@ -0,0 +1,36 @@ |
| +R1-1 (P1): **Resolved.** Applying overrides at status time excludes 412 and 416 while preserving their existing headers. |
| +R1-2 (P2): **Partly resolved.** The proxied-route exception and tests are added, but §4.4 still opens with the incorrect blanket claim. |
| + |
| +1. **P2 — §4.3: the proposed writer violates the required header-map ownership rule.** |
| + |
| + The [design:199](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/docs/superpowers/specs/2026-10-29-static-headers-design.md:199) explicitly modifies the shared header map. [AGENTS.md:443](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/AGENTS.md:443) requires a header-editing wrapper to own its map; [compress.go:169](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/compress.go:169) explains the separation. |
| + |
| + **Failure scenario:** a builder follows §4.3 literally and implements a wrapper that fails this repository requirement. The status restriction itself fixes the original leak; I found no new wire-level corruption from these five overrides. |
| + |
| + **Fix:** specify a private map initialized from the underlying headers. Let `ServeContent` edit it, apply overrides only for 200/206/304, then synchronize it downward—including deletions—before forwarding the status. Preserve the existing compressor and meter order. |
| + |
| + **Fault family:** response-writer header ownership. |
| + |
| +2. **P2 — §4.3: `ResponseController` unwrapping does not preserve `io.ReaderFrom`.** |
| + |
| + The [design:201](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/docs/superpowers/specs/2026-10-29-static-headers-design.md:201) says unwrapping is sufficient for both optional interfaces. Go’s [responsecontroller.go:26](/home/paulca/.local/go-dist/src/net/http/responsecontroller.go:26) provides no `ReaderFrom` operation; [io.go:414](/home/paulca/.local/go-dist/src/io/io.go:414) checks that interface directly. |
| + |
| + **Failure scenario:** wrapping a writer that implements `ReaderFrom` with an `Unwrap`-only wrapper hides that interface from `io.Copy`. Unwrapping also does not make a direct `http.Flusher` assertion succeed. |
| + |
| + **Fix:** explicitly omit `ReaderFrom` and let copying pass through `Write`, matching [gzipWriter](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/compress.go:178) and [countingWriter](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/usagemeter.go:98). Specify flush forwarding separately, ensuring an implicit 200 passes through the status hook before flushing. |
| + |
| + **Fault family:** response-writer interface preservation. |
| + |
| +3. **P2 — §4.4: finish the R1-2 qualification.** |
| + |
| + The [opening paragraph:217](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/docs/superpowers/specs/2026-10-29-static-headers-design.md:217) still says no static response is stored today. Tunnel selection precedes the static handler at [edge.go:805](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/edge.go:805), and current [cache eligibility:2072](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/edge.go:2072) admits static-kind routes. |
| + |
| + **Failure scenario:** a static-kind tunnel backend returns `max-age=300`; its response can currently be stored, contradicting that paragraph despite the correction below it. |
| + |
| + **Fix:** limit the opening claim to responses produced by the local static-tree handler. Retain the documented proxy behavior change and bypass tests. |
| + |
| + **Fault family:** compatibility accounting—route kind does not identify the producing handler. |
| + |
| +No P1 remains. Fix these P2s without reopening review. Reviewed commit `45a7e0533446cf9b94111b09ce2dedada1908fd1` against the specified base and Go 1.26.10 source. No files changed; no test suites run. |
| + |
| +**READY AFTER FIXES** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-branch-R1.md b/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-branch-R1.md| new file mode 100644 |
| index 000000000..06e00f02f |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-branch-R1.md |
| @@ -0,0 +1,9 @@ |
| +- **P1 — Census update missing.** [static.go:314](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/static.go:314) adds `staticSite.loadHeaders` with an `os.ReadFile`, but this branch contains no census overlay or chain update. The [committed edge fingerprint](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/provision/testdata/plan14-root-reads-static-dir-slash.tsv:5) still matches the base (`b11d75a4…`); independently recomputing it for this tip gives `8cce0717…`. [TestPlan14RootReadCensus](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/provision/plan14_root_reads_test.go:700) rejects that mismatch, blocking CI and merge. **Fix:** generate the claims, overlay and approval card; obtain the required independent census approval; commit the update and verify the gate. **Fault family:** census coverage and approval of changes to root-binary source. |
| + |
| +- **P3 — Compression test discards the body.** [static_headers_test.go:160](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/static_headers_test.go:160) checks compression headers but ignores the encoded bytes. A response labelled gzip with corrupted or incorrect content could pass. **Follow-up:** decompress the returned body, check decoding errors, and compare it with the fixture’s CSS. **Fault family:** compression representation fidelity; a test gap, with no runtime defect identified. |
| + |
| +No P2 findings. Leave the writer placement and revised `no-cache` comment unchanged: both accurately implement the approved behavior. |
| + |
| +Formatting and diff checks passed. Focused tests could not start because the read-only sandbox prevented Go from creating its work directory. No files were changed. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-plan-R1.md b/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-plan-R1.md| new file mode 100644 |
| index 000000000..43ebb30c5 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-plan-R1.md |
| @@ -0,0 +1,65 @@ |
| +Reviewed `c9c260afa1f3afeb156825cbbbd3ef22361d0778` against spec rev 4 and the named code at `a8b52609`. No files changed, subagents spawned, or tests run. |
| + |
| +1. **P1 — Task 1, Step 3: the redirect regression command cannot compile.** |
| + |
| + [Steps 1–3](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/docs/superpowers/plans/2026-10-29-static-headers.md:59) create tests referencing `parseHeaders` and `headerRules`, explicitly expect undefined-symbol failures, then require the redirect tests to pass before Step 4 defines those symbols. `-run` selects execution, not compilation: Go compiles all package test files ([Go source:64](/home/paulca/.local/go-dist/src/cmd/go/internal/test/test.go:64)). |
| + |
| + **Failure scenario:** following the steps leaves `headers_test.go` uncompilable during the supposedly passing regression check. |
| + |
| + **Fix:** factor and verify `pathPattern` before adding the new tests, or temporarily move the new test file aside for that check. |
| + |
| + **Fault family:** test checkpoints must have their compilation prerequisites. |
| + |
| +2. **P1 — Task 2, Step 5: revalidation cannot pass until Task 3’s cache exclusion exists.** |
| + |
| + [Task 2:86](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/docs/superpowers/plans/2026-10-29-static-headers.md:86) enables the shared cache and requires a 200 followed by an `If-None-Match` request returning 304. Static routes remain eligible at [edge.go:2072](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/edge.go:2072); their new positive `max-age` permits storage at [edge.go:2191](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/edge.go:2191). A hit replays the stored status and body without checking conditions ([edge.go:2479](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/edge.go:2479)). |
| + |
| + **Failure scenario:** the initial GET stores a 200; revalidation returns that 200, failing Task 2’s required passing gate. A subsequent range request can likewise receive the cached 200. |
| + |
| + **Fix:** combine Tasks 2 and 3 into one implementation checkpoint: demonstrate the cache failures after header wiring, apply the exclusion, then run the combined passing gate before committing and reviewing. |
| + |
| + **Fault family:** static conditional responses must reach the file handler. |
| + |
| +3. **P2 — Task 2, Steps 3–4: late-header synchronization is missing.** |
| + |
| + The complete writer interface at [plan:84](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/docs/superpowers/plans/2026-10-29-static-headers.md:84) only synchronizes headers at status time. Neither its implementation step nor its wiring adds finalization. The approved [spec:205](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/docs/superpowers/specs/2026-10-29-static-headers-design.md:205) explicitly requires late additions to propagate, following [gzipWriter.finish:266](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/internal/edge/compress.go:266). |
| + |
| + **Failure scenario:** a declared trailer assigned after `WriteHeader` remains in the private map and never reaches the underlying writer. Current `ServeContent` need not emit trailers for this to be a missing specified contract. |
| + |
| + **Fix:** specify trailer synchronization on completion, wire it with a defer around serving, and add a test assigning a trailer after the final status. |
| + |
| + **Fault family:** response-writer header ownership and late-header propagation. |
| + |
| +4. **P2 — Task 3, Step 1: the tests do not independently prove lookup and storage exclusion.** |
| + |
| + Both tests at [plan:112](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/docs/superpowers/plans/2026-10-29-static-headers.md:112) start empty and infer bypass from two requests reaching the handler. The [spec:263](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/docs/superpowers/specs/2026-10-29-static-headers-design.md:263) requires both lookup and store bypass. |
| + |
| + **Failure scenario:** disabling only storage makes both tests pass while lookup remains active. Conversely, disabling only lookup also passes while responses continue being stored. |
| + |
| + **Fix:** retain these behavioral checks, assert the exact cache key remains absent after serving, and separately seed a live sentinel entry with `Cache.Put` before requesting the same key. Assert the handler’s response wins for both local and proxied static routes. |
| + |
| + **Fault family:** independent enforcement of cache admission and retrieval. |
| + |
| +5. **P2 — Task 1, Step 1: ship-refusal coverage omits required error classes.** |
| + |
| + [Plan:66](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/docs/superpowers/plans/2026-10-29-static-headers.md:66) exercises `PackDir` only with an unsupported header. Other invalid inputs are tested directly against the parser. [Spec:317](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/docs/superpowers/specs/2026-10-29-static-headers-design.md:317) requires ship-level tests for bad values, misplaced header lines, empty blocks, and limits too. |
| + |
| + **Failure scenario:** a regression that mishandles one parser-error category at the packing boundary can pass the planned tests. |
| + |
| + **Fix:** make the `PackDir` test table-driven across the specified categories, checking `_headers` and the applicable line or limit diagnostic. |
| + |
| + **Fault family:** ship-time validation must reject every invalid configuration class. |
| + |
| +6. **P2 — Task 5, Steps 2–4: final changes are never explicitly committed, pushed, and gated.** |
| + |
| + The only push occurs before census generation and review fixes ([plan:132](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/docs/superpowers/plans/2026-10-29-static-headers.md:132)). The plan then proceeds directly to merge. [AGENTS.md:185](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/AGENTS.md:185) requires green CI on the exact tip. |
| + |
| + **Failure scenario:** generated census files or review fixes remain local, while the remote branch still has its earlier failing census run; the merge is refused. |
| + |
| + **Fix:** add an explicit final commit/push step for census and review changes, update the branch description, and wait for green CI on the full SHA supplied to `-expect`. |
| + |
| + **Fault family:** the reviewed, tested, and merged revisions must agree. |
| + |
| +The proposed address-backed static route reaches the intended cache path. The file-replacement technique detects replayed bytes, and the separate golden fixture can compile before Task 2’s implementation. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-plan-R2.md b/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-plan-R2.md| new file mode 100644 |
| index 000000000..23132a01e |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-plan-R2.md |
| @@ -0,0 +1,22 @@ |
| +R1-1 (P1): **Resolved.** Redirect regression checks now precede tests referencing undefined parser symbols. |
| +R1-2 (P1): **Resolved.** Header wiring and cache exclusion share one task and passing gate. |
| +R1-3 (P2): **Resolved.** Writer finalization, deferred trailer synchronization, and a trailer test are specified. |
| +R1-4 (P2): **Resolved.** Exact-key absence checks prove storage bypass; seeded entries independently test lookup bypass. |
| +R1-5 (P2): **Resolved.** `PackDir` tests now cover every required refusal class. |
| +R1-6 (P2): **Resolved.** Census changes and review fixes are explicitly committed, pushed, and gated on the merge SHA. |
| + |
| +1. **P2 — Task 4, Step 2: census decisions are incorrectly escalated to Paul.** |
| + |
| + [Plan:124](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/docs/superpowers/plans/2026-10-29-static-headers.md:124) says “Decisions or escalations go to Paul.” [AGENTS.md:293](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/static-headers/AGENTS.md:293) explicitly assigns every census class to the independent reviewer and says nothing escalates to Paul. |
| + |
| + **Failure scenario:** a disputed census disposition is sent to Paul instead of being approved or rejected by the reviewer, leaving the required review unresolved. |
| + |
| + **Fix:** replace that sentence with an instruction that the independent reviewer decides every class; rejected claims become findings for the author to fix within the existing review budget. |
| + |
| + **Fault family:** census approval authority must remain with the independent reviewer. |
| + |
| +No P1 remains. The separate golden fixture can compile before Task 2’s implementation, and its baseline capture precedes the serving changes. The proposed address-backed static route takes `Reload`’s address arm and reaches the shared-cache check. The proposed pattern extraction can preserve the existing redirect parsing order, diagnostics, and matching behavior. |
| + |
| +Reviewed `d35ae16c09d79c87614e3d7c94be417947a0c3f8` against spec rev 4 and the named code at `a8b52609`. No files changed, subagents spawned, or tests run. Apply the P2 without another plan-review round. |
| + |
| +**READY AFTER FIXES** |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-R1.md b/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-R1.md| new file mode 100644 |
| index 000000000..d08351165 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-R1.md |
| @@ -0,0 +1,80 @@ |
| +# Review brief: static-headers design (`_headers` for static sites), round 1 of 3 |
| + |
| +Repo carlos/platform, branch `static-headers`, commit named in the prompt. |
| +Under review: `docs/superpowers/specs/2026-10-29-static-headers-design.md`. |
| +Authorities: the code on `main` (a8b52609) — `internal/edge/static.go`, |
| +`internal/edge/redirects.go`, `internal/edge/edge.go` (ServeHTTP's |
| +`cacheable`, `maybeStore`, `writeCached`), `internal/edge/cache.go`, |
| +`internal/edge/assetadmit.go`, `internal/edge/assetcatch.go`, |
| +`internal/edge/compress.go`, `internal/console/apiship_assets.go`, |
| +`docs/site/cli.md`. Discussions #195 and #450 on amadan carlos/platform |
| +are the requests (summarised in the spec's section 1). Do not review |
| +against unmerged branches; if this work needs one, say so as a P1 and stop. |
| + |
| +You are an independent reviewer. Read the document, then the code it |
| +names, and check every claim against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Paul approved the approach on 2026-10-29: one feature, a Netlify/Cloudflare |
| + format `_headers` file beside `_redirects`, covering both requests. |
| +- Calls the author made and wants checked, not re-litigated as taste: |
| + last-matching-rule-wins per header (not comma joining); a five-header |
| + allowlist; `Access-Control-Allow-Origin: *` only; no preflight; headers |
| + on 200-served files only; static routes taken out of the shared response |
| + cache. Report one only if it fails a stated goal or breaks something. |
| + |
| +## What to check |
| + |
| +1. Section 4.4: is taking `Kind == "static"` out of `cacheable` truly a |
| + no-op today (no static response ever stored, lookup and store both |
| + gated), and does it miss any path by which a static response with a |
| + `max-age` could still be stored or replayed to another visitor (tunnel / |
| + far-edge / backhaul paths, `viaTunnel` static routes, the hibernation |
| + branch, the asset catch)? |
| +2. Section 4.1: matching the pre-rewrite path. Check `serveTree`'s loop: |
| + is the pre-rewrite `p` and host the right input in every branch (the |
| + folder slash redirect, `/index.html` redirect, forced rules, rewrites |
| + onto a directory)? |
| +3. Section 4.3: which responses carry the headers. Check against |
| + `serveFile` and net/http's `ServeContent` (304, 206, 412, 416, HEAD) in |
| + the repo's Go toolchain. Anything that would carry `immutable` on a |
| + response that is not the file's bytes is a P1. |
| +4. Sections 3.1-3.4: is the syntax unambiguous enough to build, and does |
| + sharing the `_redirects` source parser and matcher work (the matcher's |
| + "/x/* matches /x" and trailing-slash behaviour; host-URL sources)? |
| +5. Compatibility (section 5): any existing behaviour of a site with no |
| + `_headers` that would change, header for header. |
| +6. Anything in the allowlist that could let a site set a header the |
| + platform owns or that changes a cache or security decision elsewhere |
| + in `internal/edge` (the compressor, the guard, analytics, usage |
| + metering). |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| + Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. (The |
| + census, and review of any newly changed security, root, termination |
| + or production-storage behaviour, still check the fix; see AGENTS.md, |
| + "Stopping rules".) |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for |
| + another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not |
| +raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the section, the problem, the |
| +evidence (file:line, verified), the failure scenario, a concrete fix and |
| +the invariant or trust boundary it breaks (that is its fault family). End |
| +with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another |
| + round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. Do not run the full test suites. |
diff --git a/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-R2.md b/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-R2.md| new file mode 100644 |
| index 000000000..edcb88db8 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-R2.md |
| @@ -0,0 +1,96 @@ |
| +# Review brief: static-headers design (`_headers` for static sites), round 2 of 3 |
| + |
| +Repo carlos/platform, branch `static-headers`, commit named in the prompt. |
| +Under review: `docs/superpowers/specs/2026-10-29-static-headers-design.md`. |
| +Authorities: the code on `main` (a8b52609) — `internal/edge/static.go`, |
| +`internal/edge/redirects.go`, `internal/edge/edge.go` (ServeHTTP's |
| +`cacheable`, `maybeStore`, `writeCached`), `internal/edge/cache.go`, |
| +`internal/edge/assetadmit.go`, `internal/edge/assetcatch.go`, |
| +`internal/edge/compress.go`, `internal/console/apiship_assets.go`, |
| +`docs/site/cli.md`. Discussions #195 and #450 on amadan carlos/platform |
| +are the requests (summarised in the spec's section 1). Do not review |
| +against unmerged branches; if this work needs one, say so as a P1 and stop. |
| + |
| +You are an independent reviewer. Read the document, then the code it |
| +names, and check every claim against that code. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- Paul approved the approach on 2026-10-29: one feature, a Netlify/Cloudflare |
| + format `_headers` file beside `_redirects`, covering both requests. |
| +- Calls the author made and wants checked, not re-litigated as taste: |
| + last-matching-rule-wins per header (not comma joining); a five-header |
| + allowlist; `Access-Control-Allow-Origin: *` only; no preflight; headers |
| + on 200-served files only; static routes taken out of the shared response |
| + cache. Report one only if it fails a stated goal or breaks something. |
| + |
| +## What to check |
| + |
| +1. Section 4.4: is taking `Kind == "static"` out of `cacheable` truly a |
| + no-op today (no static response ever stored, lookup and store both |
| + gated), and does it miss any path by which a static response with a |
| + `max-age` could still be stored or replayed to another visitor (tunnel / |
| + far-edge / backhaul paths, `viaTunnel` static routes, the hibernation |
| + branch, the asset catch)? |
| +2. Section 4.1: matching the pre-rewrite path. Check `serveTree`'s loop: |
| + is the pre-rewrite `p` and host the right input in every branch (the |
| + folder slash redirect, `/index.html` redirect, forced rules, rewrites |
| + onto a directory)? |
| +3. Section 4.3: which responses carry the headers. Check against |
| + `serveFile` and net/http's `ServeContent` (304, 206, 412, 416, HEAD) in |
| + the repo's Go toolchain. Anything that would carry `immutable` on a |
| + response that is not the file's bytes is a P1. |
| +4. Sections 3.1-3.4: is the syntax unambiguous enough to build, and does |
| + sharing the `_redirects` source parser and matcher work (the matcher's |
| + "/x/* matches /x" and trailing-slash behaviour; host-URL sources)? |
| +5. Compatibility (section 5): any existing behaviour of a site with no |
| + `_headers` that would change, header for header. |
| +6. Anything in the allowlist that could let a site set a header the |
| + platform owns or that changes a cache or security decision elsewhere |
| + in `internal/edge` (the compressor, the guard, analytics, usage |
| + metering). |
| + |
| +## Round 2 |
| + |
| +Earlier rounds: `docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-R1.md` |
| +(round 1: one P1, the 412 carrying `immutable`; one P2, the proxied |
| +static-kind cache claim). The spec is now rev 3 and marks each fix |
| +**(R1-n)**. The round number counts every earlier review of this design. |
| + |
| +First give one line per P1 and P2 from round 1: resolved, partly, or not. |
| +Carry every unresolved or partly resolved finding forward at its current |
| +severity, then add new findings. The verdict covers everything |
| +outstanding, earlier rounds included. Check especially that the |
| +status-time writer in section 4.3 really leaves every non-200/206/304 |
| +answer header for header as it is today, and that it does not break the |
| +writer stack rules in AGENTS.md ("A ResponseWriter wrapper that edits |
| +headers needs its own header map"). |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| + Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. (The |
| + census, and review of any newly changed security, root, termination |
| + or production-storage behaviour, still check the fix; see AGENTS.md, |
| + "Stopping rules".) |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for |
| + another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not |
| +raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the section, the problem, the |
| +evidence (file:line, verified), the failure scenario, a concrete fix and |
| +the invariant or trust boundary it breaks (that is its fault family). End |
| +with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another |
| + round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. Do not run the full test suites. |
diff --git a/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-branch-R1.md b/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-branch-R1.md| new file mode 100644 |
| index 000000000..e6721e16d |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-branch-R1.md |
| @@ -0,0 +1,73 @@ |
| +# Review brief: static-headers branch (`_headers` for static sites), round 1 of 3 |
| + |
| +Repo carlos/platform, branch `static-headers`, tip named in the prompt. |
| +Under review: the diff `a8b52609...<tip>` (merge base is origin/main a8b52609). |
| +A packaged copy (commit list, stat, full diff with context) is at |
| +`.superpowers/sdd/2026-10-29-static-headers/review-a8b52609..e2a049f1.diff`. |
| +Authorities: `docs/superpowers/specs/2026-10-29-static-headers-design.md` |
| +rev 4 (review closed) and `docs/superpowers/plans/2026-10-29-static-headers.md` |
| +rev 3 (review closed), both on this branch; the code on main. Paul approved |
| +the spec on 2026-10-29 and the docs copy in `docs/site/cli.md` verbatim. |
| + |
| +You are an independent reviewer. Read the spec, then the diff, and check the |
| +code against both. |
| + |
| +## Fixed: do not re-argue |
| + |
| +- The spec's calls (pre-rewrite matching, last-rule-wins, five-header |
| + allowlist, ACAO `*` only, no preflight, 200/206/304 only, static routes out |
| + of the shared cache). Report only code that fails to honour them. |
| +- The docs wording in `docs/site/cli.md` (approved by Paul). Report a doc |
| + sentence only if it is factually wrong about the code. |
| +- Per-task reviews already done: Task 1 (parser) and Task 2 (serving, writer, |
| + cache) each reviewed by Astra, all findings fixed. |
| + |
| +## What to check |
| + |
| +1. Any response that is not the file's bytes under 200/206/304 carrying a |
| + `_headers` header (412, 416, 404, redirects, rewritten 404 pages, guard |
| + refusals, open failures, HEAD of each). That is a P1. |
| +2. `internal/edge/headerwriter.go` against AGENTS.md's ResponseWriter rule and |
| + `gzipWriter`: private map, wholesale sync, trailers, Flush, no ReaderFrom, |
| + interaction with the gzip wrapper above and the usage meter below. |
| +3. The `cacheable` change in `Edge.ServeHTTP`: lookup and store both bypassed |
| + for every static-kind route, and no other route kind affected. |
| +4. The `pathPattern` refactor in `redirects.go`: every `_redirects` behaviour |
| + and error string unchanged. |
| +5. A tree with no `_headers`: any header change on any response (the golden |
| + test's coverage). |
| +6. Deferred items to triage (fix before merge, or leave): the compression |
| + test checks headers only, not the decompressed body |
| + (`static_headers_test.go`); the writer is installed on the 200 path before |
| + the tag lookup rather than exactly "after os.Open"; a reworded `no-cache` |
| + comment in `staticSite.ServeHTTP`. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| + Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. (The |
| + census, and review of any newly changed security, root, termination |
| + or production-storage behaviour, still check the fix; see AGENTS.md, |
| + "Stopping rules".) |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for |
| + another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not |
| +raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the file, the problem, the evidence |
| +(file:line, verified), the failure scenario, a concrete fix and the |
| +invariant or trust boundary it breaks (that is its fault family). End with |
| +exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another |
| + round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. Do not run the full test suites; a focused `go test -run` is fine |
| +if a doubt needs it. |
diff --git a/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-plan-R1.md b/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-plan-R1.md| new file mode 100644 |
| index 000000000..ada9e1f06 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-plan-R1.md |
| @@ -0,0 +1,57 @@ |
| +# Review brief: static-headers implementation plan, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `static-headers`, commit named in the prompt. |
| +Under review: `docs/superpowers/plans/2026-10-29-static-headers.md`. |
| +Authority: the spec beside it, `docs/superpowers/specs/2026-10-29-static-headers-design.md` |
| +rev 4, whose review is CLOSED (Astra R1 and R2 findings files in |
| +`docs/superpowers/reviews/`). Paul approved the spec on 2026-10-29. Check |
| +the plan against the spec and against the code on `main` (a8b52609) it |
| +names: `internal/edge/static.go`, `redirects.go`, `redirects_test.go`, |
| +`static_test.go`, `static_cache_test.go`, `compress.go`, `edge.go`, |
| +`cache.go`, `internal/docsite`. |
| + |
| +You are an independent reviewer. Do not re-review the spec's decisions. |
| + |
| +## What to check |
| + |
| +1. Does every spec requirement have a task, and does any task contradict |
| + the spec (sections 3.1-3.4, 4.1-4.4, 5, 7)? |
| +2. Will the named tests compile and fail for the stated reason before the |
| + code, and pass after? Especially the golden in Task 2 (captured before |
| + the code change), the proxied static route in Task 3 (does a |
| + `Kind: "static"` row with `Addr` really take `Reload`'s address arm and |
| + reach the `cacheable` check?), and the cache-bypass test's way of |
| + proving a hit. |
| +3. Are the interfaces between Tasks 1-3 consistent (names, signatures)? |
| +4. Does the `pathPattern` factoring keep every existing `_redirects` error |
| + string and behaviour (`redirects_test.go`)? |
| +5. Any step a builder could not execute as written. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| + Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. (The |
| + census, and review of any newly changed security, root, termination |
| + or production-storage behaviour, still check the fix; see AGENTS.md, |
| + "Stopping rules".) |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for |
| + another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not |
| +raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the task and step, the problem, the |
| +evidence (file:line, verified), the failure scenario, a concrete fix and |
| +the invariant or trust boundary it breaks (that is its fault family). End |
| +with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another |
| + round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. Do not run the full test suites. |
diff --git a/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-plan-R2.md b/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-plan-R2.md| new file mode 100644 |
| index 000000000..5018f2fa6 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/ASTRA-REVIEW-BRIEF-static-headers-plan-R2.md |
| @@ -0,0 +1,68 @@ |
| +# Review brief: static-headers implementation plan, round 2 of 3 |
| + |
| +Repo carlos/platform, branch `static-headers`, commit named in the prompt. |
| +Under review: `docs/superpowers/plans/2026-10-29-static-headers.md`. |
| +Authority: the spec beside it, `docs/superpowers/specs/2026-10-29-static-headers-design.md` |
| +rev 4, whose review is CLOSED (Astra R1 and R2 findings files in |
| +`docs/superpowers/reviews/`). Paul approved the spec on 2026-10-29. Check |
| +the plan against the spec and against the code on `main` (a8b52609) it |
| +names: `internal/edge/static.go`, `redirects.go`, `redirects_test.go`, |
| +`static_test.go`, `static_cache_test.go`, `compress.go`, `edge.go`, |
| +`cache.go`, `internal/docsite`. |
| + |
| +You are an independent reviewer. Do not re-review the spec's decisions. |
| + |
| +## What to check |
| + |
| +1. Does every spec requirement have a task, and does any task contradict |
| + the spec (sections 3.1-3.4, 4.1-4.4, 5, 7)? |
| +2. Will the named tests compile and fail for the stated reason before the |
| + code, and pass after? Especially the golden in Task 2 (captured before |
| + the code change), the proxied static route in Task 3 (does a |
| + `Kind: "static"` row with `Addr` really take `Reload`'s address arm and |
| + reach the `cacheable` check?), and the cache-bypass test's way of |
| + proving a hit. |
| +3. Are the interfaces between Tasks 1-3 consistent (names, signatures)? |
| +4. Does the `pathPattern` factoring keep every existing `_redirects` error |
| + string and behaviour (`redirects_test.go`)? |
| +5. Any step a builder could not execute as written. |
| + |
| +## Round 2 |
| + |
| +Earlier rounds: `docs/superpowers/reviews/ASTRA-FINDINGS-static-headers-plan-R1.md` |
| +(2 P1, 4 P2). The plan is now rev 2 and marks each fix *plan R1-n*; Tasks 2 |
| +and 3 were merged into Task 2, so Docs is Task 3 and Census/merge Task 4. |
| + |
| +First give one line per P1 and P2 from round 1: resolved, partly, or not. |
| +Carry every unresolved or partly resolved finding forward at its current |
| +severity, then add new findings. The verdict covers everything |
| +outstanding, earlier rounds included. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| + Blocks merge. |
| +- **P2**: wrong or missing. Fixed without reopening this review. (The |
| + census, and review of any newly changed security, root, termination |
| + or production-storage behaviour, still check the fix; see AGENTS.md, |
| + "Stopping rules".) |
| +- **P3**: clarity or polish. Goes on a follow-up list; never a reason for |
| + another round. |
| + |
| +A P1 states its failure scenario and the evidence (file:line). Do not |
| +raise a P2 to P1 to keep the review open. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3. Each gives the task and step, the problem, the |
| +evidence (file:line, verified), the failure scenario, a concrete fix and |
| +the invariant or trust boundary it breaks (that is its fault family). End |
| +with exactly one verdict: |
| + |
| +- **READY**: no P1 and no P2. |
| +- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another |
| + round. |
| +- **NOT READY**: one or more P1s, listed. |
| + |
| +Do not edit files. Do not spawn Anthropic-model reviewers or subagents of |
| +your own. Do not run the full test suites. |
diff --git a/docs/superpowers/specs/2026-10-29-static-headers-design.md b/docs/superpowers/specs/2026-10-29-static-headers-design.md| new file mode 100644 |
| index 000000000..7aa0c651d |
| --- /dev/null |
| +++ b/docs/superpowers/specs/2026-10-29-static-headers-design.md |
| @@ -0,0 +1,333 @@ |
| +# Static sites: response headers by path (`_headers`) |
| + |
| +Status: draft rev 3, 2026-10-29 (rev 2: builder check, two minor points in 3.4 and 4.3; rev 3: Astra R1, findings marked **(R1-n)**; rev 4: Astra R2 READY AFTER FIXES, its three P2s marked **(R2-n)**. Review closed: no further rounds). Discussions #195 (item 2) and #450. |
| +Branch `static-headers`. Review budget: at most three Astra rounds; the |
| +review stops at the first round with no P1 (AGENTS.md, "Stopping rules"). |
| + |
| +## 1. Why |
| + |
| +A static site (`carlos deploy --kind static`) cannot set a response header. |
| +Since #195 item 1 (merged b58e1275, in v0.23.0) every file the tree serves |
| +carries `Cache-Control: no-cache` and a content `ETag` |
| +(`internal/edge/static.go`, `ServeHTTP` and `serveFile`). That is right for |
| +pages. It is wrong for two kinds of file, and two sites have asked: |
| + |
| +- **Files that never change.** fiesta.rastrillo.org, the CDN for Rastrillo's |
| + Fiesta design system, publishes each release at an exact path |
| + (`/1.0.0/fiesta.css`) that never changes, and floats `/1/*` onto the newest |
| + 1.x with a `_redirects` rewrite (`/1/* /1.0.0/:splat 200`). It wants |
| + `public, max-age=31536000, immutable` on `/1.0.0/*` and a short `max-age` |
| + on `/1/*`. Today every page view on every site that links Fiesta spends a |
| + conditional request per file on bytes that cannot change. Dineraya asked |
| + for the same for fingerprinted assets (#195 item 2). |
| +- **Files read from other origins.** Fiesta's `fetch()` of |
| + `/1/i18n/<lang>.json`, `<script type="module">` and subresource integrity |
| + (`integrity=` plus `crossorigin`) all need `Access-Control-Allow-Origin`. |
| + Nothing in `internal/edge` sets it (#450). Fiesta 1.0.0 ships a `.js` |
| + wrapper per language as a stopgap. |
| + |
| +Neither site is working around the gap, and neither should have to. |
| + |
| +## 2. What we build |
| + |
| +A file named `_headers` at the root of a static site's tree, in the format |
| +Netlify and Cloudflare Pages use, sets response headers by path: |
| + |
| +```text |
| +# 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: * |
| +``` |
| + |
| +One feature answers both discussions: #195 item 2 is a `Cache-Control` rule, |
| +#450 an `Access-Control-Allow-Origin` rule. |
| + |
| +### Goals |
| + |
| +- A site sets `Cache-Control` and a short list of cross-origin headers on the |
| + paths it chooses. |
| +- A site that ships no `_headers` file is served exactly as today, header for |
| + header. |
| +- A mistake is refused when the site is shipped, naming the line, as |
| + `_redirects` mistakes are. |
| + |
| +### Non-goals |
| + |
| +- Headers on backend (instance) apps. An app sets its own. |
| +- CORS preflight (`OPTIONS`) answers. Fiesta's three uses are simple GETs: |
| + `fetch()` with no custom headers, module scripts, and SRI with |
| + `crossorigin="anonymous"`. None sends a preflight. |
| +- Netlify's `! Header` detach lines and Cloudflare's `:placeholder` |
| + substitution in header values. |
| +- Changing `Content-Type`. The ETag is computed over the type |
| + (`tagCache.hash`), so overriding it would need the tag to cover the |
| + override; it waits for an asker. |
| + |
| +### Anti-goals |
| + |
| +- A `_headers` rule must never let one visitor's response reach another |
| + through the edge's shared response cache (section 4.4). |
| +- No header the platform owns (`X-Carlos-*`, `Set-Cookie`, `Content-*`, |
| + hop-by-hop headers, `ETag`, `Location`, `Vary`) can be set. |
| + |
| +## 3. The file |
| + |
| +### 3.1 Syntax |
| + |
| +As Netlify and Cloudflare Pages define it: |
| + |
| +- A line that starts at column 0 is a **path line**: a source pattern, and |
| + nothing else on the line. |
| +- An indented line (one or more spaces or tabs) is a **header line**, |
| + `Name: value`, and belongs to the nearest path line above it. A header |
| + line before any path line is an error. |
| +- A blank line, or a line whose first non-space character is `#`, is |
| + ignored. (`#` inside a header value is part of the value: CSP sources and |
| + `Link` targets can carry one.) |
| +- A path line with no header lines under it is an error: it is almost |
| + certainly an indentation mistake. |
| + |
| +The source pattern is exactly a `_redirects` source (`parseRedirectLine`'s |
| +source half in `internal/edge/redirects.go`): a path, or an http(s) URL whose |
| +host must match the request's; `:name` captures one segment; a final `*` |
| +matches the rest, `""` included, so `/1.0.0/*` also matches `/1.0.0`; |
| +case-sensitive; percent-decoding and dot-segment refusal as there. The |
| +builder factors the source parser and `redirectRule.match` out so both files |
| +share one implementation. |
| + |
| +The name is case-insensitive and stored canonical |
| +(`http.CanonicalHeaderKey`). The value is trimmed, must be non-empty, and |
| +must be visible ASCII and spaces only (no control characters). |
| + |
| +### 3.2 Which headers |
| + |
| +Version 1 allows these, and refuses every other name at ship: |
| + |
| +| Header | Value accepted | |
| +| --- | --- | |
| +| `Cache-Control` | a comma-separated directive list (`token` or `token=value`) | |
| +| `Access-Control-Allow-Origin` | `*` only | |
| +| `Access-Control-Expose-Headers` | a comma-separated list of header names | |
| +| `Cross-Origin-Resource-Policy` | `same-origin`, `same-site` or `cross-origin` | |
| +| `Timing-Allow-Origin` | `*` | |
| + |
| +`Access-Control-Allow-Origin` is `*` only because any other value is either |
| +one fixed origin (rarely what a CDN wants) or a list, which needs the edge to |
| +echo the request's `Origin` and send `Vary: Origin`. `*` also keeps the |
| +response sharable (`assetAdmit`, `internal/edge/assetadmit.go`, already |
| +treats `*` as shareable and anything else as not). `Cross-Origin-Resource-Policy` |
| +and `Timing-Allow-Origin` are on the list because a CDN's users need them: a |
| +page with `Cross-Origin-Embedder-Policy: require-corp` cannot load a |
| +cross-origin file without CORP. Widening the list later is additive. |
| + |
| +The refusal names the header and says it is not supported yet, so the next |
| +asker files a discussion rather than shipping around it. |
| + |
| +### 3.3 Limits |
| + |
| +At most 100 path lines, 2,048 characters a line and 256 KiB a file, as |
| +Cloudflare Pages bounds `_headers`. Unlike `_redirects`, which is scanned only |
| +when no file answers a path, these rules are matched on every file served, |
| +so the count is kept small. |
| + |
| +### 3.4 Where it is checked |
| + |
| +- **Ship.** `PackDir` (`internal/edge/static.go`) parses `_headers` the way it |
| + parses `_redirects` and refuses the tree on any error, naming every bad |
| + line. `carlos ship` and `carlos deploy` both pack through it. |
| +- **Edge.** The edge parses `_headers` once per version swap, beside |
| + `loadRedirects` in `currentDir`, and carries the result in `servedTree` |
| + with the redirect rules, so one request never pairs one version's files |
| + with another's headers. A line it cannot use (only a tree packed by |
| + something else can hold one) is logged and skipped; the rest apply. A path |
| + line it cannot use takes its header lines with it: they are skipped too, |
| + never attached to the path line above. |
| +- The edge never serves the `_headers` file itself: it is configuration, as |
| + `_redirects` is (`serveTree`'s `found`). |
| + |
| +## 4. How it serves |
| + |
| +### 4.1 Matching |
| + |
| +Rules match the **cleaned request path and host**, before any `_redirects` |
| +rewrite: `p` and `requestHost(r.Host)` as `serveTree` holds them on entry. |
| +The headers describe the URL the browser holds. With Fiesta's file, a request |
| +for `/1/fiesta.css` is rewritten to the file at `/1.0.0/fiesta.css` but takes |
| +`/1/*`'s `max-age=300`; matching after the rewrite would give the floating |
| +URL `immutable` and freeze it in browsers for a year. Netlify matches the |
| +same way. |
| + |
| +### 4.2 Several matching rules |
| + |
| +Every rule whose pattern matches applies. When more than one matching rule |
| +names the same header, the **last** one in the file wins, so a site can write |
| +a general rule first and a specific one under it: |
| + |
| +```text |
| +/* |
| + Access-Control-Allow-Origin: * |
| +/1.0.0/* |
| + Cache-Control: public, max-age=31536000, immutable |
| +``` |
| + |
| +Netlify and Cloudflare join repeated values with a comma instead. That turns |
| +`no-cache` plus `max-age=31536000` into a contradiction and `*` plus `*` into |
| +an invalid `Access-Control-Allow-Origin`, so we do not. The docs say so. |
| + |
| +### 4.3 Which responses carry them |
| + |
| +The headers go on every answer that **serves a file's bytes from the |
| +tree**: a 200, a 206 and a 304 (and their `HEAD` forms), including a |
| +`_redirects` 200 rewrite. Nothing else gets them. **(R1-1)** |
| + |
| +They are applied **when the status is written**, not before. `serveFile` |
| +hands `http.ServeContent` a thin writer that, on the first `WriteHeader` |
| +(or the first `Write`, which implies 200), adds the matched headers to the |
| +header map and replaces `Cache-Control` only if the status is 200, 206 or |
| +304, then passes the call down. Every other status leaves the header map |
| +exactly as it would be with no `_headers` file. Setting them earlier is not |
| +enough: net/http's `checkPreconditions` writes a 412 for a failed `If-Match` |
| +straight to the writer with whatever headers are already set (Go 1.26 |
| +`net/http/fs.go`), so `immutable` would ride a response that holds no file, |
| +and `serveError` clears `Cache-Control` on a 416 but would leave the |
| +cross-origin headers. The writer follows the rule in AGENTS.md ("A ResponseWriter wrapper that |
| +edits headers needs its own header map"): it keeps a **private header map**, |
| +cloned from the writer below when it is made, and its `Header()` returns that |
| +map, so `ServeContent`'s own edits (its 304 and error deletions included) land |
| +there. On the status it applies the overrides to the private map if the |
| +status is 200, 206 or 304, then makes the map below match the private one |
| +(additions, changes and deletions), then forwards `WriteHeader`. A header set |
| +after that is synced down the way `gzipWriter` does it |
| +(`internal/edge/compress.go`). The compressor above and the usage meter keep |
| +their order. **(R2-1)** |
| + |
| +It does **not** offer `io.ReaderFrom`: `io.Copy` goes through `Write`, as it |
| +does for `gzipWriter` and `countingWriter` (`internal/edge/usagemeter.go`), |
| +because an `Unwrap` method does not make a type assertion on `ReaderFrom` |
| +succeed. It implements `Flush` itself, writing an implicit 200 through the |
| +status hook first, and offers `Unwrap` for `http.ResponseController`. |
| +**(R2-2)** |
| + |
| +A 304 keeps the headers: net/http drops only `Content-Type`, |
| +`Content-Length` and `Content-Encoding` from it. |
| + |
| +So they do not go on redirects (a `_redirects` 3xx, the folder slash 301, |
| +the `/index.html` 301), on 404s (the tree's own and a `_redirects` 404 page), |
| +on the guard's refusals, on a 412 or 416, or on 400/403/500. A 404 under `/1.0.0/*` marked |
| +`immutable` would pin a typo in every browser for a year. |
| + |
| +A matching `Cache-Control` rule **replaces** the default `no-cache` that |
| +`ServeHTTP` sets. Everything else about the answer is unchanged: the ETag, |
| +`X-Carlos-Version`, compression. |
| + |
| +### 4.4 The edge's shared response cache |
| + |
| +Today no answer from this box's own static-tree handler is stored in the |
| +edge's shared LRU (`e.cache`, `internal/edge/cache.go`): `maybeStore` |
| +(`internal/edge/edge.go`) stores only a response with a positive `max-age`, |
| +and that handler sends `no-cache` on everything. (A proxied static-kind route |
| +is another matter; see below.) **(R2-3)** A `_headers` `max-age` would change that, and the cache is the |
| +wrong place for these files: |
| + |
| +- a hit (`writeCached`) replays the stored 200 with no `Age` and no |
| + conditional handling, so a browser revalidating with `If-None-Match` |
| + would get the whole file instead of a 304, and a browser's freshness would |
| + restart on a copy already up to five minutes old; |
| +- a hit replays the `X-Carlos-Version` frozen at store time, which |
| + `carlos deploy -kind static` reads to know a deploy landed; |
| +- a static deploy does not purge it; |
| +- the tree is on this box's disk already, so a hit saves nothing worth |
| + having. |
| + |
| +So static routes are taken out of the shared cache structurally: the |
| +`cacheable` computation in `Edge.ServeHTTP` gains `up.route.Kind != "static"` |
| +beside its existing `Kind != "status"` refusal, which gates both the lookup |
| +and the store. |
| + |
| +For a static route this box serves from its own tree this changes nothing: |
| +that handler sends `no-cache` on everything, so none of its answers was ever |
| +stored. **(R1-2)** A static-kind route can also be proxied: `Reload` picks a |
| +tunnel, fleet, socket or address proxy ahead of the static handler |
| +(`internal/edge/edge.go`, the `switch` before `case t.Kind == "static"`), and |
| +those answers do not pass through this box's `staticSite.ServeHTTP`. Today one |
| +of them carrying a positive `max-age` could be stored. After this change it |
| +is not, and every request reaches the box or backend behind it. That is |
| +intended: the same four reasons hold for those answers, and where the other |
| +side is another edge's static handler it sends `no-cache` today anyway. Tests |
| +cover lookup and store bypass on a proxied static-kind route as well as a |
| +local one. |
| + |
| +The other edge cache, the declared-asset cache (`assetcatch.go`), is already |
| +closed to static sites: the console refuses an `--assets` block on a static |
| +release (`internal/console/apiship_assets.go`, `apiShipAssetsStatic`). |
| + |
| +### 4.5 Compression |
| + |
| +Unchanged. The compressor (`internal/edge/compress.go`) sits above the |
| +handler, adds `Vary: Accept-Encoding` to what it compresses and honours a |
| +`no-transform` directive, which a site may now set. |
| + |
| +## 5. Compatibility |
| + |
| +- A tree with no `_headers` file: no change, header for header. A guard test |
| + pins it. |
| +- A static-kind route this box proxies (tunnel, fleet, socket, address) no |
| + longer has its answers stored in the shared cache (section 4.4). This is the |
| + one behaviour change for a site that ships no `_headers`. |
| +- A tree already deployed with a file named `_headers` (a site moved from |
| + Netlify, say): after the roll its valid rules apply, its invalid lines are |
| + logged and skipped, and the file is no longer served. That is the format's |
| + meaning; we do not know of such a site. |
| +- No wire or storage shape changes. The file travels inside `site.tar.gz` as |
| + any other file does. |
| + |
| +## 6. Docs |
| + |
| +`docs/site/cli.md` gains "Response headers for a static site" after |
| +"Redirects for a static site": the file, the five headers, last-rule-wins, |
| +which responses carry them, the limits, and what ship refuses. The prose goes |
| +through copy review before it lands. |
| + |
| +## 7. Testing |
| + |
| +Through the real `Edge.ServeHTTP` with a static route, not the handler alone |
| +(the production-wired rule): |
| + |
| +- Fiesta's file: `/1.0.0/fiesta.css` gets the immutable `Cache-Control` and |
| + `*`; `/1/fiesta.css` (rewritten) gets `max-age=300`, not immutable. |
| +- A 304, a 206 and a `HEAD` carry the same headers as the 200. |
| +- A failed `If-Match` (412) and an unsatisfiable range (416) under a matching |
| + pattern carry none of them, and keep the headers they have today. |
| +- A proxied static-kind route (tunnel) is neither looked up nor stored in |
| + `e.cache`. |
| +- A 404 and a redirect under a matching pattern carry none of them, and keep |
| + `no-cache`. |
| +- Last-rule-wins on a repeated header. |
| +- A site with `max-age` is never stored in `e.cache`: a second request |
| + reaches the handler. |
| +- No `_headers`: every header of a 200, 304, 404 and redirect is identical |
| + to the same tree served before the change. |
| +- `/_headers` answers 404. |
| +- `PackDir` refuses each class of bad line and names it: unknown header, |
| + bad value, header line before a path, path line with no headers, limits. |
| + |
| +## 8. Rollout |
| + |
| +No switch. A site gets this when it ships a `_headers` file to a box running |
| +the release that carries it, so the switch-on date is that release's roll |
| +(dev first, then flagship). First users: fiesta.rastrillo.org, then |
| +dineraya.com. The change touches `serveTree` and the `internal/edge` |
| +envelope, so the census needs a ruling before merge, as the folder-slash |
| +change did (a8b52609). |
| + |
| +## 9. Left to the builder |
| + |
| +Names, file layout (a `headers.go` beside `redirects.go` is the obvious |
| +place), how the shared source parser is factored, and the exact refusal |
| +wording (error fragments, outside copy review). |
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/headers.go b/internal/edge/headers.go| new file mode 100644 |
| index 000000000..b94d06f4e |
| --- /dev/null |
| +++ b/internal/edge/headers.go |
| @@ -0,0 +1,311 @@ |
| +// Response headers by path for static sites: a `_headers` file at the root of |
| +// a shipped tree, in the format Netlify introduced and Cloudflare Pages |
| +// adopted. A path line at column 0, then indented "Name: value" lines: |
| +// |
| +// # Exact releases never change. |
| +// /1.0.0/* |
| +// Cache-Control: public, max-age=31536000, immutable |
| +// Access-Control-Allow-Origin: * |
| +// |
| +// The subset served here: |
| +// |
| +// - A path line is a `_redirects` source (parsePattern) and nothing else: a |
| +// path, or an http(s) URL whose host must match the request's, with |
| +// ":name" and a final "*" as there. A header line belongs to the nearest |
| +// path line above it. |
| +// - A blank line, and a line whose first non-space character is "#", are |
| +// ignored. A "#" inside a value is part of the value. |
| +// - Only the headers in headerChecks are accepted, each with the values its |
| +// check allows. Any other name is refused, so a site never ships a header |
| +// the edge would not send, and never one the platform owns. |
| +// - Every matching rule applies, in file order; for a name set twice the |
| +// last rule wins. Values are never joined. |
| +// |
| +// Netlify's "! Name" detach lines and Cloudflare's ":placeholder" values are |
| +// not supported. `carlos ship` refuses a tree whose _headers has a line it |
| +// cannot use (PackDir); a line that still reaches the edge is skipped there. |
| +package edge |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "strings" |
| +) |
| + |
| +// headersFile is the rules file's name at the root of a static tree. The file |
| +// is configuration, not content: the edge never serves it. |
| +const headersFile = "_headers" |
| + |
| +// Limits on one _headers file, as Cloudflare Pages bounds it. Unlike |
| +// _redirects, whose rules are scanned only for paths no file answers, these |
| +// are matched on every file served, so the count is kept small. |
| +const ( |
| + headersMaxBytes = 256 << 10 |
| + headersMaxRules = 100 |
| + headersMaxLine = 2048 |
| +) |
| + |
| +// headerRule is one path line of a _headers file with the headers under it. |
| +type headerRule struct { |
| + line int // 1-based line number of the path line, for logs |
| + pathPattern |
| + set http.Header // canonical name to its one validated value |
| +} |
| + |
| +// headerRules is a parsed _headers file, immutable once built. |
| +type headerRules struct { |
| + rules []headerRule |
| +} |
| + |
| +// headerChecks are the headers a site may set, by canonical name, each with |
| +// the check its value must pass. Widening the list is additive. |
| +var headerChecks = map[string]func(value string) error{ |
| + "Cache-Control": checkCacheControl, |
| + "Access-Control-Allow-Origin": checkWildcard, |
| + "Access-Control-Expose-Headers": checkNameList, |
| + "Cross-Origin-Resource-Policy": checkResourcePolicy, |
| + "Timing-Allow-Origin": checkWildcard, |
| +} |
| + |
| +// parseHeaders parses a _headers file. It returns the rules it could use and |
| +// an error naming every line it could not; callers decide which matters. Ship |
| +// refuses on any error, and the edge serves the usable rules. A path line that |
| +// cannot be used takes its header lines with it, so they never attach to the |
| +// path line above. |
| +func parseHeaders(data []byte) (*headerRules, error) { |
| + if len(data) > headersMaxBytes { |
| + return nil, fmt.Errorf("%s is %d bytes; the limit is %d", headersFile, len(data), headersMaxBytes) |
| + } |
| + hs := &headerRules{} |
| + var errs []error |
| + bad := func(n int, err error) { errs = append(errs, fmt.Errorf("line %d: %v", n, err)) } |
| + |
| + var ( |
| + cur *headerRule // the path line being read; nil before one, or after a bad one |
| + curPath string // cur's text, for the error naming it |
| + seenPath bool // a path line, good or bad, has been read |
| + pathLines int // path lines read, good or bad, against the limit |
| + hadHeader bool // cur has had at least one header line, good or bad |
| + ) |
| + // finish closes the current path line: a rule only if a header survived. |
| + finish := func() { |
| + if cur == nil { |
| + return |
| + } |
| + switch { |
| + case len(cur.set) > 0: |
| + hs.rules = append(hs.rules, *cur) |
| + case !hadHeader: |
| + bad(cur.line, fmt.Errorf("path %q has no headers under it; indent them", curPath)) |
| + } |
| + cur, hadHeader = nil, false |
| + } |
| + |
| + // A byte-order mark is what some editors save at the front; it is not |
| + // part of the first path. |
| + text := strings.TrimPrefix(string(data), "\ufeff") |
| + for i, line := range strings.Split(text, "\n") { |
| + n := i + 1 |
| + line = strings.TrimSuffix(line, "\r") |
| + trimmed := strings.Trim(line, " \t") |
| + // The line limit holds for every line, comments and blanks included. |
| + long := len(line) > headersMaxLine |
| + if trimmed == "" || strings.HasPrefix(trimmed, "#") { |
| + if long { |
| + bad(n, fmt.Errorf("longer than %d characters", headersMaxLine)) |
| + } |
| + continue |
| + } |
| + indented := line[0] == ' ' || line[0] == '\t' |
| + |
| + if !indented { |
| + finish() |
| + seenPath = true |
| + pathLines++ |
| + if long { |
| + bad(n, fmt.Errorf("longer than %d characters", headersMaxLine)) |
| + continue |
| + } |
| + if strings.ContainsAny(trimmed, " \t") { |
| + bad(n, fmt.Errorf("path line %q: want a path and nothing else", trimmed)) |
| + continue |
| + } |
| + if pathLines > headersMaxRules { |
| + // Counted whether or not the earlier lines were usable, so |
| + // the cap is on the file, not on the rules that survived. |
| + bad(n, fmt.Errorf("more than %d path lines", headersMaxRules)) |
| + continue |
| + } |
| + pp, err := parsePattern(trimmed) |
| + if err != nil { |
| + bad(n, err) |
| + continue |
| + } |
| + cur, curPath = &headerRule{line: n, pathPattern: pp, set: http.Header{}}, trimmed |
| + continue |
| + } |
| + |
| + switch { |
| + case !seenPath: |
| + bad(n, errors.New("header line before a path line")) |
| + continue |
| + case cur == nil: |
| + continue // under a path line that was refused |
| + } |
| + hadHeader = true |
| + if long { |
| + bad(n, fmt.Errorf("longer than %d characters", headersMaxLine)) |
| + continue |
| + } |
| + name, value, err := parseHeaderLine(trimmed) |
| + if err != nil { |
| + bad(n, err) |
| + continue |
| + } |
| + cur.set.Set(name, value) |
| + } |
| + finish() |
| + return hs, errors.Join(errs...) |
| +} |
| + |
| +// parseHeaderLine splits and checks one "Name: value" line. It returns the |
| +// canonical name and the trimmed value. |
| +func parseHeaderLine(line string) (name, value string, err error) { |
| + if strings.HasPrefix(line, "!") { |
| + return "", "", fmt.Errorf("%q: removing a header with ! is not supported", line) |
| + } |
| + n, v, ok := strings.Cut(line, ":") |
| + n = strings.Trim(n, " \t") |
| + if !ok || n == "" { |
| + return "", "", fmt.Errorf("%q: want a header line like \"Name: value\"", line) |
| + } |
| + name = http.CanonicalHeaderKey(n) |
| + check, ok := headerChecks[name] |
| + if !ok { |
| + return "", "", fmt.Errorf("header %q is not supported yet", name) |
| + } |
| + value = strings.Trim(v, " \t") |
| + if value == "" { |
| + return "", "", fmt.Errorf("%s: the value is empty", name) |
| + } |
| + for i := 0; i < len(value); i++ { |
| + if value[i] < ' ' || value[i] > '~' { |
| + return "", "", fmt.Errorf("%s: the value may hold only visible ASCII and spaces", name) |
| + } |
| + } |
| + if err := check(value); err != nil { |
| + return "", "", fmt.Errorf("%s: %v", name, err) |
| + } |
| + return name, value, nil |
| +} |
| + |
| +// lookup returns the headers the file sets on a response for host and the |
| +// cleaned path p: every matching rule's headers in file order, so the last |
| +// rule to name a header wins. It returns nil when nothing matches, and for a |
| +// nil set. The result is the caller's to change. |
| +func (hs *headerRules) lookup(host, p string) http.Header { |
| + if hs == nil { |
| + return nil |
| + } |
| + segs := pathSegs(p) |
| + var out http.Header |
| + for i := range hs.rules { |
| + rule := &hs.rules[i] |
| + if _, ok := rule.match(host, segs); !ok { |
| + continue |
| + } |
| + if out == nil { |
| + out = http.Header{} |
| + } |
| + for name := range rule.set { |
| + out.Set(name, rule.set.Get(name)) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// isToken reports whether s is an HTTP token (RFC 9110): one or more of the |
| +// characters a header or directive name may hold. |
| +func isToken(s string) bool { |
| + if s == "" { |
| + return false |
| + } |
| + for i := 0; i < len(s); i++ { |
| + c := s[i] |
| + if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || |
| + strings.IndexByte("!#$%&'*+-.^_`|~", c) >= 0) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// splitOutsideQuotes splits v at the commas that are not inside a quoted |
| +// string, so no-cache="X-One, X-Two" stays one directive. An unterminated |
| +// quote leaves the rest of v in one piece, which the caller then refuses. |
| +func splitOutsideQuotes(v string) []string { |
| + var parts []string |
| + start, quoted := 0, false |
| + for i := 0; i < len(v); i++ { |
| + switch v[i] { |
| + case '"': |
| + quoted = !quoted |
| + case ',': |
| + if !quoted { |
| + parts = append(parts, v[start:i]) |
| + start = i + 1 |
| + } |
| + } |
| + } |
| + return append(parts, v[start:]) |
| +} |
| + |
| +// checkCacheControl: a comma-separated list of directives, each a token or |
| +// "token=value" where the value is a token or a quoted string. |
| +func checkCacheControl(v string) error { |
| + for _, d := range splitOutsideQuotes(v) { |
| + d = strings.Trim(d, " \t") |
| + name, val, hasVal := strings.Cut(d, "=") |
| + if !isToken(name) { |
| + return fmt.Errorf("want a comma-separated list of directives such as \"public, max-age=60\", not %q", v) |
| + } |
| + if !hasVal { |
| + continue |
| + } |
| + quoted := len(val) >= 2 && val[0] == '"' && val[len(val)-1] == '"' && |
| + !strings.ContainsAny(val[1:len(val)-1], `"\`) |
| + if !isToken(val) && !quoted { |
| + return fmt.Errorf("directive %q: want a token or a quoted string after =", d) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// checkWildcard: the value is "*" and nothing else. Any other origin would |
| +// need the edge to echo the request's Origin and send Vary: Origin. |
| +func checkWildcard(v string) error { |
| + if v != "*" { |
| + return fmt.Errorf("want * only, not %q", v) |
| + } |
| + return nil |
| +} |
| + |
| +// checkNameList: a comma-separated list of header names. |
| +func checkNameList(v string) error { |
| + for _, n := range strings.Split(v, ",") { |
| + if !isToken(strings.Trim(n, " \t")) { |
| + return fmt.Errorf("want a comma-separated list of header names, not %q", v) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// checkResourcePolicy: one of the three Cross-Origin-Resource-Policy values. |
| +func checkResourcePolicy(v string) error { |
| + switch v { |
| + case "same-origin", "same-site", "cross-origin": |
| + return nil |
| + } |
| + return fmt.Errorf("want same-origin, same-site or cross-origin, not %q", v) |
| +} |
diff --git a/internal/edge/headers_test.go b/internal/edge/headers_test.go| new file mode 100644 |
| index 000000000..9b2f395ae |
| --- /dev/null |
| +++ b/internal/edge/headers_test.go |
| @@ -0,0 +1,250 @@ |
| +package edge |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestParseHeadersAcceptsTheSupportedForms(t *testing.T) { |
| + file := "\ufeff# Exact releases never change.\r\n" + |
| + "/1.0.0/*\r\n" + |
| + " Cache-Control: public, max-age=31536000, immutable\r\n" + |
| + " Access-Control-Allow-Origin: *\r\n" + |
| + "\r\n" + |
| + "# The floating major moves to each new 1.x.\r\n" + |
| + "/1/*\r\n" + |
| + " Cache-Control: public, max-age=300\r\n" + |
| + " Access-Control-Allow-Origin: *\r\n" + |
| + "https://www.example.com/docs/:page\r\n" + |
| + "\tTiming-Allow-Origin: *\r\n" + |
| + "/lower\r\n" + |
| + " cache-control: no-store\r\n" |
| + hs, err := parseHeaders([]byte(file)) |
| + if err != nil { |
| + t.Fatalf("parseHeaders: %v", err) |
| + } |
| + if len(hs.rules) != 4 { |
| + t.Fatalf("%d rules, want 4", len(hs.rules)) |
| + } |
| + if got := hs.rules[0].set.Get("Cache-Control"); got != "public, max-age=31536000, immutable" { |
| + t.Errorf("rules[0] Cache-Control = %q", got) |
| + } |
| + if got := hs.rules[0].set.Get("Access-Control-Allow-Origin"); got != "*" { |
| + t.Errorf("rules[0] Access-Control-Allow-Origin = %q", got) |
| + } |
| + if hs.rules[2].host != "www.example.com" || hs.rules[2].set.Get("Timing-Allow-Origin") != "*" { |
| + t.Errorf("rules[2] = %+v, want the www.example.com host and a tab-indented header", hs.rules[2]) |
| + } |
| + if _, ok := hs.rules[3].set["Cache-Control"]; !ok || hs.rules[3].set.Get("Cache-Control") != "no-store" { |
| + t.Errorf("rules[3].set = %v, want the lowercase name stored as Cache-Control", hs.rules[3].set) |
| + } |
| +} |
| + |
| +func TestParseHeadersRefusesWhatItCannotServe(t *testing.T) { |
| + for _, tc := range []struct{ name, in, want string }{ |
| + {"cookie", "/a\n Set-Cookie: a=b\n", "not supported yet"}, |
| + {"platform header", "/a\n X-Carlos-Version: x\n", "not supported yet"}, |
| + {"other origin", "/a\n Access-Control-Allow-Origin: https://a.example\n", "*"}, |
| + {"policy", "/a\n Cross-Origin-Resource-Policy: anywhere\n", "cross-origin"}, |
| + {"cache directives", "/a\n Cache-Control: max-age=1, ,\n", "Cache-Control"}, |
| + {"header first", " Cache-Control: no-store\n/a\n Cache-Control: no-store\n", "before a path"}, |
| + {"path alone", "/a\n", "no headers"}, |
| + {"bad path", "/a/*/b\n Cache-Control: no-store\n", "* must be the last segment"}, |
| + {"detach", "/a\n ! Cache-Control\n", "not supported"}, |
| + {"control byte", "/a\n Cache-Control: no-store\x01\n", "value"}, |
| + {"no colon", "/a\n Cache-Control no-store\n", "Name: value"}, |
| + {"empty value", "/a\n Cache-Control:\n", "empty"}, |
| + {"path and more", "/a /b\n Cache-Control: no-store\n", "nothing else"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + _, err := parseHeaders([]byte(tc.in)) |
| + if err == nil || !strings.Contains(err.Error(), tc.want) || !strings.Contains(err.Error(), "line ") { |
| + t.Fatalf("parseHeaders(%q) = %v, want an error naming a line and containing %q", tc.in, err, tc.want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestParseHeadersKeepsTheGoodLinesAroundABadOne(t *testing.T) { |
| + file := "/a\n Cache-Control: no-store\n" + |
| + "/b/*/c\n Access-Control-Allow-Origin: *\n Timing-Allow-Origin: *\n" + |
| + "/d\n Set-Cookie: x=y\n Cache-Control: max-age=60\n" |
| + hs, err := parseHeaders([]byte(file)) |
| + if err == nil || !strings.Contains(err.Error(), "line 3:") || !strings.Contains(err.Error(), "line 7:") { |
| + t.Fatalf("err = %v, want lines 3 and 7 named", err) |
| + } |
| + if len(hs.rules) != 2 { |
| + t.Fatalf("%d rules, want 2", len(hs.rules)) |
| + } |
| + if a := hs.rules[0]; len(a.set) != 1 || a.set.Get("Cache-Control") != "no-store" { |
| + t.Errorf("/a set = %v, want only its own Cache-Control", a.set) |
| + } |
| + if d := hs.rules[1]; len(d.set) != 1 || d.set.Get("Cache-Control") != "max-age=60" { |
| + t.Errorf("/d set = %v, want only the good Cache-Control", d.set) |
| + } |
| +} |
| + |
| +func TestParseHeadersLimits(t *testing.T) { |
| + var b strings.Builder |
| + for range headersMaxRules + 1 { |
| + b.WriteString("/a\n Cache-Control: no-store\n") |
| + } |
| + hs, err := parseHeaders([]byte(b.String())) |
| + if err == nil || !strings.Contains(err.Error(), "more than 100") || len(hs.rules) != headersMaxRules { |
| + t.Errorf("101 path lines: %d rules, err %v; want 100 rules and \"more than 100\"", len(hs.rules), err) |
| + } |
| + |
| + long := "/a\n Cache-Control: no-store" + strings.Repeat("x", headersMaxLine+1-len(" Cache-Control: no-store")) + "\n" |
| + if _, err := parseHeaders([]byte(long)); err == nil || !strings.Contains(err.Error(), "longer than 2048") { |
| + t.Errorf("a 2,049-character line: %v, want \"longer than 2048\"", err) |
| + } |
| + longPath := "/" + strings.Repeat("a", headersMaxLine) + "\n Cache-Control: no-store\n" |
| + if _, err := parseHeaders([]byte(longPath)); err == nil || !strings.Contains(err.Error(), "longer than 2048") { |
| + t.Errorf("a 2,049-character path line: %v, want \"longer than 2048\"", err) |
| + } |
| + |
| + // The line limit holds for comments and blank lines too. |
| + for name, line := range map[string]string{ |
| + "comment": "# " + strings.Repeat("x", headersMaxLine-1), |
| + "blank": strings.Repeat(" ", headersMaxLine+1), |
| + "indented one": " # " + strings.Repeat("x", headersMaxLine-3), |
| + } { |
| + if len(line) != headersMaxLine+1 { |
| + t.Fatalf("%s: test line is %d characters, want %d", name, len(line), headersMaxLine+1) |
| + } |
| + file := "/a\n Cache-Control: no-store\n" + line + "\n" |
| + if _, err := parseHeaders([]byte(file)); err == nil || !strings.Contains(err.Error(), "line 3: longer than 2048") { |
| + t.Errorf("a 2,049-character %s line: %v, want \"line 3: longer than 2048\"", name, err) |
| + } |
| + } |
| + |
| + // The path-line cap counts every path line, usable or not: a valid path |
| + // after 100 refused ones is the 101st and is not an active rule. |
| + b.Reset() |
| + for range headersMaxRules { |
| + b.WriteString("/a/*/b\n Cache-Control: no-store\n") |
| + } |
| + b.WriteString("/late\n Cache-Control: no-store\n") |
| + hs, err = parseHeaders([]byte(b.String())) |
| + if err == nil || !strings.Contains(err.Error(), "line 201: more than 100") || len(hs.rules) != 0 { |
| + t.Errorf("a valid path after 100 refused ones: %d rules, err %v; want no rules and \"line 201: more than 100\"", len(hs.rules), err) |
| + } |
| + b.Reset() |
| + for range headersMaxRules { |
| + b.WriteString("/h\n") |
| + } |
| + b.WriteString("/late\n Cache-Control: no-store\n") |
| + hs, err = parseHeaders([]byte(b.String())) |
| + if err == nil || !strings.Contains(err.Error(), "more than 100") || len(hs.rules) != 0 { |
| + t.Errorf("a valid path after 100 headerless ones: %d rules, err %v; want no rules and \"more than 100\"", len(hs.rules), err) |
| + } |
| + |
| + big := strings.Repeat("# filler\n", headersMaxBytes/len("# filler\n")+1) |
| + if _, err := parseHeaders([]byte(big)); err == nil || !strings.Contains(err.Error(), "the limit is") { |
| + t.Errorf("a file over 256 KiB: %v, want \"the limit is\"", err) |
| + } |
| +} |
| + |
| +func TestHeaderLookupLastRuleWins(t *testing.T) { |
| + hs, err := parseHeaders([]byte("/*\n Access-Control-Allow-Origin: *\n Cache-Control: no-store\n" + |
| + "/1.0.0/*\n Cache-Control: public, max-age=31536000, immutable\n")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got := hs.lookup("h", "/1.0.0/a.css") |
| + if got.Get("Access-Control-Allow-Origin") != "*" || got.Get("Cache-Control") != "public, max-age=31536000, immutable" { |
| + t.Errorf("lookup /1.0.0/a.css = %v, want both headers with the immutable Cache-Control", got) |
| + } |
| + if got := hs.lookup("h", "/x"); got.Get("Cache-Control") != "no-store" { |
| + t.Errorf("lookup /x = %v, want no-store", got) |
| + } |
| + // The result is the caller's: changing it must not change the rules. |
| + hs.lookup("h", "/x").Set("Cache-Control", "changed") |
| + if got := hs.lookup("h", "/x"); got.Get("Cache-Control") != "no-store" { |
| + t.Errorf("lookup after a caller's edit = %v, want no-store", got) |
| + } |
| + if got := (*headerRules)(nil).lookup("h", "/x"); got != nil { |
| + t.Errorf("nil set lookup = %v, want nil", got) |
| + } |
| + only, _ := parseHeaders([]byte("/docs/*\n Cache-Control: no-store\nhttps://other.example/*\n Cache-Control: no-cache\n")) |
| + if got := only.lookup("h", "/x"); got != nil { |
| + t.Errorf("lookup with no match = %v, want nil", got) |
| + } |
| + if got := only.lookup("other.example", "/x"); got.Get("Cache-Control") != "no-cache" { |
| + t.Errorf("lookup on the named host = %v, want no-cache", got) |
| + } |
| +} |
| + |
| +func TestParseHeadersCacheControlQuotes(t *testing.T) { |
| + for _, ok := range []string{ |
| + `no-cache="X-One, X-Two"`, |
| + `private="Set-Cookie", max-age=60`, |
| + `public, no-cache="a,b,c", immutable`, |
| + } { |
| + if _, err := parseHeaders([]byte("/a\n Cache-Control: " + ok + "\n")); err != nil { |
| + t.Errorf("Cache-Control: %s refused: %v", ok, err) |
| + } |
| + } |
| + hs, _ := parseHeaders([]byte("/a\n Cache-Control: no-cache=\"X-One, X-Two\"\n")) |
| + if got := hs.rules[0].set.Get("Cache-Control"); got != `no-cache="X-One, X-Two"` { |
| + t.Errorf("quoted comma stored as %q", got) |
| + } |
| + for _, bad := range []string{ |
| + `no-cache="X-One`, |
| + `no-cache="X-One, X-Two`, |
| + `no-cache=X-One"`, |
| + `no-cache="a"b"`, |
| + `no-cache="a\\b"`, |
| + `no-cache="a", , public`, |
| + `max-age=`, |
| + } { |
| + if _, err := parseHeaders([]byte("/a\n Cache-Control: " + bad + "\n")); err == nil || !strings.Contains(err.Error(), "Cache-Control") { |
| + t.Errorf("Cache-Control: %s = %v, want a Cache-Control refusal", bad, err) |
| + } |
| + } |
| +} |
| + |
| +func TestParseHeadersComments(t *testing.T) { |
| + hs, err := parseHeaders([]byte("/a\n Cache-Control: no-store\n # note\n Timing-Allow-Origin: *\n")) |
| + if err != nil || len(hs.rules) != 1 || len(hs.rules[0].set) != 2 { |
| + t.Fatalf("indented comment: %v, %+v; want one rule with both headers", err, hs) |
| + } |
| + // A "#" in a value is part of the value, which these headers never take. |
| + _, err = parseHeaders([]byte("/a\n Cache-Control: max-age=60 # note\n")) |
| + if err == nil || !strings.Contains(err.Error(), "Cache-Control") { |
| + t.Fatalf("value with a trailing comment: %v, want a Cache-Control refusal", err) |
| + } |
| +} |
| + |
| +func TestPackDirRefusesABadHeadersFile(t *testing.T) { |
| + var many strings.Builder |
| + for range headersMaxRules + 1 { |
| + many.WriteString("/a\n Cache-Control: no-store\n") |
| + } |
| + for _, tc := range []struct{ name, file, want string }{ |
| + {"unsupported header", "/a\n Set-Cookie: a=b\n", "line 2:"}, |
| + {"bad value", "/a\n Access-Control-Allow-Origin: https://a.example\n", "line 2:"}, |
| + {"header before a path", " Cache-Control: no-store\n", "line 1:"}, |
| + {"path with no headers", "/a\n", "line 1:"}, |
| + {"bad path", "/a/*/b\n Cache-Control: no-store\n", "line 1:"}, |
| + {"too many paths", many.String(), "more than 100"}, |
| + {"long line", "/a\n Cache-Control: no-store" + strings.Repeat("x", headersMaxLine) + "\n", "line 2:"}, |
| + {"big file", strings.Repeat("# filler\n", headersMaxBytes/len("# filler\n")+1), "limit"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + _, err := PackDir(writeTree(t, map[string]string{"index.html": "home", "_headers": tc.file})) |
| + if err == nil || !strings.Contains(err.Error(), "_headers") || !strings.Contains(err.Error(), tc.want) { |
| + t.Fatalf("PackDir = %v, want a refusal naming _headers and %q", err, tc.want) |
| + } |
| + }) |
| + } |
| + |
| + good := "/a\n Cache-Control: no-store\n" |
| + if _, err := PackDir(writeTree(t, map[string]string{"index.html": "home", "_headers": good})); err != nil { |
| + t.Fatalf("PackDir with a good _headers: %v", err) |
| + } |
| + // Only the root file is the rules file; one deeper is content. |
| + if _, err := PackDir(writeTree(t, map[string]string{"sub/_headers": "not rules"})); err != nil { |
| + t.Fatalf("PackDir with a nested _headers: %v", err) |
| + } |
| +} |
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/redirects.go b/internal/edge/redirects.go| index 51d5f9b51..1bee36fa4 100644 |
| --- a/internal/edge/redirects.go |
| +++ b/internal/edge/redirects.go |
| @@ -60,12 +60,10 @@ const ( |
| // redirectRule is one parsed line of a _redirects file. |
| type redirectRule struct { |
| - line int // 1-based line number, for logs |
| - host string // lowercased; "" matches any host |
| - segs []string // source path segments; ":name" captures one |
| - splat bool // the source ends in "*" |
| - prefix string // a URL destination's "scheme://host", never substituted |
| - to string // the destination template after prefix |
| + line int // 1-based line number, for logs |
| + pathPattern |
| + prefix string // a URL destination's "scheme://host", never substituted |
| + to string // the destination template after prefix |
| status int |
| force bool // "!": applies even when a file exists at the request path |
| } |
| @@ -153,23 +151,70 @@ func parseRedirectLine(line string) (redirectRule, error) { |
| rule.status = code |
| } |
| - src := fields[0] |
| + pp, err := parsePattern(fields[0]) |
| + if err != nil { |
| + return rule, err |
| + } |
| + rule.pathPattern = pp |
| + |
| + dst := fields[1] |
| + switch { |
| + case strings.HasPrefix(dst, "http://") || strings.HasPrefix(dst, "https://"): |
| + if !isRedirect(rule.status) { |
| + return rule, fmt.Errorf("destination %q: a %d serves a file from this site, so it takes a path, not a URL", dst, rule.status) |
| + } |
| + u, err := url.Parse(dst) |
| + if err != nil || u.Host == "" || u.User != nil { |
| + return rule, fmt.Errorf("destination %q: not a usable URL", dst) |
| + } |
| + i := len(u.Scheme) + len("://") + len(u.Host) |
| + if !strings.EqualFold(dst[:i], u.Scheme+"://"+u.Host) { |
| + return rule, fmt.Errorf("destination %q: not a usable URL", dst) |
| + } |
| + rule.prefix, rule.to = dst[:i], dst[i:] |
| + if rule.to != "" && !strings.ContainsAny(rule.to[:1], "/?#") { |
| + return rule, fmt.Errorf("destination %q: not a usable URL", dst) |
| + } |
| + case strings.HasPrefix(dst, "//") || strings.HasPrefix(dst, "/\\"): |
| + return rule, fmt.Errorf("destination %q: name another host with https://", dst) |
| + case strings.HasPrefix(dst, "/"): |
| + rule.to = dst |
| + default: |
| + return rule, fmt.Errorf("destination %q: want a path starting with / or an http(s) URL", dst) |
| + } |
| + return rule, nil |
| +} |
| + |
| +// pathPattern is the source half of a rule: the request host and path it |
| +// applies to. _redirects sources and _headers path lines share it, so the two |
| +// files read a path the same way. |
| +type pathPattern struct { |
| + host string // lowercased; "" matches any host |
| + segs []string // path segments; ":name" captures one |
| + splat bool // the pattern ends in "*" |
| +} |
| + |
| +// parsePattern parses a source field: a path, or an http(s) URL whose host |
| +// must match the request's. |
| +func parsePattern(field string) (pathPattern, error) { |
| + var pp pathPattern |
| + src := field |
| if strings.HasPrefix(src, "http://") || strings.HasPrefix(src, "https://") { |
| u, err := url.Parse(src) |
| if err != nil || u.Host == "" || u.User != nil || u.Port() != "" || u.RawQuery != "" || u.Fragment != "" { |
| - return rule, fmt.Errorf("source %q: want a URL with only a host and a path", src) |
| + return pp, fmt.Errorf("source %q: want a URL with only a host and a path", src) |
| } |
| - rule.host = serverName(u.Hostname()) // as requestHost normalizes the request's |
| + pp.host = serverName(u.Hostname()) // as requestHost normalizes the request's |
| src = u.Path |
| if src == "" { |
| src = "/" |
| } |
| } |
| if !strings.HasPrefix(src, "/") { |
| - return rule, fmt.Errorf("source %q: want a path starting with / or an http(s) URL", fields[0]) |
| + return pp, fmt.Errorf("source %q: want a path starting with / or an http(s) URL", field) |
| } |
| if strings.ContainsAny(src, "?#") { |
| - return rule, fmt.Errorf("source %q: query strings and fragments are not matched", fields[0]) |
| + return pp, fmt.Errorf("source %q: query strings and fragments are not matched", field) |
| } |
| names := map[string]bool{} |
| trimmed := strings.Trim(src, "/") |
| @@ -177,24 +222,24 @@ func parseRedirectLine(line string) (redirectRule, error) { |
| switch { |
| case seg == "": |
| if trimmed != "" { |
| - return rule, fmt.Errorf("source %q: empty path segment", fields[0]) |
| + return pp, fmt.Errorf("source %q: empty path segment", field) |
| } |
| - case rule.splat: |
| - return rule, fmt.Errorf("source %q: * must be the last segment", fields[0]) |
| + case pp.splat: |
| + return pp, fmt.Errorf("source %q: * must be the last segment", field) |
| case seg == "*": |
| - rule.splat = true |
| + pp.splat = true |
| case strings.Contains(seg, "*"): |
| - return rule, fmt.Errorf("source %q: * must be a whole segment", fields[0]) |
| + return pp, fmt.Errorf("source %q: * must be a whole segment", field) |
| case strings.HasPrefix(seg, ":"): |
| name := seg[1:] |
| if !validPlaceholder(name) || name == "splat" { |
| - return rule, fmt.Errorf("source %q: bad placeholder %q", fields[0], seg) |
| + return pp, fmt.Errorf("source %q: bad placeholder %q", field, seg) |
| } |
| if names[name] { |
| - return rule, fmt.Errorf("source %q: placeholder %q appears twice", fields[0], seg) |
| + return pp, fmt.Errorf("source %q: placeholder %q appears twice", field, seg) |
| } |
| names[name] = true |
| - rule.segs = append(rule.segs, seg) |
| + pp.segs = append(pp.segs, seg) |
| default: |
| // Requests match decoded, as files are found, so a literal |
| // segment is decoded here to meet them: "/caf%C3%A9" matches a |
| @@ -202,44 +247,18 @@ func parseRedirectLine(line string) (redirectRule, error) { |
| // no request path has one inside a segment. |
| dec, err := url.PathUnescape(seg) |
| if err != nil || strings.Contains(dec, "/") { |
| - return rule, fmt.Errorf("source %q: bad percent-encoding in %q", fields[0], seg) |
| + return pp, fmt.Errorf("source %q: bad percent-encoding in %q", field, seg) |
| } |
| if strings.HasPrefix(dec, ":") { |
| - return rule, fmt.Errorf("source %q: %q would read as a placeholder", fields[0], seg) |
| + return pp, fmt.Errorf("source %q: %q would read as a placeholder", field, seg) |
| } |
| if dec == "." || dec == ".." { |
| - return rule, fmt.Errorf("source %q: dot segments never match", fields[0]) |
| + return pp, fmt.Errorf("source %q: dot segments never match", field) |
| } |
| - rule.segs = append(rule.segs, dec) |
| + pp.segs = append(pp.segs, dec) |
| } |
| } |
| - |
| - dst := fields[1] |
| - switch { |
| - case strings.HasPrefix(dst, "http://") || strings.HasPrefix(dst, "https://"): |
| - if !isRedirect(rule.status) { |
| - return rule, fmt.Errorf("destination %q: a %d serves a file from this site, so it takes a path, not a URL", dst, rule.status) |
| - } |
| - u, err := url.Parse(dst) |
| - if err != nil || u.Host == "" || u.User != nil { |
| - return rule, fmt.Errorf("destination %q: not a usable URL", dst) |
| - } |
| - i := len(u.Scheme) + len("://") + len(u.Host) |
| - if !strings.EqualFold(dst[:i], u.Scheme+"://"+u.Host) { |
| - return rule, fmt.Errorf("destination %q: not a usable URL", dst) |
| - } |
| - rule.prefix, rule.to = dst[:i], dst[i:] |
| - if rule.to != "" && !strings.ContainsAny(rule.to[:1], "/?#") { |
| - return rule, fmt.Errorf("destination %q: not a usable URL", dst) |
| - } |
| - case strings.HasPrefix(dst, "//") || strings.HasPrefix(dst, "/\\"): |
| - return rule, fmt.Errorf("destination %q: name another host with https://", dst) |
| - case strings.HasPrefix(dst, "/"): |
| - rule.to = dst |
| - default: |
| - return rule, fmt.Errorf("destination %q: want a path starting with / or an http(s) URL", dst) |
| - } |
| - return rule, nil |
| + return pp, nil |
| } |
| // validPlaceholder: a placeholder name is letters, digits and underscores. |
| @@ -255,17 +274,26 @@ func validPlaceholder(name string) bool { |
| return true |
| } |
| -// match reports whether the rule applies to a request for host whose cleaned |
| -// path splits into reqSegs, and returns what the source captured. |
| -func (rule *redirectRule) match(host string, reqSegs []string) (map[string]string, bool) { |
| - if rule.host != "" && rule.host != host { |
| +// pathSegs splits a cleaned request path into the segments a pattern matches |
| +// against: nil for the root. |
| +func pathSegs(p string) []string { |
| + if p == "/" { |
| + return nil |
| + } |
| + return strings.Split(p[1:], "/") |
| +} |
| + |
| +// match reports whether the pattern applies to a request for host whose |
| +// cleaned path splits into reqSegs, and returns what it captured. |
| +func (pp *pathPattern) match(host string, reqSegs []string) (map[string]string, bool) { |
| + if pp.host != "" && pp.host != host { |
| return nil, false |
| } |
| - if len(reqSegs) < len(rule.segs) || !rule.splat && len(reqSegs) != len(rule.segs) { |
| + if len(reqSegs) < len(pp.segs) || !pp.splat && len(reqSegs) != len(pp.segs) { |
| return nil, false |
| } |
| var caps map[string]string |
| - for i, seg := range rule.segs { |
| + for i, seg := range pp.segs { |
| if strings.HasPrefix(seg, ":") { |
| if caps == nil { |
| caps = map[string]string{} |
| @@ -275,11 +303,11 @@ func (rule *redirectRule) match(host string, reqSegs []string) (map[string]strin |
| return nil, false |
| } |
| } |
| - if rule.splat { |
| + if pp.splat { |
| if caps == nil { |
| caps = map[string]string{} |
| } |
| - caps["splat"] = strings.Join(reqSegs[len(rule.segs):], "/") |
| + caps["splat"] = strings.Join(reqSegs[len(pp.segs):], "/") |
| } |
| return caps, true |
| } |
| @@ -343,10 +371,7 @@ func (rs *redirectRules) resolve(host, p, rawPath, rawQuery string, exists bool) |
| if rs == nil || len(rs.rules) == 0 { |
| return redirectAction{}, false |
| } |
| - var reqSegs []string |
| - if p != "/" { |
| - reqSegs = strings.Split(p[1:], "/") |
| - } |
| + reqSegs := pathSegs(p) |
| for i := range rs.rules { |
| rule := &rs.rules[i] |
| if exists && !rule.force { |
| @@ -419,10 +444,7 @@ func (rs *redirectRules) names(host, p string) bool { |
| if rs == nil { |
| return false |
| } |
| - var reqSegs []string |
| - if p != "/" { |
| - reqSegs = strings.Split(p[1:], "/") |
| - } |
| + reqSegs := pathSegs(p) |
| rules: |
| for i := range rs.rules { |
| rule := &rs.rules[i] |
diff --git a/internal/edge/static.go b/internal/edge/static.go| index 78e276802..f2ff754c4 100644 |
| --- a/internal/edge/static.go |
| +++ b/internal/edge/static.go |
| @@ -107,6 +107,14 @@ func PackDir(dir string) ([]byte, error) { |
| return nil, fmt.Errorf("pack %s: %s: %w", dir, name, err) |
| } |
| } |
| + if name == headersFile { |
| + // Refused here for the same reason: a header the edge cannot |
| + // send is an error the shipper sees, not one that silently |
| + // never arrives. |
| + if _, err := parseHeaders(b); err != nil { |
| + return nil, fmt.Errorf("pack %s: %s: %w", dir, name, err) |
| + } |
| + } |
| } |
| if err := tw.Close(); err != nil { |
| return nil, err |
| @@ -139,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. |
| @@ -191,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. |
| @@ -264,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 |
| @@ -271,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 |
| @@ -294,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 |
| @@ -470,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. |
| @@ -486,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, |
| @@ -570,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 |
| } |
| } |
| @@ -588,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 |
| @@ -626,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..31a506a90 |
| --- /dev/null |
| +++ b/internal/edge/static_headers_golden_test.go |
| @@ -0,0 +1,188 @@ |
| +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", |
| + } |
| +} |
| + |
| +// staticHeadersEdge serves files as a static site through the real edge, |
| +// with the shared response cache on as production runs it. It returns the |
| +// edge, the server, and the directory the tree is extracted into (it exists |
| +// once the first request has been answered). It is the one fixture for the |
| +// golden and the _headers tests, so the two can never drift apart. |
| +func staticHeadersEdge(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 |
| +} |
| + |
| +// 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, _ := staticHeadersEdge(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..18d0a9a6c |
| --- /dev/null |
| +++ b/internal/edge/static_headers_test.go |
| @@ -0,0 +1,359 @@ |
| +package edge |
| + |
| +import ( |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// 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 is staticHeadersEdge for tests that need only the server and |
| +// the extracted tree. |
| +func headersEdge(t *testing.T, files map[string]string) (srv *httptest.Server, treeDir string) { |
| + t.Helper() |
| + _, srv, treeDir = staticHeadersEdge(t, files) |
| + return 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 := staticHeadersEdge(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, _ := staticHeadersEdge(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" |
| + ] |
| + } |
| + } |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 850568f73..8d944141b 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -33,3 +33,4 @@ plan14-root-reads-regional-domains-447.tsv 1de834976c615fed28567ca0a9ae7526eaa35 |
| plan14-root-reads-static-dir-slash.tsv fb7cd756f7c3eb2dc019c8fd55fea5475e2df7ee3305fbc693ae669f257f374f |
| plan14-root-reads-named-unit-delivery-114.tsv d92c9d40eb2a9e66c859e2fe6df3af10a1b9d3a83b1d717ec928cb432eebb1aa |
| plan14-root-reads-fleet-secrets-key.tsv 9df7f5aca9a502966c9643b7062829c1c25bfbd86fa20e92d764d66f676d2cd6 |
| +plan14-root-reads-static-headers.tsv 94b8ccf921f64be24a4773f72d55a8e24ceba3acfb40eefe3b56af6f5b008138 |
diff --git a/internal/provision/testdata/plan14-root-reads-static-headers.tsv b/internal/provision/testdata/plan14-root-reads-static-headers.tsv| new file mode 100644 |
| index 000000000..6b78d95a0 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-static-headers.tsv |
| @@ -0,0 +1,14 @@ |
| +# Census overlay static-headers, written by census-propose (#369). census-ruling-static-headers, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-static-headers.md. |
| +# 3 body, 1 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy 5a672c4cd5b701c3cac51b4d86ac789e4e7288c490ec378d2a3498ad2faf0446 internal/edge/static.go PackDir legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-static-redirects;identity=the carlos CLI (carlos ship and carlos deploy --kind static, on the member's own machine);basis=also parses the root _redirects file it has already read (the same ReadFile) and refuses the pack when a line does not parse; no read added, offsets unchanged;rev3=census-ruling-static-headers;basis=also parses the root _headers file it has already read (the same ReadFile as every packed file) with parseHeaders, pure and in-memory, and refuses the pack when a line does not parse, exactly as it does for _redirects; no read added file:ReadFile@626,file:WalkDir@71 ff1fc031daf5053abbec1f2f2145ed93fccaa75ba5d6673d3c69020ce33dcbda |
| +@legacy 4e9f48a0daa7ef0921f0e259812850774019f8fcb65e253d9ca1caf995e88d58 internal/edge/static.go staticSite.serveFile legacy accepted-legacy accepted-legacy;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input; serveTree's former Open and open-file Stat of the file serveTree resolved inside the extracted, digest-verified tree, unchanged, plus a non-200 branch that copies the same open file under a _redirects 404 status; no root decision;rev3=census-ruling-static-headers;basis=takes the in-memory _headers lookup result (extra) and, on the 200 branch only, wraps the writer in headerWriter, which sets those header values on 200/206/304 at status time; the same Open and open-file Stat of the same resolved file; no read added, no root decision file:Open@145,file:Stat@1607 b1cfea3e2636b4aa04641a718a8353da1b8142fe9d608a40fa3b3269aee6778a |
| +@legacy a208b3ba964930bb622d89cd262bfc2617fe96360902ead001a34dbb1c9c2bcd internal/edge/static.go staticSite.serveTree legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=the same index-aware Stat lookup inside the extracted tree, now run at most twice (the request path, then once for a _redirects rewrite destination cleaned rooted inside the same tree); the Open moves to serveFile; the _redirects file itself is never answered; no root decision;rev3=census-ruling-edge-protection-2;basis=consults the edge protection matcher (internal/edgeguard, pure and in-memory) on the request path (probe tier, only when no file and no _redirects rule names it) and on a rewrite target (hard tier, only when the file is there), and may answer the guard's 404 block page through guardDecide before a redirect or the rewritten file; the _redirects lookup gains an in-memory names check; the same index-aware Stat lookups inside the extracted tree, unchanged; no read added;rev3=census-ruling-static-dir-slash;basis=A directory requested without its trailing slash now answers a 301 to a relative "./<base>/" (query kept) instead of serving its index.html, unless the request was rewritten, the path ends in "/", a _redirects rule names the path, or the rules would redirect its slash form (redirectsSlashForm, the existing in-memory resolve with exists=true). It opens and stats exactly the files it did before; the new branch only writes a Location header and a status, from the request path and the rules it already parsed.;rev3=census-ruling-static-headers;basis=computes the in-memory _headers lookup once on the cleaned request path and host and passes it to serveFile; the _headers file itself is never answered (found excludes it, as _redirects); the same index-aware Stat lookups inside the extracted tree; no read added file:Stat@1301,file:Stat@1415 795cf8cc3fd62482607dd7078c20eca0cbba5e17ca8f241c589c9946d827545e |
| +@legacy 0df1c49dcb0dab338c17220845a25a46e194bb13f41f178c789e24e554677662 internal/edge/static.go staticSite.loadHeaders legacy accepted-legacy accepted-legacy;rev3=census-ruling-static-headers;basis=new: reads the _headers file at the root of the extracted, digest-verified tree once per version swap (ReadFile of filepath.Join(dir, headersFile), dir from the signed pointer and manifest digest as loadRedirects uses), parses it in memory; a missing file is no rules, a read or parse error is logged; the same shape as loadRedirects file:ReadFile@83 34f2ba99895615e296aaa7cd34b4c905ce43508c0383861ad1d8f9f7171bffc8 |
| +@legacy 16fc00c45bc5bb7ed5530db23274d68318befd2b9244c501c5869cb0a2fbd494 internal/edge/edge.go Edge.ServeHTTP legacy accepted-legacy accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with the import gate checked after the door's scope and a gated row left out of the response cache; serving only;rev3=census-ruling-edge-request-records;basis=one more call in the observer defer, observeRecords(up.route, ...), passing on the route the defer already holds; no new kind of read;rev3=census-ruling-design-edge-rate-limit-358;basis=calls rateAdmit twice, and an admitted request holds a slot on both paths: on the upgrade path before the activator or proxy (the handshake holds its slot through slotWriter, given back at the first final answer or at the reverse proxy's hijack on a 101, so an open WebSocket is not counted; released by a defer), and on the ordinary path after the response-cache check and before the activator and proxy (an admitted request holds a slot through slotWriter, released by a defer); a refusal is a 429 written there and returns; the upgrade path's comment now names slotWriter as its one wrapper; one comment on the door mark reworded; read sites unchanged (22: main's 21 plus edge-request-records' observeRecords pass of the route), offsets moved; no read added;rev3=census-ruling-plans-4c-box-throttle;basis=calls planThrottleAdmit before the response cache, and on an upgrade trackUpgrade then planUpgradeAdmit (plans 4c, Astra findings 1 and 2); the new reads live in those units (plans-4c-units decision). The same read sites here.;rev3=census-ruling-plans-4d-lapse;basis=calls planDisabledAdmit right after the import gate, passing the final upstream's route and the request host; a turned-off route gets the fixed disabled page before the meter, gate, cache and activator (plans 4d). The new read lives in that unit (plans-4d-units decision); one more whole-row pass here.;rev3=census-ruling-edge-protection-2;basis=runs the guard, a pure in-memory matcher on r.URL.Path and RawQuery (internal/edgeguard), once per request after the meter and observer defer and before the password gate, the upgrade branch, the cache and the activator, for a request that is not a door call, a backhauled door hop or a tunnel delivery; a matched block answers a 404 itself through guardDecide; the two new sites are one expression, up.route.Kind == "static" (a static route this box serves checks only the hard tier here and leaves the probe tier to serveTree), a read of the route row the edge already resolved; no new kind of read;rev3=census-ruling-edge-asset-cache-3;basis=the asset cache's three hooks (asset cache plan 3): the request's reserved asset headers are deleted at entry (the fill assertion kept only beside a verified hop); on the exact-remote and lookup-miss branches the far catch (serveAssetFar) is tried before backhaulTo and backhaul; after the observer defer and main's hard and probe checks, a verified hop with a valid fill assertion is answered by serveAssetFillForHop; after the upgrade branch and before gzip and the shared cache, the local catch (serveAssetLocal); the observer defer skips only the usage meter for an acknowledged home fill (out.unbilled); the new reads live in the new units of the edge-asset-cache-3-decisions overlay; the same route row and read sites (25); no read added;rev3=census-ruling-regional-domains-447;basis=#447 Task 5: straight after lookupUpstreamPath it calls regionalGate (regional.go), which for an entry built from a regional_domains row answers 503 to a hop or a deny entry before any arm that can leave the box (the exact-home backhaul, the far asset catch, the door dial, the miss backhaul), and lets a star match through only to the exact-home arm when ExactHome names another box for that distinct exact name; after the exact-home arm a regional deny entry the arm did not answer is refused (regionalRefuse, 503); refusals only, on the route map the edge already holds; read sites unchanged (25);rev3=census-ruling-static-headers;basis=the shared response cache is no longer looked up or filled for a static-kind route: one more read of the route row the edge already resolved (up.route.Kind == "static") in the cacheable expression; a refusal only, nothing new opened or followed registry:Gate@18331,registry:Gate@18391,registry:Gate@18449,registry:Host@18434,registry:ImportGate@23924,registry:Kind@13994,registry:Kind@16464,registry:Kind@23866,registry:Kind@23895,whole:Route@11802,whole:Route@12014,whole:Route@12206,whole:Route@13997,whole:Route@15300,whole:Route@15395,whole:Route@15471,whole:Route@15515,whole:Route@16467,whole:Route@18334,whole:Route@18394,whole:Route@18437,whole:Route@18452,whole:Route@20085,whole:Route@23869,whole:Route@23898,whole:Route@23927,whole:Route@25759 12d592d2b0fd1ccc81a836ff238abff2a4dcb839264d5e7b6c3dd2803c32d8dc |
| +internal/edge/static.go PackDir legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-static-redirects;identity=the carlos CLI (carlos ship and carlos deploy --kind static, on the member's own machine);basis=also parses the root _redirects file it has already read (the same ReadFile) and refuses the pack when a line does not parse; no read added, offsets unchanged;rev3=census-ruling-static-headers;basis=also parses the root _headers file it has already read (the same ReadFile as every packed file) with parseHeaders, pure and in-memory, and refuses the pack when a line does not parse, exactly as it does for _redirects; no read added file:ReadFile@626,file:WalkDir@71 ff1fc031daf5053abbec1f2f2145ed93fccaa75ba5d6673d3c69020ce33dcbda |
| +internal/edge/static.go staticSite.serveFile legacy accepted-legacy accepted-legacy;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input; serveTree's former Open and open-file Stat of the file serveTree resolved inside the extracted, digest-verified tree, unchanged, plus a non-200 branch that copies the same open file under a _redirects 404 status; no root decision;rev3=census-ruling-static-headers;basis=takes the in-memory _headers lookup result (extra) and, on the 200 branch only, wraps the writer in headerWriter, which sets those header values on 200/206/304 at status time; the same Open and open-file Stat of the same resolved file; no read added, no root decision file:Open@145,file:Stat@1607 b1cfea3e2636b4aa04641a718a8353da1b8142fe9d608a40fa3b3269aee6778a |
| +internal/edge/static.go staticSite.serveTree legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=PROPOSED-static-redirects;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=the same index-aware Stat lookup inside the extracted tree, now run at most twice (the request path, then once for a _redirects rewrite destination cleaned rooted inside the same tree); the Open moves to serveFile; the _redirects file itself is never answered; no root decision;rev3=census-ruling-edge-protection-2;basis=consults the edge protection matcher (internal/edgeguard, pure and in-memory) on the request path (probe tier, only when no file and no _redirects rule names it) and on a rewrite target (hard tier, only when the file is there), and may answer the guard's 404 block page through guardDecide before a redirect or the rewritten file; the _redirects lookup gains an in-memory names check; the same index-aware Stat lookups inside the extracted tree, unchanged; no read added;rev3=census-ruling-static-dir-slash;basis=A directory requested without its trailing slash now answers a 301 to a relative "./<base>/" (query kept) instead of serving its index.html, unless the request was rewritten, the path ends in "/", a _redirects rule names the path, or the rules would redirect its slash form (redirectsSlashForm, the existing in-memory resolve with exists=true). It opens and stats exactly the files it did before; the new branch only writes a Location header and a status, from the request path and the rules it already parsed.;rev3=census-ruling-static-headers;basis=computes the in-memory _headers lookup once on the cleaned request path and host and passes it to serveFile; the _headers file itself is never answered (found excludes it, as _redirects); the same index-aware Stat lookups inside the extracted tree; no read added file:Stat@1301,file:Stat@1415 795cf8cc3fd62482607dd7078c20eca0cbba5e17ca8f241c589c9946d827545e |
| +internal/edge/static.go staticSite.loadHeaders legacy accepted-legacy accepted-legacy;rev3=census-ruling-static-headers;basis=new: reads the _headers file at the root of the extracted, digest-verified tree once per version swap (ReadFile of filepath.Join(dir, headersFile), dir from the signed pointer and manifest digest as loadRedirects uses), parses it in memory; a missing file is no rules, a read or parse error is logged; the same shape as loadRedirects file:ReadFile@83 34f2ba99895615e296aaa7cd34b4c905ce43508c0383861ad1d8f9f7171bffc8 |
| +internal/edge/edge.go Edge.ServeHTTP legacy accepted-legacy accepted-legacy;rev3=census-ruling-seeded-instances;basis=the edge inside the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with the import gate checked after the door's scope and a gated row left out of the response cache; serving only;rev3=census-ruling-edge-request-records;basis=one more call in the observer defer, observeRecords(up.route, ...), passing on the route the defer already holds; no new kind of read;rev3=census-ruling-design-edge-rate-limit-358;basis=calls rateAdmit twice, and an admitted request holds a slot on both paths: on the upgrade path before the activator or proxy (the handshake holds its slot through slotWriter, given back at the first final answer or at the reverse proxy's hijack on a 101, so an open WebSocket is not counted; released by a defer), and on the ordinary path after the response-cache check and before the activator and proxy (an admitted request holds a slot through slotWriter, released by a defer); a refusal is a 429 written there and returns; the upgrade path's comment now names slotWriter as its one wrapper; one comment on the door mark reworded; read sites unchanged (22: main's 21 plus edge-request-records' observeRecords pass of the route), offsets moved; no read added;rev3=census-ruling-plans-4c-box-throttle;basis=calls planThrottleAdmit before the response cache, and on an upgrade trackUpgrade then planUpgradeAdmit (plans 4c, Astra findings 1 and 2); the new reads live in those units (plans-4c-units decision). The same read sites here.;rev3=census-ruling-plans-4d-lapse;basis=calls planDisabledAdmit right after the import gate, passing the final upstream's route and the request host; a turned-off route gets the fixed disabled page before the meter, gate, cache and activator (plans 4d). The new read lives in that unit (plans-4d-units decision); one more whole-row pass here.;rev3=census-ruling-edge-protection-2;basis=runs the guard, a pure in-memory matcher on r.URL.Path and RawQuery (internal/edgeguard), once per request after the meter and observer defer and before the password gate, the upgrade branch, the cache and the activator, for a request that is not a door call, a backhauled door hop or a tunnel delivery; a matched block answers a 404 itself through guardDecide; the two new sites are one expression, up.route.Kind == "static" (a static route this box serves checks only the hard tier here and leaves the probe tier to serveTree), a read of the route row the edge already resolved; no new kind of read;rev3=census-ruling-edge-asset-cache-3;basis=the asset cache's three hooks (asset cache plan 3): the request's reserved asset headers are deleted at entry (the fill assertion kept only beside a verified hop); on the exact-remote and lookup-miss branches the far catch (serveAssetFar) is tried before backhaulTo and backhaul; after the observer defer and main's hard and probe checks, a verified hop with a valid fill assertion is answered by serveAssetFillForHop; after the upgrade branch and before gzip and the shared cache, the local catch (serveAssetLocal); the observer defer skips only the usage meter for an acknowledged home fill (out.unbilled); the new reads live in the new units of the edge-asset-cache-3-decisions overlay; the same route row and read sites (25); no read added;rev3=census-ruling-regional-domains-447;basis=#447 Task 5: straight after lookupUpstreamPath it calls regionalGate (regional.go), which for an entry built from a regional_domains row answers 503 to a hop or a deny entry before any arm that can leave the box (the exact-home backhaul, the far asset catch, the door dial, the miss backhaul), and lets a star match through only to the exact-home arm when ExactHome names another box for that distinct exact name; after the exact-home arm a regional deny entry the arm did not answer is refused (regionalRefuse, 503); refusals only, on the route map the edge already holds; read sites unchanged (25);rev3=census-ruling-static-headers;basis=the shared response cache is no longer looked up or filled for a static-kind route: one more read of the route row the edge already resolved (up.route.Kind == "static") in the cacheable expression; a refusal only, nothing new opened or followed registry:Gate@18331,registry:Gate@18391,registry:Gate@18449,registry:Host@18434,registry:ImportGate@23924,registry:Kind@13994,registry:Kind@16464,registry:Kind@23866,registry:Kind@23895,whole:Route@11802,whole:Route@12014,whole:Route@12206,whole:Route@13997,whole:Route@15300,whole:Route@15395,whole:Route@15471,whole:Route@15515,whole:Route@16467,whole:Route@18334,whole:Route@18394,whole:Route@18437,whole:Route@18452,whole:Route@20085,whole:Route@23869,whole:Route@23898,whole:Route@23927,whole:Route@25759 12d592d2b0fd1ccc81a836ff238abff2a4dcb839264d5e7b6c3dd2803c32d8dc |
| +@coverage internal/edge 8cce07179dff0c8061751b5a308d33e63ef542996f7b4924d5da27228eb3fb44 |