From 878238dc548e77d1d021ef28547d0fe1ad1551d6 Mon Sep 17 00:00:00 2001 From: Josue Giron Date: Sat, 21 Nov 2026 19:54:53 +0000 Subject: [PATCH] fix(api): re-panic aborts and guard a nil formatted response Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- docs/adr/0001-v1-instance-api.md | 2 +- instance.go | 47 +++++++++--------- instance_log.go | 23 +++++++-- instance_log_test.go | 80 +++++++++++++++++++++++++------ instance_max_body_test.go | 31 ++++++++++++ instance_test.go | 8 ---- middlewares.go | 7 +++ middlewares_abort_test.go | 81 ++++++++++++++++++++++++++++++++ response.go | 9 ++-- 10 files changed, 237 insertions(+), 55 deletions(-) create mode 100644 middlewares_abort_test.go diff --git a/README.md b/README.md index 6d972ba..e2e4790 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ func main() { - reads the body and parses it according to the [request mode](#request-and-response-modes); an invalid JSON body answers 400 with code `E002`, and a body over 10 MiB answers 413 (see [Security notes](#security-notes)); - collects request metadata from HTTP headers (see [Reading the request](#reading-the-request)); - assigns an [event ID](#trace-ids) and logs the request and the response (on an `api.New` instance only through its `api.WithLogger` logger, and nothing without one; on the default instance through `slog.Default`; see [Logging](#logging)); - - stores the request context, replaces `r.Body` with the endpoint content, and answers 500 if the handler panics. + - stores the request context, replaces `r.Body` with the endpoint content, and answers 500 if the handler panics (a panic with `http.ErrAbortHandler` is re-panicked, so `net/http` aborts the response). Use `api.MiddlewaresChain(...)` to compose it with your own middlewares. `api.AddSkipPath(api.GenSkipPath(method, path), true)` makes it pass a route through untouched. 3. **The handler** reads the content, then writes one [response](#responses) or [error](#writing-errors). @@ -264,7 +264,7 @@ a := api.New( // {"level":"INFO","msg":"request","event_id":"…","method":"GET","uri":"/login?access_token=[REDACTED]&page=2","headers":{"Pin":["[REDACTED]"]}} ``` -`api.ProcessRequest` writes a `request` record (`event_id`, `method`, `uri`, `headers`) and a `response` record (`event_id`, `method`, `uri`, `status`, `status_text`, `duration_ms`) at info level. A rejected body, a failed `Get*Value*`/`UnmarshalBody` helper, a recovered panic (`panic recovered`) and a response that cannot be encoded are error records with an `error` or `panic` attribute; a panic with `http.ErrAbortHandler` is a `handler aborted` debug record. A panic record always has `panic_type`, the Go type of the value (`string`, `*errors.errorString`, `runtime.boundsError`); its `panic` is the value only for a `runtime.Error` (nil map write, index out of range), which carries no request data, and `[REDACTED]` for any other value, which may. A failed `Get*Value*` helper adds the name as `key`; for a sensitive name its `error` is only the kind (`invalid syntax`, `value out of range`, `invalid value`), never the value. A response that cannot be encoded (for example a `NaN` in the content) is answered with the `Error500()` body instead; the writer gets no request, so its records carry no request context or `event_id`. Bodies and the parsed form are never logged (query values appear only in `uri`). Header values with a sensitive name, query values in `uri` and in other header values (after each `?`), and the user information of the `uri` and of URL-valued headers are masked (see [Security notes](#security-notes)); secrets in path segments are not masked. The sensitive keys are the default list (`authorization`, `token`, `password`, `secret`, `credential`, `apikey`, `api-key`, `key`, `cookie`, `session`) plus the keys of `api.WithSensitiveLogKeys`, which can only add. `ExampleWithLogger` is the compiled version. +`api.ProcessRequest` writes a `request` record (`event_id`, `method`, `uri`, `headers`) and a `response` record (`event_id`, `method`, `uri`, `status`, `status_text`, `duration_ms`) at info level. A rejected body, a failed `Get*Value*`/`UnmarshalBody` helper, a recovered panic (`panic recovered`) and a response that cannot be encoded are error records with an `error` or `panic` attribute; a panic with `http.ErrAbortHandler`, plain or wrapped, is a `handler aborted` debug record and is re-panicked as the plain `http.ErrAbortHandler`, so `net/http` aborts the response without logging it; nothing is written and there is no `response` record (nor after any other recovered panic). A panic record always has `panic_type`, the Go type of the value (`string`, `*errors.errorString`, `runtime.boundsError`); its `panic` is the value only for a `runtime.Error` (nil map write, index out of range), which carries no request data, and `[REDACTED]` for any other value, which may. A failed `Get*Value*` helper adds the name as `key`; for a sensitive name its `error` is only the kind (`invalid syntax`, `value out of range`, `invalid value`), never the value. A response that cannot be encoded (for example a `NaN` in the content) is answered with the `Error500()` body instead; so is a nil formatted response (a custom formatter that returned nil), logged as `response cannot be written` with `error` `nil formatted response`; the writer gets no request, so its records carry no request context or `event_id`. Bodies and the parsed form are never logged (query values appear only in `uri`). Header values with a sensitive name, query values in `uri` and in other header values (after each `?`), and the user information of the `uri` and of URL-valued headers are masked (see [Security notes](#security-notes)); secrets in path segments are not masked. The sensitive keys are the default list (`authorization`, `token`, `password`, `secret`, `credential`, `apikey`, `api-key`, `key`, `cookie`, `session`) plus the keys of `api.WithSensitiveLogKeys`, which can only add. `ExampleWithLogger` is the compiled version. Since v1.0.0 the default instance writes the same records through `slog.Default()`, read at call time (route them with `slog.SetDefault`). Its sensitive keys are the default list plus `api.SensitiveLogKeys`, which can add keys but no longer remove a default one. Neither calls `api.Fatal`: a response that cannot be encoded is answered with 500. The package no longer calls `api.Print` or `api.PrintError` (only the deprecated `api.LogRequest`, `api.LogResponse` and `api.LogResponseWithDuration` call `api.Print`). `api.Print`, `api.PrintError`, `api.Fatal`, `api.SensitiveLogKeys` and the `api.Log*` functions are deprecated in favor of the options; `api.LogRequestBody`, `api.LogResponseBody`, `api.PrintFullEvent` and `api.MaxLoggedBodyBytes` are deprecated too: they affect only the deprecated `api.Log*` functions, since bodies are never logged. diff --git a/docs/adr/0001-v1-instance-api.md b/docs/adr/0001-v1-instance-api.md index a4dc2e9..ab97cf2 100644 --- a/docs/adr/0001-v1-instance-api.md +++ b/docs/adr/0001-v1-instance-api.md @@ -114,7 +114,7 @@ sequenceDiagram - An instance without `WithLogger` writes no logs. - With the built-in writer, an instance never calls `Fatal` and never exits: a response that cannot be encoded is logged at error level through the instance logger. Since v0.11.0 (#46) the default instance does not call `Fatal` either: it reports the failure through `PrintError` and answers 500. *(Superseded by Amendment 1: the default instance logs it through `slog.Default`, not `PrintError`.)* - `WithSensitiveLogKeys(keys...)` adds keys to the default list; it cannot remove a default key (security defaults are not weakened). -- As landed in 5.5: `ProcessRequest` writes two info records, `request` (`event_id`, `method`, `uri`, `headers`) and `response` (`event_id`, `method`, `uri`, `status`, `status_text`, `duration_ms`). Errors met while serving a request (a rejected body in `ProcessRequest`/`RequestBody`, a failed `Get*Value*`/`UnmarshalBody` helper) are error records with an `error` attribute; a `Get*Value*` record adds the name as `key` and, for a sensitive name, gives only the kind of error (`invalid syntax`, `value out of range`, `invalid value`), never the value. A recovered panic is a `panic recovered` error record with exactly the panic value and `event_id`, never a dump of the request; a panic with `http.ErrAbortHandler` is a `handler aborted` debug record. *(Amended in v1.1.1: the record carries `panic_type`, and `panic` is the value only for a `runtime.Error`, `[REDACTED]` otherwise, since an opaque value cannot be masked by key; header values are masked after each `?` and, when they carry a URL, in their user information, as `uri` is.)* An instance's key list is the built-in default list (the shipped value of `SensitiveLogKeys`, which has `cookie` and `session` since v0.11.0) plus its added keys; changes to the `SensitiveLogKeys` variable never reach an instance; added keys are lowercased and blank ones ignored; matching stays v0's case-insensitive substring match. The `uri` is masked with the default instance's helpers from v0.11.0 (#60), so both agree: query values by key with the literal `[REDACTED]` (a masked value runs to the next `&`, a key that cannot be unescaped is masked) and the user information of an absolute-form, `//host` or CONNECT authority-form target up to the last `@`; path segments are not. Bodies and the parsed form are never logged (no option, per section 5; query values still appear in `uri`). The built-in writer of an instance encodes before writing: a body that cannot be encoded is logged as `response cannot be encoded` and answered with 500 and the instance formatter's `Error500()` body (bare 500, with the response headers, if the formatter returns nil or that fails too); `http.ErrBodyNotAllowed` is not logged; the `Content-Type` comes only from the formatted headers (`application/json` when they set none), so one a handler set on `w.Header()` never labels the body; the encode-failure 500 drops the failed response's body headers (`Content-Type`, `Content-Encoding`, `Content-Length`, `Content-Range`, `Content-Disposition`, `Content-Language`, `Content-Location`, `ETag`, `Last-Modified`) and uses the error body's `Content-Type`; since 5.6 the default instance's writer also takes a `Content-Type` set in `Headers`, else `application/json` (section 8). `core.APIResponseWriter.Write` receives no request, so the writer's `response cannot be encoded`/`response cannot be written` records carry no request context or `event_id`. A custom writer, including a type that embeds `ResponseWriter`, is used as given and keeps the default instance's behavior. An instance never reads `Print`, `PrintError`, `Fatal` or `SensitiveLogKeys`, now deprecated with `LogRequest`, `LogResponse` and `LogResponseWithDuration`. *(Superseded by Amendment 1: the default instance writes these same records through `slog.Default`, and a type that embeds `ResponseWriter` logs through `slog.Default` with the registered formatter.)* +- As landed in 5.5: `ProcessRequest` writes two info records, `request` (`event_id`, `method`, `uri`, `headers`) and `response` (`event_id`, `method`, `uri`, `status`, `status_text`, `duration_ms`). Errors met while serving a request (a rejected body in `ProcessRequest`/`RequestBody`, a failed `Get*Value*`/`UnmarshalBody` helper) are error records with an `error` attribute; a `Get*Value*` record adds the name as `key` and, for a sensitive name, gives only the kind of error (`invalid syntax`, `value out of range`, `invalid value`), never the value. A recovered panic is a `panic recovered` error record with exactly the panic value and `event_id`, never a dump of the request; a panic with `http.ErrAbortHandler` is a `handler aborted` debug record. *(Amended in v1.1.1: the record carries `panic_type`, and `panic` is the value only for a `runtime.Error`, `[REDACTED]` otherwise, since an opaque value cannot be masked by key; header values are masked after each `?` and, when they carry a URL, in their user information, as `uri` is; a panic with `http.ErrAbortHandler`, plain or wrapped, is re-panicked as the plain `http.ErrAbortHandler` after its `handler aborted` record (a wrapped value would be logged by `net/http` with its text and a stack), writing nothing, so `net/http` aborts the response as it does without `ProcessRequest`; the built-in writer answers a nil formatted response like an encode failure and logs `response cannot be written` with `error` `nil formatted response`.)* An instance's key list is the built-in default list (the shipped value of `SensitiveLogKeys`, which has `cookie` and `session` since v0.11.0) plus its added keys; changes to the `SensitiveLogKeys` variable never reach an instance; added keys are lowercased and blank ones ignored; matching stays v0's case-insensitive substring match. The `uri` is masked with the default instance's helpers from v0.11.0 (#60), so both agree: query values by key with the literal `[REDACTED]` (a masked value runs to the next `&`, a key that cannot be unescaped is masked) and the user information of an absolute-form, `//host` or CONNECT authority-form target up to the last `@`; path segments are not. Bodies and the parsed form are never logged (no option, per section 5; query values still appear in `uri`). The built-in writer of an instance encodes before writing: a body that cannot be encoded is logged as `response cannot be encoded` and answered with 500 and the instance formatter's `Error500()` body (bare 500, with the response headers, if the formatter returns nil or that fails too); `http.ErrBodyNotAllowed` is not logged; the `Content-Type` comes only from the formatted headers (`application/json` when they set none), so one a handler set on `w.Header()` never labels the body; the encode-failure 500 drops the failed response's body headers (`Content-Type`, `Content-Encoding`, `Content-Length`, `Content-Range`, `Content-Disposition`, `Content-Language`, `Content-Location`, `ETag`, `Last-Modified`) and uses the error body's `Content-Type`; since 5.6 the default instance's writer also takes a `Content-Type` set in `Headers`, else `application/json` (section 8). `core.APIResponseWriter.Write` receives no request, so the writer's `response cannot be encoded`/`response cannot be written` records carry no request context or `event_id`. A custom writer, including a type that embeds `ResponseWriter`, is used as given and keeps the default instance's behavior. An instance never reads `Print`, `PrintError`, `Fatal` or `SensitiveLogKeys`, now deprecated with `LogRequest`, `LogResponse` and `LogResponseWithDuration`. *(Superseded by Amendment 1: the default instance writes these same records through `slog.Default`, and a type that embeds `ResponseWriter` logs through `slog.Default` with the registered formatter.)* ### 7. Errors: kind-to-status override and error hook (API-01) diff --git a/instance.go b/instance.go index 7d6eaa5..a300119 100644 --- a/instance.go +++ b/instance.go @@ -245,10 +245,9 @@ const maxErrorStatus = 599 // is not recovered: it propagates out of WriteError with nothing written. // Under ProcessRequest it answers 500 and is logged, with the panic type, // through the instance's WithLogger logger; nothing is logged without one. -// fn is shared by all -// requests the instance serves and may run concurrently, so it must be safe -// for concurrent use. A later WithErrorHook replaces an earlier one, and nil -// means no hook. +// fn is shared by all requests the instance serves and may run concurrently, +// so it must be safe for concurrent use. A later WithErrorHook replaces an +// earlier one, and nil means no hook. func WithErrorHook(fn func(r *http.Request, err error, status int)) Option { return func(o *options) { o.errorHook = fn @@ -256,22 +255,25 @@ func WithErrorHook(fn func(r *http.Request, err error, status int)) Option { } // WithLogger makes the instance log through logger: ProcessRequest writes a -// "request" and a "response" info record per request, and errors met while +// "request" info record per request and a "response" info record per +// response the handler completes (none after a recovered panic, although its +// 500 is still written), and errors met while // serving one (a rejected body, a failed Get*Value* helper, a recovered -// panic, a response that cannot be encoded) are written as error records. -// Request and response bodies and the parsed form are never logged. Header -// and query values whose key is sensitive (see WithSensitiveLogKeys) are -// masked, as is the user information of an absolute-form URI; other header -// values have the query values after each "?" masked the same way, and the -// user information too when they carry a URL; a failed Get*Value* helper logs the name as "key" and, for a sensitive name, only -// the kind of error, never the value. A recovered panic logs its Go type as -// "panic_type" and its value only for a runtime.Error. A panic with -// http.ErrAbortHandler is a "handler aborted" debug record instead of an -// error record. -// The built-in writer's records carry no request context or event_id, since -// core.APIResponseWriter.Write receives no request. -// Without it, or with nil, the instance writes no logs. A later WithLogger -// replaces an earlier one. +// panic, a response that cannot be encoded or written) are written as error +// records. Request and response bodies and the parsed form are never +// logged. Header and query values whose key is sensitive (see +// WithSensitiveLogKeys) are masked, as is the user information of an +// absolute-form URI; other header values have the query values after each +// "?" masked the same way, and the user information too when they carry a +// URL; a failed Get*Value* helper logs the name as "key" and, for a +// sensitive name, only the kind of error, never the value. A recovered +// panic logs its Go type as "panic_type" and its value only for a +// runtime.Error. A panic with http.ErrAbortHandler is a "handler aborted" +// debug record instead of an error record, and ProcessRequest re-panics it +// so net/http aborts the response. The built-in writer's records carry no +// request context or event_id, since core.APIResponseWriter.Write receives +// no request. Without it, or with nil, the instance writes no logs. A later +// WithLogger replaces an earlier one. func WithLogger(logger *slog.Logger) Option { return func(o *options) { o.logger = logger @@ -351,9 +353,10 @@ func WithResponseFormatter(formatter core.APIResponseFormatter) Option { // WithResponseWriter sets the writer that sends the instance's formatted // responses. The built-in ResponseWriter, as a value, a pointer or a nil // interface value, is bound to the instance's logger and formatter: it logs a -// body that cannot be encoded through the instance logger and answers 500 -// with the instance formatter's body. A custom writer alone decides how it -// writes and is used as given, including a typed nil pointer. A type that +// body that cannot be encoded, or a nil formatted response, through the +// instance logger and answers 500 with the instance formatter's body. A +// custom writer alone decides how it writes and is used as given, including +// a typed nil pointer. A type that // embeds ResponseWriter is custom: its promoted Write keeps the default // instance's behavior (slog.Default and the registered formatter). func WithResponseWriter(writer core.APIResponseWriter) Option { diff --git a/instance_log.go b/instance_log.go index ac4b465..5e8f7d1 100644 --- a/instance_log.go +++ b/instance_log.go @@ -122,11 +122,12 @@ func (a *API) logResponse(r *http.Request, eventID string, rec *httptest.Respons // only for a runtime.Error. Any other value (panic(err) of a failed parse, // a formatted string) may carry request data, and masking by key cannot // apply to an opaque value, so it is logged as redactedLogValue. A panic -// with http.ErrAbortHandler is a deliberate abort, so it is logged at debug -// level as "handler aborted", under the same rule. +// with http.ErrAbortHandler is a deliberate abort, re-panicked by +// ProcessRequest, so it is logged at debug level as "handler aborted", under +// the same rule. func (a *API) logPanic(r *http.Request, eventID string, recovered any) { level, msg := slog.LevelError, "panic recovered" - if err, ok := recovered.(error); ok && errors.Is(err, http.ErrAbortHandler) { + if isAbortPanic(recovered) { level, msg = slog.LevelDebug, "handler aborted" } if !a.logs(r.Context(), level) { @@ -143,18 +144,32 @@ func (a *API) logPanic(r *http.Request, eventID string, recovered any) { ) } +// isAbortPanic reports whether recovered is http.ErrAbortHandler, wrapped or +// not: net/http's documented way for a handler to abort its response. +func isAbortPanic(recovered any) bool { + err, ok := recovered.(error) + return ok && errors.Is(err, http.ErrAbortHandler) +} + // Write the API response in screen. It encodes the body before writing // anything, so a body that cannot be encoded (e.g. a NaN float) is logged as // "response cannot be encoded" and answered with 500 and the formatter's // internal server error body (see writeEncodeFailure) instead of exiting the // process. If the handler already wrote a status, that status stays and the -// error body is written under it. +// error body is written under it. A nil response (a custom formatter that +// returned nil) is logged as "response cannot be written" and answered the +// same way. // // http.ErrBodyNotAllowed from writing the body is not reported: Warning and // Informative default to status 100, which a server sends as informational // before delivering the body with 200, while the recorder that ProcessRequest // writes into returns this error. func (writer ResponseWriter) Write(response *core.ResponseFormatted, w http.ResponseWriter) { + if response == nil { + writer.logError("response cannot be written", errors.New("nil formatted response")) + writer.writeEncodeFailure(nil, w) + return + } var body bytes.Buffer if err := json.NewEncoder(&body).Encode(response.Body); err != nil { writer.logError("response cannot be encoded", err) diff --git a/instance_log_test.go b/instance_log_test.go index 2f20fa1..3a262ff 100644 --- a/instance_log_test.go +++ b/instance_log_test.go @@ -955,26 +955,78 @@ func TestInstanceWriterKeepsFormattedContentType(t *testing.T) { } } -func TestInstanceLogsAbortedHandlerAtDebug(t *testing.T) { +// nilFormatter formats every response into nil. +type nilFormatter struct{} + +func (nilFormatter) Format(core.ResponseData) *core.ResponseFormatted { return nil } + +func TestInstanceAnswers500WhenTheFormattedResponseIsNil(t *testing.T) { failOnPackageLoggers(t) - var buf bytes.Buffer - logger := slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug})) - handler := ProcessRequest(func(http.ResponseWriter, *http.Request) { panic(http.ErrAbortHandler) }) + logger, buf := newRecordingLogger() + a := New(WithLogger(logger), WithResponseFormatter(nilFormatter{})) - rec := serve(New(WithLogger(logger)).Handler(handler), http.MethodGet, "", nil) + rec := serve(a.Handler(http.HandlerFunc(okHandler)), http.MethodGet, "", nil) + + if rec.Code != http.StatusInternalServerError || rec.Body.Len() != 0 { + t.Fatalf("response = %d %q, want a bare 500", rec.Code, rec.Body) + } + record := recordNamed(t, decodeRecords(t, buf), "response cannot be written") + if record["level"] != "ERROR" || record["error"] != "nil formatted response" { + t.Fatalf("record = %v, want an error record for the nil response", record) + } +} + +func TestDefaultWriterAnswers500WhenTheFormattedResponseIsNil(t *testing.T) { + usePackageModes(t, RequestModePlain, ResponseModeEnvelope) + buf := captureDefaultLogger(t) + failOnPackageLoggers(t) + rec := httptest.NewRecorder() + + ResponseWriter{}.Write(nil, rec) if rec.Code != http.StatusInternalServerError { - t.Fatalf("status = %d, want 500 as for other panics", rec.Code) + t.Fatalf("status = %d, want 500", rec.Code) } - records := decodeRecords(t, &buf) - record := recordNamed(t, records, "handler aborted") - if record["level"] != "DEBUG" || record["event_id"] == nil || record["panic"] == nil { - t.Fatalf("record = %v, want a debug record with event_id and panic", record) + if title, code := envelopeHeader(t, rec.Body.Bytes()); title != InternalServerTitle || code != string(internalServerErrorCode()) { + t.Fatalf("title, code = %q, %q, want the Error500 body", title, code) } - for _, r := range records { - if r["level"] == "ERROR" { - t.Fatalf("unexpected error record %v", r) - } + record := recordNamed(t, decodeRecords(t, buf), "response cannot be written") + if record["error"] != "nil formatted response" { + t.Fatalf("record = %v, want the nil response error", record) + } +} + +// embeddedWriter is a custom writer that only embeds ResponseWriter. +type embeddedWriter struct{ ResponseWriter } + +// TestInstanceEmbeddedWriterLogsThroughSlogDefault checks that a type that +// embeds ResponseWriter keeps the default instance's behavior: it logs +// through slog.Default and builds the 500 with the registered (envelope) +// formatter, not the instance's (problem details) one. +func TestInstanceEmbeddedWriterLogsThroughSlogDefault(t *testing.T) { + usePackageModes(t, RequestModePlain, ResponseModeEnvelope) + defaultBuf := captureDefaultLogger(t) + failOnPackageLoggers(t) + logger, instanceBuf := newRecordingLogger() + a := New(WithLogger(logger), WithResponseMode(ResponseModeProblem), WithResponseWriter(embeddedWriter{})) + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + SuccessWithContent(math.NaN()).Write(w, r) + }) + + rec := serve(a.Handler(handler), http.MethodGet, "", nil) + + if rec.Code != http.StatusInternalServerError { + t.Fatalf("status = %d, want 500", rec.Code) + } + if got := rec.Header().Get("Content-Type"); got != "application/json" { + t.Fatalf("Content-Type = %q, want the registered formatter's application/json", got) + } + if _, code := envelopeHeader(t, rec.Body.Bytes()); code == "" { + t.Fatalf("body = %s, want the registered formatter's envelope with a code", rec.Body) + } + recordNamed(t, decodeRecords(t, defaultBuf), "response cannot be encoded") + if instanceBuf.Len() != 0 { + t.Fatalf("instance logger got records: %s", instanceBuf) } } diff --git a/instance_max_body_test.go b/instance_max_body_test.go index 1a2fc1b..cf05f89 100644 --- a/instance_max_body_test.go +++ b/instance_max_body_test.go @@ -254,3 +254,34 @@ func TestInstanceLimitAboveTheDefaultIsNotCapped(t *testing.T) { }) } } + +func TestNestedInstancesApplyTheSmallestLimit(t *testing.T) { + small, large := New(WithMaxBodyBytes(16)), New(WithMaxBodyBytes(1024)) + tests := []struct { + name string + outer *API + inner *API + bodySize int + wantStatus int + wantReached bool + }{ + {name: "smaller outer", outer: small, inner: large, bodySize: 64, wantStatus: http.StatusRequestEntityTooLarge}, + {name: "smaller inner", outer: large, inner: small, bodySize: 64, wantStatus: http.StatusRequestEntityTooLarge}, + {name: "under both", outer: small, inner: large, bodySize: 12, wantStatus: http.StatusOK, wantReached: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var reached bool + handler := tt.outer.Handler(tt.inner.Handler(ProcessRequest(reachHandler(&reached)))) + + rec := serve(handler, http.MethodPost, jsonBodyOfSize(tt.bodySize), nil) + + if rec.Code != tt.wantStatus { + t.Fatalf("status = %d, want %d", rec.Code, tt.wantStatus) + } + if reached != tt.wantReached { + t.Fatalf("handler reached = %v, want %v", reached, tt.wantReached) + } + }) + } +} diff --git a/instance_test.go b/instance_test.go index b914751..92b0b4d 100644 --- a/instance_test.go +++ b/instance_test.go @@ -282,14 +282,6 @@ func TestInstanceFromFallsBackToTheDefaultInstance(t *testing.T) { } } -// requestWithInstance returns a request that Handler served with a. -func requestWithInstance(a *API) *http.Request { - var served *http.Request - a.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { served = r })). - ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) - return served -} - func TestQuickStartAnswersLikeTheDefaultInstance(t *testing.T) { usePackageModes(t, RequestModePlain, ResponseModeEnvelope) titleRequired := codes.New("TSK-001", "title is required").WithKind(codes.KindValidation) diff --git a/middlewares.go b/middlewares.go index f2003f2..08e4fe9 100644 --- a/middlewares.go +++ b/middlewares.go @@ -291,6 +291,13 @@ func ProcessRequest(next http.HandlerFunc) http.HandlerFunc { defer func() { if recvr := recover(); recvr != nil { a.logPanic(r, rctx.EventID, recvr) + // Nothing has reached w yet, so re-panicking an abort lets + // net/http drop the response as it would without ProcessRequest. + // The plain sentinel is re-panicked even for a wrapped abort: + // net/http logs any other value, unredacted, with a stack. + if isAbortPanic(recvr) { + panic(http.ErrAbortHandler) + } Error500().Write(w, r) return } diff --git a/middlewares_abort_test.go b/middlewares_abort_test.go new file mode 100644 index 0000000..c859db9 --- /dev/null +++ b/middlewares_abort_test.go @@ -0,0 +1,81 @@ +package api + +import ( + "bytes" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "testing" +) + +// serveRecovering runs handler once and returns the recorded response and +// the value that panicked out of ServeHTTP, nil when none did. +func serveRecovering(handler http.Handler) (rec *httptest.ResponseRecorder, recovered any) { + rec = httptest.NewRecorder() + defer func() { recovered = recover() }() + handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/tasks", nil)) + return rec, nil +} + +// newDebugLogger returns a logger that writes JSON records of every level +// into buf. +func newDebugLogger(buf *bytes.Buffer) *slog.Logger { + return slog.New(slog.NewJSONHandler(buf, &slog.HandlerOptions{Level: slog.LevelDebug})) +} + +// assertAborted checks that http.ErrAbortHandler left ServeHTTP, that +// nothing was written, and that "request" and "handler aborted" are the only +// records. +func assertAborted(t *testing.T, rec *httptest.ResponseRecorder, recovered any, buf *bytes.Buffer) { + t.Helper() + // Only the plain sentinel keeps net/http quiet; a wrapped value would be + // logged by the server with its text and a stack. + if recovered != http.ErrAbortHandler { + t.Fatalf("recovered = %v, want http.ErrAbortHandler re-panicked", recovered) + } + if rec.Code != http.StatusOK || rec.Body.Len() != 0 || len(rec.Header()) != 0 { + t.Fatalf("response = %d %q %v, want nothing written", rec.Code, rec.Body, rec.Header()) + } + records := decodeRecords(t, buf) + record := recordNamed(t, records, "handler aborted") + if record["level"] != "DEBUG" || record["event_id"] == nil || record["panic"] == nil { + t.Fatalf("record = %v, want a debug record with event_id and panic", record) + } + recordNamed(t, records, "request") + if len(records) != 2 { + t.Fatalf("records = %v, want only request and handler aborted", records) + } +} + +func TestInstanceRepanicsAbortHandler(t *testing.T) { + tests := []struct { + name string + abort error + }{ + {name: "plain", abort: http.ErrAbortHandler}, + {name: "wrapped", abort: fmt.Errorf("upstream failed: %w", http.ErrAbortHandler)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + failOnPackageLoggers(t) + var buf bytes.Buffer + handler := ProcessRequest(func(http.ResponseWriter, *http.Request) { panic(tt.abort) }) + + rec, recovered := serveRecovering(New(WithLogger(newDebugLogger(&buf))).Handler(handler)) + + assertAborted(t, rec, recovered, &buf) + }) + } +} + +func TestDefaultInstanceRepanicsAbortHandler(t *testing.T) { + buf := captureDefaultLogger(t) + slog.SetDefault(newDebugLogger(buf)) + failOnPackageLoggers(t) + handler := ProcessRequest(func(http.ResponseWriter, *http.Request) { panic(http.ErrAbortHandler) }) + + rec, recovered := serveRecovering(handler) + + assertAborted(t, rec, recovered, buf) +} diff --git a/response.go b/response.go index 0cb1e4a..d8440ec 100644 --- a/response.go +++ b/response.go @@ -28,10 +28,11 @@ func getEventID(r *http.Request) string { // slog.Default and builds its 500 body with the formatter registered with // RegisterNewAPIResponseFormatter. New binds its logger and formatter to it, // so an instance's built-in writer logs through the instance logger and -// builds the 500 body with the instance formatter instead. Both send the -// Content-Type set in the formatted Headers (any key case; an empty value -// counts as unset), else application/json; one a handler set on w.Header() -// is overwritten. +// builds the 500 body with the instance formatter instead. A nil formatted +// response is logged as "response cannot be written" and answered with that +// 500 body. Both send the Content-Type set in the formatted Headers (any key +// case; an empty value counts as unset), else application/json; one a +// handler set on w.Header() is overwritten. type ResponseWriter struct { logger *slog.Logger formatter core.APIResponseFormatter