Skip to content

feat: add request and claims accessors - #720

Merged
uniqueg merged 4 commits into
devfrom
feat/715-accessors
Nov 5, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/715-accessors

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds the request and claims accessors of #634 (names as decided there), so that apps and FOCA read the request in one way that means the same on Connexion 2 and on ASGI:

  • foca.context.current_request() returns a read-only, frozen RequestSnapshot: method, path (below the root path, as Flask's request.path, i.e., what policies and owners are keyed by), root_path, url (percent-encoded), headers (a case-insensitive, read-only Headers mapping with getlist()), content_length, client_address, and route (the path template from the route table's match(), refactor: check routes from specs, not url_map #632) with path_params. It raises a RuntimeError outside requests. The representation of a snapshot leaves out the path, URL, path parameters and header values, so logging one doesn't log tokens or cookies; the URL is built from the decoded path, encoded anew, and the raw query string.
  • foca.security.auth.current_token_info() and current_claims() return copies of Connexion's token info of the request and its claims; they are empty if no token was validated, also outside requests. get_current_claims() returns current_claims(), and enforcement's internal claim reads go through the same code.
  • The 0.22.0 bodies read from Flask and Connexion 2; only they change in the ASGI release.

Switching FOCA's internals to the accessors is #717/#718, and the "Writing controllers" page is #719.

Docs: API reference (foca.context members, current_token_info, current_claims), "Reading the current request" in docs/utilities.md, current_claims() in "Using token claims" (docs/authentication.md), and a section with a replacement table in docs/migration-0.22.md.

Closes #715

Verification

  • coverage run -m pytest with MongoDB 7.0: 4631 passed, 2 skipped, 100% coverage
  • ruff check, ruff format --check, mypy, ast-grep scan, semgrep scan --config .semgrep --error, mkdocs build --strict: pass
  • Tests cover a root path (/root), a base path (/api/v1), path parameters, headers, HEAD/no route, snapshot immutability, non-ASCII URLs, representations without credentials, and the claims accessors with and without token info.
  • Downstream, with this branch (cae877b; the later commit only changes how the snapshot builds its URL and representation, which neither repo uses) installed over their locked environments (helm dependency build deployment with Helm 3.22.1, as CI):
    • cloud-registry dev (4e707a9): all pass. Mongomock with coverage: 2065 passed, 11 skipped, 100% coverage; against MongoDB 7.0: 2076 passed. The 272 Helm-dependent tests of both runs failed only because my runner lacked Helm on its path; tests/test_chart.py and tests/test_config.py rerun with Helm 3.22.1: 297 passed.
    • proTES dev (e47cac2): all pass. Mongomock with coverage: 1428 passed, 11 skipped, 100% coverage; against MongoDB 7.0: 1438 passed. The 185 Helm-dependent tests, as above; tests/test_chart.py and tests/test_config_examples.py rerun with Helm 3.22.1: 220 passed.
  • CI: all checks passed on cae877b; Sourcery findings fixed in 936d035 (path and URL encoding) or answered

Declined review findings

  • Args in both the class and the __init__ docstring of Headers: the codebase's convention (cf. RequestIdMiddleware).
  • Lazy imports of foca.security.auth in enforcement.py: the cycle is real (models.config -> access_control -> enforcement -> auth -> models.config), now named in a comment; the wrappers keep the names that callers and tests patch, which refactor(security): read the request via accessors #717 switches.
  • Repeated headers through a real request: WSGI servers join them into one value, so getlist() is covered with Headers directly.
  • Wrapping Werkzeug's headers instead of Headers: would tie the snapshot to Werkzeug, which it is meant to hide.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 3 commits November 5, 2026 21:28
Add foca.context.current_request(), a read-only snapshot of the request
being handled (method, path below the root path, root path, URL,
case-insensitive headers, content length, client address, and the route
template and path parameters from the route table), and
foca.security.auth.current_token_info() and current_claims(), which
return copies and are empty without a validated token.
get_current_claims() returns current_claims(). The accessors read from
Flask and Connexion 2 for now; only their bodies change on ASGI.

Closes #715

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Represent headers by their names only and leave the URL out of the
representation of request snapshots, so that logging one doesn't log
tokens or cookies. Percent-encode non-ASCII characters of the URL, as
documented. Return no values from Headers.getlist() for names that
aren't strings. Fix the route example of the migration guide, and
explain the import cycle and the uncopied claim helpers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Percent-encode only the path and query of the snapshot's URL: IDNA
encoding of the whole URL failed on hosts that Werkzeug accepts, e.g.,
with empty or overlong labels, which made current_request() raise in
before-request hooks and error handlers. Describe the URL as the
server reconstructs it.

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

Introduces framework-neutral request snapshots and token/claims accessors, backed by immutable copied data and shared enforcement logic, with comprehensive tests and documentation to support migration away from Flask and Connexion-specific context APIs.

Sequence diagram for framework-neutral request and claims access

sequenceDiagram
    participant Controller
    participant RequestAccessor as foca.context.current_request
    participant Flask as Flask request context
    participant Routes as foca.api.routes.match
    participant ClaimsAccessor as foca.security.auth.current_claims
    participant Connexion as Connexion token context

    Controller->>RequestAccessor: current_request()
    RequestAccessor->>Flask: has_request_context()
    RequestAccessor->>Routes: match(request.path, request.method)
    Routes-->>RequestAccessor: route and path parameters
    RequestAccessor-->>Controller: frozen RequestSnapshot

    Controller->>ClaimsAccessor: current_claims()
    ClaimsAccessor->>Connexion: _get_token_info()
    Connexion-->>ClaimsAccessor: validated token info
    ClaimsAccessor-->>Controller: copied claims
Loading

File-Level Changes

Change Details Files
Added a framework-neutral, immutable request snapshot accessor with normalized request metadata and route information.
  • Introduced RequestSnapshot and read-only, case-insensitive Headers types.
  • Builds snapshots from Flask request context, including root-relative paths, encoded URLs, client metadata, headers, and content length.
  • Resolves route templates and converted path parameters through the API route matcher, including no-route handling.
  • Protects snapshots and nested mappings from mutation and omits sensitive header values and URLs from representations.
foca/context.py
tests/test_context.py
Added public accessors for validated token information and claims, while centralizing enforcement reads on the new auth implementation.
  • Added deep-copying current_token_info() and current_claims() accessors with empty results outside requests or without validated token data.
  • Preserved support for FOCA claim envelopes and raw token-info claims, rejecting non-dictionary claims.
  • Updated enforcement helpers and get_current_claims() to use the shared accessor logic while retaining lazy imports to avoid the existing dependency cycle.
  • Added coverage for copied results, missing or malformed token data, and outside-request behavior.
foca/security/auth.py
foca/security/access_control/enforcement.py
tests/security/test_auth.py
Documented the new request and claims APIs and provided migration guidance for framework-specific access patterns.
  • Added API reference entries and examples for reading current requests and claims.
  • Documented snapshot field semantics, route matching, immutability, URL encoding, and behavior outside requests.
  • Added a replacement table mapping Flask and Connexion access to FOCA accessors for ASGI preparation.
docs/authentication.md
docs/migration-0.22.md
docs/reference.md
docs/utilities.md

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 (642ef74) to head (936d035).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #720   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           71        71           
  Lines         9010      9066   +56     
=========================================
+ Hits          9010      9066   +56     
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 21:53

@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/context.py" line_range="150" />
<code_context>
+    """
+
+    method: str
+    path: str
+    root_path: str
+    url: str = field(repr=False)
</code_context>
<issue_to_address>
**Credentials appear in snapshot logs**

When an application logs a snapshot whose request path contains a token or other credential, `RequestSnapshot`'s generated representation includes both `path` and `path_params`, so logging the snapshot writes the credential to logs even though URL and header values are omitted.

Exclude or redact sensitive path data, including `path_params`, from the generated representation.

Also at `foca/context.py:157`.
</issue_to_address>

### Comment 2
<location path="foca/context.py" line_range="172" />
<code_context>
+        host and not all hosts can be IDNA-encoded.
+    """
+    prefix = host_url.rstrip("/")
+    return prefix + quote(url[len(prefix) :], safe=_URL_SAFE)
+
+
</code_context>
<issue_to_address>
**Invalid percent escapes reach callers**

When the reconstructed request path or query contains a literal `%` not followed by two hexadecimal digits, `_encode_url()` passes every `%` through via `_URL_SAFE`, so `current_request().url` retains the malformed escape and URL parsers or consumers reject or misinterpret it.

Preserve only valid percent-escape sequences and percent-encode other `%` characters when building the URL.
</issue_to_address>

### Comment 3
<location path="foca/context.py" line_range="197" />
<code_context>
+        )
+    found = match(request.path, request.method)
+    return RequestSnapshot(
+        method=request.method,
+        path=request.path,
+        root_path=request.script_root,
</code_context>
<issue_to_address>
**Method is not always uppercase**

When a server supplies a lowercase method in the request environment, `current_request()` copies the raw WSGI method while `RequestSnapshot` promises an upper-case method, so callers comparing the snapshot method to standard uppercase names receive a value that violates the accessor contract.

Normalize the captured method to uppercase, or change the documented contract if preserving the raw method is intentional.
</issue_to_address>

### Comment 4
<location path="foca/context.py" line_range="175" />
<code_context>
+    return prefix + quote(url[len(prefix) :], safe=_URL_SAFE)
+
+
+def current_request() -> RequestSnapshot:
+    """Get a snapshot of the request being handled.
+
</code_context>
<issue_to_address>
**Request accessors omitted from reference**

The API reference’s `foca.context` section does not list `current_request`, `RequestSnapshot`, or `Headers`, so users following the stated API-reference documentation cannot find these public additions there.

Add the request accessor and snapshot types to the `foca.context` members listed in the API reference.
</issue_to_address>

Linked issues

#715 feat: add request and claims accessors · 4 of 4 met

# Requirement Status Notes
1 current_request() returns the specified read-only request snapshot and raises outside a request. ✅ Met Implemented as a frozen RequestSnapshot; current_request() raises RuntimeError without an active request.
2 current_token_info() and current_claims() return copies, are empty without a validated token, and get_current_claims() uses them. ✅ Met Both accessors return deep copies; get_current_claims() delegates to current_claims().
3 The 0.22.0 implementation reads from Flask and Connexion 2. ✅ Met current_request() reads Flask's request, and token accessors read Connexion's request context.
4 The three accessors are public, typed, documented in the API reference, and tested with a root path, base path, and headers. ✅ Met The accessors have public names and return annotations, are included in the API reference modules, and tests cover a root path, base path, and headers.

Sourcery assessment

Approval pending. 3 findings to address first.

Blocking findings: foca/context.py:150, foca/context.py:172, foca/context.py:197


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

Comment thread foca/context.py Resolved
Comment thread foca/context.py Resolved
Comment thread foca/context.py Resolved
Comment thread foca/context.py Resolved
Build the URL of request snapshots from the decoded path, encoded anew,
and the raw query string, in which percent signs that don't start
escapes are encoded: Werkzeug's URL keeps decoded percent signs of the
path. Leave the path and path parameters out of the representation of
snapshots, as they may hold credentials.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit e5a25e1 into dev Nov 5, 2026
58 checks passed
@uniqueg
uniqueg deleted the feat/715-accessors branch November 5, 2026 22:36
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.

feat: add request and claims accessors

1 participant