templates: avoid zero content length for bodyless responses (#8153)

* templates: avoid zero content length for bodyless responses

Drop Content-Length for HEAD and statuses that cannot carry a body instead of using the empty template buffer length. Continue setting the rendered length for ordinary responses.

AI-assisted-by: Jcode (OpenAI)

* templates: test Content-Length for HEAD, 204 and 304 responses

* templates: omit Content-Length for 2xx responses to CONNECT

RFC 9110 section 8.6 forbids Content-Length in any 2xx response to
CONNECT. Non-2xx CONNECT responses still report the rendered length.

(cherry picked from commit 401582cccf)
This commit is contained in:
a 2026-10-12 22:55:30 -05:00 • committed by Francis Lavoie
parent 7cc957cdfc
commit bded5b05e9
No known key found for this signature in database
2 changed files with 83 additions and 1 deletions

View file

@ -467,7 +467,16 @@ func (t *Templates) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddy
return err
}
rec.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
// responses without a body (HEAD, 1xx, 204, 304) can't tell us the
// length of the rendered template, so drop the header rather than
// advertising the length of the empty buffer, and a 2xx response to
// CONNECT must not have one at all (RFC 9110 §8.6)
connectSuccess := r.Method == http.MethodConnect && rec.Status() >= 200 && rec.Status() <= 299
if r.Method == http.MethodHead || connectSuccess || !bodyAllowedForStatus(rec.Status()) {
rec.Header().Del("Content-Length")
} else {
rec.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
}
rec.Header().Del("Accept-Ranges") // we don't know ranges for dynamically-created content
rec.Header().Del("Last-Modified") // useless for dynamic content since it's always changing
@ -479,6 +488,20 @@ func (t *Templates) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddy
return rec.WriteResponse()
}
// bodyAllowedForStatus reports whether a response with the given
// status may include a body, per RFC 9110 §6.4.1.
func bodyAllowedForStatus(status int) bool {
switch {
case status >= 100 && status <= 199:
return false
case status == http.StatusNoContent:
return false
case status == http.StatusNotModified:
return false
}
return true
}
// executeTemplate executes the template contained in wb.buf and replaces it with the results.
func (t *Templates) executeTemplate(rr caddyhttp.ResponseRecorder, r *http.Request) error {
var fs http.FileSystem

View file

@ -18,6 +18,7 @@ import (
"errors"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
@ -63,3 +64,61 @@ func TestServeHTTPErrorDeletesFileHeaders(t *testing.T) {
}
}
}
func TestServeHTTPContentLength(t *testing.T) {
const (
source = `{{"hello"}} world`
rendered = "hello world"
)
for _, tc := range []struct {
name string
method string
status int
wantLength string // empty means the header must be absent
wantBody string
}{
{name: "GET reports rendered length", method: http.MethodGet, status: http.StatusOK, wantLength: strconv.Itoa(len(rendered)), wantBody: rendered},
{name: "HEAD drops stale length", method: http.MethodHead, status: http.StatusOK},
{name: "204 drops stale length", method: http.MethodGet, status: http.StatusNoContent},
{name: "304 drops stale length", method: http.MethodGet, status: http.StatusNotModified},
{name: "CONNECT 200 drops stale length", method: http.MethodConnect, status: http.StatusOK},
{name: "CONNECT 407 reports rendered length", method: http.MethodConnect, status: http.StatusProxyAuthRequired, wantLength: strconv.Itoa(len(rendered)), wantBody: rendered},
} {
t.Run(tc.name, func(t *testing.T) {
// next behaves like file_server: it advertises the length of the
// unrendered template and writes a body only when one is allowed
next := caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
w.Header().Set("Content-Type", "text/html")
w.Header().Set("Content-Length", strconv.Itoa(len(source)))
w.WriteHeader(tc.status)
if tc.wantBody != "" {
_, err := w.Write([]byte(source))
return err
}
return nil
})
tmpl := &Templates{MIMETypes: []string{"text/html"}}
rec := httptest.NewRecorder()
req := httptest.NewRequest(tc.method, "/", nil)
if err := tmpl.ServeHTTP(rec, req, next); err != nil {
t.Fatalf("ServeHTTP: %v", err)
}
if rec.Code != tc.status {
t.Errorf("expected status %d, got %d", tc.status, rec.Code)
}
gotLength, ok := rec.Header()["Content-Length"]
switch {
case tc.wantLength == "" && ok:
t.Errorf("expected no Content-Length, got %q", gotLength)
case tc.wantLength != "" && rec.Header().Get("Content-Length") != tc.wantLength:
t.Errorf("expected Content-Length %q, got %q", tc.wantLength, rec.Header().Get("Content-Length"))
}
if body := rec.Body.String(); body != tc.wantBody {
t.Errorf("expected body %q, got %q", tc.wantBody, body)
}
})
}
}