Skip to content

Commit 0c7f2ad

Browse files
committed
fix(objectql,runtime): an app-authored hook handler's permanent delete is refused
The in-process handler of a hook bound through the hook binder is app-authored code (APP_AUTHORED_HOOK_API). Its ctx.api, and every api derived from it, now refuses delete(..., { permanent }) with the same 400 VALIDATION_ERROR and sentence a sandboxed body's api gives, under the caller and under runAs: 'system' (ADR-0148 D3, ruling A). The refusal moves to objectql (refuseAppAuthoredPermanentDelete) and the runtime's sandbox reuses it, so both faces share one code and sentence. It judges a shallow copy of the options and forwards that copy. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibvynRbCtMndW8EHNGc
1 parent 022b4e7 commit 0c7f2ad

7 files changed

Lines changed: 255 additions & 61 deletions

File tree

‎packages/objectql/src/engine-scoped-context.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import { driverSupportsTransactions } from '@objectstack/spec/data';
3434
import type { IScopedContext } from '@objectstack/spec/contracts';
3535
import { appAutomationElevationOf, markAppAutomationElevation } from '@objectstack/core';
3636
import { UnscopedHookApi } from './hook-run-as.js';
37+
import { refuseAppAuthoredPermanentDelete } from './recycle-bin/app-authored-delete.js';
3738
import type { HookRunAs, HookRunAsRef } from './hook-run-as.js';
3839
import { ObjectRepository } from './engine.js';
3940
import type { ObjectQL, ScopedContext } from './engine.js';
@@ -58,8 +59,13 @@ export interface ScopedContextHost {
5859
/** The bodies of `ScopedContext`'s methods: a stateless facet, called by the class's stubs. */
5960
export class ScopedContextFacet {
6061
/** The body of `ScopedContext#object`; the method's docblock there is its contract. */
61-
static object(this: Pick<ScopedContextHost, 'engine' | 'executionContext'>, name: string): ObjectRepository {
62-
return new ObjectRepository(name, this.executionContext, this.engine as any);
62+
static object(this: Pick<ScopedContextHost, 'appAuthored' | 'engine' | 'executionContext'>, name: string): ObjectRepository {
63+
const repo = new ObjectRepository(name, this.executionContext, this.engine as any);
64+
// [ADR-0148 D3, ruling A recorded in 6691358077] An app-authored hook's
65+
// api (and every api derived from it) refuses a permanent delete: the same
66+
// refusal a sandboxed body's api applies, here for the hook's in-process
67+
// `handler`, whatever its `runAs`.
68+
return this.appAuthored ? refuseAppAuthoredPermanentDelete(name, repo, 'hook handler') : repo;
6369
}
6470

6571
/** The body of `ScopedContext#sudo`; the method's docblock there is its contract. */

‎packages/objectql/src/engine.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10617,7 +10617,7 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi {
1061710617
/**
1061810618
* [#25653] Set on the api an app-authored hook is handed
1061910619
* ({@link APP_AUTHORED_HOOK_API}) and kept by every api derived from it
10620-
* ({@link derive}); read by {@link sudo}.
10620+
* ({@link derive}); read by {@link sudo} and {@link object}.
1062110621
*/
1062210622
private appAuthored = false;
1062310623

@@ -10628,7 +10628,16 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi {
1062810628
return child;
1062910629
}
1063010630

10631-
/** Get a repository scoped to this context */
10631+
/**
10632+
* Get a repository scoped to this context.
10633+
*
10634+
* [ADR-0148 D3, ruling A recorded in 6691358077] On an app-authored hook's
10635+
* api ({@link APP_AUTHORED_HOOK_API}) and every api derived from it, the
10636+
* repository's `delete(…, { permanent })` is refused (`400
10637+
* VALIDATION_ERROR`, `param: 'permanent'`): app-authored code cannot purge,
10638+
* so its deletes enter the recycle bin, under any `runAs`. Platform code's
10639+
* api is not app-authored, and keeps the engine's permanent delete.
10640+
*/
1063210641
object(name: string): ObjectRepository {
1063310642
// [#30052 codemod] The body moved to `engine-scoped-context.ts` (see `ScopedContextHost`).
1063410643
return ScopedContextFacet.object.call(scopedContextHost.of(this), name);

‎packages/objectql/src/hook-run-as.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,12 @@ export async function seedHookUserGrants(api: unknown): Promise<unknown> {
264264
* - its `sudo()`, on it and on every api derived from it (`transaction`,
265265
* `withRunAs`), marks the elevation it makes.
266266
*
267+
* [ADR-0148 D3, ruling A recorded in 6691358077] And every repository it and
268+
* the apis derived from it serve refuses a permanent delete
269+
* (`refuseAppAuthoredPermanentDelete`, `recycle-bin/app-authored-delete.ts`):
270+
* a hook's in-process `handler` is app-authored code, so its deletes enter the
271+
* recycle bin, under the caller and under `runAs: 'system'` alike.
272+
*
267273
* A symbol, and ⛔ not re-exported from the package entry, for the reason
268274
* {@link SEED_USER_GRANTS} gives.
269275
*/

‎packages/objectql/src/index.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,10 @@ export { parseLifecycleDuration } from './lifecycle/duration.js';
633633
// [#30237, ADR-0148 D3] What a host hands `ObjectQLPlugin`'s `recycleBinRetention`.
634634
export type { RecycleBinRetentionSettings } from './recycle-bin/retention.js';
635635
export type { RecycleBinRemovalOptions } from './recycle-bin/purge.js';
636+
// [ADR-0148 D3, ruling A recorded in 6691358077] The one refusal of an
637+
// app-authored permanent delete: the engine applies it to an app-authored
638+
// hook's api, and the runtime's sandbox to every body's.
639+
export { refuseAppAuthoredPermanentDelete } from './recycle-bin/app-authored-delete.js';
636640
export { lifecycleSettingsManifest } from './lifecycle/lifecycle-settings.js';
637641

638642
// [#4551] Read-only referential-integrity audit — the reporting half of the
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0148 D3, ruling A recorded in 6691358077] App-authored code cannot
5+
* delete a record permanently: its deletes always enter the recycle bin, and
6+
* the permanent delete stays with a principal that holds `manageRecycleBin`.
7+
*
8+
* This module is the ONE refusal, held where every face that hands app code a
9+
* scoped API can reach it:
10+
*
11+
* - a sandboxed body (hook, action, job): `@objectstack/runtime`'s
12+
* `buildSandboxApi` wraps every repository the body's API serves;
13+
* - an app-authored hook's in-process `handler` (a hook bound through the
14+
* hook binder, `APP_AUTHORED_HOOK_API` in `hook-run-as.ts`): the engine's
15+
* own `ScopedContext.object()` wraps every repository of an app-authored
16+
* api, and of every api derived from it (`sudo()`, `withRunAs(...)`, a
17+
* transaction's context), so it holds under the caller and under
18+
* `runAs: 'system'` alike.
19+
*
20+
* The engine's `delete(…, { permanent: true })` is unchanged for every other
21+
* caller (Q3 = A): platform code, a hook registered in code with
22+
* `engine.registerHook`, and `engine.createContext(...)`.
23+
*/
24+
25+
/**
26+
* The refusal of an app-authored `delete(…, { permanent })`: `400
27+
* VALIDATION_ERROR`, `param: 'permanent'`. The message names the rule, because
28+
* code that asked for a purge has to learn it got none: dropping the key would
29+
* delete into the bin and answer success, which reads as the purge it asked for.
30+
*
31+
* `face` names what asked (`'hook body'`, `'job body'`, `'hook handler'`, …).
32+
*/
33+
function appAuthoredPermanentDeleteRefusal(objectName: string, face: string): Error {
34+
const err: any = new Error(
35+
`A ${face} cannot delete a record permanently: app-authored code cannot purge; ` +
36+
`its deletes enter the recycle bin. Remove 'permanent' from the delete of '${objectName}'.`,
37+
);
38+
err.developerMessage =
39+
`'permanent' was passed to ctx.api.object('${objectName}').delete() in a ${face}. App-authored code ` +
40+
`(hook, action and job bodies, and the in-process handler of a hook bound from metadata) cannot erase a ` +
41+
`record past the recycle bin, under any execution context, a job's system envelope and a hook's ` +
42+
`runAs: 'system' included; the permanent delete stays with a principal holding manageRecycleBin ` +
43+
`(ADR-0148 D3).`;
44+
err.code = 'VALIDATION_ERROR';
45+
err.status = 400;
46+
err.httpStatus = 400;
47+
err.param = 'permanent';
48+
err.object = objectName;
49+
return err;
50+
}
51+
52+
/**
53+
* One repository as app-authored code holds it: `delete(options)` whose
54+
* `options` carry a `permanent` key with any value but `false` is refused
55+
* before the underlying verb is called, so nothing is removed and no bin entry
56+
* is skipped. `false` and an absent key are the ordinary delete, and go
57+
* through. Every other member is handed through.
58+
*
59+
* The options are read ONCE, into a shallow copy, and that copy is what the
60+
* verb receives: the key judged is the key forwarded. An in-process caller can
61+
* hand an object whose `permanent` answers differently on a second read (a
62+
* getter, a Proxy) or is inherited rather than own; judging one read and
63+
* forwarding the original would let the verb see another value than the one
64+
* judged. A sandboxed body's options arrive as plain JSON, for which the copy
65+
* is the same value.
66+
*/
67+
export function refuseAppAuthoredPermanentDelete<T>(objectName: string, repo: T, face: string): T {
68+
if (repo === null || typeof repo !== 'object') return repo;
69+
return new Proxy(repo as unknown as Record<PropertyKey, unknown>, {
70+
get(target, prop) {
71+
const value = Reflect.get(target, prop, target);
72+
if (typeof value !== 'function') return value;
73+
if (prop !== 'delete') return value.bind(target);
74+
return async (...args: unknown[]) => {
75+
const [options, ...rest] = args;
76+
if (options === null || (typeof options !== 'object' && typeof options !== 'function')) {
77+
return value.apply(target, args);
78+
}
79+
const judged: Record<string, unknown> = { ...(options as Record<string, unknown>) };
80+
if (judged.permanent !== undefined && judged.permanent !== false) {
81+
throw appAuthoredPermanentDeleteRefusal(objectName, face);
82+
}
83+
return value.apply(target, [judged, ...rest]);
84+
};
85+
},
86+
}) as unknown as T;
87+
}

‎packages/objectql/src/recycle-bin/purge.test.ts‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import { describe, it, expect } from 'vitest';
1616
import { RECYCLE_BIN_ENTRY_FIELDS } from '@objectstack/spec/data';
1717
import { ObjectQL } from '../engine.js';
18+
import { bindHooksToEngine } from '../hook-binder.js';
1819

1920
type Row = Record<string, unknown>;
2021

@@ -412,3 +413,130 @@ describe('empty(object)', () => {
412413
expect(dispatches).toEqual([]);
413414
});
414415
});
416+
417+
/**
418+
* [ADR-0148 D3, ruling A recorded in 6691358077] A hook bound from metadata
419+
* (through the hook binder) is app-authored code, and so is its in-process
420+
* `handler`: its `ctx.api` refuses a permanent delete as a sandboxed body's
421+
* does, with the same code and sentence, under the caller and under
422+
* `runAs: 'system'`, by id and in bulk, on every api derived from it. Its
423+
* ordinary delete still enters the bin; platform code keeps the permanent
424+
* delete.
425+
*/
426+
describe("an app-authored hook handler's permanent delete (ruling A)", () => {
427+
const RULE_SENTENCE =
428+
'A hook handler cannot delete a record permanently: app-authored code cannot purge; its deletes enter the recycle bin.';
429+
430+
/**
431+
* Bind one hook through the binder, on `account`'s `beforeInsert`, whose
432+
* handler runs `use(ctx.api)` and keeps what it answered or threw; then fire
433+
* it once with an insert by `ORG1_USER`.
434+
*/
435+
async function runHandler(
436+
engine: ObjectQL,
437+
runAs: 'inherit' | 'user' | 'system',
438+
use: (api: any) => Promise<unknown>,
439+
): Promise<{ value?: unknown; error?: any }> {
440+
const seen: { value?: unknown; error?: any } = {};
441+
const bound = bindHooksToEngine(engine, [{
442+
name: 'purge_on_create',
443+
object: 'account',
444+
events: ['beforeInsert'],
445+
runAs,
446+
handler: async (ctx: any) => {
447+
try { seen.value = await use(ctx.api); } catch (e) { seen.error = e; }
448+
},
449+
} as any], { packageId: 'app_under_test' });
450+
expect(bound).toMatchObject({ registered: 1, errors: [] });
451+
await engine.insert('account', { id: 'acc_trigger', name: 'Trigger', organization_id: 'org_1' }, ORG1_USER);
452+
return seen;
453+
}
454+
455+
const lonerDispatches = (dispatches: Dispatch[]) => dispatches.filter((d) => d.object === 'loner');
456+
457+
for (const runAs of ['inherit', 'user', 'system'] as const) {
458+
for (const [shape, options] of [
459+
['by id', { where: { id: 'l1' }, permanent: true }],
460+
['in bulk', { where: { name: 'one' }, multi: true, permanent: true }],
461+
] as const) {
462+
it(`runAs '${runAs}': \`delete(…, { permanent: true })\` ${shape} is refused 400 naming the rule; nothing is removed`, async () => {
463+
const { engine, driver, dispatches } = await makeEngine();
464+
driver.seed('loner', { id: 'l1', name: 'one' });
465+
466+
const { error } = await runHandler(engine, runAs, (api) => api.object('loner').delete(options));
467+
468+
expect(error).toMatchObject({ code: 'VALIDATION_ERROR', status: 400, param: 'permanent', object: 'loner' });
469+
expect(String(error?.message).startsWith(RULE_SENTENCE)).toBe(true);
470+
expect(lonerDispatches(dispatches)).toEqual([]);
471+
expect(driver.rowsOf('loner').map((r: Row) => r.id)).toEqual(['l1']);
472+
expect(entriesOf(driver)).toHaveLength(0);
473+
});
474+
}
475+
}
476+
477+
for (const [derivation, use] of [
478+
['`sudo()`', (api: any) => api.sudo().object('loner').delete({ where: { id: 'l1' }, permanent: true })],
479+
['`transaction(cb)`', (api: any) => api.transaction((trx: any) => trx.object('loner').delete({ where: { id: 'l1' }, permanent: true }))],
480+
] as const) {
481+
it(`is refused the same way on the api ${derivation} derives`, async () => {
482+
const { engine, driver, dispatches } = await makeEngine();
483+
driver.seed('loner', { id: 'l1', name: 'one' });
484+
485+
const { error } = await runHandler(engine, 'inherit', use);
486+
487+
expect(error).toMatchObject({ code: 'VALIDATION_ERROR', status: 400, param: 'permanent', object: 'loner' });
488+
expect(String(error?.message).startsWith(RULE_SENTENCE)).toBe(true);
489+
expect(lonerDispatches(dispatches)).toEqual([]);
490+
expect(driver.rowsOf('loner').map((r: Row) => r.id)).toEqual(['l1']);
491+
});
492+
}
493+
494+
it('judges the options it forwards: a `permanent` that answers differently on a second read is read once', async () => {
495+
const { engine, driver, dispatches } = await makeEngine();
496+
driver.seed('loner', { id: 'l1', name: 'one' });
497+
let reads = 0;
498+
const options = { where: { id: 'l1' }, get permanent() { reads += 1; return reads > 1; } };
499+
500+
const { error } = await runHandler(engine, 'system', (api) => api.object('loner').delete(options));
501+
502+
expect(error).toBeUndefined();
503+
expect(reads).toBe(1);
504+
expect(lonerDispatches(dispatches).map((d) => d.operation)).toEqual(['delete']);
505+
expect(entriesOf(driver).map((e) => e.record_id)).toEqual(['l1']);
506+
});
507+
508+
for (const runAs of ['inherit', 'system'] as const) {
509+
for (const [label, options] of [
510+
['no `permanent` key', { where: { id: 'l1' } }],
511+
['`permanent: false`', { where: { id: 'l1' }, permanent: false }],
512+
] as const) {
513+
it(`runAs '${runAs}': the handler's delete with ${label} is the ordinary delete, which enters the bin`, async () => {
514+
const { engine, driver, dispatches } = await makeEngine();
515+
driver.seed('loner', { id: 'l1', name: 'one' });
516+
517+
const { error } = await runHandler(engine, runAs, (api) => api.object('loner').delete(options));
518+
519+
expect(error).toBeUndefined();
520+
expect(lonerDispatches(dispatches).map((d) => d.operation)).toEqual(['delete']);
521+
expect(driver.rowsOf('loner')).toEqual([]);
522+
expect(entriesOf(driver).map((e) => e.record_id)).toEqual(['l1']);
523+
});
524+
}
525+
}
526+
527+
it("platform code keeps the permanent delete: a hook registered in code, and the engine's own context", async () => {
528+
const { engine, driver, dispatches } = await makeEngine();
529+
driver.seed('loner', { id: 'l1', name: 'one' });
530+
driver.seed('loner', { id: 'l2', name: 'two' });
531+
engine.registerHook('beforeInsert', async (ctx: any) => {
532+
await ctx.api.object('loner').delete({ where: { id: 'l1' }, permanent: true });
533+
}, { object: 'account' });
534+
535+
await engine.insert('account', { id: 'acc_trigger', name: 'Trigger', organization_id: 'org_1' }, ORG1_USER);
536+
await engine.createContext({ isSystem: true }).object('loner').delete({ where: { id: 'l2' }, permanent: true });
537+
538+
expect(lonerDispatches(dispatches).map((d) => d.operation)).toEqual(['purge', 'purge']);
539+
expect(driver.rowsOf('loner')).toEqual([]);
540+
expect(entriesOf(driver)).toHaveLength(0);
541+
});
542+
});

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

Lines changed: 11 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ import {
6262
resolveRelatedTitleTarget,
6363
resolveServedRecordTitle,
6464
servedRecordTitle,
65+
refuseAppAuthoredPermanentDelete,
6566
type FormulaServingChannel,
6667
} from '@objectstack/objectql';
6768
import { deriveThroughSeam, refuseStoredMetadataBodyReads, refuseStoredMetadataBodyWrites } from '../stored-metadata-reader-seam.js';
@@ -1181,73 +1182,26 @@ function buildSandboxApi(engineCtx: any, ql: any, errLabel: string) {
11811182
/** Marks a scoped API whose permanent deletes are already refused for a body. */
11821183
const BODY_PERMANENT_DELETES_REFUSED = Symbol.for('objectstack.runtime.bodyPermanentDeletesRefused');
11831184

1184-
/**
1185-
* The refusal of a body's `delete(…, { permanent })`: `400 VALIDATION_ERROR`,
1186-
* `param: 'permanent'`. The message names the rule, because a job that asked
1187-
* for a purge has to learn it got none: dropping the key would delete into the
1188-
* bin and answer success, which reads as the purge it asked for.
1189-
*/
1190-
function bodyPermanentDeleteRefusal(objectName: string, errLabel: string): Error {
1191-
const err: any = new Error(
1192-
`A ${errLabel} cannot delete a record permanently: app-authored code cannot purge; ` +
1193-
`its deletes enter the recycle bin. Remove 'permanent' from the delete of '${objectName}'.`,
1194-
);
1195-
err.developerMessage =
1196-
`'permanent' was passed to ctx.api.object('${objectName}').delete() in a ${errLabel}. App-authored code ` +
1197-
`(hook, action and job bodies) cannot erase a record past the recycle bin, under any execution context, ` +
1198-
`a job's system envelope included; the permanent delete stays with a principal holding manageRecycleBin ` +
1199-
`(ADR-0148 D3).`;
1200-
err.code = 'VALIDATION_ERROR';
1201-
err.status = 400;
1202-
err.httpStatus = 400;
1203-
err.param = 'permanent';
1204-
err.object = objectName;
1205-
return err;
1206-
}
1207-
1208-
/**
1209-
* One repository as a body holds it: `delete(options)` whose `options` carry a
1210-
* `permanent` key with any value but `false` is refused before the underlying
1211-
* verb is called, so nothing is removed and no bin entry is skipped. `false`
1212-
* and an absent key are the ordinary delete, and go through unchanged. Every
1213-
* other member is handed through.
1214-
*/
1215-
function refuseRepositoryPermanentDelete(objectName: string, repo: unknown, errLabel: string): unknown {
1216-
if (repo === null || typeof repo !== 'object') return repo;
1217-
return new Proxy(repo as Record<PropertyKey, unknown>, {
1218-
get(target, prop) {
1219-
const value = Reflect.get(target, prop, target);
1220-
if (typeof value !== 'function') return value;
1221-
if (prop !== 'delete') return value.bind(target);
1222-
return async (...args: unknown[]) => {
1223-
const options = args[0];
1224-
if (options !== null && typeof options === 'object') {
1225-
const permanent = (options as { permanent?: unknown }).permanent;
1226-
if (permanent !== undefined && permanent !== false) {
1227-
throw bodyPermanentDeleteRefusal(objectName, errLabel);
1228-
}
1229-
}
1230-
return value.apply(target, args);
1231-
};
1232-
},
1233-
});
1234-
}
1235-
12361185
/**
12371186
* [ADR-0148 D3, ruling A recorded in 6691358077] The scoped API a sandboxed
12381187
* BODY (a hook, action or job body) holds, with the permanent delete refused:
12391188
* app-authored code cannot purge a record, so its deletes always enter the
12401189
* recycle bin. A job body runs under a fresh `{ isSystem: true, tenantId }`
12411190
* envelope and the system is never refused the engine's `purge` verb, so the
12421191
* rule is held here, at the one place every body face gets its API, and not by
1243-
* the engine, whose `delete(…, { permanent: true })` stays open to every other
1244-
* caller. Every context the API derives (`object(name)`, `sudo()`,
1245-
* `withRunAs(...)`, a transaction's context) is refused the same way.
1246-
* Idempotent.
1192+
* the engine's `delete`, whose `delete(…, { permanent: true })` stays open to
1193+
* every caller that is not app-authored. Every context the API derives
1194+
* (`object(name)`, `sudo()`, `withRunAs(...)`, a transaction's context) is
1195+
* refused the same way. Idempotent.
1196+
*
1197+
* The refusal itself is objectql's `refuseAppAuthoredPermanentDelete`, the
1198+
* same one the engine's `ScopedContext.object()` applies to an app-authored
1199+
* hook's api, so a hook's in-process `handler` and every body are refused with
1200+
* one code and one sentence.
12471201
*/
12481202
function refuseBodyPermanentDeletes<T>(api: T, errLabel: string): T {
12491203
return deriveThroughSeam(api, BODY_PERMANENT_DELETES_REFUSED, (name, repo) =>
1250-
refuseRepositoryPermanentDelete(name, repo, errLabel),
1204+
refuseAppAuthoredPermanentDelete(name, repo, errLabel),
12511205
);
12521206
}
12531207

0 commit comments

Comments
 (0)