Skip to content

Commit 9f76546

Browse files
committed
test(runtime): a hook, action or job body passing permanent on a delete is refused and removes nothing; false or absent deletes into the bin
Changeset: @objectstack/runtime minor, and one sentence that hooks and app bodies cannot pass permanent. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibxhbtrhtRZ958iyyJp
1 parent d8e9534 commit 9f76546

2 files changed

Lines changed: 165 additions & 1 deletion

File tree

‎.changeset/30237-recycle-bin-purge-empty-permanent.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
---
22
'@objectstack/objectql': minor
33
'@objectstack/spec': minor
4+
'@objectstack/runtime': minor
45
---
56

67
feat(objectql,spec): purge and empty the recycle bin, and delete a record for good (ADR-0148): `ObjectQL.purge(entryId)`, `ObjectQL.empty(object)` and `delete(object, { where: { id }, permanent: true })`, all authorized as the `purge` operation
@@ -12,6 +13,7 @@ Skills-docs: follow-up #30847 — `skills/objectstack-api/SKILL.md` :268, :417 t
1213
The recycle bin's removal side. All three acts are dispatched through the middleware chain as one new operation, `purge`, on the business object the rows belong to, so one grant will govern all three: `manageRecycleBin`, the recycle-bin manager's (ADR-0148 D5). **Until `@objectstack/plugin-security` maps `purge` to that grant, it refuses `purge` for every caller that is not the system**, the fail-closed rule it already applies to the destructive verbs. So in this release only the system, or a composition without the security plugin, can purge, empty or delete for good. Restoring, the two grants and the REST doors are not in this release.
1314

1415
- **`@objectstack/spec`:** `EngineDeleteOptions` gains `permanent?: boolean`: delete for good, so the rows skip the recycle bin and cannot be restored. It is authorized as the `purge` operation, not `delete`, and is honoured on a by-id delete only.
16+
- **Hooks and app bodies cannot pass `permanent`:** app-authored code cannot erase a record past the recycle bin; its deletes always enter the bin, and the permanent delete stays with a principal holding `manageRecycleBin`. `HookDeleteOptions` (the bag `ctx.api.object(n).delete()` takes) omits `permanent`, and `@objectstack/runtime`'s sandbox refuses a hook, action or job body's `delete` carrying `permanent` (any value but `false`) with `400 VALIDATION_ERROR` (`param: 'permanent'`) before anything is removed, whatever envelope the body runs under, a job's system envelope included. `permanent: false` and an absent key are the ordinary delete.
1517
- **`@objectstack/objectql`, the permanent delete:** `delete(object, { where: { id }, permanent: true })` runs as the by-id delete does (its `beforeDelete` / `afterDelete` hooks, which read `permanent` off `input.options`, its cascade, its events), writes no recycle-bin entry, and is dispatched as `purge` with the row's id. These are refused `400 VALIDATION_ERROR` (`param: 'permanent'`) before any middleware or hook runs:
1618
- `permanent: true` on a delete that is not by id, or that asks `multi: true`;
1719
- `permanent: true` on a platform object (`sys_*`, `cloud_*`, `ai_*`), whose delete never enters the bin and is already permanent;

‎packages/runtime/src/sandbox/body-runner.test.ts‎

Lines changed: 163 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

33
import { describe, it, expect } from 'vitest';
4-
import { hookBodyRunnerFactory, actionBodyRunnerFactory } from './body-runner.js';
4+
import { ObjectQL, ScopedContext } from '@objectstack/objectql';
5+
import { RECYCLE_BIN_ENTRY_FIELDS } from '@objectstack/spec/data';
6+
import { hookBodyRunnerFactory, actionBodyRunnerFactory, jobBodyRunnerFactory } from './body-runner.js';
57
import { QuickJSScriptRunner } from './quickjs-runner.js';
68

79
describe('hookBodyRunnerFactory', () => {
@@ -576,3 +578,163 @@ describe('actionBodyRunnerFactory', () => {
576578
});
577579
});
578580
});
581+
582+
// [ADR-0148 D3, maintainer ruling A recorded in 6691358077] App-authored code
583+
// cannot purge: a body's delete always enters the recycle bin. A job body runs
584+
// under a fresh `{ isSystem: true, tenantId }` envelope, and the system is never
585+
// refused the engine's `purge` verb, so the rule is held by the body's API.
586+
// Real `ObjectQL` over a row-keeping driver: "nothing removed, no entry skipped"
587+
// is a reading of the rows, not of a stub's call log.
588+
describe('a body cannot delete permanently: its deletes enter the recycle bin', () => {
589+
type Row = Record<string, unknown>;
590+
const runner = new QuickJSScriptRunner({ hookTimeoutMs: 10_000 });
591+
const WRITE_CAPS = ['api.read', 'api.write'];
592+
593+
function makeDriver() {
594+
const stores = new Map<string, Map<string, Row>>();
595+
const storeFor = (o: string) => {
596+
let st = stores.get(o);
597+
if (!st) { st = new Map(); stores.set(o, st); }
598+
return st;
599+
};
600+
const matches = (row: Row, where: any) =>
601+
!where || Object.entries(where).every(([k, v]) => k.startsWith('$') || (row[k] ?? null) === (v ?? null));
602+
const driver: any = {
603+
name: 'primary', version: '0.0.0', supports: {},
604+
rowsOf: (o: string) => Array.from(storeFor(o).values()),
605+
seed(o: string, row: Row) { storeFor(o).set(String(row.id), { ...row }); },
606+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
607+
async syncSchema() {},
608+
async find(o: string, ast: any) {
609+
const rows = Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where));
610+
const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
611+
return page.map((r) => ({ ...r }));
612+
},
613+
async findOne(o: string, ast: any) {
614+
for (const r of storeFor(o).values()) if (matches(r, ast?.where)) return { ...r };
615+
return null;
616+
},
617+
async create(o: string, data: Row) {
618+
const id = (data.id as string) ?? `r_${storeFor(o).size + 1}`;
619+
const row = JSON.parse(JSON.stringify({ ...data, id }));
620+
storeFor(o).set(id, row);
621+
return { ...row };
622+
},
623+
async update(o: string, id: string, data: Row) {
624+
const up = { ...storeFor(o).get(String(id)), ...data, id };
625+
storeFor(o).set(String(id), up);
626+
return { ...up };
627+
},
628+
async delete(o: string, id: string) { return storeFor(o).delete(String(id)); },
629+
async count(o: string, ast: any) { return (await driver.find(o, ast)).length; },
630+
};
631+
return driver;
632+
}
633+
634+
async function makeEngine() {
635+
const engine = new ObjectQL();
636+
const driver = makeDriver();
637+
engine.registerDriver(driver, true);
638+
await engine.init();
639+
engine.registry.registerObject({
640+
name: 'sys_recycle_bin', label: 'Recycle Bin Entry', managedBy: 'engine-owned', fields: { ...RECYCLE_BIN_ENTRY_FIELDS },
641+
} as any, '__test__');
642+
engine.registry.registerObject({
643+
name: 'pdb_ticket', label: 'Ticket', fields: { id: { name: 'id', type: 'text' }, name: { name: 'name', type: 'text' } },
644+
} as any, '__test__');
645+
const deletes: Array<{ id: unknown; operation: string }> = [];
646+
engine.registerMiddleware(async (opCtx: any, next: () => Promise<void>) => {
647+
if (opCtx.object === 'pdb_ticket' && (opCtx.operation === 'delete' || opCtx.operation === 'purge')) {
648+
deletes.push({ id: opCtx.options?.where?.id, operation: opCtx.operation });
649+
}
650+
await next();
651+
});
652+
// One entry already in the bin, so "no entry lost" is a reading of a non-empty bin.
653+
driver.seed('pdb_ticket', { id: 't0', name: 'old' });
654+
await engine.delete('pdb_ticket', { where: { id: 't0' }, context: { isSystem: true } });
655+
driver.seed('pdb_ticket', { id: 't1', name: 'live' });
656+
deletes.length = 0;
657+
const entries = () => driver.rowsOf('sys_recycle_bin').map((e: Row) => e.record_id).sort();
658+
return { engine, driver, deletes, entries };
659+
}
660+
661+
const jobRunning = (engine: unknown, source: string) =>
662+
jobBodyRunnerFactory(runner, { ql: engine, appId: 'pdb' })({
663+
name: 'nightly_purge',
664+
body: { language: 'js', capabilities: WRITE_CAPS, source },
665+
})!;
666+
667+
it('a job body (system envelope) passing `permanent: true` is refused 400 VALIDATION_ERROR naming the rule; nothing is removed', async () => {
668+
const { engine, driver, deletes, entries } = await makeEngine();
669+
expect(entries()).toEqual(['t0']);
670+
const outcome = await jobRunning(engine, `
671+
try {
672+
await ctx.api.object('pdb_ticket').delete({ where: { id: 't1' }, permanent: true });
673+
return { outcome: 'completed', reason: 'purged' };
674+
} catch (e) {
675+
return { outcome: 'degraded', reason: e.code + ' ' + e.status + ' ' + e.message };
676+
}`)({} as any);
677+
expect(outcome?.outcome).toBe('degraded');
678+
expect(outcome?.reason).toMatch(/^VALIDATION_ERROR 400 /);
679+
expect(outcome?.reason).toContain('app-authored code cannot purge; its deletes enter the recycle bin');
680+
expect(deletes).toEqual([]);
681+
expect(driver.rowsOf('pdb_ticket').map((r: Row) => r.id)).toEqual(['t1']);
682+
expect(entries()).toEqual(['t0']);
683+
});
684+
685+
it('uncaught, the refusal fails the job run with the envelope on the host side (`param: permanent` stays host-side)', async () => {
686+
const { engine, driver, entries } = await makeEngine();
687+
await expect(jobRunning(engine, `
688+
await ctx.api.object('pdb_ticket').delete({ where: { id: 't1' }, permanent: true });
689+
return { outcome: 'completed' };`)({} as any)).rejects.toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
690+
expect(driver.rowsOf('pdb_ticket').map((r: Row) => r.id)).toEqual(['t1']);
691+
expect(entries()).toEqual(['t0']);
692+
});
693+
694+
it('a hook body and an action body are refused the same way', async () => {
695+
const { engine, driver, deletes, entries } = await makeEngine();
696+
const source = `
697+
try { await ctx.api.object('pdb_ticket').delete({ where: { id: 't1' }, permanent: true }); return { got: 'purged' }; }
698+
catch (e) { return { got: e.code + ' ' + e.status }; }`;
699+
const hook = hookBodyRunnerFactory(runner, { ql: engine, appId: 'pdb' })({
700+
name: 'purge_on_close', object: 'pdb_case', events: ['beforeUpdate'],
701+
body: { language: 'js', capabilities: WRITE_CAPS, source },
702+
} as any)!;
703+
const engineCtx: any = { object: 'pdb_case', event: 'beforeUpdate', input: {}, api: new ScopedContext({ isSystem: true } as any, engine as any) };
704+
await hook(engineCtx);
705+
expect(engineCtx.input.got).toBe('VALIDATION_ERROR 400');
706+
const action = actionBodyRunnerFactory(runner, { ql: engine, appId: 'pdb' })({
707+
name: 'purge_ticket', object: 'pdb_ticket', type: 'script',
708+
body: { language: 'js', capabilities: WRITE_CAPS, source },
709+
})!;
710+
const value = await action({ params: {}, record: {}, executionContext: { isSystem: true } });
711+
expect(value).toEqual({ got: 'VALIDATION_ERROR 400' });
712+
expect(deletes).toEqual([]);
713+
expect(driver.rowsOf('pdb_ticket').map((r: Row) => r.id)).toEqual(['t1']);
714+
expect(entries()).toEqual(['t0']);
715+
});
716+
717+
for (const [label, opts] of [
718+
['`permanent: false`', `{ where: { id: 't1' }, permanent: false }`],
719+
['no `permanent` key', `{ where: { id: 't1' } }`],
720+
] as const) {
721+
it(`a job body's delete with ${label} is the ordinary delete: the record enters the bin`, async () => {
722+
const { engine, driver, deletes, entries } = await makeEngine();
723+
const outcome = await jobRunning(engine, `
724+
await ctx.api.object('pdb_ticket').delete(${opts});
725+
return { outcome: 'completed' };`)({} as any);
726+
expect(outcome).toEqual({ outcome: 'completed' });
727+
expect(deletes).toEqual([{ id: 't1', operation: 'delete' }]);
728+
expect(driver.rowsOf('pdb_ticket')).toEqual([]);
729+
expect(entries()).toEqual(['t0', 't1']);
730+
});
731+
}
732+
733+
it('host code keeps the engine\'s permanent delete (Q3 = A): only app-authored bodies are refused', async () => {
734+
const { engine, driver, deletes, entries } = await makeEngine();
735+
await engine.delete('pdb_ticket', { where: { id: 't1' }, permanent: true, context: { isSystem: true } });
736+
expect(deletes).toEqual([{ id: 't1', operation: 'purge' }]);
737+
expect(driver.rowsOf('pdb_ticket')).toEqual([]);
738+
expect(entries()).toEqual(['t0']);
739+
});
740+
});

0 commit comments

Comments
 (0)