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
21 changes: 21 additions & 0 deletions .changeset/25280-delegation-own-organization.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
'@objectstack/plugin-approvals': patch
---

fix(plugin-approvals): an out-of-office delegation applies only in its own organization, and an organization-less delegation reroutes no approval

Clause-②: no (narrowing)
Metadata-protocol: none

<!-- adr-0087: not-required (no-migration-prescription) No key of any metadata schema is removed, renamed or re-shaped, so there is nothing for `objectstack migrate meta` to rewrite and no tombstone. What changes is how the approval service reads a stored `sys_approval_delegation` row: the reading ADR-0131 D1 retired for every tenant column, and that `grantAppliesInTenant` already applies to grant rows. -->

**BREAKING** for a stored `sys_approval_delegation` row that carries no `organization_id` (`NULL`, absent or blank). No write produces such a row any more under a walled posture, so only a database upgraded from before 18.0 can hold one.

- **Which delegation reroutes an approver.** FROM: an organization-less delegation applied in every organization ("null = applies across tenants for this delegator"), and a request with no organization took every active delegation of its approver, whatever organization it belonged to. TO: a delegation reroutes an approver only when its organization is the request's organization, the rule a stored position or permission-set grant follows. An organization-less delegation reroutes nothing anywhere, and a request with no organization takes no delegation.
- **Why.** Under `group` or `isolated`, an organization-less delegation rerouted every organization's approvals for its delegator, onto a delegate who may hold no membership in that organization. ADR-0131 D1: nothing reads a NULL tenant value as an owner.
- **Under `single`** a delegation written on 18.x applies as before: the engine stamps the Default Organization on a delegation its author writes and on the record a request is about, and the request takes its record's organization. Only an organization-less row left from before the ownership ceremony stops applying.
- **Where such a row comes from.** Under a wall a member's insert is stamped with the active organization, an elevated insert with none is refused, and an update that empties the column is refused. A row stored before that, on a database upgraded from 17.x or an 18.0 pre-release, can still be organization-less: `os migrate organization-ownership` attributes it to the Default Organization under `single`, and under a wall, where the row names nothing to attribute it by, reports it and leaves it NULL.
- **It is not silent.** Each time a lookup skips an active organization-less delegation, the approval service logs a `warn` naming the delegation, its delegator and delegate, the request's organization, and the remedy.
- **Setup.** The delegation form's Organization help says what the code does, in every shipped locale.

**What an operator does.** On a `single` deployment, run `os migrate organization-ownership --apply` if it has not run yet; it attributes these rows to the Default Organization. On a walled deployment, ask the delegator to create the delegation again while signed in to the organization whose approvals it should cover, then delete the organization-less row the warning names.
7 changes: 7 additions & 0 deletions content/docs/automation/approvals.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -900,6 +900,13 @@ background job — so a lapsed delegation simply stops applying. Chains
identity**; the reroute is recorded as an `ooo_substitute` audit action and both
the delegate and the skipped approver are notified.

A delegation belongs to the organization it is created in, and reroutes only the
approvals opened in that organization; a request's organization is its record's.
To cover approvals in two organizations, create a delegation in each. A
delegation that names no organization, which only a database upgraded from
before 18.0 can hold, reroutes nothing, and the approval service logs a warning
naming it (ADR-0131).

<Callout type="info">
**Group-routed approvers are not rerouted.** `type: position` / `team` /
`department` / `org_membership_level` keep their whole membership, so there is
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,11 +202,14 @@ describe('#4839 evidence — a delegation cannot rescue an IN-FLIGHT approval',
svc = new ApprovalService({ engine: engine as any, clock: { now: () => new Date(baseTime + (n++) * 1000) } });
});

/** Declare an out-of-office delegation directly (bypassing the write guard). */
/**
* Declare an out-of-office delegation directly (bypassing the write guard),
* in the submitter's organization: a delegation applies only there (ADR-0131).
*/
const seedDelegation = (delegatorId: string, delegateId: string) => {
engine._tables['sys_approval_delegation'] = [{
id: 'del1', delegator_id: delegatorId, delegate_id: delegateId,
valid_from: null, valid_until: null, reason: 'sick leave', organization_id: null,
valid_from: null, valid_until: null, reason: 'sick leave', organization_id: 't1',
}];
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ describe('an empty admin_rescue slate opens on the organization\'s administrator
await engine.syncSchemas();
// The organization-less rows below exist only on a store built before 18.x
// (ADR-0131 D1 makes a fresh tenant column NOT NULL): this is that store.
await relaxTenantColumns(engine, ['sys_user', 'sys_user_permission_set', 'crm_deal', 'sys_approval_delegation']);
await relaxTenantColumns(engine, ['sys_user', 'sys_user_permission_set', 'crm_deal']);
bindSecurityCatalogReader(engine, catalogServing([
'organization_admin', 'organization_admin_no_bypass', 'admin_full_access',
]));
Expand Down Expand Up @@ -292,7 +292,7 @@ describe('an empty admin_rescue slate opens on the organization\'s administrator
// it writes stays, and no case after it reads that slate.
it('an administrator out of office is covered by their delegate, as any named approver is', async () => {
await engine.insert('sys_approval_delegation', {
id: 'dlg_admin', delegator_id: 'u_admin', delegate_id: 'u_cover', reason: 'leave',
id: 'dlg_admin', delegator_id: 'u_admin', delegate_id: 'u_cover', reason: 'leave', organization_id: ORG,
valid_from: '2026-09-01T00:00:00.000Z', valid_until: '2026-12-31T00:00:00.000Z',
created_at: '2026-09-01T00:00:00.000Z', updated_at: '2026-09-01T00:00:00.000Z',
}, { context: SYSTEM } as any);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ describe('every approval notification carries its text in body', () => {
await engine.syncSchemas();
// The organization-less rows below exist only on a store built before 18.x
// (ADR-0131 D1 makes a fresh tenant column NOT NULL): this is that store.
await relaxTenantColumns(engine, ['sys_user', 'sys_approval_delegation']);
await relaxTenantColumns(engine, ['sys_user']);
for (const u of USERS) await engine.insert('sys_user', u, { context: SYSTEM } as any);

svc = new ApprovalService({
Expand Down Expand Up @@ -263,8 +263,9 @@ describe('every approval notification carries its text in body', () => {
await svc.remind(ids.bare, { actorId: 'u_sub' }, asUser('u_sub'));

// ── Out of office: the routing substitutes a delegate ──
// A delegation applies only in its own organization (ADR-0131): the deal's.
await engine.insert('sys_approval_delegation', {
id: 'dlg_1', delegator_id: 'u_ooo', delegate_id: 'u_bob', reason: 'leave',
id: 'dlg_1', delegator_id: 'u_ooo', delegate_id: 'u_bob', reason: 'leave', organization_id: orgOfDeal('ooo'),
valid_from: '2026-09-01T00:00:00.000Z', valid_until: '2026-12-31T00:00:00.000Z',
created_at: '2026-09-01T00:00:00.000Z', updated_at: '2026-09-01T00:00:00.000Z',
}, { context: SYSTEM } as any);
Expand All @@ -273,7 +274,7 @@ describe('every approval notification carries its text in body', () => {
// [#24065] The control: the absent approver names no account, so no name
// can be read for them; the delegate the same hop routes to does.
await engine.insert('sys_approval_delegation', {
id: 'dlg_2', delegator_id: GONE, delegate_id: 'u_alice', reason: 'leave',
id: 'dlg_2', delegator_id: GONE, delegate_id: 'u_alice', reason: 'leave', organization_id: orgOfDeal('ooo_gone'),
valid_from: '2026-09-01T00:00:00.000Z', valid_until: '2026-12-31T00:00:00.000Z',
created_at: '2026-09-01T00:00:00.000Z', updated_at: '2026-09-01T00:00:00.000Z',
}, { context: SYSTEM } as any);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3134,10 +3134,13 @@ describe('ApprovalService — out-of-office delegation (#1322)', () => {
expect(req.pending_approvers).toEqual(['alice']);
});

it('applies a cross-tenant (null org) rule regardless of request tenant', async () => {
// ADR-0131 D1: an organization-less row is no "every organization" rule.
// The full matrix, per posture, is `ooo-delegation-organization.test.ts`.
it('an organization-less rule reroutes nothing, in the request tenant or any other', async () => {
seedDelegation([{ delegator_id: 'alice', delegate_id: 'bob', organization_id: null }]);
const req = await svc.openNodeRequest(openInput(['alice']), CTX);
expect(req.pending_approvers).toEqual(['bob']);
expect(req.pending_approvers).toEqual(['alice']);
expect(engine._tables['sys_approval_action'].some((a: any) => a.action === 'ooo_substitute')).toBe(false);
});
});

Expand Down
61 changes: 57 additions & 4 deletions packages/plugins/plugin-approvals/src/approval-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1222,6 +1222,19 @@ function csvSplit(raw: unknown): string[] {
return String(raw).split(',').map(s => s.trim()).filter(Boolean);
}

/**
* [ADR-0131] The organization a value names, or `null` for none — `NULL`,
* absent or blank. The normalization `grantOrganizationOf`
* (`@objectstack/core`, `resolve-authz-context.ts`) gives a stored grant row's
* organization; `null` names no organization and matches none, its own
* included. Read by {@link ApprovalService.lookupActiveDelegation} on both
* sides of its comparison: the delegation row's and the request's.
*/
function organizationNamed(value: unknown): string | null {
if (value === null || value === undefined || value === '') return null;
return String(value);
}

/**
* Is a submitted decision output blank — i.e. does it fail a `required`
* declaration (objectui#2955)?
Expand Down Expand Up @@ -3227,6 +3240,32 @@ export class ApprovalService implements IApprovalService {
* shared `isGrantActive` half-open window (ADR-0091 D2), enforced here at
* resolution time — never by a background job. When several rows are active,
* the one expiring soonest wins (the most specific coverage window).
*
* **A delegation applies only in its own organization (ADR-0131).** A row
* reroutes a request's approver only when the row's `organization_id` is the
* request's organization: the rule `grantAppliesInTenant`
* (`@objectstack/core`, `resolve-authz-context.ts`) applies to a stored
* position or permission-set grant, read the same way here.
*
* - A delegation of another organization reroutes nothing in this one.
* - An organization-less delegation reroutes nothing anywhere. "NULL means
* every organization" is the reading ADR-0131 retired (D1: nothing reads a
* NULL tenant value as an owner). Under a wall no write produces such a row
* any more: a session insert is stamped with its active organization, an
* elevated insert with none is refused (D9), and the write wall refuses an
* update that empties the column. What remains is stored state from before.
* The D10 ceremony attributes it to the Default Organization under
* `single`; under a wall it has no anchor, so the ceremony reports it and
* leaves it NULL. Such a row is reported here at `warn` with its remedy,
* because its author still sees it in Setup and nothing else says it has
* stopped applying.
* - A request with no organization takes no delegation: a missing
* organization has no "every organization" reading either.
*
* The rule is the same in every posture (ADR-0131 D11). Under `single`, D9
* stamps the Default Organization on the delegation its author writes and on
* the record a request is about, and the request takes its record's
* organization, so a delegation written there applies as it did before.
*/
private async lookupActiveDelegation(
delegatorId: string,
Expand All @@ -3243,10 +3282,24 @@ export class ApprovalService implements IApprovalService {
context: SYSTEM_CTX,
} as any);
} catch { return null; } // table absent on minimal stacks — no OOO, resolve as-is
const active = (rows ?? []).filter((r: any) =>
isGrantActive(r, now)
// A null-org rule applies across tenants; a scoped rule only within its tenant.
&& (organizationId == null || r.organization_id == null || String(r.organization_id) === String(organizationId)));
const requestOrg = organizationNamed(organizationId);
const active: any[] = [];
for (const r of rows ?? []) {
if (!isGrantActive(r, now)) continue;
const rowOrg = organizationNamed(r?.organization_id);
if (rowOrg === null) {
this.logger?.warn?.(
`[approvals] out-of-office delegation '${r?.id}' (${delegatorId} → ${r?.delegate_id}) names no `
+ `organization, so it reroutes no approval: a delegation applies only to approvals in the `
+ `organization it belongs to. Create it again while signed in to the organization whose `
+ `approvals it should cover, and delete this one; on a single-organization deployment, `
+ `'os migrate organization-ownership --apply' attributes it to the Default Organization instead.`,
{ delegationId: r?.id, delegatorId, delegateId: r?.delegate_id, requestOrganizationId: requestOrg },
);
continue;
}
if (rowOrg === requestOrg) active.push(r);
}
if (!active.length) return null;
active.sort((a: any, b: any) => {
const au = a.valid_until ? Date.parse(String(a.valid_until)) : Number.POSITIVE_INFINITY;
Expand Down
Loading
Loading