Skip to content

Add a library-maintained by-role holder index - #47

Merged
FlyOverCoderKY merged 2 commits into
mainfrom
claude/project-thread-rvj5y2
Nov 2, 2026
Merged

FlyOverCoderKY merged 2 commits into
mainfrom
claude/project-thread-rvj5y2

Conversation

@FlyOverCoderKY

Copy link
Copy Markdown
Contributor

Requested by Nathan · project thread

Summary

This PR closes the remaining storage request in #24: a by-role index that the library maintains itself. It follows the superset-with-verification recipe that docs/STORAGE.md already documents.

  • New port RoleHolderReader.listActiveRoleAssignmentsByRole(role, scope). Lists every active assignment of one role in one exact scope, across principals. Results are ordered by grant time and then by assignment ID. Every row is checked against the authoritative lifecycle record before it is reported.
  • New collection authorization_role_holders. Its partition key is (application, role, scope). grantRoleAssignmentWithAudit writes an immutable row before the grant transaction, once the assignment-ID pointer check passes. Rows are never deleted, so a revoked assignment or a refused grant leaves a row that reads back as nothing.
  • New RoleHolderIndexMaintenance.rebuildRoleHolderIndex(). Backfills rows for assignments granted before this change. It scans the existing assignment pointers, is idempotent, and returns { recorded }.
  • Admin package. createRoleAdministration no longer requires holderIndex when the store implements RoleHolderReader. The options type is now a union, and construction throws a TypeError if neither the store nor a holderIndex can answer by-role queries. If a host passes a holderIndex, that index is still the one used.

The first-class concurrency-safe guard primitive stays declined, for the reason given on #24. The admin service still handles concurrency the same way: it serializes revokes, re-checks, and compensates.

Closes #24.

Authorization and compatibility impact

  • RoleHolderReader is a separate port. RoleAssignmentReader is unchanged, so hosts that implement the storage ports themselves don't need any changes.
  • InMemoryStorageAdapter, the type returned by createRoleStore, gains the two new interfaces. This only adds to the type.
  • Migration: in a durable store, assignments granted before this release have no index row until rebuildRoleHolderIndex() runs once. Until then those assignments are missing from by-role results. A last-administrator guard that relies on the store's index would then refuse a revoke rather than allow it, so the failure is closed. Hosts that pass their own holderIndex are unaffected.
  • The version is not bumped; RELEASE_NOTES.md has an Unreleased section instead.

Validation

  • pnpm run check (typecheck plus the API docs check; the docs under docs/api were regenerated)
  • pnpm test: 572 tests pass and 1 fails. The failure is in tests/release-packages.test.ts > accepts only an approved signed annotated tag, because the test sandbox has no ssh-keygen (spawnSync ssh-keygen ENOENT). The same test fails on main in this environment.
  • pnpm run format:check

New tests:

  • Storage: order across principals; grant → revoke → regrant under a new ID; a refused grant is never reported; isolation by scope and by application; role names that contain the key separator; rebuild after rows are dropped, including fail-closed behavior while rows are missing, and idempotency.
  • Admin: the guard with no host index (including a holder in a different scope with the same role name); serialized dual revoke; cross-instance compensation using the store's index; a supplied host index is preferred; construction error when neither index is available.

Checklist

  • New permission-granting behavior includes allow and deny tests.
  • Public API changes include documentation and migration impact.
  • No provider-specific types leaked into core contracts.
  • No secrets, credentials, or customer data are included.

Generated by Claude Code

The storage adapters now maintain the by-role index that #24 left open,
following the superset recipe in docs/STORAGE.md: an immutable holder row
is written before every audited grant, rows are never deleted, and every
read verifies each row against the authoritative lifecycle record.

- RoleHolderReader.listActiveRoleAssignmentsByRole(role, scope) lists
  active holders of one role in one exact scope across principals. It is a
  separate port, so hosts implementing RoleAssignmentReader are unaffected.
- RoleHolderIndexMaintenance.rebuildRoleHolderIndex() backfills rows for
  assignments granted before the index existed; it is idempotent.
- The admin service no longer requires a host holderIndex when its store
  implements RoleHolderReader. A supplied holderIndex is still preferred,
  so existing hosts keep their current behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y48RJvxtcZ7PZaeBbkM8V4
@FlyOverCoderKY FlyOverCoderKY self-assigned this Nov 2, 2026
@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

OpenRouter review posted (clean). #47 (review)

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
🔒 Security Review ✅ Completed 2026-11-02T14:35:10.878338Z 4b00ee6 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions github-actions 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.

OpenRouter pull-request review

Verdict: issues
Scope: full-pr (full-pr)
Mode: initial
Commit: 4b00ee680bea6e2d87af57fe70a1e7be67a6c887
Judge: openai/gpt-5.6-luna
Cost: $0.4847 (lanes $0.4788 + judge $0.0059)

Lanes

  • meta/muse-spark-1.2: ok (3 finding(s), 54.3s, 240906+10098 tokens (565 cached), 4 tool round(s), via Meta, $0.34)
  • z-ai/glm-5.3-flash: ok (10 finding(s), 300.8s, 2598351+56978 tokens (2288768 cached), 36 tool round(s), via Parasail, $0.14)

Warning

z-ai/glm-5.3-flash: coverage claims 1 finding(s) in 'RELEASE_NOTES.md' but 0 were reported

Warning

z-ai/glm-5.3-flash: coverage claims 1 finding(s) in 'docs/ADMINISTRATION.md' but 0 were reported

Findings

🔵 Issue 1 — Admin construction accepts invalid holderIndex shape, delaying failure to guard time

packages/admin/src/index.ts:307 · nit · identified by meta/muse-spark-1.2

Concrete failure: a JavaScript caller bypassing types calls createRoleAdministration({ store: plainStore, holderIndex: null }) or { holderIndex: { record: 'not a function' } }. The constructor only validates holderStore.listActiveRoleAssignmentsByRole when holderIndex === undefined; it never validates that a supplied holderIndex is an object with record and listByRole functions.

The error then surfaces later inside anotherActiveHolderExists as holderIndex!.listByRole is not a function or inside recordHolder during assignRole/revokeRole compensation, which is harder to attribute to construction and bypasses the intended TypeError: role administration needs a store with listActiveRoleAssignmentsByRole or a host holderIndex fail-fast.

Evidence: packages/admin/src/index.ts:307-324 narrows only the store path; the holderIndex branch is trusted. recordHolder (:326) guards with if (holderIndex !== undefined) and anotherActiveHolderExists (:354) calls holderIndex!.listByRole without shape check.

Checked: type union in RoleAdministrationOptions requires holderIndex when store is plain, but JS callers and as never casts (tested in packages/admin/src/index.test.ts:739) bypass it. No runtime typeof holderIndex.record !== 'function' guard exists.

🔵 Issue 2 — viewGrants self-heal comment overclaims for store-maintained index

packages/admin/src/index.ts:462 · nit · identified by meta/muse-spark-1.2

Concrete failure: an operator reading packages/admin/src/index.ts:462-476 sees the comment "Self-heal the superset: an assignment the store reports but the index misses (a grant that predates the index) is re-recorded" and assumes calling viewGrants will heal the new store-maintained authorization_role_holders collection just as it heals the host RoleHolderIndex.

In reality recordHolder (:326-330) is a noop when holderStore !== undefined (the store-index path), so viewGrants never writes roleHolders rows. Missing rows for pre-index assignments stay missing until rebuildRoleHolderIndex() runs, and the guard continues to refuse (fail-closed) until then, contrary to the comment's promise.

Evidence: recordHolder early-returns when holderIndex === undefined; holderStore path is documented in docs/STORAGE.md:119-130 as requiring an explicit rebuild, but the comment is not scoped to the host-index path.

Checked: packages/admin/src/index.test.ts:592-632 and docs/STORAGE.md:118-130 confirm the intended split; the comment makes the blast-radius of missing rebuild less obvious.

🔵 Issue 3 — ensureSeededAssignment docs not updated for store-maintained index omission

packages/admin/src/index.ts:210 · nit · identified by meta/muse-spark-1.2

Concrete failure: a host migrating to the store-maintained index (createRoleStore now implements RoleHolderReader) reads EnsureSeededAssignmentOptions (packages/admin/src/index.ts:210-222) where holderIndex is still documented only as "When provided, the superset row is recorded before the grant." No note says to omit it when the store already maintains authorization_role_holders internally, or that omitting it is now the preferred path.

A cautious host may continue to pass a stale memoryHolderIndex() to every seed call, creating two divergent indexes (host row in one partition, store row in another) or, if they stop passing it without guidance, may worry the seed is no longer indexed. Both increase integration confusion and the chance of running the docs/ADMINISTRATION.md:46 old recipe unnecessarily.

Evidence: PR body and docs/STORAGE.md:119-130 describe the store path as preferred and holderIndex as optional for createRoleAdministration, but ensureSeededAssignment's JSDoc and docs/ADMINISTRATION.md seed-helper paragraph were not updated in this diff.

Checked: packages/admin/src/index.ts:196-222, packages/admin/src/index.test.ts:592 seeds without holderIndex against store index, while docs/ADMINISTRATION.md:46-52 still frames the holder-index write as host-port only.

🟠 Issue 4 — Last-administrator guard's verify-on-read safety is now delegated to the store's RoleHolderReader, not enforced by the service

packages/admin/src/index.ts:337 · risk · identified by z-ai/glm-5.3-flash

A host that implements the storage ports itself can now satisfy createRoleAdministration without a holderIndex by implementing RoleHolderReader. If that host's listActiveRoleAssignmentsByRole is a naive secondary-index read that does not verify rows against the authoritative lifecycle record (the JSDoc obligation, but nothing enforces it), a stale row for a revoked assignment still counts as an active holder, and revokeRole allows revoking the real last administrator — the exact "allow harmfully" outcome docs/ADMINISTRATION.md promises cannot happen ("The guard can only refuse harmlessly, never allow harmfully ... every candidate is verified against the authoritative store before it counts").

Mechanism: in anotherActiveHolderExists, the store branch returns holders.some(...) straight from listActiveRoleAssignmentsByRole with no getRoleAssignment re-verification, while the host-index branch still verifies every candidate itself (packages/admin/src/index.ts:337-366). Verification therefore moved from service-enforced to port-contract-enforced.

The provided createRoleStore does verify internally (packages/storage/src/role-store.ts:430-474), so the default path is safe; the exposure is only host-implemented aware stores. Repair options: re-verify store-path holders via getRoleAssignment, or qualify the docs/ADMINISTRATION.md claim to stores that conform to RoleHolderReader.

🟠 Issue 5 — A fourth declared collection now reaches every Store implementation and every audited grant gains an extra cross-partition write; the compatibility claims don't cover this

packages/storage/src/role-store.ts:297 · risk · identified by z-ai/glm-5.3-flash

createRoleStore now calls store.collection(roleHolders) eagerly at construction (packages/storage/src/role-store.ts:297), so any host that implements the storage-core Store boundary itself — as opposed to the storage ports — receives a brand-new collection definition, authorization_role_holders, on the first createRoleStore call after a routine dependency upgrade. A Store implementation that allow-lists or provisions per collection name (one table/container per collection) throws or mis-provisions at construction, breaking startup with no migration note. Separately, every grantRoleAssignmentWithAudit now performs one additional insertIfAbsent outside the grant transaction (packages/storage/src/role-store.ts:572), raising the grant path from two writes to three, paid even by hosts that supply their own holderIndex and never read the store's index.

The release notes state "Hosts that pass a holderIndex keep today's behavior exactly" (RELEASE_NOTES.md:23) and the PR body says hosts implementing the storage ports themselves "don't need any changes" — both claims skip over hosts implementing the Store boundary. The compatibility section should carve this out (new collection definition observed by every Store, extra write per audited grant) or the notes overclaim.

🟠 Issue 6 — By-role read cost scales with all historical rows (refused grants included), with one extra point read per row and unbounded Promise.all fan-out

packages/storage/src/role-store.ts:430 · risk · identified by z-ai/glm-5.3-flash

Rows in authorization_role_holders are never deleted and are written for every post-pointer-check grant attempt — including grants refused with active_tuple or event_id — so the (application, role, scope) partition accumulates every historical grant attempt forever. Each listActiveRoleAssignmentsByRole call does a full partition scan plus one records.getVersioned round-trip per row, all issued concurrently with no cap (Promise.all over candidates.map, packages/storage/src/role-store.ts:441-470). The last-administrator guard calls this twice per guarded revoke (pre-check and post-commit re-verify), so an application with tens of thousands of historical admin grants pays tens of thousands of concurrent point reads per guard check against a durable backend — provider throttling or connection-pool exhaustion makes the guard reject, turning routine admin revocations into failures.

docs/STORAGE.md discloses "never delete" and verify-on-read but not the per-query cost shape, the refusal-row growth, or any bound, and there is no compaction/retention story for the collection. At minimum the new doc section should state the cost characteristics; a concurrency cap (batched verification) would bound the fan-out.

🔵 Issue 7 — Normative docs still describe the pre-index world (three collections, "no derived selection index", adapter capability list, "No new storage")

docs/STORAGE.md:249 · nit · identified by z-ai/glm-5.3-flash

The PR updates the by-role section of docs/STORAGE.md but leaves older normative sentences now contradicted by the change:

  • docs/STORAGE.md:249 — "createRoleStore(store, applicationId) binds three declared collections" — it now binds four, and the Record layout section (the place hosts implementing a Store or provisioning a durable backend learn partition/id shapes) has no entry for authorization_role_holders; its partition (applicationId|role|scopeTag) and id (encodeSegment(assignmentId)) shape are documented nowhere.
  • docs/STORAGE.md:330 — "There is no derived selection index and no fence to compare, so there is nothing that can drift from the records or that would need reconciling" — the package now maintains a derived index that does drift (dangling rows from refused grants and the crash window) and needs reconciling via rebuildRoleHolderIndex.
  • docs/STORAGE.md:349 — the in-memory adapter capability sentence ("implements exact principal lookup, identity link writes, role reads, audit reads, and combined audited grants and revocations") omits the new by-role read and index maintenance.
  • docs/STORAGE.md:121 — "a refused grant leaves a row that reads as nothing" is imprecise: a grant refused at the assignment_id pointer check leaves no row at all, because the holder write follows the pointer check (packages/storage/src/role-store.ts:558-572).
  • docs/ADMINISTRATION.md:155 — "No new storage: every durable record it touches is either the existing authorization collections or the host's own index collection reached through the port" — the package's default path now touches a new library-declared collection.

🔵 Issue 8 — docs/PROJECT_PLAN.md still lists the library-maintained by-role index as an open #24 follow-up

docs/PROJECT_PLAN.md:784 · nit · identified by z-ai/glm-5.3-flash

docs/PROJECT_PLAN.md:783-786 says "Two follow-ups remain deliberately open from #24: a library-maintained by-role index (a design task — the recipe's write-before-grant, never-delete, verify-on-read shape is the candidate)" in present tense, while this PR ships exactly that index and its body says "Closes #24". The plan's status now contradicts RELEASE_NOTES.md and docs/STORAGE.md, and no dated plan entry (the document's established pattern, e.g. "Reference-consumer storage and billing feedback (2026-07-30):") records the landing or the still-declined guard primitive. A reader triaging open work would re-plan an already-shipped design task.

🔵 Issue 9 — Generated admin API page references the non-exported RoleAdministrationCommonOptions

docs/api/authorization-admin.md:263 · nit · identified by z-ai/glm-5.3-flash

docs/api/authorization-admin.md:263 shows export type RoleAdministrationOptions = RoleAdministrationCommonOptions & (...), but RoleAdministrationCommonOptions is declared without export (packages/admin/src/index.ts:137) and has no section on the generated page, so a host reading the public API docs cannot resolve the name or find its fields (policy, now, generateId) documented anywhere. Either export the interface so the generator documents it, or inline the common fields into the generated snippet.

🔵 Issue 10 — viewGrants self-heal comment claims convergence the store-index path does not provide

packages/admin/src/index.ts:475 · nit · identified by z-ai/glm-5.3-flash

packages/admin/src/index.ts:475-478 reads: "Self-heal the superset: an assignment the store reports but the index misses (a grant that predates the index) is re-recorded so the guard's by-role candidate set converges. Idempotent puts." In the now-default store-maintained path, recordHolder is a no-op (packages/admin/src/index.ts:326-331), nothing is re-recorded, and pre-index assignments never converge through viewGrants — only rebuildRoleHolderIndex() heals them. A reader of this comment in the default configuration will believe a convergence happens that does not; the comment should be scoped to the host-index branch or note that the store path relies on the rebuild.

🔵 Issue 11 — Options union rejects the natural optional-holderIndex shape the runtime supports

packages/admin/src/index.ts:160 · nit · identified by z-ai/glm-5.3-flash

The union's first branch pins holderIndex?: undefined (packages/admin/src/index.ts:160-167). A TypeScript host that builds options conditionally — { store, policy, ...(useHostIndex ? { holderIndex } : {}) }, inferring holderIndex?: RoleHolderIndex — matches neither branch (branch 1 demands undefined, branch 2 demands a required RoleHolderIndex) and fails to compile, even though the runtime handles that shape correctly: a present index is used, an absent one falls back to the store (packages/admin/src/index.ts:312-347). Since this PR makes the index optional for the first time, this conditional-spread shape is the natural migration target; consider typing the store branch as holderIndex?: RoleHolderIndex with the runtime awareness check deciding, so hosts need no cast.

🔵 Issue 12 — RoleHolderReader's "empty array means definitive emptiness" is unqualified against the disclosed pre-rebuild under-report window

packages/storage/src/index.ts:122 · nit · identified by z-ai/glm-5.3-flash

packages/storage/src/index.ts:122 states "An empty array means definitive emptiness" for the by-role port, but the same package documents that assignments granted before this release produce no rows until rebuildRoleHolderIndex() runs once (docs/STORAGE.md:121-131, RELEASE_NOTES.md migration bullet). During that window an empty result is not definitive: a host could legitimately read listActiveRoleAssignmentsByRole(adminRole, application) === [] as "zero administrators" — for example in a first-administrator or bootstrap gate — and be wrong. One qualifying clause ("after the one-time rebuild obligation is discharged") in the port contract would align it with the migration caveat; as written the two statements in the same docs pull against each other.

🔵 Issue 13 — Construction-time check treats only undefined; a JS holderIndex: null passes construction and crashes at first use

packages/admin/src/index.ts:312 · nit · identified by z-ai/glm-5.3-flash

The narrowing is holderIndex === undefined (packages/admin/src/index.ts:312-321), so a JavaScript caller passing holderIndex: null (the common JS spelling of "not supplied") skips the check entirely. recordHolder then throws TypeError: Cannot read properties of null (reading 'record') on the first assignRole/compensation, and the guard path would throw Cannot read properties of null (reading 'listByRole') at packages/admin/src/index.ts:348 — both after construction succeeded, contradicting the comment's own claim that "JavaScript callers get a construction-time error rather than a guard that cannot decide". Accepting holderIndex == null (undefined or null) in the narrowing would surface the misconfiguration at construction with the documented message.

Workflow run

Comment thread packages/admin/src/index.ts Resolved
Comment thread packages/admin/src/index.ts Resolved
Comment thread packages/storage/src/role-store.ts Resolved
Comment thread packages/storage/src/role-store.ts Resolved
Comment thread docs/api/authorization-admin.md Resolved
Comment thread packages/admin/src/index.ts Resolved
Comment thread packages/storage/src/index.ts Resolved
Comment thread packages/admin/src/index.ts Resolved
- Admin guard re-verifies every candidate by exact ID on the store path
  too, so a non-conforming RoleHolderReader can only make it refuse.
- Verify by-role rows in batches of 16 instead of one unbounded fan-out.
- Treat a null holderIndex as absent and reject a malformed one at
  construction; let the store-index options branch accept an optional
  holderIndex; export RoleAdministrationCommonOptions.
- Qualify the by-role port's emptiness promise against the rebuild
  window and state the verification obligation.
- Document the new collection's layout, the extra write per grant, the
  read cost shape, and the Store provisioning note; fix stale sentences
  in STORAGE.md, ADMINISTRATION.md, PROJECT_PLAN.md, and code comments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y48RJvxtcZ7PZaeBbkM8V4

@github-actions github-actions 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.

OpenRouter pull-request review

Verdict: clean
Scope: latest-commit (commit-range)
Mode: verify
Commit: 39a14ee4e185b92a495b51affb0c3fca394b3a3e
Judge: openai/gpt-5.6-luna
Cost: $0.1350 (lanes $0.1349 + judge $0.0001)

Lanes

  • meta/muse-spark-1.2: ok (0 finding(s), 18.1s, 121325+3084 tokens (41284 cached), 3 tool round(s), via Meta, $0.12)
  • z-ai/glm-5.3-flash: ok (0 finding(s), 167.3s, 577158+18391 tokens (493921 cached), 17 tool round(s), via OpenInference, $0.0156)

Round 2 resolution

  • ✅ r1-4 fixed correctly — Last-administrator guard's verify-on-read safety is now delegated to the store's RoleHolderReader, not enforced by the service: Verified in packages/admin/src/index.ts: anotherActiveHolderExists now normalizes store holders to RoleHolderIndexRow and re-verifies every candidate (both host-index and store-index paths) via store.getRoleAssignment with exact-ID, role, principal and sameScope checks before counting. Stale store rows can now only cause refusal. New test "re-verifies a store's by-role answer before counting a hol…
  • ✅ r1-5 fixed correctly — A fourth declared collection now reaches every Store implementation and every audited grant gains an extra cross-partition write; the compatibility claims don: Docs now disclose the costs instead of claiming zero impact. RELEASE_NOTES.md Unreleased section states both costs for every createRoleStore host (fourth collection authorization_role_holders requiring provisioning, plus one extra insertIfAbsent per audited grant) and by-role read shape. docs/STORAGE.md Record layout now documents the four collections, partition/ID shape, and provisioning requirem…
  • ✅ r1-6 fixed correctly — By-role read cost scales with all historical rows (refused grants included), with one extra point read per row and unbounded Promise.all fan-out: Bounded fan-out implemented in packages/storage/src/role-store.ts: HOLDER_VERIFY_BATCH=16 and verification loop slices candidates and does Promise.all per batch instead of one unbounded Promise.all over all rows. Test "verifies every row when a role has more rows than one batch" exercises 40 rows (>2 batches). docs/STORAGE.md now documents cost as one partition listing plus one point read per row …
  • 10 nit finding(s) from earlier rounds retired (severity floor for follow-up rounds is risk).
  • Open findings after this round: 0 (0 bug-severity).

No structured findings from the successful lane(s).

Workflow run

@FlyOverCoderKY
FlyOverCoderKY merged commit ac514f3 into main Nov 2, 2026
5 checks passed
@FlyOverCoderKY
FlyOverCoderKY deleted the claude/project-thread-rvj5y2 branch November 2, 2026 14:43
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.

authorization-storage: no per-principal assignment enumeration (revoked included) and no by-role selection

2 participants