-
Notifications
You must be signed in to change notification settings - Fork 13
feature: do not raise 500's on bad request #255
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
Merged
Changes from all commits
Commits
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,52 @@ | ||
| package handler | ||
|
|
||
| import ( | ||
| "errors" | ||
| "io" | ||
| "log/slog" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "strings" | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestHandleError_WritesBodyAndHeaders(t *testing.T) { | ||
| cases := []struct { | ||
| name string | ||
| debugMode bool | ||
| wantBody string // substring match (http.Error appends a trailing newline) | ||
| }{ | ||
| {name: "non-debug uses StatusText", debugMode: false, wantBody: http.StatusText(http.StatusInternalServerError)}, | ||
| {name: "debug exposes error message", debugMode: true, wantBody: "boom"}, | ||
| } | ||
|
|
||
| for _, tc := range cases { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| h := &Handler{ | ||
| log: slog.New(slog.NewTextHandler(io.Discard, nil)), | ||
| internalHTTPCode: http.StatusInternalServerError, | ||
| debugMode: tc.debugMode, | ||
| } | ||
| rec := httptest.NewRecorder() | ||
|
|
||
| h.handleError(rec, errors.New("boom")) | ||
|
|
||
| resp := rec.Result() | ||
| defer func() { _ = resp.Body.Close() }() | ||
|
|
||
| if resp.StatusCode != http.StatusInternalServerError { | ||
| t.Errorf("status: got %d, want %d", resp.StatusCode, http.StatusInternalServerError) | ||
| } | ||
| if ct := resp.Header.Get("Content-Type"); !strings.HasPrefix(ct, "text/plain") { | ||
| t.Errorf("Content-Type: got %q, want text/plain prefix", ct) | ||
| } | ||
| if nosniff := resp.Header.Get("X-Content-Type-Options"); nosniff != "nosniff" { | ||
| t.Errorf("X-Content-Type-Options: got %q, want nosniff", nosniff) | ||
| } | ||
| body, _ := io.ReadAll(resp.Body) | ||
| if !strings.Contains(string(body), tc.wantBody) { | ||
| t.Errorf("body: got %q, want substring %q", body, tc.wantBody) | ||
| } | ||
| }) | ||
| } | ||
| } |
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
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
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,41 @@ | ||
| package handler | ||
|
|
||
| import ( | ||
| "errors" | ||
| "mime/multipart" | ||
| "net/http" | ||
| ) | ||
|
|
||
| // statusError carries an explicit HTTP status code through an error chain. | ||
| // Call sites that know the correct response code wrap with withStatus; | ||
| // handleRequestErr unwraps via errors.As so the wrapped status wins over | ||
|
rustatian marked this conversation as resolved.
|
||
| // the default 4xx classification. | ||
| type statusError struct { | ||
| status int | ||
| err error | ||
| } | ||
|
|
||
| func (e *statusError) Error() string { return e.err.Error() } | ||
| func (e *statusError) Unwrap() error { return e.err } | ||
| func (e *statusError) Status() int { return e.status } | ||
|
|
||
| func withStatus(status int, err error) error { | ||
| if err == nil { | ||
| return nil | ||
| } | ||
| return &statusError{status: status, err: err} | ||
| } | ||
|
|
||
| // classifyParseErr promotes payload-size errors (*http.MaxBytesError and | ||
| // multipart.ErrMessageTooLarge) to 413 by wrapping with withStatus. Other | ||
| // errors pass through unchanged so they hit handleRequestErr's 400 default — | ||
| // every error reaching this helper originates from parsing client input. | ||
| func classifyParseErr(err error) error { | ||
| if err == nil { | ||
| return nil | ||
| } | ||
| if _, ok := errors.AsType[*http.MaxBytesError](err); ok || errors.Is(err, multipart.ErrMessageTooLarge) { | ||
| return withStatus(http.StatusRequestEntityTooLarge, err) | ||
| } | ||
| return err | ||
| } | ||
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,72 @@ | ||
| package handler | ||
|
|
||
| import ( | ||
| "errors" | ||
| "mime/multipart" | ||
| "net/http" | ||
| "testing" | ||
| ) | ||
|
|
||
| func TestStatusError_Wrapping(t *testing.T) { | ||
| base := errors.New("boom") | ||
| wrapped := withStatus(http.StatusTeapot, base) | ||
|
|
||
| if wrapped.Error() != "boom" { | ||
| t.Fatalf("Error(): got %q, want %q", wrapped.Error(), "boom") | ||
| } | ||
|
|
||
| sErr, ok := errors.AsType[*statusError](wrapped) | ||
| if !ok { | ||
| t.Fatal("errors.AsType[*statusError] failed") | ||
| } | ||
| if sErr.Status() != http.StatusTeapot { | ||
| t.Errorf("Status(): got %d, want %d", sErr.Status(), http.StatusTeapot) | ||
| } | ||
| if !errors.Is(wrapped, base) { | ||
| t.Error("errors.Is should unwrap to the base error") | ||
| } | ||
| } | ||
|
|
||
| func TestStatusError_WithStatusNil(t *testing.T) { | ||
| if got := withStatus(http.StatusBadRequest, nil); got != nil { | ||
| t.Errorf("withStatus(_, nil): got %v, want nil", got) | ||
| } | ||
| } | ||
|
|
||
| func TestClassifyParseErr(t *testing.T) { | ||
| t.Run("nil passthrough", func(t *testing.T) { | ||
| if got := classifyParseErr(nil); got != nil { | ||
| t.Errorf("got %v, want nil", got) | ||
| } | ||
| }) | ||
|
|
||
| t.Run("MaxBytesError promotes to 413", func(t *testing.T) { | ||
| err := classifyParseErr(&http.MaxBytesError{Limit: 1024}) | ||
| sErr, ok := errors.AsType[*statusError](err) | ||
| if !ok || sErr.Status() != http.StatusRequestEntityTooLarge { | ||
| t.Errorf("got %v, want 413 wrapper", err) | ||
| } | ||
| }) | ||
|
|
||
| t.Run("ErrMessageTooLarge promotes to 413", func(t *testing.T) { | ||
| err := classifyParseErr(multipart.ErrMessageTooLarge) | ||
| sErr, ok := errors.AsType[*statusError](err) | ||
| if !ok || sErr.Status() != http.StatusRequestEntityTooLarge { | ||
| t.Errorf("got %v, want 413 wrapper", err) | ||
| } | ||
| }) | ||
|
|
||
| t.Run("unknown error passes through unwrapped", func(t *testing.T) { | ||
| // "invalid semicolon separator in query" is a plain errors.New from | ||
| // url.ParseQuery — by passing through (no statusError wrapper), it | ||
| // lands on handleRequestErr's 400 default. Protects issue #2353. | ||
| base := errors.New("invalid semicolon separator in query") | ||
| got := classifyParseErr(base) | ||
| if !errors.Is(got, base) { | ||
| t.Errorf("expected base error preserved in chain; got %v", got) | ||
| } | ||
| if _, ok := errors.AsType[*statusError](got); ok { | ||
| t.Error("plain errors must not be wrapped with a status") | ||
| } | ||
| }) | ||
| } |
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
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.