Skip to content

fix(auth)!: trust only configured issuers - #274

Merged
uniqueg merged 5 commits into
devfrom
fix/auth-trusted-issuers
Oct 18, 2026
Merged

uniqueg merged 5 commits into
devfrom
fix/auth-trusted-issuers

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

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 own iss claim, 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, with validation_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

  • Trusted issuers: new security.auth.issuers. Tokens of other issuers are rejected before any network request; if no issuers are configured, all tokens are rejected (fail closed).
  • Discovery: the discovery document must be issued for the token's issuer (issuer member), and the issuer is passed to jwt.decode.
  • Always verify signatures locally with the issuer's JWK set; tokens without key ID are tried against all signing keys; alg: none is rejected.
  • User info is only an additional check (validate_userinfo: True), performed after local verification; its sub must match the token's.
  • Required claims: exp, iat, iss and the identity claim (claim_identity).
  • Verified claims are returned, so add_key_to_claims works again (public key in PEM format).
  • Network: timeouts (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.
  • Warnings on app creation if no issuers are configured, audience validation is disabled, or expired tokens are accepted.
  • README, config template, examples and test fixtures updated; the README and AuthConfig docs recommend setting audience.

Claims are still copied into request.headers for now, as check_permissions relies on that; both are removed together in the next PR (header-based checks).

Closes #275

Breaking changes

  • security.auth.issuers must list the trusted issuers (e.g., the LS Login issuer for proTES/cloud-registry); otherwise all tokens are rejected.
  • validation_methods, validation_checks and claim_issuer are removed (configs using them fail validation); use validate_userinfo: True for the additional user info check.
  • Tokens must contain exp, iat, iss and the identity claim, and are always verified locally (userinfo-only validation is no longer possible).

Verification

Test-first: tests/security/test_auth.py rewritten 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 and allow_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 foca clean.

Review follow-up (Sourcery): failed fetch cooldown (tests for discovery/JWKS failures, failed refetches and unthrottled user info), no-kid test with the matching key after a non-matching one, and docs recommending audience; keeping audience optional is deliberate (startup warning). Auth tests: 42 passed, 100% coverage of foca/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:

  • Add trusted-issuer configuration with local JWT signature verification and optional user-info validation.
  • Add configurable identity-provider request timeouts, caching, key-rotation handling, and failed-fetch cooldowns.

Bug Fixes:

  • Prevent bearer tokens from untrusted issuers, forged or unsigned tokens, missing required claims, and mismatched discovery or user-info responses from being accepted.
  • Return verified token claims and enforce issuer, expiry, algorithm, and optional audience validation.

Enhancements:

  • Replace legacy validation method and issuer settings with the fail-closed authentication configuration.
  • Warn at application startup about missing trusted issuers, disabled audience validation, or acceptance of expired tokens.

Documentation:

  • Update the README, configuration template, examples, and authentication configuration documentation for trusted issuers and audience validation.

Tests:

  • Rewrite authentication coverage around signed tokens, real keys, mocked identity providers, validation failures, caching, key rotation, network behavior, configuration, and warnings.

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]>
@sourcery-ai

sourcery-ai Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Replaces 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 validation

sequenceDiagram
    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
Loading

File-Level Changes

Change Details Files
Rework bearer-token validation to fail closed and trust only explicitly configured issuers.
  • Add trusted issuer allowlisting with rejection before network access, issuer-bound discovery validation, required claims, audience/expiry enforcement, and verified claims output.
  • Remove the legacy validation-method/check and configurable issuer-claim settings in favor of mandatory local signature verification.
  • Add optional post-verification user-info validation requiring subject equality.
foca/security/auth.py
foca/models/config.py
tests/security/test_auth.py
Harden identity-provider network access and key handling.
  • Add request timeouts, redirect blocking, discovery/JWK caching, TTL expiry, and throttled JWK refetching for key rotation.
  • Verify against matching or all signing keys as appropriate, reject unsigned/forged tokens, and optionally expose the selected public key in PEM format.
foca/security/auth.py
tests/security/test_auth.py
Update authentication configuration guidance and application diagnostics for the new security model.
  • Add issuers and new timeout/cache/user-info settings to the configuration model and examples, while removing obsolete fields.
  • Log startup warnings for missing issuers, disabled audience validation, and accepted expired tokens.
  • Update configuration fixtures, README, templates, and application tests.
foca/foca.py
foca/models/config.py
README.md
templates/config.yaml
examples/petstore/config.yaml
examples/petstore-access-control/config.yaml
tests/test_files/conf_invalid_access_control.yaml
tests/test_files/conf_invalid_log_level.yaml
tests/test_files/conf_no_jobs.yaml
tests/test_files/conf_valid.yaml
tests/test_files/conf_valid_access_control.yaml
tests/test_files/conf_valid_cors_disabled.yaml
tests/test_files/conf_valid_cors_enabled.yaml
tests/test_files/conf_valid_custom_invalid.yaml
tests/test_foca.py

Assessment against linked issues

Issue Objective Addressed Explanation
#275 Trust only configured issuers: reject unlisted or missing issuers before network access, and verify that discovery metadata and the JWT issuer match. ✅
#275 Require local JWT signature verification and the required claims, make userinfo an optional additional check with a matching subject, and return verified claims. ❌ The PR implements local signature verification, additional userinfo validation, and returning verified claims. However, it requires conf.claim_identity rather than always requiring sub; with a custom identity claim, a token missing sub can pass, contrary to the issue’s required-claims criteria.
#275 Harden and document the authentication flow with safe network fetching, caching, startup warnings, and the requested reusable validation API and migration guidance. ❌ Timeouts, redirect disabling, caching, and startup warnings are implemented. The PR does not restrict fetched endpoint URLs to HTTPS (with the specified loopback exception), expose the requested pure validate_jwt(token, conf) function, add INFO-level rejection logging with reason and issuer, or update docs/access_control/README.md and provide a migration note.

Possibly linked issues

  • fix(auth)!: trust only configured issuers #275: The PR implements the issue’s proposed authentication hardening, including issuer allowlisting before network calls, signature verification, userinfo subject matching, caching, and timeouts.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (14c7164) to head (d2ef30c).

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     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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]>
@uniqueg
uniqueg marked this pull request as ready for review October 18, 2026 01:02

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/security/auth.py Resolved
Comment thread foca/security/auth.py Resolved
Comment thread tests/security/test_auth.py Resolved
uniqueg and others added 2 commits October 18, 2026 19:40
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]>
@uniqueg
uniqueg merged commit e3ef320 into dev Oct 18, 2026
13 checks passed
@uniqueg
uniqueg deleted the fix/auth-trusted-issuers branch October 18, 2026 23:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(auth)!: trust only configured issuers

1 participant