Repository navigation
refactor(errors): move the challenge to headers - #714
Conversation
FOCA's token validation now gives the WWW-Authenticate challenge of its 401 errors in `headers`, like any other header, and its own check for invalid tokens reads it from `get_headers()`. `www_authenticate` of `foca.errors.Unauthorized` is deprecated: the argument adds its challenges to `headers`, the attribute reads and writes those of `headers`, both with a DeprecationWarning. Noted in the migration guide to 0.22.0 and the exceptions docs. Closes #710 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review findings: a string passed as the deprecated `www_authenticate` is one challenge; document that the attribute returns copies and that several challenges need a header each. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideRefactors FOCA's Unauthorized implementation to store RFC 6750 authentication challenges in generic headers, with comprehensive deprecated compatibility for Werkzeug's Sequence diagram for FOCA unauthorized challenge headerssequenceDiagram
participant Security as FOCA security auth
participant Unauthorized as foca.errors.Unauthorized
participant Response as HTTP response
Security->>Security: _BearerChallenge.to_header()
Security->>Unauthorized: Unauthorized(headers={WWW-Authenticate: challenge})
Unauthorized->>Unauthorized: get_headers()
Unauthorized-->>Response: WWW-Authenticate header
Response-->>Security: 401 Unauthorized
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 #714 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 71 71
Lines 8981 9010 +29
=========================================
+ Hits 8981 9010 +29
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 4 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/errors/classes.py" line_range="125-127" />
<code_context>
+ description: str | None = None,
+ response: Any = None,
+ *,
+ headers: Mapping[str, Any] | Iterable[tuple[str, str]] | None = None,
+ www_authenticate: WWWAuthenticate | Iterable[WWWAuthenticate] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Create the error."""
</code_context>
<issue_to_address>
**Positional challenge argument breaks**
When an existing caller passes `www_authenticate` as the third positional argument, a caller using Werkzeug's previously accepted third positional `www_authenticate` argument now gets a `TypeError`, because the new `*` makes the deprecated argument keyword-only; that caller can no longer construct the error.
Preserve the positional argument during the deprecation period, or explicitly document this as a breaking change.
</issue_to_address>
### Comment 2
<location path="foca/errors/classes.py" line_range="136" />
<code_context>
+ self.headers.extend(_challenge_headers(www_authenticate))
+
+ @property
+ def www_authenticate(self) -> tuple[WWWAuthenticate, ...] | None:
+ """Deprecated: challenges of `headers`; read :py:meth:`get_headers`.
+
</code_context>
<issue_to_address>
**Legacy challenge reads change shape**
When existing code reads a single challenge from `exc.www_authenticate` and accesses it as a `WWWAuthenticate` object, a caller that previously read a single Werkzeug challenge as `exc.www_authenticate` and accessed its fields, such as `.type` or `.parameters`, now gets a tuple and raises `AttributeError`; the deprecated attribute therefore does not keep working for that usage.
Preserve the single-challenge return shape during deprecation, while providing a documented shape for multiple challenges.
</issue_to_address>
### Comment 3
<location path="foca/errors/classes.py" line_range="172-178" />
<code_context>
+ if "headers" not in vars(self):
+ return
+ _warn_www_authenticate()
+ self.headers = [
+ (name, header)
+ for name, header in self.headers
+ if name.lower() != _CHALLENGE_HEADER.lower()
+ ]
+ if value is not None:
+ self.headers.extend(_challenge_headers(value))
+
+ def get_headers(self, *args: Any, **kwargs: Any) -> list[tuple[str, str]]:
</code_context>
<issue_to_address>
**Failed replacement loses existing challenges**
When the setter receives an iterable that raises while being consumed, `_challenge_headers` raises after the setter has removed the existing `WWW-Authenticate` headers, so the assignment fails and the caller sees the old challenges gone.
Convert the new value with `_challenge_headers` before removing existing challenge headers, then replace them only after conversion succeeds.
</issue_to_address>
### Comment 4
<location path="foca/errors/classes.py" line_range="126" />
<code_context>
+ response: Any = None,
+ *,
+ headers: Mapping[str, Any] | Iterable[tuple[str, str]] | None = None,
+ www_authenticate: WWWAuthenticate | Iterable[WWWAuthenticate] | None = None,
+ **kwargs: Any,
+ ) -> None:
</code_context>
<issue_to_address>
**Supported strings fail type checks**
When a typed caller passes a plain challenge string, `www_authenticate` and `_challenge_headers` annotations exclude `str`, so the type checker rejects this supported form and callers need a suppression.
Include `str` in the annotations for the constructor argument, property setter, and `_challenge_headers` input.
Also at `foca/errors/classes.py:127`, `foca/errors/classes.py:161`, `foca/errors/classes.py:208`.
</issue_to_address>Linked issues
#710 refactor(errors): move the challenge to headers · 1 of 3 met · 2 to check by hand
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | cloud-registry no longer reads exc.www_authenticate | 👀 Check by hand (external system) | Check cloud-registry's current head to confirm it no longer reads exc.www_authenticate; that repository is not part of this diff. |
| 2 | Put the challenge in headers and deprecate the attribute, noting the change in upgrade docs | ✅ Met | FOCA's Unauthorized stores challenges in headers, deprecates www_authenticate, and documents the change in docs/migration-0.22.md. |
| 3 | proTES and cloud-registry heads pass with the change | 👀 Check by hand (runtime) | The PR reports passing downstream test runs, but a person must verify those runs against the relevant proTES and cloud-registry heads. |
Sourcery assessment
Approval pending. 3 findings to address first.
Blocking findings: foca/errors/classes.py:127, foca/errors/classes.py:136, foca/errors/classes.py:178
Address Sourcery findings: the deprecated setter replaces the challenges only once the new ones are built; type hints accept a string as a challenge. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
FOCA's 401 errors now carry the RFC 6750
WWW-Authenticatechallenge in the genericheadersoffoca.errors.Unauthorized, as #633 asked, instead of Werkzeug'swww_authenticate. cloud-registry no longer readsexc.www_authenticate(cloud-registry #370), so the move doesn't break it any more.foca.security.auth._unauthorized()setsheaders={"WWW-Authenticate": ...}, keeping the always-quoted Bearer form. FOCA's own invalid-token check (_has_invalid_token_challenge()) already readsget_headers(), so it works unchanged.www_authenticateonfoca.errors.Unauthorizedis deprecated but still works, with aDeprecationWarning:headers. A plain string counts as one challenge.WWW-Authenticateheaders, orNoneif there are none.Unauthorized.get_headers()no longer calls Werkzeug's challenge code, so challenges are sent once and the normal path never warns.docs/migration-0.22.mdhas a new section, "Challenges inheaders".docs/configuration/exceptions.mdnow usesheaders=and says how to read challenges.Raw Werkzeug
Unauthorized(www_authenticate=...)and Connexion'sOAuthProblembehave as before.Closes #710
Verification
Local runs, Python 3.13, FOCA from this branch:
coverage run -m pytestwith MongoDB 7.0 on port 12345: 4610 passed, 2 skipped. Coverage 100%.ruff check,ruff format --check,mypy(179 files),ast-grep scan,semgrep scan --config .semgrep --errorandmkdocs build --strict: all pass.uv pip install --no-deps -e), Helm chart dependencies built, andpytest -W ignore::DeprecationWarningas in their CI:dev(4e707a9): 2337 passed, 11 skipped.dev(e47cac2): 1613 passed, 11 skipped.CI passedwas green. After the Sourcery fixes (8de82c0), all 30 checks passed, with the same 3 intended skips;CI passedis green and no review threads are open.Automated reviews
Sourcery raised 4 findings:
www_authenticate: it matches Werkzeug's.Declined review findings
tests/errors/test_errors.py:260and:959toheaders=. Declined: that module imports Werkzeug's ownUnauthorized, so these cases cover the raw Werkzeug path, which must keep working. They raise no FOCA deprecation warning. Theheaders=path of FOCA's class is tested intests/errors/test_classes.py.classes.pyandauth.py. Declined: it would mean importing a private name across packages for two literals.Unauthorized.get_headerswith Werkzeug'senviron/scope. Declined: it keeps the*args, **kwargssignature ofHTTPError.get_headers.Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Move unauthorized authentication challenges to standard headers while preserving deprecated
www_authenticatecompatibility.Enhancements:
UnauthorizedRFC 6750 challenges into standard response headers and deprecate the legacywww_authenticateinterface while preserving compatibility.Documentation:
headers-based challenge handling and migration guidance.Tests: