diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 0bfcbb8..3c2011e 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,3 +1,38 @@ +# Unreleased + +`@pegma/authorization-storage` gains a library-maintained by-role index, the +remaining storage ask from issue #24: + +- `RoleHolderReader.listActiveRoleAssignmentsByRole(role, scope)` lists every + active assignment of one role in one exact scope across principals, ordered + by grant time and then assignment ID. Each result is verified against the + authoritative lifecycle record. It is a new, separate port, so hosts that + implement `RoleAssignmentReader` themselves are unaffected. +- `createRoleStore` and the in-memory adapter maintain the index on every + audited grant using the superset recipe from `docs/STORAGE.md` (write + before grant, never delete, verify on read). +- `RoleHolderIndexMaintenance.rebuildRoleHolderIndex()` backfills rows for + assignments granted before this release. Durable deployments should run it + once after upgrading; until then those assignments are missing from by-role + results, which makes a last-administrator guard refuse rather than allow. + +`@pegma/authorization-admin` no longer requires a host `holderIndex` when its +store implements `RoleHolderReader`. Hosts that pass a `holderIndex` keep +the same guard decisions; the store's index is used only when none is given. +The guard re-verifies every candidate by exact ID whichever index supplied it. + +Two costs reach every host using `createRoleStore`, including hosts that keep +their own `holderIndex`: `createRoleStore` declares a fourth collection, +`authorization_role_holders`, so a `Store` implementation that provisions +storage per collection name must provision it before upgrading; and every +audited grant performs one additional `insertIfAbsent`. By-role read cost +grows with a role's whole grant history; `docs/STORAGE.md` describes the +shape. + +A first-class concurrency-safe last-administrator guard primitive remains +declined: the admin service's serialize, re-verify, and compensate treatment +is still the documented answer. + # Authorization Core 0.4.0 Authorization Core 0.4.0 first advertises `@pegma/authorization-admin`, the diff --git a/docs/ADMINISTRATION.md b/docs/ADMINISTRATION.md index 452ac12..a1bc90f 100644 --- a/docs/ADMINISTRATION.md +++ b/docs/ADMINISTRATION.md @@ -42,7 +42,10 @@ configuration, a lesson from the reference host. **Audited assign.** A grant of a host-policy role — authorized by the HOST before the call, see the ports section — with a caller-supplied assignment id, an audit event, and duplicate refusal delegated to the store's -active-tuple guarantee. The holder-index row is written BEFORE the grant +active-tuple guarantee. When the store maintains the by-role index itself +(`RoleHolderReader`, provided by `createRoleStore`), the store writes the +index row inside its own grant path and the service needs no host index. +Otherwise the holder-index row is written BEFORE the grant through the host port (superset invariant, `docs/STORAGE.md` recipe), after a pre-check that the tuple is not already active. Dangling rows still arise — from a crash between the two writes, or from a grant the @@ -90,6 +93,11 @@ the common case, and the recovery is documented rather than implied. an ordered event timeline. No host index involvement; pre-index grants appear because the store is the authority. +**Guard verification.** Whichever index supplies the candidates — the +store's `RoleHolderReader` or a host index — the service re-reads each one +by exact ID before it counts, so a store whose by-role read is stale can +still only make the guard refuse. + **One-time seed helper.** Both hosts wrote the same bootstrap-adjacent function; the third copy would be in this package's README, so it belongs in the package: `ensureSeededAssignment` grants a role once per principal, @@ -124,12 +132,12 @@ that document forbids stays forbidden. ## Ports (all constructor-injected, host-owned) -| Port | Provided by | Notes | -| ----------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Role store | `createRoleStore` (authorization-storage) | reads, lifecycle enumeration, audited mutations | -| Holder index | host, per `docs/STORAGE.md` recipe | `record(row)`, `listByRole(role)`; write-before-grant, never delete, verify-on-read. Stays a port until the library-maintained index (#24 follow-up) ships, then becomes optional. | -| Management policy | host configuration | `{ administratorRole, oneTimeSystemActors }`; the guard's compensation actor and the seed helper's actor are included by default | -| Clock | host (`@pegma/spine`) | deterministic tests | +| Port | Provided by | Notes | +| ----------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Role store | `createRoleStore` (authorization-storage) | reads, lifecycle enumeration, audited mutations | +| Holder index | optional; host, per `docs/STORAGE.md` recipe | `record(row)`, `listByRole(role)`; write-before-grant, never delete, verify-on-read. Omit it when the store implements `RoleHolderReader` (`createRoleStore` does); a supplied index is always used in preference to the store's. | +| Management policy | host configuration | `{ administratorRole, oneTimeSystemActors }`; the guard's compensation actor and the seed helper's actor are included by default | +| Clock | host (`@pegma/spine`) | deterministic tests | The service performs no permission checks on its own callers: the HOST gates its routes with `hasPermission` against its own policy before @@ -143,9 +151,11 @@ Tenth package. Same rules as the eighth and ninth: implementation lands with conformance-style tests against the memory store; the one-time `0.0.0` name reservation publishes under the non-default `bootstrap` dist-tag; trusted publishing is configured; the next synchronized `0.x` release is -its first advertised publication. 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. +its first advertised publication. The package declares no storage of its +own: every durable record it touches is either the authorization collections +`createRoleStore` declares (including the library-maintained +`authorization_role_holders` index) or the host's own index collection +reached through the port. ## Host adoption order (recorded, executed in the host repos) diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index e52b015..168ec3e 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -788,6 +788,14 @@ candidate), and a first-class concurrency-safe guard primitive, declined for now because records for different principals live in different partitions and the single-partition transaction boundary cannot honestly promise it. +**Library-maintained by-role index (2026-11-02):** the first #24 follow-up +landed. `RoleHolderReader.listActiveRoleAssignmentsByRole` is a separate, +optional port; `createRoleStore` maintains the `authorization_role_holders` +index with the recipe's write-before-grant, never-delete, verify-on-read +shape, and `rebuildRoleHolderIndex` backfills grants made before it existed. +The admin service's host `holderIndex` becomes optional. The first-class +guard primitive remains declined for the reason above. + **Administration-surface extraction (2026-07-30, design under review):** with both reference hosts having independently built the same audited role-management surface, the extract-on-second-consumer trigger is met. diff --git a/docs/STORAGE.md b/docs/STORAGE.md index 4376aca..d6b43f4 100644 --- a/docs/STORAGE.md +++ b/docs/STORAGE.md @@ -103,12 +103,52 @@ authoritative records. ### By-role selection across principals -Neither listing crosses principals. Records are partitioned by principal and -scope so both listings are one-partition reads, which means "every active -holder of role R" has no partition to read and no supported query. A host that -needs it — a role-administration panel, or a last-administrator guard refusing -to revoke the final active `Admin` — must maintain a secondary index, and the -index must fail in the safe direction: +Neither per-principal listing crosses principals. Records are partitioned by +principal and scope so both listings are one-partition reads, which leaves +"every active holder of role R" without a partition of its own. + +`RoleHolderReader.listActiveRoleAssignmentsByRole(role, scope)` answers it. +It returns every active assignment of one role in one exact scope, across +principals, ordered by `grantedAtEpochMs` ascending and then by assignment ID. +It is a separate port from `RoleAssignmentReader`, so hosts that implement the +storage ports themselves are not required to provide it; `createRoleStore` +and the in-memory adapter both do. + +The provided adapters maintain the index themselves, following the recipe +below: every audited grant writes an immutable holder row (partitioned by +application, role, and exact scope) before the grant transaction, rows are +never deleted, and every read verifies each row against the authoritative +lifecycle record. A revoked assignment, or a grant refused after the pointer +check (an occupied tuple or a different event ID), leaves a row that reads as +nothing; a grant refused at the pointer check writes no row; a stored +assignment is never missed. + +Each audited grant therefore costs one more `insertIfAbsent` than before, +outside the grant transaction. Each by-role read is one partition listing plus +one authoritative point read per row, issued in batches of 16. Because rows +are never deleted, the partition grows with every grant attempt for that role +and scope, including revoked and refused ones, so read cost tracks a role's +whole grant history rather than its current holders. That is the right trade +for administrator-style roles granted a handful of times; a role granted +routinely to large populations is a poor fit for by-role reads. + +Assignments granted before the index existed (before this release) have no +row. Until `RoleHolderIndexMaintenance.rebuildRoleHolderIndex()` runs once +over the backing store, they are missing from by-role results, which a +last-administrator guard sees as "no other holder" and refuses — fail closed, +but still a refusal an operator would notice. The rebuild reads the +application's assignment pointers (a single-partition scan), writes any +missing rows, reports how many it wrote, and is idempotent and safe to run +alongside live grants and revocations. + +The by-role read is a non-snapshot read like every other listing, so the +concurrency caveat below still applies to at-least-one invariants. + +#### Recipe for a host-maintained index + +A host that implements the storage ports itself, or that predates the +library-maintained index, can keep its own secondary index. It must fail in +the safe direction: 1. Write the index entry **before** the audited grant, so the index can only over-report, never under-report. A grant refused after its index entry was @@ -122,8 +162,10 @@ closed. The check itself is still a non-snapshot read: a guard that verifies "another active holder exists" and then revokes can race a concurrent revocation of that other holder. A host enforcing an at-least-one invariant must re-verify after its own revocation commits and compensate — regrant under -a fresh assignment ID — when the invariant was lost. Whether this index becomes -a library-maintained structure is tracked as Phase 6 integration feedback. +a fresh assignment ID — when the invariant was lost. The library-maintained +index above follows exactly this recipe; a first-class concurrency-safe guard +primitive remains declined, because the single-partition transaction boundary +cannot make a cross-principal invariant atomic. ## Atomic create @@ -215,7 +257,7 @@ complete audit history. ## Record layout -`createRoleStore(store, applicationId)` binds three declared collections to one +`createRoleStore(store, applicationId)` binds four declared collections to one `Store` and one host application. `authorization_records` holds everything about one principal in one exact @@ -248,6 +290,14 @@ written with `insertIfAbsent` before the grant transaction rather than inside it. A pointer that resolves to nothing reads as absence, which the port already treats as definitive. +`authorization_role_holders` is the by-role index. Its partition is +`applicationId|role|scopeTag` and each record ID is the encoded assignment ID; +a row carries the assignment's principal, scope, and role. Like a pointer, a +row is immutable and written with `insertIfAbsent` before the grant +transaction, after the pointer check, and it is never deleted. A host whose +`Store` provisions storage per collection name must provision this one before +upgrading. + `authorization_identity_links` maps one exact issuer-and-subject tuple to a principal. Issuer and subject are stored raw as well as encoded into the record ID, so a reader confirms the exact case-sensitive tuple rather than trusting @@ -297,7 +347,7 @@ partition and would therefore leave the transaction boundary. ## Non-snapshot reads `listActiveRoleAssignments` and `listRoleAssignments` are each one partition -read of the authoritative assignment records. There is no derived selection +read of the authoritative assignment records. They use no derived selection index and no fence to compare, so there is nothing that can drift from the records or that would need reconciling; but a partition listing is not a snapshot, and a read that begins before a revocation may still observe the @@ -315,8 +365,8 @@ deadline, exact binding, invalidation, and stale-fill rules in that guide. `createInMemoryStorageAdapter` is `createRoleStore` over the storage-core in-process memory store, bound to one application namespace. It implements -exact principal lookup, identity link writes, role reads, audit reads, and -combined audited grants and revocations. Its returned object deliberately has +exact principal lookup, identity link writes, role reads, by-role reads and +index rebuild, audit reads, and combined audited grants and revocations. Its returned object deliberately has no `createRoleAssignment`, raw `revokeRoleAssignment` signature, or `appendRoleAssignmentAuditEvent` capability outside the combined command diff --git a/docs/api/authorization-admin.md b/docs/api/authorization-admin.md index 07e10cb..e079c6a 100644 --- a/docs/api/authorization-admin.md +++ b/docs/api/authorization-admin.md @@ -111,7 +111,12 @@ Options for {@link ensureSeededAssignment}. ```ts export interface EnsureSeededAssignmentOptions { readonly store: RoleAdministrationStore; - /** When provided, the superset row is recorded before the grant. */ + /** + * The host's own by-role index, when it keeps one: the superset row is + * recorded before the grant. Omit it when the store maintains the + * library's index (`createRoleStore` does) — the store records its own row + * on every audited grant, so a host index would only be a second copy. + */ readonly holderIndex?: RoleHolderIndex; readonly principalId: PrincipalId; readonly role: RoleName; @@ -230,6 +235,22 @@ export interface RoleAdministration { } ``` +## RoleAdministrationCommonOptions + +**Kind:** interface + +Options shared by both {@link RoleAdministrationOptions} shapes. + +```ts +export interface RoleAdministrationCommonOptions { + readonly policy: RoleManagementPolicy; + /** Epoch-milliseconds clock; injectable for deterministic tests. */ + readonly now?: () => number; + /** Fresh opaque id source for grants and audit events. */ + readonly generateId?: () => string; +} +``` + ## RoleAdministrationEvent **Kind:** interface @@ -249,20 +270,28 @@ export interface RoleAdministrationEvent { ## RoleAdministrationOptions -**Kind:** interface +**Kind:** type Constructor options for {@link createRoleAdministration}. +Either the store maintains the by-role index itself (preferred), or the +host supplies a {@link RoleHolderIndex}. When a `holderIndex` is given it +is used even if the store could answer by-role queries, so upgrading the +storage package never silently changes which index an existing host's +guard trusts. + ```ts -export interface RoleAdministrationOptions { - readonly store: RoleAdministrationStore; - readonly holderIndex: RoleHolderIndex; - readonly policy: RoleManagementPolicy; - /** Epoch-milliseconds clock; injectable for deterministic tests. */ - readonly now?: () => number; - /** Fresh opaque id source for grants and audit events. */ - readonly generateId?: () => string; -} +export type RoleAdministrationOptions = RoleAdministrationCommonOptions & + ( + | { + readonly store: RoleHolderAwareAdministrationStore; + readonly holderIndex?: RoleHolderIndex | undefined; + } + | { + readonly store: RoleAdministrationStore; + readonly holderIndex: RoleHolderIndex; + } + ); ``` ## RoleAdministrationStore @@ -276,6 +305,19 @@ export interface RoleAdministrationStore extends RoleAssignmentReader, AuditedRoleAssignmentMutationStore {} ``` +## RoleHolderAwareAdministrationStore + +**Kind:** interface + +A store that also maintains the library's by-role index +(`createRoleStore` and `createInMemoryStorageAdapter` both do). With one, +the service needs no host-provided {@link RoleHolderIndex}. + +```ts +export interface RoleHolderAwareAdministrationStore + extends RoleAdministrationStore, RoleHolderReader {} +``` + ## RoleHolderIndex **Kind:** interface diff --git a/docs/api/authorization-storage.md b/docs/api/authorization-storage.md index 0b1501e..125e426 100644 --- a/docs/api/authorization-storage.md +++ b/docs/api/authorization-storage.md @@ -219,6 +219,8 @@ export interface InMemoryStorageAdapter extends IdentityLinkStore, RoleAssignmentReader, + RoleHolderReader, + RoleHolderIndexMaintenance, RoleAssignmentAuditReader, AuditedRoleAssignmentMutationStore {} ``` @@ -269,6 +271,19 @@ operational failures, incomplete reads, and corrupt records. export interface PrincipalLookupStore extends IdentityAdapter {} ``` +## RebuildRoleHolderIndexResult + +**Kind:** interface + +Result of one by-role index rebuild. + +```ts +export interface RebuildRoleHolderIndexResult { + /** Index rows written by this run; rows already present are not counted. */ + readonly recorded: number; +} +``` + ## RevokeRoleAssignmentCommand **Kind:** interface @@ -460,6 +475,67 @@ export interface RoleAssignmentStore extends RoleAssignmentReader { } ``` +## RoleHolderIndexMaintenance + +**Kind:** interface + +Maintenance for the library-maintained by-role index. + +Grants made through this version and later maintain the index themselves. +Assignments granted by an earlier version have no index row until +`rebuildRoleHolderIndex` runs once over the backing store. It is +idempotent and safe to run concurrently with grants and revocations. + +```ts +export interface RoleHolderIndexMaintenance { + readonly rebuildRoleHolderIndex: () => Promise; +} +``` + +## RoleHolderReader + +**Kind:** interface + +Cross-principal by-role selection. + +Separate from {@link RoleAssignmentReader} so hosts that implement the +storage ports themselves are not required to provide it. Role +administration surfaces use it to answer "who holds role R in this scope", +including the last-administrator guard's "does another active holder +exist". + +```ts +export interface RoleHolderReader { + /** + * Every active assignment of one role in one exact scope, across + * principals, ordered by `grantedAtEpochMs` ascending and then by + * assignment ID code-unit order. + * + * Every result is verified against the authoritative lifecycle record, so + * a revoked or refused assignment is never reported as active. Like the + * per-principal listings this is a non-snapshot read: a concurrent grant or + * revoke in another principal's partition may or may not be reflected, so + * an at-least-one invariant still needs the re-verify-after-commit + * treatment in `docs/STORAGE.md`. + * + * Implementations must verify every reported assignment against the + * authoritative lifecycle record; an unverified secondary-index read is + * not conforming, because a stale row would count a revoked holder. + * + * An empty array means definitive emptiness once the index covers every + * stored assignment. For the provided adapters that holds after + * `rebuildRoleHolderIndex` has run once over a store that holds grants + * made before the index existed; until then an empty result can omit + * those grants. Implementations reject partial, operationally failed, or + * corrupt results. + */ + readonly listActiveRoleAssignmentsByRole: ( + role: RoleName, + scope: RoleAssignmentScope, + ) => Promise; +} +``` + ## SequencedRoleAssignmentAuditEvent **Kind:** interface diff --git a/packages/admin/src/index.test.ts b/packages/admin/src/index.test.ts index 1b6ff0e..2fc1d61 100644 --- a/packages/admin/src/index.test.ts +++ b/packages/admin/src/index.test.ts @@ -586,3 +586,215 @@ describe("ensureSeededAssignment", () => { ).toBe("granted"); }); }); + +describe("store-maintained by-role index", () => { + function indexlessWorld() { + const store = createRoleStore(createMemoryStore(), "admin-tests"); + const { now, generateId } = deterministic(); + const administration = createRoleAdministration({ + store, + policy: { administratorRole: ADMIN }, + now, + generateId, + }); + return { store, administration }; + } + + async function seed( + store: RoleAdministrationStore, + principalId: PrincipalId, + assignmentId: string, + scope: RoleAssignmentScope = APPLICATION, + ) { + expect( + await ensureSeededAssignment({ + store, + principalId, + role: ADMIN, + scope, + assignmentId, + auditEventId: `evt-${assignmentId}`, + now: () => 1, + }), + ).toBe("granted"); + } + + it("guards the last administrator with no host holder index", async () => { + const { administration, store } = indexlessWorld(); + await seed(store, bob, "seed-bob"); + // Same role name in an organization scope never counts. + await seed(store, carol, "seed-carol-org", { + kind: "organization", + organizationId: "org-1", + }); + expect( + await administration.revokeRole({ + assignmentId: "seed-bob", + actor: operator, + }), + ).toEqual({ status: "last_administrator" }); + + const assigned = await administration.assignRole({ + principalId: carol, + role: ADMIN, + scope: APPLICATION, + actor: operator, + }); + expect(assigned.status).toBe("assigned"); + expect( + await administration.revokeRole({ + assignmentId: "seed-bob", + actor: operator, + }), + ).toEqual({ status: "revoked", compensated: false }); + expect( + await administration.anotherActiveHolderExists(ADMIN, APPLICATION, carol), + ).toBe(false); + }); + + it("serializes concurrent revocations of the two last administrators", async () => { + const { administration, store } = indexlessWorld(); + await seed(store, bob, "seed-bob"); + await seed(store, carol, "seed-carol"); + const results = await Promise.all([ + administration.revokeRole({ assignmentId: "seed-bob", actor: operator }), + administration.revokeRole({ + assignmentId: "seed-carol", + actor: operator, + }), + ]); + expect(results.map(({ status }) => status).sort()).toEqual([ + "last_administrator", + "revoked", + ]); + }); + + it("compensates a cross-instance race using the store's index", async () => { + const shared = createRoleStore(createMemoryStore(), "admin-tests"); + const clockA = deterministic(); + const clockB = deterministic(); + const instanceB = createRoleAdministration({ + store: shared, + policy: { administratorRole: ADMIN }, + now: clockB.now, + generateId: () => `b-${clockB.generateId()}`, + }); + let interleaved = false; + const instanceA = createRoleAdministration({ + store: { + ...shared, + revokeRoleAssignmentWithAudit: async (command) => { + if (!interleaved) { + interleaved = true; + expect( + ( + await instanceB.revokeRole({ + assignmentId: "seed-carol", + actor: operator, + }) + ).status, + ).toBe("revoked"); + } + return shared.revokeRoleAssignmentWithAudit(command); + }, + }, + policy: { administratorRole: ADMIN }, + now: clockA.now, + generateId: () => `a-${clockA.generateId()}`, + }); + await seed(shared, bob, "seed-bob"); + await seed(shared, carol, "seed-carol"); + + expect( + await instanceA.revokeRole({ assignmentId: "seed-bob", actor: operator }), + ).toEqual({ status: "revoked", compensated: true }); + expect( + (await shared.listActiveRoleAssignmentsByRole(ADMIN, APPLICATION)).map( + ({ principalId, grantedBy }) => [principalId, grantedBy], + ), + ).toEqual([ + [bob, { kind: "system", systemId: GUARD_COMPENSATION_SYSTEM_ID }], + ]); + }); + + it("prefers an explicitly supplied host index over the store's", async () => { + const store = createRoleStore(createMemoryStore(), "admin-tests"); + const holderIndex = memoryHolderIndex(); + const administration = createRoleAdministration({ + store, + holderIndex, + policy: { administratorRole: ADMIN }, + }); + // Seeded without the host index: the store knows both holders, the + // host index knows neither, so the host index's answer is what decides. + await seed(store, bob, "seed-bob"); + await seed(store, carol, "seed-carol"); + expect( + await administration.anotherActiveHolderExists(ADMIN, APPLICATION, bob), + ).toBe(false); + }); + + it("re-verifies a store's by-role answer before counting a holder", async () => { + const store = createRoleStore(createMemoryStore(), "admin-tests"); + await seed(store, bob, "seed-bob"); + await seed(store, carol, "seed-carol"); + const carolSnapshot = ( + await store.listActiveRoleAssignmentsByRole(ADMIN, APPLICATION) + ).filter(({ principalId }) => principalId === carol); + const carolRecord = await store.getRoleAssignment("seed-carol"); + await store.revokeRoleAssignmentWithAudit({ + assignmentId: "seed-carol", + expectedConcurrencyToken: carolRecord!.concurrencyToken, + revokedBy: operator, + revokedAtEpochMs: 2, + auditEventId: "evt-revoke-carol", + }); + // A non-conforming store that keeps reporting the revoked holder. + const administration = createRoleAdministration({ + store: { + ...store, + listActiveRoleAssignmentsByRole: async (role, scope) => [ + ...(await store.listActiveRoleAssignmentsByRole(role, scope)), + ...carolSnapshot, + ], + }, + policy: { administratorRole: ADMIN }, + }); + expect( + await administration.revokeRole({ + assignmentId: "seed-bob", + actor: operator, + }), + ).toEqual({ status: "last_administrator" }); + }); + + it("treats a null holderIndex as absent and rejects a malformed one", () => { + const store = createRoleStore(createMemoryStore(), "admin-tests"); + expect(() => + createRoleAdministration({ + store, + holderIndex: null, + policy: { administratorRole: ADMIN }, + } as never), + ).not.toThrow(); + expect(() => + createRoleAdministration({ + store, + holderIndex: { record: "not a function" }, + policy: { administratorRole: ADMIN }, + } as never), + ).toThrow(TypeError); + }); + + it("refuses construction when neither index is available", () => { + const store = createRoleStore(createMemoryStore(), "admin-tests"); + const { listActiveRoleAssignmentsByRole: _omitted, ...withoutByRole } = + store; + expect(() => + createRoleAdministration({ + store: withoutByRole, + policy: { administratorRole: ADMIN }, + } as never), + ).toThrow(TypeError); + }); +}); diff --git a/packages/admin/src/index.ts b/packages/admin/src/index.ts index b4c15b0..67e58ae 100644 --- a/packages/admin/src/index.ts +++ b/packages/admin/src/index.ts @@ -18,6 +18,7 @@ import type { import type { AuditedRoleAssignmentMutationStore, RoleAssignmentReader, + RoleHolderReader, VersionedRoleAssignment, } from "@pegma/authorization-storage"; @@ -32,6 +33,14 @@ export interface RoleHolderIndexRow { readonly role: RoleName; } +/** + * A store that also maintains the library's by-role index + * (`createRoleStore` and `createInMemoryStorageAdapter` both do). With one, + * the service needs no host-provided {@link RoleHolderIndex}. + */ +export interface RoleHolderAwareAdministrationStore + extends RoleAdministrationStore, RoleHolderReader {} + /** * The host-provided by-role index (`docs/STORAGE.md` recipe): rows are * written BEFORE grants, never deleted, and verified against the @@ -129,10 +138,8 @@ export type RevokeRoleResult = | Readonly<{ readonly status: "last_administrator" }> | Readonly<{ readonly status: "conflict" }>; -/** Constructor options for {@link createRoleAdministration}. */ -export interface RoleAdministrationOptions { - readonly store: RoleAdministrationStore; - readonly holderIndex: RoleHolderIndex; +/** Options shared by both {@link RoleAdministrationOptions} shapes. */ +export interface RoleAdministrationCommonOptions { readonly policy: RoleManagementPolicy; /** Epoch-milliseconds clock; injectable for deterministic tests. */ readonly now?: () => number; @@ -140,6 +147,27 @@ export interface RoleAdministrationOptions { readonly generateId?: () => string; } +/** + * Constructor options for {@link createRoleAdministration}. + * + * Either the store maintains the by-role index itself (preferred), or the + * host supplies a {@link RoleHolderIndex}. When a `holderIndex` is given it + * is used even if the store could answer by-role queries, so upgrading the + * storage package never silently changes which index an existing host's + * guard trusts. + */ +export type RoleAdministrationOptions = RoleAdministrationCommonOptions & + ( + | { + readonly store: RoleHolderAwareAdministrationStore; + readonly holderIndex?: RoleHolderIndex | undefined; + } + | { + readonly store: RoleAdministrationStore; + readonly holderIndex: RoleHolderIndex; + } + ); + /** The administration service. One instance per application; host-gated. */ export interface RoleAdministration { readonly viewGrants: ( @@ -187,7 +215,12 @@ export function assignmentManagedBy( /** Options for {@link ensureSeededAssignment}. */ export interface EnsureSeededAssignmentOptions { readonly store: RoleAdministrationStore; - /** When provided, the superset row is recorded before the grant. */ + /** + * The host's own by-role index, when it keeps one: the superset row is + * recorded before the grant. Omit it when the store maintains the + * library's index (`createRoleStore` does) — the store records its own row + * on every audited grant, so a host index would only be a second copy. + */ readonly holderIndex?: RoleHolderIndex; readonly principalId: PrincipalId; readonly role: RoleName; @@ -274,21 +307,67 @@ function sameScope( export function createRoleAdministration( options: RoleAdministrationOptions, ): RoleAdministration { - const { store, holderIndex, policy } = options; + const { store, policy } = options; + // `null` is JavaScript's other spelling of "not supplied". + const holderIndex = options.holderIndex ?? undefined; + if ( + holderIndex !== undefined && + (typeof holderIndex.record !== "function" || + typeof holderIndex.listByRole !== "function") + ) { + throw new TypeError( + "role administration holderIndex must provide record and listByRole", + ); + } const now = options.now ?? (() => Date.now()); const generateId = options.generateId ?? (() => crypto.randomUUID()); + // Narrowed once: the options union guarantees the store answers by-role + // reads whenever the host supplies no index, and JavaScript callers get a + // construction-time error rather than a guard that cannot decide. + const holderStore = + holderIndex === undefined + ? (store as RoleHolderAwareAdministrationStore) + : undefined; + if ( + holderStore !== undefined && + typeof holderStore.listActiveRoleAssignmentsByRole !== "function" + ) { + throw new TypeError( + "role administration needs a store with listActiveRoleAssignmentsByRole or a host holderIndex", + ); + } + + /** Records a superset row before a grant, when the host owns the index. */ + const recordHolder = async (row: RoleHolderIndexRow): Promise => { + if (holderIndex !== undefined) { + await holderIndex.record(row); + } + }; + const anotherActiveHolderExists = async ( role: RoleName, scope: RoleAssignmentScope, excludingPrincipalId: PrincipalId | "", ): Promise => { - const candidates = await holderIndex.listByRole(role); + const candidates: readonly RoleHolderIndexRow[] = + holderStore !== undefined + ? (await holderStore.listActiveRoleAssignmentsByRole(role, scope)).map( + (holder) => ({ + principalId: holder.principalId, + assignmentId: holder.id, + role: holder.role, + }), + ) + : await holderIndex!.listByRole(role); for (const candidate of candidates) { if (candidate.principalId === excludingPrincipalId) { continue; } - // Rows are candidates only; the authoritative store decides — and + // Rows are candidates only, whichever index produced them: the + // service re-verifies even a conforming store's answer, so a host + // store whose by-role read skips verification can still only make + // the guard refuse. The authoritative store decides — and // only an EXACT-scope holder counts: an organization-scoped // administrator is no answer to losing the last application-scoped // one. @@ -369,7 +448,7 @@ export function createRoleAdministration( return { status: "revoked", compensated: false }; } const compensationId = generateId(); - await holderIndex.record({ + await recordHolder({ principalId: assignment.principalId, assignmentId: compensationId, role: assignment.role, @@ -410,11 +489,13 @@ export function createRoleAdministration( const service: RoleAdministration = { async viewGrants(principalId, scope) { const active = await store.listActiveRoleAssignments(principalId, scope); - // 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. + // Host-index path only: self-heal the superset, so an assignment the + // store reports but the host index misses (a grant that predates the + // index) is re-recorded and the guard's candidate set converges. + // Idempotent puts. The store-maintained index does not heal here; + // `rebuildRoleHolderIndex` backfills it once after upgrading. for (const assignment of active) { - await holderIndex.record({ + await recordHolder({ principalId, assignmentId: assignment.id, role: assignment.role, @@ -465,7 +546,7 @@ export function createRoleAdministration( return { status: "duplicate" }; } const assignmentId = generateId(); - await holderIndex.record({ + await recordHolder({ principalId: command.principalId, assignmentId, role: command.role, diff --git a/packages/storage/src/collections.ts b/packages/storage/src/collections.ts index b0e34fa..236c456 100644 --- a/packages/storage/src/collections.ts +++ b/packages/storage/src/collections.ts @@ -361,11 +361,69 @@ export function pointerKey( assignmentId: RoleAssignmentId, ): EntityKey { return { - partition: encodeSegment(applicationId), + partition: pointerPartition(applicationId), id: encodeSegment(assignmentId), }; } +/** Partition holding every assignment pointer for one host application. */ +export function pointerPartition(applicationId: ApplicationId): string { + return encodeSegment(applicationId); +} + +/** + * One candidate holder of one role in one exact scope. + * + * Records are partitioned by principal, so "every holder of role R" has no + * partition of its own. This collection supplies one, under the superset + * discipline `docs/STORAGE.md` describes: a row is written before the grant it + * describes and is never deleted, so the index can over-report (a refused + * grant, a revoked assignment) but never under-report a stored assignment. + * Readers treat every row as a candidate and verify it against the + * authoritative lifecycle record before reporting it. + * + * Like a pointer, a row is immutable: the location and role of an assignment + * id are fixed at grant, so the row can be written outside the partition + * transaction. + */ +export interface StoredRoleHolder extends RecordLocation { + readonly assignmentId: RoleAssignmentId; + readonly role: RoleName; +} + +/** Partition holding every candidate holder of one role in one exact scope. */ +export function roleHolderPartition( + applicationId: ApplicationId, + role: RoleName, + scope: RoleAssignmentScope, +): string { + return `${joinSegments([applicationId, role])}|${scopeTag(scope)}`; +} + +export const roleHolders = defineCollection({ + name: "authorization_role_holders", + key: (holder) => ({ + partition: roleHolderPartition( + holder.applicationId, + holder.role, + holder.scope, + ), + id: encodeSegment(holder.assignmentId), + }), + codec: { + encode: (holder) => ({ + ...encodeLocation(holder), + assignmentId: holder.assignmentId, + role: holder.role, + }), + decode: (record) => ({ + ...decodeLocation(record), + assignmentId: String(record["assignmentId"]), + role: String(record["role"]), + }), + }, +}); + /** * Provider identity linked to a host principal. * diff --git a/packages/storage/src/index.test.ts b/packages/storage/src/index.test.ts index 7e30b61..53697e9 100644 --- a/packages/storage/src/index.test.ts +++ b/packages/storage/src/index.test.ts @@ -12,7 +12,11 @@ import type { RoleAssignmentScope, } from "@pegma/authorization-contracts"; import { resolveAccess } from "@pegma/authorization-core"; -import { createMemoryStore } from "@pegma/storage-core"; +import { + createMemoryStore, + defineCollection, + type StoredRecord, +} from "@pegma/storage-core"; import { createInMemoryStorageAdapter, createRoleStore, @@ -24,6 +28,7 @@ import { type RevokeRoleAssignmentResult, type RoleAssignmentAuditReader, type RoleAssignmentReader, + type RoleHolderReader, type VersionedRoleAssignment, } from "@pegma/authorization-storage"; @@ -87,6 +92,7 @@ describe("storage port surface", () => { expectTypeOf(adapter).toMatchTypeOf(); expectTypeOf(adapter).toMatchTypeOf(); expectTypeOf(adapter).toMatchTypeOf(); + expectTypeOf(adapter).toMatchTypeOf(); expectTypeOf(adapter).toMatchTypeOf(); expectTypeOf(adapter).toMatchTypeOf(); expect(Object.isFrozen(adapter)).toBe(true); @@ -642,6 +648,215 @@ describe("role assignment reads", () => { }); }); +describe("by-role selection", () => { + const admin = ( + id: string, + principalId: string, + overrides: Partial = {}, + ) => activeAssignment(id, { principalId, role: "admin", ...overrides }); + + const revoke = async ( + adapter: InMemoryStorageAdapter, + granted: Awaited>, + revokedAtEpochMs = 1_700_000_000_500, + ) => { + const result = await adapter.revokeRoleAssignmentWithAudit({ + assignmentId: granted.record.assignment.id, + expectedConcurrencyToken: granted.record.concurrencyToken, + revokedBy: revoker, + revokedAtEpochMs, + auditEventId: `revoke:${granted.record.assignment.id}`, + }); + if (result.status !== "revoked") { + throw new Error(`expected revoked, received ${result.status}`); + } + }; + + it("lists active holders of one role across principals in stable order", async () => { + const adapter = createInMemoryStorageAdapter(); + await requireGrant( + adapter, + admin("z-tied", "principal_beta", { + grantedAtEpochMs: 1_700_000_000_000, + }), + ); + await requireGrant( + adapter, + admin("late", "principal_gamma", { grantedAtEpochMs: 1_700_000_002_000 }), + ); + await requireGrant( + adapter, + admin("a-tied", "principal_alpha", { + grantedAtEpochMs: 1_700_000_000_000, + }), + ); + await requireGrant(adapter, activeAssignment("other-role")); + + const holders = await adapter.listActiveRoleAssignmentsByRole( + "admin", + applicationScope, + ); + expect(holders.map(({ id, principalId }) => [id, principalId])).toEqual([ + ["a-tied", "principal_alpha"], + ["z-tied", "principal_beta"], + ["late", "principal_gamma"], + ]); + expect(Object.isFrozen(holders)).toBe(true); + expect(Object.isFrozen(holders[0])).toBe(true); + await expect( + adapter.listActiveRoleAssignmentsByRole("auditor", applicationScope), + ).resolves.toEqual([]); + }); + + it("stays correct across grant, revoke, and regrant under a new ID", async () => { + const adapter = createInMemoryStorageAdapter(); + const first = await requireGrant( + adapter, + admin("first", "principal_alpha"), + ); + await requireGrant(adapter, admin("other", "principal_beta")); + + await revoke(adapter, first); + await expect( + adapter.listActiveRoleAssignmentsByRole("admin", applicationScope), + ).resolves.toMatchObject([{ id: "other" }]); + + await requireGrant( + adapter, + admin("regrant", "principal_alpha", { + grantedAtEpochMs: 1_700_000_001_000, + }), + ); + await expect( + adapter.listActiveRoleAssignmentsByRole("admin", applicationScope), + ).resolves.toMatchObject([{ id: "other" }, { id: "regrant" }]); + }); + + it("verifies every row when a role has more rows than one batch", async () => { + const adapter = createInMemoryStorageAdapter(); + const granted = []; + for (let index = 0; index < 40; index += 1) { + granted.push( + await requireGrant( + adapter, + admin( + `admin-${String(index).padStart(2, "0")}`, + `principal_${index}`, + ), + ), + ); + } + for (const record of granted.filter((_, index) => index % 2 === 1)) { + await revoke(adapter, record); + } + const holders = await adapter.listActiveRoleAssignmentsByRole( + "admin", + applicationScope, + ); + expect(holders).toHaveLength(20); + expect(holders.every(({ id }) => Number(id.slice(-2)) % 2 === 0)).toBe( + true, + ); + }); + + it("never reports a refused grant whose index row was written", async () => { + const adapter = createInMemoryStorageAdapter(); + await requireGrant(adapter, admin("held", "principal_alpha")); + await expect( + grant(adapter, admin("refused", "principal_alpha")), + ).resolves.toMatchObject({ status: "conflict", reason: "active_tuple" }); + + await expect( + adapter.listActiveRoleAssignmentsByRole("admin", applicationScope), + ).resolves.toMatchObject([{ id: "held" }]); + }); + + it("isolates holders by exact scope and host application", async () => { + const store = createMemoryStore(); + const first = createRoleStore(store, "application_one"); + const second = createRoleStore(store, "application_two"); + await requireGrant(first, admin("app", "principal_alpha")); + await requireGrant( + first, + admin("org", "principal_beta", { scope: organizationScope }), + ); + await requireGrant(second, admin("elsewhere", "principal_gamma")); + + await expect( + first.listActiveRoleAssignmentsByRole("admin", applicationScope), + ).resolves.toMatchObject([{ id: "app" }]); + await expect( + first.listActiveRoleAssignmentsByRole("admin", organizationScope), + ).resolves.toMatchObject([{ id: "org" }]); + await expect( + first.listActiveRoleAssignmentsByRole("admin", otherOrganizationScope), + ).resolves.toEqual([]); + await expect( + second.listActiveRoleAssignmentsByRole("admin", applicationScope), + ).resolves.toMatchObject([{ id: "elsewhere" }]); + }); + + it("keeps roles whose names differ only by the key separator distinct", async () => { + const adapter = createInMemoryStorageAdapter(); + await requireGrant( + adapter, + activeAssignment("piped", { + role: "a|b", + principalId: "principal_alpha", + }), + ); + await requireGrant( + adapter, + activeAssignment("plain", { role: "a", principalId: "principal_beta" }), + ); + + await expect( + adapter.listActiveRoleAssignmentsByRole("a|b", applicationScope), + ).resolves.toMatchObject([{ id: "piped" }]); + await expect( + adapter.listActiveRoleAssignmentsByRole("a", applicationScope), + ).resolves.toMatchObject([{ id: "plain" }]); + }); + + it("rebuilds rows for assignments granted before the index existed", async () => { + const store = createMemoryStore(); + const adapter = createRoleStore(store, "application_one"); + const kept = await requireGrant(adapter, admin("kept", "principal_alpha")); + const gone = await requireGrant(adapter, admin("gone", "principal_beta")); + await revoke(adapter, gone); + // Simulate the pre-index state: drop the rows these grants wrote, as a + // grant made before the index existed never wrote one. + const holderRows = store.collection( + defineCollection({ + name: "authorization_role_holders", + key: () => { + throw new Error("read-only test view"); + }, + codec: { encode: (record) => record, decode: (record) => record }, + }), + ); + const partition = "application_one|admin|application"; + expect(await holderRows.delete({ partition, id: "kept" })).toBe(true); + expect(await holderRows.delete({ partition, id: "gone" })).toBe(true); + // Fail-closed while the index is incomplete: nothing is reported. + await expect( + adapter.listActiveRoleAssignmentsByRole("admin", applicationScope), + ).resolves.toEqual([]); + + await expect(adapter.rebuildRoleHolderIndex()).resolves.toEqual({ + recorded: 2, + }); + // Idempotent: a second run finds every row in place. + await expect(adapter.rebuildRoleHolderIndex()).resolves.toEqual({ + recorded: 0, + }); + expect(kept.record.assignment.id).toBe("kept"); + await expect( + adapter.listActiveRoleAssignmentsByRole("admin", applicationScope), + ).resolves.toMatchObject([{ id: "kept" }]); + }); +}); + describe("audited grant", () => { it("atomically grants sequence one and revokes sequence two", async () => { const adapter = createInMemoryStorageAdapter(); diff --git a/packages/storage/src/index.ts b/packages/storage/src/index.ts index 55e4555..13b9fe8 100644 --- a/packages/storage/src/index.ts +++ b/packages/storage/src/index.ts @@ -9,6 +9,7 @@ import type { RoleAssignmentActor, RoleAssignmentId, RoleAssignmentScope, + RoleName, } from "@pegma/authorization-contracts"; /** @@ -96,6 +97,63 @@ export interface RoleAssignmentReader { ) => Promise; } +/** + * Cross-principal by-role selection. + * + * Separate from {@link RoleAssignmentReader} so hosts that implement the + * storage ports themselves are not required to provide it. Role + * administration surfaces use it to answer "who holds role R in this scope", + * including the last-administrator guard's "does another active holder + * exist". + */ +export interface RoleHolderReader { + /** + * Every active assignment of one role in one exact scope, across + * principals, ordered by `grantedAtEpochMs` ascending and then by + * assignment ID code-unit order. + * + * Every result is verified against the authoritative lifecycle record, so + * a revoked or refused assignment is never reported as active. Like the + * per-principal listings this is a non-snapshot read: a concurrent grant or + * revoke in another principal's partition may or may not be reflected, so + * an at-least-one invariant still needs the re-verify-after-commit + * treatment in `docs/STORAGE.md`. + * + * Implementations must verify every reported assignment against the + * authoritative lifecycle record; an unverified secondary-index read is + * not conforming, because a stale row would count a revoked holder. + * + * An empty array means definitive emptiness once the index covers every + * stored assignment. For the provided adapters that holds after + * `rebuildRoleHolderIndex` has run once over a store that holds grants + * made before the index existed; until then an empty result can omit + * those grants. Implementations reject partial, operationally failed, or + * corrupt results. + */ + readonly listActiveRoleAssignmentsByRole: ( + role: RoleName, + scope: RoleAssignmentScope, + ) => Promise; +} + +/** Result of one by-role index rebuild. */ +export interface RebuildRoleHolderIndexResult { + /** Index rows written by this run; rows already present are not counted. */ + readonly recorded: number; +} + +/** + * Maintenance for the library-maintained by-role index. + * + * Grants made through this version and later maintain the index themselves. + * Assignments granted by an earlier version have no index row until + * `rebuildRoleHolderIndex` runs once over the backing store. It is + * idempotent and safe to run concurrently with grants and revocations. + */ +export interface RoleHolderIndexMaintenance { + readonly rebuildRoleHolderIndex: () => Promise; +} + /** Result of atomically attempting to create one active assignment. */ export type CreateRoleAssignmentResult = | Readonly<{ @@ -308,6 +366,8 @@ export interface InMemoryStorageAdapter extends IdentityLinkStore, RoleAssignmentReader, + RoleHolderReader, + RoleHolderIndexMaintenance, RoleAssignmentAuditReader, AuditedRoleAssignmentMutationStore {} diff --git a/packages/storage/src/role-store.ts b/packages/storage/src/role-store.ts index ed851c0..eae25f0 100644 --- a/packages/storage/src/role-store.ts +++ b/packages/storage/src/role-store.ts @@ -25,8 +25,11 @@ import { identityLinkKey, identityLinks as identityLinkCollection, pointerKey, + pointerPartition, recordPartition, REVOKE_SEQUENCE, + roleHolderPartition, + roleHolders, tupleRecordId, type ApplicationId, type AuthorizationRecord, @@ -44,6 +47,7 @@ import type { InMemoryStorageAdapter, InMemoryStorageAdapterOptions, LinkIdentityResult, + RebuildRoleHolderIndexResult, SequencedRoleAssignmentAuditEvent, VersionedRoleAssignment, } from "./index.js"; @@ -148,6 +152,18 @@ const freezeAuditRecord = ( return Object.freeze(record); }; +/** Authoritative point reads issued concurrently by one by-role read. */ +const HOLDER_VERIFY_BATCH = 16; + +const byGrantThenId = (left: RoleAssignment, right: RoleAssignment): number => + left.grantedAtEpochMs !== right.grantedAtEpochMs + ? left.grantedAtEpochMs - right.grantedAtEpochMs + : left.id < right.id + ? -1 + : left.id > right.id + ? 1 + : 0; + const scopesEqual = ( left: RoleAssignmentScope, right: RoleAssignmentScope, @@ -281,6 +297,7 @@ export const createRoleStore = ( const records = store.collection(authorizationRecords); const pointers = store.collection(assignmentPointers); const links = store.collection(identityLinkCollection); + const holders = store.collection(roleHolders); const locate = async ( assignmentId: RoleAssignmentId, @@ -408,19 +425,94 @@ export const createRoleStore = ( record.kind === "assignment", ) .map(({ assignment }) => assignment) - .sort((left, right) => - left.grantedAtEpochMs !== right.grantedAtEpochMs - ? left.grantedAtEpochMs - right.grantedAtEpochMs - : left.id < right.id - ? -1 - : left.id > right.id - ? 1 - : 0, + .sort(byGrantThenId) + .map((assignment) => freezeAssignment(assignment)), + ); + }, + + async listActiveRoleAssignmentsByRole( + role: RoleName, + scope: RoleAssignmentScope, + ): Promise { + const exact = snapshotScope(scope); + const candidates = await holders.list( + roleHolderPartition(applicationId, role, exact), + ); + const verify = async ( + candidate: (typeof candidates)[number], + ): Promise => { + if (candidate.role !== role || !scopesEqual(candidate.scope, exact)) { + throw corrupt(`a ${role} holder row disagrees with its partition`); + } + // Rows are candidates only. A row whose grant was refused has no + // lifecycle behind it and reads as nothing. + const current = await readAssignment(candidate, candidate.assignmentId); + if (current === null) { + return null; + } + const assignment = current.stored.assignment; + if ( + assignment.principalId !== candidate.principalId || + assignment.role !== role || + !scopesEqual(assignment.scope, exact) + ) { + throw corrupt( + `${candidate.assignmentId} disagrees with its holder row`, + ); + } + return assignment.status === "active" ? assignment : null; + }; + // Bounded fan-out: the partition keeps every historical row, so verify + // in fixed-size batches rather than one unbounded burst of point reads. + const verified: (ActiveRoleAssignment | null)[] = []; + for ( + let start = 0; + start < candidates.length; + start += HOLDER_VERIFY_BATCH + ) { + verified.push( + ...(await Promise.all( + candidates.slice(start, start + HOLDER_VERIFY_BATCH).map(verify), + )), + ); + } + return Object.freeze( + verified + .filter( + (assignment): assignment is ActiveRoleAssignment => + assignment !== null, ) + .sort(byGrantThenId) .map((assignment) => freezeAssignment(assignment)), ); }, + async rebuildRoleHolderIndex(): Promise { + // Every assignment ever granted has a pointer, and pointers already + // carry the location and role a holder row needs. + const known = await pointers.list(pointerPartition(applicationId)); + let recorded = 0; + for (const pointer of known) { + if (pointer.applicationId !== applicationId) { + throw corrupt(`${pointer.assignmentId} points outside its namespace`); + } + if ((await readAssignment(pointer, pointer.assignmentId)) === null) { + continue; + } + const written = await holders.insertIfAbsent({ + applicationId, + principalId: pointer.principalId, + scope: pointer.scope, + assignmentId: pointer.assignmentId, + role: pointer.role, + }); + if (written.inserted) { + recorded += 1; + } + } + return Object.freeze({ recorded }); + }, + async listRoleAssignmentAuditEvents( assignmentId: RoleAssignmentId, ): Promise { @@ -489,6 +581,14 @@ export const createRoleStore = ( return conflict("assignment_id"); } + // Written before the grant, never deleted: the by-role index may + // over-report a refused grant but can never miss a stored one. + await holders.insertIfAbsent({ + ...location, + assignmentId: assignment.id, + role: assignment.role, + }); + const guard = await records.getVersioned({ partition, id: tupleRecordId(assignment.role),