From 5f26af12791d10c1a676eafc9431dcdf48b4d9a8 Mon Sep 17 00:00:00 2001 From: Josue Giron Date: Sat, 21 Nov 2026 17:51:04 +0000 Subject: [PATCH] feat(api): stop copying the token in RequestHeaderSession on instances RequestHeaderSession copied the SecurityToken request header into the response header, echoing the request token that SEC-08 already keeps out of instance bodies. On an api.New instance it no longer does; it still answers 401 without the header. The default instance keeps the v0 copy. Instances are new in v1, so v0 programs see no change. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/adr/0001-v1-instance-api.md | 4 ++-- docs/migration-v1.md | 4 ++-- instance_token_echo_test.go | 28 ++++++++++++++++++++++++++++ middlewares.go | 12 ++++++++++-- 5 files changed, 43 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 235d92c..7ac2f14 100644 --- a/README.md +++ b/README.md @@ -363,7 +363,7 @@ 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` still copies the `SecurityToken` request header into the response header on both; after `api.ProcessRequest` that header holds the request token, which in envelope request mode can come from the body's `header.token`. +- 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`. - 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. diff --git a/docs/adr/0001-v1-instance-api.md b/docs/adr/0001-v1-instance-api.md index 9304de1..035f7a8 100644 --- a/docs/adr/0001-v1-instance-api.md +++ b/docs/adr/0001-v1-instance-api.md @@ -41,7 +41,7 @@ func (a *API) Handler(next http.Handler) http.Handler - The type is named `API` (it wraps `core.API`; `doc.API` stays the OpenAPI metadata). - An instance has no setters. Options are applied once in `New`; there is nothing to drift after start-up. `Option` takes an unexported `options` struct that `New` owns, not the `*API`, so no `Option` value can change an instance after `New` returns. - `New` returns `*API` without an error and never panics. An unknown mode value falls back to the default, as `SetRequestMode`/`SetResponseMode` do, and this is documented on the option. -- `New()` with no options behaves like v0's defaults (plain requests, envelope responses, the same formatter output, trace suffix 1, ID length 6, blank successes), except: codes as declared (section 4), no logging (section 6), a 10 MiB body limit (section 9) and no request token echo (section 10). +- `New()` with no options behaves like v0's defaults (plain requests, envelope responses, the same formatter output, trace suffix 1, ID length 6, blank successes), except: codes as declared (section 4), no logging (section 6), a 10 MiB body limit (section 9) and no request token echo in bodies or in `RequestHeaderSession`'s response header (section 10). Options (one exported function each): @@ -147,7 +147,7 @@ sequenceDiagram - `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). - 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` copying the `SecurityToken` request header into the response header is unchanged; it is the middleware's session contract, not a body echo. 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`. ## What stays package-level in v1 diff --git a/docs/migration-v1.md b/docs/migration-v1.md index 71b0af5..8c4f2bf 100644 --- a/docs/migration-v1.md +++ b/docs/migration-v1.md @@ -199,7 +199,7 @@ 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`. 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.** 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. **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. @@ -233,5 +233,5 @@ a.Handler(http.HandlerFunc(createTask)).ServeHTTP(rec, req) - [ ] 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. - [ ] Give the instance a `*slog.Logger`, or accept that it logs nothing. -- [ ] Check clients that read the request token back from response bodies: an instance no longer echoes it. +- [ ] 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/instance_token_echo_test.go b/instance_token_echo_test.go index 51c9a72..0e0d49f 100644 --- a/instance_token_echo_test.go +++ b/instance_token_echo_test.go @@ -1,6 +1,7 @@ package api import ( + "fmt" "net/http" "testing" @@ -139,3 +140,30 @@ func TestDefaultInstanceStillEchoesTheRequestToken(t *testing.T) { } } } + +func TestRequestHeaderSessionResponseHeader(t *testing.T) { + writeSuccess := func(w http.ResponseWriter, r *http.Request) { Success200().Write(w, r) } + setRenewedToken := func(w http.ResponseWriter, r *http.Request) { + w.Header().Set(SecurityTokenHeaderKey, "renewed-token") + Success200().Write(w, r) + } + tests := []struct { + name string + handler http.Handler + 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"}}, + // 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"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rec := serve(tt.handler, http.MethodGet, "", map[string]string{SecurityTokenHeaderKey: "request-token"}) + + if got := rec.Header().Values(SecurityTokenHeaderKey); fmt.Sprint(got) != fmt.Sprint(tt.want) { + t.Fatalf("%s response header = %q, want %q", SecurityTokenHeaderKey, got, tt.want) + } + }) + } +} diff --git a/middlewares.go b/middlewares.go index 5005430..6de2b23 100644 --- a/middlewares.go +++ b/middlewares.go @@ -118,7 +118,13 @@ func RequestHeaderJSON(next http.HandlerFunc) http.HandlerFunc { } } -// RequestHeaderSession validates that session ID is valid. +// 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. func RequestHeaderSession(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { sessionID := r.Header.Get(SecurityTokenHeaderKey) @@ -128,7 +134,9 @@ func RequestHeaderSession(next http.HandlerFunc) http.HandlerFunc { response.Write(w, r) return } - w.Header().Set(SecurityTokenHeaderKey, sessionID) + if !instanceFrom(r).fromNew { + w.Header().Set(SecurityTokenHeaderKey, sessionID) + } next.ServeHTTP(w, r) } }