From 923cf0468b542752f4870e14e593df5d061c983d Mon Sep 17 00:00:00 2001 From: Josue Giron Date: Sat, 21 Nov 2026 18:24:00 +0000 Subject: [PATCH] feat(api)!: answer like api.New on the default instance Owner decision (2026-11-21): in v1.0.0 the default instance (requests without an api.New instance in context) behaves like api.New() with its defaults. This change covers the wire behavior; logging follows in the next change of the stack. The fromNew forks for codes, token echo, RequestHeaderSession, the body limit and problem mode are gone; one code path serves both. ADR 0001 gets Amendment 1; README and the migration guide make "what changes without code changes" the main upgrade path. BREAKING CHANGE: for programs that use the package-level API without api.New (the default instance): - response codes are sent as declared (E001, E300, TSK-001), not lowercased; there is no package-level switch back, only api.New(api.WithLowercaseCodes()); - the request token (SecurityToken header, Authorization: Bearer, envelope header.token) is no longer echoed in response bodies; - RequestHeaderSession no longer copies the SecurityToken request header into the response header; - ProcessRequest, RequestBody, ProcessBody, ProcessEncryptedBody and UnmarshalBody read at most 10 MiB; a larger body, or any *http.MaxBytesError, answers 413 E002 "Request content too large" (v0.11.0: no limit, 400 for a service-installed limit); - SetResponseMode(ResponseModeProblem) is accepted and writes RFC 9457 problem details (v0.11.0 fell back to envelope); - the zero ResponseFormatter sends codes as declared. Stay on v0.11.x to keep v0 behavior. Co-Authored-By: Claude Opus 5.5 --- README.md | 36 ++--- api.go | 15 ++ basic_request_test.go | 4 +- catalogs_test.go | 8 +- default_instance_test.go | 266 +++++++++++++++++++++++++++++++ doc.go | 7 +- docs/adr/0001-v1-instance-api.md | 46 ++++-- docs/legacy.md | 6 +- docs/migration-v1.md | 65 ++++---- example_migration_test.go | 25 +-- functions.go | 9 +- instance.go | 86 +++++----- instance_codes_test.go | 24 +-- instance_max_body_test.go | 49 +++++- instance_problem_test.go | 30 ---- instance_test.go | 25 +-- instance_token_echo_test.go | 10 +- middlewares.go | 43 +++-- modes.go | 9 +- response.go | 24 --- response_error.go | 3 - response_formatter.go | 26 +-- response_informative.go | 3 - response_success.go | 3 - response_warning.go | 3 - response_writer_test.go | 4 +- write_error_test.go | 11 +- 27 files changed, 560 insertions(+), 280 deletions(-) create mode 100644 default_instance_test.go diff --git a/README.md b/README.md index 7ac2f14..f70f323 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ go get github.com/jgolang/api The JSON envelope with device metadata in the request `header` (`device_type`, `device_brand`, `lat`, `lon`, `token`, …) is still supported, but it is no longer the default. It is documented in [docs/legacy.md](docs/legacy.md). -Upgrading a v0 program? [docs/migration-v1.md](docs/migration-v1.md) takes it to v1 step by step: routing changes, the `api.New` instance, and every deprecated name with its replacement. +Upgrading a v0 program? [docs/migration-v1.md](docs/migration-v1.md) takes it to v1 step by step: what changes without code changes (the default instance now behaves like `api.New()`), routing changes, the `api.New` instance, and every deprecated name with its replacement. ## Quick start @@ -90,14 +90,14 @@ func main() { 1. **Route registration.** `api.Get`, `api.Post`, `api.Put`, `api.Patch` and `api.Delete` register a handler on any `api.Router` and record its `doc.RouteOption`s for the OpenAPI document. `stdadapter` is the `net/http` router; see [Routing and OpenAPI](#routing-and-openapi). 2. **`api.ProcessRequest`.** Wrap a handler with this middleware to get the full flow. It: - - reads the body and parses it according to the [request mode](#request-and-response-modes); an invalid JSON body answers 400 with code `E002` on an `api.New` instance (`e002` on the default instance); + - 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; see [Logging](#logging)); - stores the request context, replaces `r.Body` with the endpoint content, and answers 500 if the handler panics. 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). -4. **The formatter** shapes the response according to the [response mode](#request-and-response-modes) and adds the event ID, code and token (the request token is echoed only by the default instance). +4. **The formatter** shapes the response according to the [response mode](#request-and-response-modes) and adds the event ID, code and token (a token only when the handler sets `SecurityToken`; the request token is never echoed). A handler that is not wrapped by `api.ProcessRequest` still works: it reads the raw body itself, and its responses are formatted the same way, without a generated event ID. @@ -113,7 +113,7 @@ a := api.New( http.ListenAndServe(":8080", a.Handler(router)) ``` -`a.Handler` stores the instance in the request context, so `api.ProcessRequest`, `api.RequestBody`, the token middlewares, `Write(w, r)` on every response type (`api.Success`, `api.Error`, `api.Warning`, `api.Informative`) and `api.WriteError` use its modes; handler code does not change. Wrap the outermost chain: middlewares outside `a.Handler` (and the package-level `api.Write(data, w)`, which takes no request) use the default instance, so their rejections (for example `api.ProcessRequest`'s invalid-body `e002`) are lowercase while handlers inside answer with the instance's code case; with nested instances the innermost one wins. An instance is immutable after `api.New`, and two instances in one process (two services, or two tests) do not see each other's modes. `api.New()` with no options parses plain requests and writes envelope responses. An instance sends response codes as declared (`PLN-001`); `api.WithLowercaseCodes()` restores lowercasing, and the default instance lowercases as in v0. An instance uses the built-in request receiver, response formatter and response writer unless you pass your own: +`a.Handler` stores the instance in the request context, so `api.ProcessRequest`, `api.RequestBody`, the token middlewares, `Write(w, r)` on every response type (`api.Success`, `api.Error`, `api.Warning`, `api.Informative`) and `api.WriteError` use its modes; handler code does not change. Wrap the outermost chain: middlewares outside `a.Handler` (and the package-level `api.Write(data, w)`, which takes no request) use the default instance, so their rejections use the package modes and loggers instead of the instance's options; with nested instances the innermost one wins. An instance is immutable after `api.New`, and two instances in one process (two services, or two tests) do not see each other's modes. `api.New()` with no options parses plain requests and writes envelope responses. An instance, like the default instance, sends response codes as declared (`PLN-001`); `api.WithLowercaseCodes()` restores v0's lowercasing. An instance uses the built-in request receiver, response formatter and response writer unless you pass your own: ```go a := api.New( @@ -123,7 +123,7 @@ a := api.New( ) ``` -The mode options, and for the formatter `api.WithLowercaseCodes()`, apply to the built-in receivers (`api.RequestReceiver`, `api.RequestReceiverV2`) and formatter (`api.ResponseFormatter`), also when you pass them with these options; a custom receiver or formatter (including one that embeds a built-in) alone decides how it parses, what body it writes and its code text. A type that embeds a built-in receiver or formatter is custom, and its promoted methods read the deprecated package mode variables. A nil value keeps the built-in. The deprecated `api.RegisterNewAPIRequestReceiver`, `api.RegisterNewAPIResponseFormatter` and `api.RegisterNewAPIResponseWriter` affect only the default instance. `api.RegisterNewAPISecurityGuarantor` and `api.RegisterParamValidator` are not deprecated and apply to every instance. +The mode options, and for the formatter `api.WithLowercaseCodes()`, apply to the built-in receivers (`api.RequestReceiver`, `api.RequestReceiverV2`) and formatter (`api.ResponseFormatter`), also when you pass them with these options; a custom receiver or formatter (including one that embeds a built-in) alone decides how it parses, what body it writes and its code text. A type that embeds a built-in receiver or formatter is custom, and its promoted methods read the deprecated package mode variables and send codes as declared. A nil value keeps the built-in. The deprecated `api.RegisterNewAPIRequestReceiver`, `api.RegisterNewAPIResponseFormatter` and `api.RegisterNewAPIResponseWriter` affect only the default instance. `api.RegisterNewAPISecurityGuarantor` and `api.RegisterParamValidator` are not deprecated and apply to every instance. | Request mode | Body parsing | | --- | --- | @@ -137,13 +137,13 @@ The mode options, and for the formatter `api.WithLowercaseCodes()`, apply to the | `api.ResponseModeEnvelope` (default) | `{"header": {"type", "title", "message", "code", "token", "action", "event_id", "info"}, "content": ...}`; empty header fields are omitted, except `type`. | | `api.ResponseModePlain` | The same fields at the top level, with `content` next to them: `{"type": "success", "code": "0000", ..., "content": ...}`. Every field is present. | | `api.ResponseModeNone` | Only the content, as is. | -| `api.ResponseModeProblem` (instances only) | Errors as RFC 9457 problem details, `{"type": "about:blank", "title", "status", "detail", "code", "event_id"}`, sent as `application/problem+json`; empty members are omitted, except `type`. Other responses: only the content, as `api.ResponseModeNone`. | +| `api.ResponseModeProblem` | Errors as RFC 9457 problem details, `{"type": "about:blank", "title", "status", "detail", "code", "event_id"}`, sent as `application/problem+json`; empty members are omitted, except `type`. Other responses: only the content, as `api.ResponseModeNone`. | An unknown value falls back to the default (`api.RequestModePlain`, `api.ResponseModeEnvelope`). -`api.ResponseModeProblem` is accepted only by `api.WithResponseMode`, for the built-in formatter; `api.SetResponseMode` treats it as unknown, so the default instance never writes problem details. In a problem body `title` is the HTTP status phrase (`Not Found`) when the response title is empty or a library default (`Error response!`, `Sorry!`, `Unauthorized!`, the helpers' titles), and the title the service set otherwise (the check is by text: a service title equal to a library default also becomes the status phrase, and a default reassigned through `api.DefaultErrorTitle` and its siblings is kept); `detail` is the public message without the trace suffix, and `code` and `event_id` are extension members; `type` is always `about:blank`, and content, token, actions and info are not sent. The built-in response writer sends `Content-Type: application/json` unless the response `Headers` set a non-empty `Content-Type`, which always wins, in every mode (one set on `w.Header()` by the handler does not count) (a fix: v0 discarded a `Content-Type` the service set); the 500 sent for a body that cannot be encoded, by the default instance or an instance, carries the error body's `Content-Type` and drops the failed body's other headers (`Content-Encoding`, `Content-Length`, `ETag`, …). +`api.ResponseModeProblem` applies to the built-in formatter, set with `api.WithResponseMode` or, on the default instance, the deprecated `api.SetResponseMode` (since v1.0.0; v0 fell back to envelope). In a problem body `title` is the HTTP status phrase (`Not Found`) when the response title is empty or a library default (`Error response!`, `Sorry!`, `Unauthorized!`, the helpers' titles), and the title the service set otherwise (the check is by text: a service title equal to a library default also becomes the status phrase, and a default reassigned through `api.DefaultErrorTitle` and its siblings is kept); `detail` is the public message without the trace suffix, and `code` and `event_id` are extension members; `type` is always `about:blank`, and content, token, actions and info are not sent. The built-in response writer sends `Content-Type: application/json` unless the response `Headers` set a non-empty `Content-Type`, which always wins, in every mode (one set on `w.Header()` by the handler does not count) (a fix: v0 discarded a `Content-Type` the service set); the 500 sent for a body that cannot be encoded, by the default instance or an instance, carries the error body's `Content-Type` and drops the failed body's other headers (`Content-Encoding`, `Content-Length`, `ETag`, …). -Requests that are not wrapped by an instance's `Handler` use the default instance, which reads the package variables `api.CurrentRequestMode` and `api.CurrentResponseMode` (set with `api.SetRequestMode` and `api.SetResponseMode`). These four names are deprecated: they affect only the default instance, for the whole process. [docs/migration-v1.md](docs/migration-v1.md) lists every deprecated name with its option. The `envelope` package types are for OpenAPI documentation and match the envelope response mode. +Requests that are not wrapped by an instance's `Handler` use the default instance. Since v1.0.0 it behaves like `api.New()` with its defaults (codes as declared, no token echo, 10 MiB body limit); it reads the package variables `api.CurrentRequestMode` and `api.CurrentResponseMode` (set with `api.SetRequestMode` and `api.SetResponseMode`). These four names are deprecated: they affect only the default instance, for the whole process. [docs/migration-v1.md](docs/migration-v1.md) lists every deprecated name with its option. The `envelope` package types are for OpenAPI documentation and match the envelope response mode. ## Reading the request @@ -191,19 +191,19 @@ The older `api.GetQueryParamValue*` helpers return an `api.Response`; prefer the ## Responses -Every response kind (`api.Success`, `api.Error`, `api.Warning`, `api.Informative`) is a `core.ResponseData` with a `Write(w, r)` method. Its fields (`Title`, `Message`, `HTTPStatusCode`, `ResponseCode`, `Content`, `Headers`, `Info`, `Actions`) can be set before writing. `Write` fills the event ID and, on the default instance only, the request token (an `api.New` instance sends a token only when you set `SecurityToken`), and defaults the title, message, status and code of its kind. +Every response kind (`api.Success`, `api.Error`, `api.Warning`, `api.Informative`) is a `core.ResponseData` with a `Write(w, r)` method. Its fields (`Title`, `Message`, `HTTPStatusCode`, `ResponseCode`, `Content`, `Headers`, `Info`, `Actions`) can be set before writing. `Write` fills the event ID (a token is sent only when you set `SecurityToken`; since v1.0.0 the request token is never echoed), and defaults the title, message, status and code of its kind. | Helper | Status | Code | | --- | --- | --- | | `api.Success200()`, `api.SuccessWithMsg(msg)` | 200 | `0000` | | `api.SuccessWithContent(content)` | 200 | `0000` | | `api.Success201()` | 201 | `0000` | -| `api.Error400(errs...)`, `api.ErrorWithMsg(msg, errs...)` | 400 | the first coded error in `errs`, else `e001` | -| `api.Error401()`, `api.Error403()` | 401, 403 | `b001`, `b002` | -| `api.Error500(errs...)`, `api.Error500WithMsg(msg, errs...)` | 500 | the first coded error in `errs`, else `e300` | -| `api.Error501(errs...)` | 501 (503 before v0.10.0) | the first coded error in `errs`, else `e001` | +| `api.Error400(errs...)`, `api.ErrorWithMsg(msg, errs...)` | 400 | the first coded error in `errs`, else `E001` | +| `api.Error401()`, `api.Error403()` | 401, 403 | `B001`, `B002` | +| `api.Error500(errs...)`, `api.Error500WithMsg(msg, errs...)` | 500 | the first coded error in `errs`, else `E300` | +| `api.Error501(errs...)` | 501 (503 before v0.10.0) | the first coded error in `errs`, else `E001` | -The default instance writes response codes in lower case, as in the table (`e001`); an `api.New` instance sends them as declared (`E001`) unless created with `api.WithLowercaseCodes()`. The default titles, messages and codes are package variables (`api.DefaultSuccessTitle`, `api.InternalServerMessage`, `api.ResponseCodes`, …). +Response codes are sent as declared, as in the table (`E001`); an `api.New` instance created with `api.WithLowercaseCodes()` lowercases them (`e001`), as v0 did. The default titles, messages and codes are package variables (`api.DefaultSuccessTitle`, `api.InternalServerMessage`, `api.ResponseCodes`, …). ```go api.SuccessWithContent(task).Write(w, r) @@ -218,7 +218,7 @@ api.Error500(err).Write(w, r) Two settings shape the `title` and `message` of every response on the default instance; an `api.New` instance uses their defaults (`true`, `1`, ID length 6) and does not read them: - `api.BlankSuccess` (default `true`): success responses leave `title` and `message` empty. Error, warning, informative and custom response types always carry them. -- `api.TraceVisibility` (default `1`): a trace suffix appended to a non-empty message. `1` appends ` (-)`, `2` only ` ()`, `3` only ` ()`; any other value appends nothing. The event ID is cut to `api.TraceIDLength` characters (default 6). For example, `Error500()` writes `"An error has occurred please try again later. (cdf606-e300)"`. +- `api.TraceVisibility` (default `1`): a trace suffix appended to a non-empty message. `1` appends ` (-)`, `2` only ` ()`, `3` only ` ()`; any other value appends nothing. The event ID is cut to `api.TraceIDLength` characters (default 6). For example, `Error500()` writes `"An error has occurred please try again later. (cdf606-E300)"`. ## Writing errors @@ -363,14 +363,14 @@ See [ADR 0002](docs/adr/0002-stdadapter-servemux.md). - `doc.Security` and `docs.SetDefaultSecurity` only document authentication; they do not enforce it. Enforce it with a middleware: `api.CustomToken` (validated by `api.CustomTokenValidatorFunc`), `api.BasicToken` (validated by `api.ValidateBasicAuthCredentialsFunc`), or your own. - `api.BasicToken` with the default validator answers 401 to every request while `api.Username` or `api.Password` is empty or `"default"` (since v0.11.0; before, it accepted `default:default`). Set both, or replace `api.ValidateBasicAuthCredentialsFunc`, before exposing a route. The default validator compares credentials in constant time; a custom one should too (`crypto/subtle`). After a successful check, `BasicToken` copies the user name into the `Basic-Client` request header. Since v1.0.0 it no longer copies the plain password into a `Basic-Secret` header, and it removes a `Basic-Secret` header the client sent; a handler that needs the password must take it from its own credential source. -- An `api.New` instance does not echo the request token: a response body carries a `token` only when the handler sets `SecurityToken` on the response. Only responses written inside `a.Handler` follow this: a token middleware (`api.CustomToken`, `api.BasicToken`) or `api.ProcessRequest` placed outside it answers with the default instance and echoes the token in its 401 or 400. On the default instance the request token (`SecurityToken` header, `Authorization: Bearer`, or the envelope `header.token`) is echoed in the response `token` field unless the handler sets `SecurityToken`; do not rely on its bodies being free of it. `api.RequestHeaderSession` copies the `SecurityToken` request header into the response header only on the default instance; inside `a.Handler` it does not, and a handler that wants to return a token sets the header itself. On the default instance, after `api.ProcessRequest` that header holds the request token, which in envelope request mode can come from the body's `header.token`. +- The request token is never echoed (since v1.0.0, on the default instance too): a response body carries a `token` only when the handler sets `SecurityToken` on the response, and `api.RequestHeaderSession` does not copy the `SecurityToken` request header into the response header; a handler that wants to return a token sets it itself. - An `api.New` instance never logs bodies or the parsed form. It masks, by its sensitive keys (the `api.SensitiveLogKeys` defaults plus `api.WithSensitiveLogKeys`), header values and query parameter values in `uri`, and the user information of the `uri`, with the same rules as the default instance below. See [Logging](#logging). - On the default instance, request and response bodies are logged only when `api.LogRequestBody` / `api.LogResponseBody` are true; values under the keys in `api.SensitiveLogKeys` are masked and bodies are cut at `api.MaxLoggedBodyBytes`. - The default instance's request log masks, by the keys in `api.SensitiveLogKeys` (a name matches when it contains a key, ignoring case; the defaults include `authorization`, `token`, `password`, `key`, `cookie` and `session`): header values, JSON body fields, query parameter values in `uri` (names are found by splitting on `&` and `;`, and a masked value runs to the next `&`; a name that cannot be unescaped is masked too), and `form` values. It also masks the user information of an absolute-form, `//host` or CONNECT authority-form `uri` (`http://[REDACTED]@host/...`), up to the last `@`, so an `@` in the path or query hides the host and path too. Path segments are not masked. Masking is by name: a secret under a non-sensitive name (such as a URL with credentials in `?next=`) is logged as sent. A request body that is not JSON (form, XML, text) is logged as `[non-JSON body, N bytes]` unless `api.PrintFullEvent` is true. - With `stdadapter`, a route variable can contain `/` and `..` (`/files/..%2F..%2Fetc` gives `name` = `../../etc`). Validate it before using it in a file path or another lookup that trusts it. - `api.ProcessRequest` stores the value of the `X-Forwarded-For` header up to its first `", "` as the `proxiedIPAddress` info value (and, when the request has no device UUID, as the event ID input). Only the first `X-Forwarded-For` header line is read. That value is set by the client: trust it only behind a proxy that overwrites the header, and do not use it on its own for rate limits, allow lists or audit. -- An `api.New` instance bounds request bodies at 10 MiB: its `Handler` wraps the body in `http.MaxBytesReader`, and `api.ProcessRequest`, `api.RequestBody` and `api.UnmarshalBody` answer a larger body with 413 and code `E002` (title `Request content too large`). Set another limit with `api.WithMaxBodyBytes(n)`; `n <= 0` is ignored, so pass `math.MaxInt64` for no practical limit. Nested instance limits combine, so the smallest applies. Only readers inside `a.Handler` are bounded: an `api.ProcessRequest` or `api.RequestBody` placed outside it runs with the default instance and reads without a limit. A custom receiver or a handler that reads `r.Body` itself gets the `*http.MaxBytesError` and decides how to answer. `ExampleWithMaxBodyBytes` is the compiled version. -- The default instance sets no limit on the request body size: `api.ProcessRequest` and the request receivers read the whole body into memory. Bound it before they run, with `http.MaxBytesHandler` (or `http.MaxBytesReader` in a middleware) or a proxy limit; a body over that limit is answered with 400, as in v0.11.0: +- An `api.New` instance bounds request bodies at 10 MiB: its `Handler` wraps the body in `http.MaxBytesReader`, and `api.ProcessRequest`, `api.RequestBody` and `api.UnmarshalBody` answer a larger body with 413 and code `E002` (title `Request content too large`). Set another limit with `api.WithMaxBodyBytes(n)`; `n <= 0` is ignored, so pass `math.MaxInt64` for no practical limit. Nested instance limits combine, so the smallest applies. A custom receiver or a handler that reads `r.Body` itself gets the `*http.MaxBytesError` and decides how to answer. `ExampleWithMaxBodyBytes` is the compiled version. +- Since v1.0.0 the default instance bounds request bodies at 10 MiB where the library reads them (`api.ProcessRequest`, `api.RequestBody`, `api.ProcessBody`, `api.ProcessEncryptedBody`, `api.UnmarshalBody`), answering 413 like an instance. A handler that reads `r.Body` itself outside an instance is not bounded. For a lower limit, bound the body before they run with `http.MaxBytesHandler` (or `http.MaxBytesReader` in a middleware) or a proxy limit; a body over that limit is answered with 413 too. An outer limit can only lower the 10 MiB cap; to raise it, use `api.New(api.WithMaxBodyBytes(n)).Handler`: ```go mux.Handle("POST /tasks", http.MaxBytesHandler(api.ProcessRequest(createTask), 1<<20)) // 1 MiB diff --git a/api.go b/api.go index 14101dd..34c045d 100644 --- a/api.go +++ b/api.go @@ -50,7 +50,12 @@ func Write(data core.ResponseData, w http.ResponseWriter) { // ProcessEncryptedBody API request. You can to define request url encoding format and how to // validate it implemented the APIRequestReciver interface. +// Without an instance in r, it replaces r.Body with an http.MaxBytesReader +// at 10 MiB, so a larger body returns an *http.MaxBytesError. It has no +// ResponseWriter, so the server is not told to close the connection on +// overflow; ProcessRequest and RequestBody pass theirs. func ProcessEncryptedBody(r *http.Request) (*EncryptedRequest, error) { + boundDefaultBody(nil, r) requestData, err := instanceFrom(r).core.ProcessEncryptedBody(r) return &EncryptedRequest{ RequestEncryptedData: requestData, @@ -59,7 +64,17 @@ func ProcessEncryptedBody(r *http.Request) (*EncryptedRequest, error) { // ProcessBody API request. You can to define request JSON format and how to // validate it implemented the APIRequestReciver interface. +// Without an instance in r, it replaces r.Body with an http.MaxBytesReader +// at 10 MiB, so a larger body returns an *http.MaxBytesError. It has no +// ResponseWriter, so the server is not told to close the connection on +// overflow; ProcessRequest and RequestBody pass theirs. func ProcessBody(r *http.Request) (*RequestContext, error) { + boundDefaultBody(nil, r) + return processBody(r) +} + +// processBody is ProcessBody for a caller that already bounded the body. +func processBody(r *http.Request) (*RequestContext, error) { requestDataContext, err := instanceFrom(r).core.ProcessBody(r) return &RequestContext{ RequestDataContext: requestDataContext, diff --git a/basic_request_test.go b/basic_request_test.go index 8a6aff4..ce8d81a 100644 --- a/basic_request_test.go +++ b/basic_request_test.go @@ -37,12 +37,12 @@ func TestRequestBasicGettersSendTheRequestInfoError(t *testing.T) { "GetRequestFullInfo": "The session id was not obtained", } // The message ends with the trace suffix; without an event ID it holds - // only the code, lowercased on the default instance. + // only the code, as declared on both. instances := map[string]struct { wrap func(http.Handler) http.Handler traceSuffix string }{ - "default instance": {func(next http.Handler) http.Handler { return next }, " (-e001)"}, + "default instance": {func(next http.Handler) http.Handler { return next }, " (-E001)"}, "instance": {New().Handler, " (-E001)"}, } for instanceName, instance := range instances { diff --git a/catalogs_test.go b/catalogs_test.go index 689e870..b07a6f4 100644 --- a/catalogs_test.go +++ b/catalogs_test.go @@ -35,10 +35,10 @@ func TestInternalServerErrorCode(t *testing.T) { wantDefault string wantInstance string }{ - {name: "default code", wantDefault: "e300", wantInstance: "E300"}, - {name: "only the deprecated field set", deprecated: "X1", wantDefault: "x1", wantInstance: "X1"}, - {name: "only the new field set", current: "X2", wantDefault: "x2", wantInstance: "X2"}, - {name: "both set, new wins", deprecated: "X1", current: "X2", wantDefault: "x2", wantInstance: "X2"}, + {name: "default code", wantDefault: "E300", wantInstance: "E300"}, + {name: "only the deprecated field set", deprecated: "X1", wantDefault: "X1", wantInstance: "X1"}, + {name: "only the new field set", current: "X2", wantDefault: "X2", wantInstance: "X2"}, + {name: "both set, new wins", deprecated: "X1", current: "X2", wantDefault: "X2", wantInstance: "X2"}, } for _, tt := range tests { diff --git a/default_instance_test.go b/default_instance_test.go new file mode 100644 index 0000000..946b9bb --- /dev/null +++ b/default_instance_test.go @@ -0,0 +1,266 @@ +package api + +import ( + stderrors "errors" + "maps" + "math" + "net/http" + "net/http/httptest" + "regexp" + "slices" + "strings" + "testing" + + "github.com/jgolang/errors" + "github.com/jgolang/errors/codes" +) + +// countPackageErrorLogs replaces Print and PrintError with no-ops for one +// test and returns how many times PrintError was called. The default +// instance still logs through them until it moves to slog. +func countPackageErrorLogs(t *testing.T) *int { + t.Helper() + previousPrint, previousPrintError := Print, PrintError + calls := 0 + Print = func(string, ...interface{}) {} + PrintError = func(...interface{}) { calls++ } + t.Cleanup(func() { Print, PrintError = previousPrint, previousPrintError }) + return &calls +} + +// sameAsNewEventIDs matches what differs between two runs of one request: +// the event ID in bodies and the short ID in the trace suffix. +var sameAsNewEventIDs = regexp.MustCompile(`"event_id":"[0-9a-f]+"|\([0-9a-f]*-`) + +// TestDefaultInstanceAnswersLikeNew checks that a v0 program without +// api.New answers exactly as the same handler under api.New().Handler, +// apart from event IDs. +func TestDefaultInstanceAnswersLikeNew(t *testing.T) { + usePackageModes(t, RequestModePlain, ResponseModeEnvelope) + countPackageErrorLogs(t) + declared := codes.New("PLN-001", "plan not found").WithKind(codes.KindNotFound) + tests := []struct { + name string + handler http.Handler + body string + headers map[string]string + }{ + {name: "success", handler: ProcessRequest(okHandler), body: `{"title":"task"}`}, + {name: "declared code", handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + Error{ResponseCode: "PLN-001", Message: "plan not found"}.Write(w, r) + })}, + {name: "write error", handler: ProcessRequest(func(w http.ResponseWriter, r *http.Request) { + WriteError(w, r, errors.NewC(declared, "no plan")) + })}, + {name: "bearer token not echoed", handler: ProcessRequest(okHandler), headers: map[string]string{"Authorization": "Bearer s3cr3t"}}, + {name: "session header not copied", handler: RequestHeaderSession(okHandler), headers: map[string]string{SecurityTokenHeaderKey: "s3cr3t"}}, + {name: "session header missing", handler: RequestHeaderSession(okHandler)}, + {name: "bad json", handler: ProcessRequest(okHandler), body: `{"title":`}, + {name: "body too large", handler: ProcessRequest(okHandler), body: jsonBodyOfSize(defaultMaxBodyBytes + 1)}, + {name: "request body too large", handler: RequestBody(okHandler), body: jsonBodyOfSize(defaultMaxBodyBytes + 1)}, + {name: "unmarshal body too large", handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var payload map[string]any + if response := UnmarshalBody(&payload, r); response != nil { + response.Write(w, r) + } + }), body: jsonBodyOfSize(defaultMaxBodyBytes + 1)}, + {name: "panic", handler: ProcessRequest(func(http.ResponseWriter, *http.Request) { panic("boom") })}, + {name: "nan content", handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + SuccessWithContent(math.NaN()).Write(w, r) + })}, + {name: "custom token rejected", handler: CustomToken(okHandler), headers: map[string]string{"Authorization": "Bearer invalid"}}, + {name: "get value helper failure", handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if _, response := GetHeaderValueInt("X-Count", r); response != nil { + response.Write(w, r) + } + }), headers: map[string]string{"X-Count": "many"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + withoutInstance := serve(tt.handler, http.MethodPost, tt.body, tt.headers) + withNew := serve(New().Handler(tt.handler), http.MethodPost, tt.body, tt.headers) + + if withoutInstance.Code != withNew.Code { + t.Errorf("status = %d without instance, %d with New()", withoutInstance.Code, withNew.Code) + } + if a, b := withoutInstance.Header(), withNew.Header(); !maps.EqualFunc(a, b, slices.Equal) { + t.Errorf("headers = %v without instance, %v with New()", a, b) + } + a := sameAsNewEventIDs.ReplaceAllString(withoutInstance.Body.String(), "ID") + if b := sameAsNewEventIDs.ReplaceAllString(withNew.Body.String(), "ID"); a != b { + t.Errorf("body without instance: %s\nbody with New(): %s", a, b) + } + }) + } +} + +// TestDefaultInstanceInEnvelopeRequestModeAnswersLikeNew checks that the +// envelope header.token read by ProcessRequest is not echoed, as on an +// instance in the same request mode. +func TestDefaultInstanceInEnvelopeRequestModeAnswersLikeNew(t *testing.T) { + usePackageModes(t, RequestModeEnvelope, ResponseModeEnvelope) + countPackageErrorLogs(t) + body := `{"header":{"token":"s3cr3t"},"content":{"title":"task"}}` + handler := ProcessRequest(okHandler) + + withoutInstance := serve(handler, http.MethodPost, body, nil) + withNew := serve(New(WithRequestMode(RequestModeEnvelope)).Handler(handler), http.MethodPost, body, nil) + + if withoutInstance.Code != withNew.Code { + t.Errorf("status = %d without instance, %d with New()", withoutInstance.Code, withNew.Code) + } + if a, b := withoutInstance.Header(), withNew.Header(); !maps.EqualFunc(a, b, slices.Equal) { + t.Errorf("headers = %v without instance, %v with New()", a, b) + } + a := sameAsNewEventIDs.ReplaceAllString(withoutInstance.Body.String(), "ID") + if b := sameAsNewEventIDs.ReplaceAllString(withNew.Body.String(), "ID"); a != b { + t.Errorf("body without instance: %s\nbody with New(): %s", a, b) + } + if strings.Contains(withoutInstance.Body.String(), "s3cr3t") { + t.Errorf("body echoes the envelope token: %s", withoutInstance.Body) + } +} + +func TestDefaultInstanceSendsCodesAsDeclared(t *testing.T) { + usePackageModes(t, RequestModePlain, ResponseModePlain) + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.Header.Set(EventIDHeaderKey, "evtabc123") + rec := httptest.NewRecorder() + + Error{ResponseCode: "PLN-001", Message: "plan not found"}.Write(rec, req) + + code, message := codeAndMessage(rec.Body.Bytes()) + if code != "PLN-001" || message != "plan not found (evtabc-PLN-001)" { + t.Fatalf("code, message = %q, %q, want PLN-001 and the declared code in the suffix", code, message) + } +} + +func TestDefaultInstanceDoesNotEchoTheRequestToken(t *testing.T) { + tests := []struct { + mode ResponseMode + want string + }{ + {mode: ResponseModePlain, want: `"token":""`}, + {mode: ResponseModeEnvelope, want: ""}, + } + for _, tt := range tests { + t.Run(string(tt.mode), func(t *testing.T) { + usePackageModes(t, RequestModePlain, tt.mode) + + rec := serve(http.HandlerFunc(okHandler), http.MethodGet, "", map[string]string{"Authorization": "Bearer s3cr3t"}) + + if strings.Contains(rec.Body.String(), "s3cr3t") { + t.Fatalf("body echoes the request token: %s", rec.Body) + } + if tt.want != "" && !strings.Contains(rec.Body.String(), tt.want) { + t.Fatalf("body = %s, want %s", rec.Body, tt.want) + } + if tt.mode == ResponseModeEnvelope && strings.Contains(rec.Body.String(), `"token"`) { + t.Fatalf("envelope has a token: %s", rec.Body) + } + }) + } +} + +func TestDefaultRequestHeaderSessionDoesNotCopyTheToken(t *testing.T) { + tests := []struct { + name string + token string + wantStatus int + }{ + {name: "with session", token: "s3cr3t", wantStatus: http.StatusOK}, + {name: "without session", wantStatus: http.StatusUnauthorized}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rec := serve(RequestHeaderSession(okHandler), http.MethodGet, "", map[string]string{SecurityTokenHeaderKey: tt.token}) + + if rec.Code != tt.wantStatus { + t.Fatalf("status = %d, want %d", rec.Code, tt.wantStatus) + } + if got := rec.Header().Get(SecurityTokenHeaderKey); got != "" { + t.Fatalf("%s response header = %q, want none", SecurityTokenHeaderKey, got) + } + }) + } +} + +func TestDefaultInstanceBoundsBodiesAtTheLibraryReadPoints(t *testing.T) { + usePackageModes(t, RequestModePlain, ResponseModeEnvelope) + errorLogs := countPackageErrorLogs(t) + tests := []struct { + name string + handler http.Handler + }{ + {name: "ProcessRequest", handler: ProcessRequest(okHandler)}, + {name: "RequestBody", handler: RequestBody(okHandler)}, + {name: "UnmarshalBody", handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var payload map[string]any + if response := UnmarshalBody(&payload, r); response != nil { + response.Write(w, r) + } + })}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + *errorLogs = 0 + + rec := serve(tt.handler, http.MethodPost, jsonBodyOfSize(defaultMaxBodyBytes+1), nil) + + if rec.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("status = %d, want 413", rec.Code) + } + if title, code := envelopeHeader(t, rec.Body.Bytes()); title != "Request content too large" || code != string(ResponseCodes.InvalidJSON) { + t.Fatalf("title, code = %q, %q, want the too-large title and %s", title, code, ResponseCodes.InvalidJSON) + } + if *errorLogs != 1 { + t.Fatalf("PrintError called %d times, want 1", *errorLogs) + } + }) + } +} + +func TestDefaultProcessBodyIsBounded(t *testing.T) { + tests := []struct { + name string + read func(r *http.Request) error + }{ + {name: "ProcessBody", read: func(r *http.Request) error { _, err := ProcessBody(r); return err }}, + {name: "ProcessEncryptedBody", read: func(r *http.Request) error { _, err := ProcessEncryptedBody(r); return err }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(jsonBodyOfSize(defaultMaxBodyBytes+1))) + + err := tt.read(req) + + var maxBytesErr *http.MaxBytesError + if !stderrors.As(err, &maxBytesErr) { + t.Fatalf("err = %v, want *http.MaxBytesError", err) + } + }) + } +} + +func TestDefaultProcessBodyReadsABodyAtTheLimit(t *testing.T) { + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(jsonBodyOfSize(defaultMaxBodyBytes))) + + if _, err := ProcessBody(req); err != nil { + t.Fatalf("ProcessBody = %v, want a body of exactly the limit accepted", err) + } +} + +func TestSetResponseModeProblemWritesProblemDetails(t *testing.T) { + previous := CurrentResponseMode + t.Cleanup(func() { CurrentResponseMode = previous }) + SetResponseMode(ResponseModeProblem) + + rec := serve(http.HandlerFunc(writeTaskNotFound), http.MethodGet, "", nil) + + if got := rec.Header().Get("Content-Type"); got != problemContentType { + t.Fatalf("Content-Type = %q, want %s", got, problemContentType) + } + if members := decodeMembers(t, rec.Body.Bytes()); members["type"] != "about:blank" || members["status"] != float64(http.StatusNotFound) { + t.Fatalf("members = %v, want a 404 problem", members) + } +} diff --git a/doc.go b/doc.go index 0786871..27136ca 100644 --- a/doc.go +++ b/doc.go @@ -7,8 +7,9 @@ // handler (usually the router) with (*API).Handler; the package-level // writers and middlewares then use that instance for the request. // -// Without an instance, the package-level functions use a deprecated default -// instance configured by package variables and the RegisterNew* functions. -// It behaves as in v0 so existing programs keep working; see +// Without an instance, the package-level functions use a default instance +// that answers like New() with its defaults. It logs through Print and +// PrintError, and the deprecated package variables and RegisterNew* +// functions still configure its modes, sensitive keys and components; see // docs/migration-v1.md for the move to New. package api diff --git a/docs/adr/0001-v1-instance-api.md b/docs/adr/0001-v1-instance-api.md index 8178719..8bd0842 100644 --- a/docs/adr/0001-v1-instance-api.md +++ b/docs/adr/0001-v1-instance-api.md @@ -3,6 +3,7 @@ - Status: Accepted (2026-11-21); implemented step by step through the v1 stories, all in v1.0.0: - 5.1 lands the instance, `Handler` and the two mode options (sections 2–3 for the modes; the `Get*Value*` helpers still use the default instance); - 5.2 the receiver, formatter and writer options; 5.3 codes as declared (section 4; landed, including a `ResponseFormatter` passed with `WithResponseFormatter`); 5.4 kind overrides and the error hook (section 7; landed); 5.5 the logger, redaction and a built-in instance writer that never exits (section 6; landed); 5.6 problem details (section 8; landed). Every section has landed for v1.0.0. +- Amended 2026-11-21 by the owner: in v1.0.0 the default instance behaves like `api.New()` with its defaults ([Amendment 1](#amendment-1-2026-11-21-the-default-instance-behaves-like-new)). Where a section below says the default instance keeps v0 behavior, the amendment wins. - Issues: API-07 (#21), API-02 (#16), API-12 (#26), the v1 part of API-01 (#15). - Related: [ADR 0002](0002-stdadapter-servemux.md) (stdadapter on ServeMux patterns) records the routing change of the same release (API-08). @@ -99,21 +100,21 @@ sequenceDiagram ### 4. Codes as declared (API-02) - An instance from `New` sends `core.ResponseCode` exactly as declared (`PLN-001`). `WithLowercaseCodes()` restores v0's lowercasing. -- The default instance keeps lowercasing. A v0 program that upgrades without code changes sends the same codes; only programs that move to `api.New` see declared codes. The trace suffix uses the same code text as the `code` field. +- The default instance keeps lowercasing. A v0 program that upgrades without code changes sends the same codes; only programs that move to `api.New` see declared codes. The trace suffix uses the same code text as the `code` field. *(Superseded by Amendment 1: the default instance sends codes as declared.)* ### 5. The deprecated default instance -- The package keeps one unexported default instance. Unlike instances from `New`, it reads the deprecated package variables at call time (`CurrentRequestMode`, `CurrentResponseMode`, `TraceVisibility`, `TraceIDLength`, `BlankSuccess`, `Print`/`PrintError`/`Fatal`, `SensitiveLogKeys`, body-logging flags) and the implementations set with `RegisterNew*`. v0 code compiles and behaves as in v0.11.0, the last v0 release (except the routing change in [ADR 0002](0002-stdadapter-servemux.md) (stdadapter on ServeMux patterns), which applies to every program that uses `stdadapter`). +- *(Superseded in part by Amendment 1.)* The package keeps one unexported default instance. Unlike instances from `New`, it reads the deprecated package variables at call time (`CurrentRequestMode`, `CurrentResponseMode`, `TraceVisibility`, `TraceIDLength`, `BlankSuccess`, `Print`/`PrintError`/`Fatal`, `SensitiveLogKeys`, body-logging flags) and the implementations set with `RegisterNew*`. v0 code compiles and behaves as in v0.11.0, the last v0 release (except the routing change in [ADR 0002](0002-stdadapter-servemux.md) (stdadapter on ServeMux patterns), which applies to every program that uses `stdadapter`). - `RegisterNew*`, `SetRequestMode`, `SetResponseMode` and the variables listed in the options table only affect the default instance; their doc comments say so and point at the option. -- `TraceVisibility`, `TraceIDLength`, `BlankSuccess`, `PrintFullEvent`, `LogRequestBody`, `LogResponseBody`, `MaxLoggedBodyBytes` get no instance option (no present need). Instances use the v0 defaults (1, 6, true, bodies not logged). They stay, not deprecated, documented as default-instance-only, because a deprecation needs a replacement in the same release. +- `TraceVisibility`, `TraceIDLength`, `BlankSuccess`, `PrintFullEvent`, `LogRequestBody`, `LogResponseBody`, `MaxLoggedBodyBytes` get no instance option (no present need). Instances use the v0 defaults (1, 6, true, bodies not logged). They stay, not deprecated, documented as default-instance-only, because a deprecation needs a replacement in the same release. *(Superseded by Amendment 1: `PrintFullEvent`, `LogRequestBody`, `LogResponseBody` and `MaxLoggedBodyBytes` are deprecated; they affect only the deprecated `Log*` functions.)* ### 6. Logger and redaction - `WithLogger(*slog.Logger)` takes the standard `log/slog` logger, so `api` gains no dependency (`api` must not import `jgolang/log`). Request and response lines become `slog` records with the same fields (`event_id`, `method`, `uri`, `status`, `duration_ms`, headers). - 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. +- 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. 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`. +- 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. 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) @@ -124,7 +125,7 @@ sequenceDiagram ### 8. RFC 9457 problem details (API-12) -- New response mode value `ResponseModeProblem` (`"problem"`), accepted by `WithResponseMode` only. `SetResponseMode` keeps its v0 set, so the default instance never writes problem details. +- New response mode value `ResponseModeProblem` (`"problem"`), accepted by `WithResponseMode` only. `SetResponseMode` keeps its v0 set, so the default instance never writes problem details. *(Superseded by Amendment 1: `SetResponseMode` accepts it.)* - In this mode an `Error` response is written as `application/problem+json`: ```json @@ -138,20 +139,37 @@ sequenceDiagram ### 9. Request body limit (SEC-05, owner answer Q35) -- `(*API).Handler` wraps a request body (not a nil or `http.NoBody` one) in `http.MaxBytesReader` at the instance's limit, so every reader under the instance is bounded: the built-in receivers, custom receivers and handlers that read `r.Body`. The default is 10 MiB; `WithMaxBodyBytes(n)` sets another. `n <= 0` is ignored (the earlier value or the default stays), so a zero configuration value never switches the bound off; `math.MaxInt64` means no practical limit. A later valid call wins. Nested instances each add their bound, so the smallest limit applies (an inner instance cannot raise an outer one). Only readers inside `a.Handler` are bounded: a `ProcessRequest` or `RequestBody` outside it runs with the default instance and reads without a limit. +- `(*API).Handler` wraps a request body (not a nil or `http.NoBody` one) in `http.MaxBytesReader` at the instance's limit, so every reader under the instance is bounded: the built-in receivers, custom receivers and handlers that read `r.Body`. The default is 10 MiB; `WithMaxBodyBytes(n)` sets another. `n <= 0` is ignored (the earlier value or the default stays), so a zero configuration value never switches the bound off; `math.MaxInt64` means no practical limit. A later valid call wins. Nested instances each add their bound, so the smallest limit applies (an inner instance cannot raise an outer one). Only readers inside `a.Handler` are bounded: a `ProcessRequest` or `RequestBody` outside it runs with the default instance and reads without a limit. *(Superseded by Amendment 1: outside `a.Handler` the default instance bounds bodies at 10 MiB at the library's read points.)* - `ProcessRequest`, `RequestBody` and `UnmarshalBody` of an instance answer a `*http.MaxBytesError` with 413, code `ResponseCodes.InvalidJSON` (`E002`, no new code) and the library title `Request content too large` (problem mode: `Request Entity Too Large`). `ProcessRequest` and `RequestBody` still log it as `request body rejected`. A custom receiver, or a handler that reads the body itself, gets the error and decides the answer. `WriteError`, `ProcessEncryptedBody`, `core` and the receivers do not change. -- The default instance has no limit (v0 behavior). A body over a limit the service installed itself (`http.MaxBytesHandler`) is answered with 400 `Invalid request content`, as in v0.11.0. +- The default instance has no limit (v0 behavior). A body over a limit the service installed itself (`http.MaxBytesHandler`) is answered with 400 `Invalid request content`, as in v0.11.0. *(Superseded by Amendment 1: 10 MiB at the library's read points, and 413 for any limit.)* ### 10. No request token echo (SEC-08, owner answer Q36) -- `Success.Write`, `Error.Write`, `Warning.Write` and `Informative.Write` (and so `WriteError` and the library's own rejections) leave an empty `SecurityToken` empty on an instance from `New`: the request token (`SecurityToken` header, `Authorization: Bearer`, the envelope `header.token` read by `ProcessRequest`) never reaches the response bodies written under its `Handler`. A middleware placed outside `a.Handler` (a token middleware, `ProcessRequest`) runs with the default instance and still echoes it. Plain bodies send `"token":""`, envelope bodies omit `header.token`, problem bodies never had it. The rule sits before the formatter, so it holds for custom formatters too. A token the handler sets on the response is sent as before. -- The default instance keeps the v0 echo (wire unchanged for v0 programs, like codes in section 4). +- `Success.Write`, `Error.Write`, `Warning.Write` and `Informative.Write` (and so `WriteError` and the library's own rejections) leave an empty `SecurityToken` empty on an instance from `New`: the request token (`SecurityToken` header, `Authorization: Bearer`, the envelope `header.token` read by `ProcessRequest`) never reaches the response bodies written under its `Handler`. A middleware placed outside `a.Handler` (a token middleware, `ProcessRequest`) runs with the default instance and still echoes it. Plain bodies send `"token":""`, envelope bodies omit `header.token`, problem bodies never had it. The rule sits before the formatter, so it holds for custom formatters too. A token the handler sets on the response is sent as before. *(Superseded by Amendment 1: a middleware outside `a.Handler` no longer echoes it either.)* +- The default instance keeps the v0 echo (wire unchanged for v0 programs, like codes in section 4). *(Superseded by Amendment 1: no echo, and no `RequestHeaderSession` copy.)* - No option restores the echo on an instance: nothing in this ADR or the migration guide needs it, and a handler that wants to return a token sets `SecurityToken` (for example from `rctx.SecurityToken`) in one line (YAGNI-01). A consumer need would be a new proposal. -- `RequestHeaderSession` does not copy the `SecurityToken` request header into the response header on an instance from `New` (owner decision, 2026-11-21): the header echoes the same request token as the bodies did. It still answers 401 when the header is empty. A handler that wants to return a token sets the header itself; no option restores the copy (YAGNI-01). Outside `a.Handler`, and on the default instance, it keeps copying it as in v0; after `ProcessRequest` that header holds the request token, which in envelope request mode can come from the body's `header.token`. +- `RequestHeaderSession` does not copy the `SecurityToken` request header into the response header on an instance from `New` (owner decision, 2026-11-21): the header echoes the same request token as the bodies did. It still answers 401 when the header is empty. A handler that wants to return a token sets the header itself; no option restores the copy (YAGNI-01). Outside `a.Handler`, and on the default instance, it keeps copying it as in v0; after `ProcessRequest` that header holds the request token, which in envelope request mode can come from the body's `header.token`. *(Superseded by Amendment 1: the default instance does not copy it either.)* + +## Amendment 1 (2026-11-21): the default instance behaves like New + +- Status: Accepted by the owner, 2026-11-21. Recorded in questions-for-owner, "Default instance = New (2026-11-21)". Implemented in two stacked changes: the wire behavior (codes, token echo, `RequestHeaderSession`, body limit, problem mode), then logging through `slog.Default`. +- Decision: in v1.0.0 the default instance (requests without an instance in the context, package helpers, middlewares outside `a.Handler`) shares the instance code path and behaves like `api.New()` with its defaults. It differs only in where its configuration comes from: + - logger: `slog.Default()`, read at call time (an instance without `WithLogger` logs nothing); + - sensitive log keys: the built-in list plus `SensitiveLogKeys`, read at call time; the variable can add keys but no longer remove a built-in one; + - modes, formatter settings and components: `SetRequestMode`/`SetResponseMode` (`CurrentRequestMode`, `CurrentResponseMode`), `TraceVisibility`, `TraceIDLength`, `BlankSuccess` and the `RegisterNew*` functions, which keep configuring it. +- Consequences for v0 programs that upgrade without code changes (breaking, `feat(api)!:`, in the release notes and the migration guide): + - codes as declared (section 4); no package-level switch back, `WithLowercaseCodes` on an instance is the way back; + - no request token echo in bodies and no `RequestHeaderSession` response header copy (section 10); + - request bodies bounded at 10 MiB at the library's read points (`ProcessRequest`, `RequestBody`, `ProcessBody`, `ProcessEncryptedBody`, `UnmarshalBody`), answered with 413 `E002` like an instance; any `*http.MaxBytesError`, a service-installed limit included, is a 413 (section 9). A handler that reads `r.Body` itself is unbounded outside an instance; + - `slog` records (section 6) through `slog.Default` instead of `Print`/`PrintError` lines. The package no longer calls `Print` or `PrintError` (only the deprecated `LogRequest`/`LogResponse*` call `Print`); bodies and the form are never logged; + - `SetResponseMode(ResponseModeProblem)` is accepted and the default instance writes problem details (section 8); + - the zero `ResponseFormatter` sends codes as declared and the zero `ResponseWriter` logs through `slog.Default` with the registered formatter's 500 body. +- Deprecations (constitution V): `PrintError` and `Fatal` are deprecated as ignored; `Print` is deprecated and used only by the deprecated `Log*`; `LogRequestBody`, `LogResponseBody`, `PrintFullEvent` and `MaxLoggedBodyBytes` are now deprecated (they affect only the deprecated `Log*` functions). `TraceVisibility`, `TraceIDLength` and `BlankSuccess` stay, not deprecated, configuring the default instance (no replacement). Nothing exported is removed. +- Why: one code path instead of a `fromNew` fork in every component; v1 is the major release where the safer defaults (SEC-05, SEC-08, IX) can reach every program; the alternative "Default instance switches to declared codes" below is now taken, and the cost (a wire change on upgrade) is paid once, in v1.0.0, with the migration guide as the upgrade path. ## What stays package-level in v1 -Not deprecated, shared by every instance, and listed as the narrowed `FUNC-04` deviation: name registries (`RegisterAdapter`/`NewRouter`, `RegisterAuth`, `RegisterCodec`, `RegisterCrypto`, `RegisterValidator`, `RegisterTraceProvider`, `doc.RegisterExporter`), `RegisterTraceIDProvider`, `GetRouteVar`, header key names (`SecurityTokenHeaderKey`, `EventIDHeaderKey`, `UserIDHeaderKey`), default titles and messages, `ResponseCodes`, `SkipPaths`, security credentials (`Username`, `Password`, `CustomTokenValidatorFunc`, `ValidateBasicAuthCredentialsFunc`), map methods (`AddNewMapMethod`, `ValidateMethods`), `RegisterParamValidator`, `RegisterNewAPISecurityGuarantor`, `Write(data, w)`, and the default-instance formatter and body-logging variables of section 5. A later assessment proposes a version plan for them. +Not deprecated, shared by every instance, and listed as the narrowed `FUNC-04` deviation: name registries (`RegisterAdapter`/`NewRouter`, `RegisterAuth`, `RegisterCodec`, `RegisterCrypto`, `RegisterValidator`, `RegisterTraceProvider`, `doc.RegisterExporter`), `RegisterTraceIDProvider`, `GetRouteVar`, header key names (`SecurityTokenHeaderKey`, `EventIDHeaderKey`, `UserIDHeaderKey`), default titles and messages, `ResponseCodes`, `SkipPaths`, security credentials (`Username`, `Password`, `CustomTokenValidatorFunc`, `ValidateBasicAuthCredentialsFunc`), map methods (`AddNewMapMethod`, `ValidateMethods`), `RegisterParamValidator`, `RegisterNewAPISecurityGuarantor`, `Write(data, w)`, and the default-instance formatter variables of section 5 (the body-logging variables are deprecated by Amendment 1). A later assessment proposes a version plan for them. ## Stateless names that stay as they are @@ -162,7 +180,7 @@ Not deprecated, shared by every instance, and listed as the narrowed `FUNC-04` d - Two binaries of one service configure their own instance; tests stop sharing state. - One extra context lookup per response. - Instances read no package variables for what they own; the `FUNC-04` deviation shrinks to the shared list above instead of disappearing. -- Programs that stay on the package-level API see no wire change in v1 except the routing change in [ADR 0002](0002-stdadapter-servemux.md) (stdadapter on ServeMux patterns) (and section 8's `Content-Type` note). They also get the error title and message that `RequestBasic.GetSecurityToken`, `GetUserID` and `GetEventID` were meant to send (#63; a fix the owner decided on 2026-11-21). +- *(Superseded by Amendment 1.)* Programs that stay on the package-level API see no wire change in v1 except the routing change in [ADR 0002](0002-stdadapter-servemux.md) (stdadapter on ServeMux patterns) (and section 8's `Content-Type` note). They also get the error title and message that `RequestBasic.GetSecurityToken`, `GetUserID` and `GetEventID` were meant to send (#63; a fix the owner decided on 2026-11-21). - v1 doubles some surface (option + deprecated name) until a v2 removes the deprecated names. ## Alternatives considered @@ -171,4 +189,4 @@ Not deprecated, shared by every instance, and listed as the narrowed `FUNC-04` d - **`/v2` module path:** not needed; v0 → v1 keeps the path. - **Instance owns `*doc.Docs` and routes (`a.Get(...)`):** duplicates the router helpers and couples the root package to the doc registry; the context needs none of it. - **Whole mapping function for kinds** (`WithStatusForKind(func(codes.Kind) int)`): more flexible, but every override must remember to fall back to `StatusForKind`. -- **Default instance switches to declared codes:** a wire change for every v0 program on upgrade with no way back short of migrating, since no new global setter is allowed. +- **Default instance switches to declared codes:** a wire change for every v0 program on upgrade with no way back short of migrating, since no new global setter is allowed. *(Taken by Amendment 1, together with the rest of `New`'s defaults.)* diff --git a/docs/legacy.md b/docs/legacy.md index 4ad8f47..e7e1136 100644 --- a/docs/legacy.md +++ b/docs/legacy.md @@ -50,7 +50,7 @@ The `header` carries metadata about the request and the device making it: device } ``` -`envelope.RequestInfo` is the Go type of this header. Each field fills a field of the request context (`api.Context(r.Context())`) and has an HTTP header equivalent. **The HTTP header wins**: a `header` field is used only when its HTTP header is absent. +`envelope.RequestInfo` is the Go type of this header. Each field fills a field of the request context (`api.Context(r.Context())`) and has an HTTP header equivalent (`token` is read, never echoed back in the response since v1.0.0). **The HTTP header wins**: a `header` field is used only when its HTTP header is absent. | JSON `header` field | HTTP header | Request context field | | --- | --- | --- | @@ -97,7 +97,7 @@ The envelope response mode (the default) writes a `header` with the response met } ``` -Empty header fields are omitted, except `type`. With the default `api.BlankSuccess = true`, success responses leave `title` and `message` empty; see [Responses](../README.md#responses) for `api.TraceVisibility` and the codes. +Empty header fields are omitted, except `type`. Since v1.0.0 the response `token` is sent only when the handler sets `SecurityToken`; the request token (`header.token` above, the `SecurityToken` or `Authorization: Bearer` header) is no longer echoed. With the default `api.BlankSuccess = true`, success responses leave `title` and `message` empty; see [Responses](../README.md#responses) for `api.TraceVisibility` and the codes. ## The v1 request flow @@ -127,7 +127,7 @@ Two exported implementations of `core.APIRequestReceiver` exist. Both follow the ### Method maps and the body middleware -`api.RequestBody` (`api.NewRequestBodyMiddleware(api.PPPMethodsKey)`) runs `ProcessBody` only for the methods in a named method map and answers `e002` when the body cannot be parsed. The maps are `api.PPPGMethodsKey` (POST, PUT, PATCH, GET), `api.PPPMethodsKey` (POST, PUT, PATCH) and `api.PPMethodsKey` (POST, PUT), plus `api.MethodPostKey`, `api.MethodGetKey` and `api.MethodPutKey` for single methods. `api.AddNewMapMethod` adds a map and `api.ValidateMethods` checks a method against one. +`api.RequestBody` (`api.NewRequestBodyMiddleware(api.PPPMethodsKey)`) runs `ProcessBody` only for the methods in a named method map and answers `E002` when the body cannot be parsed (413 for a body over the 10 MiB limit). The maps are `api.PPPGMethodsKey` (POST, PUT, PATCH, GET), `api.PPPMethodsKey` (POST, PUT, PATCH) and `api.PPMethodsKey` (POST, PUT), plus `api.MethodPostKey`, `api.MethodGetKey` and `api.MethodPutKey` for single methods. `api.AddNewMapMethod` adds a map and `api.ValidateMethods` checks a method against one. ### `api.Response`-returning helpers diff --git a/docs/migration-v1.md b/docs/migration-v1.md index 148f6ad..1394d7e 100644 --- a/docs/migration-v1.md +++ b/docs/migration-v1.md @@ -5,31 +5,39 @@ This guide takes a v0 program (v0.11.x) to `github.com/jgolang/api` v1. The desi ## Summary - The module path does not change. When v1.0.0 is tagged, upgrade with `go get github.com/jgolang/api@v1.0.0`; no import changes. -- v1 removes nothing. Every v0 name still compiles. Names replaced by an instance option are deprecated, and each one points at its option. -- A program that does not change its code sends the same bodies as v0, except for the `RequestBasic` getters' error below. Three things change for it: - - `stdadapter` routes through Go 1.22 `ServeMux` patterns ([step 2](#step-2-fix-routing-stdadapter)). This is the change most programs must act on. - - A non-empty `Content-Type` set in a response's `Headers` is now sent. v0 overwrote it with `application/json`. This applies to the default instance too. It is a fix, not a breaking change: v0 discarded a `Content-Type` the service set. An empty value counts as unset, and a `Content-Type` the handler set on `w.Header()` is still overwritten, as in v0. - - `RequestBasic.GetSecurityToken`, `GetUserID` and `GetEventID` (and so `GetRequestBasicInfo` and `GetRequestFullInfo`) return their own error: title `Request info error!` and the message `The session id was not obtained` (`user id`, `event id`). v0 meant to send it but returned the generic `Error getting header value!` / `The key header has not been obtained` instead (#63). This applies to instances too. A client that matched the old title or message must change. -- Configuration moves from package variables to an instance: `a := api.New(opts...)` and `a.Handler(router)` ([step 3](#step-3-move-to-apinew)). Handler code does not change. -- One breaking change outside routing, for programs that use `api.BasicToken`: it no longer copies the password into the `Basic-Secret` request header ([details](#breaking-no-basic-secret-header)). +- v1 removes nothing. Every v0 name still compiles. Names replaced by an instance option are deprecated, and each one points at its option or says it is ignored. +- **Breaking: the default instance behaves like `api.New()`** (owner decision, 2026-11-21). A program that does not change its code still gets v1's defaults: codes as declared, no request token echo and request bodies bounded at 10 MiB ([step 1](#step-1-upgrade-what-changes-without-code-changes)). A program that needs v0.11.0 behavior stays on v0.11.x. +- `stdadapter` routes through Go 1.22 `ServeMux` patterns ([step 2](#step-2-fix-routing-stdadapter)). +- Configuration moves from package variables to an instance: `a := api.New(opts...)` and `a.Handler(router)` ([step 3](#step-3-move-to-apinew)). Handler code does not change, and it is the only way back to v0's lowercase codes (`api.WithLowercaseCodes()`). +- Programs that use `api.BasicToken` no longer get the password in the `Basic-Secret` request header ([details](#breaking-no-basic-secret-header)). -Three steps, each one shippable on its own: +Three steps. Step 1 is the upgrade itself; read it before you ship it. -1. [Upgrade without code changes.](#step-1-upgrade-without-code-changes) +1. [Upgrade: what changes without code changes.](#step-1-upgrade-what-changes-without-code-changes) 2. [Fix routing (`stdadapter`).](#step-2-fix-routing-stdadapter) 3. [Move to `api.New`.](#step-3-move-to-apinew) -## Step 1: upgrade without code changes +## Step 1: upgrade: what changes without code changes -Requests that no `a.Handler` wraps use the default instance. It keeps v0's behavior: +Requests that no `a.Handler` wraps use the default instance. Since v1.0.0 it answers like `api.New()` with its defaults. `TestDefaultInstanceAnswersLikeNew` in `default_instance_test.go` checks that status, headers and body are the same as under `api.New().Handler`, apart from event IDs. + +**Wire changes** (clients, alerts and dashboards may need to change): + +- **Codes as declared.** The `code` field and the message trace suffix send `core.ResponseCode` as declared: `E001`, `E002`, `E300`, `TSK-001` where v0 sent `e001`, `e002`, `e300`, `tsk-001`. Built-in `jgolang/errors` codes that are declared lowercase (`d001`, `s001`) do not change. There is no package-level switch back; a service that must keep lowercase codes moves to `api.New(api.WithLowercaseCodes())` ([step 3](#step-3-move-to-apinew)). +- **No request token echo.** `Success`, `Error`, `Warning` and `Informative` (and so `WriteError`, the token middlewares' 401s and every library rejection) no longer copy the request token (`SecurityToken` header, `Authorization: Bearer`, the envelope `header.token`) into the response: plain bodies send `"token":""`, envelope bodies omit `header.token`. A token the handler sets (`api.Success{SecurityToken: renewed}`) is still sent. +- **`RequestHeaderSession`** no longer copies the `SecurityToken` request header into the response header. It still answers 401 without it. A handler that wants to return a token sets the header itself. +- **Request body limit.** `ProcessRequest`, `RequestBody`, `ProcessBody`, `ProcessEncryptedBody` and `UnmarshalBody` read at most 10 MiB. `ProcessRequest`, `RequestBody` and `UnmarshalBody` answer a larger body with 413, code `E002` and the title `Request content too large`; `ProcessBody` and `ProcessEncryptedBody` return the `*http.MaxBytesError`. A limit the service installed itself (`http.MaxBytesHandler`) is answered the same way (v0.11.0 answered 400 `Invalid request content`); such an outer limit can only lower the 10 MiB cap. To raise it, use `api.New(api.WithMaxBodyBytes(n)).Handler` ([step 3](#step-3-move-to-apinew)). A handler that reads `r.Body` itself is not bounded; wrap it with `http.MaxBytesHandler`, or move to `api.New` ([step 3](#step-3-move-to-apinew)), whose `Handler` bounds every reader. +- **Problem details.** `SetResponseMode(ResponseModeProblem)` is now accepted and the default instance writes RFC 9457 errors; v0 fell back to envelope. +- A non-empty `Content-Type` set in a response's `Headers` is now sent. v0 overwrote it with `application/json`. It is a fix, not a breaking change: v0 discarded a `Content-Type` the service set. An empty value counts as unset, and a `Content-Type` the handler set on `w.Header()` is still overwritten, as in v0. +- `RequestBasic.GetSecurityToken`, `GetUserID` and `GetEventID` (and so `GetRequestBasicInfo` and `GetRequestFullInfo`) return their own error: title `Request info error!` and the message `The session id was not obtained` (`user id`, `event id`). v0 meant to send it but returned the generic `Error getting header value!` / `The key header has not been obtained` instead (#63). + +**Logging** is unchanged from v0.11.0: -- Response codes are lowercased (`e001`, `tsk-001`). -- The package variables are read at call time: `CurrentRequestMode`, `CurrentResponseMode`, `TraceVisibility`, `TraceIDLength`, `BlankSuccess` and the body-logging variables. -- The components set with `RegisterNewAPIRequestReceiver`, `RegisterNewAPIResponseFormatter` and `RegisterNewAPIResponseWriter` are used. -- Bodies are v0's, except the `RequestBasic` getters' error: `GetSecurityToken`, `GetUserID` and `GetEventID` now send `Request info error!` and their own message ([summary](#summary), #63). - Logging goes through `Print` and `PrintError` and writes the same lines as v0.11.0. A response that cannot be encoded is answered with 500, as in v0.11.0; `Fatal` is never called. That 500 now drops the failed body's `Content-Type`, `Content-Encoding`, `Content-Length` and similar headers, and answers with no body instead of panicking when a registered formatter returns nil. - `SensitiveLogKeys` keeps its v0.11.0 list (with `cookie` and `session`) and masking (headers, JSON body fields, query and form values, the user information of the `uri`). +**What still configures the default instance:** `SetRequestMode`, `SetResponseMode` (`CurrentRequestMode`, `CurrentResponseMode`), `TraceVisibility`, `TraceIDLength`, `BlankSuccess`, `SensitiveLogKeys`, the body-logging variables and the components set with `RegisterNewAPIRequestReceiver`, `RegisterNewAPIResponseFormatter` and `RegisterNewAPIResponseWriter`. + Deprecated names are reported by staticcheck (`SA1019`) and by gopls in your editor. `go vet` does not report them. Fix the routing first (step 2); the deprecations can wait until step 3. ### Breaking: no Basic-Secret header @@ -90,7 +98,7 @@ func main() { a := api.New( api.WithRequestMode(api.RequestModePlain), api.WithResponseMode(api.ResponseModePlain), - api.WithLowercaseCodes(), // keep v0's codes; drop it to send them as declared + // api.WithLowercaseCodes(), // only if clients still need v0's lowercase codes ) docs := doc.New(doc.API{Title: "Tasks API", Version: "1.0.0"}) @@ -103,16 +111,16 @@ func main() { `createTask` does not change. `a.Handler` stores the instance in the request context. `ProcessRequest`, `RequestBody`, the token middlewares, the `Get*Value*` helpers, `WriteError` and `Write(w, r)` on every response type find it there. Route registration (`api.Get`/`Post`/…), `*doc.Docs` and the adapters do not change. -With `WithLowercaseCodes()` the handler answers byte for byte as on the default instance. Without it, codes are sent as declared: +The handler answers byte for byte as on the default instance. `WithLowercaseCodes()` restores the v0.11.0 code case: ```json -{"action":"","code":"tsk-001","content":null,"event_id":"evt1","info":null,"message":"title is required (evt1-tsk-001)","title":"Error response!","token":"","type":"error"} {"action":"","code":"TSK-001","content":null,"event_id":"evt1","info":null,"message":"title is required (evt1-TSK-001)","title":"Error response!","token":"","type":"error"} +{"action":"","code":"tsk-001","content":null,"event_id":"evt1","info":null,"message":"title is required (evt1-tsk-001)","title":"Error response!","token":"","type":"error"} ``` -`Example_migrationBeforeAndAfter` in `example_migration_test.go` proves it for the handler, served without `ProcessRequest`. Under `ProcessRequest` the bodies also match apart from the generated event IDs; `TestQuickStartAnswersLikeTheDefaultInstanceExceptCodeCase` in `instance_test.go` covers that. +`Example_migrationBeforeAndAfter` in `example_migration_test.go` proves it for the handler, served without `ProcessRequest`. Under `ProcessRequest` the bodies also match apart from the generated event IDs; `TestQuickStartAnswersLikeTheDefaultInstance` in `instance_test.go` covers that. -**Wrap the outermost chain.** Middlewares outside `a.Handler` use the default instance. So does `api.Write(data, w)`, which takes no request. Put `a.Handler` around everything, or a rejection from an outer `ProcessRequest` (invalid body, `e002`) keeps v0's code case and settings. With nested instances, the innermost one wins. +**Wrap the outermost chain.** Middlewares outside `a.Handler` use the default instance. So does `api.Write(data, w)`, which takes no request. Put `a.Handler` around everything, or a rejection from an outer `ProcessRequest` uses the package modes, logs through `Print`/`PrintError` instead of the instance logger and is bounded at 10 MiB instead of the instance's limit. With nested instances, the innermost one wins. ### Deprecated names and their options @@ -155,7 +163,7 @@ a := api.New( `Example_migrationOptions` is the compiled version. Pass only the options you need: `api.New()` already uses the built-in receiver, formatter and writer. -**Custom components.** The mode options, and `WithLowercaseCodes` for the formatter, apply to the built-in `RequestReceiver`, `RequestReceiverV2` and `ResponseFormatter`, also when you pass them with an option. A custom receiver or formatter decides on its own how it parses, what body it writes and its code text. A type that embeds a built-in one is custom: its promoted methods read the deprecated package mode variables and lowercase codes. A type that embeds `ResponseWriter` keeps v0 behavior and can still call `Fatal`. A nil value keeps the built-in. +**Custom components.** The mode options, and `WithLowercaseCodes` for the formatter, apply to the built-in `RequestReceiver`, `RequestReceiverV2` and `ResponseFormatter`, also when you pass them with an option. A custom receiver or formatter decides on its own how it parses, what body it writes and its code text. A type that embeds a built-in one is custom: its promoted methods read the deprecated package mode variables and send codes as declared. A type that embeds `ResponseWriter` behaves as the default instance's writer: it logs through `PrintError` and builds its 500 body with the registered formatter. A nil value keeps the built-in. ### What stays package-level @@ -172,9 +180,9 @@ These are not deprecated and are shared by every instance: `TraceVisibility`, `TraceIDLength`, `BlankSuccess`, `PrintFullEvent`, `LogRequestBody`, `LogResponseBody` and `MaxLoggedBodyBytes` are not deprecated either, but they affect only the default instance. Instances use their v0 defaults and never log bodies. -## What changes on an instance +## What an instance adds -**Codes as declared.** An instance sends `core.ResponseCode` as declared, in the `code` field and in the message trace suffix. The library's own codes in `ResponseCodes` are declared upper-case, so `api.New()` sends `E001`, `E002`, `E300`, `B001`, … where v0 sent `e001`. Clients, alerts and dashboards that match `e001` or `tsk-001` case-sensitively must change, or keep `api.WithLowercaseCodes()`. +**Codes.** An instance sends `core.ResponseCode` as declared, in the `code` field and in the message trace suffix, like the default instance. `api.WithLowercaseCodes()` restores v0's lowercasing (`e001`, `tsk-001`) for clients that cannot change yet. **Fixed formatter settings.** An instance uses `TraceVisibility = 1`, `TraceIDLength = 6` and `BlankSuccess = true`, and does not read the package variables. @@ -201,11 +209,11 @@ a := api.New( See the README "Logging" section for every record. -**No token echo.** An instance does not copy the request token (`SecurityToken` header, `Authorization: Bearer`, or the envelope `header.token`) into the response `token` field: plain bodies send `"token":""` and envelope bodies omit `header.token`, for every response kind, 401 included. A token the handler sets on the response (`api.Success{SecurityToken: renewed}`) is still sent, through any formatter. The default instance keeps echoing it. A client that read the token back from responses must keep its own copy, or the handler sets `SecurityToken` from `rctx.SecurityToken`. `RequestHeaderSession` no longer copies the `SecurityToken` request header into the response header either; it still answers 401 without it. A client that read the token back from that header must keep its own copy, or the handler sets the header. There is no option to restore the echo. Only responses written inside `a.Handler` follow this: a token middleware or `ProcessRequest` placed outside it uses the default instance and echoes the token, 401s included. +**No token echo.** Neither an instance nor the default instance copies the request token (`SecurityToken` header, `Authorization: Bearer`, or the envelope `header.token`) into the response `token` field: plain bodies send `"token":""` and envelope bodies omit `header.token`, for every response kind, 401 included. A token the handler sets on the response (`api.Success{SecurityToken: renewed}`) is still sent, through any formatter. A client that read the token back from responses must keep its own copy, or the handler sets `SecurityToken` from `rctx.SecurityToken`. `RequestHeaderSession` does not copy the `SecurityToken` request header into the response header either; it still answers 401 without it. There is no option to restore the echo. -**Request body limit.** An instance's `Handler` bounds request bodies at 10 MiB (`http.MaxBytesReader`). `ProcessRequest`, `RequestBody` and `UnmarshalBody` answer a larger body with 413, code `E002` and the title `Request content too large` (in problem mode, `Request Entity Too Large`); the default instance has no limit and answers a limit the service set itself with 400 as in v0. Set another limit with `api.WithMaxBodyBytes(n)`; `n <= 0` is ignored, and `math.MaxInt64` means no practical limit. Nested instance limits combine, so the smallest applies. Only readers inside `a.Handler` are bounded: a `ProcessRequest` or `RequestBody` outside it runs with the default instance and reads without a limit. A custom receiver, or a handler that reads `r.Body` itself, gets the `*http.MaxBytesError` and decides the answer. +**Request body limit.** An instance's `Handler` bounds every reader of the request body at 10 MiB (`http.MaxBytesReader`), a handler reading `r.Body` itself included; the default instance bounds only the library's read points. `ProcessRequest`, `RequestBody` and `UnmarshalBody` answer a larger body with 413, code `E002` and the title `Request content too large` (in problem mode, `Request Entity Too Large`). Set another limit with `api.WithMaxBodyBytes(n)`; `n <= 0` is ignored, and `math.MaxInt64` means no practical limit. Nested instance limits combine, so the smallest applies. A custom receiver, or a handler that reads `r.Body` itself, gets the `*http.MaxBytesError` and decides the answer. -**Problem details.** `api.WithResponseMode(api.ResponseModeProblem)` writes errors as RFC 9457 `application/problem+json`. That includes the library's own rejections under the instance: `ProcessRequest`'s invalid body (400, `E002`) and panic (500, `E300`), the token and header middlewares (401, 415) and `RequestBody`. Other responses are written as their content alone. Only instances accept this mode; `SetResponseMode(ResponseModeProblem)` falls back to envelope. A non-empty `Content-Type` in the response's `Headers` still wins over `application/problem+json`. +**Problem details.** `api.WithResponseMode(api.ResponseModeProblem)` (or `SetResponseMode` on the default instance) writes errors as RFC 9457 `application/problem+json`. That includes the library's own rejections: `ProcessRequest`'s invalid body (400, `E002`) and panic (500, `E300`), the token and header middlewares (401, 415) and `RequestBody`. Other responses are written as their content alone. A non-empty `Content-Type` in the response's `Headers` still wins over `application/problem+json`. ```json {"type":"about:blank","title":"Bad Request","status":400,"detail":"title is required","code":"TSK-001","event_id":"evt1"} @@ -226,6 +234,8 @@ a.Handler(http.HandlerFunc(createTask)).ServeHTTP(rec, req) ## Checklist - [ ] Upgrade and build. Nothing is removed, so the program compiles. +- [ ] Check clients, alerts and dashboards that match lowercase codes (`e001`), read the request token back from responses or from the `SecurityToken` response header, or send bodies over 10 MiB ([step 1](#step-1-upgrade-what-changes-without-code-changes)). +- [ ] If clients send bodies over 10 MiB, raise the limit with `api.New(api.WithMaxBodyBytes(n)).Handler`; `http.MaxBytesHandler` can only lower it. - [ ] Start the service once (or build its router in a test): fix every registration panic (conflicts, methods, wildcard names). - [ ] Check trailing-slash clients, HEAD skip paths, 405 handling and `GODEBUG=httpmuxgo121`. - [ ] Validate route variables that reach file paths, headers or logs. @@ -233,7 +243,6 @@ a.Handler(http.HandlerFunc(createTask)).ServeHTTP(rec, req) - [ ] Check responses that set a `Content-Type` in `Headers`: it is now sent (one set on `w.Header()` is still overwritten). - [ ] Create one instance with `api.New` and wrap the outermost handler with `a.Handler`. - [ ] Replace each deprecated name with its option (staticcheck `SA1019` lists them). -- [ ] Decide on code case: keep `api.WithLowercaseCodes()`, or update clients and alerts to the declared codes. +- [ ] Decide on code case: update clients and alerts to the declared codes, or use `api.WithLowercaseCodes()`. - [ ] Give the instance a `*slog.Logger`, or accept that it logs nothing. -- [ ] Check clients that read the request token back from response bodies or from the `SecurityToken` response header set by `RequestHeaderSession`: an instance no longer echoes it. - [ ] Move tests to `a.Handler(h).ServeHTTP` instead of resetting package variables. diff --git a/example_migration_test.go b/example_migration_test.go index 0a70122..4a195f8 100644 --- a/example_migration_test.go +++ b/example_migration_test.go @@ -46,8 +46,9 @@ func serveMigration(handler http.Handler, body string) *httptest.ResponseRecorde } // Example_migrationBeforeAndAfter moves a v0 program that configures the -// package-level modes to an instance. With WithLowercaseCodes the body is -// byte-identical; with New() alone the code is sent as declared. +// package-level modes to an instance. Since v1.0.0 the default instance +// behaves like New(), so the body is byte-identical; WithLowercaseCodes +// restores the v0.11.0 code case for clients that compare codes exactly. func Example_migrationBeforeAndAfter() { previousRequestMode, previousResponseMode := api.CurrentRequestMode, api.CurrentResponseMode defer func() { @@ -61,28 +62,28 @@ func Example_migrationBeforeAndAfter() { before := http.HandlerFunc(migrationCreateTask) // After (v1): one instance, the router wrapped by its Handler. - lowercase := api.New( + declared := api.New( api.WithRequestMode(api.RequestModePlain), api.WithResponseMode(api.ResponseModePlain), - api.WithLowercaseCodes(), ).Handler(http.HandlerFunc(migrationCreateTask)) - declared := api.New( + lowercase := api.New( api.WithRequestMode(api.RequestModePlain), api.WithResponseMode(api.ResponseModePlain), + api.WithLowercaseCodes(), ).Handler(http.HandlerFunc(migrationCreateTask)) beforeBody := serveMigration(before, `{"title":""}`).Body.String() - lowercaseBody := serveMigration(lowercase, `{"title":""}`).Body.String() declaredRec := serveMigration(declared, `{"title":""}`) + lowercaseBody := serveMigration(lowercase, `{"title":""}`).Body.String() - fmt.Println("identical with WithLowercaseCodes:", beforeBody == lowercaseBody) - fmt.Print("before: ", beforeBody) - fmt.Print("New(): ", declaredRec.Body.String()) + fmt.Println("identical with New():", beforeBody == declaredRec.Body.String()) + fmt.Print("New(): ", declaredRec.Body.String()) + fmt.Print("WithLowercaseCodes(): ", lowercaseBody) fmt.Println("status:", declaredRec.Code) // Output: - // identical with WithLowercaseCodes: true - // before: {"action":"","code":"tsk-001","content":null,"event_id":"evt1","info":null,"message":"title is required (evt1-tsk-001)","title":"Error response!","token":"","type":"error"} - // New(): {"action":"","code":"TSK-001","content":null,"event_id":"evt1","info":null,"message":"title is required (evt1-TSK-001)","title":"Error response!","token":"","type":"error"} + // identical with New(): true + // New(): {"action":"","code":"TSK-001","content":null,"event_id":"evt1","info":null,"message":"title is required (evt1-TSK-001)","title":"Error response!","token":"","type":"error"} + // WithLowercaseCodes(): {"action":"","code":"tsk-001","content":null,"event_id":"evt1","info":null,"message":"title is required (evt1-tsk-001)","title":"Error response!","token":"","type":"error"} // status: 400 } diff --git a/functions.go b/functions.go index 2d24565..ffbc967 100644 --- a/functions.go +++ b/functions.go @@ -255,13 +255,18 @@ func GetQueryParamValueBool(queryParamName string, r *http.Request) (bool, Respo return value, nil } -// UnmarshalBody parses and validates request body to a struct +// UnmarshalBody parses and validates request body to a struct. A body over +// the instance's limit (10 MiB without an instance) is answered with 413. +// Without an instance in r, it replaces r.Body with an http.MaxBytesReader; +// it has no ResponseWriter, so the server is not told to close the +// connection on overflow (ProcessRequest and RequestBody pass theirs). func UnmarshalBody(v interface{}, r *http.Request) Response { + boundDefaultBody(nil, r) err := api.UnmarshalBody(v, r) if err != nil { a := instanceFrom(r) a.logError(r, "request body not unmarshaled", err) - if bodyTooLarge(a, err) { + if bodyTooLarge(err) { return bodyTooLargeError() } return Error{ diff --git a/instance.go b/instance.go index df93bc6..3f0efe3 100644 --- a/instance.go +++ b/instance.go @@ -17,20 +17,15 @@ import ( // CurrentResponseMode; their modes come only from its options. A custom // component that embeds RequestReceiver, RequestReceiverV2 or // ResponseFormatter is used as given, so its promoted methods read the -// package mode variables. An API from New sends response codes as declared -// unless built with WithLowercaseCodes; the default instance lowercases them. -// Only an API from New can write RFC 9457 problem details (ResponseModeProblem). -// WriteError answers with the instance's WithKindStatus overrides and calls -// its WithErrorHook; the default instance has neither. -// An API from New logs only through its WithLogger logger and masks the keys -// of WithSensitiveLogKeys; the default instance logs through Print and -// PrintError and masks SensitiveLogKeys. -// An API from New bounds request bodies at 10 MiB unless WithMaxBodyBytes -// sets another limit; the default instance does not bound them. -// An API from New does not echo the request token in response bodies: a -// response carries a token only when the handler sets SecurityToken; the -// default instance fills an empty one from the request, as v0 does. -// A zero or nil API is the default instance. +// package mode variables. WriteError answers with the instance's +// WithKindStatus overrides and calls its WithErrorHook. +// +// Requests that carry no instance are served by the default instance, which +// behaves like New() with its defaults: codes as declared, no request token +// echo and request bodies bounded at 10 MiB where the library reads them. +// It takes its modes, formatter settings and components from the deprecated +// package-level setters, and logs through Print and PrintError, masking +// SensitiveLogKeys. A zero or nil API is the default instance. type API struct { core *core.API kindStatus map[codes.Kind]int @@ -64,17 +59,16 @@ type Option func(*options) // New returns an API configured by opts. Without options it parses plain // requests, writes envelope responses and uses the built-in request -// receiver, response formatter and response writer, the v0 defaults. Unlike -// the default instance, its built-in formatter sends response codes as -// declared (PLN-001 stays PLN-001); WithLowercaseCodes restores the v0 -// lowercasing. The security guarantor and param validator are shared with -// the default instance: RegisterNewAPISecurityGuarantor and -// RegisterParamValidator apply to every instance. WriteError has no kind -// overrides and no error hook unless WithKindStatus or WithErrorHook set them. -// It writes no logs unless WithLogger sets a logger, and its built-in -// response writer never exits; a custom writer owns its behavior. Its -// Handler bounds request bodies at 10 MiB unless WithMaxBodyBytes sets -// another limit. +// receiver, response formatter and response writer, the v0 defaults. Its +// built-in formatter sends response codes as declared (PLN-001 stays +// PLN-001); WithLowercaseCodes restores the v0 lowercasing. The security +// guarantor and param validator are shared with the default instance: +// RegisterNewAPISecurityGuarantor and RegisterParamValidator apply to every +// instance. WriteError has no kind overrides and no error hook unless +// WithKindStatus or WithErrorHook set them. It writes no logs unless +// WithLogger sets a logger, and its built-in response writer never exits; a +// custom writer owns its behavior. Its Handler bounds request bodies at +// 10 MiB unless WithMaxBodyBytes sets another limit. func New(opts ...Option) *API { o := options{ requestMode: RequestModePlain, @@ -106,7 +100,7 @@ func New(opts ...Option) *API { } // defaultMaxBodyBytes is the request body limit of an API from New without -// WithMaxBodyBytes. +// WithMaxBodyBytes, and of the default instance. const defaultMaxBodyBytes = 10 << 20 // requestReceiver returns the receiver New uses. A built-in receiver without @@ -158,7 +152,7 @@ func (o options) responseFormatter() core.APIResponseFormatter { // cannot set these fields, so they are always the instance's. func (o options) bindFormatter(formatter ResponseFormatter) ResponseFormatter { formatter = formatter.withMode(o.responseMode) - formatter.declaredCodes = !o.lowercaseCodes + formatter.lowercaseCodes = o.lowercaseCodes formatter.v0Settings = true return formatter } @@ -193,10 +187,6 @@ func WithRequestMode(mode RequestMode) Option { // WithResponseFormatter alone decides the body. func WithResponseMode(mode ResponseMode) Option { return func(o *options) { - if mode == ResponseModeProblem { - o.responseMode = mode - return - } o.responseMode = normalizeResponseMode(mode) } } @@ -206,7 +196,7 @@ func WithResponseMode(mode ResponseMode) Option { // as v0 does. Without it, an instance from New sends codes as declared // (PLN-001 stays PLN-001). A custom formatter set with WithResponseFormatter // alone decides the code, and this option does not apply to it. The default -// instance always lowercases. +// instance sends codes as declared too. func WithLowercaseCodes() Option { return func(o *options) { o.lowercaseCodes = true @@ -285,9 +275,9 @@ func WithLogger(logger *slog.Logger) Option { // logged without the value. A key matches any name that contains it, // ignoring case. Secrets in path segments (/reset/{token}) are not masked. // The defaults (the shipped SensitiveLogKeys list, which includes cookie and -// session since v0.11.0; changes to the variable do not apply) are always -// kept: this option only adds. Keys are trimmed and lowercased, blank keys -// are ignored; repeat it to add more. +// session since v0.11.0; changes to the variable apply only to the default +// instance) are always kept: this option only adds. Keys are trimmed and +// lowercased, blank keys are ignored; repeat it to add more. func WithSensitiveLogKeys(keys ...string) Option { return func(o *options) { for _, key := range keys { @@ -311,7 +301,9 @@ func WithSensitiveLogKeys(keys ...string) Option { // never removes the bound; pass math.MaxInt64 for no practical limit. A // later valid call replaces an earlier one. With nested instances each // Handler adds its bound, so the smallest limit applies. The default instance -// has no limit; bound its bodies with http.MaxBytesHandler. +// bounds bodies at 10 MiB where the library reads them (ProcessRequest, +// RequestBody, ProcessBody, ProcessEncryptedBody, UnmarshalBody); a handler +// that reads r.Body itself outside an instance is not bounded. func WithMaxBodyBytes(n int64) Option { return func(o *options) { if n <= 0 { @@ -339,8 +331,9 @@ func WithRequestReceiver(receiver core.APIRequestReceiver) Option { // mode and code case; a custom formatter alone decides the body and its code // text, and WithResponseMode and WithLowercaseCodes do not apply to it. A // type that embeds ResponseFormatter is custom: its promoted methods read -// CurrentResponseMode and lowercase codes. A nil interface value keeps the -// built-in; a typed nil pointer to a custom formatter is used as given. +// CurrentResponseMode and send codes as declared. A nil interface value +// keeps the built-in; a typed nil pointer to a custom formatter is used as +// given. func WithResponseFormatter(formatter core.APIResponseFormatter) Option { return func(o *options) { o.formatter = formatter @@ -412,9 +405,9 @@ func (a *API) Handler(next http.Handler) http.Handler { type instanceKey struct{} // defaultInstance serves requests that carry no instance. It wraps the -// package-level core, so RegisterNew* and the package mode variables keep -// their v0 behavior. -var defaultInstance = &API{core: api} +// package-level core, so RegisterNew* and the package mode variables +// configure it. +var defaultInstance = &API{core: api, maxBodyBytes: defaultMaxBodyBytes} // instanceFrom returns the instance stored in r's context by Handler, or the // default instance when there is none. @@ -427,3 +420,14 @@ func instanceFrom(r *http.Request) *API { } return defaultInstance } + +// boundDefaultBody bounds r's body at the default limit when r is served by +// the default instance, which has no Handler to do it. An instance's Handler +// already bounded the body, so its requests are left alone. w may be nil for +// callers that have no response writer. +func boundDefaultBody(w http.ResponseWriter, r *http.Request) { + if r == nil || r.Body == nil || r.Body == http.NoBody || instanceFrom(r) != defaultInstance { + return + } + r.Body = http.MaxBytesReader(w, r.Body, defaultMaxBodyBytes) +} diff --git a/instance_codes_test.go b/instance_codes_test.go index 0d000cf..21a4ad1 100644 --- a/instance_codes_test.go +++ b/instance_codes_test.go @@ -76,8 +76,8 @@ func TestInstanceCodeCase(t *testing.T) { {"declared Error400", declaredInstance, "Error400", "PLN-001", "title is required (evt-12-PLN-001)"}, {"lowercase WriteError", lowercaseInstance, "WriteError", "pln-001", "title is required (evt-12-pln-001)"}, {"lowercase Error400", lowercaseInstance, "Error400", "pln-001", "title is required (evt-12-pln-001)"}, - {"default instance WriteError", noInstance, "WriteError", "pln-001", "title is required (evt-12-pln-001)"}, - {"default instance Error400", noInstance, "Error400", "pln-001", "title is required (evt-12-pln-001)"}, + {"default instance WriteError", noInstance, "WriteError", "PLN-001", "title is required (evt-12-PLN-001)"}, + {"default instance Error400", noInstance, "Error400", "PLN-001", "title is required (evt-12-PLN-001)"}, {"declared default error code", declaredInstance, "Error400 default code", "E001", "The service has not completed the operation! (evt-12-E001)"}, {"declared success", declaredInstance, "Success", "0000", ""}, {"declared warning", declaredInstance, "Warning", "0000", "The application has been successful but with potential problems! (evt-12-0000)"}, @@ -152,7 +152,7 @@ func TestInstancesServeConcurrentlyWithTheirOwnCodeCase(t *testing.T) { "PLN-001": New().Handler(codeWriters["WriteError"]), "pln-001": New(WithLowercaseCodes()).Handler(codeWriters["WriteError"]), } - // The default instance lowercases as in v0. + // The default instance sends codes as declared, like New(). defaultHandler := codeWriters["WriteError"] var wg sync.WaitGroup @@ -167,8 +167,8 @@ func TestInstancesServeConcurrentlyWithTheirOwnCodeCase(t *testing.T) { } wg.Go(func() { rec := serve(defaultHandler, http.MethodGet, "", nil) - if code, _ := codeAndMessage(rec.Body.Bytes()); code != "pln-001" { - t.Errorf("default instance code = %q, want pln-001", code) + if code, _ := codeAndMessage(rec.Body.Bytes()); code != "PLN-001" { + t.Errorf("default instance code = %q, want PLN-001", code) } }) } @@ -194,11 +194,11 @@ func TestInstanceIgnoresPackageFormatterSettings(t *testing.T) { blankSuccess bool wantDefaultMessage string }{ - {1, 6, true, "title is required (evt-12-pln-001)"}, + {1, 6, true, "title is required (evt-12-PLN-001)"}, {0, 6, true, "title is required"}, - {2, 6, true, "title is required (pln-001)"}, + {2, 6, true, "title is required (PLN-001)"}, {3, 3, true, "title is required (evt)"}, - {1, 3, false, "title is required (evt-pln-001)"}, + {1, 3, false, "title is required (evt-PLN-001)"}, } for _, tt := range tests { t.Run(fmt.Sprintf("%d/%d/%t", tt.visibility, tt.idLength, tt.blankSuccess), func(t *testing.T) { @@ -229,7 +229,7 @@ func TestInstanceIgnoresPackageFormatterSettings(t *testing.T) { // embeddedFormatter is a custom formatter that embeds the built-in one. type embeddedFormatter struct{ ResponseFormatter } -func TestEmbeddedFormatterLowercasesAndUsesThePackageMode(t *testing.T) { +func TestEmbeddedFormatterDeclaresCodesAndUsesThePackageMode(t *testing.T) { usePackageModes(t, RequestModePlain, ResponseModePlain) a := New(WithResponseMode(ResponseModeEnvelope), WithResponseFormatter(embeddedFormatter{})) @@ -238,8 +238,8 @@ func TestEmbeddedFormatterLowercasesAndUsesThePackageMode(t *testing.T) { if got := responseModeOf(rec.Body.Bytes()); got != ResponseModePlain { t.Errorf("response mode = %q, want the package mode plain", got) } - if code, _ := codeAndMessage(rec.Body.Bytes()); code != "pln-001" { - t.Errorf("code = %q, want pln-001", code) + if code, _ := codeAndMessage(rec.Body.Bytes()); code != "PLN-001" { + t.Errorf("code = %q, want PLN-001", code) } } @@ -252,7 +252,7 @@ func TestProcessRequestRejectionUsesTheInstanceCodeCase(t *testing.T) { }{ {"New()", New().Handler, "E002"}, {"New(WithLowercaseCodes())", New(WithLowercaseCodes()).Handler, "e002"}, - {"default instance", func(h http.Handler) http.Handler { return h }, "e002"}, + {"default instance", func(h http.Handler) http.Handler { return h }, "E002"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/instance_max_body_test.go b/instance_max_body_test.go index e82cd24..1a2fc1b 100644 --- a/instance_max_body_test.go +++ b/instance_max_body_test.go @@ -182,28 +182,28 @@ func TestProblemModeBodyOverLimit(t *testing.T) { } } -func TestDefaultInstanceHasNoBodyLimit(t *testing.T) { +func TestDefaultInstanceAcceptsABodyAtTheLimit(t *testing.T) { var reached bool - rec := serve(ProcessRequest(reachHandler(&reached)), http.MethodPost, jsonBodyOfSize(defaultMaxBodyBytes+1), nil) + rec := serve(ProcessRequest(reachHandler(&reached)), http.MethodPost, jsonBodyOfSize(defaultMaxBodyBytes), nil) if rec.Code != http.StatusOK || !reached { t.Fatalf("status = %d, reached = %v; want 200 with the handler", rec.Code, reached) } } -func TestDefaultInstanceKeeps400ForAServiceLimit(t *testing.T) { +func TestDefaultInstanceAnswers413ForAServiceLimit(t *testing.T) { var reached bool handler := http.MaxBytesHandler(ProcessRequest(reachHandler(&reached)), 16) rec := serve(handler, http.MethodPost, jsonBodyOfSize(17), nil) - if rec.Code != http.StatusBadRequest || reached { - t.Fatalf("status = %d, reached = %v; want 400 without the handler", rec.Code, reached) + if rec.Code != http.StatusRequestEntityTooLarge || reached { + t.Fatalf("status = %d, reached = %v; want 413 without the handler", rec.Code, reached) } title, code := envelopeHeader(t, rec.Body.Bytes()) - if title != "Invalid request content" || code != "e002" { - t.Fatalf("title, code = %q, %q; want %q, %q", title, code, "Invalid request content", "e002") + if title != "Request content too large" || code != "E002" { + t.Fatalf("title, code = %q, %q; want %q, %q", title, code, "Request content too large", "E002") } } @@ -219,3 +219,38 @@ func TestHandlerDoesNotWrapABodylessRequest(t *testing.T) { t.Fatalf("body = %T, want http.NoBody", body) } } + +// TestInstanceLimitAboveTheDefaultIsNotCapped checks that the default +// instance's 10 MiB bound never applies under an instance with a higher limit. +func TestInstanceLimitAboveTheDefaultIsNotCapped(t *testing.T) { + unmarshal := func(reached *bool) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var payload map[string]string + if response := UnmarshalBody(&payload, r); response != nil { + response.Write(w, r) + return + } + reachHandler(reached)(w, r) + }) + } + tests := []struct { + name string + handler func(reached *bool) http.Handler + }{ + {name: "ProcessRequest", handler: func(reached *bool) http.Handler { return ProcessRequest(reachHandler(reached)) }}, + {name: "RequestBody", handler: func(reached *bool) http.Handler { return RequestBody(reachHandler(reached)) }}, + {name: "UnmarshalBody", handler: unmarshal}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var reached bool + a := New(WithMaxBodyBytes(defaultMaxBodyBytes + 16)) + + rec := serve(a.Handler(tt.handler(&reached)), http.MethodPost, jsonBodyOfSize(defaultMaxBodyBytes+1), nil) + + if rec.Code != http.StatusOK || !reached { + t.Fatalf("status = %d, reached = %v; want 200 with the handler", rec.Code, reached) + } + }) + } +} diff --git a/instance_problem_test.go b/instance_problem_test.go index 5c500f2..8ed475e 100644 --- a/instance_problem_test.go +++ b/instance_problem_test.go @@ -337,36 +337,6 @@ func TestBuiltInWriterKeepsAContentTypeSetInHeaders(t *testing.T) { } } -func TestSetResponseModeTreatsProblemAsUnknown(t *testing.T) { - usePackageModes(t, CurrentRequestMode, CurrentResponseMode) - - SetResponseMode(ResponseModeProblem) - rec := serve(http.HandlerFunc(writeTaskNotFound), http.MethodGet, "", nil) - - if CurrentResponseMode != ResponseModeEnvelope { - t.Fatalf("CurrentResponseMode = %s, want envelope", CurrentResponseMode) - } - assertEnvelopeError(t, rec.Header().Get("Content-Type"), rec.Body.Bytes()) -} - -func TestDefaultInstanceWritesEnvelopeWhenThePackageModeIsProblem(t *testing.T) { - usePackageModes(t, RequestModePlain, ResponseModeProblem) - - rec := serve(http.HandlerFunc(writeTaskNotFound), http.MethodGet, "", nil) - - assertEnvelopeError(t, rec.Header().Get("Content-Type"), rec.Body.Bytes()) -} - -func assertEnvelopeError(t *testing.T, contentType string, body []byte) { - t.Helper() - if contentType != "application/json" { - t.Fatalf("Content-Type = %q, want application/json", contentType) - } - if got := responseModeOf(body); got != ResponseModeEnvelope { - t.Fatalf("response mode = %s, want envelope (%s)", got, body) - } -} - func TestProblemInstanceAnswersProblem500WhenResponseCannotBeEncoded(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { SuccessWithContent(math.NaN()).Write(w, r) diff --git a/instance_test.go b/instance_test.go index 69fccda..b914751 100644 --- a/instance_test.go +++ b/instance_test.go @@ -133,7 +133,8 @@ func TestNewFallsBackToDefaultsForUnknownModes(t *testing.T) { } // TestPackageModesKeepV0Bodies pins the bodies written by v0.10.0 (baseline -// ad03d5f) for handlers that are not wrapped by an instance. +// ad03d5f) for handlers that are not wrapped by an instance, except that +// since v1.0.0 the default instance sends codes as declared, like New(). func TestPackageModesKeepV0Bodies(t *testing.T) { notFound := errors.NewC(codes.New("PLN-111", "task not found").WithKind(codes.KindNotFound), "x") writers := map[string]http.HandlerFunc{ @@ -151,11 +152,11 @@ func TestPackageModesKeepV0Bodies(t *testing.T) { wantBody string }{ {ResponseModePlain, "success", 200, `{"action":"","code":"0000","content":null,"event_id":"evt-123456789","info":null,"message":"","title":"","token":"","type":"success"}` + "\n"}, - {ResponseModePlain, "error400", 400, `{"action":"","code":"e001","content":null,"event_id":"evt-123456789","info":null,"message":"The service has not completed the operation! (evt-12-e001)","title":"Error response!","token":"","type":"error"}` + "\n"}, - {ResponseModePlain, "writeError", 404, `{"action":"","code":"pln-111","content":null,"event_id":"evt-123456789","info":null,"message":"task not found (evt-12-pln-111)","title":"Error response!","token":"","type":"error"}` + "\n"}, + {ResponseModePlain, "error400", 400, `{"action":"","code":"E001","content":null,"event_id":"evt-123456789","info":null,"message":"The service has not completed the operation! (evt-12-E001)","title":"Error response!","token":"","type":"error"}` + "\n"}, + {ResponseModePlain, "writeError", 404, `{"action":"","code":"PLN-111","content":null,"event_id":"evt-123456789","info":null,"message":"task not found (evt-12-PLN-111)","title":"Error response!","token":"","type":"error"}` + "\n"}, {ResponseModeEnvelope, "success", 200, `{"header":{"type":"success","code":"0000","event_id":"evt-123456789"}}` + "\n"}, - {ResponseModeEnvelope, "error400", 400, `{"header":{"type":"error","title":"Error response!","message":"The service has not completed the operation! (evt-12-e001)","code":"e001","event_id":"evt-123456789"}}` + "\n"}, - {ResponseModeEnvelope, "writeError", 404, `{"header":{"type":"error","title":"Error response!","message":"task not found (evt-12-pln-111)","code":"pln-111","event_id":"evt-123456789"}}` + "\n"}, + {ResponseModeEnvelope, "error400", 400, `{"header":{"type":"error","title":"Error response!","message":"The service has not completed the operation! (evt-12-E001)","code":"E001","event_id":"evt-123456789"}}` + "\n"}, + {ResponseModeEnvelope, "writeError", 404, `{"header":{"type":"error","title":"Error response!","message":"task not found (evt-12-PLN-111)","code":"PLN-111","event_id":"evt-123456789"}}` + "\n"}, {ResponseModePlain, "warning", 200, `{"action":"","code":"0000","content":null,"event_id":"evt-123456789","info":null,"message":"The application has been successful but with potential problems! (evt-12-0000)","title":"Alert!","token":"","type":"warning"}` + "\n"}, {ResponseModePlain, "informative", 200, `{"action":"","code":"0000","content":null,"event_id":"evt-123456789","info":null,"message":"The request has been successful! (evt-12-0000)","title":"Information!","token":"","type":"info"}` + "\n"}, {ResponseModeEnvelope, "warning", 200, `{"header":{"type":"warning","title":"Alert!","message":"The application has been successful but with potential problems! (evt-12-0000)","code":"0000","event_id":"evt-123456789"}}` + "\n"}, @@ -289,7 +290,7 @@ func requestWithInstance(a *API) *http.Request { return served } -func TestQuickStartAnswersLikeTheDefaultInstanceExceptCodeCase(t *testing.T) { +func TestQuickStartAnswersLikeTheDefaultInstance(t *testing.T) { usePackageModes(t, RequestModePlain, ResponseModeEnvelope) titleRequired := codes.New("TSK-001", "title is required").WithKind(codes.KindValidation) createTask := ProcessRequest(func(w http.ResponseWriter, r *http.Request) { @@ -314,7 +315,7 @@ func TestQuickStartAnswersLikeTheDefaultInstanceExceptCodeCase(t *testing.T) { for _, body := range []string{`{"title":"Buy milk"}`, `{"title":""}`, `{"title":`, `[1]`} { t.Run(body, func(t *testing.T) { withoutInstance := serve(createTask, http.MethodPost, body, nil) - // WithLowercaseCodes is the one option that keeps an instance's codes as v0 sends them. + // WithLowercaseCodes keeps an instance's codes as v0 sent them. lowercase := serve(New(WithLowercaseCodes()).Handler(createTask), http.MethodPost, body, nil) declared := serve(New().Handler(createTask), http.MethodPost, body, nil) @@ -327,13 +328,13 @@ func TestQuickStartAnswersLikeTheDefaultInstanceExceptCodeCase(t *testing.T) { } } a := eventIDs.ReplaceAllString(withoutInstance.Body.String(), "ID") - if b := eventIDs.ReplaceAllString(lowercase.Body.String(), "ID"); a != b { - t.Errorf("body without instance: %s\nbody with lowercase instance: %s", a, b) - } - // New() differs only in code case, so lowercasing both bodies must make them equal. - if b := eventIDs.ReplaceAllString(declared.Body.String(), "ID"); strings.ToLower(a) != strings.ToLower(b) { + if b := eventIDs.ReplaceAllString(declared.Body.String(), "ID"); a != b { t.Errorf("body without instance: %s\nbody with New(): %s", a, b) } + // The lowercase instance differs only in code case. + if b := eventIDs.ReplaceAllString(lowercase.Body.String(), "ID"); strings.ToLower(a) != strings.ToLower(b) { + t.Errorf("body without instance: %s\nbody with lowercase instance: %s", a, b) + } }) } } diff --git a/instance_token_echo_test.go b/instance_token_echo_test.go index 0e0d49f..0f3b7d2 100644 --- a/instance_token_echo_test.go +++ b/instance_token_echo_test.go @@ -17,7 +17,7 @@ var tokenWriters = map[string]http.HandlerFunc{ "informative": func(w http.ResponseWriter, r *http.Request) { Informative{HTTPStatusCode: http.StatusOK}.Write(w, r) }, } -// tokenRequests carry the request token in each place getSecurityToken reads. +// tokenRequests carry the request token in each place v0 read it from to echo it. var tokenRequests = map[string]map[string]string{ "bearer": {"Authorization": "Bearer request-token"}, "token header": {SecurityTokenHeaderKey: "request-token"}, @@ -128,13 +128,13 @@ func TestInstanceCustomFormatterGetsNoRequestToken(t *testing.T) { } } -func TestDefaultInstanceStillEchoesTheRequestToken(t *testing.T) { +func TestDefaultInstanceDoesNotEchoTheRequestTokenFromAnySource(t *testing.T) { usePackageModes(t, RequestModePlain, ResponseModePlain) for writer, handler := range tokenWriters { for source, headers := range tokenRequests { t.Run(writer+"/"+source, func(t *testing.T) { - if got := responseToken(t, handler, headers); got != "request-token" { - t.Fatalf("token = %v, want request-token", got) + if got := responseToken(t, handler, headers); got != "" { + t.Fatalf("token = %v, want empty", got) } }) } @@ -153,7 +153,7 @@ func TestRequestHeaderSessionResponseHeader(t *testing.T) { want []string }{ {name: "instance does not copy the token", handler: New().Handler(RequestHeaderSession(writeSuccess)), want: nil}, - {name: "default instance copies the token", handler: RequestHeaderSession(writeSuccess), want: []string{"request-token"}}, + {name: "default instance does not copy the token", handler: RequestHeaderSession(writeSuccess), want: nil}, // A guard for the documented way to return a token on an instance. {name: "instance keeps a token the handler sets", handler: New().Handler(RequestHeaderSession(setRenewedToken)), want: []string{"renewed-token"}}, } diff --git a/middlewares.go b/middlewares.go index 6de2b23..1ee5435 100644 --- a/middlewares.go +++ b/middlewares.go @@ -121,10 +121,9 @@ func RequestHeaderJSON(next http.HandlerFunc) http.HandlerFunc { // RequestHeaderSession checks that the request carries a session ID. // // It answers 401 when the SecurityTokenHeaderKey request header is empty. -// On the default instance it copies that header into the response header, -// as in v0. On an instance from New it does not, so the request token is -// never echoed (SEC-08); a handler that wants to return a token sets the -// header itself. +// Since v1.0.0 it no longer copies that header into the response header, so +// the request token is never echoed (SEC-08); a handler that wants to return +// a token sets the header itself. func RequestHeaderSession(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { sessionID := r.Header.Get(SecurityTokenHeaderKey) @@ -134,9 +133,6 @@ func RequestHeaderSession(next http.HandlerFunc) http.HandlerFunc { response.Write(w, r) return } - if !instanceFrom(r).fromNew { - w.Header().Set(SecurityTokenHeaderKey, sessionID) - } next.ServeHTTP(w, r) } } @@ -150,10 +146,11 @@ func NewRequestBodyMiddleware(keyListMethods string) core.Middleware { return func(w http.ResponseWriter, r *http.Request) { if ValidateMethods(keyListMethods, r.Method) { a := instanceFrom(r) + boundDefaultBody(w, r) requestData, err := a.core.ProcessBody(r) if err != nil { a.logError(r, "request body rejected", err) - bodyRejection(a, err).Write(w, r) + bodyRejection(err).Write(w, r) return } r.Body = io.NopCloser(bytes.NewBuffer(requestData.RawBody)) @@ -163,11 +160,10 @@ func NewRequestBodyMiddleware(keyListMethods string) core.Middleware { } } -// bodyRejection returns the error response for a request body that a's -// receiver rejected with err: 413 when it exceeds an instance's body limit, -// else the v0 400. -func bodyRejection(a *API, err error) Error { - if bodyTooLarge(a, err) { +// bodyRejection returns the error response for a request body that the +// receiver rejected with err: 413 when it exceeds a body limit, else 400. +func bodyRejection(err error) Error { + if bodyTooLarge(err) { return bodyTooLargeError() } return Error{ @@ -177,15 +173,14 @@ func bodyRejection(a *API, err error) Error { } } -// bodyTooLarge reports whether err comes from the body limit of an instance -// from New. The default instance keeps its v0 400 even for a limit the -// service installed itself. -func bodyTooLarge(a *API, err error) bool { +// bodyTooLarge reports whether err comes from a request body limit: the +// instance's, the default one, or one the service installed itself. +func bodyTooLarge(err error) bool { var maxBytesErr *http.MaxBytesError - return a.fromNew && errors.As(err, &maxBytesErr) + return errors.As(err, &maxBytesErr) } -// bodyTooLargeError is the 413 an instance answers for a body over its limit. +// bodyTooLargeError is the 413 answered for a body over a limit. func bodyTooLargeError() Error { return Error{ Title: "Request content too large", @@ -234,9 +229,8 @@ func GenSkipPath(method string, path string) SkipPath { // to its first ", ", which the client sets; trust it only behind a proxy that // overwrites the header. // The whole request body is read into memory. Under an instance's Handler it -// is bounded by WithMaxBodyBytes (10 MiB by default) and a larger body is -// answered with 413; the default instance has no limit, so bound it before -// this middleware runs (http.MaxBytesHandler or http.MaxBytesReader). +// is bounded by WithMaxBodyBytes (10 MiB by default); without an instance it +// is bounded at 10 MiB. A larger body is answered with 413. func ProcessRequest(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { start := time.Now() @@ -247,10 +241,11 @@ func ProcessRequest(next http.HandlerFunc) http.HandlerFunc { return } - rctx, err := ProcessBody(r) + boundDefaultBody(w, r) + rctx, err := processBody(r) if err != nil { a.logError(r, "request body rejected", err) - bodyRejection(a, err).Write(w, r) + bodyRejection(err).Write(w, r) return } diff --git a/modes.go b/modes.go index 8b8148d..45e55c7 100644 --- a/modes.go +++ b/modes.go @@ -44,9 +44,7 @@ const ( // ResponseModeProblem writes error responses as RFC 9457 problem details // (application/problem+json) and any other response as its content - // alone, as ResponseModeNone. Only WithResponseMode accepts it; - // SetResponseMode treats it as unknown, so the default instance never - // writes problem details. + // alone, as ResponseModeNone. ResponseModeProblem ResponseMode = "problem" ) @@ -81,8 +79,7 @@ func SetRequestMode(mode RequestMode) { } // SetResponseMode updates the response formatting mode of the default -// instance. An unknown mode, ResponseModeProblem included, resets it to -// ResponseModeEnvelope. +// instance. An unknown mode resets it to ResponseModeEnvelope. // // Deprecated: use api.New(api.WithResponseMode(...)) instead. It affects only // the default instance. A service with a custom receiver, formatter or @@ -103,7 +100,7 @@ func normalizeRequestMode(mode RequestMode) RequestMode { func normalizeResponseMode(mode ResponseMode) ResponseMode { switch mode { - case ResponseModeNone, ResponseModePlain, ResponseModeEnvelope: + case ResponseModeNone, ResponseModePlain, ResponseModeEnvelope, ResponseModeProblem: return mode default: return ResponseModeEnvelope diff --git a/response.go b/response.go index 2a00829..1cb2b45 100644 --- a/response.go +++ b/response.go @@ -15,30 +15,6 @@ type Response interface { Write(w http.ResponseWriter, r *http.Request) } -// getSecurityToken returns the request token that Write puts in a response -// whose SecurityToken is empty. An instance from New returns "" so the -// request token is never echoed in its bodies (SEC-08); the default instance -// keeps the v0 echo. -func getSecurityToken(r *http.Request) string { - if instanceFrom(r).fromNew { - return "" - } - requestData, err := GetRequestContext(r) - if err != nil { - if token := r.Header.Get(SecurityTokenHeaderKey); token != "" { - return token - } - return bearerTokenFromHeader(r.Header.Get("Authorization")) - } - if requestData.SecurityToken != "" { - return requestData.SecurityToken - } - if token := r.Header.Get(SecurityTokenHeaderKey); token != "" { - return token - } - return bearerTokenFromHeader(r.Header.Get("Authorization")) -} - func getEventID(r *http.Request) string { requestData, err := GetRequestContext(r) if err != nil { diff --git a/response_error.go b/response_error.go index 3e83716..c536951 100644 --- a/response_error.go +++ b/response_error.go @@ -49,9 +49,6 @@ func (err Error) Write(w http.ResponseWriter, r *http.Request) { if err.ResponseCode == "" { err.ResponseCode = ResponseCodes.DefaultError } - if err.SecurityToken == "" { - err.SecurityToken = getSecurityToken(r) - } instanceFrom(r).core.Write(core.ResponseData(err), w) } diff --git a/response_formatter.go b/response_formatter.go index bffdbee..e96a307 100644 --- a/response_formatter.go +++ b/response_formatter.go @@ -10,15 +10,16 @@ import ( ) // ResponseFormatter implementation of core.APIResponseFormatter interface. -// The zero value formats with CurrentResponseMode, TraceVisibility, -// TraceIDLength and BlankSuccess and lowercases response codes, as v0 does; -// New binds an instance's mode and code case to it, and the v0 defaults of -// the three formatter settings. +// The zero value is the default instance's formatter: it formats with +// CurrentResponseMode, TraceVisibility, TraceIDLength and BlankSuccess and +// sends response codes as declared. New binds an instance's mode and code +// case to it, and the v0 defaults of the three formatter settings. type ResponseFormatter struct { // mode is set by New; empty means the default instance's package variable. mode ResponseMode - // declaredCodes is set by New; false lowercases codes, as v0 does. - declaredCodes bool + // lowercaseCodes is set by New from WithLowercaseCodes; true lowercases + // codes, as v0 does. + lowercaseCodes bool // v0Settings is set by New: the formatter uses the v0 defaults of // TraceVisibility, TraceIDLength and BlankSuccess instead of reading them. v0Settings bool @@ -52,9 +53,8 @@ var BlankSuccess = true // Format the response body information. func (formatter ResponseFormatter) Format(data core.ResponseData) *core.ResponseFormatted { - // Only the mode New binds selects problem details; the package variable - // never does, so the default instance keeps its v0 modes. - if formatter.mode == ResponseModeProblem { + mode := formatter.responseMode() + if mode == ResponseModeProblem { return formatter.formatProblem(data) } msg := data.Message @@ -93,7 +93,7 @@ func (formatter ResponseFormatter) Format(data core.ResponseData) *core.Response Content: data.Content, Header: responseInfo, }) - switch formatter.responseMode() { + switch mode { case ResponseModeNone: body = data.Content case ResponseModePlain: @@ -221,10 +221,10 @@ func problemHeaders(headers map[string]string) map[string]string { // responseCode returns code as the body and the trace suffix show it. func (formatter ResponseFormatter) responseCode(code core.ResponseCode) string { - if formatter.declaredCodes { - return string(code) + if formatter.lowercaseCodes { + return strings.ToLower(string(code)) } - return strings.ToLower(string(code)) + return string(code) } // traceSettings returns the trace visibility and ID length: the v0 defaults diff --git a/response_informative.go b/response_informative.go index c176d7f..2159f32 100644 --- a/response_informative.go +++ b/response_informative.go @@ -39,8 +39,5 @@ func (info Informative) Write(w http.ResponseWriter, r *http.Request) { if info.ResponseCode == "" { info.ResponseCode = ResponseCodes.Informative } - if info.SecurityToken == "" { - info.SecurityToken = getSecurityToken(r) - } instanceFrom(r).core.Write(core.ResponseData(info), w) } diff --git a/response_success.go b/response_success.go index 6a7e15c..6ea4a59 100644 --- a/response_success.go +++ b/response_success.go @@ -39,9 +39,6 @@ func (success Success) Write(w http.ResponseWriter, r *http.Request) { if success.ResponseCode == "" { success.ResponseCode = ResponseCodes.Success } - if success.SecurityToken == "" { - success.SecurityToken = getSecurityToken(r) - } instanceFrom(r).core.Write(core.ResponseData(success), w) } diff --git a/response_warning.go b/response_warning.go index 46e290f..bc7f5ee 100644 --- a/response_warning.go +++ b/response_warning.go @@ -39,8 +39,5 @@ func (warning Warning) Write(w http.ResponseWriter, r *http.Request) { if warning.ResponseCode == "" { warning.ResponseCode = ResponseCodes.Warning } - if warning.SecurityToken == "" { - warning.SecurityToken = getSecurityToken(r) - } instanceFrom(r).core.Write(core.ResponseData(warning), w) } diff --git a/response_writer_test.go b/response_writer_test.go index 6b10b64..aee535a 100644 --- a/response_writer_test.go +++ b/response_writer_test.go @@ -40,7 +40,7 @@ func TestResponseWriterAnswers500WhenBodyCannotBeEncoded(t *testing.T) { t.Fatalf("expected a single JSON body, got %q: %v", res.Body.String(), err) } header, _ := body["header"].(map[string]any) - wantCode := strings.ToLower(string(ResponseCodes.InternalServerEerror)) + wantCode := string(ResponseCodes.InternalServerEerror) if header["code"] != wantCode { t.Fatalf("expected code %q, got %#v", wantCode, body) } @@ -173,7 +173,7 @@ func TestResponseWriterFailureAfterStatusWrittenKeepsEarlierStatus(t *testing.T) if res.Code != http.StatusAccepted { t.Fatalf("expected the earlier status 202 to stay, got %d", res.Code) } - wantCode := strings.ToLower(string(ResponseCodes.InternalServerEerror)) + wantCode := string(ResponseCodes.InternalServerEerror) if !strings.Contains(res.Body.String(), `"code":"`+wantCode+`"`) { t.Fatalf("expected the internal server error body, got %q", res.Body.String()) } diff --git a/write_error_test.go b/write_error_test.go index d8f8806..eea39b4 100644 --- a/write_error_test.go +++ b/write_error_test.go @@ -5,7 +5,6 @@ import ( "fmt" "net/http" "net/http/httptest" - "strings" "testing" "github.com/jgolang/errors" @@ -50,15 +49,15 @@ func TestWriteErrorUsesTheKindOfTheCode(t *testing.T) { wantStatus int wantCode string }{ - {name: "not found behind fmt.Errorf", err: fmt.Errorf("loading: %w", errors.NewC(notFound, "task 42")), wantStatus: http.StatusNotFound, wantCode: "pln-111"}, + {name: "not found behind fmt.Errorf", err: fmt.Errorf("loading: %w", errors.NewC(notFound, "task 42")), wantStatus: http.StatusNotFound, wantCode: "PLN-111"}, {name: "validation built-in", err: errors.NewC(codes.ValRequired, "title"), wantStatus: http.StatusBadRequest, wantCode: "b001"}, {name: "unauthorized", err: errors.NewC(codes.AuthFailed, "bad token"), wantStatus: http.StatusUnauthorized, wantCode: "a003"}, {name: "forbidden", err: errors.NewC(codes.AuthForbidden, "no access"), wantStatus: http.StatusForbidden, wantCode: "f001"}, - {name: "conflict", err: errors.NewC(codes.New("PLN-200", "task is locked").WithKind(codes.KindConflict), "locked"), wantStatus: http.StatusConflict, wantCode: "pln-200"}, + {name: "conflict", err: errors.NewC(codes.New("PLN-200", "task is locked").WithKind(codes.KindConflict), "locked"), wantStatus: http.StatusConflict, wantCode: "PLN-200"}, {name: "infrastructure keeps its code", err: errors.NewC(codes.ConnFailed, "db down"), wantStatus: http.StatusInternalServerError, wantCode: "d001"}, - {name: "nil error", err: nil, wantStatus: http.StatusInternalServerError, wantCode: strings.ToLower(string(ResponseCodes.InternalServerEerror))}, - {name: "code without kind", err: errors.NewC(codes.New("X-1", "x"), "x"), wantStatus: http.StatusInternalServerError, wantCode: "x-1"}, - {name: "plain error", err: fmt.Errorf("boom"), wantStatus: http.StatusInternalServerError, wantCode: strings.ToLower(string(ResponseCodes.InternalServerEerror))}, + {name: "nil error", err: nil, wantStatus: http.StatusInternalServerError, wantCode: string(ResponseCodes.InternalServerEerror)}, + {name: "code without kind", err: errors.NewC(codes.New("X-1", "x"), "x"), wantStatus: http.StatusInternalServerError, wantCode: "X-1"}, + {name: "plain error", err: fmt.Errorf("boom"), wantStatus: http.StatusInternalServerError, wantCode: string(ResponseCodes.InternalServerEerror)}, } for _, tt := range tests {