Repository navigation
Tags
Tags
fix(rp): keep the default azp check when IDTokenVerifier.AZP is nil (#… …1018) # Which Problems Are Solved - Since v3.43.0 (#752), `rp.VerifyIDToken` calls `oidc.CheckAZPVerifier(claims, v.AZP)`. `NewIDTokenVerifier` sets `AZP`, but an `IDTokenVerifier` built as a struct literal, which was common before the field existed, leaves it nil. Every `VerifyIDToken` (and `VerifyTokens`) call then panics with a nil pointer dereference instead of verifying the token. Upgrading past v3.43.0 turns working code into a panic with no compile error. # How the Problems Are Solved - When `v.AZP` is nil, `VerifyIDToken` falls back to `oidc.DefaultAZPVerifier(v.ClientID)`, the check it ran before #752 (`oidc.CheckAuthorizedParty(claims, v.ClientID)`). Verifiers that set `AZP`, including through `NewIDTokenVerifier` and `WithAZPVerifier`, behave exactly as before. # Additional Changes - `TestVerifyIDTokenWithoutAZPVerifier` builds a verifier as a struct literal without `AZP`. It checks that a valid token verifies, and that a token whose `azp` names another client is still rejected with `ErrAzpInvalid`. Without the fix, the first case panics. # Additional Context - Follow-up for PR #752. That PR also had to add `AZP` to the struct literal in `relying_party_test.go`, which is the same breakage for callers. - `go test ./...` passes locally, apart from `TestAuthResponseCode`, `TestRoutes` and `TestServerRoutes`, which also fail on `main` on Windows (line endings in HTML fixtures). `go vet` and staticcheck are clean. Co-authored-by: Wim Van Laer <wim@wvl.app>
fix(rp): accept a refreshed ID token without a nonce (#1012) # Which Problems Are Solved Closes #509. [OIDC Core 1.0 §12.2](https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse) says an ID Token returned from a refresh SHOULD NOT have a `nonce`, and if it has one, its value must be the nonce from the original authentication. Its `auth_time` is also that of the original authentication. `RefreshTokens` verified the refreshed ID Token with the same checks as the code exchange, so `CheckNonce` required an exact match. A relying party whose `Nonce` function returns the original nonce (the `WithNonce` workaround suggested in #509) rejected a spec-compliant refresh response that leaves the nonce out, with `nonce does not match: expected "…" but was ""`. In the same way, a relying party with `MaxAge` set rejected a refresh once the original authentication was older than `MaxAge`. The issue thread agreed that an empty nonce should be allowed here; it stalled because `VerifyIDToken` can't tell a refresh from a code exchange without a signature change. # How the Problems Are Solved `VerifyTokens` and `VerifyIDToken` now wrap internal `verifyTokens` and `verifyIDToken` functions that take a `refreshed` flag, so no exported signature changes and the relying party's verifier is passed unchanged: - With `refreshed`, a missing `nonce` is accepted, and a present one must still match `Nonce(ctx)`. - With `refreshed`, `CheckAuthTime` (`MaxAge`) is skipped, since `auth_time` is that of the original authentication. - `RefreshTokens` verifies through `verifyRefreshTokenResponse`, which sets the flag. The code exchange path is unchanged. For providers like Entra ID that do return the nonce on refresh, `WithNonce` keeps working as before, now without breaking providers that follow the SHOULD NOT. # Additional Changes - `Test_verifyRefreshTokenResponse` covers a refreshed ID token with no nonce, the original nonce and a different nonce, and one whose `auth_time` is older than `MaxAge`. Subtests pin that the code exchange still rejects a missing nonce and an `auth_time` older than `MaxAge`. - The verifier setup from `Test_verifyTokenResponse` moved into a `testIDTokenVerifier` helper, shared by both tests. - `go test ./pkg/client/rp/...`, `go vet` and `gofmt` are clean. # Additional Context - Discussion: #509 --------- Co-authored-by: Wim Van Laer <wim@wvl.app>
feat(rp): add a cache TTL option to the remote key set (#1007) # Which Problems Are Solved - `NewRemoteKeySet` caches the fetched JWKS forever and only refetches when no cached key matches the token's `kid`. A key the issuer has rotated out (for example after it was compromised) keeps being accepted for as long as the process runs. # How the Problems Are Solved - New `rp.CacheTTL(ttl time.Duration)` option for `NewRemoteKeySet`. When it's set, the cached keys expire `ttl` after their fetch started and the next signature verification fetches them again. If that fetch succeeds, keys the issuer removed stop being accepted. If it fails, the cached keys keep being used and the next attempt is made after a 10s back-off. - Verifications share a single fetch, which no longer uses the context of the request that started it. - Without the option (or with `ttl <= 0`) the behaviour is unchanged. # Additional Changes - The tests run in a `synctest` bubble with an in-memory transport and cover: key kept within the TTL, rotated key rejected after it, key still published, failed refresh with back-off, concurrent verifications sharing one fetch, and a canceled first request. # Additional Context - Closes #747
feat(op): serve RFC 8414 metadata through a separate MetadataServer (#… …1035) # Which Problems Are Solved - Clients that follow RFC 8414 (OAuth 2.0 Authorization Server Metadata), such as MCP clients, look up `/.well-known/oauth-authorization-server`. The `op.Server` API serves only `/.well-known/openid-configuration`, so these clients get a 404. - For an issuer with a path, such as `https://h/oauth/p1`, RFC 8414 §3 places the metadata at `https://h/.well-known/oauth-authorization-server/oauth/p1`, outside the prefix the OP is mounted under. The mirrored OIDC form from RFC 8414 §5 is outside it too. A router can't route these paths for a dynamic issuer: chi params never span a `/` and `*` only works at the end of a pattern, and `http.ServeMux` behaves the same way. - A multi-tenant OP, with one issuer per path segment, has no built-in way to get the tenant into `Server` methods or into an `IssuerFromRequest`. # How the Problems Are Solved - **New `MetadataServer` interface**, with `OpenIDConfiguration` and `AuthorizationServerMetadata`. Implementations embed `UnimplementedMetadataServer`. - **`RegisterMetadataServer`** returns a `*MetadataHandler` that serves only well-known paths. The handler parses the path itself and passes the issuer path to the server as `MetadataRequest.IssuerPath`: | Path | Method | IssuerPath | |---|---|---| | `/.well-known/oauth-authorization-server{P}` | `AuthorizationServerMetadata` | `P` | | `/.well-known/openid-configuration{P}` | `OpenIDConfiguration` | `P` (RFC 8414 §5) | | `{P}/.well-known/openid-configuration` | `OpenIDConfiguration` | `P` (OIDC Discovery) | - Mount it at `/.well-known/` and give the OIDC form its own pattern, or wrap the whole mux with `Intercept(next)`. `Intercept` also covers multi-segment issuer paths. - It answers `GET` and `HEAD`; other methods get a JSON 405 with `Allow`. Its 404s go through CORS, like the rest of its responses. - It takes `ServerOption`, so `WithHTTPMiddleware` and `WithServerCORSOptions` apply. It has no routes of its own: the middleware runs as a chain around it, and of `WithSetRouter` only the middleware applies. - **`WithTenantPrefix(prefix)`**, honoured by both `RegisterServer` and `RegisterMetadataServer`. Both handlers set the tenant on the context before user middleware runs, so one `IssuerFromRequest` built on `TenantFromContext` works for both. - `RegisterServer` puts a small chi router in front of its own, with each of its routes registered twice: as `{prefix}/{tenant}{route}` an 8000 d, for the empty tenant, as `{prefix}{route}`. chi tries a static segment before the `{tenant}` parameter, so a known route wins: `/oauth/authorize` belongs to the empty tenant and `/oauth/p1/authorize` to tenant `p1`. The empty tenant can serve as a root or platform issuer at `https://h/oauth`. Any other path under the prefix is forwarded as a chi `Mount` at `{prefix}/{tenant}` would forward it, so the router's NotFound handler, mounted routers and middleware still apply. The OP router gets the rest of the path as the chi route path, the URL is left as is, and chi's route pattern reads `/oauth/{tenant}/authorize`, as under a `Mount`. Paths outside the prefix and invalid tenants get a JSON 404 with CORS headers. A tenant `T` loses a route `R` only when `/T`+`R` is itself a route, which never happens with the default endpoints; the doc comment spells this out. - `RegisterMetadataServer` accepts issuer paths `{prefix}` (empty tenant) and `{prefix}/{tenant}`, and gives anything else a 404 without calling the server. - Without the option, `RegisterServer` behaves exactly as before, and the metadata handler passes every issuer path through without setting a tenant. - **Path handling:** both handlers work on the path chi routes on, including a `RoutePath` set by `Mount`. In the OP handler chi splits the raw path and the tenant is percent-decoded once; the metadata handler decodes the path once and then splits it. In both, a tenant with a `%2F`, a dot segment or an empty segment is a 404. A `RoutePath` that middleware rebuilt from the decoded path, such as chi's `StripSlashes`, is not decoded a second time. - **`TenantFromContext` / `ContextWithTenant`** expose the tenant on the context. Wiring with a prefix on a `ServeMux`: ```go meta := op.RegisterMetadataServer(ms, op.WithTenantPrefix("/oauth"), op.WithHTTPMiddleware(issuerMW)) srv := op.RegisterServer(s, ep, op.WithTenantPrefix("/oauth"), op.WithHTTPMiddleware(issuerMW)) mux.Handle("/.well-known/", meta) mux.Handle("/oauth/{t}/.well-known/openid-configuration", meta) mux.Handle("/oauth/.well-known/openid-configuration", meta) mux.Handle("/oauth/", srv) ``` # Additional Changes - New constant `oidc.AuthorizationServerMetadataEndpoint`. - `Server.Discovery` is deprecated in favour of `MetadataServer`. `RegisterServer` still routes `/.well-known/openid-configuration` to it, so existing implementations keep working. - `simpleHandler` now delegates to a generic `serveSimple`, which the metadata handler shares. - Table tests on `http.ServeMux` and on chi `Handle`, `Mount` and `StripSlashes`. They cover: - both setups end to end: a static prefix on a `ServeMux`, and tenants directly under the host with `Intercept` in front of the mux; - all three URL forms and multi-segment issuer paths; - escaped, double-escaped and dot segments; - the empty tenant, the known-route rule, shadowing and tenants named like routes; - chi route patterns and NotFound handlers of routers mounted through `WithSetRouter`; - methods, CORS on 404 and preflights; - `RegisterLegacyServer` passing the option through; - that the `ServeMux` patterns above register without a conflict panic. - The README features table lists RFC 8414. - A one-character gofmt fix in a comment in `pkg/oidc/jwt_profile.go`, which was already on `main`. # Additional Context - Related: zitadel/nextgen#2793, which serves one issuer per project under `/oauth/{project_id}` and maps the empty tenant to the platform project. - Supersedes #1034, which routed `Server.Discovery` to the RFC 8414 paths inside `RegisterServer`'s router. That route had to rely on a router wildcard and precedence workarounds, and it could not serve the RFC 8414 §5 form. - `LegacyServer` does not implement `MetadataServer`. `LegacyServer` users keep the deprecated `Discovery` for now. - Out of scope: `signed_metadata` (RFC 8414 §2.1), client-side RFC 8414 discovery, and the legacy `Provider` / `CreateRouter`. - https://www.rfc-editor.org/rfc/rfc8414.html - https://openid.net/specs/openid-connect-discovery-1_0.html 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
fix(op): pass a storage server_error through client authentication (#… …1000) # Which Problems Are Solved - A Storage that fails client authentication with `oidc.ErrServerError()` (database down, corrupt row) gets a 401 `invalid_client` answer instead of a 500 `server_error`. The client sees a credentials error for a server fault and retries or rotates secrets for nothing. - The cause is the wrap at each client authentication call site. `oidc.ErrInvalidClient().WithParent(err)` puts a new error on the outside, and `RequestError` maps the status from the outermost `*oidc.Error` only, so the typed `server_error` is never seen. # How the Problems Are Solved - New unexported helper `clientAuthError(base, err)` in `pkg/op/client.go`. It returns the Storage's own error when that error is a `server_error`, and `base.WithParent(err)` for everything else. - The 8 call sites that wrapped Storage client errors now use it. That covers `AuthorizeClientCredentialsClient`, `AuthorizeClientIDSecret`, `AuthorizeCodeClient`, `AuthorizeTokenExchangeClient`, `ParseTokenRevocationRequest`, `ClientBasicAuth`, `LegacyServer.VerifyClient` and the legacy server introspection client check. - Only `server_error` passes through. A wrong secret or an unknown client still answers `invalid_client`, so the response does not leak more than it does today. No exported signature changes. # Additional Changes - `pkg/op/client_auth_error_test.go` has unit tests for `AuthorizeClientCredentialsClient` and `AuthorizeClientIDSecret` and a token endpoint test through `op.NewOpenIDProvider` with basic auth for the `client_credentials` and `authorization_code` grants. Each runs one Storage that returns `oidc.ErrServerError()` and one that returns a plain error. ``` $ go test -count=1 -run 'StorageErrors' -v ./pkg/op/ main c9e2385 plus the new test file --- FAIL: TestAuthorizeClientCredentialsClient_StorageErrors/typed_server_error_passes_through expected: "server_error" actual: "invalid_client" --- FAIL: TestAuthorizeClientIDSecret_StorageErrors/typed_server_error_passes_through expected: "server_error" actual: "invalid_client" --- FAIL: TestTokenEndpoint_ClientAuthStorageErrors/client_credentials/typed_server_error_passes_through expected: 500 actual: 401 --- FAIL: TestTokenEndpoint_ClientAuthStorageErrors/authorization_code/typed_server_error_passes_through expected: 500 actual: 401 (4 plain_error_stays_invalid_client subtests PASS) FAIL github.com/zitadel/oidc/v3/pkg/op 1.416s this branch (8 of 8 subtests PASS) ok github.com/zitadel/oidc/v3/pkg/op 0.986s ``` - `go test -race -count=1 ./pkg/...` (the CI command) gives 9 ok packages on main and on this branch. `gofmt -l pkg/op` and `go vet ./pkg/op/` are clean. `staticcheck` 2026.2.1 with the tags '', `no_otel` and `create_regression_data` reports nothing. All with go1.26.4. - I also checked the complaint over real HTTP with `httptest.NewServer`, the example storage and a Storage that returns `oidc.ErrServerError()` from `AuthorizeClientIDSecret` and `ClientCredentials`. A `server_error` from `GetClientByClientID` gives the same main and branch answers for the code and revoke rows. ``` main this branch op.NewProvider token client_credentials (basic) 401 invalid_client 500 server_error token authorization_code (basic/post) 401 invalid_client 500 server_error revoke (post) 401 invalid_client 500 server_error device_authorization (basic) 400 unauthorized_client 500 server_error op.RegisterLegacyServer token authorization_code (basic/post) 400 invalid_client 500 server_error revoke (post) 400 invalid_client 500 server_error device_authorization (basic) 400 invalid_client 500 server_error introspect (basic) 400 unauthorized_client 500 server_error plain Storage error, every row above same answer on main and on this branch ``` - `op.Provider`'s introspection handler writes 401 for every error, on main and on this branch. I left it as it is. # Additional Context - Closes #990 - The paths that already return the Storage error unwrapped (refresh, device, JWT profile, the legacy server `client_credentials` grant) keep the behaviour from #865 and are unchanged. --------- Co-authored-by: Wim Van Laer <wim@wvl.app>
fix(op): reject an unsupported code_challenge_method (#1003) # Which Problems Are Solved - The authorization endpoint accepted any `code_challenge_method` and stored it with the auth request. `oidc.VerifyCodeChallenge` only transforms the `code_verifier` for `S256`, so at the token endpoint an auth request with an unsupported method (for example `S512`, or a lower-case `s256` from a misconfigured client) was verified **as if the method were `plain`**. - [RFC 7636, section 4.4.1](https://www.rfc-editor.org/rfc/rfc7636#section-4.4.1) requires the server to answer `invalid_request` when it does not support the requested transformation. # How the Problems Are Solved - Adds `op.ValidateAuthReqCodeChallengeMethod(codeChallenge, method)`, next to the other `ValidateAuthReq*` helpers. When a `code_challenge` is sent, it returns `invalid_request` for a method that is not supported. An absent method is accepted (it defaults to `plain`, section 4.3), and so is any method sent without a `code_challenge`, since there is nothing to downgrade. - Calls it from `ValidateAuthRequestClient` (Provider path) and from `authorizeWithValidRedirectURI` (op.Server path), after the redirect_uri is validated, so the error is delivered to the client like the other request errors. - A custom `AuthorizeValidator` replaces `ValidateAuthRequestClient`, so `Authorize` also runs the check in that case only (where it looks the client up itself), before `CreateAuthRequest`. Since such a validator may not have verified the redirect_uri, the error is redirected only to a redirect_uri registered for the client (`redirectURIRegistered`: exact match, glob, or a native client's loopback redirect on any port, RFC 8252 section 7.3) and rendered directly otherwise. - The error description does not echo the method. `plain` and `S256` stay accepted, so behaviour does not change for any client that sends a supported method. # Additional Changes - Adds `oidc.CodeChallengeMethod.IsSupported()` (a `switch` on the two constants) and uses it in the validator and in the RP's PKCE-from-discovery check. - `oidc.VerifyCodeChallenge` switches on the method and returns false for an unsupported one instead of comparing it as `plain`; the example storage's `CodeChallengeToOIDC` passes the stored method through instead of mapping unknown methods to `plain`. - Tests: - `TestValidateAuthReqCodeChallengeMethod` and `TestValidateAuthRequestClientCodeChallengeMethod` (fails if the check in `ValidateAuthRequestClient` is removed). - `TestAuthorizeErrorParity`: "unsupported code_challenge_method" delivers `invalid_request` to the redirect_uri on both paths. - `TestAuthorizeCustomValidatorCodeChallengeMethod`: a custom validator that accepts `S512`, with registered, unregistered, native loopback on another port, and registered native `http` redirect_uris; `state` and the exact redirect_uri are asserted. - `TestCodeChallengeMethod_IsSupported` and `TestVerifyCodeChallenge` in `pkg/oidc`. # Additional Context - On Windows, `TestAuthResponseCode`, `TestRoutes` and `TestServerRoutes` fail on `main` as well (line endings in HTML fixtures); everything else in `go test ./...` passes locally. _AI assistance: prepared with Claude Code._ --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Wim Van Laer <wim@wvl.app>
fix(rp): generate the PKCE code_verifier from 32 random octets (#1004) # Which Problems Are Solved - `GenerateAndStoreCodeChallenge` and `GenerateAndStoreCodeChallengeWithRequest` built the PKCE `code_verifier` as `base64url(uuid.New().String())`. A version 4 UUID carries 122 random bits; base64url-encoding its 36-character text form (fixed dashes, fixed version nibble, hex alphabet only) makes the verifier 48 characters long without adding any entropy. - [RFC 7636, section 4.1](https://www.rfc-editor.org/rfc/rfc7636#section-4.1) recommends a 32-octet random sequence (256 bits), base64url-encoded to 43 characters. # How the Problems Are Solved - Both functions use `oauth2.GenerateVerifier()` from `golang.org/x/oauth2` (already a dependency), which produces exactly the RFC-recommended verifier from `crypto/rand`. - The now unused `encoding/base64` and `github.com/google/uuid` imports are removed from `relying_party.go` (the module still uses `uuid` elsewhere, so `go.mod` is unchanged). The verifier stays an opaque value stored in the PKCE cookie and sent to the token endpoint, so nothing else changes for callers or OPs. # Additional Changes - `TestGenerateAndStoreCodeChallenge` reads the verifier back from the cookie and checks it decodes to 32 octets, that the returned challenge is its S256 hash, and that it does not repeat. It fails before this change (the decoded UUID text is 36 bytes). # Additional Context - Same recommendation as [`oauth2.GenerateVerifier`](https://pkg.go.dev/golang.org/x/oauth2#GenerateVerifier) cites. _AI assistance: prepared with Claude Code._ --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Wim Van Laer <wim@wvl.app>
fix(http): keep the underlying error when requests to the OP fail (#1002 ) # Which Problems Are Solved - `HttpRequest` formats body read and unmarshal errors with `%v`, and the remote key set does the same when fetching the JWKS. The original error is lost, so callers can't use `errors.Is` / `errors.As` to tell a network failure, timeout, `*oidc.Error` or `ErrResponseBodyTooLarge` apart from an invalid signature. # How the Problems Are Solved - Wrap those errors with `%w` in `pkg/http/http.go` and `pkg/client/rp/jwks.go`. Error messages are unchanged. # Additional Changes - Tests for `HttpRequest` error wrapping and for `remoteKeySet.VerifySignature` exposing JWKS fetch errors. # Additional Context - Refs #961. This covers the error chain inside the library; passing the error on from `CodeExchangeHandler` / `UserinfoCallback` needs an API decision and is left out.
fix(oidc): return an error for non-string audience array entries (#998) # Which Problems Are Solved - `Audience.UnmarshalJSON` panics when an `aud` array contains a non-string element, for example `"aud":["client",1]` (`interface conversion: interface {} is float64, not string`). - `rp.VerifyIDToken` decodes the claims before it checks the signature, so an unsigned token can reach this code and panic the relying party. # How the Problems Are Solved - Replace the unchecked type assertion with `gu.AssertInterfaces[string]`, which the `amr` and `locales` decoders in the same file already use, and return the error with an `oidc aud:` prefix. # Additional Changes - Add test cases to `TestAudience_UnmarshalText`: an array with a number (now an error, no panic) and a bare number (still ignored, as before). - The `default` case (number, object, bool, null) is unchanged. It still leaves `aud` empty, and the audience check rejects the token later. Changing it to an error would also reject `"aud":null`, so I left it out of this fix. # Additional Context - Reproduced on v3.51.10, v3.51.11 and main. Co-authored-by: Wim Van Laer <wim@wvl.app>
PreviousNext