Repository navigation
refactor(errors): make errors framework-neutral - #709
Conversation
Add exception classes and stable names of Connexion's problems to foca.errors, raise them in FOCA, and split the problem core off from the Connexion 2 adapter. Warn of raw Werkzeug classes in exception maps. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideRefactors FOCA error handling around framework-neutral HTTP classes and problem-detail logic, keeps Connexion 2 as an adapter, updates all raises, mappings, examples, and documentation, and adds compatibility and migration coverage for a future ASGI implementation. Sequence diagram for framework-neutral error response handlingsequenceDiagram
participant App as FOCA application
participant Problems as foca.errors.problems
participant Adapter as Connexion 2 adapter
participant Flask as Flask response
App->>Problems: build_problem(exc, conf)
Problems->>Problems: build_headers(exc, status)
Problems-->>Adapter: problem details and headers
Adapter->>Flask: problem_response(exc, conf)
Flask-->>App: JSON problem response
Flow diagram for exception mapping compatibilityflowchart TD
Map[Exception map key] --> Check{foca.errors class or counterpart?}
Check -->|Yes| Resolve[Resolve one shared problem mapping]
Check -->|Raw Werkzeug class| Warn[Warn once when handler is registered]
Warn --> Resolve
Resolve --> Response[Build problem response]
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 #709 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 67 70 +3
Lines 8673 8731 +58
=========================================
+ Hits 8673 8731 +58
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:
|
Keep several values of headers, let specific classes win over the bases of all HTTP errors, and treat raw 401 errors of token validation as before. Fix docstrings and document keyword arguments. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Apps may raise Werkzeug's NotFound from existence checks, so keep skipping the owner restore for it. Also document that base classes of exception mappings come last, and fix docstrings. Co-Authored-By: Claude Opus 5.5 <[email protected]>
cloud-registry reads the challenge from this attribute to tell invalid tokens from other rejections, so keep setting it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Hey - I've found 6 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="58" />
<code_context>
CLIENT_CLAIMS = ("client_id", "azp")
+# Error code in the challenge of an invalid token, quoted or not
+_INVALID_TOKEN_ERROR = re.compile(r'\berror="?invalid_token"?')
+
# Description of the `invalid_token` error of `WWW-Authenticate` challenges,
</code_context>
<issue_to_address>
**Optional auth rejects unrelated challenges**
When a 401 challenge contains `error=invalid_token` in another parameter, uses a different scheme, or has an error value beginning with `invalid_token`, `_INVALID_TOKEN_ERROR.search` scans the rendered header and matches those cases, so `_reject_invalid_token` re-raises the `Unauthorized` instead of continuing anonymously; optional-auth requests receive a 401.
Parse the Bearer challenge and re-raise only when its `error` parameter is exactly `invalid_token`.
Also at `foca/security/auth.py:257`.
</issue_to_address>
### Comment 2
<location path="foca/errors/exceptions.py" line_range="79" />
<code_context>
+ """
+ for cls in conf.problems:
+ if (
+ cls.__module__ == "werkzeug.exceptions"
+ and cls is not AccessDeniedProblem
+ and cls not in _warned_mappings
</code_context>
<issue_to_address>
**Subclass mappings miss migration warnings**
When an exception map contains an app-defined subclass of a Werkzeug HTTP exception, `_warn_werkzeug_mappings` checks only `cls.__module__`, so it skips the warning for the subclass; when raw Werkzeug mappings stop working on ASGI, the configured mapping is lost and callers receive fallback problem details.
Detect Werkzeug HTTP exception subclasses through their base classes and warn for those mappings.
</issue_to_address>
### Comment 3
<location path="foca/security/auth.py" line_range="27" />
<code_context>
from werkzeug.http import quote_header_value
from foca.config.access import get_app_config, get_config
+from foca.errors import Unauthorized
from foca.models.config import (
NAMESPACE_SEPARATOR,
</code_context>
<issue_to_address>
**Put challenge in headers**
The issue asks for the RFC 6750 challenge to go in `headers`. The token error now uses `foca.errors.Unauthorized`, but `_unauthorized` still supplies the challenge via Werkzeug’s `www_authenticate` keyword, leaving this path dependent on a Werkzeug-specific constructor argument.
</issue_to_address>
### Comment 4
<location path="foca/errors/exceptions.py" line_range="79-83" />
<code_context>
+ """
+ for cls in conf.problems:
+ if (
+ cls.__module__ == "werkzeug.exceptions"
+ and cls is not AccessDeniedProblem
+ and cls not in _warned_mappings
+ ):
+ _warned_mappings.add(cls)
+ logger.warning(
+ "Exception map uses 'werkzeug.exceptions.%s', which stops working "
</code_context>
<issue_to_address>
**Concurrent registrations duplicate warnings**
When two threads register handlers with the same raw Werkzeug class at the same time, both calls can pass the membership check before either adds the class, so both log the warning and operators see duplicate deprecation messages.
Make the membership check and set insertion atomic, for example by protecting them with a lock.
</issue_to_address>
### Comment 5
<location path="tests/errors/test_classes.py" line_range="68" />
<code_context>
+def test_exports() -> None:
+ """All classes and aliases are exported."""
+ for name in foca.errors.__all__:
+ assert hasattr(foca.errors, name)
+
+
</code_context>
<issue_to_address>
**Missing exports pass unnoticed**
When a promised error class is accidentally removed from both the package exports and `__all__`, `test_exports` iterates only over the current `__all__` at line 67, so removing a promised class from both the package imports and `__all__` makes the loop empty and the test pass; callers then cannot import that class from `foca.errors`.
Assert that `__all__` contains the expected public names before checking their attributes.
</issue_to_address>
### Comment 6
<location path="tests/errors/test_classes.py" line_range="247-248" />
<code_context>
+ } | {
+ (node.module or "").split(".")[0]
+ for node in ast.walk(tree)
+ if isinstance(node, ast.ImportFrom)
+ }
+ assert "flask" not in names
+
+
+def test_no_raw_raises() -> None:
+ """FOCA's own code imports no Werkzeug or Connexion exceptions to raise them."""
+ root = Path(foca.errors.__file__ or "").parents[1]
+ allowed = {"errors/classes.py", "errors/problems.py", "errors/exceptions.py"}
+ for path in root.rglob("*.py"):
+ if str(path.relative_to(root)) in allowed:
+ continue
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ imported = {
+ alias.asname or alias.name
+ for node in ast.walk(tree)
+ if isinstance(node, ast.ImportFrom)
+ and node.module in ("werkzeug.exceptions", "connexion.exceptions")
+ for alias in node.names
+ }
</code_context>
<issue_to_address>
**Module-style raw raises evade guard**
When FOCA code imports exceptions through a module alias and raises one using that alias, `test_no_raw_raises` collects only `ast.ImportFrom` names at lines 244-250; with `import werkzeug.exceptions as wz; raise wz.BadRequest()`, the import is ignored and the raised attribute has no `id` at line 252, so the test passes despite a raw Werkzeug raise.
Handle module imports and attribute-qualified exception names when collecting imports and raises.
</issue_to_address>Linked issues
#633 refactor(errors): make errors framework-neutral · 7 of 8 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Export the specified HTTP error classes and stable Connexion problem names from foca.errors, with code, description and optional headers. |
✅ Met | foca.errors exports the requested classes and aliases; the HTTP classes inherit the shared implementation of those attributes. |
| 2 | Have FOCA raise foca.errors classes, with the RFC 6750 challenge in headers. |
🟡 Partly met | FOCA now uses foca.errors.Unauthorized, but the token challenge is still passed as www_authenticate=, not through headers. |
| 3 | Separate framework-independent problem and header handling from the Connexion 2 Flask adapter, keeping the validation logger name in the adapter. | ✅ Met | The core is in foca/errors/problems.py; the Flask responses and validation logger filtering remain in foca/errors/exceptions.py. |
| 4 | Treat a foca.errors class and its Werkzeug counterpart as one exception-map entry, including framework-generated 404s. |
✅ Met | The counterpart resolution handles mappings in both directions, and the tests cover both classes. |
| 5 | Keep raw Werkzeug mappings working temporarily, warn once per exception class, and document the transition. | ✅ Met | Registration warns for raw Werkzeug mapping keys, with the documented Forbidden exception, and the configuration and migration docs describe the change. |
| 6 | Document the exported classes and aliases in the API reference and exception configuration docs, with an example map using only foca.errors names. |
✅ Met | The reference and configuration docs describe the new names and show a map using them. |
| 7 | Keep response behavior unchanged, including headers and validation details. | ✅ Met | The Connexion 2 adapter retains response handling, and the supplied verification reports the existing error tests passing unchanged. |
| 8 | Test that a foca.errors class and its Werkzeug base map to the same problem. |
✅ Met | The new tests check this both with and without an explicit mapping. |
Sourcery assessment
Needs a human reviewer. 5 findings to address first, and invalid-token handling now detects the invalid_token challenge by searching serialized WWW-Authenticate headers; if that check misses a challenge, an optional-token request may continue as unauthenticated instead of rejecting the invalid credential. Reverting restores the old check, but any access granted while the new behavior is live cannot be undone.
Blocking findings: foca/security/auth.py:58, foca/errors/exceptions.py:79, foca/security/auth.py:27, tests/errors/test_classes.py:68, tests/errors/test_classes.py:248
Only a Bearer challenge with the exact error code invalid_token rejects a request on optional auth. Also pin the public names of foca.errors in the export test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes #633
Summary
foca.errorsexportsHTTPError,BadRequest,Unauthorized,Forbidden,NotFound,MethodNotAllowed,Conflict,PayloadTooLarge,UnprocessableContent,InternalServerError,ServiceUnavailable, and the stable namesRequestValidationProblem,ExtraParameterProblem,AuthenticationProblem,AccessDeniedProblem. The classes subclass their Werkzeug counterparts and takeheaders; the names are aliases of Connexion 2's classes.auth.pystays inwww_authenticate, which apps read.foca/errors/problems.pyhas status, problem and header logic on plain data, without Flask.foca/errors/exceptions.pystays as the Connexion 2 adapter, with Flask responses, handlers and the name of Connexion's validation logger. Its public names keep working.foca.errorsand its Werkzeug base count as one in exception maps, in both directions, also for Werkzeug's own404of unknown routes. Raw Werkzeug classes in maps log a warning, once per class.docs/configuration/exceptions.md, the API reference, a newdocs/migration-0.22.md, and the examples use onlyfoca.errorsnames.Notes
AccessDeniedProblemiswerkzeug.exceptions.Forbiddenon Connexion 2, so mapping rawwerkzeug.exceptions.Forbiddendoesn't warn: the two can't be told apart.Unauthorized.www_authenticatestays set on FOCA's token errors, because cloud-registry reads it.PayloadTooLargeforRequestEntityTooLarge). Responses don't change.Verification
Local, Python 3.12:
coverage run -m pytest -m 'not mongodb', without the integration test files: 4275 passed, 3 skipped;foca/errors/*andfoca/security/auth.pyat 100%. Total 99%, from tests needing MongoDB; CI runs them. Existing error tests are unchanged.ruff check,ruff format --check,mypy,ast-grep scan,mkdocs build --strict: passed.App heads on this branch, Python 3.13, without
tests/test_chart.pyandtests/test_config_examples.py:dev(full run one commit before the last; on the final commit, the public read tests pass: 11).CI: all checks passed on 2b6de8c.
Declined review findings
Forbiddenin maps: it is the same class asAccessDeniedProblemon Connexion 2; documented.headersas the issue asks:www_authenticatekept, because cloud-registry reads it; moving needs the app to change first.exceptions.py: kept for existing tests.Open questions
None.
🤖 Generated with Claude Code