diff --git a/README.md b/README.md index c6f48ff..235d92c 100644 --- a/README.md +++ b/README.md @@ -362,7 +362,7 @@ See [ADR 0002](docs/adr/0002-stdadapter-servemux.md). ## Security notes - `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 and the plain password into the `Basic-Client` and `Basic-Secret` request headers; do not forward or log those headers. +- `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 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`. diff --git a/docs/migration-v1.md b/docs/migration-v1.md index c5110d8..71b0af5 100644 --- a/docs/migration-v1.md +++ b/docs/migration-v1.md @@ -10,6 +10,7 @@ This guide takes a v0 program (v0.11.x) to `github.com/jgolang/api` v1. The desi - `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. - 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)). Three steps, each one shippable on its own: @@ -29,6 +30,10 @@ Requests that no `a.Handler` wraps use the default instance. It keeps v0's behav 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 + +After a successful check, `api.BasicToken` no longer copies the plain password into the `Basic-Secret` request header, on the default instance and on instances. It also removes a `Basic-Secret` header the client sent, so a handler never reads a client-chosen value there. `Basic-Client` (the user name) is still set. A handler that read `Basic-Secret` must take the password from its own credential source, for example the `Authorization` header (`r.BasicAuth()`) or its secret store. + ## Step 2: fix routing (stdadapter) `stdadapter` registers each route as one `ServeMux` pattern (`GET /tasks/{id}`). Matching, precedence, 404 and 405 now come from `net/http`. `api.GetRouteVar` works as before, and `r.PathValue` now works too. Other adapters are not affected. @@ -222,6 +227,7 @@ a.Handler(http.HandlerFunc(createTask)).ServeHTTP(rec, req) - [ ] 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. +- [ ] Find handlers that read the `Basic-Secret` request header after `api.BasicToken`: it is no longer set. - [ ] 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). diff --git a/middlewares.go b/middlewares.go index 262d604..5005430 100644 --- a/middlewares.go +++ b/middlewares.go @@ -40,8 +40,9 @@ var MiddlewaresChain = core.MiddlewaresChain // With the default validator it answers 401 to every request while // Username or Password is empty or "default"; set both (or replace // ValidateBasicAuthCredentialsFunc) to use it. After a successful check it -// copies the user name and the plain password into the Basic-Client and -// Basic-Secret request headers; do not forward or log those headers. +// copies the user name into the Basic-Client request header. Since v1.0.0 +// it no longer copies the password into a Basic-Secret header, and it +// removes one the client sent, so a handler never reads a password there. func BasicToken(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2) @@ -52,7 +53,7 @@ func BasicToken(next http.HandlerFunc) http.HandlerFunc { response.Write(w, r) return } - client, secret, tokenValid := ValidateBasicToken(auth[1]) + client, _, tokenValid := ValidateBasicToken(auth[1]) if !tokenValid { response := Error401() response.Message = DefaultBasicUnauthorizedMsg @@ -60,7 +61,7 @@ func BasicToken(next http.HandlerFunc) http.HandlerFunc { return } r.Header.Set("Basic-Client", client) - r.Header.Set("Basic-Secret", secret) + r.Header.Del("Basic-Secret") next(w, r) } } diff --git a/security_test.go b/security_test.go index 2aee45d..d078447 100644 --- a/security_test.go +++ b/security_test.go @@ -147,3 +147,63 @@ func TestBasicTokenUsesCustomValidatorWhileNotConfigured(t *testing.T) { t.Fatalf("expected status %d, got %d", http.StatusNoContent, res.Code) } } + +// serveBasicToken answers an authenticated request through BasicToken on +// the default instance and on an instance, and returns the Basic-Client and +// Basic-Secret request headers the handler saw on each. +func serveBasicToken(t *testing.T, requestHeaders map[string]string) map[string][2]string { + t.Helper() + previousUsername, previousPassword := Username, Password + Username, Password = "service-user", "service-password" + defer func() { Username, Password = previousUsername, previousPassword }() + + instances := map[string]func(http.Handler) http.Handler{ + "default instance": func(next http.Handler) http.Handler { return next }, + "instance": New().Handler, + } + seen := map[string][2]string{} + for name, wrap := range instances { + handler := BasicToken(func(w http.ResponseWriter, r *http.Request) { + seen[name] = [2]string{r.Header.Get("Basic-Client"), r.Header.Get("Basic-Secret")} + w.WriteHeader(http.StatusNoContent) + }) + req := httptest.NewRequest(http.MethodGet, "/private", nil) + req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("service-user:service-password"))) + for key, value := range requestHeaders { + req.Header.Set(key, value) + } + res := httptest.NewRecorder() + + wrap(handler).ServeHTTP(res, req) + + if res.Code != http.StatusNoContent { + t.Fatalf("%s: status = %d, want %d", name, res.Code, http.StatusNoContent) + } + } + return seen +} + +func TestBasicTokenDoesNotCopyThePasswordIntoBasicSecret(t *testing.T) { + for name, headers := range serveBasicToken(t, nil) { + if headers[1] != "" { + t.Errorf("%s: Basic-Secret = %q, want no header", name, headers[1]) + } + } +} + +// v0 overwrote a client-sent Basic-Secret, so handlers may still trust it. +func TestBasicTokenRemovesAClientSentBasicSecret(t *testing.T) { + for name, headers := range serveBasicToken(t, map[string]string{"Basic-Secret": "forged"}) { + if headers[1] != "" { + t.Errorf("%s: Basic-Secret = %q, want no header", name, headers[1]) + } + } +} + +func TestBasicTokenSetsBasicClient(t *testing.T) { + for name, headers := range serveBasicToken(t, nil) { + if headers[0] != "service-user" { + t.Errorf("%s: Basic-Client = %q, want %q", name, headers[0], "service-user") + } + } +}