encode: fix response corruption when handle_errors is used (#7235)

* encode: fix response corruption when handle_errors is used

* Move disabled check before hdr assignment
This commit is contained in:
Siomachkin 2025-09-02 23:34:56 +02:00 committed by GitHub
parent 2d0f3f887b
commit 5473eb95d8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -177,7 +177,17 @@ func (enc *Encode) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyh
break break
} }
} }
return next.ServeHTTP(w, r)
err := next.ServeHTTP(w, r)
// If there was an error, disable encoding completely
// This prevents corruption when handle_errors processes the response
if err != nil {
if ew, ok := w.(*responseWriter); ok {
ew.disabled = true
}
}
return err
} }
func (enc *Encode) addEncoding(e Encoding) error { func (enc *Encode) addEncoding(e Encoding) error {
@ -233,6 +243,7 @@ type responseWriter struct {
statusCode int statusCode int
wroteHeader bool wroteHeader bool
isConnect bool isConnect bool
disabled bool // disable encoding (for error responses)
} }
// WriteHeader stores the status to write when the time comes // WriteHeader stores the status to write when the time comes
@ -425,7 +436,14 @@ func (rw *responseWriter) Unwrap() http.ResponseWriter {
// init should be called before we write a response, if rw.buf has contents. // init should be called before we write a response, if rw.buf has contents.
func (rw *responseWriter) init() { func (rw *responseWriter) init() {
// Don't initialize encoder for error responses
// This prevents response corruption when handle_errors is used
if rw.disabled {
return
}
hdr := rw.Header() hdr := rw.Header()
if hdr.Get("Content-Encoding") == "" && isEncodeAllowed(hdr) && if hdr.Get("Content-Encoding") == "" && isEncodeAllowed(hdr) &&
rw.config.Match(rw) { rw.config.Match(rw) {
rw.w = rw.config.writerPools[rw.encodingName].Get().(Encoder) rw.w = rw.config.writerPools[rw.encodingName].Get().(Encoder)