-
Notifications
You must be signed in to change notification settings - Fork 45
fix(server): recover from panics in RPC and UI HTTP handlers #1877
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+308
−5
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f5b2cae
fix(server): recover from panics in RPC and UI HTTP handlers
whoAbhishekSah eecc659
refactor(server): reuse pkg/errors ErrInternalServerError in panic re…
whoAbhishekSah 094eb1f
fix(server): abort committed responses instead of appending an error …
whoAbhishekSah 838970f
fix(server): extend panic recovery wrapper and cover the connect mux
whoAbhishekSah f891372
test(server): call committedWriter.ReadFrom directly
whoAbhishekSah File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| package server | ||
|
|
||
| import ( | ||
| "context" | ||
| "io" | ||
| "log/slog" | ||
| "net/http" | ||
| "runtime/debug" | ||
|
|
||
| "connectrpc.com/connect" | ||
| "github.com/raystack/frontier/pkg/errors" | ||
| ) | ||
|
|
||
| // connectPanicRecovery converts a panic anywhere in the RPC handler chain | ||
| // into a CodeInternal error response. The panic value and stack go to the | ||
| // server log only, never to the caller. | ||
| func connectPanicRecovery(logger *slog.Logger) connect.HandlerOption { | ||
| return connect.WithRecover(func(ctx context.Context, spec connect.Spec, _ http.Header, panicValue any) error { | ||
| logger.ErrorContext(ctx, "rpc handler panic", | ||
| "procedure", spec.Procedure, | ||
| "panic", panicValue, | ||
| "stack", string(debug.Stack())) | ||
| return connect.NewError(connect.CodeInternal, errors.ErrInternalServerError) | ||
| }) | ||
| } | ||
|
|
||
| // committedWriter tracks whether the response status line has gone out, so | ||
| // the recovery handler knows whether a 500 can still be sent. | ||
| type committedWriter struct { | ||
| http.ResponseWriter | ||
| committed bool | ||
| } | ||
|
|
||
| func (c *committedWriter) WriteHeader(statusCode int) { | ||
| c.committed = true | ||
| c.ResponseWriter.WriteHeader(statusCode) | ||
| } | ||
|
|
||
| func (c *committedWriter) Write(b []byte) (int, error) { | ||
| c.committed = true | ||
| return c.ResponseWriter.Write(b) | ||
| } | ||
|
|
||
| // Flush commits the response too. The connect reverse proxy on the UI server | ||
| // needs the Flusher interface for streaming. | ||
| func (c *committedWriter) Flush() { | ||
|
whoAbhishekSah marked this conversation as resolved.
|
||
| c.committed = true | ||
| if f, ok := c.ResponseWriter.(http.Flusher); ok { | ||
| f.Flush() | ||
| } | ||
| } | ||
|
|
||
| // Unwrap lets http.ResponseController reach the underlying writer's | ||
| // Hijacker, deadline, and full-duplex methods. | ||
| func (c *committedWriter) Unwrap() http.ResponseWriter { | ||
| return c.ResponseWriter | ||
| } | ||
|
|
||
| // ReadFrom keeps the underlying writer's optimized copy path (pooled | ||
| // buffers, sendfile for OS files), which io.Copy looks for on the | ||
| // destination directly without walking Unwrap. | ||
| func (c *committedWriter) ReadFrom(r io.Reader) (int64, error) { | ||
| c.committed = true | ||
| if rf, ok := c.ResponseWriter.(io.ReaderFrom); ok { | ||
| return rf.ReadFrom(r) | ||
| } | ||
| return io.Copy(c.ResponseWriter, r) | ||
| } | ||
|
|
||
| // httpPanicRecovery responds with a plain 500 instead of dropping the | ||
| // connection when a handler behind the wrapped mux panics. If the handler | ||
| // already wrote part of a response, the status can no longer be changed, so | ||
| // it aborts the connection instead of appending an error to the partial body. | ||
| func httpPanicRecovery(logger *slog.Logger, next http.Handler) http.Handler { | ||
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| cw := &committedWriter{ResponseWriter: w} | ||
| defer func() { | ||
| if panicValue := recover(); panicValue != nil { | ||
| // net/http checks for ErrAbortHandler with ==, so we should too. | ||
| if panicValue == http.ErrAbortHandler { | ||
| panic(panicValue) | ||
| } | ||
| logger.ErrorContext(r.Context(), "http handler panic", | ||
| "path", r.URL.Path, | ||
| "panic", panicValue, | ||
| "stack", string(debug.Stack())) | ||
| if cw.committed { | ||
| panic(http.ErrAbortHandler) | ||
| } | ||
| http.Error(cw, errors.ErrInternalServerError.Error(), http.StatusInternalServerError) | ||
| } | ||
| }() | ||
| next.ServeHTTP(cw, r) | ||
| }) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,203 @@ | ||
| package server | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "io" | ||
| "log/slog" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "connectrpc.com/connect" | ||
| "google.golang.org/protobuf/types/known/emptypb" | ||
| ) | ||
|
|
||
| func TestConnectPanicRecoveryReturnsInternalError(t *testing.T) { | ||
| var logBuf bytes.Buffer | ||
| logger := slog.New(slog.NewJSONHandler(&logBuf, nil)) | ||
|
|
||
| handler := connect.NewUnaryHandler( | ||
| "/test.v1.TestService/Panic", | ||
| func(ctx context.Context, req *connect.Request[emptypb.Empty]) (*connect.Response[emptypb.Empty], error) { | ||
| panic("boom") | ||
| }, | ||
| connectPanicRecovery(logger), | ||
| ) | ||
| mux := http.NewServeMux() | ||
| mux.Handle("/test.v1.TestService/Panic", handler) | ||
| srv := httptest.NewServer(mux) | ||
| defer srv.Close() | ||
|
|
||
| resp, err := http.Post(srv.URL+"/test.v1.TestService/Panic", "application/json", strings.NewReader("{}")) | ||
| if err != nil { | ||
| t.Fatalf("expected an error response, got a dropped connection: %v", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| if resp.StatusCode != http.StatusInternalServerError { | ||
| t.Errorf("status = %d, want %d", resp.StatusCode, http.StatusInternalServerError) | ||
| } | ||
| body, err := io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| t.Fatalf("read body: %v", err) | ||
| } | ||
| if !strings.Contains(string(body), `"internal"`) { | ||
| t.Errorf("body %q does not carry the internal error code", body) | ||
| } | ||
| if strings.Contains(string(body), "boom") { | ||
| t.Errorf("panic detail leaked to the client: %q", body) | ||
| } | ||
|
|
||
| logged := logBuf.String() | ||
| if !strings.Contains(logged, `"level":"ERROR"`) { | ||
| t.Errorf("panic was not logged at error level: %q", logged) | ||
| } | ||
| if !strings.Contains(logged, "boom") || !strings.Contains(logged, "/test.v1.TestService/Panic") { | ||
| t.Errorf("log entry is missing the panic value or procedure: %q", logged) | ||
| } | ||
| if !strings.Contains(logged, "recovery_test.go") { | ||
| t.Errorf("log entry is missing the stack trace: %q", logged) | ||
| } | ||
| } | ||
|
|
||
| func TestHTTPPanicRecoveryReturnsInternalError(t *testing.T) { | ||
| var logBuf bytes.Buffer | ||
| logger := slog.New(slog.NewJSONHandler(&logBuf, nil)) | ||
|
|
||
| mux := http.NewServeMux() | ||
| mux.HandleFunc("/panic", func(w http.ResponseWriter, r *http.Request) { | ||
| panic("boom") | ||
| }) | ||
|
|
||
| rec := httptest.NewRecorder() | ||
| httpPanicRecovery(logger, mux).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/panic", nil)) | ||
|
|
||
| if rec.Code != http.StatusInternalServerError { | ||
| t.Errorf("status = %d, want %d", rec.Code, http.StatusInternalServerError) | ||
| } | ||
| if strings.Contains(rec.Body.String(), "boom") { | ||
| t.Errorf("panic detail leaked to the client: %q", rec.Body.String()) | ||
| } | ||
|
|
||
| logged := logBuf.String() | ||
| if !strings.Contains(logged, `"level":"ERROR"`) || !strings.Contains(logged, "boom") || !strings.Contains(logged, "/panic") { | ||
| t.Errorf("log entry is missing the error level, panic value, or path: %q", logged) | ||
| } | ||
| } | ||
|
|
||
| func TestHTTPPanicRecoveryPassesThroughNormalRequests(t *testing.T) { | ||
| logger := slog.New(slog.NewTextHandler(io.Discard, nil)) | ||
|
|
||
| mux := http.NewServeMux() | ||
| mux.HandleFunc("/ok", func(w http.ResponseWriter, r *http.Request) { | ||
| w.WriteHeader(http.StatusTeapot) | ||
| }) | ||
|
|
||
| rec := httptest.NewRecorder() | ||
| httpPanicRecovery(logger, mux).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/ok", nil)) | ||
|
|
||
| if rec.Code != http.StatusTeapot { | ||
| t.Errorf("status = %d, want %d", rec.Code, http.StatusTeapot) | ||
| } | ||
| } | ||
|
|
||
| func TestHTTPPanicRecoveryAbortsCommittedResponses(t *testing.T) { | ||
| var logBuf bytes.Buffer | ||
| logger := slog.New(slog.NewJSONHandler(&logBuf, nil)) | ||
|
|
||
| mux := http.NewServeMux() | ||
| mux.HandleFunc("/partial", func(w http.ResponseWriter, r *http.Request) { | ||
| w.WriteHeader(http.StatusOK) | ||
| if _, err := w.Write([]byte("partial")); err != nil { | ||
| t.Fatalf("write: %v", err) | ||
| } | ||
| panic("boom") | ||
| }) | ||
|
|
||
| rec := httptest.NewRecorder() | ||
| func() { | ||
| defer func() { | ||
| if recovered := recover(); recovered != http.ErrAbortHandler { | ||
| t.Errorf("recovered %v, want http.ErrAbortHandler", recovered) | ||
| } | ||
| }() | ||
| httpPanicRecovery(logger, mux).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/partial", nil)) | ||
| }() | ||
|
|
||
| if rec.Code != http.StatusOK { | ||
| t.Errorf("status = %d, want the already-committed %d", rec.Code, http.StatusOK) | ||
| } | ||
| if rec.Body.String() != "partial" { | ||
| t.Errorf("body = %q, want the partial body with nothing appended", rec.Body.String()) | ||
| } | ||
| if !strings.Contains(logBuf.String(), "boom") { | ||
| t.Errorf("panic was not logged: %q", logBuf.String()) | ||
| } | ||
| } | ||
|
|
||
| func TestHTTPPanicRecoveryAbortsAfterFlush(t *testing.T) { | ||
| logger := slog.New(slog.NewTextHandler(io.Discard, nil)) | ||
|
|
||
| mux := http.NewServeMux() | ||
| mux.HandleFunc("/flush", func(w http.ResponseWriter, r *http.Request) { | ||
| w.(http.Flusher).Flush() | ||
| panic("boom") | ||
| }) | ||
|
|
||
| rec := httptest.NewRecorder() | ||
| func() { | ||
| defer func() { | ||
| if recovered := recover(); recovered != http.ErrAbortHandler { | ||
| t.Errorf("recovered %v, want http.ErrAbortHandler", recovered) | ||
| } | ||
| }() | ||
| httpPanicRecovery(logger, mux).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/flush", nil)) | ||
| }() | ||
|
|
||
| if strings.Contains(rec.Body.String(), "internal server error") { | ||
| t.Errorf("error body appended to a flushed response: %q", rec.Body.String()) | ||
| } | ||
| } | ||
|
|
||
| func TestCommittedWriterUnwrapReturnsUnderlyingWriter(t *testing.T) { | ||
| rec := httptest.NewRecorder() | ||
| cw := &committedWriter{ResponseWriter: rec} | ||
|
|
||
| if cw.Unwrap() != http.ResponseWriter(rec) { | ||
| t.Errorf("Unwrap() = %v, want the underlying writer", cw.Unwrap()) | ||
| } | ||
| } | ||
|
|
||
| func TestCommittedWriterReadFromCommitsAndCopies(t *testing.T) { | ||
| rec := httptest.NewRecorder() | ||
| cw := &committedWriter{ResponseWriter: rec} | ||
|
|
||
| n, err := cw.ReadFrom(strings.NewReader("data")) | ||
| if err != nil || n != 4 { | ||
| t.Fatalf("ReadFrom = (%d, %v), want (4, nil)", n, err) | ||
| } | ||
| if !cw.committed { | ||
| t.Error("ReadFrom did not mark the response as committed") | ||
| } | ||
| if rec.Body.String() != "data" { | ||
| t.Errorf("body = %q, want %q", rec.Body.String(), "data") | ||
| } | ||
| } | ||
|
|
||
| func TestHTTPPanicRecoveryRepanicsOnErrAbortHandler(t *testing.T) { | ||
| logger := slog.New(slog.NewTextHandler(io.Discard, nil)) | ||
|
|
||
| mux := http.NewServeMux() | ||
| mux.HandleFunc("/abort", func(w http.ResponseWriter, r *http.Request) { | ||
| panic(http.ErrAbortHandler) | ||
| }) | ||
|
|
||
| defer func() { | ||
| if recovered := recover(); recovered != http.ErrAbortHandler { | ||
| t.Errorf("recovered %v, want http.ErrAbortHandler", recovered) | ||
| } | ||
| }() | ||
| httpPanicRecovery(logger, mux).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/abort", nil)) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.