From 42903a03ff2f55faf81e1390d8736397b7ebb0bb Mon Sep 17 00:00:00 2001 From: Ravi Agarwal Date: Sun, 22 Nov 2026 17:21:28 +0000 Subject: [PATCH 1/2] fix(handler): probe with GET when the upstream refuses HEAD A HEAD miss is forwarded upstream as HEAD. A presigned GET URL includes the method in its signature, so S3-compatible stores answer HEAD with 403 even when GET would return the object, and servers without a HEAD route answer 405 or 501. Clients probing through the cache then got an error for an object they could download, including when the upstream redirects to such a URL. When the HEAD miss gets 403, 405 or 501, the probe is repeated as a GET and only its status and headers are used. The handler never reads the body and caches nothing; closing it drops the connection, although Go 1.27's transport first drains a body of up to 256 KiB to reuse it. The GET asks for identity encoding when the client didn't send Accept-Encoding, since otherwise the transport requests gzip and drops Content-Length as it decompresses. Other statuses, including 401, 404, 429 and server errors, are returned as before. Signed-off-by: Ravi Agarwal Co-authored-by: Perplexity --- internal/strategy/handler/handler.go | 37 +++++++-- internal/strategy/handler/handler_test.go | 96 +++++++++++++++++++++++ 2 files changed, 125 insertions(+), 8 deletions(-) diff --git a/internal/strategy/handler/handler.go b/internal/strategy/handler/handler.go index 4e691a1a..ae50de93 100644 --- a/internal/strategy/handler/handler.go +++ b/internal/strategy/handler/handler.go @@ -196,7 +196,8 @@ func (h *Handler) ParallelFetch(chunkSize int64, concurrency int) *Handler { // ServeHTTP serves from cache, or fetches from upstream and caches the response while streaming it to the client. // -// HEAD misses are forwarded upstream without caching, so metadata probes never trigger full downloads. +// HEAD misses are forwarded upstream without caching, so metadata probes never trigger full downloads. An upstream +// that refuses HEAD is asked with a GET whose body is never read. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := h.metrics.WithRequest(r.Context(), h.strategy, h.registry, h.external) r = r.WithContext(ctx) @@ -442,20 +443,40 @@ func (h *Handler) upstreamRequest(r *http.Request) (*http.Request, error) { } func (h *Handler) forwardHead(w http.ResponseWriter, r *http.Request) { - req, err := h.upstreamRequest(r) + status, headers, err := h.probe(r, http.MethodHead) + // Some upstreams refuse HEAD for objects they serve: a presigned GET URL signs the method, so HEAD gets a 403. + if err == nil && headRefused(status) { + status, headers, err = h.probe(r, http.MethodGet) + } if err != nil { h.errorHandler(err, w, r) return } - req.Method = http.MethodHead + maps.Copy(w.Header(), headers) + w.WriteHeader(status) +} + +func (h *Handler) probe(r *http.Request, method string) (int, http.Header, error) { + req, err := h.upstreamRequest(r) + if err != nil { + return 0, nil, err + } + req.Method = method + // Otherwise the transport asks for gzip on a GET and drops Content-Length when it decompresses. + if method == http.MethodGet && req.Header.Get("Accept-Encoding") == "" { + req.Header.Set("Accept-Encoding", "identity") + } resp, err := h.client.Do(req) if err != nil { - h.errorHandler(httputil.Errorf(http.StatusBadGateway, "failed to fetch: %w", err), w, r) - return + return 0, nil, httputil.Errorf(http.StatusBadGateway, "failed to fetch: %w", err) } - _ = resp.Body.Close() //nolint:errcheck // HEAD has no body to lose - maps.Copy(w.Header(), resp.Header) - w.WriteHeader(resp.StatusCode) + _ = resp.Body.Close() //nolint:errcheck // Only the status and headers are used. + return resp.StatusCode, resp.Header, nil +} + +func headRefused(status int) bool { + // 401 and 404 usually mean the caller or the object is the problem, so a GET would only repeat them. + return status == http.StatusForbidden || status == http.StatusMethodNotAllowed || status == http.StatusNotImplemented } func (h *Handler) fetchAndCache(w http.ResponseWriter, r *http.Request, key cache.Key) error { diff --git a/internal/strategy/handler/handler_test.go b/internal/strategy/handler/handler_test.go index ec00e41e..e85b6b7c 100644 --- a/internal/strategy/handler/handler_test.go +++ b/internal/strategy/handler/handler_test.go @@ -571,6 +571,102 @@ func TestHeadRequests(t *testing.T) { assert.Equal(t, []string{http.MethodHead, http.MethodGet}, methods) } +func TestHeadMissRefusedByUpstream(t *testing.T) { + const gzipLength = "27" + tests := []struct { + name string + headStatus int + getStatus int + acceptEncoding string + expectStatus int + expectLength string + expectEncoding string + expectCalls []string + }{ + {name: "HeadSupported", headStatus: http.StatusOK, + expectStatus: http.StatusOK, expectLength: "7", expectCalls: []string{http.MethodHead}}, + {name: "PresignedURL", headStatus: http.StatusForbidden, getStatus: http.StatusOK, + expectStatus: http.StatusOK, expectLength: "7", expectCalls: []string{http.MethodHead, http.MethodGet}}, + {name: "PresignedURLMissingObject", headStatus: http.StatusForbidden, getStatus: http.StatusNotFound, + expectStatus: http.StatusNotFound, expectLength: "0", expectCalls: []string{http.MethodHead, http.MethodGet}}, + {name: "MethodNotAllowed", headStatus: http.StatusMethodNotAllowed, getStatus: http.StatusOK, + expectStatus: http.StatusOK, expectLength: "7", expectCalls: []string{http.MethodHead, http.MethodGet}}, + {name: "NotImplemented", headStatus: http.StatusNotImplemented, getStatus: http.StatusOK, + expectStatus: http.StatusOK, expectLength: "7", expectCalls: []string{http.MethodHead, http.MethodGet}}, + {name: "ClientAcceptsGzip", headStatus: http.StatusMethodNotAllowed, getStatus: http.StatusOK, + acceptEncoding: "gzip", expectStatus: http.StatusOK, expectLength: gzipLength, expectEncoding: "gzip", + expectCalls: []string{http.MethodHead, http.MethodGet}}, + {name: "ObjectMissing", headStatus: http.StatusNotFound, + expectStatus: http.StatusNotFound, expectCalls: []string{http.MethodHead}}, + {name: "Unauthorized", headStatus: http.StatusUnauthorized, + expectStatus: http.StatusUnauthorized, expectCalls: []string{http.MethodHead}}, + {name: "RateLimited", headStatus: http.StatusTooManyRequests, + expectStatus: http.StatusTooManyRequests, expectCalls: []string{http.MethodHead}}, + {name: "ServerError", headStatus: http.StatusBadGateway, + expectStatus: http.StatusBadGateway, expectCalls: []string{http.MethodHead}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var ( + mu sync.Mutex + calls []string + waited atomic.Bool + hungUp atomic.Bool + bodyGet = tt.getStatus == http.StatusOK + ) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + calls = append(calls, r.Method) + mu.Unlock() + status := tt.getStatus + if r.Method == http.MethodHead { + status = tt.headStatus + } + if status != http.StatusOK { + w.WriteHeader(status) + return + } + // Compress whenever allowed, as servers that gzip on the fly do. + if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { + w.Header().Set("Content-Encoding", "gzip") + w.Header().Set("Content-Length", gzipLength) + } else { + w.Header().Set("Content-Length", "7") + } + w.WriteHeader(http.StatusOK) + if r.Method != http.MethodGet { + return + } + // Holding the body back until the client hangs up shows the probe never waits for it. + w.(http.Flusher).Flush() + waited.Store(true) + select { + case <-r.Context().Done(): + hungUp.Store(true) + case <-time.After(5 * time.Second): + } + })) + c := mustNewMemoryCache() + defer c.Close() + h := handler.New(http.DefaultClient, c, newTestSpools(t)).Transform(upstreamTransform(upstream.URL)) + + var headers map[string]string + if tt.acceptEncoding != "" { + headers = map[string]string{"Accept-Encoding": tt.acceptEncoding} + } + w := serve(t, h, http.MethodHead, "http://example.com/a", headers) + upstream.Close() + assert.Equal(t, tt.expectStatus, w.Code) + assert.Equal(t, tt.expectLength, w.Header().Get("Content-Length")) + assert.Equal(t, tt.expectEncoding, w.Header().Get("Content-Encoding")) + assert.Equal(t, "", w.Body.String()) + assert.Equal(t, tt.expectCalls, calls) + assert.Equal(t, bodyGet && tt.headStatus != http.StatusOK, waited.Load()) + assert.Equal(t, waited.Load(), hungUp.Load()) + }) + } +} + func TestRangeMissCachesFullObject(t *testing.T) { const payload = "0123456789" tests := []struct { From 9d914528a055f94b77aee5fb85f6ad406d36a463 Mon Sep 17 00:00:00 2001 From: Ravi Agarwal Date: Sun, 22 Nov 2026 17:43:49 +0000 Subject: [PATCH 2/2] refactor(handler): drop comments from the short HEAD probe helpers Signed-off-by: Ravi Agarwal Co-authored-by: Perplexity --- internal/strategy/handler/handler.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/internal/strategy/handler/handler.go b/internal/strategy/handler/handler.go index ae50de93..ba1d47d1 100644 --- a/internal/strategy/handler/handler.go +++ b/internal/strategy/handler/handler.go @@ -197,7 +197,7 @@ func (h *Handler) ParallelFetch(chunkSize int64, concurrency int) *Handler { // ServeHTTP serves from cache, or fetches from upstream and caches the response while streaming it to the client. // // HEAD misses are forwarded upstream without caching, so metadata probes never trigger full downloads. An upstream -// that refuses HEAD is asked with a GET whose body is never read. +// that refuses HEAD with 403, 405 or 501, as presigned GET URLs do, is asked with a GET whose body isn't read. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := h.metrics.WithRequest(r.Context(), h.strategy, h.registry, h.external) r = r.WithContext(ctx) @@ -444,7 +444,6 @@ func (h *Handler) upstreamRequest(r *http.Request) (*http.Request, error) { func (h *Handler) forwardHead(w http.ResponseWriter, r *http.Request) { status, headers, err := h.probe(r, http.MethodHead) - // Some upstreams refuse HEAD for objects they serve: a presigned GET URL signs the method, so HEAD gets a 403. if err == nil && headRefused(status) { status, headers, err = h.probe(r, http.MethodGet) } @@ -462,7 +461,6 @@ func (h *Handler) probe(r *http.Request, method string) (int, http.Header, error return 0, nil, err } req.Method = method - // Otherwise the transport asks for gzip on a GET and drops Content-Length when it decompresses. if method == http.MethodGet && req.Header.Get("Accept-Encoding") == "" { req.Header.Set("Accept-Encoding", "identity") } @@ -475,7 +473,6 @@ func (h *Handler) probe(r *http.Request, method string) (int, http.Header, error } func headRefused(status int) bool { - // 401 and 404 usually mean the caller or the object is the problem, so a GET would only repeat them. return status == http.StatusForbidden || status == http.StatusMethodNotAllowed || status == http.StatusNotImplemented }