Repository navigation
fix(auth)!: trust only configured issuers - #274
Conversation
Bearer token validation fetched the OpenID Connect discovery document from whatever issuer a token named, and validated the token against that issuer's keys and user info endpoint. Tokens minted by any OpenID Connect provider could therefore be accepted, and the service could be made to send requests to arbitrary URLs. - accept only tokens of the trusted issuers listed in the new `security.auth.issuers` setting; reject all others before any network request; reject all tokens if no issuers are configured - check that the discovery document was issued for the token's issuer and pass the issuer to `jwt.decode` - always verify the signature locally; the user info endpoint is only an additional check (`validate_userinfo`), done after verification, whose `sub` must match the token's - require `exp`, `iat`, `iss` and the identity claim - return the verified claims; `add_key_to_claims` works again - fetch documents with timeouts and without following redirects; cache discovery documents and JWK sets (`timeout`, `cache_ttl`), refetching JWK sets on unknown key IDs at most every 30 seconds - log warnings on app creation if no issuers are configured, audience validation is disabled or expired tokens are accepted BREAKING CHANGE: `security.auth.issuers` must list the trusted token issuers; otherwise, all tokens are rejected. `validation_methods`, `validation_checks` and `claim_issuer` are removed; use `validate_userinfo: True` to additionally validate tokens via the user info endpoint. Signatures are always verified locally. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideReplaces unverified, token-selected issuer validation with fail-closed authentication: only configured issuers are contacted, discovery and JWKs are validated and cached, signatures and required claims are always checked locally, and user info is optional and performed only after verification. Configuration, startup warnings, documentation, fixtures, and comprehensive signed-token tests are updated for the breaking changes. Sequence diagram for trusted issuer token validationsequenceDiagram
participant Client
participant Auth as validate_token
participant IdP as TrustedIssuer
participant Cache as DiscoveryAndJWKCache
Client->>Auth: validate_token(token)
Auth->>Auth: jwt.decode(token, verify_signature=False)
alt issuer is not configured
Auth-->>Client: Unauthorized
else issuer is trusted
Auth->>Cache: _get_oidc_config(issuer, conf)
Cache->>IdP: _fetch_json(discovery_url, timeout, no redirects)
IdP-->>Cache: discovery document
Cache->>Cache: verify discovery issuer matches token issuer
Auth->>Cache: _get_jwk_set(jwks_uri, conf)
Cache->>IdP: _fetch_json(jwks_uri, timeout, no redirects)
IdP-->>Cache: JWK set
Auth->>Auth: _verify_signature(token, issuer, jwks_uri, conf)
Auth->>Auth: jwt.decode(token, key, issuer, required claims)
opt validate_userinfo
Auth->>IdP: _validate_userinfo(token, subject, userinfo_endpoint, conf)
IdP-->>Auth: user info with matching sub
end
Auth-->>Client: verified claims
end
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #274 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 22 22
Lines 1151 1121 -30
=========================================
- Hits 1151 1121 -30
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Also drop the unreachable error handling for decoding the token header, which can always be decoded once the token itself was decoded. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Hey - I've found 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/security/auth.py" line_range="271" />
<code_context>
+ options = {
+ "require": ["exp", "iat", "iss", conf.claim_identity],
+ "verify_aud": conf.audience is not None,
+ "verify_exp": not conf.allow_expired,
+ }
+ for key in keys:
</code_context>
<issue_to_address>
**Tokens for other audiences are accepted**
When the service uses the default or otherwise unset `security.auth.audience` and a caller presents a valid token for another audience from a trusted issuer, a holder of a token issued by a trusted provider for a different application can call this service when `audience` is unset: `_verify_signature` disables audience verification and accepts the otherwise valid token.
Require a configured audience for protected deployments, or otherwise make audience-less validation an explicit opt-in that fails closed by default.
</issue_to_address>
### Comment 2
<location path="foca/security/auth.py" line_range="224" />
<code_context>
+ jwk_set = jwt.PyJWKSet.from_dict(_fetch_json(url=url, conf=conf))
+ except jwt.PyJWTError as exc:
+ raise Unauthorized("Issuer's JWK set is invalid") from exc
+ _jwk_sets[url] = (time.monotonic(), jwk_set)
+ return jwk_set
</code_context>
<issue_to_address>
**Failed key refreshes repeat on every request**
When the cached JWKS is older than the cooldown, a token has an unknown key ID, and fetching the issuer’s JWKS fails, `_get_jwk_set` only updates the cached timestamp after a successful fetch, so each request repeats the failed JWKS request and amplifies load on the issuer during an outage.
Record a refresh-attempt time before or independently of fetching, and use it to enforce the cooldown after failures too.
</issue_to_address>
### Comment 3
<location path="tests/security/test_auth.py" line_range="86" />
<code_context>
+ "userinfo_endpoint": USERINFO_URI,
+ }
+ ),
+ JWKS_URI: MockResponse({"keys": [_public_jwk(PRIVATE_KEY, KID)]}),
+ USERINFO_URI: MockResponse({"sub": SUBJECT}),
+ }
</code_context>
<issue_to_address>
**Single key misses fallback**
When the implementation tries only one signing key for a token without a key ID, `test_no_key_id` at line 235 succeeds with this fixture, which contains only one signing key. An implementation that checks only the first key when `kid` is absent therefore passes, even though it fails to try all signing keys.
Include multiple signing keys in the fixture, with the matching key after a non-matching key, and assert that a no-`kid` token signed by the latter is accepted.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 3 findings to address first, and the configured issuer list now determines which identity providers can authenticate users: trusting the wrong issuer lets its validly signed tokens grant access, and any resulting data exposure or access cannot be undone by reverting. This is a trust-boundary decision, not just a validation implementation change.
Blocking findings: foca/security/auth.py:271, foca/security/auth.py:224, tests/security/test_auth.py:86
Discovery documents and JWK sets were only cached after successful fetches, so while an identity provider was unavailable, every request fetched them again, amplifying load on the provider during an outage. Do not fetch a discovery document or JWK set again within `JWKS_REFETCH_COOLDOWN` seconds after a failed attempt. User info requests depend on the token and are not throttled. Also test that tokens without key ID are verified with all signing keys, not only the first one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Explain that without `audience`, tokens that trusted issuers issued for other services are accepted, and recommend setting it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Tokens without key ID are verified with each signing key of the issuer. Keys of another type or algorithm than the token (e.g., an EC key for an RS256 token) raised `InvalidAlgorithmError`, which rejected the token instead of trying the remaining keys. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
First PR of the v0.14.0 production-readiness series: fixes bearer token validation.
validate_token()decoded tokens without verification, took the issuer from the token's ownissclaim, and fetched that issuer's OpenID Connect discovery document to obtain the keys and user info endpoint used for validation. Tokens minted by any OpenID Connect provider could therefore be accepted (with arbitrary subjects and group claims), and the service could be made to send requests to arbitrary URLs. In addition, withvalidation_checks: any(the template default), a successful user info request alone was enough, the returned claims were the unverified ones, and requests had no timeouts.Changes
security.auth.issuers. Tokens of other issuers are rejected before any network request; if no issuers are configured, all tokens are rejected (fail closed).issuermember), and the issuer is passed tojwt.decode.alg: noneis rejected.validate_userinfo: True), performed after local verification; itssubmust match the token's.exp,iat,issand the identity claim (claim_identity).add_key_to_claimsworks again (public key in PEM format).timeout, default 10 s), no redirects, caching of discovery documents and JWK sets (cache_ttl, default 300 s), refetching JWK sets on unknown key IDs at most every 30 s; after a failed fetch of a discovery document or JWK set, no new attempt is made for 30 s (tokens are rejected), so that requests do not amplify load on an identity provider during an outage.AuthConfigdocs recommend settingaudience.Claims are still copied into
request.headersfor now, ascheck_permissionsrelies on that; both are removed together in the next PR (header-based checks).Closes #275
Breaking changes
security.auth.issuersmust list the trusted issuers (e.g., the LS Login issuer for proTES/cloud-registry); otherwise all tokens are rejected.validation_methods,validation_checksandclaim_issuerare removed (configs using them fail validation); usevalidate_userinfo: Truefor the additional user info check.exp,iat,issand the identity claim, and are always verified locally (userinfo-only validation is no longer possible).Verification
Test-first:
tests/security/test_auth.pyrewritten with real RSA keys and signed tokens and a mocked identity provider (36 tests): untrusted/missing issuer (no requests made), no issuers configured, malformed tokens, discovery issuer mismatch, unavailable discovery document/JWK set, caching and TTL expiry, key rotation and refetch cooldown, forged signatures (with and without key ID), unsigned tokens, expiry andallow_expired, required claims, custom identity claim, audience match/mismatch,add_key_to_claims, user info (order, subject mismatch, errors), timeouts/no redirects, config defaults and removed fields, warnings.Locally: unit tests without MongoDB: 304 passed on Python 3.13 and 3.10;
ruff check,ruff format --check,mypy focaclean.Review follow-up (Sourcery): failed fetch cooldown (tests for discovery/JWKS failures, failed refetches and unthrottled user info), no-
kidtest with the matching key after a non-matching one, and docs recommendingaudience; keepingaudienceoptional is deliberate (startup warning). Auth tests: 42 passed, 100% coverage offoca/security/auth.py.CI: all checks pass (CI incl. MongoDB-dependent and integration tests on Python 3.10-3.14, Codecov patch/project, Sourcery, Read the Docs). All automated review threads are resolved.
Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Harden bearer-token authentication by restricting accepted issuers and requiring locally verified JWTs before granting access.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: