Repository navigation
feat(access-control): add field-based ownership - #456
Conversation
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]>
Reviewer's GuideIntroduces 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 ownershipsequenceDiagram
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
Flow diagram for owner attribution and filteringflowchart 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]
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
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 foradd_owner()(user an allowed service client acts for, otherwise the service client by client ID, otherwise the user byclaim_identity). Raises401if 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 asis_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.., no leading$).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 indocs/migration-0.18.md, API reference.Deviation from the issue: the owner has a
typebesidesissandsub, so that users and service clients stay apart as they do in rule-based ownership (user:vsclient:); 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 .: cleanmypy foca: no issuesmkdocs build --strict: OKast-grep scan: clean;semgrep --config=.semgrep --error ...: no findingsCI: 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 whatresource_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:
Enhancements:
Documentation:
Tests: