|
| 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 | +}); |
0 commit comments