carlos / platform Public

edge: read forwarding-header Vary values as the backend received them

The response cache rendered a variant's Vary value from the inbound
request, but every proxy replaces X-Forwarded-For, -Host, -Proto and
Forwarded (setForwarded). A backend's Vary: X-Forwarded-For therefore
selected nothing, and one client's answer was served to the next
(hunt H5-M4). varyValue now reads those names from forwardedView, which
runs setForwarded on a scratch request. A Vary on the per-request
forwarded proof is refused like Vary: Cookie.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 6c8925ee8add10f821cf2089e534584aced78368 parent 1e90a27
2 files changed, +186 −2
  • internal/edge/edge.go +52 −2
  • internal/edge/hunt_H5-M4_test.go +134 −0
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index d023c5633..ca153c571 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -3365,6 +3365,8 @@ func (e *Edge) cacheMaxBody() int {
// private per RFC 9111 §3.5, unless Cache-Control explicitly says public,
// which is the app asserting the response is safe to share.
// - Vary: Cookie — varying by cookie would defeat correctness per-visitor.
+// - Vary: X-Carlos-Forwarded-Proof — the edge signs that header afresh for
+// every request, so no two visitors' values ever agree.
// - Vary: * — RFC 9111 §4.1 / RFC 9110 §12.5.5: the response depends on
// something request headers can't capture, so it is never reusable from
// a shared cache.
@@ -3412,7 +3414,10 @@ func (e *Edge) maybeStore(key CacheKey, rec *recordingResponseWriter) {
if vary != "" {
for _, h := range strings.Split(vary, ",") {
h = strings.TrimSpace(h)
- if h == "*" || strings.EqualFold(h, "Cookie") {
+ // The forwarded proof is signed afresh for every request
+ // (forwardproof.go), so a response that varies on it is
+ // one visitor's, every time, like Vary: Cookie.
+ if h == "*" || strings.EqualFold(h, "Cookie") || strings.EqualFold(h, edgeproof.Header) {
return
}
}
@@ -3538,10 +3543,28 @@ func canonicalVary(vary string) string {
// The request side reads all of a header's lines (joinHeader), so two requests
// that differ only in how they split a varied-on header still land in the same
// bucket, which is what RFC 9110 §5.3 says they mean.
+//
+// A value is the one the BACKEND received, not the one the client sent: Vary
+// names request headers as the origin saw them. For almost every header the
+// two are the same bytes. The forwarding headers are the exception
+// (forwardedVaryHeaders): every proxy here deletes the client's and writes
+// its own in setForwarded, so two clients that both sent no X-Forwarded-For
+// reach the backend with two different ones. Read from the inbound request,
+// a backend's honest Vary: X-Forwarded-For selected nothing, and one
+// client's answer was served to the next (hunt H5-M4). Those names are read
+// from forwardedView instead, which runs setForwarded itself.
func varyValue(r *http.Request, vary string) string {
var b strings.Builder
+ var fwd http.Header // forwardedView(r), built on first need
for _, h := range canonicalVaryNames(vary) {
- v := joinHeader(r.Header, h)
+ src := r.Header
+ if forwardedVaryHeaders[h] {
+ if fwd == nil {
+ fwd = forwardedView(r)
+ }
+ src = fwd
+ }
+ v := joinHeader(src, h)
b.WriteString(h)
b.WriteByte('=')
b.WriteString(strconv.Itoa(len(v)))
@@ -3552,6 +3575,33 @@ func varyValue(r *http.Request, vary string) string {
return b.String()
}
+// forwardedVaryHeaders are the request headers the edge's proxies rewrite
+// rather than pass on (setForwarded; httputil.ReverseProxy's Rewrite path
+// deletes all four before Rewrite runs). varyValue reads them from
+// forwardedView. Canonical names, as canonicalVaryNames yields them.
+var forwardedVaryHeaders = map[string]bool{
+ "Forwarded": true,
+ "X-Forwarded-For": true,
+ "X-Forwarded-Host": true,
+ "X-Forwarded-Proto": true,
+}
+
+// forwardedView is the forwarding headers as the backend receives r: what
+// setForwarded writes on a fresh outbound header, which is what every Rewrite
+// in this package starts from, since ReverseProxy has already deleted the
+// inbound ones. Running setForwarded itself, rather than restating it, keeps
+// the cache's view and the proxy's from drifting: the verified hop's chain,
+// the door's scheme and the linked request's public host all come out as
+// the proxy would send them. The forwarded proof is left unsigned here (the
+// key is masked): it is never a cache input, since maybeStore refuses a Vary
+// that names it.
+func forwardedView(r *http.Request) http.Header {
+ in := r.WithContext(context.WithValue(r.Context(), forwardKeyCtx{}, []byte(nil)))
+ out := &http.Request{Header: http.Header{}}
+ setForwarded(&httputil.ProxyRequest{In: in, Out: out})
+ return out.Header
+}
+
// parseMaxAge extracts the freshness lifetime a SHARED cache should use from a
// Cache-Control header. Returns ok=false for "no-store", "no-cache", "private",
// or a missing/malformed lifetime — any of which mean "don't cache this in a
diff --git a/internal/edge/hunt_H5-M4_test.go b/internal/edge/hunt_H5-M4_test.go
new file mode 100644
index 000000000..3e9497fe5
--- /dev/null
+++ b/internal/edge/hunt_H5-M4_test.go
@@ -0,0 +1,134 @@
+package edge
+
+// Hunt H5-M4 (verifier: opus). The edge rewrites X-Forwarded-For on the way
+// out (tcpProxy -> setForwarded -> SetXForwarded: the backend sees the
+// client's address), but the response cache computes a variant's Vary value
+// from the INBOUND request (maybeStore -> varyValue(rec.request, ...);
+// GetFor matches the inbound request too). So a backend that honestly
+// declares "Vary: X-Forwarded-For" on a per-client response has its variant
+// served to every other client whose INBOUND header matches — including all
+// clients that send none. Geo headers are handled correctly because
+// ServeHTTP writes them onto r.Header before the cache (edge.go:1511); the
+// forwarding headers get no such treatment.
+//
+// Production wiring: real registry, New, EnableCache, and the route's real
+// tcpProxy. Asserts the secure answer: two different clients get their own
+// bodies and the backend is asked twice.
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func TestHunt_H5_M4_VaryOnRewrittenForwardedFor(t *testing.T) {
+ var hits atomic.Int64
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ w.Header().Set("Cache-Control", "public, max-age=60")
+ w.Header().Set("Vary", "X-Forwarded-For")
+ w.Write([]byte("for=" + r.Header.Get("X-Forwarded-For")))
+ }))
+ t.Cleanup(backend.Close)
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "app.test", Kind: "instance", Addr: backend.Listener.Addr().String(), Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes))
+
+ get := func(from string) string {
+ w := httptest.NewRecorder()
+ e.ServeHTTP(w, geoReq("app.test", from))
+ return w.Body.String()
+ }
+ first := get("198.51.100.7") // the "attacker", primes the cache
+ second := get("203.0.113.9") // an unrelated visitor
+ if first != "for=198.51.100.7" {
+ t.Fatalf("test bug: backend saw %q, want the first client's address", first)
+ }
+ if second != "for=203.0.113.9" || hits.Load() != 2 {
+ t.Fatalf("H5-M4: second client (203.0.113.9) got %q from the cache (backend hits=%d); the variant keyed on "+
+ "Vary: X-Forwarded-For was selected by the INBOUND header (absent for both), not the value the backend received",
+ second, hits.Load())
+ }
+}
+
+// The same client asking twice still gets the cached variant: the view of
+// the forwarded headers must be stable for one client, or Vary on them
+// would make every response a miss. And a client-supplied X-Forwarded-For,
+// which the proxy discards, must not open a slot of its own.
+func TestVaryOnForwardedForHitsForTheSameClient(t *testing.T) {
+ var hits atomic.Int64
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ w.Header().Set("Cache-Control", "public, max-age=60")
+ w.Header().Set("Vary", "x-forwarded-for")
+ w.Write([]byte("for=" + r.Header.Get("X-Forwarded-For")))
+ }))
+ t.Cleanup(backend.Close)
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "app.test", Kind: "instance", Addr: backend.Listener.Addr().String(), Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes))
+
+ get := func(spoof string) string {
+ r := geoReq("app.test", "198.51.100.7")
+ if spoof != "" {
+ r.Header.Set("X-Forwarded-For", spoof)
+ }
+ w := httptest.NewRecorder()
+ e.ServeHTTP(w, r)
+ return w.Body.String()
+ }
+ for _, spoof := range []string{"", "", "203.0.113.9"} {
+ if got := get(spoof); got != "for=198.51.100.7" {
+ t.Fatalf("X-Forwarded-For %q: got %q, want the connection's address", spoof, got)
+ }
+ }
+ if hits.Load() != 1 {
+ t.Fatalf("backend hits = %d, want 1: one client, one variant", hits.Load())
+ }
+}
+
+// A response that varies on the forwarded proof is never stored: the edge
+// signs that header afresh per request, so it is one visitor's every time.
+func TestVaryOnForwardedProofIsNotStored(t *testing.T) {
+ var hits atomic.Int64
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ w.Header().Set("Cache-Control", "public, max-age=60")
+ w.Header().Set("Vary", "X-Carlos-Forwarded-Proof")
+ w.Write([]byte("ok"))
+ }))
+ t.Cleanup(backend.Close)
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "app.test", Kind: "instance", Addr: backend.Listener.Addr().String(), Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes))
+ for i := 0; i < 2; i++ {
+ e.ServeHTTP(httptest.NewRecorder(), geoReq("app.test", "198.51.100.7"))
+ }
+ if hits.Load() != 2 {
+ t.Fatalf("backend hits = %d, want 2: a Vary on the proof must not be cached", hits.Load())
+ }
+}