Skip to content

feat: add option to reject invalid optional tokens - #668

Merged
uniqueg merged 4 commits into
devfrom
feat/607-reject-invalid-optional-tokens
Nov 4, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/607-reject-invalid-optional-tokens

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

On operations with optional authentication (an empty alternative in security), a request with an invalid token is treated as anonymous.

  • New option security.auth.reject_invalid_tokens (default false): such requests get 401 with error="invalid_token". Failures of the identity provider don't count as invalid tokens; those requests stay anonymous, as documented.
  • It applies to schemes with x-bearerInfoFunc: foca.security.auth.validate_token, not to wrappers of apps. Implemented as a resolver (InvalidTokenResolver), sharing _normalize_resolver with AccessControlResolver in the new foca/security/resolvers.py.
  • The config template named a placeholder, app.validate_token, with which the option would have no effect; it now names FOCA's function.
  • Docs: authentication ("Optional tokens"), configuration reference, access control example.

Closes #607

Verification

  • ruff check, ruff format --check, mypy, ast-grep scan, mkdocs build --strict: pass.
  • coverage run -m pytest with MongoDB 7.0: 3408 passed, 1 skipped, 100% coverage.
  • Both reviewer subagents, then a second adversarial round (no high or medium findings in round 2).
  • CI: see the checks of this PR.

Declined review findings

  • getattr() for connexion_context: it is always set on resolved operations.
  • Direct unit tests of each header form: covered through the app tests.
  • Not limiting optional tokens to bearer schemes: with add_security_fields, an apiKey scheme also gets x-bearerInfoFunc, so an operation [{apiKey: []}, {}] rejects an invalid bearer token sent without a key. A client sending an invalid token should get an error here as well; OpenAPI 2 needs apiKey with x-authentication-scheme in any case.

For the maintainer

The default stays false, so nothing changes for existing apps. Whether it flips for 1.0.0-rc1 is open; I recommend flipping it then.

🤖 Generated with Claude Code

Summary by Sourcery

Add configurable rejection of invalid bearer tokens on operations that allow anonymous access.

New Features:

  • Add optional-token handling that can reject invalid bearer tokens with a 401 invalid_token challenge when configured.

Bug Fixes:

  • Ensure optional authentication does not silently accept invalid bearer tokens when rejection is enabled, while preserving anonymous access for identity-provider failures and requests without tokens.

Enhancements:

  • Apply invalid-token resolution consistently to application APIs and access-control permission APIs, while leaving required, public, and non-FOCA authentication schemes unchanged.

Documentation:

  • Document optional-token behavior and the reject_invalid_tokens configuration option.
  • Update configuration templates and reference documentation for optional-token rejection.

Tests:

  • Add comprehensive coverage for optional-token validation, rejection behavior, fallback cases, resolver composition, and permission API registration.

uniqueg and others added 2 commits November 4, 2026 04:38
On operations with optional authentication, Connexion treats a request
with an invalid token as anonymous, so a client with an expired token
silently gets less. With security.auth.reject_invalid_tokens, such
requests get 401. The default keeps today's behaviour.

Also point the config template to foca.security.auth.validate_token.

Closes #607

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The logged text is the reason for rejecting the token, not the token.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces an opt-in resolver-based mechanism that rejects invalid FOCA-validated bearer tokens with 401 invalid_token on optional-authentication operations, while retaining anonymous access for missing tokens and identity-provider failures. The change also centralizes resolver normalization, updates the generated configuration and validator reference, documents the behavior, and adds broad integration and unit coverage.

Sequence diagram for rejecting invalid optional bearer tokens

sequenceDiagram
    participant Client
    participant Connexion
    participant Controller
    participant FOCA as FOCA auth
    participant Provider as Identity provider

    Client->>Connexion: Request with optional bearer token
    Connexion->>FOCA: validate_token(token)
    alt Valid token
        FOCA-->>Connexion: token_info
        Connexion->>Controller: Invoke resolved operation
    else Invalid token
        FOCA-->>Connexion: Unauthorized invalid_token
        Connexion->>Controller: Invoke wrapped operation anonymously
        Controller->>FOCA: _reject_invalid_token()
        FOCA-->>Controller: Unauthorized invalid_token
        Controller-->>Client: 401 invalid_token
    else Provider failure
        FOCA-->>Connexion: Unauthorized provider failure
        Connexion->>Controller: Invoke wrapped operation anonymously
        Controller->>FOCA: validate_token(token)
        FOCA->>Provider: Validate token
        Provider-->>FOCA: Unavailable or other failure
        FOCA-->>Controller: Keep request anonymous
        Controller-->>Client: Public response
    end
Loading

File-Level Changes

Change Details Files
Adds configurable rejection of invalid bearer tokens on optionally authenticated operations while preserving anonymous behavior for missing tokens and validation-provider failures.
  • Adds security.auth.reject_invalid_tokens, defaulting to false.
  • Captures FOCA validation failures and applies a controller wrapper that returns 401 with an RFC 6750 invalid_token challenge only for invalid tokens.
  • Detects optional operations using FOCA’s validate_token, including cases where the empty security requirement is first.
  • Leaves required/public operations, non-bearer schemes, custom validators, non-bearer headers, and identity-provider outages unchanged.
foca/models/config.py
foca/security/auth.py
foca/api/register_openapi.py
foca/security/resolvers.py
foca/security/access_control/enforcement.py
Composes the new token-rejection resolver with existing Connexion and access-control resolution.
  • Extracts shared resolver normalization for callable, object, and default resolvers.
  • Wraps the existing resolved controller rather than replacing operation resolution behavior.
  • Registers the resolver only when the new configuration option is enabled.
foca/security/resolvers.py
foca/security/auth.py
foca/security/access_control/enforcement.py
foca/api/register_openapi.py
Aligns generated configuration and documentation with the new optional-token behavior.
  • Adds the option to the configuration template and reference documentation.
  • Replaces the placeholder validation function with FOCA’s fully qualified validator.
  • Documents ordering, anonymous behavior, rejection semantics, provider failures, and access-control interactions.
templates/config.yaml
docs/authentication.md
docs/configuration/auth.md
docs/access-control.md
docs/reference.md
Adds comprehensive coverage for rejection behavior and resolver composition.
  • Tests missing, malformed, valid, invalid, and differently cased bearer headers.
  • Covers empty-first and bearer-first security alternatives, provider outages, validation-once behavior, and unchanged operation categories.
  • Verifies resolver normalization for callable and duck-typed resolver inputs.
tests/security/test_optional_tokens.py

Possibly linked issues


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 Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #668   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           56        57    +1     
  Lines         7328      7395   +67     
=========================================
+ Hits          7328      7395   +67     
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.

@uniqueg
uniqueg marked this pull request as ready for review November 4, 2026 03:48

@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 2 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="230" />
<code_context>
+        token = _get_bearer_token()
+        # Set by Connexion's security handlers, which wrap the controller
+        context = request_ctx.connexion_context  # type: ignore[attr-defined]
+        if token is not None and not context.get("token_info"):
+            try:
+                error = g.pop(_TOKEN_ERROR_ATTRIBUTE, None)
</code_context>
<issue_to_address>
**Other authentication bypasses token check**

When an optional operation has a FOCA-validated scheme and a non-FOCA alternative that succeeds while the request also carries an invalid Bearer token, connexion can populate `token_info` when a non-FOCA security alternative succeeds, so this guard skips `validate_token(token)` even when the request also carries an invalid bearer token; the controller then handles the request without the configured rejection.

Only skip the extra validation when the successful `token_info` is known to come from the FOCA-validated bearer scheme.
</issue_to_address>

### Comment 2
<location path="foca/api/register_openapi.py" line_range="527-530" />
<code_context>
             connexion_kwargs["resolver"] = AccessControlResolver(
                 resolver=connexion_kwargs.get("resolver"),
             )
+        if _rejects_invalid_tokens(app):
+            connexion_kwargs["resolver"] = InvalidTokenResolver(
+                resolver=connexion_kwargs.get("resolver"),
+            )
         try:
             app.add_api(
</code_context>
<issue_to_address>
**Permission API skips token rejection**

When a custom permission API specification contains an optional security requirement with a scheme naming `foca.security.auth.validate_token`, `register_permission_specs` registers its API directly with `AccessControlResolver`, without `InvalidTokenResolver`, so Connexion still handles invalid tokens on those operations as anonymous.

Apply `InvalidTokenResolver` to the permission API resolver when `security.auth.reject_invalid_tokens` is enabled.
</issue_to_address>

Linked issues

#607 feat(auth): reject invalid optional tokens · 4 of 4 met

# Requirement Status Notes
1 Add an option under security.auth to return 401 with an RFC 6750 challenge for invalid tokens on optional-auth operations, while requests without a token stay anonymous. ✅ Met The option defaults to false; when enabled, invalid FOCA-validated tokens are rejected, and requests without a bearer token remain anonymous.
2 Test no token, valid, expired, wrong audience and untrusted issuer with the option on and off, with 100% coverage. ✅ Met The added tests cover these cases with the option enabled and disabled; the PR verification reports 100% coverage.
3 Decide whether the default changes; if it does, land by 1.0.0-rc1 and document the change in the migration guide. ✅ Met The option defaults to false, so the existing behavior is preserved and no migration-guide entry is needed.
4 Document the behavior on the authentication page. ✅ Met The new Optional tokens section describes the option and its behavior.

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: foca/security/auth.py:230, foca/api/register_openapi.py:530


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/api/register_openapi.py Resolved
Another scheme of the operation accepting a request hid an invalid
bearer token, as its token_info looked like a validated one. Custom
specifications of the permissions API skipped the option altogether.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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.

Sourcery assessment

Approved.

…d-optional-tokens

# Conflicts:
#	foca/api/register_openapi.py
#	foca/security/access_control/register_access_control.py
#	tests/security/access_control/test_register_access_control.py
@uniqueg
uniqueg merged commit 2c47558 into dev Nov 4, 2026
56 checks passed
@uniqueg
uniqueg deleted the feat/607-reject-invalid-optional-tokens branch November 4, 2026 05:39
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.

feat(auth): reject invalid optional tokens

1 participant