diff --git a/modules/caddyhttp/fileserver/staticfiles.go b/modules/caddyhttp/fileserver/staticfiles.go index d1346c91f..25a4af1e4 100644 --- a/modules/caddyhttp/fileserver/staticfiles.go +++ b/modules/caddyhttp/fileserver/staticfiles.go @@ -473,6 +473,8 @@ func (fsrv *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request, next c } var file fs.File + var sidecarEncoding string + var sidecarSize int64 respHeader := w.Header() // etag is usually unset, but if the user knows what they're doing, let them override it @@ -517,15 +519,12 @@ func (fsrv *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request, next c continue } defer file.Close() - respHeader.Set("Content-Encoding", ae) - // stdlib won't set Content-Length for non-range requests if Content-Encoding is set. - // see: https://github.com/caddyserver/caddy/issues/7040 - // Setting the Range header manually will result in 206 Partial Content. - // see: https://github.com/caddyserver/caddy/issues/7250 - if r.Header.Get("Range") == "" { - respHeader.Set("Content-Length", strconv.FormatInt(compressedInfo.Size(), 10)) - } + // remember the sidecar's encoding and size, but don't set the + // headers until we can no longer return an error, or they would + // end up on the error response + sidecarEncoding = ae + sidecarSize = compressedInfo.Size() // try to get the etag from pre computed files if an etag suffix list was provided if etag == "" && fsrv.EtagFileExtensions != nil { @@ -625,6 +624,20 @@ func (fsrv *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request, next c } } + // there are no more error returns below this point, so it is now safe + // to describe the precompressed sidecar we are about to serve + if sidecarEncoding != "" { + respHeader.Set("Content-Encoding", sidecarEncoding) + + // stdlib won't set Content-Length for non-range requests if Content-Encoding is set. + // see: https://github.com/caddyserver/caddy/issues/7040 + // Setting the Range header manually will result in 206 Partial Content. + // see: https://github.com/caddyserver/caddy/issues/7250 + if r.Header.Get("Range") == "" { + respHeader.Set("Content-Length", strconv.FormatInt(sidecarSize, 10)) + } + } + // if we do have an override from the previous two parts, then // we wrap the response writer to intercept the WriteHeader call if statusCodeOverride > 0 { diff --git a/modules/caddyhttp/fileserver/staticfiles_test.go b/modules/caddyhttp/fileserver/staticfiles_test.go index e7c942f07..cf42e658d 100644 --- a/modules/caddyhttp/fileserver/staticfiles_test.go +++ b/modules/caddyhttp/fileserver/staticfiles_test.go @@ -407,6 +407,96 @@ func TestPrecompressedRangeResponse(t *testing.T) { }) } +// Once a precompressed sidecar is chosen, every error the handler can +// still return must not carry the sidecar's Content-Encoding and +// Content-Length, since the error response has a different body. +func TestPrecompressedErrorResponseHeaders(t *testing.T) { + for _, tc := range []struct { + name string + method string + target string + etagFileDir bool + statusCode caddyhttp.WeakString + wantHTTPCode int // 0 if the error is not a HandlerError + }{ + { + name: "method not allowed", + method: http.MethodPost, + target: "/f.txt", + wantHTTPCode: http.StatusMethodNotAllowed, + }, + { + name: "unreadable etag file for sidecar", + method: http.MethodGet, + target: "/f.txt", + etagFileDir: true, + }, + { + name: "invalid status code", + method: http.MethodGet, + target: "/f.txt?code=abc", + statusCode: "{http.request.uri.query.code}", + wantHTTPCode: http.StatusInternalServerError, + }, + } { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + body := []byte("original response body") + if err := os.WriteFile(filepath.Join(root, "f.txt"), body, 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "f.txt.gz"), gzipBytes(t, body), 0o600); err != nil { + t.Fatal(err) + } + var etagExts []string + if tc.etagFileDir { + // a directory where the etag file should be makes reading it fail + if err := os.Mkdir(filepath.Join(root, "f.txt.gz.etag"), 0o700); err != nil { + t.Fatal(err) + } + etagExts = []string{".etag"} + } + + fsrv := FileServer{ + Root: root, + CanonicalURIs: new(bool), + PrecompressedOrder: []string{"gzip"}, + EtagFileExtensions: etagExts, + StatusCode: tc.statusCode, + } + ctx, _ := caddy.NewContext(caddy.Context{Context: context.Background()}) + if err := fsrv.Provision(ctx); err != nil { + t.Fatal(err) + } + fsrv.precompressors = map[string]encode.Precompressed{ + "gzip": testPrecompressed{encoding: "gzip", suffix: ".gz"}, + } + + r := httptest.NewRequest(tc.method, tc.target, nil) + repl := caddyhttp.NewTestReplacer(r) + r = r.WithContext(context.WithValue(r.Context(), caddy.ReplacerCtxKey, repl)) + r.Header.Set("Accept-Encoding", "gzip") + w := httptest.NewRecorder() + + err := fsrv.ServeHTTP(w, r, nil) + if err == nil { + t.Fatal("expected an error") + } + if tc.wantHTTPCode != 0 { + var herr caddyhttp.HandlerError + if !errors.As(err, &herr) || herr.StatusCode != tc.wantHTTPCode { + t.Fatalf("error = %v, want HTTP %d", err, tc.wantHTTPCode) + } + } + for _, field := range []string{"Content-Encoding", "Content-Length"} { + if got := w.Header().Get(field); got != "" { + t.Errorf("%s = %q on the error response, want it unset", field, got) + } + } + }) + } +} + func gzipBytes(t *testing.T, data []byte) []byte { t.Helper()