From 48d46e8d41c651228c6519ad8d7f6bbe9e43a5d9 Mon Sep 17 00:00:00 2001 From: Pedro Gomes Date: Sun, 22 Nov 2026 14:41:07 +0000 Subject: [PATCH] webui: give the raw and gzip bodies one strong ETag each MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit serveWebAsset digested the raw bytes and then served either the raw or the gzip body under that single ETag. ServeContent validates Range/If-Range and If-None-Match against that header, so a request validated with the ETag of one representation could be answered from the other: a client that held the gzip entity and sent `If-Range: ` got raw bytes back as a 206, and the 304 path had the same shape. Vary: Accept-Encoding does not help — it tells caches that the representations differ, it does not make one validator describe both. Digest the compressed bytes as well and publish `"-gzip"` for that representation. The two validators are now distinct strong ETags over what is actually on the wire, selected together with the body. Tests: TestServeWebAssetPerRepresentationETag asserts the validators differ, that a range with If-Range from its own representation gets 206 + 10 bytes, and that a range with If-Range from the other representation comes back 200 with the full self-consistent body. TestServeWebAssetConditionalIsPerRepresentation covers the same for If-None-Match (304 vs 200). Both fail against the shared-validator code (304 where 200 is required). The existing stability check now pins the ETag per representation rather than per file. --- server/webui_assets.go | 32 +++++++-- server/webui_assets_test.go | 128 +++++++++++++++++++++++++++++++++++- 2 files changed, 151 insertions(+), 9 deletions(-) diff --git a/server/webui_assets.go b/server/webui_assets.go index e4258f5..99036bf 100644 --- a/server/webui_assets.go +++ b/server/webui_assets.go @@ -40,11 +40,19 @@ const ( ) // assetEntry is one embedded file, digested and pre-compressed. +// +// etag and gzETag are distinct strong validators, one per representation: bytes +// on the wire for the raw body differ from those for the gzip body, so a single +// validator shared by both would let a range or a conditional request validated +// against one representation be answered from the other. Vary is not a +// substitute — it only tells caches that the representations differ, it does not +// make one ETag describe both. type assetEntry struct { - raw []byte - gz []byte - etag string - ctype string + raw []byte + gz []byte + etag string + gzETag string + ctype string } // assetCache holds entries keyed by path within the embedded tree. @@ -68,6 +76,11 @@ func loadAsset(fsys fs.FS, name string) (*assetEntry, error) { _ = zw.Close() if buf.Len() < len(raw) { e.gz = buf.Bytes() + // Digest the compressed bytes ourselves rather than suffixing + // the raw validator: the plaintext hash would say nothing about + // what this representation actually contains. + gzSum := sha256.Sum256(e.gz) + e.gzETag = `"` + hex.EncodeToString(gzSum[:16]) + `-gzip"` } } } @@ -129,19 +142,26 @@ func serveWebAsset(w http.ResponseWriter, r *http.Request, fsys fs.FS, name stri } h := w.Header() h.Set("Content-Type", e.ctype) - h.Set("ETag", e.etag) h.Add("Vary", "Accept-Encoding") if immutable { h.Set("Cache-Control", immutableValue) } else { h.Set("Cache-Control", revalidateValue) } + // Pick the representation first, then publish the validator for it. The raw + // and gzip bodies are different entity-tags: sharing one would let a client + // that holds the gzip ETag send If-Range and be served raw bytes (or the + // reverse) as a 206. body := e.raw + etag := e.etag if e.gz != nil && gzipAccepted(r) { h.Set("Content-Encoding", "gzip") body = e.gz + etag = e.gzETag } - // ServeContent handles Range, HEAD and If-None-Match against our ETag. + h.Set("ETag", etag) + // ServeContent handles Range, HEAD and If-None-Match against the ETag we + // just set for this representation. // Zero modtime: content-hashed assets have no meaningful mtime and we do // not want a second, weaker validator in play. http.ServeContent(w, r, name, time.Time{}, bytes.NewReader(body)) diff --git a/server/webui_assets_test.go b/server/webui_assets_test.go index 6dc9481..c3636e5 100644 --- a/server/webui_assets_test.go +++ b/server/webui_assets_test.go @@ -63,11 +63,15 @@ func TestServeWebAssetGzipAndValidators(t *testing.T) { t.Errorf("compression ineffective: %d of %d bytes", len(body), len(fsys[testAssetPath].Data)) } - // Same asset carries the same ETag on a second, unrelated request. + // The same representation carries the same ETag on a second, unrelated + // request; the identity representation carries a different one (covered in + // TestServeWebAssetPerRepresentationETag). rec2 := httptest.NewRecorder() - serveWebAsset(rec2, httptest.NewRequest(http.MethodGet, "/"+testAssetPath, nil), fsys, testAssetPath, true) + req2 := httptest.NewRequest(http.MethodGet, "/"+testAssetPath, nil) + req2.Header.Set("Accept-Encoding", "gzip") + serveWebAsset(rec2, req2, fsys, testAssetPath, true) if got := rec2.Result().Header.Get("ETag"); got != etag { - t.Errorf("ETag not stable: %q vs %q", got, etag) + t.Errorf("gzip ETag not stable: %q vs %q", got, etag) } } @@ -133,6 +137,124 @@ func TestServeWebAssetHonoursEncodingAndCachePolicy(t *testing.T) { } } +// bothRepresentations returns the ETag and body of the identity and gzip +// representations of testAssetPath. +func bothRepresentations(t *testing.T, fsys fstest.MapFS) (rawETag, gzETag string, rawBody, gzBody []byte) { + t.Helper() + for _, enc := range []string{"identity", "gzip"} { + req := httptest.NewRequest(http.MethodGet, "/"+testAssetPath, nil) + req.Header.Set("Accept-Encoding", enc) + rec := httptest.NewRecorder() + if !serveWebAsset(rec, req, fsys, testAssetPath, true) { + t.Fatalf("%s: asset not served", enc) + } + res := rec.Result() + body, err := io.ReadAll(res.Body) + if err != nil { + t.Fatalf("%s: read body: %v", enc, err) + } + if enc == "identity" { + rawETag, rawBody = res.Header.Get("ETag"), body + } else { + gzETag, gzBody = res.Header.Get("ETag"), body + } + if len(body) == 0 { + t.Fatalf("%s: empty body", enc) + } + } + return rawETag, gzETag, rawBody, gzBody +} + +// TestServeWebAssetPerRepresentationETag pins the property that the raw and gzip +// bodies never share a strong validator: a request validated against one must +// not be answered from the other. +func TestServeWebAssetPerRepresentationETag(t *testing.T) { + fsys := webuiTestFS() + rawETag, gzETag, rawBody, gzBody := bothRepresentations(t, fsys) + + if rawETag == "" || gzETag == "" { + t.Fatalf("missing validator: raw %q gzip %q", rawETag, gzETag) + } + if rawETag == gzETag { + t.Fatalf("both representations share the strong validator %q", rawETag) + } + + type request struct { + name string + enc string + ifRange string + wantStatus int + wantBody []byte + } + cases := []request{ + // Sanity: a range validated against its own representation is honoured. + {"range on raw, own etag", "identity", rawETag, http.StatusPartialContent, rawBody[:10]}, + {"range on gzip, own etag", "gzip", gzETag, http.StatusPartialContent, gzBody[:10]}, + // The regression: the ETag of the other representation must not + // validate a range, so the full, self-consistent body comes back. + {"range on raw, gzip etag", "identity", gzETag, http.StatusOK, rawBody}, + {"range on gzip, raw etag", "gzip", rawETag, http.StatusOK, gzBody}, + } + for _, tc := range cases { + req := httptest.NewRequest(http.MethodGet, "/"+testAssetPath, nil) + req.Header.Set("Accept-Encoding", tc.enc) + req.Header.Set("Range", "bytes=0-9") + req.Header.Set("If-Range", tc.ifRange) + rec := httptest.NewRecorder() + if !serveWebAsset(rec, req, fsys, testAssetPath, true) { + t.Fatalf("%s: asset not served", tc.name) + } + res := rec.Result() + body, _ := io.ReadAll(res.Body) + if res.StatusCode != tc.wantStatus { + t.Errorf("%s: status = %d, want %d", tc.name, res.StatusCode, tc.wantStatus) + } + if !bytes.Equal(body, tc.wantBody) { + t.Errorf("%s: body = %d bytes, want %d", tc.name, len(body), len(tc.wantBody)) + } + if got := res.Header.Get("Content-Encoding"); tc.enc == "gzip" && got != "gzip" { + t.Errorf("%s: Content-Encoding = %q, want gzip", tc.name, got) + } + if got := res.Header.Get("ETag"); got == "" { + t.Errorf("%s: ETag missing", tc.name) + } + } +} + +// TestServeWebAssetConditionalIsPerRepresentation is the 304 half of the same +// property: a client holding the gzip validator must not revalidate the raw +// representation against it. +func TestServeWebAssetConditionalIsPerRepresentation(t *testing.T) { + fsys := webuiTestFS() + rawETag, gzETag, _, _ := bothRepresentations(t, fsys) + + type conditional struct { + name string + enc string + validator string + want int + } + cases := []conditional{ + {"raw against own etag", "identity", rawETag, http.StatusNotModified}, + {"gzip against own etag", "gzip", gzETag, http.StatusNotModified}, + {"raw against gzip etag", "identity", gzETag, http.StatusOK}, + {"gzip against raw etag", "gzip", rawETag, http.StatusOK}, + } + for _, tc := range cases { + req := httptest.NewRequest(http.MethodGet, "/"+testAssetPath, nil) + req.Header.Set("Accept-Encoding", tc.enc) + req.Header.Set("If-None-Match", tc.validator) + rec := httptest.NewRecorder() + serveWebAsset(rec, req, fsys, testAssetPath, true) + if rec.Code != tc.want { + t.Errorf("%s: status = %d, want %d", tc.name, rec.Code, tc.want) + } + if tc.want == http.StatusOK && rec.Body.Len() == 0 { + t.Errorf("%s: 200 carried no body", tc.name) + } + } +} + func TestServeWebAssetMissing(t *testing.T) { if serveWebAsset(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/nope.js", nil), webuiTestFS(), "nope.js", false) { t.Error("missing asset reported as served")