Repository navigation
fix(errors): keep headers of HTTP exceptions - #349
Conversation
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]>
Reviewer's GuideThe 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 headerssequenceDiagram
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)
Sequence diagram for RFC 6750 Bearer authentication challengessequenceDiagram
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
Sequence diagram for Connexion security Bearer fallbacksequenceDiagram
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
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 #349 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 24 24
Lines 1753 1786 +33
=========================================
+ Hits 1753 1786 +33
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
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
- 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]>
Summary
Closes #343
get_headers()) and Connexion'sProblemException(headers), except headers describing the body (Content-Type, which stays the configured problem media type,Content-Length,Content-Encoding,Transfer-Encoding). Examples:Allowfor 405,WWW-Authenticatefor 401, andRetry-Afterfor 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.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.Bearer. This covers identity provider failures and validated tokens that lack access control's identity claim, cases where logging in again would not help.OAuthProblem, e.g., for a missing token) that have no challenge of their own getWWW-Authenticate: Bearer, because FOCA supports Bearer tokens only.docs/configuration/exceptions.mdand a note indocs/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: passmongod, port 12345):uv --resolution lowest-direct, Werkzeug 3.1.5): 1049 passed, 1 skippedfoca/errors/exceptions.py,foca/security/auth.py,foca/security/access_control/enforcement.py): 100%invalid_token) fixed in 4f68a63; Sourcery's two findings (403 is no token rejection; drop body headers) fixed in 7a5ed8a.Declined review findings
_unauthorizedinenforcement.py(import cycle): kept. It follows the existing pattern infoca/config/access.py(# noqa: PLC0415 (import cycle)), andregister_access_control.pyalready imports a private helper across modules. A new leaf module would add structure for little gain.Retry-Afterinstead of 401: not done here, because it changes the status code. PlainBearerwithout an error code avoids needless re-logins.Bearerchallenge from Connexion'sOAuthProblem: documented as a limitation, since FOCA supports Bearer only.realm: FOCA has no realm setting.INVALID_TOKEN_CHALLENGEliteral in two test modules: kept on purpose, so that the tests check the wire format independently of the implementation constant.AttributeError(500) (round-2 adversarial, low): existing behaviour outside this issue; listed as a follow-up.Open questions
None.
🤖 Generated with Claude Code