Skip to content

Commit 818ff4b

Browse files
committed
fix(runtime): a hook body's capability denial answers a coded 403 refusal, not a 500 fault
Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5o5GCE3vGxq6G24dZu
1 parent e1ab32e commit 818ff4b

2 files changed

Lines changed: 220 additions & 5 deletions

File tree

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#26903] A HOOK body's capability denial is a coded REFUSAL, not a fault.
5+
*
6+
* ## What was measured broken
7+
*
8+
* A `beforeInsert` hook whose sandboxed body calls `ctx.api.find(…)` without
9+
* `capabilities: ['api.read']` is refused by the gate ("capability 'api.read'
10+
* not granted"). The runner marked that denial as the sandbox's OWN fault
11+
* (#4431), so `mapDataError` answered the user's save with the sanitised
12+
* `500 INTERNAL_ERROR`: no code, no hook, no capability, nothing the caller or
13+
* the author could act on.
14+
*
15+
* ## The line this file pins
16+
*
17+
* - The gate is exactly as strict as before: the denied call never runs.
18+
* - `onError: 'abort'`: the save is refused with `403 INSUFFICIENT_PRIVILEGES`
19+
* (the standard catalog's member, no new code), whose sentence names the
20+
* hook and the capability, and nothing is written. One gate per token.
21+
* - `onError: 'log'`: the refusal is recorded where every hook error under
22+
* `log` is recorded (the hook wrapper's `[hook] handler failed` line), naming
23+
* the hook and the capability, and the save proceeds as `log` promises.
24+
* - Control: the same body WITH the capability runs as it always has.
25+
* - An ACTION body's denial keeps the #4431 fault contract
26+
* (`capability-denial-is-a-fault.test.ts`); this card ruled on hooks only.
27+
*
28+
* Measured in composition — a real `ObjectQL`, a real driver, the real
29+
* `QuickJSScriptRunner` and hook wrapper — and read off `mapDataError`, the
30+
* ADR-0112 table every data door answers with.
31+
*/
32+
33+
import { describe, it, expect, afterEach } from 'vitest';
34+
import { mapDataError } from '@objectstack/types';
35+
import { ObjectQL, bindHooksToEngine } from '@objectstack/objectql';
36+
import { InMemoryDriver } from '@objectstack/driver-memory';
37+
import { hookBodyRunnerFactory } from './body-runner.js';
38+
import { QuickJSScriptRunner } from './quickjs-runner.js';
39+
40+
const NOTE = {
41+
name: 'cap_note',
42+
fields: {
43+
title: { type: 'text', name: 'title' },
44+
stamp: { type: 'text', name: 'stamp' },
45+
},
46+
};
47+
48+
/** The object a nested write lands on, so the guard never re-fires on its own write. */
49+
const LOG = { name: 'cap_log', fields: { title: { type: 'text', name: 'title' } } };
50+
51+
interface Line { level: 'debug' | 'info' | 'warn' | 'error'; msg: string; err?: unknown; meta?: any }
52+
53+
/** A `Logger`-contract double (`error` is `(message, error, meta)`) that records every call. */
54+
function recordingLogger() {
55+
const lines: Line[] = [];
56+
return {
57+
lines,
58+
debug: (msg: string, meta?: any) => { lines.push({ level: 'debug', msg, meta }); },
59+
info: (msg: string, meta?: any) => { lines.push({ level: 'info', msg, meta }); },
60+
warn: (msg: string, meta?: any) => { lines.push({ level: 'warn', msg, meta }); },
61+
error: (msg: string, err?: unknown, meta?: any) => { lines.push({ level: 'error', msg, err, meta }); },
62+
};
63+
}
64+
65+
/** One gate per `HookBodyCapability` token: the call that trips it, as a hook body. */
66+
const GATES = [
67+
{ capability: 'api.read', source: "await ctx.api.object('cap_note').find({});" },
68+
{ capability: 'api.write', source: "await ctx.api.object('cap_log').insert({ title: 'nested' });" },
69+
{ capability: 'api.transaction', source: 'await ctx.api.transaction(async () => {});' },
70+
{ capability: 'crypto.uuid', source: 'ctx.input.stamp = ctx.crypto.randomUUID();' },
71+
{ capability: 'log', source: "ctx.log.info('stamping');" },
72+
] as const;
73+
74+
describe('[#26903] a hook body\'s capability denial is a coded refusal', () => {
75+
let engine: ObjectQL | null = null;
76+
77+
afterEach(async () => {
78+
try { await engine?.destroy(); } catch { /* noop */ }
79+
engine = null;
80+
});
81+
82+
async function boot(hook: Record<string, unknown>) {
83+
const hookLog = recordingLogger();
84+
const bodyLog = recordingLogger();
85+
engine = new ObjectQL();
86+
engine.registerDriver(new InMemoryDriver() as any, true);
87+
await engine.init();
88+
for (const o of [NOTE, LOG]) engine.registry.registerObject(o as any);
89+
const bodyRunner = hookBodyRunnerFactory(new QuickJSScriptRunner(), { ql: engine, appId: 'cap', logger: bodyLog });
90+
bindHooksToEngine(engine, [hook as any], { packageId: 'cap', bodyRunner, logger: hookLog as any });
91+
return { e: engine, hookLog, bodyLog };
92+
}
93+
94+
function guard(source: string, capabilities: string[], onError?: 'abort' | 'log') {
95+
return {
96+
name: 'cap_note_guard',
97+
object: 'cap_note',
98+
events: ['beforeInsert'],
99+
...(onError ? { onError } : {}),
100+
body: { language: 'js', source, capabilities },
101+
};
102+
}
103+
104+
async function rowCount(e: ObjectQL): Promise<number> {
105+
return (await e.find('cap_note', {})).length;
106+
}
107+
108+
for (const gate of GATES) {
109+
it(`onError: abort — '${gate.capability}' denied answers 403 INSUFFICIENT_PRIVILEGES naming hook and capability, nothing written`, async () => {
110+
const { e, bodyLog } = await boot(guard(gate.source, []));
111+
112+
const err = await e.insert('cap_note', { title: 'first' }).then(() => null, (x) => x);
113+
expect(err, 'the denied call must refuse the save').not.toBeNull();
114+
115+
const { status, body } = mapDataError(err, 'cap_note');
116+
expect(status).toBe(403);
117+
expect(body.code).toBe('INSUFFICIENT_PRIVILEGES');
118+
expect(String(body.error)).toContain(`capability '${gate.capability}' not granted to hook 'cap_note_guard'`);
119+
expect(String(body.error)).toContain(`adding '${gate.capability}' to the hook's body.capabilities`);
120+
// The caller's sentence carries neither the sandbox debug wrapper nor its name prefix.
121+
expect(String(body.error)).not.toMatch(/threw:|SandboxError/);
122+
123+
expect(await rowCount(e)).toBe(0);
124+
125+
// Logged once on the refusal side of the BodyRunner's band: info, coded, no stack.
126+
const refused = bodyLog.lines.filter((l) => l.msg.includes('sandboxed hook refused'));
127+
expect(refused).toHaveLength(1);
128+
expect(refused[0].level).toBe('info');
129+
expect(refused[0].meta).toMatchObject({ hook: 'cap_note_guard', code: 'INSUFFICIENT_PRIVILEGES', status: 403 });
130+
expect(bodyLog.lines.filter((l) => l.level === 'error')).toEqual([]);
131+
}, 30_000);
132+
}
133+
134+
for (const gate of GATES) {
135+
it(`onError: log — '${gate.capability}' denied is recorded in the hook-error log and the save proceeds`, async () => {
136+
const { e, hookLog } = await boot(guard(gate.source, [], 'log'));
137+
138+
await expect(e.insert('cap_note', { title: 'first' })).resolves.toBeTruthy();
139+
expect(await rowCount(e)).toBe(1);
140+
141+
const recorded = hookLog.lines.filter((l) => l.msg.includes('handler failed (onError=log'));
142+
expect(recorded).toHaveLength(1);
143+
expect(recorded[0].meta).toMatchObject({ hook: 'cap_note_guard', object: 'cap_note', event: 'beforeInsert' });
144+
expect(String(recorded[0].meta?.error)).toContain(`capability '${gate.capability}' not granted to hook 'cap_note_guard'`);
145+
}, 30_000);
146+
}
147+
148+
for (const gate of GATES) {
149+
it(`control — the same body WITH '${gate.capability}' runs as before`, async () => {
150+
const caps = [gate.capability];
151+
const { e, hookLog, bodyLog } = await boot(guard(gate.source, caps));
152+
153+
await expect(e.insert('cap_note', { title: 'first' })).resolves.toBeTruthy();
154+
expect(await rowCount(e)).toBe(1);
155+
expect([...hookLog.lines, ...bodyLog.lines].filter((l) => /refused|failed|threw/.test(l.msg))).toEqual([]);
156+
}, 30_000);
157+
}
158+
});

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

Lines changed: 62 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -713,8 +713,10 @@ export class QuickJSScriptRunner implements ScriptRunner {
713713
const installTxLeaf = (name: string, run: () => Promise<void>): void => {
714714
const fn = vm.newFunction(name, () => {
715715
if (!caps.has('api.transaction')) {
716-
throwSandboxFault(
716+
throwCapabilityDenial(
717717
vm,
718+
origin,
719+
'api.transaction',
718720
`capability 'api.transaction' not granted to ${origin.kind} '${origin.name}' (called ctx.api.transaction)`,
719721
);
720722
}
@@ -809,7 +811,7 @@ export class QuickJSScriptRunner implements ScriptRunner {
809811
for (const level of ['debug', 'info', 'warn', 'error'] as const) {
810812
const fn = vm.newFunction(level, (msgH, dataH) => {
811813
if (!caps.has('log')) {
812-
throwSandboxFault(vm, `capability 'log' not granted to ${origin.kind} '${origin.name}'`);
814+
throwCapabilityDenial(vm, origin, 'log', `capability 'log' not granted to ${origin.kind} '${origin.name}'`);
813815
}
814816
const msg = vm.getString(msgH);
815817
// [#7448] `vm.dump`, NOT `vm.getString` — the marshalling every other
@@ -835,7 +837,12 @@ export class QuickJSScriptRunner implements ScriptRunner {
835837
const cryptoObj = vm.newObject();
836838
const uuidFn = vm.newFunction('randomUUID', () => {
837839
if (!caps.has('crypto.uuid')) {
838-
throwSandboxFault(vm, `capability 'crypto.uuid' not granted to ${origin.kind} '${origin.name}'`);
840+
throwCapabilityDenial(
841+
vm,
842+
origin,
843+
'crypto.uuid',
844+
`capability 'crypto.uuid' not granted to ${origin.kind} '${origin.name}'`,
845+
);
839846
}
840847
const v = ctx.crypto?.randomUUID?.() ?? cryptoRandomUUID();
841848
return vm.newString(v);
@@ -885,8 +892,10 @@ export class QuickJSScriptRunner implements ScriptRunner {
885892
// "[object Object]".
886893
const fieldName = field === undefined || field === null ? undefined : String(field);
887894
if (fieldName !== undefined && !caps.has('api.read')) {
888-
throwSandboxFault(
895+
throwCapabilityDenial(
889896
vm,
897+
origin,
898+
'api.read',
890899
`capability 'api.read' not granted to ${origin.kind} '${origin.name}' ` +
891900
`(called ctx.title('${fieldName}'), which reads the related record). ` +
892901
`ctx.title() with no argument needs no capability.`,
@@ -1284,8 +1293,10 @@ function installApiMethod(
12841293
// Capability gate — throw synchronously so the VM sees a normal exception at
12851294
// the call site (mirrors ctx.log / ctx.crypto gating).
12861295
if (!caps.has(required)) {
1287-
throwSandboxFault(
1296+
throwCapabilityDenial(
12881297
vm,
1298+
origin,
1299+
required,
12891300
`capability '${required}' not granted to ${origin.kind} '${origin.name}' (called ctx.api.object('${objectName}').${method})`,
12901301
);
12911302
}
@@ -1786,6 +1797,52 @@ function throwSandboxFault(vm: QuickJSContext, message: string): never {
17861797
throw hostErrorToVm(vm, new SandboxError(message));
17871798
}
17881799

1800+
/**
1801+
* [#26903] The code and status a HOOK body's capability denial is answered
1802+
* with: the standard catalog's `INSUFFICIENT_PRIVILEGES` ("operation requires
1803+
* higher privileges", `@objectstack/spec` `errors.zod.ts`), at its 403.
1804+
*/
1805+
const HOOK_CAPABILITY_REFUSAL_CODE = 'INSUFFICIENT_PRIVILEGES';
1806+
const HOOK_CAPABILITY_REFUSAL_STATUS = 403;
1807+
1808+
/**
1809+
* [#26903] Throw a capability gate's denial OUT OF a host function.
1810+
*
1811+
* In a HOOK body the denial is a REFUSAL, not the sandbox faulting: the hook's
1812+
* metadata did not grant what its body called, and the caller whose save fired
1813+
* the hook is owed a coded answer naming the hook and the capability, not the
1814+
* sanitised `500 INTERNAL_ERROR` {@link throwSandboxFault} reaches. So the VM
1815+
* error carries `code` and `status` the way a body's own
1816+
* `throw Object.assign(new Error(…), { code, status })` does, and the pump loop
1817+
* builds the same `SandboxError` (with `innerMessage`) it builds for that
1818+
* throw. Every door then answers it through `mapDataError`'s sandbox unwrap
1819+
* arm — `403 INSUFFICIENT_PRIVILEGES` with this sentence — and the BodyRunner
1820+
* logs it on the refusal side of its band, and `onError: 'log'` records it
1821+
* where it records any hook error.
1822+
*
1823+
* ⛔ The gate is exactly as strict as before: only how its denial is answered
1824+
* changed. ⛔ A plain `Error`, never a `SandboxError` instance: an instance is
1825+
* what {@link hostErrorToVm} marks as a fault, and a host error with an
1826+
* `innerMessage` is what it relays as a NESTED body's refusal (which the outer
1827+
* catch then does not log). Neither is true of this denial.
1828+
*
1829+
* An action or job body's denial keeps the #4431 fault contract
1830+
* ({@link SANDBOX_FAULT_PROP}); this card ruled on hooks only.
1831+
*/
1832+
function throwCapabilityDenial(
1833+
vm: QuickJSContext,
1834+
origin: ScriptOrigin,
1835+
capability: HookBodyCapability,
1836+
message: string,
1837+
): never {
1838+
if (origin.kind !== 'hook') throwSandboxFault(vm, message);
1839+
const refusal = Object.assign(
1840+
new Error(`${message.replace(/\.$/, '')}. Grant it by adding '${capability}' to the hook's body.capabilities.`),
1841+
{ name: 'SandboxError', code: HOOK_CAPABILITY_REFUSAL_CODE, status: HOOK_CAPABILITY_REFUSAL_STATUS },
1842+
);
1843+
throw hostErrorToVm(vm, refusal);
1844+
}
1845+
17891846
/**
17901847
* Strip the `SandboxError: ` name prefix the VM's flattening prepends.
17911848
*

0 commit comments

Comments
 (0)