carlos / platform Public

edge: parse _headers for static sites; ship refuses a bad one (#195, #450)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 6e35306ee559990eca62635fc5b541599502e64e parent c8d4d0f
3 files changed, +475 −0
  • internal/edge/headers.go +282 −0
  • internal/edge/headers_test.go +185 −0
  • internal/edge/static.go +8 −0

Intent

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

diff --git a/internal/edge/headers.go b/internal/edge/headers.go
new file mode 100644
index 000000000..9aaeed23f
--- /dev/null
+++ b/internal/edge/headers.go
@@ -0,0 +1,282 @@
+// 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
+ 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")
+ if trimmed == "" || strings.HasPrefix(trimmed, "#") {
+ continue
+ }
+ indented := line[0] == ' ' || line[0] == '\t'
+
+ if !indented {
+ finish()
+ seenPath = true
+ if len(line) > headersMaxLine {
+ 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
+ }
+ pp, err := parsePattern(trimmed)
+ if err != nil {
+ bad(n, err)
+ continue
+ }
+ if len(hs.rules) == headersMaxRules {
+ bad(n, fmt.Errorf("more than %d path lines", headersMaxRules))
+ 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 len(line) > headersMaxLine {
+ 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
+}
+
+// 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 strings.Split(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..a6fb03f93
--- /dev/null
+++ b/internal/edge/headers_test.go
@@ -0,0 +1,185 @@
+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)
+ }
+
+ 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 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/static.go b/internal/edge/static.go
index 78e276802..a415c8987 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