Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/delegated-subtree-one-organization.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@objectstack/plugin-security': patch
---

fix(plugin-security)!: a delegated business-unit subtree stays inside one organization, whether or not the caller's context names one

Clause-②: no (narrowing) — the delegated-administration gate bounds every delegated business-unit subtree to one organization: the caller's when its context names one, otherwise the scope root's own. A unit of another organization is outside the subtree, and so is every unit below it, even where its parent link names a unit inside the scope. Nothing is widened: no export, error code or status is added.
Metadata-protocol: none

<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export of the package entry changes: an adminScope keeps its shape and meaning, and the subtree it names is bounded to one organization for every caller. There is nothing for a migration to rewrite and no tombstone. -->

**BREAKING** accept-set narrowing in the delegated-administration gate (`@objectstack/plugin-security`), for a business unit whose organization differs from its subtree's only.

- **Rule.** A delegated scope covers the units of ONE organization: the scope root and its descendants that carry that organization. Every answer that reads the subtree follows it — the delegated business-unit read (the read door, `canReadObject`, `getReadFilter`, `security/explain`), an assignment or direct grant written under the scope, the delegable-scope report and the explain coverage of a user. A unit outside it is refused `403 DELEGATION_SCOPE_VIOLATION` on a write and left out of every read and report.
- **Unchanged.** A context that names its organization gets every answer it got before. A unit of the subtree's own organization is inside the subtree, as before. A store whose units carry no organization keeps its whole tree.
- **Who moves.** Nobody whose business-unit tree keeps each unit in its parent's organization.
49 changes: 49 additions & 0 deletions packages/plugins/plugin-security/src/delegated-admin-gate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,55 @@ describe('DelegatedAdminGate — the anchor is picked by organization, not by ar
});
});

// ── A delegated subtree is one organization's, on a driver that scopes NOTHING ─
//
// [ADR-0090 D12] The harness `ql` ignores `context`, so the walk's child read
// hands every organization's units to the gate and the row-level bound is the
// only thing standing; the delegate's context names no organization. The
// posture rig (`delegated-admin-own-name-set.posture.test.ts`) pins the rule
// through the doors on a real engine; this half also pins the organization-less
// root, which a real table cannot hold (its tenant column is NOT NULL,
// ADR-0131 D1).
describe("DelegatedAdminGate — a delegated subtree is one organization's, with no organization on the context", () => {
/**
* Stamp every unit with `organizationId` (none: leave them organization-less),
* then link a unit of `linkedOrganization`, and one below it, under the scope
* root `bu_east`.
*/
function linkUnderScopeRoot(organizationId: string | null, linkedOrganization: string | null) {
if (organizationId) for (const r of h.tables.sys_business_unit) r.organization_id = organizationId;
h.tables.sys_business_unit.push(
{ id: 'bu_linked', name: 'linked', parent_business_unit_id: 'bu_east', organization_id: linkedOrganization },
{ id: 'bu_linked_child', name: 'linked_child', parent_business_unit_id: 'bu_linked', organization_id: linkedOrganization },
);
}
const placeable = async () => [...(await h.gate.describeDelegableScope(
await (h.gate as any).deps.resolveSets({ principal: 'delegate' }),
h.ctxOf('delegate'),
)).placeableBusinessUnitIds].sort();
const assignAt = (business_unit_id: string) =>
insertAssignment(h.ctxOf('delegate'), { user_id: 'u_east_1', position: 'sales_rep', business_unit_id });

for (const [label, root] of [['a stamped scope root', 'org_a'], ['an organization-less scope root', null]] as const) {
it(`${label}: the subtree stops at a unit stamped with another organization`, async () => {
linkUnderScopeRoot(root, 'org_b');
expect(await placeable()).toEqual(['bu_east', 'bu_es']);
for (const unit of ['bu_linked', 'bu_linked_child']) {
const err = await refusalOf(() => assignAt(unit));
expect([err.code, err.status], `${unit}: ${err.message}`).toEqual(['DELEGATION_SCOPE_VIOLATION', 403]);
}
// CONTROL: inside the subtree the same write is admitted.
await expect(assignAt('bu_es')).resolves.toBeUndefined();
});

it(`CONTROL — ${label}: a unit of the root's own organization under the same link is inside the subtree`, async () => {
linkUnderScopeRoot(root, root);
expect(await placeable()).toEqual(['bu_east', 'bu_es', 'bu_linked', 'bu_linked_child']);
await expect(assignAt('bu_linked_child')).resolves.toBeUndefined();
});
}
});

// ── A position is the security catalog's definition, not an organization's row ─
// [ADR-0131 D3/D4] The two position-keyed authority decisions (delegatable;
// bound sets) read the position's DEFINITION from the environment catalog by
Expand Down
36 changes: 27 additions & 9 deletions packages/plugins/plugin-security/src/delegated-admin-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@ const DEFAULT_DELEGATION_CEILING_MS = 30 * 24 * 60 * 60 * 1000;
* C1 it exists from boot, and every session on a stock `single` deployment —
* the administrator's and a delegate's alike — carries it as its active
* organization. Undefined only for a context carrying no organization at all,
* where a by-name anchor is read organization-less and nothing here changes.
* where a by-name anchor is read organization-less and the subtree under it
* stays inside that anchor's own organization (`resolveSubtree`).
*
* Under the `group` posture (ADR-0105 D2) this is the ACTIVE organization, not
* the caller's whole membership set. That is the narrower of the two, which is
Expand Down Expand Up @@ -1629,8 +1630,9 @@ export class DelegatedAdminGate {
*
* Fail closed on both axes: a name that resolves to no row of the caller's
* own organization approves nothing, exactly as a misconfigured scope does.
* An organization-less caller (`single` posture) keeps the by-name answer —
* there is no other organization for it to cross into.
* An organization-less caller (`single` posture) keeps the by-name answer
* for the ROOT; the subtree under it is still one organization's — the
* root row's own ({@link resolveSubtreeById}).
*/
private async resolveSubtree(
businessUnitName: string,
Expand All @@ -1652,14 +1654,26 @@ export class DelegatedAdminGate {
// nothing (fail closed).
if (!root?.id) return new Set<string>();
if (!includeSubtree) return new Set<string>([String(root.id)]);
return this.resolveSubtreeById(String(root.id), organizationId);
// The organization the subtree is bounded to: the caller's when its context
// names one (the root was resolved inside it above), otherwise the root
// row's own — never "any organization".
return this.resolveSubtreeById(String(root.id), organizationId ?? rowOrganizationId(root));
}

/** BU id → covered BU-id set (root id + all descendants). Subtree is always
* walked: the delegator's readScope depth is not known on the delegation
* path, so the whole subtree is the containment bound — matching the D12
* admin subtree check. Fail-closed on unresolvable ids (empty set). */
private async resolveSubtreeById(rootId: string, organizationId?: string): Promise<Set<string>> {
* admin subtree check. Fail-closed on unresolvable ids (empty set).
*
* Bounded to ONE organization, `organizationId`, which every caller names:
* a descendant stamped with any other organization is outside the subtree
* and is not walked through, whether or not the caller's context names an
* organization. `null` is the bound of an organization-less root (invalid
* state on a stamped store, `organization-scope.ts`, so met only on a store
* whose units carry no organization at all): organization-less descendants
* only, so a stamped unit is never reached from one, nor one from a stamped
* root. */
private async resolveSubtreeById(rootId: string, organizationId: string | null): Promise<Set<string>> {
const ids = new Set<string>();
const ql = this.deps.ql;
if (!ql?.find || !rootId) return ids;
Expand All @@ -1671,15 +1685,15 @@ export class DelegatedAdminGate {
children = await ql.find('sys_business_unit', {
where: { parent_business_unit_id: { $in: frontier } },
limit: 5000,
context: organizationScopedCtx(organizationId),
context: organizationScopedCtx(organizationId ?? undefined),
});
} catch { children = []; }
const next: string[] = [];
for (const c of Array.isArray(children) ? children : []) {
// A parent link is not an organization predicate: whatever a driver
// returned, a descendant outside the caller's organization never
// returned, a descendant outside the subtree's organization never
// widens the subtree a delegation is judged against.
if (organizationId && rowOrganizationId(c) !== organizationId) continue;
if (rowOrganizationId(c) !== organizationId) continue;
const id = String((c as any)?.id ?? '');
if (id && !ids.has(id)) { ids.add(id); next.push(id); }
}
Expand All @@ -1701,6 +1715,10 @@ export class DelegatedAdminGate {
organizationId?: string,
): Promise<Set<string>> {
const allowed = new Set<string>();
// A holding takes effect only in its own organization
// ({@link holdingTakesEffectIn}), so a context naming none holds nothing
// to anchor a delegation in, and there is no organization to bound a walk to.
if (!organizationId) return allowed;
let memberSubtreeResolved = false;
for (const h of directHoldings) {
if (h.businessUnitId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { SecurityPlugin } from './security-plugin.js';
import { SysUserPosition } from './objects/sys-user-position.object.js';
import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js';
import { defaultPermissionSets } from './objects/index.js';
import { installDefaultOrganization } from './default-organization.testkit.js';

const SYS = { isSystem: true } as const;
const ORG_A = 'org_a';
Expand Down Expand Up @@ -99,7 +100,13 @@ afterEach(async () => {
}
});

async function boot(posture: Posture) {
/**
* `defaultOrganization`: also give the engine the organization object holding the
* Default Organization, as every real `single` install has — so a write whose
* context names no organization is stamped with it instead of being refused for
* having none (`default-organization.testkit.ts`).
*/
async function boot(posture: Posture, opts: { defaultOrganization?: boolean } = {}) {
const engine = new ObjectQL();
engine.registerDriver(
new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }),
Expand Down Expand Up @@ -128,6 +135,7 @@ async function boot(posture: Posture) {
],
} as any);
await engine.syncSchemas();
if (opts.defaultOrganization) await installDefaultOrganization(engine as any);
engines.push(engine);

const services: Record<string, unknown> = {
Expand Down Expand Up @@ -447,3 +455,110 @@ describe('[ADR-0090 D12, ruling of record 6663849489; #30758] canReadObject and
});
}
});

/**
* [ADR-0090 D12, ruling of record 6663849489] The subtree a delegated scope
* covers is ONE organization's, whether or not the caller's context names an
* organization: a unit stamped with another organization is outside it even
* where its parent link names a unit inside the scope, and so is everything
* below it. Every answer that reads the subtree is asked — the gate's covered
* units (what the read door confines a delegated read to), the delegable-scope
* report, the explain coverage of a user, the write gate — and the read and
* write doors themselves.
*/
describe('[ADR-0090 D12, ruling of record 6663849489] a delegated business-unit subtree never crosses an organization boundary, whether or not the caller\'s context names an organization — three postures', () => {
const ORG_B = 'org_b';
/** The delegate's context with no organization on it at all. */
const NO_ORGANIZATION: any = { userId: 'u_delegate', positions: [], permissions: ['east_admin'] };
/** The same, carrying the users it may name — an assignment's `user_id` is a reference it must read. */
const NO_ORGANIZATION_NAMING_USERS: any = { ...NO_ORGANIZATION, org_user_ids: ORG_USER_IDS };
const IN_SCOPE = ['bu_east', 'bu_east_field'];

/** Another organization's unit whose parent link names the scope root `bu_east`, a unit below it, and a member of it. */
async function linkOtherOrganization(h: Awaited<ReturnType<typeof boot>>) {
const asOrgB = { context: { isSystem: true, tenantId: ORG_B } } as any;
await h.engine.insert('sys_business_unit', [
{ id: 'bu_b_linked', name: 'b_linked', parent_business_unit_id: 'bu_east', organization_id: ORG_B },
{ id: 'bu_b_linked_child', name: 'b_linked_child', parent_business_unit_id: 'bu_b_linked', organization_id: ORG_B },
], asOrgB);
await h.engine.insert('sys_user', { id: 'u_b_member', email: 'u_b_member@example.test', name: 'u_b_member' }, asOrgB);
await h.engine.insert('sys_business_unit_member',
{ id: 'bum_b_member', user_id: 'u_b_member', business_unit_id: 'bu_b_linked', organization_id: ORG_B }, asOrgB);
}

/** What the gate itself answers for `context`: covered units, placeable units, and whether it covers the other organization's member. */
async function gateAnswers(h: Awaited<ReturnType<typeof boot>>, context: any) {
const security = h.plugin as any;
const sets = await security.resolvePermissionSetsForContext(context);
const gate = security.delegatedAdminGate;
return {
covered: [...(await gate.scopedBusinessUnitIds(sets, context)) as Set<string>].sort(),
placeable: [...(await gate.describeDelegableScope(sets, context)).placeableBusinessUnitIds as string[]].sort(),
coversOtherMember: await gate.scopesCoverUser(sets, 'u_b_member', context),
};
}

/** The write gate's verdict on an insert of `data` into `object` as `context`. */
const gateInsert = (h: Awaited<ReturnType<typeof boot>>, context: any, object: string, data: Record<string, unknown>) =>
outcome(() => (h.plugin as any).delegatedAdminGate.assert({ object, operation: 'insert', data, context }));

for (const posture of POSTURES) {
describe(`posture '${posture}'`, () => {
it("ground truth: the store holds another organization's units under a parent link that names the scope root", async () => {
const h = await boot(posture);
await linkOtherOrganization(h);
const rows = await h.engine.find('sys_business_unit', { where: { organization_id: ORG_B }, context: SYS });
expect((Array.isArray(rows) ? rows : []).map((r: any) => [r.id, r.parent_business_unit_id]).sort())
.toEqual([['bu_b_linked', 'bu_east'], ['bu_b_linked_child', 'bu_b_linked']]);
});

it("the gate covers the scope's own organization's units only — with no organization on the context, and with one", async () => {
const h = await boot(posture);
await linkOtherOrganization(h);
for (const [label, context] of [['no organization', NO_ORGANIZATION], ['its organization', NARROW]] as const) {
expect(await gateAnswers(h, context), label).toEqual({ covered: IN_SCOPE, placeable: IN_SCOPE, coversOtherMember: false });
}
});

it('the read door returns no unit of another organization to a context naming no organization', async () => {
const h = await boot(posture);
await linkOtherOrganization(h);
// `single` has no tenancy layer, so the delegated scope is the read's
// only bound; under `group`/`isolated` that layer reads nothing for a
// context naming no organization.
expect(await unitsRead(h, NO_ORGANIZATION)).toEqual(posture === 'single' ? IN_SCOPE : []);
// CONTROL: the context naming its organization reads its scope, as before.
expect(await unitsRead(h, NARROW)).toEqual(IN_SCOPE);
});

it("the write gate refuses an assignment anchored in, and a direct grant to a member of, another organization's unit — and admits one inside the scope", async () => {
const h = await boot(posture);
await linkOtherOrganization(h);
for (const [label, context] of [['no organization', NO_ORGANIZATION], ['its organization', NARROW]] as const) {
for (const unit of ['bu_b_linked', 'bu_b_linked_child']) {
const r = await gateInsert(h, context, 'sys_user_position', { user_id: 'u_target', position: 'field_rep', business_unit_id: unit });
expect([r.status, r.code], `${label} · ${unit}: ${r.message}`).toEqual([403, 'DELEGATION_SCOPE_VIOLATION']);
}
const grant = await gateInsert(h, context, 'sys_user_permission_set', { user_id: 'u_b_member', permission_set: 'field_user' });
expect([grant.status, grant.code], `${label} · grant: ${grant.message}`).toEqual([403, 'DELEGATION_SCOPE_VIOLATION']);
// CONTROL: the gate has not gone dark — inside the scope it admits.
const inside = await gateInsert(h, context, 'sys_user_position', { user_id: 'u_target', position: 'field_rep', business_unit_id: 'bu_east_field' });
expect(inside, label).toEqual({ status: 200 });
}
});
});
}

it("posture 'single' with its Default Organization: the write door refuses an assignment anchored in another organization's unit for a context naming no organization, and stores one inside the scope", async () => {
const h = await boot('single', { defaultOrganization: true });
await linkOtherOrganization(h);
const assignAt = (unit: string) => outcome(() => h.engine.insert('sys_user_position',
{ user_id: 'u_target', position: 'field_rep', business_unit_id: unit }, { context: NO_ORGANIZATION_NAMING_USERS } as any));
const refused = await assignAt('bu_b_linked');
expect([refused.status, refused.code], refused.message).toEqual([403, 'DELEGATION_SCOPE_VIOLATION']);
expect(await storedPositions(h)).toEqual([]);
// CONTROL: the same door, context and position, inside the scope.
expect(await assignAt('bu_east_field')).toEqual({ status: 200 });
expect(await storedPositions(h)).toEqual(['field_rep']);
});
});
Loading