Repository navigation
feat: add option to reject invalid optional tokens - #668
Conversation
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]>
Reviewer's GuideIntroduces an opt-in resolver-based mechanism that rejects invalid FOCA-validated bearer tokens with Sequence diagram for rejecting invalid optional bearer tokenssequenceDiagram
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
File-Level Changes
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 #668 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 56 57 +1
Lines 7328 7395 +67
=========================================
+ Hits 7328 7395 +67
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:
|
There was a problem hiding this comment.
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
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]>
…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
Summary
On operations with optional authentication (an empty alternative in
security), a request with an invalid token is treated as anonymous.security.auth.reject_invalid_tokens(defaultfalse): such requests get401witherror="invalid_token". Failures of the identity provider don't count as invalid tokens; those requests stay anonymous, as documented.x-bearerInfoFunc: foca.security.auth.validate_token, not to wrappers of apps. Implemented as a resolver (InvalidTokenResolver), sharing_normalize_resolverwithAccessControlResolverin the newfoca/security/resolvers.py.app.validate_token, with which the option would have no effect; it now names FOCA's function.Closes #607
Verification
ruff check,ruff format --check,mypy,ast-grep scan,mkdocs build --strict: pass.coverage run -m pytestwith MongoDB 7.0: 3408 passed, 1 skipped, 100% coverage.Declined review findings
getattr()forconnexion_context: it is always set on resolved operations.add_security_fields, anapiKeyscheme also getsx-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 needsapiKeywithx-authentication-schemein 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:
Bug Fixes:
Enhancements:
Documentation:
Tests: