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

fix(plugin-approvals): an out-of-office delegation with an inverted window or the delegator as their own delegate is refused at the write, naming the field

Clause-②: yes (narrowing) — narrowed: a `sys_approval_delegation` insert, or an update that moves the compared columns, answers `400 VALIDATION_FAILED` where it was stored, when `valid_until` is at or before `valid_from` (field `valid_until`, rule `validity_window_order`) or when `delegate_id` equals `delegator_id` (field `delegate_id`, rule `delegate_not_delegator`). Both shapes were stored and never rerouted an approval. Nothing widens.
Metadata-protocol: none
Skills-docs: none — no skill under `skills/**` teaches out-of-office delegation; `content/docs/automation/approvals.mdx` gains the rule in this change.

<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed, renamed or re-shaped: the change is two declared validation rules on a platform object's data rows. A row stored with either shape before them was already inert and stays inert, so there is nothing for a migration to rewrite. -->

An out-of-office delegation whose window ends at or before it starts, or whose delegate is the delegator, could never reroute an approval, yet the write answered `201` and the delegator believed their approvals were covered. Both are now refused with `400 VALIDATION_FAILED` and a message on the field to correct.

Unchanged: a valid window with a different delegate; an open-ended window (either bound empty, or both); and an update that moves neither compared column, so a row stored with either shape before this release still takes unrelated edits.

What to do: nothing for a valid delegation. A row stored with an inverted window or a self-delegate stays inert as before: correct its dates or its delegate, or delete it.
7 changes: 7 additions & 0 deletions content/docs/automation/approvals.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1056,6 +1056,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 that could never reroute anything is refused at the write with
`400 VALIDATION_FAILED`, naming the field: a window whose `valid_until` is at or
before its `valid_from` (on `valid_until`), and a `delegate_id` equal to the
`delegator_id` (on `delegate_id`). Leave either bound empty for an open-ended
window. A row stored with either shape before this check existed stays inert:
correct its dates or its delegate, or delete it.

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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* An out-of-office delegation that could never reroute an approval is refused
* at the write, naming the field.
*
* Two shapes used to land and then do nothing: a validity window that ends at
* or before it starts (`isGrantActive` drops the row at every routing), and a
* delegate who is the delegator (rerouting a slot onto the same person moves
* nothing, so no substitute is recorded). Both were stored, and the delegator
* believed their approvals were covered while they were not.
*
* The refusals are the object's declared `validations`, so every engine write
* path judges them. An insert is judged by its own values, an update by the
* stored row overlaid with the patch; an update that moves neither compared
* column is not judged, so a row stored before the refusals existed keeps
* taking unrelated edits.
*
* Measured on a REAL `ObjectQL` engine over a real SQL driver, with the
* plugin's own delegation write guard bound: the guard stamps an omitted
* delegator in `beforeInsert`, before validation, so a self-delegation that
* leaves the delegator to the stamp is judged too. Refusals are read through
* their ADR-0112 envelope (`resolveThrownHttpError`, the resolver both HTTP
* doors answer with), never a bare `toThrow()`.
*/

import { describe, it, expect, afterEach } from 'vitest';
import { ObjectQL } from '@objectstack/objectql';
import { SqlDriver } from '@objectstack/driver-sql';
import { resolveThrownHttpError } from '@objectstack/types';
import type { EngineQueryOptions } from '@objectstack/spec/data';

import { SysApprovalDelegation } from './sys-approval-delegation.object.js';
import { bindDelegationWriteGuard } from './lifecycle-hooks.js';
import { installDefaultOrganization } from './default-organization.testkit.js';

const DELEGATIONS = 'sys_approval_delegation';
const SYS = { isSystem: true, positions: [], permissions: [] } as const;
const ALICE = { userId: 'u_alice', positions: [], permissions: [] } as const;

const T0 = '2026-11-01T00:00:00.000Z';
const T1 = '2026-12-01T00:00:00.000Z';
const T2 = '2027-01-01T00:00:00.000Z';

const sysUser = {
name: 'sys_user',
label: 'User',
fields: {
id: { name: 'id', label: 'Id', type: 'text' as const, primaryKey: true },
name: { name: 'name', label: 'Name', type: 'text' as const },
},
};

const engines: ObjectQL[] = [];
afterEach(async () => {
while (engines.length) {
try { await engines.pop()?.destroy(); } catch { /* noop */ }
}
});

async function boot() {
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
const engine = new ObjectQL();
engine.registerDriver(driver, true);
await engine.init();
for (const def of [sysUser, SysApprovalDelegation]) {
engine.registry.registerObject(def as any, 'approvals-test', 'approvals-test');
}
await engine.syncSchemas();
await installDefaultOrganization(engine as any);
for (const id of ['u_alice', 'u_bob']) await engine.insert('sys_user', { id, name: id }, { context: SYS } as any);
bindDelegationWriteGuard(engine as any);
engines.push(engine);
return { engine, driver };
}

type Harness = Awaited<ReturnType<typeof boot>>;

async function refusalOf(run: () => Promise<unknown>): Promise<unknown> {
try {
await run();
} catch (e) {
return e;
}
throw new Error('expected the write to be refused, but it succeeded');
}

const ruleMessage = (name: string) =>
(SysApprovalDelegation.validations as unknown as Array<{ name: string; message: string }>)
.find((r) => r.name === name)!.message;

/** The ADR-0112 envelope an HTTP door answers this throw with, and the field the rule named. */
function expectRefusal(err: unknown, field: string, rule: string): void {
const r = resolveThrownHttpError(err);
const fields = (r.details?.fields ?? []) as any[];
expect([r.status, r.code]).toEqual([400, 'VALIDATION_FAILED']);
expect(fields.map((f) => [f.field, f.code])).toEqual([[field, 'rule_violation']]);
expect(fields[0].constraint?.reason).not.toBe('unevaluable');
const message = ruleMessage(rule);
expect(String(fields[0].message).slice(0, message.length)).toBe(message);
}

const expectWindowRefusal = (err: unknown) => expectRefusal(err, 'valid_until', 'validity_window_order');
const expectSelfRefusal = (err: unknown) => expectRefusal(err, 'delegate_id', 'delegate_not_delegator');

async function rowsOf(h: Harness, id: string): Promise<any[]> {
const rows = await h.engine.find(DELEGATIONS, { where: { id }, context: SYS as any } satisfies EngineQueryOptions);
return Array.isArray(rows) ? rows : [];
}

const instant = (v: unknown) => (v == null ? v : new Date(v as string).toISOString());
const shapeOf = (row: any) => ({
delegator_id: row?.delegator_id,
delegate_id: row?.delegate_id,
valid_from: instant(row?.valid_from),
valid_until: instant(row?.valid_until),
});

describe('an insert that could never reroute an approval is refused', () => {
for (const [who, context] of [['the delegator', ALICE], ['a system writer', SYS]] as const) {
it(`NEGATIVE — ${who}: valid_until before valid_from is refused 400 on valid_until; nothing is stored`, async () => {
const h = await boot();
const err = await refusalOf(() => h.engine.insert(DELEGATIONS, {
id: 'd_inv', delegator_id: 'u_alice', delegate_id: 'u_bob', valid_from: T1, valid_until: T0,
}, { context } as any));
expectWindowRefusal(err);
expect(await rowsOf(h, 'd_inv')).toHaveLength(0);
});

it(`NEGATIVE — ${who}: the delegator as their own delegate is refused 400 on delegate_id; nothing is stored`, async () => {
const h = await boot();
const err = await refusalOf(() => h.engine.insert(DELEGATIONS, {
id: 'd_self', delegator_id: 'u_alice', delegate_id: 'u_alice', valid_from: T0, valid_until: T1,
}, { context } as any));
expectSelfRefusal(err);
expect(await rowsOf(h, 'd_self')).toHaveLength(0);
});
}

it('NEGATIVE — equal bounds are refused: a window from t until t is empty', async () => {
const h = await boot();
const err = await refusalOf(() => h.engine.insert(DELEGATIONS, {
id: 'd_eq', delegate_id: 'u_bob', valid_from: T1, valid_until: T1,
}, { context: ALICE } as any));
expectWindowRefusal(err);
expect(await rowsOf(h, 'd_eq')).toHaveLength(0);
});

it('NEGATIVE — a self-delegation that leaves the delegator to the write guard\'s stamp is refused', async () => {
const h = await boot();
const err = await refusalOf(() => h.engine.insert(DELEGATIONS, {
id: 'd_stamped', delegate_id: 'u_alice', valid_from: T0, valid_until: T1,
}, { context: ALICE } as any));
expectSelfRefusal(err);
expect(await rowsOf(h, 'd_stamped')).toHaveLength(0);
});

it('CONTROL — a valid window and a different delegate lands', async () => {
const h = await boot();
await h.engine.insert(DELEGATIONS, { id: 'd_ok', delegate_id: 'u_bob', valid_from: T0, valid_until: T1 }, { context: ALICE } as any);
expect(shapeOf((await rowsOf(h, 'd_ok'))[0])).toEqual({ delegator_id: 'u_alice', delegate_id: 'u_bob', valid_from: T0, valid_until: T1 });
});

it('CONTROL — an open-ended window lands: either bound alone, or none', async () => {
const h = await boot();
await h.engine.insert(DELEGATIONS, { id: 'd_from', delegate_id: 'u_bob', valid_from: T1 }, { context: ALICE } as any);
await h.engine.insert(DELEGATIONS, { id: 'd_until', delegate_id: 'u_bob', valid_until: T0 }, { context: ALICE } as any);
await h.engine.insert(DELEGATIONS, { id: 'd_none', delegate_id: 'u_bob' }, { context: ALICE } as any);
expect(shapeOf((await rowsOf(h, 'd_from'))[0])).toMatchObject({ valid_from: T1, valid_until: null });
expect(shapeOf((await rowsOf(h, 'd_until'))[0])).toMatchObject({ valid_from: null, valid_until: T0 });
expect(shapeOf((await rowsOf(h, 'd_none'))[0])).toMatchObject({ valid_from: null, valid_until: null });
});
});

describe('an update is judged by the stored row overlaid with the patch', () => {
async function stored(h: Harness, id: string) {
await h.engine.insert(DELEGATIONS, { id, delegate_id: 'u_bob', valid_from: T1, valid_until: T2 }, { context: ALICE } as any);
}
const STORED = { delegator_id: 'u_alice', delegate_id: 'u_bob', valid_from: T1, valid_until: T2 };

it('NEGATIVE — moving valid_until to before the stored valid_from is refused; the row is unchanged', async () => {
const h = await boot();
await stored(h, 'd_move_until');
expectWindowRefusal(await refusalOf(() => h.engine.update(DELEGATIONS, { id: 'd_move_until', valid_until: T0 }, { context: ALICE } as any)));
expect(shapeOf((await rowsOf(h, 'd_move_until'))[0])).toEqual(STORED);
});

it('NEGATIVE — changing the delegate to the delegator is refused; the row is unchanged', async () => {
const h = await boot();
await stored(h, 'd_move_delegate');
expectSelfRefusal(await refusalOf(() => h.engine.update(DELEGATIONS, { id: 'd_move_delegate', delegate_id: 'u_alice' }, { context: ALICE } as any)));
expect(shapeOf((await rowsOf(h, 'd_move_delegate'))[0])).toEqual(STORED);
});

it('CONTROL — moving a bound within a valid window lands', async () => {
const h = await boot();
await stored(h, 'd_extend');
await h.engine.update(DELEGATIONS, { id: 'd_extend', valid_from: T0 }, { context: ALICE } as any);
expect(shapeOf((await rowsOf(h, 'd_extend'))[0])).toEqual({ ...STORED, valid_from: T0 });
});

it('a row stored inert before the refusals existed takes an unrelated edit; repairing it lands', async () => {
const h = await boot();
// Stored beneath the engine, the way a row written before the refusals
// existed sits in a deployed table.
await h.driver.create(DELEGATIONS, {
id: 'd_legacy', delegator_id: 'u_alice', delegate_id: 'u_alice', valid_from: T2, valid_until: T1,
organization_id: 'org_default',
});
await h.engine.update(DELEGATIONS, { id: 'd_legacy', reason: 'unrelated edit' }, { context: ALICE } as any);
expect((await rowsOf(h, 'd_legacy'))[0]).toMatchObject({ reason: 'unrelated edit' });

await h.engine.update(DELEGATIONS, { id: 'd_legacy', delegate_id: 'u_bob', valid_until: T2.replace('2027', '2028') }, { context: ALICE } as any);
expect(shapeOf((await rowsOf(h, 'd_legacy'))[0])).toEqual({
delegator_id: 'u_alice', delegate_id: 'u_bob', valid_from: T2, valid_until: '2028-01-01T00:00:00.000Z',
});
});
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

import { ObjectSchema, Field } from '@objectstack/spec/data';
import { F } from '@objectstack/spec';
import { F, P } from '@objectstack/spec';

/**
* sys_approval_delegation — self-service out-of-office (OOO) delegation (#1322 M1).
Expand Down Expand Up @@ -170,6 +170,61 @@ export const SysApprovalDelegation = ObjectSchema.create({
}),
},

// Two shapes the resolver can store but never applies: a window that ends at
// or before it starts (`isGrantActive` drops it at every routing), and a
// delegate who is the delegator (rerouting a slot onto the same person moves
// nothing). Both used to land 201 and then do nothing, so the delegator
// believed their approvals were covered. Refused at the write instead.
//
// Declared, not a hook: the engine evaluates an object's validation rules on
// every write path — insert (single and batch) and update (by id, and per
// matched row of a multi-row update), for system and non-system writers
// alike — against the stored row overlaid with the patch, AFTER the
// `beforeInsert` hooks, so a delegator the write guard stamps
// (`bindDelegationWriteGuard`) is judged too.
//
// ⛔ A declared rule is an INVARIANT by default: it would refuse ANY edit to a
// row that already violates. The `previous` clause narrows each rule to the
// writes that make the shape — an insert (`previous` is null there), or an
// update that moves one of the two columns it compares. A row stored before
// these rules existed stays inert and keeps taking unrelated edits; the write
// that repairs it is the only one that has to state a valid value.
//
// `datetime()` compares instants, not spellings. `cross_field` so each
// violation attaches to the first field it lists, where a form shows it.
// Same rule shape as `sys_user_permission_set.validity_window_order`.
validations: [
{
type: 'cross_field',
name: 'validity_window_order',
label: 'Delegation window ends after it starts',
// [ADR-0091 D1/D2] The validity window `isGrantActive` judges.
description:
'A delegation applies from valid_from up to, but not including, valid_until, so a window that '
+ 'ends at or before it starts never reroutes an approval. Judged on insert, and on an update that moves a bound.',
fields: ['valid_until', 'valid_from'],
condition: P`(previous == null || record.valid_from != previous.valid_from || record.valid_until != previous.valid_until) && record.valid_from != null && record.valid_until != null && datetime(record.valid_until) <= datetime(record.valid_from)`,
severity: 'error',
message:
'Valid Until must be later than Valid From. The delegation applies from Valid From up to, but not including, '
+ 'Valid Until, so a window that ends at or before it starts never reroutes an approval. Leave either one empty for an open-ended window.',
},
{
type: 'cross_field',
name: 'delegate_not_delegator',
label: 'Delegate is someone other than the delegator',
description:
'A delegation hands the delegator\'s approvals to another user, so a delegate who is the delegator '
+ 'never reroutes an approval. Judged on insert, and on an update that changes either user.',
fields: ['delegate_id', 'delegator_id'],
condition: P`(previous == null || record.delegate_id != previous.delegate_id || record.delegator_id != previous.delegator_id) && record.delegate_id != null && record.delegate_id == record.delegator_id`,
severity: 'error',
message:
'Delegate must be someone other than the Delegator. A delegation hands your approvals to another user while '
+ 'you are away, so naming yourself as the delegate never reroutes an approval.',
},
],

indexes: [
// Resolution-time lookup: "active delegations for this delegator".
{ fields: ['delegator_id', 'organization_id'] },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,14 @@ export const arObjects: NonNullable<TranslationData['objects']> = {
message: "أعلِن تفويضًا للغياب كي تُوجَّه الموافقات إلى بديل أثناء غيابك."
}
}
},
_validations: {
validity_window_order: {
message: "Valid Until must be later than Valid From. The delegation applies from Valid From up to, but not including, Valid Until, so a window that ends at or before it starts never reroutes an approval. Leave either one empty for an open-ended window."
},
delegate_not_delegator: {
message: "Delegate must be someone other than the Delegator. A delegation hands your approvals to another user while you are away, so naming yourself as the delegate never reroutes an approval."
}
}
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
*/

export const arGeneratedSourceHashes: Readonly<Record<string, string>> = {
"objects.sys_approval_delegation._validations.delegate_not_delegator.message": "e4924bc4008bd3b5",
"objects.sys_approval_delegation._validations.validity_window_order.message": "e6a6433d70cb122d",
"objects.sys_approval_request.fields.process_package.help": "2c4cfa5880a99e24",
"objects.sys_approval_request.fields.process_package.label": "e2102a7a50e2a26d",
};
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,14 @@ export const deObjects: NonNullable<TranslationData['objects']> = {
message: "Legen Sie eine Abwesenheitsvertretung an, damit Genehmigungen während Ihrer Abwesenheit an eine Vertretung gehen."
}
}
},
_validations: {
validity_window_order: {
message: "Valid Until must be later than Valid From. The delegation applies from Valid From up to, but not including, Valid Until, so a window that ends at or before it starts never reroutes an approval. Leave either one empty for an open-ended window."
},
delegate_not_delegator: {
message: "Delegate must be someone other than the Delegator. A delegation hands your approvals to another user while you are away, so naming yourself as the delegate never reroutes an approval."
}
}
}
};
Loading
Loading