diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c6b6b57..aca1e81 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -104,11 +104,30 @@ jobs: RELEASE_COMMIT: ${{ github.sha }} steps: - - name: Check out the exact release tag + - name: Check out the release event commit uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - ref: refs/tags/${{ github.event.release.tag_name }} + ref: ${{ github.sha }} fetch-depth: 1 + persist-credentials: false + + - name: Confirm the release tag target + shell: bash + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + authorization="$(printf 'x-access-token:%s' "${GITHUB_TOKEN}" | base64 | tr -d '\n')" + unset GITHUB_TOKEN + GIT_CONFIG_COUNT=1 \ + GIT_CONFIG_KEY_0=http.https://github.com/.extraheader \ + GIT_CONFIG_VALUE_0="AUTHORIZATION: basic ${authorization}" \ + git fetch --force --no-tags origin "refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + unset authorization + tag_commit="$(git rev-parse "refs/tags/${RELEASE_TAG}^{commit}")" + if [[ "${tag_commit}" != "${RELEASE_COMMIT}" ]]; then + echo "::error::Release tag target does not match the release event commit" + exit 1 + fi - name: Set up Node.js and the npm registry uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 @@ -127,4 +146,4 @@ jobs: path: .release - name: Publish prepared tarballs - run: npm run release:publish -- -- --expected-release-commit "${RELEASE_COMMIT}" --manifest .release/package-manifest.json + run: node scripts/release-packages.mjs publish --expected-release-commit "${RELEASE_COMMIT}" --manifest .release/package-manifest.json diff --git a/docs/POLICY.md b/docs/POLICY.md index a8af506..ff96b1f 100644 --- a/docs/POLICY.md +++ b/docs/POLICY.md @@ -72,12 +72,19 @@ A policy version is 1–128 ASCII characters and matches: ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$ ``` -The `defaults`, `roles`, and `entitlements` sections are optional. Present -sections must use arrays and objects exactly as shown; `null`, sparse arrays, -accessors, inherited configuration, custom prototypes, symbols, and non-JSON -values are rejected. Successful validation returns a detached, deeply frozen -copy so later mutation of the decoded input cannot change authorization -behavior. +The `defaults`, `roles`, and `entitlements` sections are optional. Present grant +lists must be ordinary dense arrays, while the document and mapping objects may +use either `Object.prototype` or a null prototype. `null`, accessors, inherited +configuration, symbols, non-JSON values, and other prototypes are rejected. +Successful validation returns a detached, deeply frozen copy with a null +prototype, so later mutation of the decoded input cannot change authorization +behavior. Parsed output may be passed directly to `validatePolicy` or +`parsePolicy` again. + +Core resolution reads optional subject and policy fields only from own data +properties. Inherited optional fields are ignored, and an own optional field +whose value is `undefined` is treated as absent. A present role or entitlement +map entry must be an array; `null` entries are rejected. ## Permission names diff --git a/docs/STORAGE.md b/docs/STORAGE.md index d6b43f4..4886136 100644 --- a/docs/STORAGE.md +++ b/docs/STORAGE.md @@ -125,20 +125,21 @@ 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. +one exact holder confirmation per row, followed by pointer lookup and an +authoritative assignment read 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 +application's assignment pointers, confirms each through its exact key, 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 @@ -346,12 +347,19 @@ partition and would therefore leave the transaction boundary. ## Non-snapshot reads -`listActiveRoleAssignments` and `listRoleAssignments` are each one partition -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 -assignment as active. +`listActiveRoleAssignments` and `listRoleAssignments` each begin with one +partition 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 assignment as active. + +Each decoded row is confirmed through its recomputed exact record key before it +is used, with point reads issued in batches of 16. A key outside the requested +partition or a duplicate recomputed key rejects as malformed. If a row vanishes +or changes between the partition listing and point confirmation, the read +rejects with a retry-oriented storage error. This confirmation is still not a +snapshot. The host's cache generation fence is therefore load-bearing rather than belt-and-braces. A fill must capture all applicable generations before its diff --git a/docs/api/authorization-policy.md b/docs/api/authorization-policy.md index bbcc2c3..64f1778 100644 --- a/docs/api/authorization-policy.md +++ b/docs/api/authorization-policy.md @@ -153,9 +153,10 @@ export type PolicyValidationResult = Validate an already parsed policy value without returning a partial policy. -The input must have the same ordinary data-property shape produced by -JSON.parse. Unexpected proxies or reflective failures are reported as an -invalid structure rather than escaping the fail-closed boundary. +The input must use enumerable data properties and either the ordinary JSON +object prototype or a null prototype. Unexpected proxies or reflective +failures are reported as an invalid structure rather than escaping the +fail-closed boundary. ```ts export declare function validatePolicy(input: unknown): PolicyValidationResult; diff --git a/packages/core/src/index.test.ts b/packages/core/src/index.test.ts index 28aac26..ef77e12 100644 --- a/packages/core/src/index.test.ts +++ b/packages/core/src/index.test.ts @@ -7,7 +7,7 @@ import { resolveAccessWithDiagnostics, serializeAccessContext, } from "./index.js"; -import type { AccessContext } from "./index.js"; +import type { AccessContext, AccessPolicy, AccessSubject } from "./index.js"; const policy = { version: "test-1", @@ -125,6 +125,274 @@ describe("resolveAccess", () => { expect(context.permissions).toEqual(["account.read.own"]); }); + it("treats optional fields inherited from custom prototypes as absent", () => { + let inheritedGetterReads = 0; + const subjectPrototype = Object.defineProperties( + {}, + { + roles: { + get() { + inheritedGetterReads += 1; + return ["support"]; + }, + }, + entitlements: { + get() { + inheritedGetterReads += 1; + return ["plan.pro"]; + }, + }, + }, + ); + const policyPrototype = Object.defineProperties( + {}, + { + defaults: { + get() { + inheritedGetterReads += 1; + return ["account.read.own"]; + }, + }, + roles: { + get() { + inheritedGetterReads += 1; + return { support: ["support.queue.read"] }; + }, + }, + entitlements: { + get() { + inheritedGetterReads += 1; + return { "plan.pro": ["support.ticket.create"] }; + }, + }, + }, + ); + const subject = Object.assign(Object.create(subjectPrototype), { + principalId: "principal-custom-prototype", + }) as AccessSubject; + const inheritedPolicy = Object.assign(Object.create(policyPrototype), { + version: "custom-prototype-1", + }) as AccessPolicy; + + expect(resolveAccess(subject, inheritedPolicy)).toEqual({ + principalId: "principal-custom-prototype", + policyVersion: "custom-prototype-1", + roles: [], + entitlements: [], + permissions: [], + }); + expect(inheritedGetterReads).toBe(0); + }); + + it("treats optional fields inherited from Object.prototype as absent", () => { + const fields = ["defaults", "roles", "entitlements"] as const; + const originalDescriptors = new Map( + fields.map((field) => [ + field, + Object.getOwnPropertyDescriptor(Object.prototype, field), + ]), + ); + let context: AccessContext | undefined; + + try { + Object.defineProperties(Object.prototype, { + defaults: { + configurable: true, + value: ["account.read.own"], + }, + roles: { + configurable: true, + value: ["support"], + }, + entitlements: { + configurable: true, + value: ["plan.pro"], + }, + }); + + context = resolveAccess( + { principalId: "principal-object-prototype" }, + { version: "object-prototype-1" }, + ); + } finally { + for (const field of fields) { + const descriptor = originalDescriptors.get(field); + if (descriptor === undefined) { + Reflect.deleteProperty(Object.prototype, field); + } else { + Object.defineProperty(Object.prototype, field, descriptor); + } + } + } + + expect(context).toEqual({ + principalId: "principal-object-prototype", + policyVersion: "object-prototype-1", + roles: [], + entitlements: [], + permissions: [], + }); + }); + + it("rejects own accessor-backed resolver fields without invoking them", () => { + const cases = [ + { + label: "roles", + run(read: () => void) { + const subject = { principalId: "principal-accessor-roles" }; + Object.defineProperty(subject, "roles", { get: read }); + resolveAccess(subject as AccessSubject, policy); + }, + }, + { + label: "entitlements", + run(read: () => void) { + const subject = { principalId: "principal-accessor-entitlements" }; + Object.defineProperty(subject, "entitlements", { get: read }); + resolveAccess(subject as AccessSubject, policy); + }, + }, + { + label: "policy.defaults", + run(read: () => void) { + const accessorPolicy = { version: "accessor-defaults-1" }; + Object.defineProperty(accessorPolicy, "defaults", { get: read }); + resolveAccess( + { principalId: "principal-accessor-defaults" }, + accessorPolicy, + ); + }, + }, + { + label: "policy.roles", + run(read: () => void) { + const accessorPolicy = { version: "accessor-roles-1" }; + Object.defineProperty(accessorPolicy, "roles", { get: read }); + resolveAccess( + { principalId: "principal-accessor-policy-roles" }, + accessorPolicy, + ); + }, + }, + { + label: "policy.entitlements", + run(read: () => void) { + const accessorPolicy = { version: "accessor-entitlements-1" }; + Object.defineProperty(accessorPolicy, "entitlements", { get: read }); + resolveAccess( + { principalId: "principal-accessor-policy-entitlements" }, + accessorPolicy, + ); + }, + }, + ] as const; + + for (const testCase of cases) { + let accessorRead = false; + expect(() => + testCase.run(() => { + accessorRead = true; + }), + ).toThrowError(`${testCase.label} must be an own data property`); + expect(accessorRead).toBe(false); + } + }); + + it("rejects accessor-backed assignment entries without invoking them", () => { + let roleGetterRead = false; + const roles = {} as Record; + Object.defineProperty(roles, "support", { + get() { + roleGetterRead = true; + return ["support.queue.read"]; + }, + }); + + expect(() => + resolveAccess( + { principalId: "principal-assignment-accessor", roles: ["support"] }, + { version: "assignment-accessor-1", roles }, + ), + ).toThrowError("policy.roles.support must be an own data property"); + expect(roleGetterRead).toBe(false); + }); + + it("reads array length from its own data descriptor", () => { + let directLengthReads = 0; + const roles = new Proxy(["support"], { + get(target, property, receiver) { + if (property === "length") { + directLengthReads += 1; + throw new Error("array length was read directly"); + } + return Reflect.get(target, property, receiver) as unknown; + }, + }); + + const context = resolveAccess( + { principalId: "principal-array-length", roles }, + policy, + ); + + expect(context.roles).toEqual(["support"]); + expect(context.permissions).toContain("support.queue.read"); + expect(directLengthReads).toBe(0); + }); + + it("treats own undefined optional fields as absent", () => { + const context = resolveAccess( + { + principalId: "principal-undefined-optionals", + roles: undefined, + entitlements: undefined, + } as unknown as AccessSubject, + { + version: "undefined-optionals-1", + defaults: undefined, + roles: undefined, + entitlements: undefined, + } as unknown as AccessPolicy, + ); + + expect(context).toEqual({ + principalId: "principal-undefined-optionals", + policyVersion: "undefined-optionals-1", + roles: [], + entitlements: [], + permissions: [], + }); + }); + + it("rejects null role and entitlement entries", () => { + const nullRoles = { support: null } as unknown as Record< + string, + readonly string[] + >; + const nullEntitlements = { "plan.pro": null } as unknown as Record< + string, + readonly string[] + >; + + expect(() => + resolveAccess( + { principalId: "principal-null-role", roles: ["support"] }, + { version: "null-role-1", roles: nullRoles }, + ), + ).toThrowError("policy.roles.support must be an array of strings"); + expect(() => + resolveAccess( + { + principalId: "principal-null-entitlement", + entitlements: ["plan.pro"], + }, + { + version: "null-entitlement-1", + entitlements: nullEntitlements, + }, + ), + ).toThrowError("policy.entitlements.plan.pro must be an array of strings"); + }); + it("rejects empty identifiers and permission names", () => { expect(() => resolveAccess({ principalId: " " }, policy)).toThrowError( "principalId must not be empty", diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c2daed2..20dfec8 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -27,40 +27,79 @@ function requireName(value: string, field: string): void { } } -function ownDataValue(value: object, field: string): unknown { +function ownDataValue( + value: object, + field: string, + label: string = field, +): unknown { + if (!Object.hasOwn(value, field)) { + throw new TypeError(`${label} must be an own data property`); + } + + const descriptor = Object.getOwnPropertyDescriptor(value, field); + if (descriptor === undefined || !("value" in descriptor)) { + throw new TypeError(`${label} must be an own data property`); + } + + return descriptor.value; +} + +function optionalOwnDataValue( + value: object, + field: string, + label: string = field, +): unknown { + if (!Object.hasOwn(value, field)) { + return undefined; + } + const descriptor = Object.getOwnPropertyDescriptor(value, field); if (descriptor === undefined || !("value" in descriptor)) { - throw new TypeError(`${field} must be an own data property`); + throw new TypeError(`${label} must be an own data property`); } return descriptor.value; } -function requiredString(value: object, field: string): string { - const candidate = ownDataValue(value, field); +function requiredString( + value: object, + field: string, + label: string = field, +): string { + const candidate = ownDataValue(value, field, label); if (typeof candidate !== "string") { - throw new TypeError(`${field} must be a string`); + throw new TypeError(`${label} must be a string`); } - requireName(candidate, field); + requireName(candidate, label); return candidate; } -function copyStringArray(value: object, field: string): string[] { - const candidate = ownDataValue(value, field); +function copyStringArrayValue(candidate: unknown, label: string): string[] { if (!Array.isArray(candidate)) { - throw new TypeError(`${field} must be an array of strings`); + throw new TypeError(`${label} must be an array of strings`); + } + + const lengthDescriptor = Object.getOwnPropertyDescriptor(candidate, "length"); + if ( + lengthDescriptor === undefined || + !("value" in lengthDescriptor) || + typeof lengthDescriptor.value !== "number" || + !Number.isSafeInteger(lengthDescriptor.value) || + lengthDescriptor.value < 0 + ) { + throw new TypeError(`${label} must be a dense array of strings`); } const copy: string[] = []; - for (let index = 0; index < candidate.length; index += 1) { + for (let index = 0; index < lengthDescriptor.value; index += 1) { const descriptor = Object.getOwnPropertyDescriptor(candidate, index); if ( descriptor === undefined || !("value" in descriptor) || typeof descriptor.value !== "string" ) { - throw new TypeError(`${field} must be a dense array of strings`); + throw new TypeError(`${label} must be a dense array of strings`); } copy.push(descriptor.value); @@ -69,6 +108,19 @@ function copyStringArray(value: object, field: string): string[] { return copy; } +function copyStringArray(value: object, field: string): string[] { + return copyStringArrayValue(ownDataValue(value, field), field); +} + +function copyOptionalStringArray( + value: object, + field: string, + label: string, +): string[] { + const candidate = optionalOwnDataValue(value, field, label); + return candidate === undefined ? [] : copyStringArrayValue(candidate, label); +} + function serializeJsonString(value: string): string { const serialized = JSON.stringify(value); if (serialized === undefined) { @@ -89,29 +141,66 @@ function uniqueSorted(values: readonly string[]): readonly string[] { function ownPermissions( assignments: Readonly> | undefined, name: string, + label: string, ): readonly PermissionName[] | undefined { if (assignments === undefined || !Object.hasOwn(assignments, name)) { return undefined; } - return assignments[name] ?? []; + const descriptor = Object.getOwnPropertyDescriptor(assignments, name); + if (descriptor === undefined || !("value" in descriptor)) { + throw new TypeError(`${label}.${name} must be an own data property`); + } + + if (descriptor.value === undefined) { + return []; + } + + return copyStringArrayValue(descriptor.value, `${label}.${name}`); +} + +function optionalPermissionMap( + policy: AccessPolicy, + field: "roles" | "entitlements", +): Readonly> | undefined { + const label = `policy.${field}`; + const candidate = optionalOwnDataValue(policy, field, label); + if (candidate === undefined) { + return undefined; + } + if (typeof candidate !== "object" || candidate === null) { + throw new TypeError(`${label} must be an object`); + } + + return candidate as Readonly>; } function resolveAccessInternal( subject: AccessSubject, policy: AccessPolicy, ): AccessResolution { - requireName(subject.principalId, "principalId"); - requireName(policy.version, "policy.version"); + const principalId = requiredString(subject, "principalId"); + const policyVersion = requiredString(policy, "version", "policy.version"); + const roles = uniqueSorted( + copyOptionalStringArray(subject, "roles", "roles"), + ); + const entitlements = uniqueSorted( + copyOptionalStringArray(subject, "entitlements", "entitlements"), + ); + const defaults = copyOptionalStringArray( + policy, + "defaults", + "policy.defaults", + ); + const roleAssignments = optionalPermissionMap(policy, "roles"); + const entitlementAssignments = optionalPermissionMap(policy, "entitlements"); - const roles = uniqueSorted(subject.roles ?? []); - const entitlements = uniqueSorted(subject.entitlements ?? []); - const granted = new Set(policy.defaults ?? []); + const granted = new Set(defaults); const unknownRoles: string[] = []; const unknownEntitlements: string[] = []; for (const role of roles) { - const permissions = ownPermissions(policy.roles, role); + const permissions = ownPermissions(roleAssignments, role, "policy.roles"); if (permissions === undefined) { unknownRoles.push(role); continue; @@ -123,7 +212,11 @@ function resolveAccessInternal( } for (const entitlement of entitlements) { - const permissions = ownPermissions(policy.entitlements, entitlement); + const permissions = ownPermissions( + entitlementAssignments, + entitlement, + "policy.entitlements", + ); if (permissions === undefined) { unknownEntitlements.push(entitlement); continue; @@ -135,8 +228,8 @@ function resolveAccessInternal( } const context = Object.freeze({ - principalId: subject.principalId, - policyVersion: policy.version, + principalId, + policyVersion, roles, entitlements, permissions: uniqueSorted([...granted]), diff --git a/packages/policy/src/index.test.ts b/packages/policy/src/index.test.ts index 74eaae2..a799b1a 100644 --- a/packages/policy/src/index.test.ts +++ b/packages/policy/src/index.test.ts @@ -33,6 +33,7 @@ describe("PolicyDocumentV1", () => { expect(policy).toEqual({ schemaVersion: 1, version: "v1" }); expect(policy.schemaVersion).toBe(POLICY_SCHEMA_VERSION); + expect(Object.getPrototypeOf(policy)).toBeNull(); expect(Object.isFrozen(policy)).toBe(true); }); @@ -76,6 +77,23 @@ describe("PolicyDocumentV1", () => { expect(second).toEqual(first); }); + it("revalidates parsed null-prototype output", () => { + const first = parsePolicy({ + schemaVersion: 1, + version: "direct-round-trip-1", + defaults: ["account.read.own"], + roles: { support: ["support.queue.read"] }, + entitlements: { "plan.pro": ["planner.desktop.use"] }, + }); + + const second = parsePolicy(first); + + expect(second).toEqual(first); + expect(Object.getPrototypeOf(second)).toBeNull(); + expect(Object.getPrototypeOf(second.roles)).toBeNull(); + expect(Object.getPrototypeOf(second.entitlements)).toBeNull(); + }); + it("integrates with core while allowing cross-source overlap", () => { const policy = parsePolicy({ schemaVersion: 1, @@ -336,17 +354,7 @@ describe("strict document validation", () => { Object.create({ defaults: ["inherited.read"] }), { schemaVersion: 1, version: "v1" }, ); - const nullPrototypeDocument = Object.assign(Object.create(null), { - schemaVersion: 1, - version: "v1", - }); - - for (const input of [ - symbolDocument, - accessorDocument, - inheritedDocument, - nullPrototypeDocument, - ]) { + for (const input of [symbolDocument, accessorDocument, inheritedDocument]) { expect(diagnosticCodes(input)).toContain("invalid_structure"); } }); diff --git a/packages/policy/src/index.ts b/packages/policy/src/index.ts index d623ef1..9980bb8 100644 --- a/packages/policy/src/index.ts +++ b/packages/policy/src/index.ts @@ -112,9 +112,10 @@ function invalidResult( } function plainRecordIssue(value: object): string | undefined { + const prototype = Object.getPrototypeOf(value); if ( Array.isArray(value) || - Object.getPrototypeOf(value) !== Object.prototype + (prototype !== Object.prototype && prototype !== null) ) { return "Expected an ordinary JSON object."; } @@ -461,16 +462,15 @@ function validatePolicyInternal(input: unknown): PolicyValidationResult { return invalidResult(diagnostics); } - const policy: { + const policy = Object.create(null) as { schemaVersion: typeof POLICY_SCHEMA_VERSION; version: string; defaults?: readonly PermissionName[]; roles?: Readonly>; entitlements?: Readonly>; - } = { - schemaVersion: POLICY_SCHEMA_VERSION, - version, }; + policy.schemaVersion = POLICY_SCHEMA_VERSION; + policy.version = version; if (defaults !== undefined) { policy.defaults = defaults; } @@ -490,9 +490,10 @@ function validatePolicyInternal(input: unknown): PolicyValidationResult { /** * Validate an already parsed policy value without returning a partial policy. * - * The input must have the same ordinary data-property shape produced by - * JSON.parse. Unexpected proxies or reflective failures are reported as an - * invalid structure rather than escaping the fail-closed boundary. + * The input must use enumerable data properties and either the ordinary JSON + * object prototype or a null prototype. Unexpected proxies or reflective + * failures are reported as an invalid structure rather than escaping the + * fail-closed boundary. */ export function validatePolicy(input: unknown): PolicyValidationResult { try { diff --git a/packages/storage/src/collections.test.ts b/packages/storage/src/collections.test.ts new file mode 100644 index 0000000..e359135 --- /dev/null +++ b/packages/storage/src/collections.test.ts @@ -0,0 +1,706 @@ +import { describe, expect, it } from "vitest"; + +import type { ActiveRoleAssignment } from "@pegma/authorization-contracts"; +import { + createMemoryStore, + defineCollection, + StorageError, + type CollectionDefinition, + type CollectionStore, + type EntityKey, + type Store, + type StoredRecord, + type StoredValue, +} from "@pegma/storage-core"; + +import { + assignmentPointers, + assignmentRecordId, + auditRecordId, + authorizationRecords, + GRANT_SEQUENCE, + identityLinkKey, + identityLinks, + pointerKey, + recordPartition, + REVOKE_SEQUENCE, + roleHolderPartition, + roleHolders, + tupleRecordId, + type AuthorizationRecord, + type RecordLocation, + type StoredAssignment, + type StoredAssignmentPointer, + type StoredAudit, + type StoredIdentityLink, + type StoredRoleHolder, + type StoredTuple, +} from "./collections.js"; +import { createRoleStore, storedRecordsEqual } from "./role-store.js"; + +const APPLICATION_ID = "application_one"; +const ASSIGNMENT_ID = "assignment_one"; +const PRINCIPAL_ID = "principal_one"; +const ROLE = "support"; +const GRANT_EVENT_ID = "grant_one"; +const applicationScope = { kind: "application" } as const; +const location: RecordLocation = { + applicationId: APPLICATION_ID, + principalId: PRINCIPAL_ID, + scope: applicationScope, +}; +const assignment: ActiveRoleAssignment = { + id: ASSIGNMENT_ID, + principalId: PRINCIPAL_ID, + role: ROLE, + scope: applicationScope, + grantedBy: { kind: "principal", principalId: "principal_admin" }, + grantedAtEpochMs: 1_700_000_000_000, + status: "active", +}; +const storedAssignment: StoredAssignment = { + kind: "assignment", + ...location, + assignment, + grantEventId: GRANT_EVENT_ID, + revokeEventId: null, +}; +const pointer: StoredAssignmentPointer = { + ...location, + assignmentId: ASSIGNMENT_ID, + role: ROLE, +}; + +const replaceFields = ( + record: StoredRecord, + replacements: Readonly>, +): StoredRecord => ({ ...record, ...replacements }); + +const omitField = (record: StoredRecord, field: string): StoredRecord => { + const copy: Record = { ...record }; + delete copy[field]; + return copy; +}; + +const putRaw = async ( + store: Store, + name: string, + key: EntityKey, + record: StoredRecord, +): Promise => { + const collection = store.collection( + defineCollection({ + name, + key: () => key, + codec: { + encode: (value) => value, + decode: (value) => value, + }, + }), + ); + await collection.put(record); +}; + +const putPointer = (store: Store): Promise => + putRaw( + store, + assignmentPointers.name, + pointerKey(APPLICATION_ID, ASSIGNMENT_ID), + assignmentPointers.codec.encode(pointer), + ); + +const putAssignment = ( + store: Store, + record = authorizationRecords.codec.encode(storedAssignment), +): Promise => + putRaw( + store, + authorizationRecords.name, + { + partition: recordPartition(location), + id: assignmentRecordId(ASSIGNMENT_ID), + }, + record, + ); + +const wrapAuthorizationRecords = ( + store: Store, + wrap: ( + collection: CollectionStore, + ) => CollectionStore, +): Store => ({ + collection(definition: CollectionDefinition): CollectionStore { + const collection = store.collection(definition); + if (definition.name !== authorizationRecords.name) { + return collection; + } + return wrap( + collection as unknown as CollectionStore, + ) as unknown as CollectionStore; + }, +}); + +const requireGrant = async (store: Store) => { + const adapter = createRoleStore(store, APPLICATION_ID); + const result = await adapter.grantRoleAssignmentWithAudit({ + assignment, + auditEventId: GRANT_EVENT_ID, + }); + if (result.status !== "granted") { + throw new Error(`expected granted, received ${result.status}`); + } + return adapter; +}; + +describe("storage collection codecs", () => { + const activeRecord = authorizationRecords.codec.encode(storedAssignment); + + it("round-trips exact active and revoked assignment records", () => { + expect(authorizationRecords.codec.decode(activeRecord)).toEqual( + storedAssignment, + ); + + const revoked: StoredAssignment = { + ...storedAssignment, + assignment: { + ...assignment, + status: "revoked", + revokedBy: { kind: "system", systemId: "role-administration" }, + revokedAtEpochMs: assignment.grantedAtEpochMs + 1, + reason: "routine cleanup", + }, + revokeEventId: "revoke_one", + }; + expect( + authorizationRecords.codec.decode( + authorizationRecords.codec.encode(revoked), + ), + ).toEqual(revoked); + }); + + it.each([ + ["unknown status", replaceFields(activeRecord, { status: "pending" })], + ["missing field", omitField(activeRecord, "role")], + ["extra field", replaceFields(activeRecord, { extra: "value" })], + [ + "wrong field type", + replaceFields(activeRecord, { grantedAtEpochMs: "1700000000000" }), + ], + ["unknown scope", replaceFields(activeRecord, { scopeKind: "tenant" })], + [ + "unknown actor", + replaceFields(activeRecord, { grantedByKind: "operator" }), + ], + ])("rejects an assignment record with %s", (_label, record) => { + expect(() => authorizationRecords.codec.decode(record)).toThrow( + StorageError, + ); + }); + + it("rejects accessor-backed fields", () => { + const record = { ...activeRecord }; + Object.defineProperty(record, "role", { + enumerable: true, + get: () => ROLE, + }); + expect(() => + authorizationRecords.codec.decode(record as StoredRecord), + ).toThrow(StorageError); + }); + + it("treats symbol-bearing stored records as unequal", () => { + const extra = Symbol("extra"); + const clean = { field: "value" } as StoredRecord; + const withSymbol = { + field: "value", + [extra]: "extra", + } as unknown as StoredRecord; + + expect(storedRecordsEqual(clean, withSymbol)).toBe(false); + expect(storedRecordsEqual(withSymbol, clean)).toBe(false); + expect(storedRecordsEqual(withSymbol, withSymbol)).toBe(false); + }); + + it("rejects unknown record kinds and lifecycle positions", () => { + const tuple: StoredTuple = { + kind: "tuple", + ...location, + role: ROLE, + activeAssignmentId: ASSIGNMENT_ID, + }; + expect(() => + authorizationRecords.codec.decode( + replaceFields(authorizationRecords.codec.encode(tuple), { + kind: "other", + }), + ), + ).toThrow(StorageError); + + const lifecyclePosition: StoredAudit = { + kind: "audit", + ...location, + assignmentId: ASSIGNMENT_ID, + sequence: GRANT_SEQUENCE, + eventId: GRANT_EVENT_ID, + }; + expect(() => + authorizationRecords.codec.decode( + replaceFields(authorizationRecords.codec.encode(lifecyclePosition), { + sequence: 3, + }), + ), + ).toThrow(StorageError); + }); + + it.each([ + [ + "assignment pointer", + () => + assignmentPointers.codec.decode( + replaceFields(assignmentPointers.codec.encode(pointer), { + role: 42, + }), + ), + ], + [ + "role holder", + () => + roleHolders.codec.decode( + omitField( + roleHolders.codec.encode({ + ...pointer, + }), + "principalId", + ), + ), + ], + [ + "identity link", + () => + identityLinks.codec.decode({ + applicationId: APPLICATION_ID, + issuer: "issuer", + subject: "subject", + principalId: 42, + }), + ], + ])("rejects a malformed %s record", (_label, decode) => { + expect(decode).toThrow(StorageError); + }); +}); + +describe("storage record bindings", () => { + it.each([ + ["application", { applicationId: "application_two" }], + ["assignment", { assignmentId: "assignment_two" }], + ] as const)( + "rejects a pointer with a mismatched %s", + async (_label, change) => { + const store = createMemoryStore(); + await putRaw( + store, + assignmentPointers.name, + pointerKey(APPLICATION_ID, ASSIGNMENT_ID), + replaceFields(assignmentPointers.codec.encode(pointer), change), + ); + await expect( + createRoleStore(store, APPLICATION_ID).getRoleAssignment(ASSIGNMENT_ID), + ).rejects.toBeInstanceOf(StorageError); + }, + ); + + it("rejects an assignment row stored under a different physical id", async () => { + const store = createMemoryStore(); + await putRaw( + store, + authorizationRecords.name, + { + partition: recordPartition(location), + id: assignmentRecordId("assignment_two"), + }, + authorizationRecords.codec.encode(storedAssignment), + ); + await expect( + createRoleStore(store, APPLICATION_ID).listRoleAssignments( + PRINCIPAL_ID, + applicationScope, + ), + ).rejects.toThrow("changed during read; retry"); + }); + + it("reports a retry when a listed row changes before confirmation", async () => { + const base = createMemoryStore(); + await putAssignment(base); + let listed = false; + const store = wrapAuthorizationRecords(base, (collection) => ({ + ...collection, + async list(partition) { + const found = await collection.list(partition); + listed = true; + return found; + }, + async get(key) { + return listed ? null : collection.get(key); + }, + })); + + await expect( + createRoleStore(store, APPLICATION_ID).listRoleAssignments( + PRINCIPAL_ID, + applicationScope, + ), + ).rejects.toThrow("changed during read; retry"); + }); + + it("confirms principal listing rows in bounded batches", async () => { + const base = createMemoryStore(); + const writer = createRoleStore(base, APPLICATION_ID); + for (let index = 0; index < 17; index += 1) { + const next = { + ...assignment, + id: `assignment_${String(index)}`, + role: `role_${String(index)}`, + }; + const result = await writer.grantRoleAssignmentWithAudit({ + assignment: next, + auditEventId: `grant_${String(index)}`, + }); + expect(result.status).toBe("granted"); + } + + let active = 0; + let maximum = 0; + let calls = 0; + const store = wrapAuthorizationRecords(base, (collection) => ({ + ...collection, + async get(key) { + active += 1; + calls += 1; + maximum = Math.max(maximum, active); + await Promise.resolve(); + try { + return await collection.get(key); + } finally { + active -= 1; + } + }, + })); + + await expect( + createRoleStore(store, APPLICATION_ID).listRoleAssignments( + PRINCIPAL_ID, + applicationScope, + ), + ).resolves.toHaveLength(17); + expect(calls).toBe(51); + expect(maximum).toBe(16); + }); + + it.each([ + ["application", { applicationId: "application_two" }], + ["principal", { principalId: "principal_two" }], + [ + "scope", + { scopeKind: "organization", organizationId: "organization_two" }, + ], + ["assignment", { assignmentId: "assignment_two" }], + ["role", { role: "viewer" }], + ] as const)( + "rejects an assignment row with a mismatched %s binding", + async (_label, change) => { + const store = createMemoryStore(); + await putPointer(store); + await putAssignment( + store, + replaceFields( + authorizationRecords.codec.encode(storedAssignment), + change, + ), + ); + await expect( + createRoleStore(store, APPLICATION_ID).getRoleAssignment(ASSIGNMENT_ID), + ).rejects.toBeInstanceOf(StorageError); + }, + ); + + it("rejects a role-holder row stored under a different physical id", async () => { + const store = createMemoryStore(); + const adapter = await requireGrant(store); + const correctKey = { + partition: roleHolderPartition(APPLICATION_ID, ROLE, applicationScope), + id: ASSIGNMENT_ID, + }; + const holderRows = store.collection( + defineCollection({ + name: roleHolders.name, + key: () => correctKey, + codec: { + encode: (value) => value, + decode: (value) => value, + }, + }), + ); + const existing = await holderRows.get(correctKey); + if (existing === null) { + throw new Error("expected a role-holder row"); + } + await holderRows.delete(correctKey); + await putRaw( + store, + roleHolders.name, + { ...correctKey, id: "assignment_two" }, + existing, + ); + await expect( + adapter.listActiveRoleAssignmentsByRole(ROLE, applicationScope), + ).rejects.toBeInstanceOf(StorageError); + }); + + it("rejects an assignment pointer stored under a different physical id", async () => { + const store = createMemoryStore(); + await putRaw( + store, + assignmentPointers.name, + { + partition: APPLICATION_ID, + id: "assignment_two", + }, + assignmentPointers.codec.encode(pointer), + ); + await expect( + createRoleStore(store, APPLICATION_ID).rebuildRoleHolderIndex(), + ).rejects.toBeInstanceOf(StorageError); + }); + + it.each([ + ["application", { applicationId: "application_two" }], + ["principal", { principalId: "principal_two" }], + [ + "scope", + { scopeKind: "organization", organizationId: "organization_two" }, + ], + ] as const)( + "rejects a partition row with a mismatched %s binding", + async (_label, change) => { + const store = createMemoryStore(); + await putAssignment( + store, + replaceFields( + authorizationRecords.codec.encode(storedAssignment), + change, + ), + ); + await expect( + createRoleStore(store, APPLICATION_ID).listRoleAssignments( + PRINCIPAL_ID, + applicationScope, + ), + ).rejects.toThrow("corrupt record"); + }, + ); + + it("rejects a tuple whose role disagrees with its requested key", async () => { + const store = createMemoryStore(); + const tuple: StoredTuple = { + kind: "tuple", + ...location, + role: "viewer", + activeAssignmentId: null, + }; + await putRaw( + store, + authorizationRecords.name, + { + partition: recordPartition(location), + id: tupleRecordId(ROLE), + }, + authorizationRecords.codec.encode(tuple), + ); + await expect( + createRoleStore(store, APPLICATION_ID).grantRoleAssignmentWithAudit({ + assignment, + auditEventId: GRANT_EVENT_ID, + }), + ).rejects.toBeInstanceOf(StorageError); + }); + + it.each([ + ["application", { applicationId: "application_two" }], + ["principal", { principalId: "principal_two" }], + [ + "scope", + { scopeKind: "organization", organizationId: "organization_two" }, + ], + ["role", { role: "viewer" }], + ["assignment", { assignmentId: "assignment_two" }], + ] as const)( + "rejects a role-holder row with a mismatched %s binding", + async (_label, change) => { + const store = createMemoryStore(); + const adapter = await requireGrant(store); + const holder: StoredRoleHolder = { + ...location, + assignmentId: ASSIGNMENT_ID, + role: ROLE, + }; + await putRaw( + store, + roleHolders.name, + { + partition: roleHolderPartition( + APPLICATION_ID, + ROLE, + applicationScope, + ), + id: ASSIGNMENT_ID, + }, + replaceFields(roleHolders.codec.encode(holder), change), + ); + await expect( + adapter.listActiveRoleAssignmentsByRole(ROLE, applicationScope), + ).rejects.toBeInstanceOf(StorageError); + }, + ); + + it.each([ + ["application", { applicationId: "application_two" }], + ["issuer", { issuer: "issuer_two" }], + ["subject", { subject: "subject_two" }], + ] as const)( + "rejects an identity row with a mismatched %s binding", + async (_label, change) => { + const store = createMemoryStore(); + const stored: StoredIdentityLink = { + applicationId: APPLICATION_ID, + link: { + key: { issuer: "issuer_one", subject: "subject_one" }, + principalId: PRINCIPAL_ID, + }, + }; + await putRaw( + store, + identityLinks.name, + identityLinkKey(APPLICATION_ID, "issuer_one", "subject_one"), + replaceFields(identityLinks.codec.encode(stored), change), + ); + await expect( + createRoleStore(store, APPLICATION_ID).resolvePrincipalId({ + issuer: "issuer_one", + subject: "subject_one", + }), + ).rejects.toBeInstanceOf(StorageError); + }, + ); + + it.each([ + ["assignment", { assignmentId: "assignment_two" }], + ["sequence", { sequence: REVOKE_SEQUENCE }], + ["event", { eventId: "grant_two" }], + ] as const)( + "rejects a lifecycle row with a mismatched %s binding", + async (_label, change) => { + const store = createMemoryStore(); + const adapter = await requireGrant(store); + const lifecyclePosition: StoredAudit = { + kind: "audit", + ...location, + assignmentId: ASSIGNMENT_ID, + sequence: GRANT_SEQUENCE, + eventId: GRANT_EVENT_ID, + }; + await putRaw( + store, + authorizationRecords.name, + { + partition: recordPartition(location), + id: auditRecordId(ASSIGNMENT_ID, GRANT_SEQUENCE), + }, + replaceFields( + authorizationRecords.codec.encode(lifecyclePosition), + change, + ), + ); + await expect( + adapter.listRoleAssignmentAuditEvents(ASSIGNMENT_ID), + ).rejects.toBeInstanceOf(StorageError); + }, + ); + + it("rejects an unexpected revoke position on an active assignment", async () => { + const store = createMemoryStore(); + const adapter = await requireGrant(store); + const lifecyclePosition: StoredAudit = { + kind: "audit", + ...location, + assignmentId: ASSIGNMENT_ID, + sequence: REVOKE_SEQUENCE, + eventId: "revoke_one", + }; + await putRaw( + store, + authorizationRecords.name, + { + partition: recordPartition(location), + id: auditRecordId(ASSIGNMENT_ID, REVOKE_SEQUENCE), + }, + authorizationRecords.codec.encode(lifecyclePosition), + ); + await expect( + adapter.listRoleAssignmentAuditEvents(ASSIGNMENT_ID), + ).rejects.toBeInstanceOf(StorageError); + }); + + it("rejects lifecycle positions without their assignment row", async () => { + const store = createMemoryStore(); + await putPointer(store); + const lifecyclePosition: StoredAudit = { + kind: "audit", + ...location, + assignmentId: ASSIGNMENT_ID, + sequence: GRANT_SEQUENCE, + eventId: GRANT_EVENT_ID, + }; + await putRaw( + store, + authorizationRecords.name, + { + partition: recordPartition(location), + id: auditRecordId(ASSIGNMENT_ID, GRANT_SEQUENCE), + }, + authorizationRecords.codec.encode(lifecyclePosition), + ); + + await expect( + createRoleStore(store, APPLICATION_ID).listRoleAssignmentAuditEvents( + ASSIGNMENT_ID, + ), + ).rejects.toBeInstanceOf(StorageError); + }); + + it("rejects a miskeyed lifecycle position without its assignment row", async () => { + const store = createMemoryStore(); + await putPointer(store); + const lifecyclePosition: StoredAudit = { + kind: "audit", + ...location, + assignmentId: ASSIGNMENT_ID, + sequence: GRANT_SEQUENCE, + eventId: GRANT_EVENT_ID, + }; + await putRaw( + store, + authorizationRecords.name, + { + partition: recordPartition(location), + id: auditRecordId("assignment_two", GRANT_SEQUENCE), + }, + authorizationRecords.codec.encode(lifecyclePosition), + ); + + await expect( + createRoleStore(store, APPLICATION_ID).listRoleAssignmentAuditEvents( + ASSIGNMENT_ID, + ), + ).rejects.toBeInstanceOf(StorageError); + }); +}); diff --git a/packages/storage/src/collections.ts b/packages/storage/src/collections.ts index 236c456..f43c544 100644 --- a/packages/storage/src/collections.ts +++ b/packages/storage/src/collections.ts @@ -9,6 +9,7 @@ import type { } from "@pegma/authorization-contracts"; import { defineCollection, + StorageError, type EntityKey, type StoredRecord, } from "@pegma/storage-core"; @@ -24,6 +25,73 @@ import { */ const KEY_ESCAPES = /[%|/\\#?\u0000-\u001F\u007F-\u009F]/g; +const malformed = (detail: string): never => { + throw new StorageError( + `authorization storage holds a corrupt record: ${detail}`, + ); +}; + +const readOwnValue = (record: StoredRecord, field: string): unknown => { + const descriptor = Object.getOwnPropertyDescriptor(record, field); + if (descriptor === undefined || !("value" in descriptor)) { + return malformed(`${field} must be an own data field`); + } + return descriptor.value; +}; + +const assertExactFields = ( + record: StoredRecord, + expected: readonly string[], +): void => { + const expectedSet = new Set(expected); + const actual = Reflect.ownKeys(record); + if ( + actual.length !== expected.length || + actual.some((field) => typeof field !== "string" || !expectedSet.has(field)) + ) { + malformed(`record fields must be exactly ${expected.join(", ")}`); + } + for (const field of expected) { + readOwnValue(record, field); + } +}; + +const readString = (record: StoredRecord, field: string): string => { + const value = readOwnValue(record, field); + if (typeof value !== "string") { + return malformed(`${field} must be a string`); + } + return value; +}; + +const readNullableString = ( + record: StoredRecord, + field: string, +): string | null => { + const value = readOwnValue(record, field); + if (value !== null && typeof value !== "string") { + return malformed(`${field} must be a string or null`); + } + return value; +}; + +const readNonNegativeSafeInteger = ( + record: StoredRecord, + field: string, +): number => { + const value = readOwnValue(record, field); + if (!Number.isSafeInteger(value) || (value as number) < 0) { + return malformed(`${field} must be a non-negative safe integer`); + } + return value as number; +}; + +const requireNull = (record: StoredRecord, field: string): void => { + if (readOwnValue(record, field) !== null) { + malformed(`${field} must be null`); + } +}; + function encodeSegment(value: string): string { // `%` is escaped by the same rule, and because it is listed first in the // class it can never be produced by escaping something else. The encoding is @@ -165,12 +233,19 @@ function decodeActor( record: StoredRecord, prefix: string, ): RoleAssignmentActor { - return record[`${prefix}Kind`] === "system" - ? { kind: "system", systemId: String(record[`${prefix}SystemId`]) } - : { - kind: "principal", - principalId: String(record[`${prefix}PrincipalId`]), - }; + const kind = readString(record, `${prefix}Kind`); + if (kind === "system") { + requireNull(record, `${prefix}PrincipalId`); + return { kind, systemId: readString(record, `${prefix}SystemId`) }; + } + if (kind === "principal") { + requireNull(record, `${prefix}SystemId`); + return { + kind, + principalId: readString(record, `${prefix}PrincipalId`), + }; + } + return malformed(`${prefix}Kind must name a known actor kind`); } function encodeLocation(location: RecordLocation): StoredRecord { @@ -186,15 +261,24 @@ function encodeLocation(location: RecordLocation): StoredRecord { } function decodeScope(record: StoredRecord): RoleAssignmentScope { - return record["scopeKind"] === "organization" - ? { kind: "organization", organizationId: String(record["organizationId"]) } - : { kind: "application" }; + const kind = readString(record, "scopeKind"); + if (kind === "organization") { + return { + kind, + organizationId: readString(record, "organizationId"), + }; + } + if (kind === "application") { + requireNull(record, "organizationId"); + return { kind }; + } + return malformed("scopeKind must name a known scope kind"); } function decodeLocation(record: StoredRecord): RecordLocation { return { - applicationId: String(record["applicationId"]), - principalId: String(record["principalId"]), + applicationId: readString(record, "applicationId"), + principalId: readString(record, "principalId"), scope: decodeScope(record), }; } @@ -224,36 +308,111 @@ function encodeAssignment(stored: StoredAssignment): StoredRecord { }; } +const LOCATION_FIELDS = [ + "applicationId", + "principalId", + "scopeKind", + "organizationId", +] as const; + +const ASSIGNMENT_FIELDS = [ + "kind", + ...LOCATION_FIELDS, + "assignmentId", + "role", + "status", + "grantedAtEpochMs", + "grantedByKind", + "grantedByPrincipalId", + "grantedBySystemId", + "revokedAtEpochMs", + "revokedByKind", + "revokedByPrincipalId", + "revokedBySystemId", + "reason", + "grantEventId", + "revokeEventId", +] as const; + +const TUPLE_FIELDS = [ + "kind", + ...LOCATION_FIELDS, + "role", + "activeAssignmentId", +] as const; + +const AUDIT_FIELDS = [ + "kind", + ...LOCATION_FIELDS, + "assignmentId", + "sequence", + "eventId", +] as const; + +const POINTER_FIELDS = [...LOCATION_FIELDS, "assignmentId", "role"] as const; + +const IDENTITY_LINK_FIELDS = [ + "applicationId", + "issuer", + "subject", + "principalId", +] as const; + function decodeAssignment(record: StoredRecord): StoredAssignment { + assertExactFields(record, ASSIGNMENT_FIELDS); const location = decodeLocation(record); + const grantedAtEpochMs = readNonNegativeSafeInteger( + record, + "grantedAtEpochMs", + ); const grant = { - id: String(record["assignmentId"]), + id: readString(record, "assignmentId"), principalId: location.principalId, - role: String(record["role"]), + role: readString(record, "role"), scope: location.scope, grantedBy: decodeActor(record, "grantedBy"), - grantedAtEpochMs: Number(record["grantedAtEpochMs"]), + grantedAtEpochMs, }; - const reason = record["reason"]; - const assignment: RoleAssignment = - record["status"] === "revoked" - ? { - ...grant, - status: "revoked", - revokedBy: decodeActor(record, "revokedBy"), - revokedAtEpochMs: Number(record["revokedAtEpochMs"]), - ...(reason == null ? {} : { reason: String(reason) }), - } - : { ...grant, status: "active" }; + const status = readString(record, "status"); + let assignment: RoleAssignment; + let revokeEventId: string | null; + if (status === "active") { + requireNull(record, "revokedAtEpochMs"); + requireNull(record, "revokedByKind"); + requireNull(record, "revokedByPrincipalId"); + requireNull(record, "revokedBySystemId"); + requireNull(record, "reason"); + requireNull(record, "revokeEventId"); + assignment = { ...grant, status }; + revokeEventId = null; + } else if (status === "revoked") { + const revokedAtEpochMs = readNonNegativeSafeInteger( + record, + "revokedAtEpochMs", + ); + if (revokedAtEpochMs < grantedAtEpochMs) { + return malformed("revokedAtEpochMs must not precede grantedAtEpochMs"); + } + const reason = readNullableString(record, "reason"); + revokeEventId = readString(record, "revokeEventId"); + assignment = { + ...grant, + status, + revokedBy: decodeActor(record, "revokedBy"), + revokedAtEpochMs, + ...(reason === null ? {} : { reason }), + }; + } else { + return malformed("status must be active or revoked"); + } - const revokeEventId = record["revokeEventId"]; return { kind: "assignment", ...location, assignment, - grantEventId: String(record["grantEventId"]), - revokeEventId: revokeEventId == null ? null : String(revokeEventId), + grantEventId: readString(record, "grantEventId"), + revokeEventId, }; } @@ -297,26 +456,34 @@ export const authorizationRecords = defineCollection({ }; }, decode: (record) => { - if (record["kind"] === "assignment") { + const kind = readString(record, "kind"); + if (kind === "assignment") { return decodeAssignment(record); } - if (record["kind"] === "tuple") { - const activeAssignmentId = record["activeAssignmentId"]; + if (kind === "tuple") { + assertExactFields(record, TUPLE_FIELDS); return { - kind: "tuple", + kind, ...decodeLocation(record), - role: String(record["role"]), - activeAssignmentId: - activeAssignmentId == null ? null : String(activeAssignmentId), + role: readString(record, "role"), + activeAssignmentId: readNullableString(record, "activeAssignmentId"), }; } - return { - kind: "audit", - ...decodeLocation(record), - assignmentId: String(record["assignmentId"]), - sequence: Number(record["sequence"]), - eventId: String(record["eventId"]), - }; + if (kind === "audit") { + assertExactFields(record, AUDIT_FIELDS); + const sequence = readNonNegativeSafeInteger(record, "sequence"); + if (sequence !== GRANT_SEQUENCE && sequence !== REVOKE_SEQUENCE) { + return malformed("sequence must name a known lifecycle position"); + } + return { + kind, + ...decodeLocation(record), + assignmentId: readString(record, "assignmentId"), + sequence, + eventId: readString(record, "eventId"), + }; + } + return malformed("kind must name a known authorization record kind"); }, }, }); @@ -347,11 +514,14 @@ export const assignmentPointers = defineCollection({ assignmentId: pointer.assignmentId, role: pointer.role, }), - decode: (record) => ({ - ...decodeLocation(record), - assignmentId: String(record["assignmentId"]), - role: String(record["role"]), - }), + decode: (record) => { + assertExactFields(record, POINTER_FIELDS); + return { + ...decodeLocation(record), + assignmentId: readString(record, "assignmentId"), + role: readString(record, "role"), + }; + }, }, }); @@ -416,11 +586,14 @@ export const roleHolders = defineCollection({ assignmentId: holder.assignmentId, role: holder.role, }), - decode: (record) => ({ - ...decodeLocation(record), - assignmentId: String(record["assignmentId"]), - role: String(record["role"]), - }), + decode: (record) => { + assertExactFields(record, POINTER_FIELDS); + return { + ...decodeLocation(record), + assignmentId: readString(record, "assignmentId"), + role: readString(record, "role"), + }; + }, }, }); @@ -451,16 +624,19 @@ export const identityLinks = defineCollection({ subject: stored.link.key.subject, principalId: stored.link.principalId, }), - decode: (record) => ({ - applicationId: String(record["applicationId"]), - link: { - key: { - issuer: String(record["issuer"]), - subject: String(record["subject"]), + decode: (record) => { + assertExactFields(record, IDENTITY_LINK_FIELDS); + return { + applicationId: readString(record, "applicationId"), + link: { + key: { + issuer: readString(record, "issuer"), + subject: readString(record, "subject"), + }, + principalId: readString(record, "principalId"), }, - principalId: String(record["principalId"]), - }, - }), + }; + }, }, }); diff --git a/packages/storage/src/role-store.ts b/packages/storage/src/role-store.ts index eae25f0..854e363 100644 --- a/packages/storage/src/role-store.ts +++ b/packages/storage/src/role-store.ts @@ -14,12 +14,14 @@ import { createMemoryStore, StorageError, type Store, + type StoredRecord, type TransactionAction, } from "@pegma/storage-core"; import { assignmentPointers, assignmentRecordId, + auditRecordId, authorizationRecords, GRANT_SEQUENCE, identityLinkKey, @@ -37,6 +39,7 @@ import { type StoredAssignment, type StoredAssignmentPointer, type StoredAudit, + type StoredRoleHolder, type StoredTuple, } from "./collections.js"; import type { @@ -155,6 +158,9 @@ const freezeAuditRecord = ( /** Authoritative point reads issued concurrently by one by-role read. */ const HOLDER_VERIFY_BATCH = 16; +/** Point confirmations issued concurrently by one principal listing. */ +const RECORD_CONFIRM_BATCH = 16; + const byGrantThenId = (left: RoleAssignment, right: RoleAssignment): number => left.grantedAtEpochMs !== right.grantedAtEpochMs ? left.grantedAtEpochMs - right.grantedAtEpochMs @@ -233,23 +239,140 @@ const snapshotRevokeCommand = ( const corrupt = (detail: string): StorageError => new StorageError(`authorization storage holds a corrupt record: ${detail}`); +const changedDuringRead = (detail: string): StorageError => + new StorageError( + `authorization storage changed during read; retry: ${detail}`, + ); + +export const storedRecordsEqual = ( + left: StoredRecord, + right: StoredRecord, +): boolean => { + const leftFields = Reflect.ownKeys(left); + const rightFields = Reflect.ownKeys(right); + if ( + leftFields.some((field) => typeof field !== "string") || + rightFields.some((field) => typeof field !== "string") + ) { + return false; + } + return ( + leftFields.length === rightFields.length && + leftFields.every( + (field) => + typeof field === "string" && + Object.hasOwn(right, field) && + left[field] === right[field], + ) + ); +}; + +const requireLocation = ( + actual: RecordLocation, + expected: RecordLocation, + detail: string, +): void => { + if ( + actual.applicationId !== expected.applicationId || + actual.principalId !== expected.principalId || + !scopesEqual(actual.scope, expected.scope) + ) { + throw corrupt(`${detail} disagrees with its requested partition`); + } +}; + +const requirePointerKey = ( + pointer: StoredAssignmentPointer, + applicationId: ApplicationId, + assignmentId: RoleAssignmentId, +): StoredAssignmentPointer => { + if ( + pointer.applicationId !== applicationId || + pointer.assignmentId !== assignmentId + ) { + throw corrupt(`${assignmentId} has a pointer that disagrees with its key`); + } + return pointer; +}; + +const requireHolderKey = ( + holder: StoredRoleHolder, + expected: StoredRoleHolder, +): StoredRoleHolder => { + requireLocation(holder, expected, `${expected.assignmentId} holder row`); + if ( + holder.assignmentId !== expected.assignmentId || + holder.role !== expected.role + ) { + throw corrupt( + `${expected.assignmentId} has a holder row that disagrees with its key`, + ); + } + return holder; +}; + const requireAssignment = ( record: AuthorizationRecord | undefined, + location: RecordLocation, assignmentId: RoleAssignmentId, + role: RoleName, ): StoredAssignment => { if (record === undefined || record.kind !== "assignment") { throw corrupt(`${assignmentId} is not an assignment record`); } + requireLocation(record, location, `${assignmentId} assignment`); + if ( + record.assignment.id !== assignmentId || + record.assignment.principalId !== location.principalId || + !scopesEqual(record.assignment.scope, location.scope) || + record.assignment.role !== role + ) { + throw corrupt(`${assignmentId} disagrees with its requested key`); + } return record; }; const requireTuple = ( record: AuthorizationRecord | undefined, - role: string, + location: RecordLocation, + role: RoleName, ): StoredTuple => { if (record === undefined || record.kind !== "tuple") { throw corrupt(`the guard for ${role} is not a tuple record`); } + requireLocation(record, location, `${role} guard`); + if (record.role !== role) { + throw corrupt(`the guard for ${role} disagrees with its requested key`); + } + return record; +}; + +const requireLifecyclePosition = ( + record: AuthorizationRecord | null, + location: RecordLocation, + assignmentId: RoleAssignmentId, + sequence: number, + eventId: string, +): StoredAudit => { + if (record === null || record.kind !== "audit") { + throw corrupt( + `${assignmentId} is missing lifecycle position ${String(sequence)}`, + ); + } + requireLocation( + record, + location, + `${assignmentId} lifecycle position ${String(sequence)}`, + ); + if ( + record.assignmentId !== assignmentId || + record.sequence !== sequence || + record.eventId !== eventId + ) { + throw corrupt( + `${assignmentId} lifecycle position ${String(sequence)} disagrees with its requested key`, + ); + } return record; }; @@ -299,19 +422,99 @@ export const createRoleStore = ( const links = store.collection(identityLinkCollection); const holders = store.collection(roleHolders); + const confirmRecordListing = async ( + partition: string, + found: readonly AuthorizationRecord[], + ): Promise => { + const ids = new Set(); + const keyed = found.map((record) => { + const key = authorizationRecords.key(record); + if (key.partition !== partition || ids.has(key.id)) { + throw corrupt("an authorization row disagrees with its physical key"); + } + ids.add(key.id); + return { key, record }; + }); + for (let start = 0; start < keyed.length; start += RECORD_CONFIRM_BATCH) { + await Promise.all( + keyed.slice(start, start + RECORD_CONFIRM_BATCH).map(async (listed) => { + const confirmed = await records.get(listed.key); + if ( + confirmed === null || + !storedRecordsEqual( + authorizationRecords.codec.encode(listed.record), + authorizationRecords.codec.encode(confirmed), + ) + ) { + throw changedDuringRead("an authorization row moved"); + } + }), + ); + } + }; + + const confirmHolderListing = async ( + partition: string, + found: readonly StoredRoleHolder[], + ): Promise => { + const ids = new Set(); + for (const holder of found) { + const key = roleHolders.key(holder); + if (key.partition !== partition || ids.has(key.id)) { + throw corrupt("a role-holder row disagrees with its physical key"); + } + ids.add(key.id); + const confirmed = await holders.get(key); + if ( + confirmed === null || + !storedRecordsEqual( + roleHolders.codec.encode(holder), + roleHolders.codec.encode(confirmed), + ) + ) { + throw changedDuringRead("a role-holder row moved"); + } + } + }; + + const confirmPointerListing = async ( + partition: string, + found: readonly StoredAssignmentPointer[], + ): Promise => { + const ids = new Set(); + for (const pointer of found) { + const key = assignmentPointers.key(pointer); + if (key.partition !== partition || ids.has(key.id)) { + throw corrupt("an assignment pointer disagrees with its physical key"); + } + ids.add(key.id); + const confirmed = await pointers.get(key); + if ( + confirmed === null || + !storedRecordsEqual( + assignmentPointers.codec.encode(pointer), + assignmentPointers.codec.encode(confirmed), + ) + ) { + throw changedDuringRead("an assignment pointer moved"); + } + } + }; + const locate = async ( assignmentId: RoleAssignmentId, - ): Promise => { + ): Promise => { const pointer = await pointers.get(pointerKey(applicationId, assignmentId)); - if (pointer === null || pointer.assignmentId !== assignmentId) { + if (pointer === null) { return null; } - return pointer; + return requirePointerKey(pointer, applicationId, assignmentId); }; const readAssignment = async ( location: RecordLocation, assignmentId: RoleAssignmentId, + role: RoleName, ): Promise<{ readonly stored: StoredAssignment; readonly version: string; @@ -323,7 +526,12 @@ export const createRoleStore = ( return versioned === null ? null : { - stored: requireAssignment(versioned.value, assignmentId), + stored: requireAssignment( + versioned.value, + location, + assignmentId, + role, + ), version: versioned.version, }; }; @@ -335,12 +543,15 @@ export const createRoleStore = ( const stored = await links.get( identityLinkKey(applicationId, key.issuer, key.subject), ); + if (stored === null) { + return null; + } if ( - stored === null || + stored.applicationId !== applicationId || stored.link.key.issuer !== key.issuer || stored.link.key.subject !== key.subject ) { - return null; + throw corrupt("an identity link disagrees with its requested key"); } return stored.link.principalId; }, @@ -353,6 +564,7 @@ export const createRoleStore = ( }); const stored = result.value.link; if ( + result.value.applicationId !== applicationId || stored.key.issuer !== snapshot.key.issuer || stored.key.subject !== snapshot.key.subject ) { @@ -376,7 +588,11 @@ export const createRoleStore = ( if (location === null) { return null; } - const current = await readAssignment(location, assignmentId); + const current = await readAssignment( + location, + assignmentId, + location.role, + ); return current === null ? null : freezeVersioned({ @@ -389,12 +605,18 @@ export const createRoleStore = ( principalId: PrincipalId, scope: RoleAssignmentScope, ): Promise { + const exact = snapshotScope(scope); const partition = recordPartition({ applicationId, principalId, - scope: snapshotScope(scope), + scope: exact, }); const found = await records.list(partition); + await confirmRecordListing(partition, found); + const expected = { applicationId, principalId, scope: exact }; + for (const record of found) { + requireLocation(record, expected, "authorization record"); + } return Object.freeze( found .filter( @@ -412,12 +634,18 @@ export const createRoleStore = ( principalId: PrincipalId, scope: RoleAssignmentScope, ): Promise { + const exact = snapshotScope(scope); const partition = recordPartition({ applicationId, principalId, - scope: snapshotScope(scope), + scope: exact, }); const found = await records.list(partition); + await confirmRecordListing(partition, found); + const expected = { applicationId, principalId, scope: exact }; + for (const record of found) { + requireLocation(record, expected, "authorization record"); + } return Object.freeze( found .filter( @@ -435,18 +663,42 @@ export const createRoleStore = ( scope: RoleAssignmentScope, ): Promise { const exact = snapshotScope(scope); - const candidates = await holders.list( - roleHolderPartition(applicationId, role, exact), - ); + const partition = roleHolderPartition(applicationId, role, exact); + const candidates = await holders.list(partition); + await confirmHolderListing(partition, candidates); const verify = async ( candidate: (typeof candidates)[number], ): Promise => { - if (candidate.role !== role || !scopesEqual(candidate.scope, exact)) { + if ( + candidate.applicationId !== applicationId || + candidate.role !== role || + !scopesEqual(candidate.scope, exact) + ) { throw corrupt(`a ${role} holder row disagrees with its partition`); } + const pointer = await locate(candidate.assignmentId); + if (pointer === null) { + throw corrupt( + `${candidate.assignmentId} has a holder row without a pointer`, + ); + } + requireLocation( + candidate, + pointer, + `${candidate.assignmentId} holder row`, + ); + if (candidate.role !== pointer.role) { + throw corrupt( + `${candidate.assignmentId} holder row disagrees with its pointer`, + ); + } // 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); + const current = await readAssignment( + pointer, + candidate.assignmentId, + pointer.role, + ); if (current === null) { return null; } @@ -490,22 +742,32 @@ export const createRoleStore = ( 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)); + const partition = pointerPartition(applicationId); + const known = await pointers.list(partition); + await confirmPointerListing(partition, known); 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) { + if ( + (await readAssignment( + pointer, + pointer.assignmentId, + pointer.role, + )) === null + ) { continue; } - const written = await holders.insertIfAbsent({ + const expectedHolder: StoredRoleHolder = { applicationId, principalId: pointer.principalId, scope: pointer.scope, assignmentId: pointer.assignmentId, role: pointer.role, - }); + }; + const written = await holders.insertIfAbsent(expectedHolder); + requireHolderKey(written.value, expectedHolder); if (written.inserted) { recorded += 1; } @@ -520,35 +782,59 @@ export const createRoleStore = ( if (location === null) { return Object.freeze([]); } - const found = await records.list(recordPartition(location)); - const positions = found - .filter( + const current = await readAssignment( + location, + assignmentId, + location.role, + ); + const partition = recordPartition(location); + if (current === null) { + const positions = (await records.list(partition)).filter( (record): record is StoredAudit => record.kind === "audit" && record.assignmentId === assignmentId, - ) - .map(({ sequence }) => sequence) - .sort((left, right) => left - right); - if (positions.length === 0) { + ); + if (positions.length > 0) { + throw corrupt( + `${assignmentId} has lifecycle positions without a record`, + ); + } return Object.freeze([]); } - - const stored = requireAssignment( - found.find( - (record) => - record.kind === "assignment" && - record.assignment.id === assignmentId, - ), + requireLifecyclePosition( + await records.get({ + partition, + id: auditRecordId(assignmentId, GRANT_SEQUENCE), + }), + location, assignmentId, + GRANT_SEQUENCE, + current.stored.grantEventId, ); - return Object.freeze( - positions.map((sequence) => - freezeAuditRecord( - sequence === REVOKE_SEQUENCE - ? revokeAuditRecord(stored) - : grantAuditRecord(stored), - ), - ), + const grantRecord = freezeAuditRecord(grantAuditRecord(current.stored)); + const revokePosition = await records.get({ + partition, + id: auditRecordId(assignmentId, REVOKE_SEQUENCE), + }); + if (current.stored.assignment.status === "active") { + if (revokePosition !== null) { + throw corrupt(`${assignmentId} has a revoke position while active`); + } + return Object.freeze([grantRecord]); + } + if (current.stored.revokeEventId === null) { + throw corrupt(`${assignmentId} is revoked without a revoke event id`); + } + requireLifecyclePosition( + revokePosition, + location, + assignmentId, + REVOKE_SEQUENCE, + current.stored.revokeEventId, ); + return Object.freeze([ + grantRecord, + freezeAuditRecord(revokeAuditRecord(current.stored)), + ]); }, async grantRoleAssignmentWithAudit( @@ -574,6 +860,7 @@ export const createRoleStore = ( assignmentId: assignment.id, role: assignment.role, }); + requirePointerKey(pointer.value, applicationId, assignment.id); if ( !pointer.inserted && pointsElsewhere(pointer.value, location, assignment.role) @@ -583,11 +870,13 @@ export const createRoleStore = ( // 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({ + const expectedHolder: StoredRoleHolder = { ...location, assignmentId: assignment.id, role: assignment.role, - }); + }; + const holder = await holders.insertIfAbsent(expectedHolder); + requireHolderKey(holder.value, expectedHolder); const guard = await records.getVersioned({ partition, @@ -596,7 +885,8 @@ export const createRoleStore = ( const occupant = guard === null ? null - : requireTuple(guard.value, assignment.role).activeAssignmentId; + : requireTuple(guard.value, location, assignment.role) + .activeAssignmentId; if (occupant !== null && occupant !== assignment.id) { return conflict("active_tuple"); } @@ -614,7 +904,11 @@ export const createRoleStore = ( auditRecord: freezeAuditRecord(grantAuditRecord(found.stored)), }); - const existing = await readAssignment(location, assignment.id); + const existing = await readAssignment( + location, + assignment.id, + assignment.role, + ); if (existing !== null) { // The lifecycle already exists. An exact replay is unchanged and never // reactivates a revoked record; a different event ID for the same ID is @@ -671,7 +965,11 @@ export const createRoleStore = ( // first. Which precondition it refused is best-effort information, so // decide from the state that actually landed rather than from the // rejection. - const landed = await readAssignment(location, assignment.id); + const landed = await readAssignment( + location, + assignment.id, + assignment.role, + ); if (landed === null) { return conflict("active_tuple"); } @@ -680,7 +978,11 @@ export const createRoleStore = ( : conflict("assignment_id"); } - const written = await readAssignment(location, assignment.id); + const written = await readAssignment( + location, + assignment.id, + assignment.role, + ); if (written === null) { throw corrupt(`${assignment.id} vanished after a committed grant`); } @@ -703,7 +1005,11 @@ export const createRoleStore = ( return Object.freeze({ status: "not_found" }); } const partition = recordPartition(location); - const existing = await readAssignment(location, command.assignmentId); + const existing = await readAssignment( + location, + command.assignmentId, + location.role, + ); if (existing === null) { return Object.freeze({ status: "not_found" }); } @@ -741,7 +1047,7 @@ export const createRoleStore = ( `${current.role} has an active assignment without a guard`, ); } - const held = requireTuple(guard.value, current.role); + const held = requireTuple(guard.value, location, current.role); const revoked: RevokedRoleAssignment = { ...current, @@ -796,7 +1102,11 @@ export const createRoleStore = ( ); } - const written = await readAssignment(location, command.assignmentId); + const written = await readAssignment( + location, + command.assignmentId, + location.role, + ); if (written === null) { throw corrupt( `${command.assignmentId} vanished after a committed revoke`, diff --git a/packages/tokens/src/index.test.ts b/packages/tokens/src/index.test.ts index 16869f1..6c40bdc 100644 --- a/packages/tokens/src/index.test.ts +++ b/packages/tokens/src/index.test.ts @@ -25,6 +25,7 @@ import { parseAccessGrantJwks, type AccessGrantIssuer, type AccessGrantIssuerConfiguration, + type IssueAccessGrantInput, type SourceAuthorizationSnapshot, } from "./index.js"; import { defaultJwksFetcher, JwksCache } from "./jwks.js"; @@ -389,6 +390,117 @@ describe("@pegma/authorization-tokens issuer", () => { expect(Number(payload["exp"]) - Number(payload["iat"])).toBe(25); }); + it("requires own source context data properties without invoking accessors", async () => { + const values = context(); + for (const field of [ + "principalId", + "policyVersion", + "roles", + "entitlements", + "permissions", + ] as const) { + let getterCalls = 0; + const supplied = { ...values } as Record; + Object.defineProperty(supplied, field, { + configurable: true, + enumerable: true, + get: () => { + getterCalls += 1; + return values[field]; + }, + }); + const fixture = issuerFixture(); + fixture.setSource( + source({ context: supplied as unknown as ReturnType }), + ); + + await expect(fixture.issuer.readSourceAuthorization()).rejects.toThrow( + `context.${field} must be an own data property`, + ); + expect(getterCalls).toBe(0); + } + }); + + it("requires own source context fields instead of inherited values", async () => { + const values = context(); + for (const field of [ + "principalId", + "policyVersion", + "roles", + "entitlements", + "permissions", + ] as const) { + const prototype = { [field]: values[field] }; + const supplied = Object.assign( + Object.create(prototype), + values, + ) as Record; + Reflect.deleteProperty(supplied, field); + const fixture = issuerFixture(); + fixture.setSource( + source({ context: supplied as unknown as ReturnType }), + ); + + await expect(fixture.issuer.readSourceAuthorization()).rejects.toThrow( + `context.${field} must be an own data property`, + ); + } + }); + + it("requires own source scope data properties without invoking accessors", async () => { + const scopeValues = { + kind: "organization", + organizationId: "organization-one", + } as const; + for (const field of ["kind", "organizationId"] as const) { + let getterCalls = 0; + const supplied = { ...scopeValues } as Record; + Object.defineProperty(supplied, field, { + configurable: true, + enumerable: true, + get: () => { + getterCalls += 1; + return scopeValues[field]; + }, + }); + const fixture = issuerFixture(); + fixture.setSource( + source({ + scope: supplied as unknown as SourceAuthorizationSnapshot["scope"], + }), + ); + + await expect(fixture.issuer.readSourceAuthorization()).rejects.toThrow( + `scope.${field} must be an own data property`, + ); + expect(getterCalls).toBe(0); + } + }); + + it("requires own source scope fields instead of inherited values", async () => { + const scopeValues = { + kind: "organization", + organizationId: "organization-one", + } as const; + for (const field of ["kind", "organizationId"] as const) { + const supplied = Object.assign( + Object.create({ [field]: scopeValues[field] }), + scopeValues, + ) as Record; + Reflect.deleteProperty(supplied, field); + const fixture = issuerFixture(); + fixture.setSource( + source({ + scope: supplied as unknown as SourceAuthorizationSnapshot["scope"], + }), + ); + + await expect(fixture.issuer.readSourceAuthorization()).rejects.toThrow( + `scope.${field} must be an own data property`, + ); + } + }); + it("snapshots every issuer configuration and dependency at construction", async () => { const configuredPermissions = [permission]; const configuredPolicies = [ @@ -448,6 +560,103 @@ describe("@pegma/authorization-tokens issuer", () => { }); }); + it("snapshots issue input data properties once before validation", async () => { + const fixture = issuerFixture(); + const read = await fixture.issuer.readSourceAuthorization(); + const bound = fixture.issuer.bindSourceAuthorization(read); + const firstValues: IssueAccessGrantInput = { + audience, + requestedPermissions: [permission], + source: bound, + }; + const laterValues = { + audience: "alternate-api", + requestedPermissions: [secondPermission], + source: Object.freeze({}), + }; + const descriptorReads = new Map(); + const valueReads = new Map(); + const input = new Proxy(firstValues, { + get(target, property, receiver) { + const reads = valueReads.get(property) ?? 0; + valueReads.set(property, reads + 1); + if (Object.hasOwn(laterValues, property)) { + return reads === 0 + ? Reflect.get(target, property, receiver) + : laterValues[property as keyof typeof laterValues]; + } + return Reflect.get(target, property, receiver) as unknown; + }, + getOwnPropertyDescriptor(target, property) { + const descriptor = Reflect.getOwnPropertyDescriptor(target, property); + if (descriptor === undefined || !Object.hasOwn(laterValues, property)) { + return descriptor; + } + const reads = descriptorReads.get(property) ?? 0; + descriptorReads.set(property, reads + 1); + return { + ...descriptor, + value: + reads === 0 + ? descriptor.value + : laterValues[property as keyof typeof laterValues], + }; + }, + }); + + const compact = await fixture.issuer.issue(input); + const payload = JSON.parse( + Buffer.from(compact.split(".")[1]!, "base64url").toString("utf8"), + ) as Record; + + expect(payload["aud"]).toBe(audience); + expect(payload["permissions"]).toEqual([permission]); + expect(Object.fromEntries(descriptorReads)).toEqual({ + audience: 1, + requestedPermissions: 1, + source: 1, + }); + expect(valueReads.size).toBe(0); + }); + + it("requires own issue input data properties without invoking accessors", async () => { + const fixture = issuerFixture(); + const read = await fixture.issuer.readSourceAuthorization(); + const bound = fixture.issuer.bindSourceAuthorization(read); + const values: IssueAccessGrantInput = { + audience, + requestedPermissions: [permission], + source: bound, + }; + + for (const field of [ + "audience", + "requestedPermissions", + "source", + ] as const) { + let getterCalls = 0; + const input = { ...values } as Record; + Object.defineProperty(input, field, { + configurable: true, + enumerable: true, + get: () => { + getterCalls += 1; + return values[field]; + }, + }); + + await expect( + fixture.issuer.issue(input as unknown as IssueAccessGrantInput), + ).rejects.toThrow(`${field} must be an own data property`); + expect(getterCalls).toBe(0); + } + + const inherited = Object.create(values) as IssueAccessGrantInput; + await expect(fixture.issuer.issue(inherited)).rejects.toThrow( + "audience must be an own data property", + ); + }); + it("requires six whole seconds, caps nominal life at thirty, and reads wall time first", async () => { const sixSeconds = issuerFixture(); sixSeconds.setSource(source({ maximumLifetimeMs: 6_000 })); diff --git a/packages/tokens/src/issuer.ts b/packages/tokens/src/issuer.ts index f9d498e..f3bee22 100644 --- a/packages/tokens/src/issuer.ts +++ b/packages/tokens/src/issuer.ts @@ -111,36 +111,109 @@ export interface AccessGrantIssuer { issue(input: IssueAccessGrantInput): Promise; } -function snapshotStringArray( - value: readonly string[], - field: string, -): string[] { +function snapshotStringArray(value: unknown, field: string): readonly string[] { if (!Array.isArray(value)) { fail(`${field} must be an array`); } + const lengthDescriptor = Object.getOwnPropertyDescriptor(value, "length"); + if ( + lengthDescriptor === undefined || + !("value" in lengthDescriptor) || + typeof lengthDescriptor.value !== "number" || + !Number.isSafeInteger(lengthDescriptor.value) || + lengthDescriptor.value < 0 + ) { + fail(`${field} must be a dense string array`); + } const copy: string[] = []; - for (let index = 0; index < value.length; index += 1) { - if (!Object.hasOwn(value, index) || typeof value[index] !== "string") { + for (let index = 0; index < lengthDescriptor.value; index += 1) { + const descriptor = Object.getOwnPropertyDescriptor(value, index); + if ( + descriptor === undefined || + !("value" in descriptor) || + typeof descriptor.value !== "string" + ) { fail(`${field} must be a dense string array`); } - copy.push(value[index]); + copy.push(descriptor.value); } - return Object.freeze(copy) as string[]; + return Object.freeze(copy); +} + +function ownDataProperty( + value: object, + property: PropertyKey, + field: string, +): unknown { + const descriptor = Object.getOwnPropertyDescriptor(value, property); + if (descriptor === undefined || !("value" in descriptor)) { + fail(`${field} must be an own data property`); + } + return descriptor.value; +} + +function snapshotIssueInput(value: unknown): Readonly<{ + audience: string; + requestedPermissions: readonly string[]; + source: unknown; +}> { + if (typeof value !== "object" || value === null) { + fail("access-grant issue input must be an object"); + } + const audience = ownDataProperty(value, "audience", "input.audience"); + const requestedPermissions = ownDataProperty( + value, + "requestedPermissions", + "input.requestedPermissions", + ); + const source = ownDataProperty(value, "source", "input.source"); + if (typeof audience !== "string") { + fail("input.audience must be a string"); + } + return Object.freeze({ + audience, + requestedPermissions: snapshotStringArray( + requestedPermissions, + "input.requestedPermissions", + ), + source, + }); } function snapshotContext(value: AccessContext): AccessContext { if (typeof value !== "object" || value === null) { fail("source access context must be an object"); } + const principalId = ownDataProperty( + value, + "principalId", + "context.principalId", + ); + const policyVersion = ownDataProperty( + value, + "policyVersion", + "context.policyVersion", + ); + const roles = ownDataProperty(value, "roles", "context.roles"); + const entitlements = ownDataProperty( + value, + "entitlements", + "context.entitlements", + ); + const permissions = ownDataProperty( + value, + "permissions", + "context.permissions", + ); + if (typeof principalId !== "string" || typeof policyVersion !== "string") { + fail("source access context identifiers must be strings"); + } return Object.freeze({ - principalId: value.principalId, - policyVersion: value.policyVersion, - roles: snapshotStringArray(value.roles, "context.roles"), - entitlements: snapshotStringArray( - value.entitlements, - "context.entitlements", - ), - permissions: snapshotStringArray(value.permissions, "context.permissions"), + principalId, + policyVersion, + roles: snapshotStringArray(roles, "context.roles"), + entitlements: snapshotStringArray(entitlements, "context.entitlements"), + permissions: snapshotStringArray(permissions, "context.permissions"), }); } @@ -148,17 +221,22 @@ function snapshotScope(value: AccessGrantSourceScope): AccessGrantSourceScope { if (typeof value !== "object" || value === null) { fail("source scope must be an object"); } - if (value.kind === "application") { + const kind = ownDataProperty(value, "kind", "scope.kind"); + if (kind === "application") { return Object.freeze({ kind: "application" }); } - if ( - value.kind === "organization" && - typeof value.organizationId === "string" && - value.organizationId.length > 0 - ) { + if (kind === "organization") { + const organizationId = ownDataProperty( + value, + "organizationId", + "scope.organizationId", + ); + if (typeof organizationId !== "string" || organizationId.length === 0) { + fail("source scope is malformed"); + } return Object.freeze({ kind: "organization", - organizationId: value.organizationId, + organizationId, }); } fail("source scope is malformed"); @@ -308,7 +386,10 @@ export function createAccessGrantIssuerInternal( }, async issue(input: IssueAccessGrantInput): Promise { - const source = sourceCapabilities.get(input.source); + const issueInput = snapshotIssueInput(input); + const source = sourceCapabilities.get( + issueInput.source as SourceAuthorizationCapability, + ); if ( source === undefined || source.owner !== owner || @@ -336,11 +417,11 @@ export function createAccessGrantIssuerInternal( fail("source authorization snapshot is malformed"); } - const allowed = audiencePermissions.get(input.audience); + const allowed = audiencePermissions.get(issueInput.audience); if (allowed === undefined) { fail("access-grant audience is not configured"); } - const requested = canonicalPermissions(input.requestedPermissions); + const requested = canonicalPermissions(issueInput.requestedPermissions); if (requested.length === 0) { fail("access grant must contain at least one permission"); } @@ -371,7 +452,7 @@ export function createAccessGrantIssuerInternal( const payload = { iss: issuerName, application_id: applicationId, - aud: input.audience, + aud: issueInput.audience, sub: source.context.principalId, exp, iat, diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index 2368dcf..3e29608 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -465,13 +465,51 @@ describe("release source authentication", () => { expect(publishStart).toBeGreaterThan(prepareStart); const prepare = jobs.slice(prepareStart, publishStart); const publish = jobs.slice(publishStart); + const tagCheckStart = publish.indexOf( + " - name: Confirm the release tag target", + ); + const nodeSetupStart = publish.indexOf( + " - name: Set up Node.js and the npm registry", + ); + expect(tagCheckStart).toBeGreaterThanOrEqual(0); + expect(nodeSetupStart).toBeGreaterThan(tagCheckStart); + const beforeTagCheck = publish.slice(0, tagCheckStart); + const tagCheck = publish.slice(tagCheckStart, nodeSetupStart); + const afterTagCheck = publish.slice(nodeSetupStart); expect(prepare).not.toContain("id-token: write"); expect(publish).toContain("id-token: write"); expect(publish).not.toContain("corepack"); expect(publish).not.toContain("pnpm"); expect(publish).not.toContain("release:pack"); expect(publish).toContain("npm install --global npm@11.18.0"); - expect(publish).toContain("npm run release:publish"); + expect(publish).not.toContain("npm run"); + expect(publish).toContain("ref: ${{ github.sha }}"); + expect(publish).toContain("persist-credentials: false"); + expect(beforeTagCheck).not.toContain("github.token"); + expect(afterTagCheck).not.toContain("github.token"); + expect(tagCheck).toContain("GITHUB_TOKEN: ${{ github.token }}"); + expect(tagCheck).toContain("unset GITHUB_TOKEN"); + expect(tagCheck).toContain("GIT_CONFIG_COUNT=1"); + expect(tagCheck).toContain( + "GIT_CONFIG_KEY_0=http.https://github.com/.extraheader", + ); + expect(tagCheck).toContain( + 'GIT_CONFIG_VALUE_0="AUTHORIZATION: basic ${authorization}"', + ); + expect(tagCheck).toContain( + 'git fetch --force --no-tags origin "refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}"', + ); + expect(tagCheck).toContain("unset authorization"); + expect(tagCheck).not.toContain("git config"); + expect(publish).toContain( + 'git rev-parse "refs/tags/${RELEASE_TAG}^{commit}"', + ); + expect(publish).toContain( + 'if [[ "${tag_commit}" != "${RELEASE_COMMIT}" ]]', + ); + expect(publish).toContain( + 'node scripts/release-packages.mjs publish --expected-release-commit "${RELEASE_COMMIT}"', + ); expect(workflow).not.toContain("identity-bootstrap"); expect(workflow).not.toContain("github.run_attempt"); expect(workflow).toContain("retention-days: 30");