Skip to content

refactor(errors): move the challenge to headers - #714

Merged
uniqueg merged 4 commits into
devfrom
refactor/710-challenge-in-headers
Nov 5, 2026
Merged

uniqueg merged 4 commits into
devfrom
refactor/710-challenge-in-headers

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Summary

FOCA's 401 errors now carry the RFC 6750 WWW-Authenticate challenge in the generic headers of foca.errors.Unauthorized, as #633 asked, instead of Werkzeug's www_authenticate. cloud-registry no longer reads exc.www_authenticate (cloud-registry #370), so the move doesn't break it any more.

  • foca.security.auth._unauthorized() sets headers={"WWW-Authenticate": ...}, keeping the always-quoted Bearer form. FOCA's own invalid-token check (_has_invalid_token_challenge()) already reads get_headers(), so it works unchanged.
  • www_authenticate on foca.errors.Unauthorized is deprecated but still works, with a DeprecationWarning:
    • The argument adds its challenges to headers. A plain string counts as one challenge.
    • The attribute returns parsed copies of the WWW-Authenticate headers, or None if there are none.
    • Setting the attribute replaces those headers.
  • Unauthorized.get_headers() no longer calls Werkzeug's challenge code, so challenges are sent once and the normal path never warns.
  • Docs: docs/migration-0.22.md has a new section, "Challenges in headers". docs/configuration/exceptions.md now uses headers= and says how to read challenges.

Raw Werkzeug Unauthorized(www_authenticate=...) and Connexion's OAuthProblem behave as before.

Closes #710

Verification

Local runs, Python 3.13, FOCA from this branch:

  • coverage run -m pytest with 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 --error and mkdocs build --strict: all pass.
  • Downstream heads, with FOCA from this branch installed into their locked venvs (uv pip install --no-deps -e), Helm chart dependencies built, and pytest -W ignore::DeprecationWarning as in their CI:
    • cloud-registry dev (4e707a9): 2337 passed, 11 skipped.
    • proTES dev (e47cac2): 1613 passed, 11 skipped.
  • CI: the draft run passed all 29 checks, with 3 intended skips (image push, publish, Trivy upload), and the gate CI passed was green. After the Sourcery fixes (8de82c0), all 30 checks passed, with the same 3 intended skips; CI passed is green and no review threads are open.

Automated reviews

Sourcery raised 4 findings:

  • Fixed: the deprecated setter now keeps the old challenges if building the new ones fails, and the type hints accept a string as a challenge.
  • Answered and resolved:

Declined review findings

  • Quality, medium: switch tests/errors/test_errors.py:260 and :959 to headers=. Declined: that module imports Werkzeug's own Unauthorized, so these cases cover the raw Werkzeug path, which must keep working. They raise no FOCA deprecation warning. The headers= path of FOCA's class is tested in tests/errors/test_classes.py.
  • Quality, low: share one header-name constant between classes.py and auth.py. Declined: it would mean importing a private name across packages for two literals.
  • Quality, low: type Unauthorized.get_headers with Werkzeug's environ/scope. Declined: it keeps the *args, **kwargs signature of HTTPError.get_headers.
  • Adversarial, low: keep the original quoting when the deprecated attribute is read and written back. Declined: this is a deprecated round trip. The docs now say the attribute returns copies.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Move unauthorized authentication challenges to standard headers while preserving deprecated www_authenticate compatibility.

Enhancements:

  • Move Unauthorized RFC 6750 challenges into standard response headers and deprecate the legacy www_authenticate interface while preserving compatibility.

Documentation:

  • Document the new headers-based challenge handling and migration guidance.

Tests:

  • Add coverage for challenge header handling, deprecated compatibility behavior, and authentication challenge detection.

uniqueg and others added 2 commits November 5, 2026 19:52
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]>
@uniqueg uniqueg added this to the v0.22.0 milestone Nov 5, 2026
@uniqueg uniqueg added the priority: low Low priority label Nov 5, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Refactors FOCA's Unauthorized implementation to store RFC 6750 authentication challenges in generic headers, with comprehensive deprecated compatibility for Werkzeug's www_authenticate API. Security generation, documentation, and tests are updated while raw Werkzeug and Connexion behavior remains unchanged.

Sequence diagram for FOCA unauthorized challenge headers

sequenceDiagram
    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
Loading

File-Level Changes

Change Details Files
Move FOCA Unauthorized challenges into ordinary response headers while preserving deprecated Werkzeug-compatible access.
  • Add explicit construction, parsing, replacement, and deprecation behavior for www_authenticate.
  • Override header generation to avoid duplicate challenge emission and warnings on the normal path.
  • Keep raw Werkzeug and Connexion exception behavior unchanged.
foca/errors/classes.py
Emit Bearer authentication challenges directly through the generic headers API.
  • Serialize the Bearer challenge into a WWW-Authenticate header.
  • Retain invalid-token challenge detection through existing header-based logic.
foca/security/auth.py
Document the migration to header-based authentication challenges.
  • Update exception configuration examples to use headers.
  • Describe deprecated compatibility behavior and how to read challenges.
  • Document one challenge per repeated WWW-Authenticate header.
docs/configuration/exceptions.md
docs/migration-0.22.md
Expand coverage for challenge storage, compatibility, warning behavior, and authentication integration.
  • Test deprecated constructor and attribute paths, including strings, multiple challenges, parsing, replacement, and removal.
  • Verify headers are emitted once and header-based construction does not warn.
  • Verify security-generated challenges and invalid-token detection use headers.
tests/errors/test_classes.py
tests/security/test_optional_tokens.py

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

@codecov

codecov Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Codecov Report

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

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     
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 5, 2026 19:35

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/errors/classes.py Resolved
Comment thread foca/errors/classes.py Resolved
Comment thread foca/errors/classes.py Resolved
Comment thread foca/errors/classes.py Resolved
uniqueg and others added 2 commits November 5, 2026 20:43
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]>
@uniqueg
uniqueg merged commit 642ef74 into dev Nov 5, 2026
55 of 56 checks passed
@uniqueg
uniqueg deleted the refactor/710-challenge-in-headers branch November 5, 2026 20:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority: low Low priority

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor(errors): move the challenge to headers

1 participant