diff --git a/echo.go b/echo.go index 7c8541d2a..5181ec381 100644 --- a/echo.go +++ b/echo.go @@ -452,6 +452,17 @@ func (e *Echo) Router() Router { return e.router } +// clearRepresentationHeaders removes headers that described the body the handler +// meant to send and are wrong for the error body that replaces it. A middleware +// that encodes the error body sets its own Content-Encoding. Content-Type and +// validators such as ETag are kept because they can be meant for the error +// response, for example a vendor media type or a 304. +func clearRepresentationHeaders(h http.Header) { + h.Del(HeaderContentEncoding) + h.Del(HeaderContentLength) + h.Del(HeaderContentDisposition) +} + // DefaultHTTPErrorHandler creates new default HTTP error handler implementation. It sends a JSON response // with status code. `exposeError` parameter decides if returned message will contain also error message or not // @@ -498,6 +509,8 @@ func DefaultHTTPErrorHandler(exposeError bool) HTTPErrorHandler { result = msg } + clearRepresentationHeaders(c.Response().Header()) + var cErr error if c.Request().Method == http.MethodHead { // Issue #608 cErr = c.NoContent(code) diff --git a/echo_test.go b/echo_test.go index dda5be7ca..86c98ba4f 100644 --- a/echo_test.go +++ b/echo_test.go @@ -1452,6 +1452,64 @@ func TestDefaultHTTPErrorHandler(t *testing.T) { } } +func TestHTTPErrorHandlers_ClearRepresentationHeaders(t *testing.T) { + handlers := map[string]struct { + handler HTTPErrorHandler + contentType string + }{ + "default": {DefaultHTTPErrorHandler(false), MIMEApplicationJSON}, + "problem details": {ProblemDetailsHTTPErrorHandler(false), MIMEApplicationProblemJSON}, + } + for name, tt := range handlers { + t.Run(name, func(t *testing.T) { + e := New() + e.HTTPErrorHandler = tt.handler + e.GET("/", func(c *Context) error { + h := c.Response().Header() + h.Set(HeaderContentEncoding, "br") + h.Set(HeaderContentLength, "5000") + h.Set(HeaderContentDisposition, `attachment; filename="report.csv"`) + h.Set("ETag", `"v1"`) + return ErrNotFound + }) + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + + assert.Equal(t, http.StatusNotFound, rec.Code) + for _, name := range []string{HeaderContentEncoding, HeaderContentLength, HeaderContentDisposition} { + assert.Empty(t, rec.Header().Get(name), name) + } + assert.Equal(t, tt.contentType, rec.Header().Get(HeaderContentType)) + assert.Equal(t, `"v1"`, rec.Header().Get("ETag")) + }) + } +} + +type encodingResponseWriter struct { + http.ResponseWriter +} + +func (w *encodingResponseWriter) Unwrap() http.ResponseWriter { + return w.ResponseWriter +} + +func TestDefaultHTTPErrorHandler_ClearsEncodingOfWrappedResponse(t *testing.T) { + e := New() + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + c := e.NewContext(req, rec) + c.SetResponse(&encodingResponseWriter{ResponseWriter: c.Response()}) + c.Response().Header().Set(HeaderContentEncoding, "gzip") + c.Response().Header().Set(HeaderContentLength, "5000") + + DefaultHTTPErrorHandler(false)(c, ErrNotFound) + + assert.Equal(t, http.StatusNotFound, rec.Code) + assert.Empty(t, rec.Header().Get(HeaderContentEncoding)) + assert.Empty(t, rec.Header().Get(HeaderContentLength)) +} + func TestDefaultHTTPErrorHandler_CommitedResponse(t *testing.T) { e := New() req := httptest.NewRequest(http.MethodGet, "/", nil) diff --git a/middleware/compress.go b/middleware/compress.go index b551b6ce6..28ddbeeeb 100644 --- a/middleware/compress.go +++ b/middleware/compress.go @@ -156,6 +156,11 @@ func (config GzipConfig) ToMiddleware() (echo.MiddlewareFunc, error) { } func (w *gzipResponseWriter) WriteHeader(code int) { + if code >= 100 && code < 200 && code != http.StatusSwitchingProtocols { + // Informational responses precede the final status and are never compressed. + w.ResponseWriter.WriteHeader(code) + return + } if w.passthrough { w.ResponseWriter.WriteHeader(code) return @@ -202,14 +207,7 @@ func (w *gzipResponseWriter) Write(b []byte) (int, error) { func (w *gzipResponseWriter) Flush() { if w.passThroughIfEncoded() { - if !w.wroteHeader { - // Commit through echo.Response so the error handler sees the response as written. - w.wroteHeader = true - w.code = http.StatusOK - if r, err := echo.UnwrapResponse(w.ResponseWriter); err == nil && !r.Committed { - r.WriteHeader(http.StatusOK) - } - } + // echo.Response.Flush commits the status if nothing was written yet. _ = http.NewResponseController(w.ResponseWriter).Flush() return } diff --git a/middleware/compress_test.go b/middleware/compress_test.go index 7b5794e31..96ef66891 100644 --- a/middleware/compress_test.go +++ b/middleware/compress_test.go @@ -6,10 +6,13 @@ package middleware import ( "bytes" "compress/gzip" + "context" "fmt" "io" "net/http" "net/http/httptest" + "net/http/httptrace" + "net/textproto" "os" "strconv" "strings" @@ -347,6 +350,43 @@ func TestGzip_PassthroughFlushCommitsResponse(t *testing.T) { assert.Empty(t, rec.Body.String()) } +func TestGzip_ForwardsInformationalStatus(t *testing.T) { + e := echo.New() + e.Use(Gzip()) + e.GET("/", func(c *echo.Context) error { + c.Response().Header().Set("Link", "; rel=preload; as=style") + c.Response().WriteHeader(http.StatusEarlyHints) + return c.String(http.StatusCreated, "ok") + }) + srv := httptest.NewServer(e) + defer srv.Close() + + var informational []int + trace := &httptrace.ClientTrace{ + Got1xxResponse: func(code int, _ textproto.MIMEHeader) error { + informational = append(informational, code) + return nil + }, + } + req, err := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), http.MethodGet, srv.URL, nil) + require.NoError(t, err) + req.Header.Set(echo.HeaderAcceptEncoding, gzipScheme) + tr := &http.Transport{DisableCompression: true} + defer tr.CloseIdleConnections() + res, err := tr.RoundTrip(req) + require.NoError(t, err) + defer res.Body.Close() + + assert.Equal(t, []int{http.StatusEarlyHints}, informational) + assert.Equal(t, http.StatusCreated, res.StatusCode) + reader, err := gzip.NewReader(res.Body) + require.NoError(t, err) + defer reader.Close() + body, err := io.ReadAll(reader) + require.NoError(t, err) + assert.Equal(t, "ok", string(body)) +} + func TestGzip_FlushWithoutWriteProducesValidStream(t *testing.T) { e := echo.New() e.Use(Gzip()) diff --git a/response.go b/response.go index e218ef4d6..e6adea77c 100644 --- a/response.go +++ b/response.go @@ -52,6 +52,11 @@ func (r *Response) WriteHeader(code int) { r.logger.Error("echo: response already written to client") return } + if isInformationalStatus(code) { + // Informational responses precede the final status and do not commit the response. + r.ResponseWriter.WriteHeader(code) + return + } r.Status = code for _, fn := range r.beforeFuncs { fn() @@ -80,6 +85,16 @@ func (r *Response) Write(b []byte) (n int, err error) { // buffered data to the client. // See [http.Flusher](https://golang.org/pkg/net/http/#Flusher) func (r *Response) Flush() { + if !r.Committed { + if !supportsFlush(r.ResponseWriter) { + panic(fmt.Errorf("echo: response writer %T does not support flushing (http.Flusher interface)", r.ResponseWriter)) + } + // Flushing sends the headers, so commit them the same way Write does. + if r.Status == 0 { + r.Status = http.StatusOK + } + r.WriteHeader(r.Status) + } err := http.NewResponseController(r.ResponseWriter).Flush() if err != nil && errors.Is(err, http.ErrNotSupported) { panic(fmt.Errorf("echo: response writer %T does not support flushing (http.Flusher interface)", r.ResponseWriter)) @@ -132,6 +147,32 @@ func UnwrapResponse(rw http.ResponseWriter) (*Response, error) { } } +// isInformationalStatus reports whether code is a 1xx status that precedes the final one. +// 101 Switching Protocols is final. +func isInformationalStatus(code int) bool { + return code >= 100 && code < 200 && code != http.StatusSwitchingProtocols +} + +// supportsFlush reports whether http.ResponseController can flush rw. It uses +// the same lookup, except that *Response is skipped because its Flush only +// delegates to the writer it wraps. +func supportsFlush(rw http.ResponseWriter) bool { + for { + if r, ok := rw.(*Response); ok { + rw = r.ResponseWriter + continue + } + switch t := rw.(type) { + case interface{ FlushError() error }, http.Flusher: + return true + case interface{ Unwrap() http.ResponseWriter }: + rw = t.Unwrap() + default: + return false + } + } +} + // delayedStatusWriter is a wrapper around http.ResponseWriter that delays writing the status code until first Write is called. // This allows (global) error handler to decide correct status code to be sent to the client. type delayedStatusWriter struct { @@ -141,6 +182,10 @@ type delayedStatusWriter struct { } func (w *delayedStatusWriter) WriteHeader(statusCode int) { + if isInformationalStatus(statusCode) { + w.ResponseWriter.WriteHeader(statusCode) + return + } // in case something else writes status code explicitly before us we need mark response committed w.committed = true w.ResponseWriter.WriteHeader(statusCode) @@ -158,6 +203,14 @@ func (w *delayedStatusWriter) Write(data []byte) (int, error) { } func (w *delayedStatusWriter) Flush() { + if !w.committed && supportsFlush(w.ResponseWriter) { + // Flushing sends the headers, so send the delayed status first. + w.committed = true + if w.status == 0 { + w.status = http.StatusOK + } + w.ResponseWriter.WriteHeader(w.status) + } err := http.NewResponseController(w.ResponseWriter).Flush() if err != nil && errors.Is(err, http.ErrNotSupported) { panic(errors.New("response writer flushing is not supported")) @@ -197,6 +250,10 @@ func (w *headResponseWriter) WriteHeader(code int) { if w.wroteStatus { return } + if isInformationalStatus(code) { + w.rw.WriteHeader(code) + return + } w.wroteStatus = true w.status = code if r, err := UnwrapResponse(w.rw); err == nil { diff --git a/response_test.go b/response_test.go index 4ad849c04..2caac2577 100644 --- a/response_test.go +++ b/response_test.go @@ -4,12 +4,17 @@ package echo import ( + "context" "fmt" + "io" "net/http" "net/http/httptest" + "net/http/httptrace" + "net/textproto" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestResponse(t *testing.T) { @@ -421,3 +426,156 @@ func TestWrapHeadHandler_RouteLevelMiddlewareSeesTrueCommitted(t *testing.T) { assert.NoError(t, wrapped(c)) assert.True(t, committedAfterHandler) } + +func TestResponse_Flush_CommitsResponse(t *testing.T) { + e := New() + rec := httptest.NewRecorder() + res := NewResponse(rec, e.Logger) + beforeCalled := false + res.Before(func() { + beforeCalled = true + res.Header().Set("X-Before", "1") + }) + + res.Flush() + + assert.True(t, res.Committed) + assert.True(t, beforeCalled) + assert.Equal(t, http.StatusOK, res.Status) + assert.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, "1", rec.Header().Get("X-Before")) + assert.True(t, rec.Flushed) +} + +func TestResponse_Flush_ErrorHandlerSkipsCommittedResponse(t *testing.T) { + e := New() + e.GET("/", func(c *Context) error { + if err := http.NewResponseController(c.Response()).Flush(); err != nil { + return err + } + return ErrBadRequest + }) + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + + assert.Equal(t, http.StatusOK, rec.Code) + assert.Empty(t, rec.Body.String()) +} + +func TestResponse_WriteHeader_Informational(t *testing.T) { + e := New() + srv := httptest.NewServer(e) + defer srv.Close() + + var status int + var committedAfter1xx bool + e.GET("/", func(c *Context) error { + c.Response().Header().Set("Link", "; rel=preload; as=style") + c.Response().WriteHeader(http.StatusEarlyHints) + r, err := UnwrapResponse(c.Response()) + if err != nil { + return err + } + committedAfter1xx = r.Committed + err = c.String(http.StatusCreated, "ok") + status = r.Status + return err + }) + + var informational []int + trace := &httptrace.ClientTrace{ + Got1xxResponse: func(code int, _ textproto.MIMEHeader) error { + informational = append(informational, code) + return nil + }, + } + req, err := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), http.MethodGet, srv.URL, nil) + require.NoError(t, err) + res, err := http.DefaultClient.Do(req) + require.NoError(t, err) + defer res.Body.Close() + body, err := io.ReadAll(res.Body) + require.NoError(t, err) + + assert.Equal(t, []int{http.StatusEarlyHints}, informational) + assert.False(t, committedAfter1xx) + assert.Equal(t, http.StatusCreated, res.StatusCode) + assert.Equal(t, "ok", string(body)) + assert.Equal(t, http.StatusCreated, status) +} + +func TestResponse_Flush_PanicsBeforeCommit(t *testing.T) { + e := New() + res := NewResponse(new(testResponseWriter), e.Logger) + beforeCalled := false + res.Before(func() { beforeCalled = true }) + + assert.Panics(t, func() { res.Flush() }) + assert.False(t, res.Committed) + assert.False(t, beforeCalled) +} + +func TestHeadResponseWriter_WriteHeader_Informational(t *testing.T) { + e := New() + rec := httptest.NewRecorder() + res := NewResponse(rec, e.Logger) + w := &headResponseWriter{rw: res} + + w.WriteHeader(http.StatusEarlyHints) + assert.False(t, w.wroteStatus) + assert.False(t, res.Committed) + + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte("ok")) + w.commit() + + assert.Equal(t, http.StatusCreated, res.Status) + assert.Equal(t, "2", rec.Header().Get(HeaderContentLength)) +} + +func TestDelayedStatusWriter_Flush_SendsDelayedStatus(t *testing.T) { + e := New() + rec := httptest.NewRecorder() + res := NewResponse(rec, e.Logger) + w := &delayedStatusWriter{ResponseWriter: res, status: http.StatusCreated} + + w.WriteHeader(http.StatusEarlyHints) + assert.False(t, w.committed) + w.Flush() + _, _ = w.Write([]byte("ok")) + + // httptest.ResponseRecorder keeps the first status it sees, including 1xx, so check Response. + assert.Equal(t, http.StatusCreated, res.Status) + assert.True(t, res.Committed) + assert.True(t, rec.Flushed) +} + +func TestDelayedStatusWriter_Flush_PanicsBeforeCommit(t *testing.T) { + e := New() + res := NewResponse(new(testResponseWriter), e.Logger) + w := &delayedStatusWriter{ResponseWriter: res, status: http.StatusCreated} + + assert.Panics(t, func() { w.Flush() }) + assert.False(t, w.committed) + assert.False(t, res.Committed) +} + +type flushingWrapper struct { + http.ResponseWriter + flushed bool +} + +func (w *flushingWrapper) Flush() { w.flushed = true } + +func (w *flushingWrapper) Unwrap() http.ResponseWriter { return w.ResponseWriter } + +func TestResponse_Flush_UsesWrapperFlush(t *testing.T) { + e := New() + w := &flushingWrapper{ResponseWriter: new(testResponseWriter)} + res := NewResponse(w, e.Logger) + + assert.NotPanics(t, func() { res.Flush() }) + assert.True(t, w.flushed) + assert.True(t, res.Committed) +} diff --git a/rfc9457.go b/rfc9457.go index 2719b536e..a4df58a71 100644 --- a/rfc9457.go +++ b/rfc9457.go @@ -118,6 +118,7 @@ func ProblemDetailsHTTPErrorHandler(exposeError bool) HTTPErrorHandler { problem.Title = http.StatusText(problem.Status) } + clearRepresentationHeaders(c.Response().Header()) c.Response().Header().Set(HeaderContentType, MIMEApplicationProblemJSON) var cErr error