Skip to content

fix: check bearer tokens before reading bodies - #817

Merged
uniqueg merged 6 commits into
devfrom
fix/814-token-before-body
Nov 22, 2026
Merged

uniqueg merged 6 commits into
devfrom
fix/814-token-before-body

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

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 a before_request hook before anything reads the body. This applies on operations whose effective security can only be met by FOCA's token validation: every alternative names only http/bearer schemes with x-bearerInfoFunc: foca.security.auth.validate_token. Requests without such a token, with a malformed Authorization header or with an invalid token get the same 401 as from Connexion, and their body is never read.

  • foca/security/auth.py:
    • New _check_bearer_token hook. It uses the same header parsing and the same errors as Connexion's get_auth_header_value / verify_security; a test compares the bodies and challenges.
    • New predicate _requires_bearer_token.
    • validate_token keeps the token info for the request (_ValidatedToken on flask.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: Route records three more things:
    • security_schemes;
    • bearer_info_functions: the functions resolved when the API was added, as Connexion resolves them, so test patches of validate_token during 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.
  • Left to Connexion as before: operations with optional tokens, no security, API keys, Basic, OAuth 2.0, other validation functions, or schemes resolved to different functions.

Closes #814

Decisions taken

  • The token check runs before the body size check, not after it (the issue said "after the body size check"). Otherwise the size check would read bodies without a declared size (chunked) up to the limit for anonymous clients, which fails the issue's acceptance criterion ("401 without its body being read"). As a result, anonymous requests with too large bodies get 401 instead of 413 on these operations, and authenticated ones still get 413. This is documented in the migration guide. Easy to revert (two lines in connexion_app.py, plus the docs and one test) if you prefer the issue's order.
  • Board: issue on board 25, In progress (decided by the main session for tonight).

Verification

  • coverage run -m pytest with a local MongoDB 7.0 on port 12345 (all tests, 100% coverage): 5602 passed, 2 skipped, 100% coverage
  • ruff 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.
  • New tests:
    • tests/security/test_early_token_check.py:
      • anonymous, other-scheme, malformed and invalid tokens with JSON, URL-encoded, multipart and chunked bodies: 401 with Request.get_data, form and files patched and never called;
      • no-body operations, preflight, and the 401 vs 413 order;
      • valid tokens validated once;
      • same response as Connexion;
      • unchecked operations behave as before;
      • spec/UI/app routes shadowed by templates or the same rule;
      • the per-request cache.
    • tests/api/test_routes.py: the new Route fields.
    • Petstore example (in-process): tests/examples/test_petstore_access_control.py::test_unauthenticated_body_unread.
  • The docker-based tests/integration_tests.py petstore has no security, so the petstore-access-control example covers the integration level in-process.
  • CI: all checks pass (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 new Route fields.

Sourcery (fixed): the hook is now registered also for apps created without a config; the /both test asserts validation after the body is read; the migration guide notes that replacements of validate_token run twice per request. Answered: running before the size check (see Decisions taken).

Declined review findings

  • Quality: replace _TOKEN_VALID_ATTRIBUTE with the new info cache. Declined: it predates this PR and drives _reject_invalid_token on optional operations, which this PR doesn't change. A comment now explains how the three flask.g attributes relate.
  • Quality: reuse the form/files probes in the petstore example test. Declined: the example test checks the JSON flow end to end. The probes for all body kinds are in test_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:

  • Check FOCA-validated bearer tokens before request bodies are read for operations that require them.
  • Reuse validated token information so each token is validated only once per request.
  • Expose effective security schemes, resolved bearer validators, and framework endpoints through recorded route metadata.

Bug Fixes:

  • Prevent unauthenticated or invalidly authenticated requests from reading request bodies before receiving the expected 401 response.
  • Ensure early authentication applies only when Flask routed the request to the corresponding OpenAPI operation.

Enhancements:

  • Preserve Connexion-compatible authentication responses and leave optional authentication and non-FOCA security schemes to existing Connexion handling.

Documentation:

  • Document early bearer-token checks, body-size ordering, affected operations, migration considerations, and new route metadata.

Tests:

  • Add comprehensive coverage for unread bodies, authentication responses, token caching, routing edge cases, body-size ordering, and unchanged behavior for other security configurations.

uniqueg and others added 4 commits November 22, 2026 06:46
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]>
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]>
@uniqueg uniqueg self-assigned this Nov 22, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Extend operation routes with the security schemes, resolved bearer validators, and Flask endpoint needed by the early token check.

  • foca/api/routes.py L57-69, L80-86

Implementation

Record each operation’s Flask endpoint and resolved bearer validators when Connexion adds it, and expose the route metadata to request handling.

  • foca/api/routes.py L147-176, L210-235, L261-267 (+1 small edits)
  • foca/context.py L17, L347-372

Register the early bearer-token check for every Connexion app, before the body-size check.

  • foca/factories/connexion_app.py L17, L52-56, L215-216

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.

  • foca/security/auth.py L195-210, L245-253, L285-404 (+6 small edits)

Documentation

Explain which operations get an early token check, which routes and security configurations remain with Connexion, and how token validation is resolved.

  • docs/authentication.md L51-85

Update body-size guidance to distinguish operations checked for bearer tokens before body reads from those handled by Connexion first.

  • docs/configuration/server.md L36-43, L58-59, L65-69

Clarify deployment body-size guidance for operations using FOCA-validated bearer tokens.

  • docs/deployment.md L145-147

Document the migration impact of early token rejection, changed 401-versus-413 outcomes, validation replacements, and before-request hooks.

  • docs/migration-0.23.md L27-31, L334-361

Document the security metadata exposed on recorded operation routes.

  • docs/utilities.md L262-266

Tests

Test route security metadata, immutability, resolved bearer functions, and recorded Flask endpoints.

  • tests/api/test_routes.py L17-22, L191-246

Test early token rejection without body reads, valid-token caching, route exclusions, and unchanged handling for other security configurations.

  • tests/security/test_early_token_check.py L1-652

Verify the petstore example rejects unauthenticated requests without reading their bodies.

  • tests/examples/test_petstore_access_control.py L11, L120-138

Test detection that a request was routed to the operation’s own rule and endpoint.

  • tests/test_context.py L580-590

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 22, 2026 •

Copy link
Copy Markdown

Codecov Report

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

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     
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 22, 2026 09:17
@sourcery-ai

sourcery-ai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit befa883

#814 fix: validate bearer tokens before parsing bodies · 5 of 6 met

# Requirement Status Notes
1 Check required FOCA-validated bearer tokens before Connexion reads the body, after the body-size check. 🟡 Partly met The early token check runs before Connexion reads the body, but it is registered before the body-size check, so oversized anonymous requests get 401 rather than the requested size-check response.
2 Reuse validated token info so each token is validated once per request. ✅ Met validate_token caches successful token info for the request, and the tests check that validation runs once.
3 Leave optional or non-bearer security operations to Connexion as before. ✅ Met The predicate excludes optional, public, mixed-scheme, and differently validated operations; tests cover these cases.
4 Keep the check in one place that can move to ASGI middleware. ✅ Met The check is implemented in one hook, and its docstring identifies it as middleware to move with ASGI support.
5 Test unread bodies for JSON, URL-encoded, multipart, and bodyless operations; test valid tokens, unchanged security cases, the petstore example, and 100% coverage. ✅ Met The diff adds the requested regression and petstore example tests; the PR reports 100% coverage for the full test suite.
6 Document which operations are checked before body reads and which are not, including release migration guidance. ✅ Met The authentication and server configuration docs describe the checked and unchecked cases, and the migration guide documents the behavior change.

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


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/factories/connexion_app.py Resolved
Comment thread foca/factories/connexion_app.py Resolved
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]>

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

New gaps against the linked issues

Comment thread foca/factories/connexion_app.py Resolved

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

New gaps against the linked issues

Comment thread foca/factories/connexion_app.py Resolved
@uniqueg
uniqueg merged commit f003a36 into dev Nov 22, 2026
58 checks passed
@uniqueg
uniqueg deleted the fix/814-token-before-body branch November 22, 2026 10:09
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: validate bearer tokens before parsing bodies

1 participant