Repository navigation
feat(auth)!: always namespace subjects by issuer - #773
Conversation
Subjects are namespaced by their issuer (`<namespace>|<subject>`, by default with the issuer as namespace) also if only one issuer is trusted, so that trusting another issuer later changes nothing about what is stored, as for owners in documents. `namespace: ""` keeps an issuer's subjects bare, e.g., for apps that stored them before. To migrate stored rules, `foca namespace-subjects <namespace>` rewrites the bare users of stored rules that aren't configured (with `--dry-run` to count them). On startup, configured and stored rules naming users that no trusted issuer has are warned about. The petstore access control example routes namespaced users (which contain slashes) with `format: path` and matches them with `*`. BREAKING CHANGE: subjects of a single trusted issuer are namespaced by the issuer; stored bare users no longer apply. See "Migrating to 0.23.0". Closes #631 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review findings of the namespacing of stored subjects: - `namespace_users()` keeps the role of a bare user on a resource if the namespaced user already has a role there (e.g., changed since the upgrade), so that the rewrite doesn't add a second role, and reports rules whose users already start with the namespace, which bare subjects like `auth0|123` can't be told apart from. - The startup check of stored rules looks at subjects only. - The owner-field snippet of the migration guide only rewrites owners of the issuer; the docs warn of namespaces that subjects start with. - Tests share one bare issuer fixture, and cover `/me` with the default namespace. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Check resource role conflicts against the roles that namespaced users had before the run, so that several roles of a bare user on the same resource are all rewritten, and dry runs count as real runs do. Only stored, non-configured g* rules on a resource count. Users starting with the namespace of any trusted issuer count as ambiguous, not only those of the target namespace. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideData structuresDefault issuer namespaces in authentication configuration make the issuer part of the subject identity, with an explicit bare-subject opt-out.
The access-control constants module now owns the namespace separator used by subject identities and policy rules.
APISubject-namespacing helpers and current-user accessors now expose issuer-namespaced identities by default.
The petstore permissions endpoints accept issuer-namespaced user identifiers in path parameters.
The CLI adds the
ImplementationThe policy adapter detects unknown users and migrates stored rules while handling configured rules, invalid values, conflicts, ambiguity, and change tracking.
Access-control registration validates configured users against trusted issuer namespaces and warns about unknown users in stored rules.
ConfigurationThe petstore example configures a wildcard permissions-user route to accommodate namespaced identifiers containing slashes.
DocumentationAccess-control guidance updates policy examples, subject formats, startup checks, permissions paths, and API response examples for issuer-namespaced users.
Authentication documentation explains the always-namespaced default, the compatibility opt-out, and the migration implications of trusting issuers.
CLI documentation describes the migration command, its safety behavior, and how to run or recover it.
Startup-check documentation describes validation and warnings for configured and stored rules naming users without a trusted namespace.
Authentication configuration documentation describes default namespaces and the bare-subject compatibility setting.
Deployment guidance includes unknown-user policy rules among startup warnings and errors.
The 0.23.0 migration guide covers identity changes, stored-rule and application-data migration, and compatibility options.
Plugin documentation updates principal and delegated-user identity descriptions to reflect issuer namespacing.
The petstore README updates its examples and instructions for issuer-namespaced users and slash-containing permission paths.
TestsExample tests use issuer-namespaced identities in pet ownership and permissions requests.
Configuration tests verify issuer namespaces default to issuer values and enforce the namespace constraints.
Shared access-control test fixtures explicitly retain bare subjects so existing tests continue exercising their intended behavior.
Adapter tests cover unknown-user detection and migration behavior, including conflicts, ambiguous identities, dry runs, and concurrent changes.
Enforcement tests verify current subjects are namespaced by default for a single trusted issuer.
Enforcer-cache tests retain the bare-subject fixture for the behaviors under test.
The
Ownership tests verify namespaced identities in stored roles and owner fields, including users named by service clients.
Ownership-server tests keep existing bare-subject test setup explicit.
Path-helper tests preserve existing bare-subject behavior with an explicit fixture.
Registration tests cover configured-user validation, custom and copied models, and stored-user warnings.
Service-client tests retain the bare-subject fixture for existing behavior checks.
Authentication tests cover namespaced defaults, explicit namespaces, the bare opt-out, and the no-issuer case.
Optional-token tests explicitly preserve bare subjects for their existing scenarios.
CLI tests exercise migration reporting, rewrites, refusal conditions, and dry-run behavior against MongoDB.
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 #773 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 74 74
Lines 9651 9788 +137
==========================================
+ Hits 9651 9788 +137
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:
|
Configured policy rules naming users that no trusted issuer has (e.g., bare users after the upgrade to namespaced subjects) now make the app refuse to start instead of only logging a warning, so that a missed migration of configured admin rules can't go unnoticed. The error names the positions of the rules, not the users, and says how to fix the configuration. The output of `foca namespace-subjects` now says that stored configured rules with bare users are replaced on startup or by `sync-policies`. Docs and the 0.23.0 migration guide are updated; the guide also marks `namespace: ""` as an opt-out for existing deployments. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`namespace: ""` stays as an explicit opt-out for one issuer, so that existing deployments can upgrade without moving data. Document it as such, to be reconsidered for FOCA 1.0. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Custom Casbin models may match users in other ways (e.g., `user:*` with `keyMatch`), so configured rules naming users that no trusted issuer has only fail startup with the models that FOCA ships; with a custom model, a warning is logged. Named rules are named in the error instead of their positions in the merged list. Also from review: the `Raises` section of `register_access_control()` covers the new error, the message drops the `foca namespace-subjects` hint (the command can't run while configured rules are bare), tests drop an unused fixture and check positions on registration, and doc paragraphs are reflowed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Apps that copied a model that FOCA ships (e.g., before `foca:<file>` existed) match subjects in the same way, so configured rules naming unknown users fail their startup, too. Models are compared ignoring whitespace. Adds direct tests of the model detection for all shipped models and copies, and restructures the startup-check docs for users (configured rules, custom models, stored rules). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…jects # Conflicts: # docs/migration-0.23.md
Linked issuesChecked at commit 6bc1493 #631 feat(auth)!: always namespace subjects by issuer · 6 of 6 met
|
There was a problem hiding this comment.
Hey - I've found 6 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="958" />
<code_context>
+ rewritten = invalid = conflicting = 0
+ try:
+ for document in self._collection.find(
+ {CONFIGURED_FIELD: {"$ne": True}, **_user_query(pattern)}
+ ):
+ changed = {
</code_context>
<issue_to_address>
**Bare-user grants disappear**
When a legacy instance writes or changes a bare-user rule while the migration is running, `namespace_users()` can miss a rule inserted after its scan, or count a conditional update as rewritten when `update_one()` matched nothing; the rule remains bare and stops applying to namespaced users.
Coordinate policy writes with the migration, rescan or retry missed rules, and count a rule as rewritten only when its update succeeds.
Also at `foca/security/access_control/foca_casbin_adapter/adapter.py:976-984`.
</issue_to_address>
### Comment 2
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="954-973" />
<code_context>
+ resource_roles = self._namespaced_resource_roles(namespaced)
</code_context>
<issue_to_address>
**Revoked roles return**
When a namespaced user’s resource role changes, or policy is written, while the migration is running, `namespace_users()` checks bare rules against a stale `resource_roles` snapshot, so it rewrites a role that was just revoked or demoted; concurrent writes can also leave duplicate or ineffective roles.
Coordinate policy writes with the migration and refresh the resource-role conflict check before rewriting each bare rule.
</issue_to_address>
### Comment 3
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="960-966" />
<code_context>
+ for document in self._collection.find(
+ {CONFIGURED_FIELD: {"$ne": True}, **_user_query(pattern)}
+ ):
+ changed = {
+ field: f"{prefix}{namespace}{NAMESPACE_SEPARATOR}"
+ f"{value[len(prefix) :]}"
+ for field in _VALUE_FIELDS
+ if isinstance(value := document.get(field), str)
+ and regex.match(value)
+ }
+ try:
+ for value in changed.values():
</code_context>
<issue_to_address>
**Prefixed roles are mistaken for users**
When a valid role name in a `g` rule starts with the configured user prefix, such as `user:reviewer`, `namespace_users()` rewrites every rule value starting with `subject_prefix`, including a role value in a `g` rule, so role inheritance stops matching after migration. The configured-rule check also treats that role as an unknown user and refuses startup.
Only treat subject-position values as users, or consistently reject roles beginning with `subject_prefix` when validating configured and stored rules.
Also at `foca/security/access_control/register_access_control.py:243-244`.
</issue_to_address>
### Comment 4
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="954-973" />
<code_context>
+ resource_roles = self._namespaced_resource_roles(namespaced)
</code_context>
<issue_to_address>
**Retry skips remaining roles**
When a run rewrites one of several bare resource-role rules and stops before rewriting the rest, `_namespaced_resource_roles()` sees the role rewritten by the failed run as a pre-existing conflict, so the retry skips the remaining bare roles and they no longer apply to the namespaced user.
Distinguish roles rewritten by an earlier migration attempt from genuine pre-existing conflicts when retrying.
</issue_to_address>
### Comment 5
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="987-988" />
<code_context>
+ conflicting += 1
+ continue
+ rewritten += 1
+ if not dry_run:
+ # Only if unchanged meanwhile; another run rewrites it
+ self._collection.update_one(
+ {
+ "_id": document["_id"],
+ **{field: document[field] for field in changed},
+ },
+ {"$set": changed},
+ )
+ finally:
+ if not dry_run:
+ self.mark_changed()
+ configured = self._collection.count_documents(
+ {
</code_context>
<issue_to_address>
**Interrupted migration leaves stale caches**
When the migration process is killed after updating one or more rules but before reaching its `finally` block, `namespace_users()` marks rules changed only after its rewrite loop finishes or raises a Python exception. A process termination after some MongoDB updates but before this marker leaves other running instances with cached bare rules and no change record to trigger a reload, so their authorization decisions stay stale.
Make progress visible to cached enforcers before or during the rewrite, or ensure the migration runs with no other active instances and requires them to restart afterward.
</issue_to_address>
### Comment 6
<location path="foca/security/access_control/register_access_control.py" line_range="300" />
<code_context>
+ path = Path(model)
+ if not path.is_file():
+ return False
+ content = path.read_text(encoding="utf-8").split()
+ packaged = files(ACCESS_CONTROL_BASE_PATH)
+ return any(
</code_context>
<issue_to_address>
**Commented models are misclassified**
When a copy of a shipped model has added or changed comments, `_is_packaged_model()` compares comments as tokens and treats the copy as custom; `_check_policy_users()` then only warns, and configured rules for unknown users apply to nobody.
Compare model behavior without treating comments as significant.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 6 findings to address first, and the new default changes every single-issuer user’s authorization identity, so existing grants and ownership records using bare subjects stop matching unless deployments opt out or migrate them. Reverting restores the old identity mapping but does not undo policy rules rewritten by the migration command or owner values applications migrate themselves.
Blocking findings: foca/security/access_control/foca_casbin_adapter/adapter.py:958, foca/security/access_control/foca_casbin_adapter/adapter.py:973, foca/security/access_control/foca_casbin_adapter/adapter.py:966, foca/security/access_control/foca_casbin_adapter/adapter.py:973, foca/security/access_control/foca_casbin_adapter/adapter.py:988, and 1 more
- `namespace_users()` counts a rule as rewritten only if the conditional update modified it, not if it changed meanwhile. - Copies of shipped models are compared without comments, too. - `docs/cli.md` says when to run `namespace-subjects` (no writes by old instances), and how to recover from interrupted runs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Subjects are now namespaced by issuer (
<namespace>|<subject>, by default with the issuer as namespace) also when only one issuer is trusted. Trusting a second issuer later then changes nothing that is stored, which matches field-based ownership (#455). Breaking change: the next release (0.23.0) has a migration section.AuthConfig.get_namespaces()defaults every issuer's namespace to the issuer.namespace_subject(),get_current_subject(),get_on_behalf_of_user(), the owners thatadd_owner()/set_owner_field()store, pluginPrincipalidentities and audit users all follow from that.namespace: ""still keeps one issuer's subjects bare, as an explicit opt-out for existing deployments (see "Decisions"). An issuer that is its own namespace has to meet the namespace rules (no|, comma or line break, at most 256 characters) even when it is the only issuer; otherwise the app refuses to start and asks for anamespace.foca namespace-subjects <namespace> [--dry-run]. It rewrites bare users in stored, non-configured policy rules (any value, e.g.g2owners) touser:<namespace>|<subject>. It is idempotent (users that already start with a trusted namespace and|are skipped), keeps rules whose result would be invalid, keeps roles of bare users on resources on which the namespaced user already had a stored role before the run (so roles changed since the upgrade aren't added to; several roles of one bare user on a resource are all rewritten, and dry runs count as real runs), counts configured rules without changing them, and marks rules as changed so that cached enforcers reload. It refuses an unknown or empty namespace, and refuses to run when an issuer keeps its subjects bare. It follows cloud-registry'snamespace_subjects, limited to what FOCA stores. App data (e.g. owner fields) is covered in the migration guide, with amongoshsnippet.ValueError) if configuredpoliciesname users that no trusted issuer has, so that a missed migration of configured admin rules can't go unnoticed. The error names the rules (by name for named rules, otherwise by position), not the users, and says how to fix the configuration (namespace the users, or keep the issuer's subjects bare withnamespace: ""). With a custommodel(neither one that FOCA ships nor a copy of one, compared ignoring whitespace), which may match users in other ways (e.g.,user:*withkeyMatch), it stays a warning. Stored rules with such users get a warning, in the same place as the existing stored-group-subject check.foca namespace-subjectsreports stored configured rules with bare users as replaced on startup or bysync-policies.docs/migration-0.23.md(new section "Subjects are always namespaced by issuer")./pets/{id}/permissions/users/{userId}route now usesformat: path, and the rule uses/users/*instead of:userId(the pattern the access-control docs already describe). README and test updated.NAMESPACE_SEPARATORmoved tofoca.security.access_control.constantsto avoid an import cycle.foca.models.configstill re-exports it (cloud-registry imports it from there).Tests: the shared access-control test fixtures, which name users bare throughout, now trust their issuer with
namespace: "". Changing hundreds of expectations would hide the behaviour under test in noise. New tests cover the default: one issuer, several issuers, a setnamespace, the bare opt-out, no issuers,get_current_subject(), owners viaadd_owner()andset_owner_field(), service clients acting for users, the adapter methods (in-memory and on real MongoDB, to check the lookahead regex in$regex), the startup warnings and the CLI command.How it was verified
coverage run -m pytestwith MongoDB 7.0 on localhost:12345: 5198 passed, 2 skipped (after merging dev);coverage report: 100%ruff check,ruff format --check,mypy: cleanast-grep scan --error=flask-import,semgrep scan --config .semgrep --error: cleanmkdocs build --strict: built without warningstests/integration_tests.py,tests/integration_gateway_tests.py); CI runs them. Neither names users in rules or paths.Declined review findings
Two rounds of adversarial and quality review ran before the first push, and two more for the decided changes (round 1: custom models, named rules, docstrings, message, doc wording; round 2: copies of shipped models, direct tests of the model detection, doc structure and wrapping); confirmed findings were fixed (e.g. conflicting resource roles, counts of users that already start with a trusted namespace). Declined or partly addressed:
NAMESPACE_SEPARATORfromfoca.models.config: kept, as apps import it from there.v0) only, not all values: limited rather than removed, to keep the check a single cheap query on startup; the CLI command covers all values.user:would fail startup with a packaged model: kept, as resources of the packaged models are paths and roles can't start with the prefix; this matches the earlier warning's scope.create_celery_app()fails on configured unknown users: it runs the samecheck_access_control_config(), which is tested.Sourcery (6 threads, all answered and resolved):
namespace_users()counts a rule as rewritten only if the conditional update modified it; copies of shipped models are compared without comments, too.docs/cli.md): runnamespace-subjectswhile no old instance writes rules; rerun after interrupted runs (it marks rules as changed again); roles kept because an interrupted run already namespaced another role of the user on that resource need to be fixed by hand (a persistent marker would let later bare rules add to migrated roles).subject_prefixas roles (FOCA's roles can't start with it, so such values name users).Decisions
Decided by the maintainer on 2026-11-15:
namespace: ""stays as an explicit opt-out for a single issuer, so that existing deployments (e.g., cloud-registry) can upgrade without moving data. Documented as such (authentication,security.authreference, model docstring, migration guide), to be reconsidered for 1.0.format: path,*rules; proxies that merge slashes break them) are accepted as the default for now. A follow-up issue (take the user from the body or query) is drafted, not yet posted.Open questions
None.
Closes #631
🤖 Generated with Claude Code