Skip to content

feat(access-control): add field-based ownership - #456

Merged
uniqueg merged 5 commits into
devfrom
feat/owner-field-455
Oct 24, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/owner-field-455

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Opt-in ownership by document field, for apps whose resources are never shared, next to the existing rule-based resource ownership (unchanged, still the default):

  • set_owner_field(document, field="owner", on_behalf_of=None) sets the owner in the document before it is stored, so the owner is written atomically with the resource: {"iss": ..., "type": "user" | "client", "sub": ...} — the token's issuer, and the subject the request is attributed to exactly as for add_owner() (user an allowed service client acts for, otherwise the service client by client ID, otherwise the user by claim_identity). Raises 401 if the caller cannot be identified.
  • owner_filter(field="owner", on_behalf_of=None) returns a MongoDB filter for the caller's documents, {} for admins with the same semantics as is_admin()/resource_filter() (client's own admin status; users' admin rights don't carry over to clients acting for them; named users validated also for admins), and a match-none filter for callers that cannot own documents.
  • Field names are restricted to top-level names (no ., no leading $).
  • Docs: new section "Ownership by document field" in docs/access-control.md (helpers, enforcing in controllers with a 404 for others' resources, index recommendation, when to choose it over rule-based ownership, what is not covered: no sharing unless the app adds it; FOCA's role endpoints, list_roles()/list_subject_roles() and self-service don't cover such resources), entry in docs/migration-0.18.md, API reference.

Deviation from the issue: the owner has a type besides iss and sub, so that users and service clients stay apart as they do in rule-based ownership (user: vs client:); without it, a client allowed to act for users could name another client as "user" and get its documents (adversarial review finding).

Verification

  • coverage run -m pytest (with MongoDB 7 on port 12345): 2071 passed, coverage 100%
  • ruff check ., ruff format --check .: clean
  • mypy foca: no issues
  • mkdocs build --strict: OK
  • ast-grep scan: clean; semgrep --config=.semgrep --error ...: no findings

CI: all checks passed (unit tests on Python 3.11–3.14 with MongoDB 7.0/8.0 and lowest direct dependencies, lint/type-check/build, integration tests, chart install on kind, image scans, CodeQL, codecov, Read the Docs).

Declined review findings

  • Issuer of users that service clients act for: the owner gets the issuer of the client's token, as the user's issuer is unknown; with several trusted issuers, a user of another issuer would not see documents created for them. Documented as an assumption; selecting the user's issuer would need new configuration (rule-based ownership ignores issuers of users entirely).

  • Building _get_owner() on _get_creator() instead of _get_listing_subjects() (quality, low): _get_listing_subjects() is what resource_filter() uses, so setting and filtering pick the subject the same way; _get_creator() raises for anonymous callers, which the filter must not.

Open questions

None.

Closes #455

🤖 Generated with Claude Code

Summary by Sourcery

Support opt-in ownership stored directly in resource documents for applications whose resources are not shared.

New Features:

  • Add opt-in field-based document ownership with helpers to assign an authenticated owner and filter resources by that owner.

Enhancements:

  • Preserve distinct user and service-client ownership identities, including issuer information and service-client impersonation semantics.
  • Validate owner field names and provide safe behavior for unidentified callers and administrators.

Documentation:

  • Document field-based ownership, migration guidance, API references, usage patterns, limitations, and indexing recommendations.

Tests:

  • Add comprehensive coverage for field ownership, filtering, impersonation, administrators, validation, and unidentified callers.

uniqueg and others added 4 commits October 24, 2026 05:49
Add opt-in helpers for apps whose resources are never shared: store the
creator in a field of the resource document, as issuer and subject,
written together with the document (set_owner_field()), and filter
documents by owner, with the admin bypass of resource_filter()
(owner_filter()). No policy rules are stored per resource.

Refs #455

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Describe the helpers, how to enforce ownership in controllers, and when
to choose it over rule-based resource ownership.

Refs #455

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Store the type of the owning subject (user or client) with the owner,
and identify service clients by client ID, as add_owner() does, so
that clients acting for users cannot get the documents of other
clients by naming them as users. Document that users that clients act
for are assumed to be of the client's issuer, and share the error for
unidentified subjects.

Refs #455

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Store a copy of the owner in documents, spell out the filtered owner
fields, and test that service clients are identified by client ID.

Refs #455

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

sourcery-ai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces opt-in field-based ownership for unshared resources by storing an issuer-qualified user/client owner in each document and providing matching MongoDB filters, while preserving existing rule-based ownership as the default. The implementation reuses established attribution and admin semantics, validates safe top-level fields, exposes the new helpers, adds extensive isolation and edge-case tests, and documents integration and migration guidance.

Sequence diagram for field-based resource ownership

sequenceDiagram
    participant Caller
    participant Controller
    participant AccessControl
    participant MongoDB

    Caller->>Controller: CreateTask(body)
    Controller->>AccessControl: set_owner_field(task, field, on_behalf_of)
    AccessControl->>AccessControl: _get_listing_subjects(on_behalf_of)
    AccessControl->>AccessControl: _get_claims()
    AccessControl-->>Controller: owner {iss, type, sub}
    Controller->>MongoDB: insert_one(task with owner)

    Caller->>Controller: GetTask(id)
    Controller->>AccessControl: owner_filter(field, on_behalf_of)
    AccessControl->>AccessControl: _get_owner(on_behalf_of)
    AccessControl-->>Controller: MongoDB owner filter
    Controller->>MongoDB: find_one(id plus owner filter)
    MongoDB-->>Controller: Owned document or none
Loading

Flow diagram for owner attribution and filtering

flowchart TD
    A[Request] --> B[_get_owner]
    B --> C{Caller can be attributed?}
    C -->|No| D[owner_filter returns match-none filter]
    C -->|Yes| E{Caller is admin?}
    E -->|Yes| F[owner_filter returns empty filter]
    E -->|No| G[Build issuer-qualified filter]
    G --> H[owner.iss plus owner.type plus owner.sub]
    B --> I[set_owner_field writes owner before storage]
    I --> J[Atomic resource document write]
Loading

File-Level Changes

Change Details Files
Added opt-in document-field ownership helpers that atomically record and query the attributed owner.
  • Store issuer, subject type, and subject identifier in a configurable top-level document field.
  • Generate MongoDB ownership filters, including match-none behavior for unidentified callers and unrestricted filters for admins.
  • Reuse existing service-client, on-behalf-of, identity, issuer, and admin semantics.
  • Export the helpers and define the default owner field constant.
foca/security/access_control/ownership.py
foca/security/access_control/__init__.py
foca/security/access_control/constants.py
Added comprehensive validation and regression coverage for field-based ownership behavior.
  • Validate field names against MongoDB nested-field and operator syntax.
  • Cover users, service clients, on-behalf-of attribution, issuer/type isolation, admins, anonymous callers, invalid callers, and custom fields.
  • Verify ownership is not represented by policy roles and prevents cross-client impersonation.
tests/security/access_control/test_ownership.py
Documented the new ownership model, migration impact, API exposure, and controller enforcement pattern.
  • Explain atomic creation, filtered reads/listings, indexing, 404 handling, limitations, and when to choose field ownership over rule-based ownership.
  • Add migration guidance and reference entries for the new helpers.
docs/access-control.md
docs/migration-0.18.md
docs/reference.md

Assessment against linked issues

Issue Objective Addressed Explanation
#455 Add opt-in helpers to set a resource document’s owner atomically and build a MongoDB filter for the caller’s owned resources, including identity, service-client, admin-bypass, and missing-identity behavior. ✅
#455 Document when and how to use field-based ownership, its limitations and indexing guidance, and add a migration-guide entry. ✅
#455 Keep rule-based ownership unchanged and the default, with tests covering the new helpers’ key caller scenarios. ✅

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 Oct 24, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #456   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           28        28           
  Lines         3238      3266   +28     
=========================================
+ Hits          3238      3266   +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 October 24, 2026 04:13

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

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

## Individual Comments

### Comment 1
<location path="foca/security/access_control/ownership.py" line_range="884" />
<code_context>
+        ValueError: The field is empty, names a nested field (with `.`),
+            or starts with `$`, which MongoDB reserves for operators.
+    """
+    if not field or "." in field or field.startswith("$"):
+        raise ValueError(
+            f"Invalid owner field '{field}': expected a top-level field name "
</code_context>
<issue_to_address>
**NUL owner fields break requests**

When the configured owner field contains a NUL byte, `_check_owner_field` accepts the NUL byte, so `set_owner_field` writes an invalid BSON key and `owner_filter` builds an invalid query key; PyMongo rejects serialization and resource writes or filtered queries fail.

Reject field names containing a NUL byte in `_check_owner_field`.
</issue_to_address>

### Comment 2
<location path="foca/security/access_control/ownership.py" line_range="965" />
<code_context>
+    if owner is None:
+        raise _unidentified()
+    # A copy, so that changing the returned owner does not change the document
+    document[field] = dict(owner)
+    return owner
+
</code_context>
<issue_to_address>
**Using `_id` replaces resource identity**

When an app passes `field="_id"` to `set_owner_field()`, `set_owner_field()` writes the owner over the document’s MongoDB primary key. When documents rely on MongoDB’s generated `_id`, repeated creates by the same owner then reuse the same `_id` and fail with a duplicate-key error; an existing `_id` is also discarded.

Reject `_id` as an owner field, or otherwise ensure setting ownership cannot replace the document’s primary key.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and if the ownership filter misidentifies a caller or omits an ownership constraint, callers could read other users’ documents; reverting would stop future access but could not undo data already exposed. The feature is opt-in, so this risk is limited to apps that use these helpers.

Blocking findings: foca/security/access_control/ownership.py:884, foca/security/access_control/ownership.py:965


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

Refuse owner fields that would replace a document's primary key or that
BSON cannot encode.

Refs #455

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit d8c3159 into dev Oct 24, 2026
26 checks passed
@uniqueg
uniqueg deleted the feat/owner-field-455 branch October 24, 2026 04:31
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(access-control): add field-based ownership

1 participant