edge: asset fix round 1: acknowledge a refused home-fill waiter; strip app-set asset trailers
assetForward applies its header edits before the rate limit too, so a 429 written to a home-fill waiter whose coalesced fill stored nothing is acknowledged (expiry 0) rather than billed by nobody. responseModifier removes the asset vocabulary from an app's trailers: the announced names at header time and the values when the body closes; the fill writer's trailer copy skips them as well. A comment at the home's expiry signing records that it is the header-time verdict (controller ruling on D5).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 files changed,
+200
−11
internal/edge/asset_local_test.go+144 −0internal/edge/assetcatch.go+51 −8internal/edge/cookiescope.go+5 −3
CI failed — run details
diff --git a/internal/edge/asset_local_test.go b/internal/edge/asset_local_test.go| index 0317fc820..be7cca56a 100644 |
| --- a/internal/edge/asset_local_test.go |
| +++ b/internal/edge/asset_local_test.go |
| @@ -1017,3 +1017,147 @@ func TestAssetHitsPassThePlanThrottle(t *testing.T) { |
| t.Fatalf("row = %+v, want one plan-throttle refusal metered", row) |
| } |
| } |
| + |
| +// ---- review round 1 ------------------------------------------------------- |
| + |
| +// fillRequest is a far edge's fill of path as a request, and the assertion |
| +// it carries. |
| +func fillRequest(key []byte, host, path string, c assetFillClaims) (*http.Request, string) { |
| + now := time.Now() |
| + assertion := signAssetFill(key, c, now) |
| + req := httptest.NewRequest(http.MethodGet, "http://"+host+path, nil) |
| + req.Header.Set(hopHeader, "1") |
| + req.Header.Set(hopAuthHeader, signHop(key, host, now)) |
| + req.Header.Set("X-Forwarded-For", "203.0.113.7") |
| + req.Header.Set("Accept-Encoding", "identity") |
| + req.Header.Set(assetFillHeader, assertion) |
| + return req, assertion |
| +} |
| + |
| +func (s *laScene) flightWaiters(id string) int { |
| + f := &s.e.assets.flight |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if c := f.m[id]; c != nil { |
| + return c.waiters |
| + } |
| + return 0 |
| +} |
| + |
| +// A home fill that waited on a coalesced fill which stored nothing makes |
| +// its own request; when the rate limit refuses that one, the 429 is still |
| +// this home's acknowledged answer to the fill (expiry 0), because the home |
| +// does not bill it and the far edge bills only acknowledged responses. |
| +func TestHomeFillWaiterRefusedByTheRateLimitIsAcknowledged(t *testing.T) { |
| + t.Setenv("CARLOS_RATE_LIMIT", "enforce") |
| + started, proceed := make(chan struct{}), make(chan struct{}) |
| + var first atomic.Bool |
| + s := newLAScene(t, func(w http.ResponseWriter, r *http.Request) { |
| + if first.CompareAndSwap(false, true) { |
| + close(started) |
| + <-proceed |
| + } |
| + assetOK(laBody, "Cache-Control", "no-store")(w, r) |
| + }) |
| + if err := s.reg.Upsert(registry.Route{Host: laHost, Kind: "instance", Addr: s.b.srv.Listener.Addr().String(), |
| + Status: "ready", Account: "abc", App: "shop", AssetGen: laGen, Version: laBuild, RateLimit: `{"rate":1,"burst":1}`}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + key := s.armMesh(t) |
| + m := NewUsageMeter() |
| + s.e.EnableUsage(m) |
| + serve := func(req *http.Request) <-chan *httptest.ResponseRecorder { |
| + ch := make(chan *httptest.ResponseRecorder, 1) |
| + go func() { |
| + rec := httptest.NewRecorder() |
| + s.e.ServeHTTP(rec, req) |
| + ch <- rec |
| + }() |
| + return ch |
| + } |
| + leaderReq, _ := fillRequest(key, laHost, "/assets/app.js", laClaims("/assets/app.js")) |
| + leader := serve(leaderReq) |
| + <-started |
| + waiterReq, assertion := fillRequest(key, laHost, "/assets/app.js", laClaims("/assets/app.js")) |
| + waiter := serve(waiterReq) |
| + id := s.key("/assets/app.js", "").ID() |
| + laWaitFor(t, "the waiter to join the fill", func() bool { return s.flightWaiters(id) == 1 }) |
| + close(proceed) |
| + |
| + if rec := <-leader; rec.Code != 200 { |
| + t.Fatalf("leader = %d", rec.Code) |
| + } |
| + rec := <-waiter |
| + if rec.Code != http.StatusTooManyRequests { |
| + t.Fatalf("waiter = %d, want the rate limit's 429", rec.Code) |
| + } |
| + exp := rec.Header().Get(assetExpiresHeader) |
| + if exp != "0" || !verifyAssetAck(key, assertion, 0, rec.Header().Get(assetAckHeader)) { |
| + t.Fatalf("the refused waiter's 429 carries expiry %q ack %q, want an acknowledgement with expiry 0", |
| + exp, rec.Header().Get(assetAckHeader)) |
| + } |
| + if row, ok := m.Drain()[laHost]; ok && row.Requests != 0 { |
| + t.Fatalf("the home billed an acknowledged fill: %+v", row) |
| + } |
| +} |
| + |
| +// The app may not send the asset cache's vocabulary as trailers either, |
| +// announced or not, on an uncaught path or a caught one; its other trailers |
| +// still flow. |
| +func TestAppSetAssetTrailersAreStripped(t *testing.T) { |
| + reserved := []string{assetAckHeader, assetExpiresHeader, assetCacheHeader, assetFillHeader} |
| + for _, announced := range []bool{true, false} { |
| + for _, path := range []string{"/index.html", "/assets/app.js"} { |
| + t.Run(fmt.Sprintf("announced=%v%s", announced, path), func(t *testing.T) { |
| + s := newLAScene(t, func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "application/javascript") |
| + w.Header().Set("Cache-Control", "public, max-age=3600") |
| + if announced { |
| + w.Header().Set("Trailer", strings.Join(append([]string{"X-Kept"}, reserved...), ", ")) |
| + } |
| + io.WriteString(w, laBody) |
| + w.(http.Flusher).Flush() |
| + prefix := "" |
| + if !announced { |
| + prefix = http.TrailerPrefix |
| + } |
| + w.Header().Set(prefix+"X-Kept", "1") |
| + for _, h := range reserved { |
| + w.Header().Set(prefix+h, "forged") |
| + } |
| + }) |
| + front := httptest.NewServer(s.e) |
| + t.Cleanup(front.Close) |
| + req, err := http.NewRequest(http.MethodGet, front.URL+path, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Host = laHost |
| + resp, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + if b, _ := io.ReadAll(resp.Body); string(b) != laBody { |
| + t.Fatalf("body = %q", b) |
| + } |
| + for _, h := range reserved { |
| + if _, ok := resp.Trailer[http.CanonicalHeaderKey(h)]; ok { |
| + t.Errorf("the client received the app's %s trailer: %v", h, resp.Trailer) |
| + } |
| + for _, v := range resp.Header.Values("Trailer") { |
| + if strings.Contains(strings.ToLower(v), strings.ToLower(h)) { |
| + t.Errorf("the response announces the app's %s trailer: %q", h, v) |
| + } |
| + } |
| + } |
| + if got := resp.Trailer.Get("X-Kept"); got != "1" { |
| + t.Errorf("X-Kept trailer = %q, want 1: trailers stopped flowing (trailers %v)", got, resp.Trailer) |
| + } |
| + }) |
| + } |
| + } |
| +} |
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go| index d085bf544..81ff62807 100644 |
| --- a/internal/edge/assetcatch.go |
| +++ b/internal/edge/assetcatch.go |
| @@ -383,6 +383,9 @@ func (e *Edge) serveAssetFillForHop(w http.ResponseWriter, r *http.Request, host |
| } |
| unack(w.Header()) |
| e.leadAssetFill(w, r, up, k, a, release, done, func(v assetVerdict, h http.Header) { |
| + // The expiry is the header-time storability verdict (§5.3), not a |
| + // claim that this home's own commit will succeed: the far edge stores |
| + // under its own admission, size, trailer and reservation checks. |
| var exp int64 |
| if v.Store { |
| exp = v.Expires.Unix() |
| @@ -402,8 +405,14 @@ func markUnbilled(r *http.Request) { |
| // assetForward is the uncached fallback: the request forwarded exactly as |
| // today, through the rate limit (D7), answered Carlos-Cache: bypass. onHeader, |
| -// when set, edits the response headers at the first final status. |
| +// when set, edits the response headers at the first final status, and is |
| +// applied before admission too, so a 429 the rate limit writes carries the |
| +// same edits: on a home fill that is the acknowledgement, without which a |
| +// refusal the home does not bill would be billed by nobody. |
| func (e *Edge) assetForward(w http.ResponseWriter, r *http.Request, up upstream, onHeader func(http.Header)) { |
| + if onHeader != nil { |
| + onHeader(w.Header()) |
| + } |
| release, ok := e.rateAdmit(w, r, up) |
| if !ok { |
| return |
| @@ -802,7 +811,7 @@ func (fw *assetFillWriter) finish(brokeOff bool) (*assetcache.Entry, error) { |
| if teeBody && len(trailers) > 0 { |
| h := fw.w.Header() |
| for k, vs := range trailers { |
| - if vs != nil { |
| + if vs != nil && !isAssetVocabulary(strings.TrimPrefix(k, http.TrailerPrefix)) { |
| h[k] = vs |
| } |
| } |
| @@ -865,12 +874,46 @@ func assetTrailers(snap, final http.Header) http.Header { |
| return t |
| } |
| +// assetVocabulary is the asset cache's header vocabulary: the fill, |
| +// acknowledgement and expiry headers and Carlos-Cache are the platform's to |
| +// set, never the app's (§5.3). |
| +var assetVocabulary = []string{assetFillHeader, assetAckHeader, assetExpiresHeader, assetCacheHeader} |
| + |
| +// isAssetVocabulary reports whether name is one of assetVocabulary. |
| +func isAssetVocabulary(name string) bool { |
| + for _, v := range assetVocabulary { |
| + if strings.EqualFold(strings.TrimSpace(name), v) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| // stripAssetResponseHeaders deletes the asset cache's vocabulary from an |
| -// app's response: the fill, acknowledgement and expiry headers and |
| -// Carlos-Cache are the platform's to set, never the app's (§5.3). |
| +// app's response headers. |
| func stripAssetResponseHeaders(h http.Header) { |
| - h.Del(assetFillHeader) |
| - h.Del(assetAckHeader) |
| - h.Del(assetExpiresHeader) |
| - h.Del(assetCacheHeader) |
| + for _, v := range assetVocabulary { |
| + h.Del(v) |
| + } |
| +} |
| + |
| +// stripAssetTrailers keeps the vocabulary out of an app's trailers, announced |
| +// or not. A ModifyResponse hook sees only the announced names (keys of |
| +// resp.Trailer without values), from which httputil.ReverseProxy builds the |
| +// Trailer header it sends on; the values, and any unannounced trailer, land |
| +// in resp.Trailer at EOF, and the proxy copies them out after closing the |
| +// body. So the names go now and the values when the body closes. A 101 |
| +// keeps its body untouched: httputil needs it to be the raw connection. |
| +func stripAssetTrailers(resp *http.Response) { |
| + for _, v := range assetVocabulary { |
| + resp.Trailer.Del(v) |
| + } |
| + if resp.StatusCode == http.StatusSwitchingProtocols || resp.Body == nil { |
| + return |
| + } |
| + resp.Body = &trailerCookieBody{ReadCloser: resp.Body, close: func() { |
| + for _, v := range assetVocabulary { |
| + resp.Trailer.Del(v) |
| + } |
| + }} |
| } |
diff --git a/internal/edge/cookiescope.go b/internal/edge/cookiescope.go| index ba197ee11..e8f073124 100644 |
| --- a/internal/edge/cookiescope.go |
| +++ b/internal/edge/cookiescope.go |
| @@ -72,9 +72,10 @@ func appsDomainFromEnv() string { |
| // responseModifier is the ModifyResponse hook for a tenant route's reverse |
| // proxy: the Carlos-Purge channel (purgeModifier), the removal of any asset |
| -// cache header the app set (stripAssetResponseHeaders: the edge's own are |
| -// set after this, never inherited from the app) and the cookie scoping |
| -// above, in that order. None depends on another. |
| +// cache header or trailer the app set (stripAssetResponseHeaders, |
| +// stripAssetTrailers: the edge's own are set after this, never inherited |
| +// from the app) and the cookie scoping above, in that order. None depends on |
| +// another. |
| func (e *Edge) responseModifier(rt registry.Route) func(*http.Response) error { |
| purge := e.purgeModifier(rt) |
| return func(resp *http.Response) error { |
| @@ -82,6 +83,7 @@ func (e *Edge) responseModifier(rt registry.Route) func(*http.Response) error { |
| return err |
| } |
| stripAssetResponseHeaders(resp.Header) |
| + stripAssetTrailers(resp) |
| e.scopeCookies(rt, resp) |
| return nil |
| } |