Repository navigation
fix: check bearer tokens before reading bodies - #817
Conversation
Routes now carry the security schemes of their API specification, so that FOCA can tell before Connexion handles a request how its security requirements are validated (#814). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Connexion 2 reads and parses the body of every request before its security handler checks the token. A before_request hook, ahead of the body size check, now rejects requests without a valid bearer token on operations whose security is met only by schemes validated by validate_token, with their body unread. validate_token reuses its token info within a request, so each token is validated once. Closes #814 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review findings of the early token check (#814): - check only requests that Flask routed to the operation's own rule and endpoint, so the served specification, the Swagger UI and app routes stay public, also if an operation's template matches them - call the bearer function Connexion resolved when the API was added (Route.bearer_info_functions), so patches during registration apply - resolve only schemes named by the operation, as Connexion does - name the cached token info (_ValidatedToken), more tests and docs Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideData structuresExtend operation routes with the security schemes, resolved bearer validators, and Flask endpoint needed by the early token check.
ImplementationRecord each operation’s Flask endpoint and resolved bearer validators when Connexion adds it, and expose the route metadata to request handling.
Register the early bearer-token check for every Connexion app, before the body-size check.
Cache successful token info per request and reject requests before body reads only when every effective security alternative uses the same FOCA-validated bearer function.
DocumentationExplain which operations get an early token check, which routes and security configurations remain with Connexion, and how token validation is resolved.
Update body-size guidance to distinguish operations checked for bearer tokens before body reads from those handled by Connexion first.
Clarify deployment body-size guidance for operations using FOCA-validated bearer tokens.
Document the migration impact of early token rejection, changed 401-versus-413 outcomes, validation replacements, and before-request hooks.
Document the security metadata exposed on recorded operation routes.
TestsTest route security metadata, immutability, resolved bearer functions, and recorded Flask endpoints.
Test early token rejection without body reads, valid-token caching, route exclusions, and unchanged handling for other security configurations.
Verify the petstore example rejects unauthenticated requests without reading their bodies.
Test detection that a request was routed to the operation’s own rule and endpoint.
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 #817 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 76 76
Lines 10640 10708 +68
=========================================
+ Hits 10640 10708 +68
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:
|
Linked issuesChecked at commit befa883 #814 fix: validate bearer tokens before parsing bodies · 5 of 6 met
|
There was a problem hiding this comment.
Hey - I've found 4 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="405" />
<code_context>
specification's config, its security requirements are removed, e.g., for
local development.
+### Tokens are checked before bodies are read
+
</code_context>
<issue_to_address>
**Replacement validators run twice**
When the validator resolved for the bearer scheme when the API is added is a replacement that does not cache its result, `route.bearer_info_functions[first](token)` runs in the early hook, then Connexion calls the same validator again after reading the body. The second call duplicates side effects or returns a different result, so the request can fail after its body is read.
Reuse the early check’s validation result in Connexion’s security handling, or otherwise ensure the resolved validator runs only once per request.
Also at `foca/security/auth.py:404`.
</issue_to_address>
### Comment 2
<location path="foca/factories/connexion_app.py" line_range="214" />
<code_context>
+ # first, so that bodies of requests without a valid token aren't read at
+ # all (the size check reads bodies without a declared size); the size
+ # check also checks limits set in the Flask config later
+ app.app.before_request(_check_bearer_token)
app.app.before_request(_check_body_size)
if conf.debug and not _is_loopback(conf.host):
</code_context>
<issue_to_address>
**Unauthenticated request bodies are read**
When a secured FOCA API is used with a Connexion app not created through `create_connexion_app()` with a non-None config, `create_connexion_app()` skips `__add_config_to_connexion_app`, where `_check_bearer_token` is registered, and `register_openapi()` does not install the hook; Connexion parses request bodies before authentication, so anonymous clients’ bodies are read.
Register `_check_bearer_token` for FOCA APIs regardless of whether `create_connexion_app()` receives a config.
</issue_to_address>
### Comment 3
<location path="foca/factories/connexion_app.py" line_range="214-215" />
<code_context>
+ # first, so that bodies of requests without a valid token aren't read at
+ # all (the size check reads bodies without a declared size); the size
+ # check also checks limits set in the Flask config later
+ app.app.before_request(_check_bearer_token)
app.app.before_request(_check_body_size)
if conf.debug and not _is_loopback(conf.host):
logger.warning(
</code_context>
<issue_to_address>
**Keep size check first**
The issue asks for the early token hook to run after the body-size check, but this change registers it before that check. As the PR notes, this changes oversized anonymous requests from 413 to 401 and avoids reading chunked bodies before authentication.
</issue_to_address>
### Comment 4
<location path="tests/security/test_early_token_check.py" line_range="444-448" />
<code_context>
+ subject: str | None,
+ ) -> None:
+ """Bodies are read before Connexion's checks, as before."""
+ token = _token() if path == "/both" else "opaque"
+ header = None if path in {"/optional", "/public"} else f"Bearer {token}"
+ response = _post(app, path, header, **headers)
+ assert body_reads.called
+ assert response.status_code == 200
+ if path != "/both":
+ assert response.json() == subject
</code_context>
<issue_to_address>
**Mixed-scheme early checks pass unnoticed**
When the early-check hook incorrectly runs for the `/both` operation, in `test_read_as_before`, `/both` is sent with a valid bearer token and API key, so a broken hook that checks the bearer before reading the body still reaches Connexion, reads the body, and returns 200. The assertions therefore pass without verifying that this mixed-scheme operation is left entirely to Connexion.
For `/both`, assert that the bearer validator runs only after body access, or otherwise observe that the early hook does not invoke it.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 4 findings to address first, and the new pre-body check validates bearer tokens and caches their token info for Connexion to reuse, changing the authentication path and the order in which requests reach app hooks. If the early check or reuse diverges from Connexion's behavior, requests could be wrongly rejected or handled with incorrect auth info; reverting removes the change, but any access or request handling that occurred while it was deployed cannot be undone.
Blocking findings: foca/security/auth.py:405, foca/factories/connexion_app.py:214, foca/factories/connexion_app.py:215, tests/security/test_early_token_check.py:448
Address Sourcery review of #817: register the early token check in create_connexion_app() with or without a config, test that operations with mixed schemes validate tokens only after reading the body, and note in the migration guide that replacements of validate_token are called twice per request unless they reuse their result. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Connexion 2 reads and parses the body of every request (
get_data(),form,files) before its security handler checks the token. With this PR, FOCA checks bearer tokens in abefore_requesthook before anything reads the body. This applies on operations whose effective security can only be met by FOCA's token validation: every alternative names onlyhttp/bearerschemes withx-bearerInfoFunc: foca.security.auth.validate_token. Requests without such a token, with a malformedAuthorizationheader or with an invalid token get the same401as from Connexion, and their body is never read.foca/security/auth.py:_check_bearer_tokenhook. It uses the same header parsing and the same errors as Connexion'sget_auth_header_value/verify_security; a test compares the bodies and challenges._requires_bearer_token.validate_tokenkeeps the token info for the request (_ValidatedTokenonflask.g, keyed to the request and the token). Connexion's second call returns the same info, so each token is validated once per request.foca/api/routes.py:Routerecords three more things:security_schemes;bearer_info_functions: the functions resolved when the API was added, as Connexion resolves them, so test patches ofvalidate_tokenduring registration apply to both checks;endpoint: Flask's endpoint of the operation.foca/context.py:_is_routed_to()checks that Flask routed the request to the operation's own rule and endpoint. The served spec, the Swagger UI and app routes stay unchecked, also when a/{param}template or the same rule matches them.Closes #814
Decisions taken
401instead of413on these operations, and authenticated ones still get413. This is documented in the migration guide. Easy to revert (two lines inconnexion_app.py, plus the docs and one test) if you prefer the issue's order.Verification
coverage run -m pytestwith a local MongoDB 7.0 on port 12345 (all tests, 100% coverage): 5602 passed, 2 skipped, 100% coverageruff check,ruff format --check,mypy,ast-grep scan --error=flask-import,ast-grep test --skip-snapshot-tests,semgrep scan --config .semgrep --error,mkdocs build --strict: all pass.tests/security/test_early_token_check.py:401withRequest.get_data,formandfilespatched and never called;401vs413order;tests/api/test_routes.py: the newRoutefields.tests/examples/test_petstore_access_control.py::test_unauthenticated_body_unread.tests/integration_tests.pypetstore has no security, so the petstore-access-control example covers the integration level in-process.CI passed) on both pushes, no reruns needed (the flaky timing tests did not fail)Docs
docs/authentication.md: new section "Tokens are checked before bodies are read": what is checked, what isn't, and when the validation function is resolved.docs/configuration/server.md: request body size section and warning.docs/deployment.md.docs/migration-0.23.md: new section "Bearer tokens are checked before bodies are read".docs/utilities.md: the newRoutefields.Sourcery (fixed): the hook is now registered also for apps created without a config; the
/bothtest asserts validation after the body is read; the migration guide notes that replacements ofvalidate_tokenrun twice per request. Answered: running before the size check (see Decisions taken).Declined review findings
_TOKEN_VALID_ATTRIBUTEwith the new info cache. Declined: it predates this PR and drives_reject_invalid_tokenon optional operations, which this PR doesn't change. A comment now explains how the threeflask.gattributes relate.form/filesprobes in the petstore example test. Declined: the example test checks the JSON flow end to end. The probes for all body kinds are intest_early_token_check.py.Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Reject unauthenticated requests to FOCA-protected operations before reading their bodies while preserving Connexion behavior for all other routes and security schemes.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: