Skip to content

Commit c9cb46a

Browse files
committed
feat(plugin-security): a delegate reads the business units its admin scope covers
A delegation's admin scope over a business-unit subtree (ADR-0090 D12) also grants read on the units inside that scope, so delegated administration can name the units it administers. The read is admitted only for a read of sys_business_unit the caller's sets do not grant, on the caller's own behalf, and is bounded to the union of the subtrees its scopes cover. Claude-Session: https://claude.ai/code/session_01Utp6CYQjMkN514R78sCrTT Co-authored-by: Claude <noreply@anthropic.com>
1 parent 61bba86 commit c9cb46a

3 files changed

Lines changed: 175 additions & 9 deletions

File tree

‎packages/plugins/plugin-security/src/delegated-admin-gate.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,6 +423,47 @@ export function isUnreadableAddressedRowRefusal(refusal: unknown): boolean {
423423
return refusal instanceof UnreadableAddressedRowRefusal;
424424
}
425425

426+
/** The object a delegation's scope grants read on: the business-unit tree it is drawn over. */
427+
const DELEGATED_READ_OBJECT = 'sys_business_unit';
428+
/** The operations that read; the middleware dispatches no other read verb. */
429+
const DELEGATED_READ_OPERATIONS: ReadonlySet<string> = new Set(['find', 'findOne', 'count', 'aggregate']);
430+
431+
/**
432+
* [ADR-0090 D12, ruling of record 6663849489] A delegation's admin scope over
433+
* a business-unit subtree also grants read on the units inside that scope, so
434+
* delegated administration can name the units it administers (an assignment's
435+
* `business_unit_id` is a reference the caller must be able to read).
436+
*
437+
* The authz middleware asks this only for an operation the caller's sets do
438+
* NOT grant, and admits it only on a non-null answer: the `where` scope
439+
* `id IN <the covered units>` it then ANDs into the read. Null — the ordinary
440+
* refusal stands — unless every condition holds: a read of
441+
* `sys_business_unit` carrying a query, on the caller's own behalf (no
442+
* on-behalf-of delegator), with the gate composed, and at least one covered
443+
* unit ({@link DelegatedAdminGate.scopedBusinessUnitIds}). Nothing wider: no
444+
* other object, no write, and no unit outside the scopes the caller holds; a
445+
* caller whose sets already grant the read is untouched. A scope that cannot
446+
* be resolved admits nothing (fail closed).
447+
*/
448+
export async function delegatedUnitReadScope(
449+
gate: Pick<DelegatedAdminGate, 'scopedBusinessUnitIds'> | null | undefined,
450+
opCtx: { object?: string; operation?: string; ast?: unknown; context?: any },
451+
permissionSets: PermissionSet[],
452+
delegatorSets: PermissionSet[] | null | undefined,
453+
): Promise<Record<string, unknown> | null> {
454+
if (!gate || delegatorSets) return null;
455+
if (opCtx.object !== DELEGATED_READ_OBJECT || !DELEGATED_READ_OPERATIONS.has(String(opCtx.operation)) || !opCtx.ast) {
456+
return null;
457+
}
458+
let ids: ReadonlySet<string>;
459+
try {
460+
ids = await gate.scopedBusinessUnitIds(permissionSets, opCtx.context);
461+
} catch {
462+
return null;
463+
}
464+
return ids.size > 0 ? { id: { $in: [...ids] } } : null;
465+
}
466+
426467
/**
427468
* [ADR-0090 D12] A row an administrator's write targets — the delegated walk's
428469
* and the organization branch's alike — with what the caller may be told about
@@ -655,6 +696,26 @@ export class DelegatedAdminGate {
655696
return false;
656697
}
657698

699+
/**
700+
* [ADR-0090 D12, ruling of record 6663849489] The business units a caller's
701+
* delegated scopes cover: the union of the subtrees of every `adminScope`
702+
* its resolved sets carry, resolved in the caller's own organization
703+
* ({@link callerOrganizationId}), exactly as the write path resolves them.
704+
* A delegation's scope also grants read on these units, so delegated
705+
* administration can name the units it administers; the authz middleware
706+
* admits that read on this answer alone. Any held scope counts, as for
707+
* {@link scopesCoverUser}.
708+
*
709+
* Fail closed: no scope, or a scope that resolves to no unit of the
710+
* caller's organization, covers nothing — an empty set.
711+
*/
712+
async scopedBusinessUnitIds(sets: PermissionSet[], callerContext?: any): Promise<ReadonlySet<string>> {
713+
const held = await this.resolveHeldScopes(sets, callerOrganizationId(callerContext));
714+
const ids = new Set<string>();
715+
for (const s of held) for (const id of s.subtree) ids.add(id);
716+
return ids;
717+
}
718+
658719
/**
659720
* [ADR-0090 D12 / ADR-0105 D8] Describe what the caller may DELEGATE —
660721
* the read half of this gate.

‎packages/plugins/plugin-security/src/delegated-admin-own-name-set.posture.test.ts‎

Lines changed: 98 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ const eastScope = (allow: string[]) => ({
4343
assignablePermissionSets: allow,
4444
});
4545
const CRUD = { sys_user_position: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } };
46+
/** [#29029] A plain object whose `unit` lookup names a business unit. */
47+
const UNIT_NOTE = 'qa_unit_note';
48+
const NOTE_CRUD = { allowRead: true, allowCreate: true, allowEdit: true };
4649

4750
/**
4851
* The catalog. `field_rep` and `field_lead` each list only `field_user`, and
@@ -60,7 +63,9 @@ const PERMISSIONS = [
6063
// Carries an adminScope equal to the wide delegate's own: not strictly contained by it.
6164
{ name: 'field_lead', label: 'Field lead (own name)', objects: CRUD, adminScope: eastScope(['field_user', 'field_rep', 'field_lead']) },
6265
// Narrow: allowlists the sets the positions LIST, not their own-name sets.
63-
{ name: 'east_admin', label: 'East delegate', objects: CRUD, adminScope: eastScope(['field_user']) },
66+
{ name: 'east_admin', label: 'East delegate', objects: { ...CRUD, [UNIT_NOTE]: NOTE_CRUD }, adminScope: eastScope(['field_user']) },
67+
// [#29029] A writer of the unit note with no admin scope at all.
68+
{ name: 'note_writer', label: 'Note writer', objects: { [UNIT_NOTE]: NOTE_CRUD } },
6469
// Wide: also allowlists the own-name sets.
6570
{ name: 'east_admin_wide', label: 'East delegate (wide)', objects: CRUD, adminScope: eastScope(['field_user', 'field_rep', 'field_lead']) },
6671
];
@@ -74,8 +79,10 @@ const POSITIONS = [
7479
type Posture = 'single' | 'group' | 'isolated';
7580
const POSTURES: Posture[] = ['single', 'group', 'isolated'];
7681

82+
/** The users of `ORG_A`, as the runtime resolves them onto every session's context from `sys_member`. */
83+
const ORG_USER_IDS = ['u_delegate', 'u_delegate_wide', 'u_target', 'u_writer', 'u_org_admin'];
7784
const delegateCtx = (userId: string, set: string) =>
78-
({ userId, positions: [], permissions: [set], tenantId: ORG_A, accessible_org_ids: [ORG_A] });
85+
({ userId, positions: [], permissions: [set], tenantId: ORG_A, accessible_org_ids: [ORG_A], org_user_ids: ORG_USER_IDS });
7986
const NARROW = delegateCtx('u_delegate', 'east_admin');
8087
const WIDE = delegateCtx('u_delegate_wide', 'east_admin_wide');
8188

@@ -100,11 +107,22 @@ async function boot(posture: Posture) {
100107
version: '1.0.0',
101108
type: 'plugin',
102109
scope: 'system',
103-
objects: [SysUserPosition, SysUserPermissionSet, SysMember, SysBusinessUnit, SysBusinessUnitMember],
110+
// [#29029] `sys_user` provisioned: an assignment's `user_id` names a user
111+
// the caller must be able to read, so the table the read door asks exists.
112+
objects: [
113+
SysUser, SysUserPosition, SysUserPermissionSet, SysMember, SysBusinessUnit, SysBusinessUnitMember,
114+
{
115+
name: UNIT_NOTE,
116+
label: 'Unit note',
117+
sharingModel: 'public_read_write',
118+
fields: {
119+
name: { name: 'name', type: 'text' },
120+
unit: { name: 'unit', type: 'lookup', reference: 'sys_business_unit' },
121+
},
122+
},
123+
],
104124
} as any);
105125
await engine.syncSchemas();
106-
// `sys_user` registered and unprovisioned, as in the sibling posture suite.
107-
if (!engine.registry.getObject(SysUser.name)) engine.registry.registerObject(SysUser as never, 'qa.delegated-own-name');
108126
engines.push(engine);
109127

110128
const services: Record<string, unknown> = {
@@ -140,8 +158,10 @@ async function boot(posture: Posture) {
140158
{ id: 'bu_east', name: 'east', parent_business_unit_id: 'bu_hq', organization_id: ORG_A },
141159
{ id: 'bu_east_field', name: 'east_field', parent_business_unit_id: 'bu_east', organization_id: ORG_A },
142160
], sys);
143-
for (const userId of ['u_delegate', 'u_delegate_wide', 'u_target']) {
144-
await engine.insert('sys_member', { id: `m_${userId}`, user_id: userId, organization_id: ORG_A, role: 'member' }, sys);
161+
for (const userId of ORG_USER_IDS) {
162+
await engine.insert('sys_user', { id: userId, email: `${userId}@example.test`, name: userId }, sys);
163+
const role = userId === 'u_org_admin' ? 'admin' : 'member';
164+
await engine.insert('sys_member', { id: `m_${userId}`, user_id: userId, organization_id: ORG_A, role }, sys);
145165
}
146166
await engine.insert('sys_business_unit_member',
147167
{ id: 'bum_target', user_id: 'u_target', business_unit_id: 'bu_east_field', organization_id: ORG_A }, sys);
@@ -236,3 +256,74 @@ describe('[ADR-0090 D12, amended 2026-10-17; #24757] a delegate is judged on exa
236256
});
237257
}
238258
});
259+
260+
/** [#29029] Every unit id `context` reads, sorted, or the refusal's status and code. */
261+
async function unitsRead(h: Awaited<ReturnType<typeof boot>>, context: any): Promise<string[] | { status: number; code?: string }> {
262+
try {
263+
const rows = await h.engine.find('sys_business_unit', { context } as any);
264+
return (Array.isArray(rows) ? rows : []).map((r: any) => String(r.id)).sort();
265+
} catch (e) {
266+
const r = resolveThrownHttpError(e);
267+
return { status: r.status, code: r.code };
268+
}
269+
}
270+
271+
/** [#29029] A unit note naming `unit`, written as `context`: the outcome, and the refused field's code. */
272+
async function noteNaming(h: Awaited<ReturnType<typeof boot>>, context: any, unit: string) {
273+
try {
274+
await h.engine.insert(UNIT_NOTE, { name: `note on ${unit}`, unit }, { context } as any);
275+
return { status: 200 };
276+
} catch (e) {
277+
const r = resolveThrownHttpError(e);
278+
const fields = ((e as any)?.fields ?? []) as Array<{ field?: string; code?: string }>;
279+
return { status: r.status, code: r.code, fields: fields.map((f) => `${f.field}:${f.code}`) };
280+
}
281+
}
282+
283+
async function storedNotes(h: Awaited<ReturnType<typeof boot>>): Promise<string[]> {
284+
const rows = await h.engine.find(UNIT_NOTE, { context: SYS });
285+
return (Array.isArray(rows) ? rows : []).map((r: any) => String(r.unit)).sort();
286+
}
287+
288+
describe('[ADR-0090 D12, ruling of record 6663849489; #29029] a delegate reads the business units its scope covers, and no other — three postures', () => {
289+
const WRITER = delegateCtx('u_writer', 'note_writer');
290+
const ORG_ADMIN = delegateCtx('u_org_admin', 'organization_admin');
291+
292+
for (const posture of POSTURES) {
293+
describe(`posture '${posture}'`, () => {
294+
it('the delegate reads exactly the units its scope covers: the scope root and its subtree, not the unit above it', async () => {
295+
const h = await boot(posture);
296+
expect(await unitsRead(h, NARROW)).toEqual(['bu_east', 'bu_east_field']);
297+
const above = await h.engine.findOne('sys_business_unit', { where: { id: 'bu_hq' }, context: NARROW } as any);
298+
expect(above ?? null).toBeNull();
299+
expect(await h.engine.count('sys_business_unit', { context: NARROW } as any)).toBe(2);
300+
});
301+
302+
it('the delegate assigns a position in a unit its scope covers, and the assignment is stored', async () => {
303+
const h = await boot(posture);
304+
expect(await assign(h, NARROW, 'field_rep')).toEqual({ status: 200 });
305+
expect(await storedPositions(h)).toEqual(['field_rep']);
306+
});
307+
308+
it('a unit outside the scope is a unit the delegate cannot read: a reference to it answers reference_not_found, and one inside is admitted', async () => {
309+
const h = await boot(posture);
310+
expect(await noteNaming(h, NARROW, 'bu_hq')).toEqual({ status: 400, code: 'VALIDATION_FAILED', fields: ['unit:reference_not_found'] });
311+
expect(await noteNaming(h, NARROW, 'bu_east_field')).toEqual({ status: 200 });
312+
expect(await storedNotes(h)).toEqual(['bu_east_field']);
313+
});
314+
315+
it('CONTROL: a caller holding no scope still reads no unit, and cannot name one', async () => {
316+
const h = await boot(posture);
317+
expect(await unitsRead(h, WRITER)).toEqual({ status: 403, code: 'PERMISSION_DENIED' });
318+
expect(await noteNaming(h, WRITER, 'bu_east')).toEqual({ status: 400, code: 'VALIDATION_FAILED', fields: ['unit:reference_not_found'] });
319+
expect(await storedNotes(h)).toEqual([]);
320+
});
321+
322+
it('CONTROL: an organization administrator reads and names every unit of its organization, as before', async () => {
323+
const h = await boot(posture);
324+
expect(await unitsRead(h, ORG_ADMIN)).toEqual(['bu_east', 'bu_east_field', 'bu_hq']);
325+
expect(await noteNaming(h, ORG_ADMIN, 'bu_hq')).toEqual({ status: 200 });
326+
});
327+
});
328+
}
329+
});

‎packages/plugins/plugin-security/src/security-plugin-authz-middleware.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ import { declaredHttpStatus } from '@objectstack/types';
104104
import type { SecurityPlugin } from './security-plugin.js';
105105
import { isGuestEnvelope, readUnlessRefused, requiredCapsForOperation } from './security-plugin.js';
106106
import { assertFlowSystemIdentityWriteAllowed } from './flow-system-identity-write-refusal.js';
107-
import { isUnreadableAddressedRowRefusal } from './delegated-admin-gate.js';
107+
import { delegatedUnitReadScope, isUnreadableAddressedRowRefusal } from './delegated-admin-gate.js';
108108
import { isRowWriteProbe, logGateRefusal, type AuthzMiddlewareFn } from './record-row-write-probe.js';
109109
import {
110110
intersectDelegatedScope,
@@ -840,15 +840,26 @@ export function registerAuthzMiddleware(
840840
// guard this replaced admitted that caller to every object no set
841841
// grants. A principal-less context never reaches this line — it was
842842
// refused above ({@link isPrincipalLessContext}, [#21908] ADR-0096 D5).
843+
//
844+
// [ADR-0090 D12, ruling of record 6663849489] One admission beside the
845+
// grant: a delegate reads the business units its admin scopes cover. For
846+
// a read of `sys_business_unit` no set grants, `delegatedUnitReadScope`
847+
// answers the `id IN <covered units>` scope step 3 ANDs into the read, or
848+
// null — and null keeps the refusal below. Every condition and why it is
849+
// no wider is on that function.
850+
let delegatedUnitScope: Record<string, unknown> | null = null;
843851
if (!referentialFieldClearWrite) {
844852
const allowed = this.permissionEvaluator.checkObjectPermission(
845853
opCtx.operation,
846854
opCtx.object,
847855
permissionSets,
848856
{ isPrivate: secMeta.isPrivate },
849857
);
850-
851858
if (!allowed) {
859+
delegatedUnitScope = await delegatedUnitReadScope(this.delegatedAdminGate, opCtx, permissionSets, delegatorSets);
860+
}
861+
862+
if (!allowed && !delegatedUnitScope) {
852863
// [#7414] TWO messages, two audiences — the split #7307 made for
853864
// `DELETE_RESTRICTED`, reached from the authorization side and through
854865
// the SAME catalog.
@@ -2351,6 +2362,9 @@ export function registerAuthzMiddleware(
23512362
);
23522363
const rlsFilter = andComposeLayers(layered.layer0, layered.layer1);
23532364
if (rlsFilter) extra.push(rlsFilter);
2365+
// [ADR-0090 D12] The delegated unit read admitted at step 2 sees the
2366+
// units its scopes cover, and only those.
2367+
if (delegatedUnitScope) extra.push(delegatedUnitScope);
23542368
let tenantLayer0Verdict = layered.tenantLayer0Verdict;
23552369
// ADR-0055: a controlled_by_parent object derives its read scope from the
23562370
// master record — `masterFK IN (<the master ids this caller may read>)`,

0 commit comments

Comments
 (0)