Skip to content

refactor(api): check routes from specs - #707

Merged
uniqueg merged 4 commits into
devfrom
refactor/route-table
Nov 5, 2026
Merged

uniqueg merged 4 commits into
devfrom
refactor/route-table

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Closes #632

Summary

New foca.api.routes: a route table filled while APIs are registered, with get_routes() and match(path, method). _check_routes_enforced, the ownership wrappers, the service-info check, is_permitted_for, the check of me_path and the plugin adapter use it instead of Flask's url_map, view_functions and url_rule. Path semantics are defined once, in the module docstring and docs/utilities.md.

Design decisions

  • Recording: a subclass of Connexion's API class, installed in create_connexion_app(), rather than a recording resolver around register_openapi(). It covers every add_api() call, including FOCA's permissions and /me APIs and calls by apps, and failed resolutions. It is the only Connexion-2-specific place, plus reading operation._resolution (private), for the function the issue asks for; build: add support for Connexion 3+ #188 replaces this hook.
  • Matching: the table has its own Werkzeug Map, with Connexion's converters and the same OPTIONS handling per rule as Flask, so precedence, redirects and conversions stay identical. Werkzeug stays installed on Connexion 3 (refactor(errors): make errors framework-neutral #633); Flask's routes aren't used. A test compares the table's rules with Flask's.
  • Function: Route.function is the resolver's result, with FOCA's wrappers but without Connexion's; inspect.unwrap() and _ENFORCING_ATTRIBUTE work as before.

Behaviour differences on Connexion 2

Only routes that aren't operations (Swagger UI, openapi.json, routes added to Flask directly), which the table doesn't hold:

  • is_permitted_for() on such a path is now False, not True.
  • me_path on such a path is no longer refused or warned about.
  • An ownership controller routed through a plain Flask rule, not a specification, now refuses requests.
  • InboundRequest.route of the plugin adapter is the path for such requests.

An app that doesn't use create_connexion_app() gets the table from register_openapi() and the access control registrations; APIs it added earlier aren't in it, and ownership controllers on them refuse requests.

The ownership wrappers now also need policies to have allowed this very request (mark on flask.g), because the table can find an enforced route with the same path as a route outside it. Apps' tests calling ownership controllers directly in a request context would have to go through an enforced route; those of cloud-registry and proTES don't depend on this (see below).

Everything else is unchanged. Two existing tests that used plain Flask routes register them in the table now.

Verification

Local, Python 3.12:

  • coverage run -m pytest -m 'not mongodb', without the integration test files: 4201 passed, 3 skipped; foca/api/routes.py and the changed modules at 100%. Total 99%, from tests needing MongoDB; CI runs them.
  • ruff check, ruff format --check, mypy, ast-grep scan, mkdocs build --strict: passed.
  • Checks tested with url_map emptied, for an unenforced ownership route and a service-info route.

Heads of the apps, on this branch (Python 3.13, without chart tests, which need Helm dependencies): proTES 1393 passed, 11 skipped; cloud-registry 87 failed, 2020 passed, 11 skipped, with the same failures on dev of FOCA (chart overlay tests and others, not caused by this PR). MongoDB-backed tests of FOCA and the integration tests run only in CI.

CI: see the checks of this PR.

Declined review findings

  • Making _match_rule and _install_route_table public: internal across modules, as _register_api and others in this code base.
  • Adding Swagger UI and specification routes to the table: they serve no operation; the differences are listed above.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Replace framework route introspection with a specification-backed route table for consistent API route discovery, matching, and access-control checks.

New Features:

  • Add a route table API for discovering and matching routes defined by OpenAPI operations, including route metadata and converted path parameters.

Bug Fixes:

  • Make access-control, ownership, service-info, and plugin route handling independent of Flask's route map and view registry.
  • Prevent ownership controllers from accepting requests unless access-control policies explicitly enforced that request.

Enhancements:

  • Centralize route path semantics and matching behavior while preserving framework-compatible precedence, conversions, redirects, and automatic method handling.

Documentation:

  • Document the route discovery and matching API and clarify that non-operation routes are excluded from route-based access checks.

Tests:

  • Add coverage for route recording, matching, metadata, unresolved operations, framework parity, root paths, enforcement behavior, and operation checks without Flask routes.

Record the operations of registered APIs in a route table, with match()
for apps, and use it instead of Flask's routes for FOCA's route checks
and lookups, so that they don't pass vacuously when routes are built
lazily, as on Connexion 3.

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

Adds a Connexion registration hook that records specification operations in an independent route table, then refactors access-control and related integrations to resolve routes through that table rather than Flask internals, with documented semantics and comprehensive parity and regression tests.

Sequence diagram for recording and matching an API operation

sequenceDiagram
    participant App as Connexion app
    participant API as Recording API
    participant Table as FOCA route table
    participant Matcher as match()
    participant Caller as Access-control consumer

    App->>API: add_api()
    API->>API: _add_operation_internal()
    API->>Table: _add_route(Route)
    Caller->>Matcher: match(path, method)
    Matcher->>Table: Werkzeug rule matching
    Table-->>Matcher: RouteMatch(route, params)
    Matcher-->>Caller: RouteMatch or None
Loading

File-Level Changes

Change Details Files
Introduces a specification-derived route table and matching API independent of Flask's route registry.
  • Records resolved and unresolved Connexion operations during API registration, including methods, templates, converters, security, extensions, and wrapped functions.
  • Matches request paths with a dedicated Werkzeug map while preserving Connexion converters, precedence, redirects, HEAD, and automatic OPTIONS behavior.
  • Documents and publicly exposes route metadata and matching semantics.
foca/api/routes.py
foca/api/register_openapi.py
foca/factories/connexion_app.py
docs/utilities.md
docs/reference.md
docs/access-control.md
tests/api/test_routes.py
Migrates access-control, ownership, service-info, and plugin logic from Flask routing internals to the specification route table.
  • Uses recorded routes for enforcement checks, permission decisions, me-path validation, service-info discovery, ownership resource extraction, and plugin inbound route metadata.
  • Adds a per-request enforcement marker so ownership wrappers cannot accept enforcement from a different route with the same path.
  • Changes non-operation and plain-Flask route behavior to follow the documented route-table scope.
foca/security/access_control/enforcement.py
foca/security/access_control/ownership_server.py
foca/security/access_control/register_access_control.py
foca/api/service_info.py
foca/plugins/adapter.py
Expands tests to validate route recording, matching parity, integration behavior, and enforcement safety without relying on Flask's url_map.
  • Covers base paths, parameter conversion, redirects, root paths, HEAD/OPTIONS, unresolved operations, duplicate installation, and apps registered outside FOCA's factory.
  • Compares recorded rules with Flask and verifies checks continue to work when Flask routes are emptied.
  • Updates direct ownership and plain-route tests to use the route table and enforcement marker.
tests/api/test_routes.py
tests/plugins/test_plugin_adapter.py
tests/security/access_control/test_ownership_server.py
tests/security/access_control/test_path_helpers.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 (a9efcd6) to head (53303d5).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #707   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           66        67    +1     
  Lines         8599      8673   +74     
=========================================
+ Hits          8599      8673   +74     
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 2 commits November 5, 2026 11:15
Ownership wrappers also need policies to have run for the request, as a
route outside of the table can share a path with an enforced one. Install
the table in register_openapi() too, and drop what became unused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The app context can outlive a request, so keep the request itself.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg marked this pull request as ready for review November 5, 2026 10:52

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

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/api/register_openapi.py" line_range="467" />
<code_context>
             not a mapping, patches set fields of path items defined via
             `$ref`, or the specification is invalid after applying patches.
     """
+    _install_route_table(app)
+
     # Iterate over OpenAPI specs
</code_context>
<issue_to_address>
**Earlier API routes are missing**

When a plain Connexion `App` has an API registered before `register_openapi()` installs the table, `_install_route_table()` instruments only future `add_api()` calls, so `match()` finds no operation and the ownership wrapper raises `RuntimeError`, returning a 500 for requests to ownership controllers on those earlier routes.

Install the route recorder before any API registration, or backfill operations from APIs already registered when installing it.
</issue_to_address>

### Comment 2
<location path="foca/api/routes.py" line_range="87-90" />
<code_context>
+
+    routes: list[Route] = field(default_factory=list)
+    rules: Map = field(
+        default_factory=lambda: Map(
+            converters={"float": NumberConverter, "int": IntegerConverter}
+        )
+    )
+
</code_context>
<issue_to_address>
**Accepted slash paths are rejected**

When an app customizes Flask URL-map settings such as `strict_slashes=False`, `_RouteTable` builds its own `Map` with Werkzeug defaults, so `match()` can return no operation for a path Flask serves; ownership checks then reject the request or raise `RuntimeError`.

Initialize the route table with the Flask app’s URL-map settings.
</issue_to_address>

### Comment 3
<location path="foca/api/routes.py" line_range="100-104" />
<code_context>
+                itself, unless the operation is one, so that the order of the
+                rules for a path counts in the same way.
+        """
+        self.routes.append(route)
+        self.rules.add(
+            Rule(
+                route.rule,
+                endpoint=len(self.routes) - 1,
+                methods={route.method, "OPTIONS"},
+            )
</code_context>
<issue_to_address>
**Concurrent registrations return the wrong operation**

When two threads register APIs on the same app at the same time, `_RouteTable.add` appends a route and then derives its endpoint from the shared list length without synchronization, so both rules can point to the same route; `match()` then returns the wrong operation and path parameters.

Assign each rule an endpoint atomically with its route append.
</issue_to_address>

### Comment 4
<location path="foca/api/service_info.py" line_range="175" />
<code_context>
-        rule.rule
-        for rule in app.url_map.iter_rules()
-        if unwrap(app.view_functions[rule.endpoint]) is controller
+        route.rule for route in get_routes(app) if unwrap(route.function) is controller
     )

</code_context>
<issue_to_address>
**Direct service-info route escapes startup check**

When an app registers `getServiceInfo` with `Flask.add_url_rule()` instead of an API specification and omits service-info configuration, `_routes_to_controller` no longer finds a plain Flask route to `getServiceInfo`, so `check_service_info` treats the app as having no service-info endpoint and allows startup; requests to that route then fail with an internal server error because no service info is configured.

Preserve direct Flask-route detection for this startup validation while using the operation table for specification routes.
</issue_to_address>

### Comment 5
<location path="foca/security/access_control/enforcement.py" line_range="866-867" />
<code_context>
-    # Connexion's route for authenticating all paths (`auth_all_paths`) serves
-    # no operation, it only responds with `404`
-    if rule.rule.endswith(_CATCH_ALL_RULE_SUFFIX):
+    found = _match_rule(path, method)
+    if found is None:
         return False
-    if (method == "OPTIONS" and getattr(rule, "provide_automatic_options", False)) or (
</code_context>
<issue_to_address>
**Preserve Connexion 2 behavior**

The issue requires no behavior change on Connexion 2, but is_permitted_for() now matches against the operation table only. As the PR notes, paths served by non-operation routes can therefore receive different decisions than before.
</issue_to_address>

Linked issues

#632 refactor: check routes from specs, not url_map · 9 of 10 met

# Requirement Status Notes
1 Record each operation’s method, base-path path, operation ID, security, x-foca-* extensions, and resolved function. ✅ Met The recording API captures these fields, including the resolver’s function after FOCA wrappers.
2 Expose get_routes() and match(path, method), with path parameters. ✅ Met Both helpers are implemented; match() returns the matched route and converted parameters.
3 Use the route table for the route checks and lookups named in the issue. ✅ Met _check_routes_enforced, the ownership wrappers, and the service-info check use the table.
4 Define and document path semantics, including the API base path and app root path. ✅ Met The semantics are described in the module docstring and docs/utilities.md.
5 Provide and document match() as a helper for apps. ✅ Met docs/utilities.md documents how apps can call match() and inspect its result.
6 No behavior change on Connexion 2. 🟡 Partly met Operation routes use the new table, but the PR documents behavior changes for non-operation routes, including Swagger UI, served specifications, and routes added directly to Flask.
7 Remove url_map, view_functions, url_rule, and test_request_context from route checks or lookups in foca/. ✅ Met A search of foca/ found no remaining uses of these route lookup APIs.
8 Keep the startup checks failing in the same cases and test the ownership and service-info cases. ✅ Met The new tests cover an unenforced ownership route; the existing service-info endpoint test verifies startup fails when that route is served without service-info configuration.
9 Test that the checks do not depend on Flask routes having been built. ✅ Met Tests empty Flask’s url_map before checking an ownership route and a service-info route.
10 Test match() with base paths, path parameters, and an app root path. ✅ Met The route tests cover base paths, typed parameters, and SCRIPT_NAME.

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and access-control decisions now depend on a specification-built route table rather than Flask’s live routing table; if it matches a request to the wrong operation, a protected route could be treated as public and expose data or allow unauthorized changes. Reverting prevents future decisions based on that table, but cannot undo access or changes that already occurred.

Blocking findings: foca/api/register_openapi.py:467, foca/api/routes.py:90, foca/api/routes.py:104, foca/api/service_info.py:175, foca/security/access_control/enforcement.py:867


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

Comment thread foca/api/register_openapi.py Resolved
Comment thread foca/api/routes.py Resolved
Comment thread foca/api/routes.py Resolved
Comment thread foca/api/service_info.py Resolved
@uniqueg
uniqueg merged commit 240ec95 into dev Nov 5, 2026
57 checks passed
@uniqueg
uniqueg deleted the refactor/route-table branch November 5, 2026 11:15
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: check routes from specs, not url_map

1 participant