Skip to content

refactor(utils): read the request via accessors - #726

Merged
uniqueg merged 5 commits into
devfrom
refactor/718-request-accessors
Nov 6, 2026
Merged

uniqueg merged 5 commits into
devfrom
refactor/718-request-accessors

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Summary

FOCA no longer reads the request from flask.request, request_ctx or connexion.request outside foca.context. The one exception is the body-size limit, as decided in #718. Implements the maintainer's decisions:

  1. query in the snapshot: RequestSnapshot.query is a read-only QueryParams mapping of the raw query. Names are case-sensitive, a name gives its first value, and getlist() gives all values. Values are decoded as by Werkzeug: + as space, blank values kept, and bytes that aren't UTF-8 left percent-encoded instead of raising. The representation shows names only, so tokens in queries aren't logged. The plugin adapter's parser moved into foca.context, and the adapter now reads request.query.
  2. operation_id in the snapshot, base path from FOCA's registry:
    • RequestSnapshot.operation_id is the operationId of the specification, or the resolved one if the spec has none. Route.operation_id (route table, unreleased) has the same meaning, so x-openapi-router-controller specs give findPets, not controllers.findPets.
    • get_operation_id(), used for the log field operation_id and for logs of nonconforming responses, reads it from the route table instead of request.endpoint.
    • get_api_base_path() / get_resource_path() find the API of a request from FOCA's registry of APIs (_RegisteredApi) instead of Flask blueprints. Each route records the base path of its API (Route.base_path), and the API of a request is the registered API with that base path. Routes of unregistered APIs, e.g., GET /me, fall back as before.
  3. Body-size limit exempt: _check_body_size() (rewrites wsgi.input) imports Flask's request locally. Its docstring, docs/configuration/server.md and the migration guide document it as middleware and the one place that touches raw input, which moves to ASGI middleware later.

Other changes:

  • Logging: RequestSnapshot.protocol (e.g., HTTP/1.1) keeps the log_traffic request line unchanged.
  • Also switched: get_public_url() (root_path), pagination links (query, path) and the strict-validation check for unexpected query parameters (query).
  • Cost on hot paths: the private helpers _match_request() / _get_operation_id() read only the route, e.g., for each log record, without copying headers or parsing the query.
  • Regression test: the AST check (moved to tests/test_framework_neutral.py) now covers all of foca/ except foca/context.py. It exempts only _check_body_size, with a test that the exemption isn't stale, and also forbids flask.ctx.

Behaviour changes, in the migration guide

  • Log field operation_id: for router-controller specs it is now the bare operationId; before, it was e.g. controllers_findPets. It is empty for routes that aren't Connexion operations, e.g., Flask routes, the Swagger UI or automatic OPTIONS, and in Connexion apps not created by FOCA.
  • Base path for non-operation routes: requests to routes that aren't operations, e.g., an API's Swagger UI, fall back as requests outside the APIs do.
  • Non-UTF-8 query strings: they no longer cause a 500 in pagination links or in the extra-parameter check.

Docs:

  • docs/utilities.md: the snapshot fields and root_path in get_public_url().
  • docs/writing-controllers.md: what query is for.
  • docs/configuration/log.md: the operation_id field.
  • docs/access-control.md: how the API of a request is found.
  • docs/configuration/server.md: the body-size limit as middleware.
  • docs/migration-0.22.md: new replacement rows (SERVER_PROTOCOL, args, endpoint, blueprint) and the list of behaviour changes.

Closes #718

Verification

  • coverage run -m pytest with a private MongoDB 7.0 (--nounixsocket, port 12345), at c3e77b3: 4794 passed, 2 skipped, 100% coverage.
  • ruff check, ruff format --check, mypy, ast-grep scan, ast-grep test, semgrep scan --config .semgrep --error and mkdocs build --strict: pass. pre-commit can't fetch its hook repos through the sandbox proxy, so I ran the tools directly and rely on CI's pre-commit job.
  • Downstream, with this branch installed (editable, --no-deps) over their locked environments (uv sync --locked --extra dev), with helm dependency build deployment using Helm 3.22.1, and run with -W ignore::DeprecationWarning as in their CI:
    • proTES dev (d237a18): mongomock with coverage, at c3e77b3: 1615 passed, 11 skipped, 100% coverage. Against MongoDB 7.0, at cec4547: 1625 passed, 1 skipped.
    • cloud-registry dev (31c7b8f): mongomock with coverage, at c3e77b3: 2338 passed, 11 skipped, 100% coverage. Against MongoDB 7.0, at cec4547: 2349 passed.
    • Neither repo uses Route.operation_id, get_operation_id, RequestSnapshot or the moved adapter internals (checked by the reviewer).
  • CI: all checks passed on c3e77b3 (CI passed). Sourcery: 3 threads; the base-path one fixed in c3e77b3, the other two answered; all resolved.

Declined review findings

  • Make _has_request() public: private helpers shared across modules are the codebase's convention, e.g., _get_request_key() and _get_token_info(), and a public API should wait for the ASGI design.
  • Cache the snapshot per request: snapshots must reflect the request when retaken (tested). The route-only helpers cover the hot path. Pagination takes two snapshots per call, which is negligible.
  • Migration note for the new RequestSnapshot fields: the class is new in the unreleased 0.22.0.
  • Flag getattr(flask, "request") in the AST check: that's deliberate obfuscation, which the check isn't meant to stop. flask.ctx was added.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 4 commits November 6, 2026 15:49
The request snapshot gains `query` (read-only `QueryParams`, decoded as
by Werkzeug, invalid UTF-8 kept percent-encoded), `operation_id` (as in
the specification, else as resolved) and `protocol`. URLs, logging,
pagination, validation and response-validation errors read the request
via `current_request()`; the base path of the API handling a request
comes from FOCA's registry of APIs instead of Flask blueprints. The
plugin adapter takes the query from the snapshot.

The body-size limit stays the one function reading Flask's request, as
middleware rewriting `wsgi.input`. The AST check now covers all of
`foca/` except `foca.context`, with that function exempt.

Refs #718

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Document the new snapshot fields (`protocol`, `query`, `operation_id`),
how the base path of a request's API is found, the `operation_id` log
field, the body-size limit as the one place reading raw input, and the
replacements and behaviour changes in the 0.22 migration guide.

Refs #718

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Read the operation and route of a request without a whole snapshot
(`_match_request()`, `_get_operation_id()` in `foca.context`), so log
records don't copy headers or parse the query; use `_has_request()`
throughout `foca.context`; simplify the operation ID fallback of
routes; also forbid `flask.ctx` in the AST check; keep log records via
the resolver in the logging test; fix doc wrapping and the paragraph
split in the migration guide; clarify the `operation_id` log field.

Refs #718

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Test `_match_request()` and `_get_operation_id()` outside requests, for
unmatched paths and for operations; say in the log docs that
`operation_id` is set for all APIs added via Connexion.

Refs #718

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.22.0 milestone Nov 6, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Record the API base path and the specification-facing operation identifier on each route so request lookups can rely on route metadata.

  • foca/api/routes.py L173-176 (+4 small edits)

Define the read-only multi-value query mapping and extend the request snapshot with query, protocol, and operation metadata.

  • foca/context.py L75-128, L141-159, L164-199 (+7 small edits)

API

Expose the current request's route-derived operation identifier and use route metadata to resolve the API base path for request-scoped URL helpers.

  • foca/utils/urls.py L338-343, L463-481 (+2 small edits)

Uses of the API

Replace direct framework request reads with FOCA accessors in validation, plugin adaptation, logging, pagination, response-validation logging, and URL construction, while keeping the body-size middleware exception explicit.

  • foca/api/validation.py L39 (removed lines), L41, L456
  • foca/context.py L34-57, L268-281, L321-358 (+7 small edits)
  • foca/errors/exceptions.py L14, L19, L392
  • foca/factories/connexion_app.py L10, L127-131, L138-140
  • foca/plugins/adapter.py L11-128 (5 small edits)
  • foca/utils/logging.py L189-192 (+3 small edits)
  • foca/utils/pagination.py L12, L125-130
  • foca/utils/urls.py L24-332 (6 small edits)

Documentation

Document the new request snapshot fields, query semantics, operation identifiers, API lookup behavior, middleware exception, and migration guidance.

  • docs/access-control.md L506-515
  • docs/configuration/log.md L68, L103
  • docs/configuration/server.md L44-48
  • docs/migration-0.22.md L105-108, L117-148
  • docs/utilities.md L210-214, L225-235 (+3 small edits)
  • docs/writing-controllers.md L86-88

Tests

Cover route metadata, request snapshot semantics, API selection, logging behavior, and the framework-neutral request-access rule.

  • tests/api/test_routes.py L54-68, L157-166 (+2 small edits)
  • tests/errors/test_errors.py L41, L581-582
  • tests/security/access_control/test_path_helpers.py L41-46, L548-582
  • tests/test_context.py L445-498, L540-574 (+7 small edits)
  • tests/utils/test_logging_context.py L37-88, L140-145, L194-206 (+3 small edits)
  • tests/plugins/test_plugin_adapter.py L3 (removed lines), L181 (removed lines)

Other changes

Files not grouped.

  • tests/security/test_framework_neutral.py L12-22, L70-88, L128-151 (+5 small edits)

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 6, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #726   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           71        71           
  Lines         9127      9141   +14     
=========================================
+ Hits          9127      9141   +14     
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 6, 2026 16:09

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

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

## Individual Comments

### Comment 1
<location path="foca/utils/urls.py" line_range="488" />
<code_context>
+    owners = [
+        api for api in candidates if found.route.operation_id in api.operation_ids
+    ]
+    return max((api.base_path for api in owners or candidates), key=len, default=None)
+
+
</code_context>
<issue_to_address>
**Resource checks use wrong API path**

When nested API base paths overlap and the matched route belongs to the outer API, while its operation ID is shared by both APIs or is resolver-generated and absent from the registry, `get_api_base_path()` selects the longest matching base path even when the matched operation belongs to an outer API, so callers that build a resource path with `get_resource_path()` check permissions against the wrong namespace and can allow access to a resource the caller is not authorized to access.

Retain the serving API's base path on each route and use that association when resolving the current request's API.
</issue_to_address>

### Comment 2
<location path="foca/context.py" line_range="310" />
<code_context>
         root_path=request.script_root,
         url=_get_url(),
+        query=QueryParams(
+            parse_qsl(_get_query_string(), keep_blank_values=True, errors=_INVALID_UTF8)
+        ),
         headers=Headers(request.headers.items()),
</code_context>
<issue_to_address>
**Large queries amplify request memory**

When the server accepts unusually long query strings containing many parameters and several such requests are handled concurrently, `current_request()` materializes every query pair into strings and per-name lists. `log_traffic()` now calls it for every decorated request just to format the request line, so concurrent requests with very large accepted query strings consume substantially more memory and CPU than before, potentially exhausting worker memory.

Avoid parsing the query when callers only need request-line fields, or enforce a query-size limit before constructing the snapshot.
</issue_to_address>

### Comment 3
<location path="foca/context.py" line_range="355" />
<code_context>
             "No request: current_request() works only while a request is handled"
         )
-    found = match(request.path, request.method)
+    found = _match_request()
     return RequestSnapshot(
         method=request.method,
</code_context>
<issue_to_address>
**Catch-all routes misidentify UI requests**

When a request to a non-operation Connexion route, such as the served specification or Swagger UI, overlaps a catch-all operation route, `match()` sees only FOCA’s operation table, so a catch-all operation can win its lookup even when Connexion routes the request to a static Swagger or specification endpoint. `_get_operation_id()` then logs the catch-all operation, and `_get_request_base_path()` treats the non-operation request as belonging to that API instead of using the documented fallback.

Make route identification account for Connexion’s non-operation route precedence before reporting an operation or API base path.

Also at `foca/utils/urls.py:476`.
</issue_to_address>

Linked issues

#718 refactor(utils): read the request via accessors · 2 of 2 met

# Requirement Status Notes
1 Switch the listed remaining modules to read request data via FOCA's accessors. ✅ Met URLs, logging, pagination, validation, and response-validation logging use helpers from foca.context; the body-size check remains the documented middleware exception.
2 Keep request reads outside the accessor module only where the design answers exempt them. ✅ Met The AST check covers foca/ outside foca/context.py and exempts only _check_body_size, with tests for the exemption.

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and if route matching assigns a request to the wrong API, resource paths can be built under the wrong base path and access-control checks may apply the wrong policy, potentially allowing access that should be denied. Reverting restores the previous API lookup, but any access or data exposure that occurred before the revert cannot be undone.

Blocking findings: foca/utils/urls.py:488, foca/context.py:310, foca/context.py:355


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

Comment thread foca/utils/urls.py Resolved
Comment thread foca/context.py Resolved
Comment thread foca/context.py Resolved
Routes record the base path of their API (`Route.base_path`), and the
API of a request is the registered API with that base path. With
nested base paths, the API was inferred from the path template and
operation IDs, which picked the inner API when both shared an
operation ID or it was resolver-generated (Sourcery review).

Refs #718

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 8411ca2 into dev Nov 6, 2026
83 checks passed
@uniqueg
uniqueg deleted the refactor/718-request-accessors branch November 6, 2026 17:10
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(utils): read the request via accessors

1 participant