Skip to content

feat: config-driven access control - #259

Merged
uniqueg merged 7 commits into
devfrom
worktree-issue-258
Oct 17, 2026
Merged

uniqueg merged 7 commits into
devfrom
worktree-issue-258

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

Closes #258

Summary

Makes FOCA's Casbin-based access control usable through config alone and closes the privilege escalation hole in the permissions API.

  • Config-driven enforcement: new access_control.enforce (default false). When enabled, policies are enforced on every operation of the app's specs that requires authentication. Operations with security: [] or x-foca-access-control: false are skipped. Enforcement wraps resolved controllers via a Connexion resolver (AccessControlResolver), so it runs after token validation.
  • Identity from validated OIDC tokens: subject taken from the validated token claims (access_control.claim_identity, defaulting to auth.claim_identity, i.e. sub), not by re-decoding the token or reading headers.
  • Groups to roles: claim_groups (e.g. eduperson_entitlement) plus optional group_mapping (claim value -> role). The resulting roles are checked as additional subjects, so no per-user rules are needed (e.g. for admins).
  • Namespaced subjects: in rules, user identifiers are prefixed with subject_prefix (default user:), and group claim values without group_mapping with group:. Roles (from group_mapping or g rules) are used as is. A user ID or IdP group equal to a role name (admin, owner, …) therefore does not grant that role.
  • Permissions API secured (fix): access-control-specs.yaml now requires bearerAuth (validated by foca.security.auth.validate_token), and policies are always enforced on it, irrespective of enforce. Unauthenticated requests get 401, unauthorized ones 403.
  • Public helpers in foca.security.access_control: get_current_subject(), get_current_groups(), add_resource_role(), remove_resource_role(), list_resource_roles(), remove_resource(). The resource-role helpers take and return unprefixed user IDs, accept ptype (default g2), and raise ValueError if the model does not define that role type with three fields (e.g. the default model, whose g2 groups objects).
  • Reference model resource_role_model.conf: resource-scoped roles (g2 = _, _, _), * = any authenticated user, owner/maintainer examples, admin role = everything.
  • Docs: new section in docs/access_control/README.md (config, claims, subject namespaces, resource roles with an ownership-on-create example, permissions API), and a pointer in README.md.
  • CI fixes (pre-existing failures on dev): mypy foca failed on foca/security/auth.py because recent PyJWT types jwt.decode(options=…) as a TypedDict; silenced with # type: ignore[arg-type] (as for key on the line above), keeping compatibility with older PyJWT allowed by PyJWT~=2.4. A test imported pkg_resources, which recent setuptools (installed in CI) no longer ships; replaced with importlib.resources.

Decisions

Raised as open questions in the first version of this PR and decided since:

  1. User IDs can't collide with role names: user IDs are prefixed (subject_prefix, default user:) by enforcement and the helpers.
  2. Unmapped group values: dropped when group_mapping is set; without a mapping, raw values are prefixed with group:.
  3. Helper policy type: ptype argument (default g2) plus a model check that raises instead of silently writing wrong rules.
  4. Identity claim: access_control.claim_identity defaults to auth.claim_identity and can be overridden. Docs recommend a stable, IdP-assigned claim such as sub.

Verification

CI: all checks pass: lint, mypy and unit tests on Python 3.9–3.12 × MongoDB 4.4–7.0 (16 jobs), petstore integration tests, Docker builds (4 jobs), Codecov patch and project (coverage stays at 100%), Read the Docs.

Locally (Python 3.12 venv, pip install -e .[dev], latest setuptools):

  • flake8: clean
  • mypy foca: no issues
  • pytest tests/security/access_control/test_enforcement.py: 53 passed (no MongoDB needed; uses mongomock and a mocked bearer-info function). Covers: public ops, authentication before enforcement, any-authenticated create, owner/maintainer/non-member, admin via group mapping, unmapped group values ignored, raw group: values without mapping, user IDs and groups equal to role names, missing identity claim, identity claim fallback/override, per-op opt-out, enforce: false, permissions API (401/403/200, also with enforce: false), subject/group helpers, resource-role helpers (persistence, custom prefix, custom ptype, incompatible models).
  • Regression checks: with the permissions-API enforcement removed, the non-admin permissions tests fail. With subject_prefix set to empty, the collision tests fail (users owner/admin gain those roles). Both pass with the change.
  • Full suite pytest locally: all tests pass except the 22 existing ones that need a real MongoDB on localhost:12345 (adapter, permission controllers, check_permissions), which wasn't running locally; they pass in CI.

Risks

  • Behaviour change for existing apps (intended fix): the permissions API is registered whenever auth.required is true (the default). It now needs a valid bearer token plus a Casbin rule (or the admin role in the reference model). Admins of apps using default_model.conf need explicit rules for the permissions API routes, added directly to the database or via group mapping.
  • Custom permissions-API specs (access_control.api_specs) without security now deny all requests (fail-closed).
  • Rules written by hand or via the permissions API must use the prefixed forms (user:alice, group:…).
  • Policies are loaded from MongoDB on every enforced request (fresh casbin.Enforcer), as check_permissions already does: never stale, but adds latency under load.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Enable secure, configuration-driven access control enforcement across authenticated APIs while closing the permissions API privilege-escalation gap.

New Features:

  • Add configuration-driven Casbin enforcement for authenticated API operations using identities and group claims from validated OIDC tokens.
  • Provide namespaced subjects, group-to-role mapping, and public helpers for current identities and resource-scoped role management.
  • Add a reference Casbin model for resource-scoped roles and ownership-based authorization.

Bug Fixes:

  • Secure the permissions API with bearer-token authentication and unconditional policy enforcement, preventing unauthorized permission changes.

Enhancements:

  • Support per-operation enforcement opt-out and preserve authentication-before-authorization behavior.
  • Use configurable identity claims and subject prefixes to prevent collisions between users, groups, and roles.

CI:

  • Fix mypy compatibility with current PyJWT type definitions and replace the deprecated pkg_resources test dependency with importlib.resources.

Documentation:

  • Document config-driven enforcement, token claims, subject namespaces, resource roles, and permissions API authorization.

Tests:

  • Add comprehensive tests covering enforcement behavior, group mappings, permissions API authorization, identity helpers, and resource-role helpers.

uniqueg and others added 2 commits October 17, 2026 01:41
- Add `access_control.enforce` (default: false) to enforce Casbin policies
  on all operations of the app's specs that require authentication; skip
  operations with `security: []` or `x-foca-access-control: false`.
  Enforcement wraps resolved controllers via a Connexion resolver, so it
  runs after token validation.
- Take the subject from validated token claims (`claim_identity`, default
  `sub`) and roles from `claim_groups`, optionally mapped via
  `group_mapping`.
- Secure the permissions API: require `bearerAuth` and always enforce
  policies on it, so that unauthenticated and unauthorized users can no
  longer manage rules.
- Add public helpers for resource-scoped roles and a reference model
  `resource_role_model.conf`.

Refs #258

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR makes Casbin authorization configurable across authenticated API operations, derives safely namespaced subjects and roles from already validated OIDC claims, and secures the permissions API independently of the global enforcement flag. It also adds resource-scoped role helpers and a reference model, with extensive tests and documentation covering authorization semantics, fail-closed behavior, and compatibility fixes.

Sequence diagram for config-driven access control enforcement

sequenceDiagram
    participant Client
    participant Connexion
    participant Auth as validate_token
    participant Resolver as AccessControlResolver
    participant AC as enforce_access_control
    participant Casbin as CasbinEnforcer
    participant Controller

    Client->>Connexion: HTTP request
    Connexion->>Auth: validate_token
    Auth-->>Connexion: Validated token claims
    Connexion->>Resolver: resolve operation
    Resolver->>AC: Wrapped controller
    Connexion->>AC: Execute request
    AC->>AC: get_current_subject()
    AC->>AC: get_current_groups()
    AC->>Casbin: enforce(subjects, request.path, request.method)
    alt Policy allows access
        Casbin-->>AC: allowed
        AC->>Controller: Invoke controller
        Controller-->>Client: Response
    else Missing identity or denied
        Casbin-->>AC: denied
        AC-->>Client: 401 or 403
    end
Loading

Flow diagram for enforced and public API operations

flowchart TD
    A[Request] --> B{Requires authentication?}
    B -->|No: security: &#91;&#93;| P[Public operation]
    B -->|Yes| C[Validate bearer token]
    C --> D{Access control opt-out?}
    D -->|Yes: x-foca-access-control: false| O[Invoke controller]
    D -->|No| E{Identity claim present?}
    E -->|No| U[401 Unauthorized]
    E -->|Yes| F[Build namespaced user and group subjects]
    F --> G[Load current Casbin policies]
    G --> H{Any subject is allowed?}
    H -->|Yes| O
    H -->|No| X[403 Forbidden]
Loading

File-Level Changes

Change Details Files
Adds opt-in, config-driven Casbin enforcement around authenticated OpenAPI operations after Connexion token validation.
  • Introduces enforcement configuration and operation selection based on security requirements and per-operation opt-out metadata.
  • Derives namespaced user and group subjects from validated token claims, with configurable identity claims, group mappings, and 401/403 handling.
  • Loads current policies per request and enforces them against request paths and HTTP methods.
  • Adds resolver integration during application and permissions-API registration, while warning when enforcement is enabled without authentication.
foca/api/register_openapi.py
foca/foca.py
foca/models/config.py
foca/security/access_control/enforcement.py
foca/security/access_control/register_access_control.py
Closes the permissions API privilege-escalation path by requiring authentication and always applying Casbin authorization.
  • Adds bearerAuth security using the existing token validation function to the permissions API specification.
  • Ensures permissions endpoints are enforced even when global access-control enforcement is disabled.
  • Preserves distinct 401 responses for missing or invalid tokens and 403 responses for authenticated subjects without permission.
foca/security/access_control/api/access-control-specs.yaml
foca/security/access_control/register_access_control.py
tests/security/access_control/test_enforcement.py
Adds public request-context and resource-scoped role management APIs with model validation.
  • Exports helpers for retrieving the validated subject and groups and for adding, removing, listing, and cleaning up resource roles.
  • Prefixes helper-managed user IDs and supports configurable prefixes and resource-role policy types.
  • Validates that the configured Casbin model defines the requested three-field resource role type before modifying policies.
foca/security/access_control/__init__.py
foca/security/access_control/enforcement.py
tests/security/access_control/test_enforcement.py
Provides a reference resource-role model and documents the new configuration, identity model, permissions behavior, and ownership workflow.
  • Adds wildcard authenticated-user access, global admin access, and resource-scoped owner/maintainer role examples.
  • Documents claim mapping, subject namespaces, opt-outs, helper usage, permissions API requirements, and operational caveats.
  • Links the access-control documentation from the project README.
foca/security/access_control/api/resource_role_model.conf
docs/access_control/README.md
README.md
Updates compatibility and regression coverage for CI and the new enforcement behavior.
  • Adds comprehensive mocked-token tests covering enforcement, group mapping, namespace collision prevention, permissions authorization, helper persistence, and incompatible models.
  • Updates PyJWT typing compatibility and replaces deprecated pkg_resources usage with importlib.resources.
tests/security/access_control/test_enforcement.py
tests/security/access_control/test_access_control_server.py
foca/security/auth.py
tests/test_foca.py
tests/test_files/conf_enforce_access_control_without_auth.yaml

Assessment against linked issues

Issue Objective Addressed Explanation
#258 Allow applications to enforce Casbin policies through configuration on authenticated API operations, using identity and group claims from already validated OIDC tokens, while retaining backward-compatible defaults and per-operation opt-outs. ✅
#258 Secure the permissions API so unauthenticated requests are rejected and policy checks prevent unauthorized users from managing permissions, including when general enforcement is disabled. ✅
#258 Provide documented public helpers and a reference model for resource-scoped roles, with examples and tests supporting app-specific ownership rules. ✅

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

uniqueg and others added 4 commits October 17, 2026 02:15
- Prefix user identifiers in rules with `access_control.subject_prefix`
  (default: `user:`) and group claim values without `group_mapping` with
  `group:`, so that a user identifier or identity provider group equal to
  a role name (e.g., `admin`, `owner`) no longer grants that role.
- Resource role helpers take and return unprefixed user identifiers, accept
  a `ptype` argument (default: `g2`) and raise a `ValueError` if the model
  does not define that role type with three fields, instead of silently
  writing meaningless rules (e.g., with the default model).
- `access_control.claim_identity` now defaults to `auth.claim_identity`.

Refs #258

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Recent PyJWT versions type `options` of `jwt.decode()` as a TypedDict,
which makes `mypy foca` (and thus CI) fail. Ignore the argument type, as
already done for `key`, to stay compatible with older PyJWT versions
allowed by `PyJWT~=2.4`.

Refs #258

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`pkg_resources` is no longer shipped with recent setuptools, which CI
installs, so test collection failed. Resolve the default model path the
same way `AccessControlConfig` does.

Refs #258

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@codecov

codecov Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (7ad5d3b) to head (31c20ee).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #259    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           20        22     +2     
  Lines          969      1087   +118     
==========================================
+ Hits           969      1087   +118     
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.

Restore 100% line coverage (required by Codecov): unprefixed subjects in
resource role listings, invalid group claim values, and the error logged
when enforcement is enabled without auth.

Refs #258

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg changed the title feat: config-driven access control enforcement with OIDC claims feat: config-driven access control Oct 17, 2026
@uniqueg
uniqueg marked this pull request as ready for review October 17, 2026 00:45
Copilot AI balanced review requested due to automatic review settings October 17, 2026 00:45
@uniqueg
uniqueg merged commit 568a58d into dev Oct 17, 2026
25 checks passed
@uniqueg
uniqueg deleted the worktree-issue-258 branch October 17, 2026 00:45

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

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

## Individual Comments

### Comment 1
<location path="foca/models/config.py" line_range="737" />
<code_context>
     user_headers: Optional[set] = None
+    enforce: bool = False
+    claim_identity: Optional[str] = None
+    subject_prefix: str = "user:"
+    claim_groups: Optional[str] = None
+    group_mapping: Optional[Dict[str, str]] = None
</code_context>
<issue_to_address>
**Role-name identities gain access**

When `subject_prefix` is configured as an empty string and a user's identity matches a privileged role, `_prefix_subject()` returns the identity unchanged, so the reference model treats an identity such as `admin` as the `admin` role and grants its permissions.

Reject an empty `subject_prefix` in `AccessControlConfig`.

Also at `foca/security/access_control/enforcement.py:69`.
</issue_to_address>

### Comment 2
<location path="foca/models/config.py" line_range="738" />
<code_context>
+    enforce: bool = False
+    claim_identity: Optional[str] = None
+    subject_prefix: str = "user:"
+    claim_groups: Optional[str] = None
+    group_mapping: Optional[Dict[str, str]] = None

</code_context>
<issue_to_address>
**Users inherit matching group access**

When `subject_prefix` is `group:` and an unmapped group value matches a user's identifier, `_prefix_subject()` gives the user the same subject as the group, so the user receives access granted to that group even when the token does not contain it.

Prevent user subjects from sharing the namespace used for unmapped group subjects.

Also at `foca/security/access_control/enforcement.py:19`, `foca/security/access_control/enforcement.py:69`, `foca/security/access_control/enforcement.py:106`, `foca/models/config.py:737`.
</issue_to_address>

### Comment 3
<location path="foca/foca.py" line_range="113-115" />
<code_context>
             cnx_app = register_openapi(
                 app=cnx_app,
                 specs=self.conf.api.specs,
+                enforce_access_control=(
+                    self.conf.security.auth.required
+                    and self.conf.security.access_control.enforce
+                ),
             )
</code_context>
<issue_to_address>
**Enforcement skipped with per-operation authentication**

When `access_control.enforce` is true, `auth.required` is false, and an API spec independently declares an operation requiring authentication, `auth.required` being false prevents `register_openapi` from installing the access-control resolver, even when an API operation declares authentication in its OpenAPI spec and Connexion validates its bearer token. That authenticated caller reaches the controller without a policy check.

Reject this conflicting configuration when secured operations are present, or enable the resolver and register the access-control backend for those operations regardless of `auth.required`.
</issue_to_address>

### Comment 4
<location path="foca/api/register_openapi.py" line_range="135-136" />
<code_context>
+    global_security = spec.get('security')
+    operations = set()
+    for path, path_item_object in spec.get('paths', {}).items():
+        for operation, operation_object in path_item_object.items():
+            if operation not in _OPERATION_OBJECT_FIELDS:
+                continue
+            if operation_object.get('x-foca-access-control') is False:
</code_context>
<issue_to_address>
**Referenced operations skip enforcement**

When an authenticated path item is defined through a `$ref`, `_get_enforced_operations` scans only methods present directly in each path item and does not resolve path-item `$ref`s. Connexion can register the referenced authenticated operations, but they are absent from the enforcement set, so their controllers run without policy checks.

Resolve path-item references before collecting enforced operations, or derive the enforcement set from the resolved operations Connexion registers.
</issue_to_address>

### Comment 5
<location path="foca/api/register_openapi.py" line_range="140" />
<code_context>
+                continue
+            if operation_object.get('x-foca-access-control') is False:
+                continue
+            if not operation_object.get('security', global_security):
+                continue
+            operations.add((path, operation))
</code_context>
<issue_to_address>
**Public operations reject anonymous callers**

When an operation's security requirements include an empty requirement object, such as `security: [{}]`, `_get_enforced_operations()` treats the non-empty security list as requiring authentication and wraps the operation. `enforce_access_control()` then rejects anonymous callers with 401, despite the specification allowing them.

Exclude operations with an empty security requirement alternative from the enforced operations set.

Also at `foca/api/register_openapi.py:141`.
</issue_to_address>

### Comment 6
<location path="foca/security/access_control/enforcement.py" line_range="67-69" />
<code_context>
+    return None if subject is None else str(subject)
+
+
+def _prefix_subject(subject: str) -> str:
+    """Add configured prefix to a subject, as used in policy rules."""
+    return f"{_get_access_control_config().subject_prefix}{subject}"
+
+
</code_context>
<issue_to_address>
**Existing policy grants stop matching**

When persisted rules contain unprefixed user identifiers when enforcement is enabled, `_prefix_subject()` checks the request using a prefixed subject, while `get_enforcer()` loads the existing rules unchanged. Casbin no longer matches those grants, so previously authorized users, including administrators relying on them to manage the permissions API, are denied.

Preserve compatibility with persisted unprefixed subjects or migrate those policy rows when enabling the prefix.

Also at `foca/security/access_control/enforcement.py:150`.
</issue_to_address>

### Comment 7
<location path="foca/security/access_control/enforcement.py" line_range="214" />
<code_context>
+            f"{operation.path}"
+        )
+        return Resolution(
+            function=enforce_access_control(resolution.function),
+            operation_id=resolution.operation_id,
+        )
</code_context>
<issue_to_address>
**Decorated routes reject allowed callers**

When config-driven enforcement wraps a controller already decorated with `check_permissions`, and the new policy allows a request that the legacy check rejects, `AccessControlResolver` wraps the controller, so the request must pass both the new claim-based check and the separate legacy check. The legacy check rejects the request, and the caller receives 403.

Avoid running the separate legacy permission check after config-driven enforcement has authorized the request.
</issue_to_address>

### Comment 8
<location path="foca/security/access_control/enforcement.py" line_range="69" />
<code_context>
+
+def _prefix_subject(subject: str) -> str:
+    """Add configured prefix to a subject, as used in policy rules."""
+    return f"{_get_access_control_config().subject_prefix}{subject}"
+
+
</code_context>
<issue_to_address>
**Decorated controllers reject namespaced rules**

When a controller uses `check_permissions` and its rules use the documented `subject_prefix` format, `check_permissions` still authorizes using the legacy header-based subject, without applying `subject_prefix`; rules created for this feature use `user:<id>`. A controller protected by `check_permissions` therefore denies a user whose namespaced rule would allow access, including when `access_control.enforce` is false and the decorator is the only enforcement path.

Make the legacy decorator evaluate subjects using the same namespacing and validated-claim rules, or keep its rule format explicitly separate and ensure the documentation and helper APIs do not imply the new format applies to it.
</issue_to_address>

### Comment 9
<location path="foca/api/register_openapi.py" line_range="106-108" />
<code_context>
         spec.connexion = {} if spec.connexion is None else spec.connexion
+        connexion_kwargs = spec.model_dump().get('connexion', {})
+        if enforce_access_control:
+            connexion_kwargs['resolver'] = AccessControlResolver(
+                resolver=connexion_kwargs.get('resolver'),
+                operations=_get_enforced_operations(spec_parsed),
+            )
         app.add_api(
</code_context>
<issue_to_address>
**Custom resolver fails at runtime**

When access control enforcement is enabled and `connexion.resolver` is configured in a Connexion-supported form other than a resolver instance, `connexion.resolver` is passed through as `resolver` without checking its type, then `AccessControlResolver.resolve()` calls `.resolve()` on it. If an app configures a resolver in a form accepted by Connexion but not as a resolver instance, resolving API operations fails and those endpoints are unavailable.

Normalize supported resolver classes or import strings into resolver instances before wrapping them, or reject unsupported values during configuration validation.
</issue_to_address>

### Comment 10
<location path="foca/security/access_control/enforcement.py" line_range="267-268" />
<code_context>
+    Raises:
+        ValueError: The model does not define resource-scoped roles.
+    """
+    return _get_resource_role_enforcer(ptype).add_named_grouping_policy(
+        ptype, _prefix_subject(subject), role, resource
+    )
+
</code_context>
<issue_to_address>
**Concurrent grants create duplicates**

When two requests concurrently grant the same subject, role, and resource while that grant is absent, each `add_resource_role()` call loads an enforcer before either inserts the rule, so both persist an identical row. `list_resource_roles()` then returns duplicate entries.

Make the grant operation atomic or enforce uniqueness for resource-role rows.
</issue_to_address>

### Comment 11
<location path="docs/access_control/README.md" line_range="302-306" />
<code_context>
+
+def postService(**kwargs):
+    service_id = ...  # create resource
+    add_resource_role(
+        subject=get_current_subject(),
+        role="owner",
+        resource=f"{request.path.rstrip('/')}/{service_id}",
+    )
+    return service_id
+
</code_context>
<issue_to_address>
**Resource and policy state diverge**

When resource creation or deletion and its separate ACL helper call fail or overlap, creation can persist a resource before its owner grant is written, leaving an orphaned resource; a retry can create another one. Deletion cleanup can also race with a grant and leave a stale rule that grants access if the path is reused.

Make resource lifecycle changes and their ACL updates atomic, including cleanup during deletion.

Also at `docs/access_control/README.md:312`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 11 findings to address first, and a flaw in the policy evaluation or token-claim handling could let an authenticated user reach protected API operations or manage permissions they should not access. Reverting would stop the new enforcement behavior, but it cannot undo data or access already exposed.

Blocking findings: foca/models/config.py:737, foca/models/config.py:738, foca/foca.py:115, foca/api/register_openapi.py:136, foca/api/register_openapi.py:140, and 6 more


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

Comment thread foca/models/config.py Resolved
Comment thread foca/models/config.py Resolved
Comment thread foca/foca.py Resolved
Comment thread foca/api/register_openapi.py Resolved
Comment thread foca/api/register_openapi.py Resolved
Comment thread foca/api/register_openapi.py Resolved
Comment thread docs/access_control/README.md Resolved

Copilot AI 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.

🟡 Changes recommended

Referenced paths bypass authorization, and optional-authentication and callable-resolver configurations regress.

3 open issues
What changed in this PR

Adds configuration-driven Casbin authorization using validated token claims, secures the permissions API, and provides resource-role helpers.

Changes:

  • Adds enforcement configuration, claim-based identity, and group mapping.
  • Introduces resource-role helpers and a reference policy model.
  • Documents usage and adds regression tests and compatibility fixes.
File Description
tests/​test_foca.py Tests enforcement without authentication configuration.
tests/​test_files/​conf_enforce_access_control_without_auth.yaml Adds disabled-authentication fixture.
tests/​security/​access_control/​test_enforcement.py Tests enforcement, claims, permissions, and helpers.
tests/​security/​access_control/​test_access_control_server.py Replaces deprecated resource lookup.
README.md Links configuration-driven enforcement documentation.
foca/​security/​auth.py Adds PyJWT type-check suppression.
foca/​security/​access_control/​register_access_control.py Enforces permissions-API authorization.
foca/​security/​access_control/​enforcement.py Implements enforcement and resource-role helpers.
foca/​security/​access_control/​constants.py Identifies the reference model.
foca/​security/​access_control/​api/​resource_role_model.conf Defines resource-scoped authorization.
foca/​security/​access_control/​api/​access-control-specs.yaml Requires validated bearer authentication.
foca/​security/​access_control/​__init__.py Exports public helpers.
foca/​models/​config.py Adds access-control configuration fields.
foca/​foca.py Connects configuration to enforcement.
foca/​api/​register_openapi.py Wraps selected operations with authorization.
docs/​access_control/​README.md Documents configuration, roles, and permissions security.

Review effort: Balanced

Comment thread foca/api/register_openapi.py Resolved
Comment thread foca/api/register_openapi.py Resolved
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.

Access control: config-driven enforcement with OIDC claims, secured permissions API

2 participants