Skip to content

fix(errors): keep headers of HTTP exceptions - #349

Merged
uniqueg merged 6 commits into
devfrom
fix/error-headers
Oct 21, 2026
Merged

uniqueg merged 6 commits into
devfrom
fix/error-headers

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #343

  • FOCA's problem handler now keeps the headers of werkzeug HTTP exceptions (get_headers()) and Connexion's ProblemException (headers), except headers describing the body (Content-Type, which stays the configured problem media type, Content-Length, Content-Encoding, Transfer-Encoding). Examples: Allow for 405, WWW-Authenticate for 401, and Retry-After for 503/429 when set. Headers are dropped if the exception is mapped to problem details with a different status, because they may not apply to it.
  • 401s from FOCA's own token validation and access control carry an RFC 6750 Bearer challenge:
    • invalid tokens (malformed, expired, untrusted issuer, bad signature or claims, user info rejected with 401 or not matching) get Bearer error="invalid_token", error_description="The access token could not be validated". The description is deliberately generic, so it reveals nothing about the identity provider.
    • otherwise the challenge is plain Bearer. This covers identity provider failures and validated tokens that lack access control's identity claim, cases where logging in again would not help.
    • parameter values are always quoted, as in RFC 6750's examples (werkzeug leaves token-like values unquoted).
  • 401s from Connexion's security exceptions (OAuthProblem, e.g., for a missing token) that have no challenge of their own get WWW-Authenticate: Bearer, because FOCA supports Bearer tokens only.
  • Docs: a new "Headers" section in docs/configuration/exceptions.md and a note in docs/authentication.md.

Release notes (0.16.0): error responses keep exception headers (Allow, WWW-Authenticate, Retry-After) and 401s carry RFC 6750 Bearer challenges.

No new public API: the helpers are private (_build_headers, _unauthorized, _BearerChallenge).

Verification

  • ruff check, ruff format --check, mypy foca, mkdocs build --strict: pass
  • Full suite with MongoDB 7.0 (mise mongod, port 12345):
    • Python 3.13: 1050 passed
    • Python 3.10: 1049 passed, 1 skipped
    • Python 3.14: 1050 passed
    • Python 3.10 with lowest direct dependencies (uv --resolution lowest-direct, Werkzeug 3.1.5): 1049 passed, 1 skipped
  • Coverage of the changed modules (foca/errors/exceptions.py, foca/security/auth.py, foca/security/access_control/enforcement.py): 100%
  • Reviewed by the adversarial and quality reviewer agents (2 rounds); round-2 medium (user info outages gave invalid_token) fixed in 4f68a63; Sourcery's two findings (403 is no token rejection; drop body headers) fixed in 7a5ed8a.
  • semgrep (p/python, p/secrets): clean; the pre-existing unverified pre-decode of tokens (issuer check before any network request) is suppressed inline with a justification.
  • CI: all checks pass (lint/type-check/build, unit tests on Python 3.10-3.14 with MongoDB 7.0, lowest dependencies, petstore integration tests, Read the Docs; the MongoDB 8.0 job is skipped on affected runner kernels as designed)

Declined review findings

  • Local import of _unauthorized in enforcement.py (import cycle): kept. It follows the existing pattern in foca/config/access.py (# noqa: PLC0415 (import cycle)), and register_access_control.py already imports a private helper across modules. A new leaf module would add structure for little gain.
  • IdP outages could return 503 with Retry-After instead of 401: not done here, because it changes the status code. Plain Bearer without an error code avoids needless re-logins.
  • Basic/apiKey-secured operations get a Bearer challenge from Connexion's OAuthProblem: documented as a limitation, since FOCA supports Bearer only.
  • No realm: FOCA has no realm setting.
  • Duplicate INVALID_TOKEN_CHALLENGE literal in two test modules: kept on purpose, so that the tests check the wire format independently of the implementation constant.
  • JWKS that is valid JSON but not an object raises AttributeError (500) (round-2 adversarial, low): existing behaviour outside this issue; listed as a follow-up.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 5 commits October 21, 2026 22:31
Error responses now keep the headers of werkzeug HTTP exceptions
(get_headers()) and Connexion problem exceptions (headers), except
Content-Type, e.g., Allow for 405, WWW-Authenticate for 401 and
Retry-After for 503. Headers are dropped if the exception is mapped to
another status. 401s to Connexion's security exceptions without a
challenge (e.g., missing token) get WWW-Authenticate: Bearer
(RFC 6750, section 3.1).

Refs #343

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Token validation and access control raise 401s with a Bearer challenge
as per RFC 6750, section 3.1: with error="invalid_token" and a generic
error_description if a token was given, without error code if not.
Parameter values are always quoted, as in RFC 6750.

Refs #343

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Identity provider failures (unavailable or invalid discovery documents
and JWK sets) and validated tokens lacking the identity claim of access
control now get a Bearer challenge without error code, as logging in
again would not help. Document that Connexion's security errors get a
Bearer challenge, and fix a test for Werkzeug 3.1.5, which renders
challenges without parameters with a trailing space.

Refs #343

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Failures to fetch user info (e.g., 5xx or timeouts) no longer give
error="invalid_token"; only 401 and 403 responses of the identity
provider, which reject the token, do.

Refs #343

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The token is decoded without verification only to reject untrusted
issuers before any network request; its signature is verified later
in _verify_signature(). Flagged by semgrep's unverified-jwt-decode
rule, as auth.py changed in this branch.

Refs #343

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

sourcery-ai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR preserves relevant headers from HTTP and Connexion exceptions in problem responses and adds consistently formatted RFC 6750 Bearer challenges to FOCA and Connexion authentication failures, with comprehensive tests and documentation.

Sequence diagram for preserved exception headers

sequenceDiagram
    participant Exception as HTTP_or_Connexion_Exception
    participant Handler as FOCA_Problem_Handler
    participant Response as Problem_Response

    Exception->>Handler: build_problem(exc)
    Handler->>Handler: _build_headers(exc, status)
    alt status matches exception
        Handler->>Handler: get_headers() or headers
        Handler->>Handler: remove Content-Type
    else status was remapped
        Handler->>Handler: discard exception headers
    end
    Handler->>Response: Response(problem, status, headers, media_type)
Loading

Sequence diagram for RFC 6750 Bearer authentication challenges

sequenceDiagram
    participant Client
    participant Auth as Token_Validation_or_Access_Control
    participant Exception as Unauthorized
    participant Handler as FOCA_Problem_Handler

    Client->>Auth: validate_token(token)
    alt token invalid
        Auth->>Auth: _unauthorized(description, invalid_token=True)
        Auth-->>Handler: Unauthorized
        Handler->>Handler: _build_headers(exc, 401)
        Handler-->>Client: 401 WWW-Authenticate: Bearer error="invalid_token", error_description="The access token could not be validated"
    else validation or identity provider unavailable
        Auth->>Auth: _unauthorized(description, invalid_token=False)
        Auth-->>Handler: Unauthorized
        Handler-->>Client: 401 WWW-Authenticate: Bearer
    end
Loading

Sequence diagram for Connexion security Bearer fallback

sequenceDiagram
    participant Client
    participant Connexion as Connexion_Security
    participant Handler as FOCA_Problem_Handler

    Client->>Connexion: secured request
    Connexion-->>Handler: OAuthProblem(status=401)
    Handler->>Handler: _build_headers(exc, 401)
    Handler-->>Client: 401 WWW-Authenticate: Bearer
Loading

File-Level Changes

Change Details Files
Preserve applicable exception headers when rendering problem responses while enforcing the configured problem media type.
  • Added header extraction for Werkzeug HTTP exceptions and Connexion ProblemException instances.
  • Dropped headers when mapped status differs and removed Content-Type before response construction.
  • Added coverage for Allow, Retry-After, WWW-Authenticate, status remapping, and response media type behavior.
foca/errors/exceptions.py
tests/errors/test_errors.py
Attach RFC 6750 Bearer challenges to FOCA-generated authentication and access-control failures.
  • Added a private Bearer challenge formatter that always quotes parameter values.
  • Distinguished invalid-token failures from identity-provider or validated-token failures using generic challenge metadata.
  • Added a default Bearer challenge for Connexion OAuthProblem responses without their own challenge.
  • Updated access-control enforcement to use the shared unauthorized-exception helper.
foca/security/auth.py
foca/security/access_control/enforcement.py
tests/security/test_auth.py
tests/security/access_control/test_enforcement.py
Document the new exception-header and authentication-challenge behavior.
  • Documented retained headers, status-mapping rules, and Content-Type handling.
  • Documented Bearer challenge variants and limitations for non-Bearer security schemes.
docs/configuration/exceptions.md
docs/authentication.md

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

@uniqueg
uniqueg marked this pull request as ready for review October 21, 2026 20:56
@codecov

codecov Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (357bcf8) to head (7a5ed8a).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #349   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           24        24           
  Lines         1753      1786   +33     
=========================================
+ Hits          1753      1786   +33     
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.

@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

Fixed security issues:

  • Detected JWT token decoded with 'verify=False'. This bypasses any integrity checks for the token which means the token could be tampered with by malicious actors. Ensure that the JWT token is verified. (link)
Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/security/auth.py" line_range="273" />
<code_context>
+        # the user info endpoint) make it invalid, not failures to respond
+        raise _unauthorized(
+            f"Could not fetch document from identity provider: {url}",
+            invalid_token=status in (401, 403),
         ) from exc
     _failed_fetches.pop(url, None)
</code_context>
<issue_to_address>
**Valid tokens get rejected**

When a discovery or JWKS request returns 401/403, or user-info returns 403 for a valid token with insufficient scope, `_fetch_json` sets `invalid_token=True` for every 401/403, including these provider failures, so clients receive a misleading `invalid_token` challenge and reauthenticate or discard valid tokens.

Distinguish provider-document failures and insufficient-scope responses from actual token rejection before setting `invalid_token=True`.
</issue_to_address>

### Comment 2
<location path="foca/errors/exceptions.py" line_range="200" />
<code_context>
+        headers.extend(exc.get_headers())
+    elif isinstance(exc, ProblemException) and exc.headers:
+        headers.extend(exc.headers)
+    headers.remove("Content-Type")
+    if (
+        status == 401
</code_context>
<issue_to_address>
**Problem responses carry stale body headers**

When an exception carries `Content-Encoding`, or a `ProblemException` carries `Content-Length`, `_build_headers` copies these body-specific headers, then `_problem_handler_json` replaces the exception body with newly serialized JSON; clients honoring the stale headers fail to decode or truncate the response.

Remove body-specific headers when building headers for the newly serialized JSON response.

Also at `foca/errors/exceptions.py:197`, `foca/errors/exceptions.py:199`.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: foca/security/auth.py:273, foca/errors/exceptions.py:200


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/errors/exceptions.py Resolved
- Drop headers describing the body (Content-Length, Content-Encoding,
  Transfer-Encoding, besides Content-Type) from error responses, as
  their body is newly serialized problem details.
- Only a 401 of the user info endpoint makes a token invalid; 403
  (e.g., insufficient scope) and 401/403 for documents that do not
  depend on the token do not.

Refs #343

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.

@uniqueg
uniqueg merged commit a6cb827 into dev Oct 21, 2026
14 checks passed
@uniqueg
uniqueg deleted the fix/error-headers branch October 21, 2026 21:05
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.

1 participant