Skip to content

refactor(security): read requests via accessors - #722

Merged
uniqueg merged 5 commits into
devfrom
refactor/717-security-accessors
Nov 6, 2026
Merged

uniqueg merged 5 commits into
devfrom
refactor/717-security-accessors

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Summary

FOCA's security code no longer reads the request from flask.request, request_ctx or connexion.request. It uses the accessors from #715 / PR 720 instead:

  • Enforcement (enforcement.py): the request path and method for policies, the on_behalf_of_header and the opt-in roles header now come from current_request().
  • Ownership server (ownership_server.py): path and method for matching the route, and path_params instead of view_args, also come from current_request().
  • auth.py: the bearer token is read from current_request().headers. The token info comes from foca.context.
  • Plugin adapter (plugins/adapter.py):
    • Headers, path, method and path parameters come from the snapshot.
    • Query parameters are parsed from the snapshot's url, the same way Werkzeug parses request.args. A parametrised test and a 30,000-case fuzz comparison in review show the results are identical. The one difference: query strings that aren't UTF-8 no longer raise. Bytes that aren't valid UTF-8 stay percent-encoded.
    • The media type comes from the Content-Type header via werkzeug.http.parse_options_header.
    • Header names are title-cased, which is the same spelling WSGI gave them before.
  • Framework glue in foca.context only: two private helpers hold the remaining Flask/Connexion reads.
    • _get_token_info() is moved there from auth.py.
    • _get_request_key() gives a per-request identity for the enforcement mark on flask.g. It is the same object as before, so the ownership controllers' enforcement check keeps its meaning.
  • Permissions API: postPermission() and putPermission() take the rule as the keyword-only argument body instead of calling request.get_json(), and FOCA's spec no longer sets x-body-name: permission.
    • Old specs keep working: custom access_control.api_specs copied from FOCA's spec before 0.22.0, which still set x-body-name: permission, get the body as keyword-only permission, with a DeprecationWarning.
    • A call with neither or both raises a TypeError with a clear message.
    • Verified end to end through Connexion 2 for both spec variants, POST and PUT.
  • New regression test tests/security/test_framework_neutral.py: an AST check that the modules under foca/security and foca/plugins/adapter.py don't import or access the request objects of Flask or Connexion.

The snapshot is not extended. The adapter gets the query from url.

Public changes and docs

  • docs/migration-0.22.md and docs/access-control.md now say that the permissions API controllers take body, so x-body-name is optional.
    • Old specs with x-body-name: permission keep working, but that name is deprecated. The warning only shows where deprecation warnings are enabled, which the migration guide says.
    • Other body names fail. In 0.21, any name worked, because the controllers ignored the argument and read the request.
    • Direct callers, e.g. tests, pass body.
  • Nothing else public changes. docs/utilities.md (Reading the current request) needs no update.

Existing tests

Assertions are unchanged. Changed call signatures and fixtures only:

  • tests/security/access_control/test_access_control_server.py and tests/test_audit.py pass the payload as body= instead of through test_request_context(json=...).
  • The traffic-logging test's plain Flask views pass the JSON body to the controllers through a small wrapper, as Connexion does.
  • The ownership tests and their g mark setup are untouched.

New tests:

  • test_enforcement.py::TestSelfService::test_writes_get_body covers POST/PUT end to end through Connexion. It also passes on dev.
  • The adapter tests compare query parsing with Werkzeug and check header names and the media type.
  • test_context.py tests the request key and the token info helper directly.

Closes #717

Verification

Run locally in the agent clone; MongoDB 7.0.34 on port 12345 for the tests.

  • coverage run -m pytest && coverage report -m: 4695 passed, 3 skipped, 100% coverage (at 7b5120a; 03e1183 changes only docs).
  • End to end through Connexion: test_enforcement.py::TestSelfService::test_writes_get_body covers FOCA's current spec and a copy of the old spec with x-body-name: permission, POST and PUT. It also checks that only the old spec gets the deprecation warning.
  • test_access_control_server.py::TestBodyNames covers permission with a warning, and neither or both with a TypeError.
  • ruff format --check, ruff check foca tests, mypy: clean.
  • ast-grep scan and semgrep --config=.semgrep on the changed files: no findings.
  • mkdocs build --strict: OK.
  • Downstream: cloud-registry dev and proTES dev, with this branch installed editable and Helm 3.22.1 on PATH (chart dependencies built and checksums OK), using mongomock.
    • Final run (at ecfcfbd; the later Sourcery fixes only touch the plugin adapter's method and query extraction and the test): cloud-registry 2337 passed, 11 skipped (mongomock thread-safety skips); proTES 1613 passed, 11 skipped.
    • Not re-run for the body-name change, which only touches these controllers and docs. Neither repo routes operations to FOCA's permission controllers. cloud-registry's x-body-name: permission belongs to its own controllers.
  • CI: all checks passed on every push, last on 03e1183 (30 passed, 3 skipped by design; including CI passed, codecov patch/project and Read the Docs).
  • Sourcery review: 4 threads, all answered and resolved.
    • Fixed: method upper-cased again; query taken after the first ?, independent of the host; the AST test resolves module aliases.
    • Not an issue: credential headers are filtered on the snapshot's lower-case names, as the existing test shows.

Declined review findings

  • Private helpers imported across modules (_get_request_key, _get_token_info; quality, medium). The repo already does this, e.g. _ENFORCED_MARK and auth._get_claims. Making them public would add API surface the ASGI port would have to keep.
  • Move query parsing into RequestSnapshot (quality, medium). Out of scope: the brief for refactor(security): read the request via accessors #717 rules out extending the snapshot. The parsing lives in the adapter, which FOCA 1.0 replaces.
  • Header title-casing as a behaviour change (quality). Not a change: Werkzeug's EnvironHeaders gives the same spelling under WSGI.
  • Plugin path parameters for routes outside FOCA's route table (adversarial, low). Such routes (Flask routes added outside API specs) now get empty path_params. This is documented in the inbound_from_request docstring rather than kept on Flask's view_args.
  • Startup check for x-body-name in custom specs (adversarial, low). Superseded: the controllers now accept the old name permission, with a deprecation warning.
  • Deprecation warning hidden in production (adversarial, low; default filters attribute it to foca/utils/logging.py). FOCA's other deprecations behave the same, so I kept the warning and documented when it shows. A once-per-process log line would also make it visible.
  • Indirect flask.request reads through foca.utils (get_page_links, log_traffic_if; adversarial, low). These are the utilities left to refactor(utils): read the request via accessors #718, which awaits design decisions.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 2 commits November 6, 2026 00:29
Access control, ownership, token validation and the plugin adapter
read the request via foca.context.current_request() and the token
info via foca.security.auth.current_token_info() instead of
flask.request, request_ctx or connexion.request. The framework glue
lives in foca.context only: private helpers give the token info and
a per-request key for the enforcement mark.

The permissions API controllers take the rule as the body argument
that Connexion passes instead of reading request.get_json(). The
plugin adapter parses query parameters from the snapshot's URL, as
Werkzeug does, and no longer fails on query strings that aren't
UTF-8. A test checks that the security modules don't import the
request objects of Flask or Connexion.

Closes #717

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Make body a required argument of postPermission() and putPermission(),
so that operations renaming the body fail clearly. Document that the
permissions API controllers take the body as body, including for
custom api_specs, and that plugin path parameters come from the
operations of the app's specifications. Test the token info helper
of foca.context directly.

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

The PR makes FOCA security and plugin code framework-neutral by routing request data through context accessors and snapshot-based adaptation, while updating permission controllers to accept Connexion’s explicit body argument and documenting the resulting custom-spec migration requirement.

Sequence diagram for snapshot-based security enforcement

sequenceDiagram
    participant Client
    participant Framework as Flask_or_Connexion
    participant Context as foca.context
    participant Enforcement as enforcement.py
    participant Handler as Protected_handler

    Client->>Framework: HTTP request
    Framework->>Context: current_request()
    Context-->>Enforcement: RequestSnapshot
    Enforcement->>Enforcement: is_permitted()
    Enforcement->>Context: current_request()
    Context-->>Enforcement: path and method
    Enforcement->>Handler: enforce_access_control()
    Handler-->>Client: Response
Loading

Sequence diagram for explicit permission request bodies

sequenceDiagram
    participant Client
    participant Connexion
    participant Controller as postPermission_or_putPermission
    participant RuleParser as _get_rule
    participant Store as Casbin_adapter

    Client->>Connexion: POST_or_PUT_permission(body)
    Connexion->>Controller: body
    Controller->>RuleParser: _get_rule(body)
    RuleParser-->>Controller: policy_type_and_values
    Controller->>Store: save_policy_line()
    Store-->>Controller: permission_id
    Controller-->>Client: Permission response
Loading

File-Level Changes

Change Details Files
Centralize framework-specific request access behind FOCA context accessors.
  • Replace direct Flask/Connexion request reads in enforcement, ownership, authentication, and plugin adapter code with current_request() and context helpers.
  • Preserve request identity and Connexion token-info behavior through private helpers in foca.context.
  • Add AST regression coverage preventing framework request access from returning to security and adapter modules.
foca/context.py
foca/security/access_control/enforcement.py
foca/security/access_control/ownership_server.py
foca/security/auth.py
foca/plugins/adapter.py
tests/security/test_framework_neutral.py
tests/test_context.py
Refactor plugin request adaptation to consume the request snapshot while preserving framework-compatible inbound values.
  • Parse query parameters from the snapshot URL with Werkzeug-compatible decoding and percent-encode invalid UTF-8.
  • Use snapshot headers, path, method, and path parameters; title-case header names and parse media types from Content-Type.
  • Add regression tests for query equivalence, invalid encoding, headers, and media types.
foca/plugins/adapter.py
tests/plugins/test_plugin_adapter.py
Make permission controllers consume Connexion-injected request bodies explicitly.
  • Change postPermission() and putPermission() to require body and validate it directly.
  • Remove ineffective x-body-name: permission overrides from the permissions API specification.
  • Update documentation, direct-call fixtures, wrappers, and end-to-end tests for the new controller contract.
foca/security/access_control/access_control_server.py
foca/security/access_control/api/access-control-specs.yaml
docs/access-control.md
docs/migration-0.22.md
tests/security/access_control/test_access_control_server.py
tests/security/access_control/test_enforcement.py
tests/test_audit.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 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (438c8a1) to head (03e1183).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #722   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           71        71           
  Lines         9099      9127   +28     
=========================================
+ Hits          9099      9127   +28     
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 00:12

@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/plugins/adapter.py" line_range="136" />
<code_context>
+        {
+            name.title(): ", ".join(request.headers.getlist(name))
+            for name in request.headers
+            if name not in CREDENTIAL_HEADERS
+        }
+    )
</code_context>
<issue_to_address>
**Credentials reach plugins and backends**

When an incoming request carries a standard credential header, `request.headers` yields title-cased names, but `CREDENTIAL_HEADERS` contains lowercase names, so the case-sensitive filter retains credentials in `InboundRequest.headers` and exposes them to plugins and downstream backends.

Compare header names to `CREDENTIAL_HEADERS` case-insensitively while preserving the names used in `InboundRequest.headers`.
</issue_to_address>

### Comment 2
<location path="foca/plugins/adapter.py" line_range="143" />
<code_context>
     return InboundRequest(
-        method=request.method.upper(),
+        method=request.method,
         path=request.path,
         route=route if route is not None else rule,
-        path_params={
</code_context>
<issue_to_address>
**Plugins receive lowercase methods**

When the WSGI request method is lowercase, `inbound_from_request()` copies `request.method` unchanged, so `InboundRequest.method` violates its uppercase contract and plugins that dispatch on it can mishandle the request.

Uppercase `request.method` when assigning `InboundRequest.method`.
</issue_to_address>

### Comment 3
<location path="tests/security/test_framework_neutral.py" line_range="48-58" />
<code_context>
+                for alias in node.names
+                if names is None or alias.name in names
+            )
+        elif isinstance(node, ast.Import):
+            found.extend(
+                f"import {alias.name}"
+                for alias in node.names
+                if alias.name in _FORBIDDEN and _FORBIDDEN[alias.name] is None
+            )
+        elif (
+            isinstance(node, ast.Attribute)
+            and isinstance(node.value, ast.Name)
+            and node.value.id in _FORBIDDEN
+            and node.attr in (_FORBIDDEN[node.value.id] or ())
+        ):
+            found.append(f"{node.value.id}.{node.attr}")
</code_context>
<issue_to_address>
**Forbidden framework reads go undetected**

When a checked security module imports Flask or Connexion under an alias and accesses its request through that alias, `_forbidden_uses()` recognizes attribute access only when the base name is a key in `_FORBIDDEN`, so it reports no finding and `test_no_framework_request` passes despite the forbidden framework request read.

Resolve framework import aliases in `_forbidden_uses()` when checking attribute access.
</issue_to_address>

### Comment 4
<location path="foca/plugins/adapter.py" line_range="167" />
<code_context>
+    """
+    query: dict[str, list[str]] = {}
+    for key, value in parse_qsl(
+        urlsplit(url).query, keep_blank_values=True, errors=_INVALID_UTF8
+    ):
+        query.setdefault(key, []).append(value)
</code_context>
<issue_to_address>
**Malformed hosts break gateway requests**

When a WSGI request has a malformed bracketed Host value, such as an unmatched `[`, `urlsplit(url)` rejects a malformed bracketed host with `ValueError` before extracting the query, so `inbound_from_request` fails instead of processing the request.

Extract and parse the query independently of the URL authority, or handle invalid authorities without failing query parsing.
</issue_to_address>

Linked issues

#717 refactor(security): read the request via accessors · 2 of 2 met

# Requirement Status Notes
1 These modules read no request data from flask.request, request_ctx or connexion.request. ✅ Met The enforcement, ownership, auth and plugin adapter code uses FOCA accessors; the AST regression test checks for direct framework request imports and accesses.
2 Policies and owners match exactly as before: the existing access-control and ownership tests pass unchanged. ✅ Met Policy checks use the snapshot path and method, while ownership uses its path parameters; the permission-controller test-call updates reflect the new required body argument, not changed policy or ownership assertions.

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and if the new request accessors or body binding supply the wrong values, a permission rule could be stored that grants unintended access; reverting would not undo the stored rule or any access already exposed.

Blocking findings: foca/plugins/adapter.py:136, foca/plugins/adapter.py:143, tests/security/test_framework_neutral.py:58, foca/plugins/adapter.py:167


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

Comment thread foca/plugins/adapter.py Resolved
Comment thread foca/plugins/adapter.py Resolved
Comment thread foca/plugins/adapter.py Resolved
uniqueg and others added 3 commits November 6, 2026 01:19
Upper-case the method of inbound requests again, take the query from
what follows the first ? of the URL rather than parsing its host, and
resolve module aliases in the framework-neutrality test, from review.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Let postPermission() and putPermission() take the request body as the
keyword argument body or, for specifications that still set
x-body-name: permission as FOCA's did before 0.22.0, as permission,
with a DeprecationWarning. Calls with neither or both raise a
TypeError. Test both variants end to end through Connexion, and
document that old specifications keep working.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 54079ae into dev Nov 6, 2026
83 checks passed
@uniqueg
uniqueg deleted the refactor/717-security-accessors branch November 6, 2026 00:57
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(security): read the request via accessors

1 participant