Skip to content

refactor(errors): make errors framework-neutral - #709

Merged
uniqueg merged 5 commits into
devfrom
refactor/neutral-errors
Nov 5, 2026
Merged

uniqueg merged 5 commits into
devfrom
refactor/neutral-errors

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Closes #633

Summary

  • foca.errors exports HTTPError, BadRequest, Unauthorized, Forbidden, NotFound, MethodNotAllowed, Conflict, PayloadTooLarge, UnprocessableContent, InternalServerError, ServiceUnavailable, and the stable names RequestValidationProblem, ExtraParameterProblem, AuthenticationProblem, AccessDeniedProblem. The classes subclass their Werkzeug counterparts and take headers; the names are aliases of Connexion 2's classes.
  • FOCA raises them everywhere; the Bearer challenge of auth.py stays in www_authenticate, which apps read.
  • Core and adapter: foca/errors/problems.py has status, problem and header logic on plain data, without Flask. foca/errors/exceptions.py stays as the Connexion 2 adapter, with Flask responses, handlers and the name of Connexion's validation logger. Its public names keep working.
  • Mappings: a class of foca.errors and its Werkzeug base count as one in exception maps, in both directions, also for Werkzeug's own 404 of unknown routes. Raw Werkzeug classes in maps log a warning, once per class.
  • Docs: docs/configuration/exceptions.md, the API reference, a new docs/migration-0.22.md, and the examples use only foca.errors names.

Notes

  • AccessDeniedProblem is werkzeug.exceptions.Forbidden on Connexion 2, so mapping raw werkzeug.exceptions.Forbidden doesn't warn: the two can't be told apart.
  • The warning is checked when the handler is registered, on keys of the map, not on raised exceptions, since Flask itself raises raw Werkzeug classes.
  • Unauthorized.www_authenticate stays set on FOCA's token errors, because cloud-registry reads it.
  • In a log line of an exception, the name can differ (PayloadTooLarge for RequestEntityTooLarge). 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/* and foca/security/auth.py at 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.py and tests/test_config_examples.py:

  • cloud-registry: 87 failed, 2020 passed, 11 skipped; the failures are identical to those on FOCA dev (full run one commit before the last; on the final commit, the public read tests pass: 11).
  • proTES: 1393 passed, 11 skipped on the final commit.

CI: all checks passed on 2b6de8c.

Declined review findings

  • Positional Werkzeug arguments of the new classes: documented as keywords.
  • No warning for raw Forbidden in maps: it is the same class as AccessDeniedProblem on Connexion 2; documented.
  • Sourcery: challenge in headers as the issue asks: www_authenticate kept, because cloud-registry reads it; moving needs the app to change first.
  • Sourcery: warnings for app subclasses of Werkzeug classes, a lock around the warning, module-style imports in the guard test: see the threads.
  • AST guard tests and private re-exports in exceptions.py: kept for existing tests.

Open questions

None.

🤖 Generated with Claude Code

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]>
@uniqueg uniqueg added this to the v0.22.0 milestone Nov 5, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Refactors 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 handling

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

Flow diagram for exception mapping compatibility

flowchart 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]
Loading

File-Level Changes

Change Details Files
Introduces framework-neutral HTTP error classes and stable Connexion problem aliases as the application-facing error API.
  • Exports standard HTTP errors with keyword-only header support while retaining Werkzeug compatibility.
  • Adds stable aliases for validation, extra-parameter, authentication, and access-denied problems.
  • Moves error/problem behavior into framework-independent modules and retains Flask/Connexion handling in the adapter.
foca/errors/__init__.py
foca/errors/classes.py
foca/errors/problems.py
foca/errors/exceptions.py
Updates FOCA internals and authentication handling to consistently raise the new error types without changing response semantics.
  • Replaces direct Werkzeug and Connexion exception raises across validation, APIs, access control, pagination, factories, and plugins.
  • Preserves Bearer challenges and recognizes raw Werkzeug unauthorized errors during token validation.
  • Keeps framework-generated and application-raised HTTP errors interoperable.
foca/api/service_info.py
foca/api/validation.py
foca/factories/connexion_app.py
foca/plugins/adapter.py
foca/security/access_control/access_control_server.py
foca/security/access_control/enforcement.py
foca/security/access_control/ownership.py
foca/security/access_control/ownership_server.py
foca/security/auth.py
foca/utils/pagination.py
Extends exception mapping to treat FOCA errors and their Werkzeug counterparts equivalently and warns about framework-specific mappings.
  • Resolves mapped FOCA/Werkzeug counterpart classes in both directions, including framework-generated not-found errors.
  • Ensures HTTP base-class mappings do not override specific mappings.
  • Warns once when raw Werkzeug classes appear as map keys, while preserving the Connexion 2 Forbidden alias exception.
foca/errors/problems.py
foca/errors/exceptions.py
Migrates examples and documentation to the framework-neutral error API and documents the ASGI migration path.
  • Replaces Werkzeug and Connexion names in configuration guidance, examples, API references, and internal documentation.
  • Adds 0.22 migration guidance covering replacements, headers, keyword-only arguments, and mapping warnings.
  • Updates navigation, changelog, and README migration links.
README.md
docs/access-control.md
docs/changelog.md
docs/configuration/exceptions.md
docs/configuration/service-info.md
docs/index.md
docs/migration-0.22.md
docs/reference.md
examples/petstore-access-control/exceptions.py
examples/petstore/exceptions.py
mkdocs.yml
Adds focused coverage for exports, framework independence, counterpart mappings, headers, warnings, and authentication edge cases.
  • Tests stable aliases, standard attributes, custom headers, filtered body headers, and Bearer challenge defaults.
  • Verifies mapping symmetry, base-class precedence, raw Werkzeug warnings, and absence of Flask imports in the core.
  • Covers raw not-found and unauthorized behavior in access-control and token-validation paths.
tests/errors/test_classes.py
tests/security/access_control/test_ownership_server.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 (240ec95) to head (2b6de8c).
⚠️ Report is 1 commits behind head on dev.

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     
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 and others added 3 commits November 5, 2026 12:45
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]>
@uniqueg
uniqueg marked this pull request as ready for review November 5, 2026 12:10

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


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
Comment thread foca/security/auth.py Resolved
Comment thread foca/errors/exceptions.py Resolved
Comment thread tests/errors/test_classes.py Resolved
Comment thread tests/errors/test_classes.py Resolved
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]>
@uniqueg
uniqueg merged commit eb77558 into dev Nov 5, 2026
58 checks passed
@uniqueg
uniqueg deleted the refactor/neutral-errors branch November 5, 2026 12:38
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.

refactor(errors): make errors framework-neutral

1 participant