carlos / platform Public

edge: asset admission, expiry, trailer veto and stored headers

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a895bfe81b3a140df2e6a301f99ce8b37e673ef8 parent d00bbac
2 files changed, +570 −0
  • internal/edge/assetadmit.go +232 −0
  • internal/edge/assetadmit_test.go +338 −0
diff --git a/internal/edge/assetadmit.go b/internal/edge/assetadmit.go
new file mode 100644
index 000000000..2ff03170e
--- /dev/null
+++ b/internal/edge/assetadmit.go
@@ -0,0 +1,232 @@
+package edge
+
+import (
+ "errors"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/assetcache"
+)
+
+// The pure half of the asset cache's fill: whether a response may be stored,
+// when it expires, whether its trailers veto it, and which of its headers are
+// kept with the entry. Nothing here touches a store, a clock or a request, so
+// the home's fill, a far edge's fill and the header-time storability test the
+// home answers with (X-Carlos-Asset-Expires) all ask the same questions of the
+// same code.
+
+const (
+ // maxAssetLifetime is the longest an entry may live whatever the app says.
+ // There is no shorter clamp: a declared prefix plus an explicit lifetime is
+ // the app saying the bytes hold.
+ maxAssetLifetime = 365 * 24 * time.Hour
+
+ // maxAssetAge bounds an Age header before it is added to anything, so a
+ // hostile or absurd value cannot overflow a Duration.
+ maxAssetAge = 10 * 365 * 24 * time.Hour
+)
+
+// assetVerdict is assetAdmit's answer. When Store is false, Reason names the
+// first rule that refused and the other fields are zero. When Store is true,
+// Reason is empty, Lifetime is the capped lifetime the app declared, Expires
+// is the entry's absolute expiry and Gzip says whether a gzip copy should be
+// made at fill.
+type assetVerdict struct {
+ Store bool
+ Reason string
+ Expires time.Time
+ Lifetime time.Duration
+ Gzip bool
+}
+
+func assetRefuse(reason string) assetVerdict { return assetVerdict{Reason: reason} }
+
+// assetAdmit applies the header-time storage rules (spec 5.3), in order, to a
+// response that has just arrived. requestTime is when the request left,
+// responseTime when the response headers arrived, declared whether the build
+// that answered declared the prefix. A refused response is still served; the
+// verdict only says it is not kept.
+//
+// The body-time rules (a short body, a body past the cap while streaming, a
+// failed reservation, a trailer carrying Set-Cookie) are the caller's.
+func assetAdmit(status int, h http.Header, requestTime, responseTime time.Time, declared bool) assetVerdict {
+ if status != http.StatusOK {
+ return assetRefuse("status")
+ }
+ if len(h.Values("Set-Cookie")) > 0 {
+ return assetRefuse("set-cookie")
+ }
+
+ cc := joinHeader(h, "Cache-Control")
+ if strings.TrimSpace(cc) == "" {
+ return assetRefuse("no-cache-control")
+ }
+ for _, d := range []string{"private", "no-store", "no-cache"} {
+ if hasCCDirective(cc, d) {
+ return assetRefuse("cache-control")
+ }
+ }
+ lifetime, ok := parseMaxAge(cc)
+ if !ok || lifetime <= 0 {
+ return assetRefuse("no-lifetime")
+ }
+ if lifetime > maxAssetLifetime {
+ lifetime = maxAssetLifetime
+ }
+
+ if !assetVaryOK(h) {
+ return assetRefuse("vary")
+ }
+ for _, v := range h.Values("Content-Encoding") {
+ for _, tok := range strings.Split(v, ",") {
+ if tok = strings.TrimSpace(tok); tok != "" && !strings.EqualFold(tok, "identity") {
+ return assetRefuse("content-encoding")
+ }
+ }
+ }
+
+ mt, _, _ := strings.Cut(h.Get("Content-Type"), ";")
+ mt = strings.ToLower(strings.TrimSpace(mt))
+ if mt == "" {
+ return assetRefuse("content-type")
+ }
+ if mt == "text/html" || mt == "application/xhtml+xml" {
+ return assetRefuse("html")
+ }
+
+ if vs := h.Values("Access-Control-Allow-Origin"); len(vs) > 0 {
+ if len(vs) != 1 || strings.TrimSpace(vs[0]) != "*" {
+ return assetRefuse("allow-origin")
+ }
+ }
+ if !declared {
+ return assetRefuse("undeclared")
+ }
+ if cl := strings.TrimSpace(h.Get("Content-Length")); cl != "" {
+ n, err := strconv.ParseInt(cl, 10, 64)
+ if err != nil || n < 0 {
+ return assetRefuse("content-length")
+ }
+ if n > assetcache.MaxBody {
+ return assetRefuse("too-large")
+ }
+ }
+
+ age := correctedInitialAge(h, requestTime, responseTime)
+ if age >= lifetime {
+ return assetRefuse("expired")
+ }
+ return assetVerdict{
+ Store: true,
+ Expires: responseTime.Add(lifetime - age),
+ Lifetime: lifetime,
+ Gzip: compressible(h, http.StatusOK),
+ }
+}
+
+// assetVaryOK reports whether Vary is absent or names only Accept-Encoding.
+// Compression is the one variation the cache keeps itself (an identity body
+// and a gzip copy); any other axis would need a key the cache does not have.
+func assetVaryOK(h http.Header) bool {
+ for _, v := range h.Values("Vary") {
+ for _, tok := range strings.Split(v, ",") {
+ if tok = strings.TrimSpace(tok); tok != "" && !strings.EqualFold(tok, "Accept-Encoding") {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// correctedInitialAge is RFC 9111 4.2.3: the larger of the apparent age (how
+// far the response's Date lags behind its arrival) and the Age header plus the
+// response delay. Unreadable or negative Age and Date count as absent, a Date
+// in the future is no age at all, and a response time before the request time
+// (a stepped clock) is a zero delay.
+func correctedInitialAge(h http.Header, requestTime, responseTime time.Time) time.Duration {
+ var apparent time.Duration
+ if d, err := http.ParseTime(h.Get("Date")); err == nil {
+ if a := responseTime.Sub(d); a > 0 {
+ apparent = min(a, maxAssetAge)
+ }
+ }
+
+ var ageValue time.Duration
+ if s := strings.TrimSpace(h.Get("Age")); s != "" {
+ secs, err := strconv.ParseUint(s, 10, 64)
+ switch {
+ case err == nil && secs <= uint64(maxAssetAge/time.Second):
+ ageValue = time.Duration(secs) * time.Second
+ case errors.Is(err, strconv.ErrRange) || err == nil:
+ ageValue = maxAssetAge
+ }
+ }
+
+ delay := max(responseTime.Sub(requestTime), 0)
+ return max(apparent, ageValue+delay)
+}
+
+// assetTrailerVeto reports whether a response's trailers carry Set-Cookie,
+// announced in the Trailer header (the key is present in the map, valued or
+// not) or sent unannounced under http.TrailerPrefix. A cookie that arrives
+// after the headers were judged must still keep the response out of a shared
+// store, so every fill, home and far, asks this after the last body byte and
+// before Commit. A far edge passes the backhauled response's own trailers,
+// which the transport carries through.
+func assetTrailerVeto(trailer http.Header) bool {
+ for k := range trailer {
+ if len(k) >= len(http.TrailerPrefix) && strings.EqualFold(k[:len(http.TrailerPrefix)], http.TrailerPrefix) {
+ k = k[len(http.TrailerPrefix):]
+ }
+ if strings.EqualFold(strings.TrimSpace(k), "Set-Cookie") {
+ return true
+ }
+ }
+ return false
+}
+
+// assetStoredHeader returns a clone of h holding what an entry keeps: every
+// end-to-end response header (so Content-Security-Policy,
+// Cross-Origin-Resource-Policy and the rest reach a hit as they reached the
+// miss), without
+//
+// - hop-by-hop headers: Connection and every name it lists, Keep-Alive,
+// Transfer-Encoding, Upgrade, TE, Trailer, Proxy-*;
+// - Date (regenerated), Age (recomputed), Content-Length (recomputed per
+// representation);
+// - the purge headers, Carlos-Cache and every X-Carlos-* header, which belong
+// to the platform and are never the app's to store or replay.
+func assetStoredHeader(h http.Header) http.Header {
+ out := h.Clone()
+ if out == nil {
+ return http.Header{}
+ }
+ listed := map[string]bool{}
+ for k, vs := range out {
+ if strings.EqualFold(k, "Connection") {
+ for _, v := range vs {
+ for _, name := range strings.Split(v, ",") {
+ if name = strings.TrimSpace(name); name != "" {
+ listed[strings.ToLower(name)] = true
+ }
+ }
+ }
+ }
+ }
+ for k := range out {
+ lk := strings.ToLower(k)
+ switch {
+ case listed[lk]:
+ delete(out, k)
+ case strings.HasPrefix(lk, "proxy-"), strings.HasPrefix(lk, "x-carlos-"):
+ delete(out, k)
+ case lk == "connection", lk == "keep-alive", lk == "transfer-encoding", lk == "upgrade",
+ lk == "te", lk == "trailer", lk == "date", lk == "age", lk == "content-length",
+ lk == "carlos-purge", lk == "carlos-purge-host", lk == "carlos-cache":
+ delete(out, k)
+ }
+ }
+ return out
+}
diff --git a/internal/edge/assetadmit_test.go b/internal/edge/assetadmit_test.go
new file mode 100644
index 000000000..39b6bb38c
--- /dev/null
+++ b/internal/edge/assetadmit_test.go
@@ -0,0 +1,338 @@
+package edge
+
+import (
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Not acceptance: these pin the pure admission, expiry and stored-header
+// functions only. The wired fill is exercised by the plan's acceptance tests.
+
+var admitT0 = time.Unix(1_800_000_000, 0)
+
+// admitHeaders is a response that stores: every rule passes.
+func admitHeaders() http.Header {
+ h := http.Header{}
+ h.Set("Cache-Control", "public, max-age=31536000, immutable")
+ h.Set("Content-Type", "text/css; charset=utf-8")
+ return h
+}
+
+func TestAssetAdmitTable(t *testing.T) {
+ const year = 365 * 24 * time.Hour
+ tests := []struct {
+ name string
+ status int
+ mutate func(h http.Header)
+ declared bool
+ store bool
+ reason string
+ lifetime time.Duration
+ }{
+ {name: "immutable css stores", status: 200, declared: true, store: true, lifetime: year},
+ {name: "s-maxage beats max-age", status: 200, declared: true, store: true, lifetime: 60 * time.Second,
+ mutate: func(h http.Header) { h.Set("Cache-Control", "public, max-age=31536000, s-maxage=60") }},
+ {name: "max-age over a year is capped", status: 200, declared: true, store: true, lifetime: year,
+ mutate: func(h http.Header) { h.Set("Cache-Control", "max-age=999999999") }},
+ {name: "vary accept-encoding stores, any case and spacing", status: 200, declared: true, store: true, lifetime: year,
+ mutate: func(h http.Header) { h.Set("Vary", " accept-ENCODING ") }},
+ {name: "identity content-encoding stores", status: 200, declared: true, store: true, lifetime: year,
+ mutate: func(h http.Header) { h.Set("Content-Encoding", "identity") }},
+ {name: "allow-origin star stores", status: 200, declared: true, store: true, lifetime: year,
+ mutate: func(h http.Header) { h.Set("Access-Control-Allow-Origin", "*") }},
+ {name: "content-length at the cap stores", status: 200, declared: true, store: true, lifetime: year,
+ mutate: func(h http.Header) { h.Set("Content-Length", "33554432") }},
+
+ {name: "206 refused", status: 206, declared: true, reason: "status"},
+ {name: "404 refused", status: 404, declared: true, reason: "status"},
+ {name: "set-cookie refused", status: 200, declared: true, reason: "set-cookie",
+ mutate: func(h http.Header) { h.Add("Set-Cookie", "a=b") }},
+ {name: "no cache-control refused", status: 200, declared: true, reason: "no-cache-control",
+ mutate: func(h http.Header) { h.Del("Cache-Control") }},
+ {name: "private refused", status: 200, declared: true, reason: "cache-control",
+ mutate: func(h http.Header) { h.Set("Cache-Control", "private, max-age=600") }},
+ {name: "no-store refused", status: 200, declared: true, reason: "cache-control",
+ mutate: func(h http.Header) { h.Set("Cache-Control", "no-store, max-age=600") }},
+ {name: "no-cache refused", status: 200, declared: true, reason: "cache-control",
+ mutate: func(h http.Header) { h.Set("Cache-Control", "no-cache, max-age=600") }},
+ {name: "private on a second line refused", status: 200, declared: true, reason: "cache-control",
+ mutate: func(h http.Header) { h.Add("Cache-Control", "private") }},
+ {name: "no lifetime refused", status: 200, declared: true, reason: "no-lifetime",
+ mutate: func(h http.Header) { h.Set("Cache-Control", "public") }},
+ {name: "zero lifetime refused", status: 200, declared: true, reason: "no-lifetime",
+ mutate: func(h http.Header) { h.Set("Cache-Control", "max-age=0") }},
+ {name: "zero s-maxage refused", status: 200, declared: true, reason: "no-lifetime",
+ mutate: func(h http.Header) { h.Set("Cache-Control", "max-age=600, s-maxage=0") }},
+ {name: "malformed max-age refused", status: 200, declared: true, reason: "no-lifetime",
+ mutate: func(h http.Header) { h.Set("Cache-Control", "max-age=soon") }},
+ {name: "vary origin refused", status: 200, declared: true, reason: "vary",
+ mutate: func(h http.Header) { h.Set("Vary", "Origin") }},
+ {name: "vary cookie refused", status: 200, declared: true, reason: "vary",
+ mutate: func(h http.Header) { h.Set("Vary", "Accept-Encoding, Cookie") }},
+ {name: "vary star refused", status: 200, declared: true, reason: "vary",
+ mutate: func(h http.Header) { h.Set("Vary", "*") }},
+ {name: "vary on a second line refused", status: 200, declared: true, reason: "vary",
+ mutate: func(h http.Header) { h.Set("Vary", "Accept-Encoding"); h.Add("Vary", "Accept") }},
+ {name: "gzip content-encoding refused", status: 200, declared: true, reason: "content-encoding",
+ mutate: func(h http.Header) { h.Set("Content-Encoding", "gzip") }},
+ {name: "no content-type refused", status: 200, declared: true, reason: "content-type",
+ mutate: func(h http.Header) { h.Del("Content-Type") }},
+ {name: "blank content-type refused", status: 200, declared: true, reason: "content-type",
+ mutate: func(h http.Header) { h.Set("Content-Type", " ") }},
+ {name: "html refused", status: 200, declared: true, reason: "html",
+ mutate: func(h http.Header) { h.Set("Content-Type", "text/html; charset=utf-8") }},
+ {name: "html in any case refused", status: 200, declared: true, reason: "html",
+ mutate: func(h http.Header) { h.Set("Content-Type", " Text/HTML") }},
+ {name: "xhtml refused", status: 200, declared: true, reason: "html",
+ mutate: func(h http.Header) { h.Set("Content-Type", "application/xhtml+xml") }},
+ {name: "allow-origin specific refused", status: 200, declared: true, reason: "allow-origin",
+ mutate: func(h http.Header) { h.Set("Access-Control-Allow-Origin", "https://example.com") }},
+ {name: "undeclared refused", status: 200, declared: false, reason: "undeclared"},
+ {name: "content-length over the cap refused", status: 200, declared: true, reason: "too-large",
+ mutate: func(h http.Header) { h.Set("Content-Length", "33554433") }},
+ {name: "unreadable content-length refused", status: 200, declared: true, reason: "content-length",
+ mutate: func(h http.Header) { h.Set("Content-Length", "lots") }},
+ {name: "already stale refused", status: 200, declared: true, reason: "expired",
+ mutate: func(h http.Header) { h.Set("Cache-Control", "max-age=30"); h.Set("Age", "30") }},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ h := admitHeaders()
+ if tc.mutate != nil {
+ tc.mutate(h)
+ }
+ v := assetAdmit(tc.status, h, admitT0, admitT0, tc.declared)
+ if v.Store != tc.store {
+ t.Fatalf("Store = %v (reason %q), want %v", v.Store, v.Reason, tc.store)
+ }
+ if !tc.store {
+ if v.Reason != tc.reason {
+ t.Fatalf("Reason = %q, want %q", v.Reason, tc.reason)
+ }
+ if !v.Expires.IsZero() {
+ t.Fatalf("a refusal carries Expires %v", v.Expires)
+ }
+ return
+ }
+ if v.Reason != "" {
+ t.Fatalf("a stored verdict carries Reason %q", v.Reason)
+ }
+ if v.Lifetime != tc.lifetime {
+ t.Fatalf("Lifetime = %v, want %v", v.Lifetime, tc.lifetime)
+ }
+ if want := admitT0.Add(tc.lifetime); !v.Expires.Equal(want) {
+ t.Fatalf("Expires = %v, want %v", v.Expires, want)
+ }
+ })
+ }
+}
+
+func TestAssetAdmitGzipFollowsCompressible(t *testing.T) {
+ h := admitHeaders()
+ h.Set("Content-Length", "100000")
+ if v := assetAdmit(200, h, admitT0, admitT0, true); !v.Store || !v.Gzip {
+ t.Fatalf("large css: Store=%v Gzip=%v, want both", v.Store, v.Gzip)
+ }
+ h.Set("Content-Type", "image/png")
+ if v := assetAdmit(200, h, admitT0, admitT0, true); !v.Store || v.Gzip {
+ t.Fatalf("png: Store=%v Gzip=%v, want stored and not gzip", v.Store, v.Gzip)
+ }
+ h = admitHeaders()
+ h.Set("Content-Length", "100000")
+ h.Set("Cache-Control", "public, max-age=600, no-transform")
+ if v := assetAdmit(200, h, admitT0, admitT0, true); !v.Store || v.Gzip {
+ t.Fatalf("no-transform: Store=%v Gzip=%v, want stored and not gzip", v.Store, v.Gzip)
+ }
+}
+
+func TestAssetAdmitRefusesALongLivedHTMLFallback(t *testing.T) {
+ h := http.Header{}
+ h.Set("Content-Type", "text/html; charset=utf-8")
+ h.Set("Cache-Control", "public, max-age=31536000")
+ v := assetAdmit(200, h, admitT0, admitT0, true)
+ if v.Store || v.Reason != "html" {
+ t.Fatalf("Store=%v Reason=%q, want an html refusal", v.Store, v.Reason)
+ }
+}
+
+func TestAssetAdmitRefusesNoContentType(t *testing.T) {
+ h := http.Header{}
+ h.Set("Cache-Control", "public, max-age=31536000")
+ v := assetAdmit(200, h, admitT0, admitT0, true)
+ if v.Store || v.Reason != "content-type" {
+ t.Fatalf("Store=%v Reason=%q, want a content-type refusal", v.Store, v.Reason)
+ }
+}
+
+func TestAssetAdmitRefusesAnUndeclaringBuild(t *testing.T) {
+ v := assetAdmit(200, admitHeaders(), admitT0, admitT0, false)
+ if v.Store || v.Reason != "undeclared" {
+ t.Fatalf("Store=%v Reason=%q, want an undeclared refusal", v.Store, v.Reason)
+ }
+}
+
+func TestExpiryIsFromResponseTime(t *testing.T) {
+ // The request left at 0 and the answer arrived at 20 with Age: 0. The
+ // corrected initial age is the 20 s response delay, so a 30 s lifetime
+ // ends at 30, not at 50.
+ h := admitHeaders()
+ h.Set("Cache-Control", "max-age=30")
+ h.Set("Age", "0")
+ req := admitT0
+ resp := admitT0.Add(20 * time.Second)
+ v := assetAdmit(200, h, req, resp, true)
+ if !v.Store {
+ t.Fatalf("not stored: %q", v.Reason)
+ }
+ if want := admitT0.Add(30 * time.Second); !v.Expires.Equal(want) {
+ t.Fatalf("Expires = %v, want %v", v.Expires, want)
+ }
+ if v.Lifetime != 30*time.Second {
+ t.Fatalf("Lifetime = %v, want 30s", v.Lifetime)
+ }
+}
+
+func TestAnAlreadyExpiredResponseIsNotStored(t *testing.T) {
+ h := admitHeaders()
+ h.Set("Cache-Control", "max-age=30")
+ h.Set("Age", "45")
+ v := assetAdmit(200, h, admitT0, admitT0, true)
+ if v.Store || v.Reason != "expired" {
+ t.Fatalf("Store=%v Reason=%q, want an expired refusal", v.Store, v.Reason)
+ }
+}
+
+func TestCorrectedInitialAge(t *testing.T) {
+ req := admitT0
+ resp := admitT0.Add(4 * time.Second)
+ tests := []struct {
+ name string
+ set func(h http.Header)
+ want time.Duration
+ }{
+ {name: "no Age, no Date: the response delay", want: 4 * time.Second},
+ {name: "Age plus delay beats a small Age", want: 14 * time.Second,
+ set: func(h http.Header) { h.Set("Age", "10") }},
+ {name: "apparent age beats Age plus delay", want: 60 * time.Second,
+ set: func(h http.Header) {
+ h.Set("Age", "1")
+ h.Set("Date", resp.Add(-60*time.Second).UTC().Format(http.TimeFormat))
+ }},
+ {name: "a Date in the future is not negative age", want: 4 * time.Second,
+ set: func(h http.Header) { h.Set("Date", resp.Add(time.Hour).UTC().Format(http.TimeFormat)) }},
+ {name: "a garbled Age counts as zero", want: 4 * time.Second,
+ set: func(h http.Header) { h.Set("Age", "old") }},
+ {name: "a negative Age counts as zero", want: 4 * time.Second,
+ set: func(h http.Header) { h.Set("Age", "-5") }},
+ {name: "a huge Age is clamped, not wrapped", want: maxAssetAge + 4*time.Second,
+ set: func(h http.Header) { h.Set("Age", "99999999999999999999") }},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ h := http.Header{}
+ if tc.set != nil {
+ tc.set(h)
+ }
+ if got := correctedInitialAge(h, req, resp); got != tc.want {
+ t.Fatalf("correctedInitialAge = %v, want %v", got, tc.want)
+ }
+ })
+ }
+ // A response time before the request time (a clock step) is a zero delay.
+ if got := correctedInitialAge(http.Header{}, resp, req); got != 0 {
+ t.Fatalf("backwards clock: correctedInitialAge = %v, want 0", got)
+ }
+}
+
+func TestStoredHeaderKeepsCSPAndCORP(t *testing.T) {
+ in := admitHeaders()
+ in.Set("Content-Security-Policy", "default-src 'self'")
+ in.Set("Cross-Origin-Resource-Policy", "same-site")
+ in.Set("ETag", `"abc"`)
+ in.Set("Last-Modified", "Mon, 02 Jan 2006 15:04:05 GMT")
+ in.Add("Link", "</a>; rel=preload")
+ in.Add("Link", "</b>; rel=preload")
+ got := assetStoredHeader(in)
+ for _, name := range []string{"Content-Security-Policy", "Cross-Origin-Resource-Policy", "ETag", "Last-Modified", "Cache-Control", "Content-Type"} {
+ if got.Get(name) != in.Get(name) || got.Get(name) == "" {
+ t.Errorf("%s = %q, want %q", name, got.Get(name), in.Get(name))
+ }
+ }
+ if len(got.Values("Link")) != 2 {
+ t.Errorf("Link values = %v, want both kept", got.Values("Link"))
+ }
+ got.Set("Content-Security-Policy", "changed")
+ if in.Get("Content-Security-Policy") != "default-src 'self'" {
+ t.Error("the stored header shares storage with its input")
+ }
+}
+
+func TestStoredHeaderDropsHopAndPlatformHeaders(t *testing.T) {
+ in := admitHeaders()
+ in.Set("Connection", "close, X-Hop-Custom")
+ in.Set("X-Hop-Custom", "1")
+ in.Set("Keep-Alive", "timeout=5")
+ in.Set("Transfer-Encoding", "chunked")
+ in.Set("Upgrade", "h2c")
+ in.Set("Te", "trailers")
+ in.Set("Trailer", "Expires")
+ in.Set("Proxy-Authenticate", "Basic")
+ in.Set("Proxy-Connection", "keep-alive")
+ in.Set("Date", "Mon, 02 Jan 2006 15:04:05 GMT")
+ in.Set("Age", "12")
+ in.Set("Content-Length", "123")
+ in.Set("Carlos-Purge", "x")
+ in.Set("Carlos-Purge-Host", "shop.example.com")
+ in.Set("Carlos-Cache", "miss")
+ in.Set("X-Carlos-Asset-Expires", "99")
+ in.Set("X-Carlos-Whatever", "1")
+ in.Set("X-Custom", "keep me")
+ // A header map built by hand need not be canonical.
+ in["x-carlos-lower"] = []string{"1"}
+ got := assetStoredHeader(in)
+ for _, name := range []string{
+ "Connection", "X-Hop-Custom", "Keep-Alive", "Transfer-Encoding", "Upgrade", "Te", "Trailer",
+ "Proxy-Authenticate", "Proxy-Connection", "Date", "Age", "Content-Length",
+ "Carlos-Purge", "Carlos-Purge-Host", "Carlos-Cache", "X-Carlos-Asset-Expires", "X-Carlos-Whatever",
+ } {
+ if _, ok := got[name]; ok {
+ t.Errorf("%s survived: %v", name, got[name])
+ }
+ }
+ if _, ok := got["x-carlos-lower"]; ok {
+ t.Error("a non-canonical x-carlos-* key survived")
+ }
+ if got.Get("X-Custom") != "keep me" || got.Get("Content-Type") == "" || got.Get("Cache-Control") == "" {
+ t.Errorf("end-to-end headers lost: %v", got)
+ }
+ if in.Get("Connection") == "" || in.Get("Date") == "" {
+ t.Error("the input was modified")
+ }
+}
+
+func TestTrailerVetoAnnouncedAndUnannounced(t *testing.T) {
+ tests := []struct {
+ name string
+ t http.Header
+ want bool
+ }{
+ {name: "nil", t: nil, want: false},
+ {name: "empty", t: http.Header{}, want: false},
+ {name: "other trailer", t: http.Header{"Expires": {"x"}}, want: false},
+ {name: "announced with a value", t: http.Header{"Set-Cookie": {"a=b"}}, want: true},
+ {name: "announced and empty", t: http.Header{"Set-Cookie": nil}, want: true},
+ {name: "announced, lower case", t: http.Header{"set-cookie": {"a=b"}}, want: true},
+ {name: "unannounced", t: http.Header{http.TrailerPrefix + "Set-Cookie": {"a=b"}}, want: true},
+ {name: "unannounced, odd case", t: http.Header{strings.ToLower(http.TrailerPrefix) + "set-cookie": {"a=b"}}, want: true},
+ {name: "unannounced other", t: http.Header{http.TrailerPrefix + "Expires": {"x"}}, want: false},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := assetTrailerVeto(tc.t); got != tc.want {
+ t.Fatalf("assetTrailerVeto(%v) = %v, want %v", tc.t, got, tc.want)
+ }
+ })
+ }
+}