diff --git a/.changeset/30758-delegated-unit-read-answers.md b/.changeset/30758-delegated-unit-read-answers.md new file mode 100644 index 00000000000..30d351836d2 --- /dev/null +++ b/.changeset/30758-delegated-unit-read-answers.md @@ -0,0 +1,10 @@ +--- +'@objectstack/plugin-security': patch +--- + +fix(plugin-security): `canReadObject`, `getReadFilter` and `security/explain` answer a delegated administrator's read of the business units its scope covers as the read door does + +Clause-②: no +Metadata-protocol: none + +A delegated administrator reads the business units its admin scopes cover (ADR-0090 D12), and the read door already admitted that read for `find`, `findOne`, `count` and `aggregate`. The answers outside the door did not: `canReadObject('sys_business_unit')` answered `false`, so a unit picker or a door that compiles its own statement refused units the delegate can read, and `security/explain` reported the read as denied. All three now ask the read door's own judgment. `canReadObject` answers `true`, `getReadFilter` confines the read to the covered units (an `id` `$in` filter over them), and `security/explain` reports the read as allowed with the same confinement in its `readFilter`, and a unit outside the scope as not visible. Nothing the door refuses is admitted: a unit outside the scope, a read on behalf of another user, an export and every write stay refused, and a caller with no admin scope is answered as before. diff --git a/packages/plugins/plugin-security/src/delegated-admin-gate.ts b/packages/plugins/plugin-security/src/delegated-admin-gate.ts index 7bf56e43050..06b3f1e8f7e 100644 --- a/packages/plugins/plugin-security/src/delegated-admin-gate.ts +++ b/packages/plugins/plugin-security/src/delegated-admin-gate.ts @@ -437,27 +437,50 @@ const DELEGATED_READ_OPERATIONS: ReadonlySet = new Set(['find', 'findOne * The authz middleware asks this only for an operation the caller's sets do * NOT grant, and admits it only on a non-null answer: the `where` scope * `id IN ` it then ANDs into the read. Null — the ordinary - * refusal stands — unless every condition holds: a read of - * `sys_business_unit` carrying a query, on the caller's own behalf (no - * on-behalf-of delegator), with the gate composed, and at least one covered - * unit ({@link DelegatedAdminGate.scopedBusinessUnitIds}). Nothing wider: no - * other object, no write, and no unit outside the scopes the caller holds; a - * caller whose sets already grant the read is untouched. A scope that cannot - * be resolved admits nothing (fail closed). + * refusal stands — unless every condition holds: a read carrying a query, and + * every condition of {@link delegatedUnitReadAdmission}, the one judgment the + * answers outside the middleware ask too. */ export async function delegatedUnitReadScope( gate: Pick | null | undefined, opCtx: { object?: string; operation?: string; ast?: unknown; context?: any }, permissionSets: PermissionSet[], delegatorSets: PermissionSet[] | null | undefined, +): Promise | null> { + if (!opCtx.ast) return null; + return delegatedUnitReadAdmission(gate, opCtx.object, opCtx.operation, opCtx.context, permissionSets, delegatorSets); +} + +/** + * [ADR-0090 D12, ruling of record 6663849489] The delegated business-unit read + * itself, for an operation the caller's sets do NOT grant: the scope + * `id IN ` the read is confined to, or null when it + * admits nothing. Asked by the read door ({@link delegatedUnitReadScope}) and + * by every answer that must say what that door does — `canReadObject`, + * `getReadFilter` and `security/explain` — so there is one judgment, never a + * second copy of it. + * + * Non-null only when every condition holds: a read (`find`, `findOne`, + * `count` or `aggregate`) of `sys_business_unit`, on the caller's own behalf + * (no on-behalf-of delegator), with the gate composed, and at least one + * covered unit ({@link DelegatedAdminGate.scopedBusinessUnitIds}). Nothing + * wider: no other object, no write, no export, and no unit outside the scopes + * the caller holds; a caller whose sets already grant the read is untouched. + * A scope that cannot be resolved admits nothing (fail closed). + */ +export async function delegatedUnitReadAdmission( + gate: Pick | null | undefined, + object: string | undefined, + operation: string | undefined, + context: any, + permissionSets: PermissionSet[], + delegatorSets: PermissionSet[] | null | undefined, ): Promise | null> { if (!gate || delegatorSets) return null; - if (opCtx.object !== DELEGATED_READ_OBJECT || !DELEGATED_READ_OPERATIONS.has(String(opCtx.operation)) || !opCtx.ast) { - return null; - } + if (object !== DELEGATED_READ_OBJECT || !DELEGATED_READ_OPERATIONS.has(String(operation))) return null; let ids: ReadonlySet; try { - ids = await gate.scopedBusinessUnitIds(permissionSets, opCtx.context); + ids = await gate.scopedBusinessUnitIds(permissionSets, context); } catch { return null; } diff --git a/packages/plugins/plugin-security/src/delegated-admin-own-name-set.posture.test.ts b/packages/plugins/plugin-security/src/delegated-admin-own-name-set.posture.test.ts index f074c4df683..80a414adb46 100644 --- a/packages/plugins/plugin-security/src/delegated-admin-own-name-set.posture.test.ts +++ b/packages/plugins/plugin-security/src/delegated-admin-own-name-set.posture.test.ts @@ -25,6 +25,7 @@ import { describe, it, expect, afterEach, vi } from 'vitest'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { resolveThrownHttpError } from '@objectstack/types'; +import type { EngineAggregateOptions, EngineQueryOptions, FilterCondition } from '@objectstack/spec/data'; import { SysUser, SysMember, SysBusinessUnit, SysBusinessUnitMember } from '@objectstack/platform-objects/identity'; import { SecurityPlugin } from './security-plugin.js'; @@ -63,7 +64,11 @@ const PERMISSIONS = [ // Carries an adminScope equal to the wide delegate's own: not strictly contained by it. { name: 'field_lead', label: 'Field lead (own name)', objects: CRUD, adminScope: eastScope(['field_user', 'field_rep', 'field_lead']) }, // Narrow: allowlists the sets the positions LIST, not their own-name sets. - { name: 'east_admin', label: 'East delegate', objects: { ...CRUD, [UNIT_NOTE]: NOTE_CRUD }, adminScope: eastScope(['field_user']) }, + // [#30758] It may not read `external_ref`, so the aggregate field guard (step 2.5b) has a field to refuse. + { + name: 'east_admin', label: 'East delegate', objects: { ...CRUD, [UNIT_NOTE]: NOTE_CRUD }, adminScope: eastScope(['field_user']), + fields: { 'sys_business_unit.external_ref': { readable: false } }, + }, // [#29029] A writer of the unit note with no admin scope at all. { name: 'note_writer', label: 'Note writer', objects: { [UNIT_NOTE]: NOTE_CRUD } }, // Wide: also allowlists the own-name sets. @@ -327,3 +332,118 @@ describe('[ADR-0090 D12, ruling of record 6663849489; #29029] a delegate reads t }); } }); + +/** [#30758] The unit ids the system context reads under `filter` — what a door that compiles its own statement returns. */ +async function unitsUnder(h: Awaited>, filter: Record | null | undefined): Promise { + const query: EngineQueryOptions = { ...(filter ? { where: filter as FilterCondition } : {}), context: SYS }; + const rows = await h.engine.find('sys_business_unit', query); + return (Array.isArray(rows) ? rows : []).map((r: any) => String(r.id)).sort(); +} + +/** [#30758] An aggregate of `sys_business_unit` as `context`: the group names it counts, or the refusal. */ +async function unitAggregate( + h: Awaited>, + context: any, + query: { where?: FilterCondition; groupBy: string[] }, +): Promise { + try { + const aggregate: EngineAggregateOptions = { ...query, aggregations: [{ function: 'count', alias: 'n' }] }; + const rows = await h.engine.aggregate('sys_business_unit', aggregate, { context }); + return (Array.isArray(rows) ? rows : []).map((r: any) => `${String(r[query.groupBy[0]])}:${Number(r.n)}`).sort(); + } catch (e) { + const r = resolveThrownHttpError(e); + return { status: r.status, code: r.code, forbiddenFields: (e as any)?.details?.forbiddenFields }; + } +} + +const layerOf = (decision: any, layer: string) => decision.layers.find((l: any) => l.layer === layer); + +describe('[ADR-0090 D12, ruling of record 6663849489; #30758] canReadObject and security/explain answer the delegated business-unit read as the read door does — three postures', () => { + const WRITER = delegateCtx('u_writer', 'note_writer'); + const ORG_ADMIN = delegateCtx('u_org_admin', 'organization_admin'); + + for (const posture of POSTURES) { + describe(`posture '${posture}'`, () => { + it('canReadObject admits the delegate, and getReadFilter scopes a bypassing door to exactly the units the read door returns', async () => { + const h = await boot(posture); + const door = await unitsRead(h, NARROW); + expect(door).toEqual(['bu_east', 'bu_east_field']); + expect(await h.plugin.canReadObject('sys_business_unit', NARROW)).toBe(true); + expect(await unitsUnder(h, await h.plugin.getReadFilter('sys_business_unit', NARROW))).toEqual(door); + }); + + it('security/explain read: allowed, the object grant names the delegated scope, and its readFilter returns exactly the read door\'s units', async () => { + const h = await boot(posture); + const d: any = await h.plugin.explainAccessForCaller({ object: 'sys_business_unit', operation: 'read' }, NARROW); + expect(d.allowed).toBe(true); + expect(layerOf(d, 'object_crud').verdict).toBe('grants'); + expect(await unitsUnder(h, d.readFilter)).toEqual(await unitsRead(h, NARROW)); + }); + + it('security/explain of one unit: the units the scope covers are visible, the unit above it is not — asked by the delegate and by its organization administrator', async () => { + const h = await boot(posture); + await h.engine.insert('sys_user_permission_set', + { id: 'ups_delegate', user_id: 'u_delegate', permission_set: 'east_admin', organization_id: ORG_A }, { context: { isSystem: true, tenantId: ORG_A } }); + for (const [asker, request] of [ + ['delegate', (recordId: string) => h.plugin.explainAccessForCaller({ object: 'sys_business_unit', operation: 'read', recordId }, NARROW)], + ['organization administrator', (recordId: string) => + h.plugin.explainAccessForCaller({ object: 'sys_business_unit', operation: 'read', userId: 'u_delegate', recordId }, ORG_ADMIN)], + ] as const) { + for (const unit of ['bu_east', 'bu_east_field']) { + const d: any = await request(unit); + expect(d.record?.visible, `${asker} · ${unit}`).toBe(true); + } + const above: any = await request('bu_hq'); + expect(above.record?.visible, `${asker} · bu_hq`).toBe(false); + } + }); + + it('aggregate is the read door too: inside the scope it counts the covered units, outside it counts none, and the field guard still refuses an unreadable field', async () => { + const h = await boot(posture); + expect(await unitAggregate(h, NARROW, { groupBy: ['name'] })).toEqual(['east:1', 'east_field:1']); + expect(await unitAggregate(h, NARROW, { where: { id: 'bu_hq' }, groupBy: ['name'] })).toEqual([]); + expect(await unitAggregate(h, NARROW, { groupBy: ['external_ref'] })) + .toEqual({ status: 403, code: 'PERMISSION_DENIED', forbiddenFields: ['external_ref'] }); + // CONTROL: the organization administrator counts every unit; a caller with no scope is refused the object. + expect(await unitAggregate(h, ORG_ADMIN, { groupBy: ['name'] })).toEqual(['east:1', 'east_field:1', 'hq:1']); + expect(await unitAggregate(h, WRITER, { groupBy: ['name'] })).toEqual({ status: 403, code: 'PERMISSION_DENIED', forbiddenFields: undefined }); + }); + + it('CONTROL: a caller holding no scope is still refused by the door, canReadObject and explain alike', async () => { + const h = await boot(posture); + expect(await unitsRead(h, WRITER)).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + expect(await h.plugin.canReadObject('sys_business_unit', WRITER)).toBe(false); + const d: any = await h.plugin.explainAccessForCaller({ object: 'sys_business_unit', operation: 'read' }, WRITER); + expect(d.allowed).toBe(false); + expect(layerOf(d, 'object_crud').verdict).toBe('denies'); + }); + + it('CONTROL: an organization administrator\'s answers are unchanged — every unit, granted by its own set', async () => { + const h = await boot(posture); + expect(await h.plugin.canReadObject('sys_business_unit', ORG_ADMIN)).toBe(true); + expect(await unitsUnder(h, await h.plugin.getReadFilter('sys_business_unit', ORG_ADMIN))).toEqual(['bu_east', 'bu_east_field', 'bu_hq']); + const d: any = await h.plugin.explainAccessForCaller({ object: 'sys_business_unit', operation: 'read' }, ORG_ADMIN); + expect(d.allowed).toBe(true); + expect(layerOf(d, 'object_crud').contributors.map((c: any) => c.name)).toContain('organization_admin'); + }); + + it('CONTROL: the delegated read is the caller\'s own — acting on behalf of another user, even one who reads every unit, no answer admits it, as the door does not', async () => { + const h = await boot(posture); + const onBehalf = { ...NARROW, principalKind: 'agent', onBehalfOf: { userId: 'u_org_admin' } }; + expect(await unitsRead(h, onBehalf as any)).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + expect(await h.plugin.canReadObject('sys_business_unit', onBehalf)).toBe(false); + const d: any = await h.plugin.explainAccessForCaller({ object: 'sys_business_unit', operation: 'read' }, onBehalf); + expect(d.allowed).toBe(false); + }); + + it('CONTROL: the delegated scope grants a read and nothing else — explain still denies create and export, as their doors do', async () => { + const h = await boot(posture); + for (const operation of ['create', 'export'] as const) { + const d: any = await h.plugin.explainAccessForCaller({ object: 'sys_business_unit', operation }, NARROW); + expect(d.allowed, operation).toBe(false); + } + expect(await h.plugin.canExport('sys_business_unit', NARROW)).toBe(false); + }); + }); + } +}); diff --git a/packages/plugins/plugin-security/src/explain-engine.ts b/packages/plugins/plugin-security/src/explain-engine.ts index 7eef2b35053..937d2310031 100644 --- a/packages/plugins/plugin-security/src/explain-engine.ts +++ b/packages/plugins/plugin-security/src/explain-engine.ts @@ -372,6 +372,24 @@ export interface ExplainEngineDeps { * error. */ tenancyPosture: TenancyPosture; + /** + * [ADR-0090 D12, ruling of record 6663849489] The one admission the read + * door makes beside the CRUD grant, for an operation the principal's sets do + * NOT grant: a delegate reads the business units its admin scopes cover. + * The middleware's own judgment (`delegatedUnitReadAdmission`), answering the + * scope `id IN ` the read is confined to, or null. + * + * Optional: a deps bag wired without it explains such a read as refused — + * the answer from before the read was ruled, which over-refuses and never + * widens. The plugin's own wiring passes it. + */ + delegatedUnitReadScope?: ( + sets: PermissionSet[], + object: string, + engineOperation: string, + context: any, + delegatorSets: PermissionSet[] | null, + ) => Promise | null>; // ── [C2 / ADR-0095] Record-grained deps. All OPTIONAL: absent → the engine // stays object-level and byte-compatible. Present → the sharing / rls / owd / @@ -1713,6 +1731,13 @@ interface RecordAttributionContext { * so the record verdict of an `update` or a `delete` composes it too. */ delegator?: { sets: PermissionSet[]; context: any }; + /** + * [ADR-0090 D12] The delegated business-unit read's confinement, when the + * object-level pass admitted the read through it and no set's grant: the + * read door ANDs `id IN ` into the find, so a unit + * outside it is a unit the principal does not read. + */ + delegatedUnitScope?: Record; } /** @@ -1769,7 +1794,7 @@ async function applyRecordAttribution( ): Promise<{ record: NonNullable; posture: AuthzPosture }> { const { deps, object, recordId, engineOp, rlsOp, context, sets, layers, owd, capsDeny, crudAllowed, vamaEffective, vamaSets, - declaredColumns, depthScope, delegator, + declaredColumns, depthScope, delegator, delegatedUnitScope, } = ra; const isRead = engineOp === 'find'; const posture = derivePosture(context); @@ -2413,6 +2438,10 @@ async function applyRecordAttribution( if (capsDeny) { visible = false; decidedBy = 'required_permissions'; } else if (!crudAllowed) { visible = false; decidedBy = 'object_crud'; } else if (!recordExists) { visible = false; decidedBy = undefined; } + // [ADR-0090 D12] A read the object grant admitted only as the delegated + // business-unit read reaches the covered units alone: the door's find + // answers no other, so the layer that admitted it is the one that withholds it. + else if (delegatedUnitScope && matches(delegatedUnitScope) === false) { visible = false; decidedBy = 'object_crud'; } else if (tenantExcluded) { visible = false; decidedBy = 'tenant_isolation'; } else if (rlsExcluded) { visible = false; decidedBy = 'rls'; } // A dependency that threw decides by failing the request, in the order the @@ -2707,6 +2736,8 @@ interface ObjectPass { delegatorContextForRls: any; readFilter: Record | null | undefined; allowed: boolean; + /** [ADR-0090 D12] The delegated business-unit read's confinement, when the object grant admitted the read through it. */ + delegatedUnitScope: Record | null; } async function explainOnce(deps: ExplainEngineDeps, input: ExplainInput, asker: ExplainAsker | undefined): Promise { @@ -2969,7 +3000,15 @@ async function explainObjectPass(deps: ExplainEngineDeps, input: ExplainInput, a // that layer's grant is computed FROM, and reporting the real cause beats a // misleading "no set grants it" when the sets were never the problem. const postureUnresolved = secMeta.unresolved === true; - const crudAllowed = agentCrud && delegatorCrud && !delegatorRefused && !postureUnresolved; + // [ADR-0090 D12, ruling of record 6663849489] The one admission the read + // door makes beside the grant, asked as the door asks it: only for an + // operation the principal's sets do not grant, and through the door's own + // judgment ({@link ExplainEngineDeps.delegatedUnitReadScope}). A delegated + // (on-behalf-of) principal is never admitted by it. + const delegatedUnitScope = !agentCrud && !postureUnresolved && !delegatorRefused && deps.delegatedUnitReadScope + ? await deps.delegatedUnitReadScope(sets, object, engineOp, context, delegatorSets).catch(() => null) + : null; + const crudAllowed = (agentCrud || delegatedUnitScope !== null) && delegatorCrud && !delegatorRefused && !postureUnresolved; const granting = postureUnresolved ? [] : sets @@ -2979,8 +3018,12 @@ async function explainObjectPass(deps: ExplainEngineDeps, input: ExplainInput, a layer: 'object_crud', verdict: crudAllowed ? 'grants' : 'denies', detail: crudAllowed - ? `${operation} on '${object}' is granted by [${granting.join(', ')}]` + - (delegatorSets ? ' AND by the delegator (D10 intersection).' : '.') + ? delegatedUnitScope !== null + ? `No resolved permission set grants ${operation} on '${object}'; the business units the principal's ` + + `delegated admin scope covers are read as delegated administration (ADR-0090 D12), and no other ` + + `(see readFilter).` + : `${operation} on '${object}' is granted by [${granting.join(', ')}]` + + (delegatorSets ? ' AND by the delegator (D10 intersection).' : '.') : postureUnresolved // [#10401] One wording, shared with the middleware's own throw, so // explanation and enforcement cannot drift into telling a reader two @@ -3219,7 +3262,10 @@ async function explainObjectPass(deps: ExplainEngineDeps, input: ExplainInput, a delegatorFilter = { id: DENY_ALL_SENTINEL_ID }; } } - const filterParts = [agentFilter, delegatorFilter].filter(Boolean) as Record[]; + // [ADR-0090 D12] The delegated business-unit read is confined as the door + // confines it: `id IN `, ANDed beside the row-level + // security at step 3. + const filterParts = [agentFilter, delegatorFilter, delegatedUnitScope].filter(Boolean) as Record[]; // [#20604] A composed filter the find cannot run is refused here, as // enforcement refuses it, and never published as the filter a read runs // under. Before the record-grained pass, so a record id no row carries is @@ -3252,6 +3298,7 @@ async function explainObjectPass(deps: ExplainEngineDeps, input: ExplainInput, a : readFilter ? 'Row-level security narrows the row set (see readFilter for the composed predicate)' + (delegatorFilter ? ' — intersection of agent + delegator filters (D10).' : '.') + + (delegatedUnitScope ? ' The delegated business-unit read is confined to the units the delegated admin scope covers (ADR-0090 D12).' : '') + (objectDefaults.length > 0 ? objectDefaultRowScopeSource(object, objectDefaults) : '') : 'No RLS policy applies.') + (membershipKeys.length > 0 ? await membershipKeySource(deps, membershipKeys) : ''), @@ -3263,6 +3310,7 @@ async function explainObjectPass(deps: ExplainEngineDeps, input: ExplainInput, a return { object, operation, context, dataOp, rlsOp, layers, sets, setNames, positions, owd, capsDeny, crudAllowed, vamaEffective, vamaSets, declaredColumns, scope, delegatorSets, delegatorContextForRls, readFilter, allowed, + delegatedUnitScope, }; } @@ -3279,7 +3327,7 @@ async function explainRecordOnPass( ): Promise<{ record: NonNullable; posture: AuthzPosture }> { const { object, operation, context, dataOp, rlsOp, layers, sets, owd, capsDeny, crudAllowed, vamaEffective, vamaSets, - declaredColumns, scope, delegatorSets, delegatorContextForRls, + declaredColumns, scope, delegatorSets, delegatorContextForRls, delegatedUnitScope, } = pass; let recordVerdict: NonNullable; const readQuestion = deps.recordAbsentToCaller; @@ -3350,6 +3398,7 @@ async function explainRecordOnPass( object, recordId, engineOp: dataOp, rlsOp, context, sets, layers, owd, capsDeny, crudAllowed, vamaEffective, vamaSets, declaredColumns, depthScope: scope, ...(delegatorSets && delegatorContextForRls ? { delegator: { sets: delegatorSets, context: delegatorContextForRls } } : {}), + ...(delegatedUnitScope ? { delegatedUnitScope } : {}), }); recordVerdict = out.record; if (principalCannotRead) { diff --git a/packages/plugins/plugin-security/src/security-plugin-explain-access.ts b/packages/plugins/plugin-security/src/security-plugin-explain-access.ts index 0c35b86cf0a..948c09b8fec 100644 --- a/packages/plugins/plugin-security/src/security-plugin-explain-access.ts +++ b/packages/plugins/plugin-security/src/security-plugin-explain-access.ts @@ -74,6 +74,7 @@ import type { SecurityPlugin } from './security-plugin.js'; import { absentUnderCallerRead, requiredCapsForOperation, unreadableUnderCallerRead } from './security-plugin.js'; import { ExplainUserNotFoundError, PermissionDeniedError } from './errors.js'; import { grantRowPolicySpeaks } from './external-owd-grant-stamp.js'; +import { delegatedUnitReadAdmission } from './delegated-admin-gate.js'; import { rlsOperationForVerb } from './lifecycle-verb-rls-operation.js'; import { buildContextForUser, @@ -421,6 +422,10 @@ export async function explainAccessForCaller( // [#25107] The prologue's posture, for its organization-membership // refusal of a delegated context ({@link delegatedOrganizationRefusal}). tenancyPosture: this.tenancyPosture, + // [ADR-0090 D12, ruling of record 6663849489] The read door's admission + // beside the grant, asked through the door's own judgment. + delegatedUnitReadScope: (sets, o, engineOp, c, delSets) => + delegatedUnitReadAdmission(this.delegatedAdminGate, o, engineOp, c, sets as any, delSets as any), // ── record-grained deps (only consulted when recordId is present) ── computeLayeredRlsFilter: async (sets, o, engineOp, c) => this.computeLayeredRlsFilter( diff --git a/packages/plugins/plugin-security/src/security-plugin-object-admission.ts b/packages/plugins/plugin-security/src/security-plugin-object-admission.ts index 62f75f48e59..85f239bb7fb 100644 --- a/packages/plugins/plugin-security/src/security-plugin-object-admission.ts +++ b/packages/plugins/plugin-security/src/security-plugin-object-admission.ts @@ -71,6 +71,7 @@ import type { PermissionSet } from '@objectstack/spec/security'; import { PermissionDeniedError } from './errors.js'; import { assertEngineOwnedWriteAllowed } from './system-write-guard.js'; import { delegatedOrganizationRefusal, resolveDelegatorContext } from './explain-engine.js'; +import { delegatedUnitReadAdmission } from './delegated-admin-gate.js'; /** * The `SecurityPlugin` members the functions below read — every one of them, @@ -95,7 +96,7 @@ export interface ObjectAdmissionHost { /** The body of `SecurityPlugin#canReadObject`; the method's docblock there is its contract. */ export async function canReadObject( - this: Pick, + this: Pick, object: string, context?: any, ): Promise { @@ -130,7 +131,16 @@ export async function canReadObject( // 3–6. The posture and grant arms, over the resolved sets — the one // predicate the ADR-0055 master-derived read scope asks as well. - return await this.objectReadAdmission(objectName, permissionSets, delegatorSets); + // + // [ADR-0090 D12, ruling of record 6663849489] With the one admission the + // read door makes beside the grant at arm 5: a delegate reads the business + // units its admin scopes cover ({@link delegatedUnitReadAdmission}), so this + // answers yes where that read is admitted. A read of SOME rows, answered + // as every row-restricted read is: `true` here, the rows in + // `getReadFilter`, which confines the same read to the same units. + const gate = this.delegatedAdminGate; + return await this.objectReadAdmission(objectName, permissionSets, delegatorSets, async () => + (await delegatedUnitReadAdmission(gate, objectName, 'find', context, permissionSets, delegatorSets)) !== null); } catch (e) { this.logger.error?.( `[security] canReadObject could not resolve the object-level read admission for ` + @@ -147,6 +157,7 @@ export async function objectReadAdmission( objectName: string, permissionSets: PermissionSet[], delegatorSets: PermissionSet[] | null, + ungrantedRead?: () => Promise, ): Promise { if (permissionSets.length === 0) return false; @@ -168,8 +179,14 @@ export async function objectReadAdmission( } } - // 5. The object-level CRUD grant. - if (!this.permissionEvaluator.checkObjectPermission('find', objectName, permissionSets, { isPrivate })) { + // 5. The object-level CRUD grant — or, where the asker hands one, the + // admission the read door makes beside it for a read no set grants + // (`canReadObject`'s ADR-0090 D12 delegated unit read). The ADR-0055 + // master-derived scope hands none. + if ( + !this.permissionEvaluator.checkObjectPermission('find', objectName, permissionSets, { isPrivate }) + && !(ungrantedRead && (await ungrantedRead())) + ) { return false; } diff --git a/packages/plugins/plugin-security/src/security-plugin-read-filter.ts b/packages/plugins/plugin-security/src/security-plugin-read-filter.ts index 5bc6b34d8ba..0cb82ab0591 100644 --- a/packages/plugins/plugin-security/src/security-plugin-read-filter.ts +++ b/packages/plugins/plugin-security/src/security-plugin-read-filter.ts @@ -65,6 +65,7 @@ import { isPrincipalLessContext } from './security-plugin.js'; import { RLS_DENY_FILTER } from './rls-compiler.js'; import { andComposeLayers } from './tenant-layer.js'; import { delegatedOrganizationRefusal, intersectDelegatedScope, resolveDelegatorContext } from './explain-engine.js'; +import { delegatedUnitReadAdmission } from './delegated-admin-gate.js'; /** * The `SecurityPlugin` members the functions below read — every one of them, @@ -75,6 +76,7 @@ import { delegatedOrganizationRefusal, intersectDelegatedScope, resolveDelegator * for which members are getters. */ export interface ReadFilterHost { + readonly delegatedAdminGate: SecurityPlugin['delegatedAdminGate']; readonly logger: SecurityPlugin['logger']; readonly permissionEvaluator: SecurityPlugin['permissionEvaluator']; readonly ql: SecurityPlugin['ql']; @@ -89,7 +91,7 @@ export interface ReadFilterHost { /** The body of `SecurityPlugin#getReadFilter`; the method's docblock there is its contract. */ export async function getReadFilter( - this: Pick, + this: Pick, object: string, context?: any, ): Promise | undefined> { @@ -157,11 +159,26 @@ export async function getReadFilter( // registry walk refuses); a THROW propagates to the catch below, which // denies — the same posture as the surrounding layers. const cbpFilter = this.computeControlledByParentFilter(object, 'find', context, permissionSets); + // [ADR-0090 D12, ruling of record 6663849489] The THIRD thing the + // middleware ANDs in for a read: where no set grants it, the delegated + // business-unit read it admits beside the grant (step 2) is confined to + // `id IN ` (step 3). `canReadObject` admits that read + // on the same judgment ({@link delegatedUnitReadAdmission}), so the two + // answers a bypassing door asks agree with the door: the delegate's units, + // and no other. A delegated (on-behalf-of) context never reaches here, and + // the judgment admits none. + let unitScope: Record | null = null; + if (this.delegatedAdminGate) { + const { isPrivate } = await this.getObjectSecurityMeta(object); + if (!this.permissionEvaluator.checkObjectPermission('find', object, permissionSets, { isPrivate })) { + unitScope = await delegatedUnitReadAdmission(this.delegatedAdminGate, object, 'find', context, permissionSets, null); + } + } // [#4467] RLS AND controlled-by-parent AND sharing — the same // AND-composition the middlewares achieve by all writing into `ast.where`. // Any layer may be absent; `andComposeLayers` returns the others, or null // when none constrains. - return andComposeLayers(andComposeLayers(filter, cbpFilter), sharingFilter) ?? undefined; + return andComposeLayers(andComposeLayers(andComposeLayers(filter, cbpFilter), unitScope), sharingFilter) ?? undefined; } catch (e) { // Fail CLOSED — a resolution failure must deny (zero rows), never expose // every tenant's data through the raw-SQL analytics path. diff --git a/packages/plugins/plugin-security/src/security-plugin.ts b/packages/plugins/plugin-security/src/security-plugin.ts index c242a045edd..b44d99314c1 100644 --- a/packages/plugins/plugin-security/src/security-plugin.ts +++ b/packages/plugins/plugin-security/src/security-plugin.ts @@ -2902,12 +2902,17 @@ export class SecurityPlugin implements Plugin { context?: any, ): Promise | undefined> { // [#25223 cut 9] The body moved to `security-plugin-read-filter.ts` (see `ReadFilterHost`). + const readDelegatedAdminGate = () => this.delegatedAdminGate; const readLogger = () => this.logger; - const host: Pick = { + const readPermissionEvaluator = () => this.permissionEvaluator; + const host: Pick = { computeControlledByParentFilter: (...a) => this.computeControlledByParentFilter(...a), computeDelegatedReadFilter: (...a) => this.computeDelegatedReadFilter(...a), computeRlsFilter: (...a) => this.computeRlsFilter(...a), + get delegatedAdminGate() { return readDelegatedAdminGate(); }, + getObjectSecurityMeta: (...a) => this.getObjectSecurityMeta(...a), get logger() { return readLogger(); }, + get permissionEvaluator() { return readPermissionEvaluator(); }, resolvePermissionSetsForContext: (...a) => this.resolvePermissionSetsForContext(...a), resolveSharingReadFilter: (...a) => this.resolveSharingReadFilter(...a), }; @@ -3335,7 +3340,13 @@ export class SecurityPlugin implements Plugin { * CRUD class, checked BEFORE the grant, for the caller AND (D10) the * delegator; * 5. the `allowRead` CRUD grant ({@link PermissionEvaluator.checkObjectPermission} - * on `find`); + * on `find`) — or, where no set grants it, the one admission the + * middleware makes beside it: [ADR-0090 D12, ruling of record + * 6663849489] a delegate reads the business units its admin scopes + * cover (`delegatedUnitReadAdmission`, the middleware's own judgment). + * That read is of SOME units, so `true` here comes with + * {@link getReadFilter} confining it to them, as every row-restricted + * read does; * 6. ADR-0090 D10 — the delegator must independently hold the same grant; * a dangling delegator denies. * @@ -3353,10 +3364,12 @@ export class SecurityPlugin implements Plugin { */ canReadObject(object: string, context?: any): Promise { // [#25223 cut 9] The body moved to `security-plugin-object-admission.ts` (see `ObjectAdmissionHost`). + const readDelegatedAdminGate = () => this.delegatedAdminGate; const readLogger = () => this.logger; const readQl = () => this.ql; const readTenancyPosture = () => this.tenancyPosture; - const host: Pick = { + const host: Pick = { + get delegatedAdminGate() { return readDelegatedAdminGate(); }, get logger() { return readLogger(); }, objectReadAdmission: (...a) => this.objectReadAdmission(...a), get ql() { return readQl(); }, @@ -3392,7 +3405,10 @@ export class SecurityPlugin implements Plugin { * - 3. [#3545] An unresolvable posture denies. * - 4. The capabilities the object requires for a read, held by the caller * and (D10) by a delegator who resolved any set. - * - 5. The caller's `find` grant, with the posture's `isPrivate` (ADR-0066 D2). + * - 5. The caller's `find` grant, with the posture's `isPrivate` (ADR-0066 D2), + * or `ungrantedRead` where the asker hands it — the read door's admission + * beside the grant (`canReadObject` hands the ADR-0090 D12 delegated unit + * read; the ADR-0055 master-derived scope hands none). * - 6. [ADR-0090 D10] The delegator's `find` grant, asked over its list * whatever its length, as the middleware asks it: a delegator who resolves * NO set grants nothing, the deny baseline for the second principal too. @@ -3404,6 +3420,7 @@ export class SecurityPlugin implements Plugin { objectName: string, permissionSets: PermissionSet[], delegatorSets: PermissionSet[] | null, + ungrantedRead?: () => Promise, ): Promise { // [#25223 cut 9] The body moved to `security-plugin-object-admission.ts` (see `ObjectAdmissionHost`). const readPermissionEvaluator = () => this.permissionEvaluator; @@ -3411,7 +3428,7 @@ export class SecurityPlugin implements Plugin { getObjectSecurityMeta: (...a) => this.getObjectSecurityMeta(...a), get permissionEvaluator() { return readPermissionEvaluator(); }, }; - return objectReadAdmission.call(host, objectName, permissionSets, delegatorSets); + return objectReadAdmission.call(host, objectName, permissionSets, delegatorSets, ungrantedRead); } /**