From f1aa4185a1e7406e4d18d999b78cc474c4878fab Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 22:01:10 +0000 Subject: [PATCH 01/11] wip(lint): judge every sandbox capability gate on action and hook bodies Claude-Session: https://claude.ai/code/session_01ADHkmSwS4mQyXWrddL4r6B Co-authored-by: Claude --- packages/lint/src/authoring-rules.ts | 7 +- .../src/validate-action-body-capabilities.ts | 294 +++++++++++++++--- 2 files changed, 262 insertions(+), 39 deletions(-) diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 7f72959de0a..dbf722f936a 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -3369,8 +3369,11 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ commands: ALL, source: 'packages/lint/src/validate-action-body-capabilities.ts', surfaces: CLI_AND_RUNTIME, - runtimeTypes: ['action', 'object'], - run: (stack) => validateActionBodyCapabilities(stack), + // [#37815] `hook`: the same judgement over an L2 hook body, every token + // the sandbox gates (`hook-body-capability-undeclared`); no object write + // carries a hook. + runtimeTypes: ['action', 'object', 'hook'], + run: (stack, ctx) => validateActionBodyCapabilities(stack, ctx), }, // The same compile check over an L2 hook body and an L2 job body, in the // wrapper the runtime runs both in (`(async (ctx) => { SOURCE })`, built from diff --git a/packages/lint/src/validate-action-body-capabilities.ts b/packages/lint/src/validate-action-body-capabilities.ts index 01222d90333..27ee34c6f42 100644 --- a/packages/lint/src/validate-action-body-capabilities.ts +++ b/packages/lint/src/validate-action-body-capabilities.ts @@ -1,8 +1,9 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * An L2 action body that calls a write method of `ctx.api` without granting - * itself `api.write` (#35143, Seeds and actions family). + * An L2 action or hook body that calls a member the sandbox gates without + * granting itself the member's token: a `ctx.api` write without `api.write` + * (#35143, Seeds and actions family), and every other gate (#37815). * * ## Why * @@ -51,9 +52,45 @@ * the sandbox, so a body that reaches the call fails every time. The one * reading under which the body works is that the call is never reached, and a * write the author wrote and never runs is no reason to publish it. + * + * ## Every gate, on action and hook bodies (#37815) + * + * `installCtx` gates more than the writes, and a hook body runs in the same + * sandbox with the same `body.capabilities`. {@link SANDBOX_CAPABILITY_GATES} + * is the runner's census, token by token, pinned to the runner's source by + * this rule's test so a gate the runner adds or drops turns the pin red. Each + * gate is read the way the writes are (blanked source, the receiver itself or + * a local bound once to it): + * + * - `api.read`: a read leaf on `ctx.api.object(…)`, and on a hook body + * `ctx.title(FIELD)` with an argument (the related-record form; the action + * face installs no `ctx.title`, and `ctx.title()` needs no token); + * - `api.transaction`: `ctx.api.transaction(…)`; + * - `log`: `ctx.log.debug|info|warn|error(…)`; + * - `crypto.uuid`: `ctx.crypto.randomUUID(…)`; + * - `email.send`: `ctx.email.send(…)`; `activity.append`: + * `ctx.activity.append(…)`. + * + * Ids: an action body's missing `api.write` keeps its own id and words + * ({@link ACTION_BODY_WRITE_CAPABILITY_UNDECLARED}); every other token on an + * action body is {@link ACTION_BODY_CAPABILITY_UNDECLARED}; every token on a + * hook body is {@link HOOK_BODY_CAPABILITY_UNDECLARED}. One finding per body + * and token, since each token is its own grant. + * + * A hook body is never granted `email.send` (the hook's parse refuses the + * grant: a message cannot be taken back if the write that runs the hook rolls + * back), so a hook's `ctx.email.send` call is refused with the remedy that + * works: remove the call and send the mail from an action, a job or a flow. + * + * A hook `os build` / `os validate` lowered from an inline handler is + * reported at `hooks[i].handler`, the key the author wrote + * (`hookBodyFindingLocation`); its grant is the build's inference, so the hint + * names the body the author can write instead. */ import { collectActionBodies } from './validate-action-body-writes.js'; +import { hookBodyFindingLocation } from './validate-hook-body-writes.js'; +import { recordsOf } from './object-graph.js'; type AnyRec = Record; @@ -82,6 +119,56 @@ export interface ActionBodyCapabilityFinding { hint: string; } +/** [#37815] A token other than `api.write` an action body calls without being granted. */ +export const ACTION_BODY_CAPABILITY_UNDECLARED = 'action-body-capability-undeclared'; +/** [#37815] Any token a hook body calls without being granted. */ +export const HOOK_BODY_CAPABILITY_UNDECLARED = 'hook-body-capability-undeclared'; + +/** The read leaves the sandbox installs on `ctx.api.object(name)` behind `api.read` — `READ` in `installCtx`. */ +export const SANDBOX_API_READ_METHODS: readonly string[] = ['find', 'findOne', 'count', 'aggregate']; + +/** The levels the sandbox installs on `ctx.log` behind `log`. */ +export const SANDBOX_LOG_LEVELS: readonly string[] = ['debug', 'info', 'warn', 'error']; + +/** Which kinds of body a gate is installed on. */ +export type BodyKind = 'action' | 'hook'; + +/** + * One capability gate of the sandbox: the token, the `ctx` member it sits on + * and how the gated call is spelled. + * + * - `object-leaf`: `ctx.MEMBER.object(…).LEAF(…)`; + * - `member-leaf`: `ctx.MEMBER.LEAF(…)`; + * - `called-with-argument`: `ctx.MEMBER(ARG)`, gated only when an argument + * is passed. + */ +export interface SandboxCapabilityGate { + token: string; + member: string; + shape: 'object-leaf' | 'member-leaf' | 'called-with-argument'; + leaves: readonly string[]; + /** The bodies the gated member is installed on. */ + kinds: readonly BodyKind[]; +} + +/** + * Every capability gate `installCtx` (`packages/runtime/src/sandbox/ + * quickjs-runner.ts`) puts on a body's `ctx`, in the runner's order. Pinned to + * the runner's source by this rule's test: the token set, the read and write + * leaves, the log levels and the two doors. + */ +export const SANDBOX_CAPABILITY_GATES: readonly SandboxCapabilityGate[] = [ + { token: 'api.read', member: 'api', shape: 'object-leaf', leaves: SANDBOX_API_READ_METHODS, kinds: ['action', 'hook'] }, + { token: 'api.write', member: 'api', shape: 'object-leaf', leaves: SANDBOX_API_WRITE_METHODS, kinds: ['action', 'hook'] }, + { token: 'api.transaction', member: 'api', shape: 'member-leaf', leaves: ['transaction'], kinds: ['action', 'hook'] }, + { token: 'log', member: 'log', shape: 'member-leaf', leaves: SANDBOX_LOG_LEVELS, kinds: ['action', 'hook'] }, + { token: 'crypto.uuid', member: 'crypto', shape: 'member-leaf', leaves: ['randomUUID'], kinds: ['action', 'hook'] }, + { token: 'email.send', member: 'email', shape: 'member-leaf', leaves: ['send'], kinds: ['action', 'hook'] }, + { token: 'activity.append', member: 'activity', shape: 'member-leaf', leaves: ['append'], kinds: ['action', 'hook'] }, + // `ctx.title` is built only where the host builds its seam: hook bodies. + { token: 'api.read', member: 'title', shape: 'called-with-argument', leaves: [], kinds: ['hook'] }, +]; + /** Blank string, template-literal and comment contents, keeping every offset. */ export function maskBodySource(source: string): string { const out = source.split(''); @@ -118,9 +205,11 @@ export function maskBodySource(source: string): string { } const IDENT = String.raw`[A-Za-z_$][\w$]*`; -const WRITE_ALT = [...SANDBOX_API_WRITE_METHODS].sort((a, b) => b.length - a.length).join('|'); -/** `.update(` / `?.insert(` — a write leaf called on what precedes it. */ -const WRITE_CALL = new RegExp(String.raw`^\s*\??\.\s*(${WRITE_ALT})(?![\w$])\s*\(`); + +/** The leaves as one alternation, longest first so `update` never shadows `updateMany`. */ +function leafAlternation(leaves: readonly string[]): string { + return [...leaves].sort((a, b) => b.length - a.length).join('|'); +} function escapeIdentifier(name: string): string { return name.replace(/\$/g, '\\$'); @@ -153,27 +242,30 @@ function boundOnce(masked: string, name: string, declarations: number): boolean } /** - * The write methods a body calls through `ctx.api` (see the header for the - * three shapes), in first-seen order. + * The receivers that are `ctx.MEMBER`: the expression itself (`?.` allowed), + * a local bound once to it (`const api = ctx.api`) and a local destructured + * once from `ctx` (`const { api } = ctx`, `const { api: a } = ctx`). */ -export function bodyApiWriteCalls(source: string): string[] { - if (!/\bapi\b/.test(source)) return []; - const masked = maskBodySource(source); - - // Receivers that are `ctx.api`: the expression itself, and locals bound to it. - const receivers: string[] = [String.raw`(?.object(…)` with nothing chained after it. @@ -194,31 +286,159 @@ export function bodyApiWriteCalls(source: string): string[] { } } for (const name of handles) { - const call = new RegExp(String.raw`(? new RegExp(receiver + String.raw`\s*(?:\?\.\s*)?\(\s*[^)\s]`).test(masked)); +} + +/** + * The write methods a body calls through `ctx.api` (see the header for the + * three shapes), in first-seen order. + */ +export function bodyApiWriteCalls(source: string): string[] { + if (!/\bapi\b/.test(source)) return []; + const masked = maskBodySource(source); + return objectLeafCalls(masked, memberReceivers(masked, 'api'), SANDBOX_API_WRITE_METHODS); +} + +/** The gated calls of one token that a body makes, spelled the way a message names them. */ +export interface GatedCalls { + token: string; + calls: string[]; +} + +/** + * Every gated call a body of `kind` makes, grouped by token in the order of + * {@link SANDBOX_CAPABILITY_GATES}, whether or not the body is granted it. + */ +export function bodyGatedCalls(source: string, kind: BodyKind): GatedCalls[] { + const gates = SANDBOX_CAPABILITY_GATES.filter((g) => g.kinds.includes(kind) && new RegExp(String.raw`\b${g.member}\b`).test(source)); + if (gates.length === 0) return []; + const masked = maskBodySource(source); + const byToken = new Map(); + const receiversOf = new Map(); + for (const gate of gates) { + let receivers = receiversOf.get(gate.member); + if (!receivers) { + receivers = memberReceivers(masked, gate.member); + receiversOf.set(gate.member, receivers); + } + let calls: string[]; + if (gate.shape === 'object-leaf') { + calls = objectLeafCalls(masked, receivers, gate.leaves).map((leaf) => `ctx.${gate.member}.object(…).${leaf}(…)`); + } else if (gate.shape === 'member-leaf') { + calls = memberLeafCalls(masked, receivers, gate.leaves).map((leaf) => `ctx.${gate.member}.${leaf}(…)`); + } else { + calls = calledWithArgument(masked, receivers) ? [`ctx.${gate.member}(FIELD)`] : []; + } + if (calls.length === 0) continue; + byToken.set(gate.token, [...(byToken.get(gate.token) ?? []), ...calls]); + } + return [...byToken].map(([token, calls]) => ({ token, calls })); +} + +function isRecord(v: unknown): v is AnyRec { + return !!v && typeof v === 'object' && !Array.isArray(v); +} + +/** The sandbox's answer to an ungranted call, and what is lost with it. */ +function refusalClause(token: string, kind: BodyKind): string { + const lost = + token === 'api.write' ? ', and nothing is written' : token === 'email.send' ? ', and no mail is sent' : ''; + return `so the sandbox refuses the call (403 INSUFFICIENT_PRIVILEGES) every time the ${kind} reaches it${lost}.`; +} + +/** + * Every L2 action body, and every L2 hook body, that calls a member the + * sandbox gates without granting itself the member's token (the header lists + * the gates and the ids). `ctx.loweredHookRefs` locates a hook the build + * lowered from an inline `handler` at `hooks[i].handler`. + */ +export function validateActionBodyCapabilities( + stack: AnyRec, + ctx?: { loweredHookRefs?: ReadonlySet }, +): ActionBodyCapabilityFinding[] { const findings: ActionBodyCapabilityFinding[] = []; if (!stack || typeof stack !== 'object') return findings; for (const site of collectActionBodies(stack)) { - if (site.capabilities.includes('api.write')) continue; - const calls = bodyApiWriteCalls(site.source); - if (calls.length === 0) continue; - const listed = calls.map((c) => `${c}(…)`).join(', '); - findings.push({ - severity: 'error', - rule: ACTION_BODY_WRITE_CAPABILITY_UNDECLARED, - where: `action "${site.name}" › body`, - path: site.path.replace(/\.source$/, '.capabilities'), - message: - `body calls ctx.api.object(…).${listed} but its capabilities do not grant 'api.write', so the sandbox ` + - 'refuses the call (403 INSUFFICIENT_PRIVILEGES) every time the action reaches it, and nothing is written.', - hint: "Add 'api.write' to the action's body.capabilities, or remove the write.", - }); + for (const { token, calls } of bodyGatedCalls(site.source, 'action')) { + if (site.capabilities.includes(token)) continue; + const path = site.path.replace(/\.source$/, '.capabilities'); + const where = `action "${site.name}" › body`; + if (token === 'api.write') { + const listed = calls.map((c) => c.replace(/^ctx\.api\.object\(…\)\./, '')).join(', '); + findings.push({ + severity: 'error', + rule: ACTION_BODY_WRITE_CAPABILITY_UNDECLARED, + where, + path, + message: + `body calls ctx.api.object(…).${listed} but its capabilities do not grant 'api.write', so the sandbox ` + + 'refuses the call (403 INSUFFICIENT_PRIVILEGES) every time the action reaches it, and nothing is written.', + hint: "Add 'api.write' to the action's body.capabilities, or remove the write.", + }); + continue; + } + findings.push({ + severity: 'error', + rule: ACTION_BODY_CAPABILITY_UNDECLARED, + where, + path, + message: `body calls ${calls.join(', ')} but its capabilities do not grant '${token}', ${refusalClause(token, 'action')}`, + hint: `Add '${token}' to the action's body.capabilities, or remove the call.`, + }); + } } + recordsOf(stack.hooks).forEach((hook, index) => { + const body = hook.body; + if (!isRecord(body) || body.language !== 'js') return; + const source = body.source; + if (typeof source !== 'string' || source.trim() === '') return; + const granted: readonly unknown[] = Array.isArray(body.capabilities) ? body.capabilities : []; + const name = typeof hook.name === 'string' && hook.name ? hook.name : `#${index}`; + const loc = hookBodyFindingLocation(hook, index, ctx); + const lowered = loc.path !== `hooks[${index}].body.source`; + for (const { token, calls } of bodyGatedCalls(source, 'hook')) { + if (granted.includes(token)) continue; + const listed = calls.join(', '); + const mail = token === 'email.send'; + findings.push({ + severity: 'error', + rule: HOOK_BODY_CAPABILITY_UNDECLARED, + where: `hook "${name}" › body`, + path: lowered ? loc.path : `hooks[${index}].body.capabilities`, + message: + (mail + ? `body calls ${listed}, and a hook body is never granted 'email.send' (a message cannot be taken back ` + + "if the write that runs the hook rolls back), so the sandbox refuses the call every time the hook reaches it, and no mail is sent." + : `body calls ${listed} but its capabilities do not grant '${token}', ${refusalClause(token, 'hook')}`) + + loc.messageSuffix, + hint: mail + ? 'Remove the ctx.email.send call, and send mail on a record change from an action, a job or a flow.' + : lowered + ? `The build grants a handler only the tokens it infers from the handler's calls, and it did not infer '${token}' ` + + `here: write the hook's body with '${token}' in body.capabilities instead of the handler, or remove the call.` + : `Add '${token}' to the hook's body.capabilities, or remove the call.`, + }); + } + }); return findings; } From 1106f067ad8d27838aa03dadd63189a4bfaa8470 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 22:04:29 +0000 Subject: [PATCH 02/11] feat(lint)!: judge every sandbox capability gate on action and hook bodies Claude-Session: https://claude.ai/code/session_01ADHkmSwS4mQyXWrddL4r6B Co-authored-by: Claude --- .../docs/deployment/validating-metadata.mdx | 2 + packages/lint/src/rule-explanations.ts | 54 +++- ...capabilities.hook-and-tokens-37815.test.ts | 248 ++++++++++++++++++ 3 files changed, 303 insertions(+), 1 deletion(-) create mode 100644 packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 71244eff42d..8f317f269d4 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -524,7 +524,9 @@ orthogonal to both, and no cell here can carry it; it is written out in | Script action bodies compile in the runtime's wrapper — an L2 action's `body.source` that does not compile as the body of `(async (input, ctx) => { … })`, most often `const input = …` redeclaring a parameter; an object write runs it over its inline `actions[]`, so an object write cannot republish a refused body (`action-body-does-not-compile`, #34884) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | | Script action bodies hold the grant they call — an L2 action body that calls a `ctx.api` write (`insert`, `update`, `delete`, `updateMany`, `deleteMany`, `upsert`) without `api.write` in its `body.capabilities`, which the sandbox refuses at every call (`action-body-write-capability-undeclared`, #35143) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | | Seed record keys — a seed record key, or a seed `columns` key, that names no field of the dataset's object, no system column injected on it and none of `id` / `created_at` / `updated_at`; the engine's insert door refuses such a record and the seed load loads the rest (`seed-record-unknown-field`, #35143) | ✓ | ✓ | ✓ | ✓ˢ | +| Script action bodies hold every other grant they call — an L2 action body that calls a member the sandbox gates behind a token other than `api.write` without that token in its `body.capabilities`: a `ctx.api.object(…)` read leaf (`api.read`), `ctx.api.transaction(…)` (`api.transaction`), `ctx.log.*` (`log`), `ctx.crypto.randomUUID()` (`crypto.uuid`), `ctx.email.send(…)` (`email.send`) or `ctx.activity.append(…)` (`activity.append`), each refused by the sandbox at every call (`action-body-capability-undeclared`, #37815) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | | Hook and job bodies compile in the runtime's wrapper — an L2 hook or job `body.source` that does not compile as the body of `(async (ctx) => { … })`, most often `const ctx = …` redeclaring the parameter or one name declared twice; no door publishes a job, so the publish column is the `hook` write alone (`hook-body-does-not-compile`, `job-body-does-not-compile`, #34987) | ✓ | ✓ | ✓ | ✓ʰ | +| Hook bodies hold the grant they call — an L2 hook body that calls a member the sandbox gates without its token in `body.capabilities`: a `ctx.api.object(…)` read or write leaf, `ctx.api.transaction(…)`, `ctx.log.*`, `ctx.crypto.randomUUID()`, `ctx.activity.append(…)` or the related-record form `ctx.title(FIELD)`, each refused by the sandbox at every call; and any `ctx.email.send(…)`, which a hook body is never granted (`hook-body-capability-undeclared`, #37815) | ✓ | ✓ | ✓ | ✓ʰ | | Approval-node approvers (ADR-0090 D3) | ✓ | ✓ | ✓ | ✓ᶠ | | Security posture (ADR-0090 — e.g. every custom object declares `sharingModel`) | ✓ | ✓ | ✓ | ✓ˢᵖᵉᵇᵒ | | Security vocabulary freeze (ADR-0090 D3 — the reserved word, replaced by `permission_set` / `position` / `business_unit`) | ✓ | ✓ | ✓ | ✓ᵒᵖᵉᵇᵖᵒᵃᵒˣ | diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 689b821ee6e..2b47ce7d775 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -1423,7 +1423,8 @@ const ACTION_BODY_WRITE_UNKNOWN_FIELD_EXPLANATION: RuleExplanation = { covers: 'why an undeclared field write is refused', paragraphs: [ 'An action body persists records only through `ctx.api`: ' + - '`ctx.api.object(NAME).insert({ … })`, or `.update({ id, … })` for one record. `ctx.api` is a scoped handle on ' + + '`ctx.api.object(NAME).insert({ … })`, `.update({ id, … })` for one record, `.upsert(…)` or ' + + '`.updateMany(…)`, the leaves the sandbox installs that carry fields. `ctx.api` is a scoped handle on ' + 'the running engine, so the payload arrives as an ordinary CALLER write. An action\'s `ctx.input` ' + 'is its params bag, validated against the action\'s own `params`, so it is never resolved against ' + 'fields.', @@ -1522,6 +1523,55 @@ const ACTION_BODY_WRITE_CAPABILITY_UNDECLARED_EXPLANATION: RuleExplanation = { ], }; +/** + * [#37815] The two ids beside `action-body-write-capability-undeclared`: every + * other sandbox gate on an action body, and every gate on a hook body. One + * paragraph set, worded per kind. + */ +const BODY_GATES_PARAGRAPH = + 'The sandbox gates these calls, each behind its own token: the `ctx.api.object(…)` read leaves (`find`, ' + + '`findOne`, `count`, `aggregate`) behind `api.read`, the write leaves behind `api.write`, ' + + '`ctx.api.transaction(…)` behind `api.transaction`, `ctx.log.debug|info|warn|error(…)` behind `log`, ' + + '`ctx.crypto.randomUUID()` behind `crypto.uuid`, `ctx.email.send(…)` behind `email.send` and ' + + '`ctx.activity.append(…)` behind `activity.append`. A call the body was not granted throws at the call site ' + + 'with `403 INSUFFICIENT_PRIVILEGES`.'; +const BODY_GATES_READING = + 'The rule reads the body\'s source with comments, strings and template literals blanked, and finds a gated ' + + 'call on the `ctx` member itself (with `?.` allowed), on a local bound once to it (`const log = ctx.log`, or ' + + '`log` destructured from `ctx`), or, for the `ctx.api.object(…)` leaves, on a handle bound once to ' + + '`.object(…)`. It does not parse or run the body: the runtime save door may load no parser. A call spelled ' + + 'another way is not found, which leaves the author where the sandbox would.'; + +const ACTION_BODY_CAPABILITY_UNDECLARED_EXPLANATION: RuleExplanation = { + rule: 'action-body-capability-undeclared', + covers: 'the grant a script action body\'s gated calls need, other than its writes', + paragraphs: [ + 'A script action body runs in the QuickJS sandbox with only the capabilities its `body.capabilities` ' + + 'lists (none by default). ' + BODY_GATES_PARAGRAPH + ' The action answers that refusal every time it ' + + 'reaches the call. A write without `api.write` has its own id, `action-body-write-capability-undeclared`.', + BODY_GATES_READING, + 'To fix it, add the token the message names to the action\'s `body.capabilities` (Studio\'s action ' + + 'inspector draws the list), or remove the call.', + ], +}; + +const HOOK_BODY_CAPABILITY_UNDECLARED_EXPLANATION: RuleExplanation = { + rule: 'hook-body-capability-undeclared', + covers: 'the grant a hook body\'s gated calls need', + paragraphs: [ + 'A hook body runs in the same QuickJS sandbox as an action body, with only the capabilities its ' + + '`body.capabilities` lists (none by default). ' + BODY_GATES_PARAGRAPH + ' A hook body also has ' + + '`ctx.title(FIELD)`, which reads the related record and needs `api.read`; `ctx.title()` with no argument ' + + 'needs no token. Under the hook\'s default `onError: \'abort\'` the refusal aborts the write that ran it.', + BODY_GATES_READING, + 'To fix it, add the token the message names to the hook\'s `body.capabilities`, or remove the call. A hook ' + + 'body is never granted `email.send`, because a message cannot be taken back if the write that runs the ' + + 'hook rolls back: remove the `ctx.email.send` call and send the mail from an action, a job or a flow. A ' + + 'hook the build lowered from an inline `handler` is reported at `handler`: the build grants it only the ' + + 'tokens it infers from the handler\'s calls, so write the hook\'s `body` with the grant instead.', + ], +}; + const SEED_RECORD_UNKNOWN_FIELD_EXPLANATION: RuleExplanation = { rule: 'seed-record-unknown-field', covers: 'which keys a seed record may carry', @@ -7331,6 +7381,8 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [ACTION_BODY_SOURCE_UNPARSEABLE_EXPLANATION.rule]: ACTION_BODY_SOURCE_UNPARSEABLE_EXPLANATION, [ACTION_BODY_DOES_NOT_COMPILE_EXPLANATION.rule]: ACTION_BODY_DOES_NOT_COMPILE_EXPLANATION, [ACTION_BODY_WRITE_CAPABILITY_UNDECLARED_EXPLANATION.rule]: ACTION_BODY_WRITE_CAPABILITY_UNDECLARED_EXPLANATION, + [ACTION_BODY_CAPABILITY_UNDECLARED_EXPLANATION.rule]: ACTION_BODY_CAPABILITY_UNDECLARED_EXPLANATION, + [HOOK_BODY_CAPABILITY_UNDECLARED_EXPLANATION.rule]: HOOK_BODY_CAPABILITY_UNDECLARED_EXPLANATION, [SEED_RECORD_UNKNOWN_FIELD_EXPLANATION.rule]: SEED_RECORD_UNKNOWN_FIELD_EXPLANATION, [LIST_VIEW_KANBAN_GROUP_FIELD_UNCATEGORICAL_EXPLANATION.rule]: LIST_VIEW_KANBAN_GROUP_FIELD_UNCATEGORICAL_EXPLANATION, [LIST_VIEW_FILTER_FIELD_VIRTUAL_EXPLANATION.rule]: LIST_VIEW_FILTER_FIELD_VIRTUAL_EXPLANATION, diff --git a/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts b/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts new file mode 100644 index 00000000000..500921f0909 --- /dev/null +++ b/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts @@ -0,0 +1,248 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// [#37815] items (a) and (b): the capability judgement over hook bodies, and +// over every token the sandbox gates besides `api.write`. + +import { readFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; +import { HookBodyCapability } from '@objectstack/spec/data'; + +import { + ACTION_BODY_CAPABILITY_UNDECLARED, + ACTION_BODY_WRITE_CAPABILITY_UNDECLARED, + HOOK_BODY_CAPABILITY_UNDECLARED, + SANDBOX_API_READ_METHODS, + SANDBOX_CAPABILITY_GATES, + SANDBOX_LOG_LEVELS, + bodyGatedCalls, + validateActionBodyCapabilities, +} from './validate-action-body-capabilities.js'; +import { runAuthoringRules } from './authoring-rules.js'; +import { runRuntimeAuthoringRules, runtimeAuthoringRulesFor } from './runtime-gate.js'; +import { explainRule } from './rule-explanations.js'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const RUNNER = resolve(HERE, '../../runtime/src/sandbox/quickjs-runner.ts'); + +const TICKET = { + name: 'cb_ticket', + label: 'Ticket', + sharingModel: 'private', + fields: { name: { type: 'text', label: 'Name' }, done: { type: 'boolean', label: 'Done' } }, +}; + +const hook = (source: string, capabilities?: string[], extra: Record = {}) => ({ + name: 'cb_stamp', + object: 'cb_ticket', + events: ['beforeUpdate'], + body: { language: 'js', source, ...(capabilities ? { capabilities } : {}) }, + ...extra, +}); + +const action = (source: string, capabilities?: string[]) => ({ + name: 'cb_close', + label: 'Close', + objectName: 'cb_ticket', + type: 'script', + locations: ['record_page'], + body: { language: 'js', source, ...(capabilities ? { capabilities } : {}) }, +}); + +const ofRule = (fs: readonly T[], rule: string): T[] => fs.filter((f) => f.rule === rule); + +describe('the gate census is the sandbox runner’s, exactly (#37815)', () => { + const runner = readFileSync(RUNNER, 'utf8'); + const tokens = new Set(SANDBOX_CAPABILITY_GATES.map((g) => g.token)); + + it('every token the runner gates, and no other', () => { + const literal = [...runner.matchAll(/caps\.has\('([^']+)'\)/g)].map((m) => m[1]); + const viaApiMethod = [...runner.matchAll(/installApiMethod\([^)]*caps, '([^']+)'/g)].map((m) => m[1]); + const viaDoor = [...runner.matchAll(/installDoor\('[^']+', '[^']+', '([^']+)'\)/g)].map((m) => m[1]); + expect([...new Set([...literal, ...viaApiMethod, ...viaDoor])].sort()).toEqual([...tokens].sort()); + // Two gates take their token as a parameter: `installApiMethod`'s `required` + // and `installDoor`'s `token`. A third such gate is a token this census cannot + // read, so it turns this red until the census learns it. + const dynamic = [...runner.matchAll(/caps\.has\(([A-Za-z_$][\w$]*)\)/g)].map((m) => m[1]).sort(); + expect(dynamic).toEqual(['required', 'token']); + }); + + it('every token the spec declares is a gate the runner holds', () => { + expect([...HookBodyCapability.options].sort()).toEqual([...tokens].sort()); + }); + + it('the read leaves, the log levels and the two doors', () => { + const read = /const READ = \[([^\]]*)\] as const;/.exec(runner); + expect(read, 'the runner no longer declares `const READ = [...]`').not.toBeNull(); + expect([...SANDBOX_API_READ_METHODS].sort()).toEqual([...read![1].matchAll(/'([^']+)'/g)].map((x) => x[1]).sort()); + + const levels = /for \(const level of \[([^\]]*)\] as const\)/.exec(runner); + expect(levels, 'the runner no longer loops `for (const level of [...] as const)`').not.toBeNull(); + expect([...SANDBOX_LOG_LEVELS]).toEqual([...levels![1].matchAll(/'([^']+)'/g)].map((x) => x[1])); + + const doors = [...runner.matchAll(/installDoor\('([^']+)', '([^']+)', '([^']+)'\)/g)].map((m) => `${m[1]}.${m[2]}:${m[3]}`); + const declared = SANDBOX_CAPABILITY_GATES.filter((g) => g.member === 'email' || g.member === 'activity').map( + (g) => `${g.member}.${g.leaves.join('|')}:${g.token}`, + ); + expect(declared.sort()).toEqual(doors.sort()); + }); + + it('api.transaction gates ctx.api.transaction, crypto.uuid gates randomUUID, and ctx.title(FIELD) gates api.read', () => { + expect(runner).toContain('__ctx.api.transaction = async function (fn)'); + expect(runner).toMatch(/const fn = vm\.newFunction\(name, \(\) => \{\s*if \(!caps\.has\('api\.transaction'\)\)/); + expect(runner).toMatch(/newFunction\('randomUUID', \(\) => \{\s*if \(!caps\.has\('crypto\.uuid'\)\)/); + expect(runner).toContain("if (fieldName !== undefined && !caps.has('api.read'))"); + }); +}); + +describe('arm (a): a hook body is judged like an action body (#37815)', () => { + const WRITE = "await ctx.api.object('cb_ticket').update({ id: ctx.input.id, done: true });"; + + it('refuses a hook body that writes through ctx.api with no api.write grant', () => { + const fs = validateActionBodyCapabilities({ hooks: [hook(WRITE, ['api.read'])] }); + expect(fs.map((f) => [f.rule, f.severity, f.where, f.path])).toEqual([ + [HOOK_BODY_CAPABILITY_UNDECLARED, 'error', 'hook "cb_stamp" › body', 'hooks[0].body.capabilities'], + ]); + expect(fs[0].message).toContain("'api.write'"); + expect(fs[0].hint).toContain("Add 'api.write' to the hook's body.capabilities"); + }); + + it('passes the same hook body once api.write is granted', () => { + expect(validateActionBodyCapabilities({ hooks: [hook(WRITE, ['api.write'])] })).toEqual([]); + }); + + it('stays quiet on a hook body that calls nothing gated', () => { + const source = "var t = await ctx.title(); ctx.input.name = String(t || ''); if (ctx.previous) return;"; + expect(validateActionBodyCapabilities({ hooks: [hook(source)] })).toEqual([]); + }); + + it('reads a name-keyed hooks map, and leaves a non-js hook alone', () => { + const fs = validateActionBodyCapabilities({ + hooks: { + cb_stamp: { object: 'cb_ticket', events: ['beforeUpdate'], body: { language: 'js', source: WRITE } }, + cb_expr: { object: 'cb_ticket', events: ['beforeUpdate'], body: { language: 'expression', source: WRITE } }, + }, + }); + expect(fs.map((f) => f.path)).toEqual(['hooks[0].body.capabilities']); + }); + + it('the save door refuses a hook write whose body writes ungranted, and admits it granted', () => { + expect(runtimeAuthoringRulesFor('hook').map((r) => r.name)).toContain('validateActionBodyCapabilities'); + const refused = runRuntimeAuthoringRules({ type: 'hook', item: hook(WRITE, []), context: { objects: [TICKET] } }); + expect(ofRule(refused.errors, HOOK_BODY_CAPABILITY_UNDECLARED).map((e) => [e.severity, e.path])).toEqual([ + ['error', 'hooks[0].body.capabilities'], + ]); + const granted = runRuntimeAuthoringRules({ type: 'hook', item: hook(WRITE, ['api.write']), context: { objects: [TICKET] } }); + expect(ofRule(granted.errors, HOOK_BODY_CAPABILITY_UNDECLARED)).toEqual([]); + expect(granted.rulesRun).toContain('validateActionBodyCapabilities'); + }); + + it('os validate, os build and os lint refuse it the same way', () => { + const stack = { objects: [TICKET], hooks: [hook(WRITE, [])] }; + for (const command of ['validate', 'build', 'lint'] as const) { + const fs = ofRule(runAuthoringRules(command, { normalized: stack, parsed: stack }), HOOK_BODY_CAPABILITY_UNDECLARED); + expect(fs.map((f) => [f.severity, f.path]), command).toEqual([['error', 'hooks[0].body.capabilities']]); + } + }); + + it('a hook the build lowered from a handler is reported at handler, with the remedy the author can write', () => { + const lowered = { ...hook("await ctx.api.transaction(async () => {});", ['api.write']), handler: 'cb_stamp_fn' }; + const fs = validateActionBodyCapabilities({ hooks: [lowered] }, { loweredHookRefs: new Set(['cb_stamp_fn']) }); + expect(fs.map((f) => [f.rule, f.path])).toEqual([[HOOK_BODY_CAPABILITY_UNDECLARED, 'hooks[0].handler']]); + expect(fs[0].message).toContain('lowered from the inline handler'); + expect(fs[0].hint).toContain("write the hook's body with 'api.transaction'"); + }); + + it('a hook body’s ctx.email.send is refused with the remedy that works: no grant can fix it', () => { + const fs = validateActionBodyCapabilities({ hooks: [hook("await ctx.email.send({ to: ['a@b.c'] });", [])] }); + expect(fs.map((f) => f.rule)).toEqual([HOOK_BODY_CAPABILITY_UNDECLARED]); + expect(fs[0].message).toContain("never granted 'email.send'"); + expect(fs[0].hint).toContain('send mail on a record change from an action, a job or a flow'); + expect(fs[0].hint).not.toContain('Add '); + }); + + it('a hook body’s ctx.title(FIELD) needs api.read; ctx.title() needs nothing', () => { + const related = "var t = await ctx.title('account_id'); ctx.input.name = t;"; + expect(validateActionBodyCapabilities({ hooks: [hook(related, [])] }).map((f) => f.message)).toEqual([ + expect.stringContaining("ctx.title(FIELD) but its capabilities do not grant 'api.read'"), + ]); + expect(validateActionBodyCapabilities({ hooks: [hook(related, ['api.read'])] })).toEqual([]); + }); + + it('os explain has a page for the hook id', () => { + expect(explainRule(HOOK_BODY_CAPABILITY_UNDECLARED)?.paragraphs.join('\n')).toContain('body.capabilities'); + }); +}); + +describe('arm (b): the tokens besides api.write (#37815)', () => { + it.each([ + ['api.transaction', 'await ctx.api.transaction(async () => { return 1; });'], + ['email.send', "await ctx.email.send({ to: ['a@b.c'], subject: 's', text: 't' });"], + ['activity.append', "await ctx.activity.append({ object: 'cb_ticket', recordId: ctx.recordId, text: 'x' });"], + ['log', "ctx.log.info('closing');"], + ['crypto.uuid', 'var id = ctx.crypto.randomUUID();'], + ['api.read', "var n = await ctx.api.object('cb_ticket').count({});"], + ])('an action body calling the %s gate is refused without it and passes with it', (token, source) => { + const refused = validateActionBodyCapabilities({ actions: [action(source, [])] }); + expect(refused.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [ACTION_BODY_CAPABILITY_UNDECLARED, 'error', 'actions[0].body.capabilities'], + ]); + expect(refused[0].message).toContain(`'${token}'`); + expect(refused[0].hint).toBe(`Add '${token}' to the action's body.capabilities, or remove the call.`); + expect(validateActionBodyCapabilities({ actions: [action(source, [token])] })).toEqual([]); + }); + + it('the same call on a hook body is refused under the hook id', () => { + const fs = validateActionBodyCapabilities({ hooks: [hook('await ctx.api.transaction(async () => {});', ['api.write'])] }); + expect(fs.map((f) => [f.rule, f.path])).toEqual([[HOOK_BODY_CAPABILITY_UNDECLARED, 'hooks[0].body.capabilities']]); + expect(fs[0].message).toContain("'api.transaction'"); + }); + + it('one finding per missing token; a write keeps its own id and words', () => { + const source = "await ctx.api.transaction(async () => { await ctx.api.object('cb_ticket').insert({ name: 'x' }); }); ctx.log.warn('w');"; + const fs = validateActionBodyCapabilities({ actions: [action(source, ['log'])] }); + expect(fs.map((f) => f.rule)).toEqual([ACTION_BODY_WRITE_CAPABILITY_UNDECLARED, ACTION_BODY_CAPABILITY_UNDECLARED]); + expect(fs[0].message).toContain("ctx.api.object(…).insert(…) but its capabilities do not grant 'api.write'"); + expect(fs[1].message).toContain("ctx.api.transaction(…) but its capabilities do not grant 'api.transaction'"); + }); + + it('stays quiet on calls no token gates', () => { + const source = + "var r = ctx.record; var i = ctx.input; var t = ctx.title ? 1 : 0; var h = ctx.api.object('cb_ticket'); return { r, i, t, h };"; + expect(validateActionBodyCapabilities({ actions: [action(source, [])] })).toEqual([]); + }); + + it('the save door refuses an action write over a door call, and admits it granted', () => { + const source = "await ctx.activity.append({ object: 'cb_ticket', recordId: ctx.recordId, text: 'x' });"; + const refused = runRuntimeAuthoringRules({ type: 'action', item: action(source, []), context: { objects: [TICKET] } }); + expect(ofRule(refused.errors, ACTION_BODY_CAPABILITY_UNDECLARED).map((e) => e.path)).toEqual(['actions[0].body.capabilities']); + const granted = runRuntimeAuthoringRules({ type: 'action', item: action(source, ['activity.append']), context: { objects: [TICKET] } }); + expect(ofRule(granted.errors, ACTION_BODY_CAPABILITY_UNDECLARED)).toEqual([]); + }); + + it('os explain has a page for the action id', () => { + expect(explainRule(ACTION_BODY_CAPABILITY_UNDECLARED)?.paragraphs.join('\n')).toContain('api.transaction'); + }); + + describe('which calls are read', () => { + it.each([ + ['a transaction', 'await ctx.api.transaction(async () => {});', 'action', [['api.transaction', ['ctx.api.transaction(…)']]]], + ['a transaction on an alias', 'const api = ctx.api; await api.transaction(async () => {});', 'action', [['api.transaction', ['ctx.api.transaction(…)']]]], + ['every log level', "ctx.log.debug('a'); ctx.log.error('b');", 'action', [['log', ['ctx.log.debug(…)', 'ctx.log.error(…)']]]], + ['a destructured log', "const { log } = ctx; log.warn('a');", 'hook', [['log', ['ctx.log.warn(…)']]]], + ['an optional call', "ctx.log?.info?.('a');", 'action', [['log', ['ctx.log.info(…)']]]], + ['a read through a handle', "const repo = ctx.api.object('a');\nawait repo.findOne({});", 'hook', [['api.read', ['ctx.api.object(…).findOne(…)']]]], + ['ctx.title on an action body', "await ctx.title('account_id');", 'action', []], + ['ctx.title(FIELD) on a hook body', "await ctx.title('account_id');", 'hook', [['api.read', ['ctx.title(FIELD)']]]], + ['ctx.title() on a hook body', 'await ctx.title();', 'hook', []], + ['a door spelled in a string', "return 'ctx.email.send(x)';", 'action', []], + ['a door in a comment', '// ctx.activity.append({})\nreturn 1;', 'action', []], + ['another receiver', "other.log.info('a'); other.api.transaction(f);", 'action', []], + ['a reassigned alias', "let log = ctx.log; log = other; log.info('a');", 'action', []], + ['a member read, not called', 'var l = ctx.log; var c = ctx.crypto;', 'action', []], + ])('%s', (_label, source, kind, expected) => { + expect(bodyGatedCalls(source, kind as 'action' | 'hook').map((g) => [g.token, g.calls])).toEqual(expected); + }); + }); +}); From 1b364999957b0d06c8d61e85de22373583dd045a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 22:05:49 +0000 Subject: [PATCH 03/11] chore(changeset): lint body capability gates, breaking Claude-Session: https://claude.ai/code/session_01ADHkmSwS4mQyXWrddL4r6B Co-authored-by: Claude --- .../37815-body-capabilities-every-gate.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .changeset/37815-body-capabilities-every-gate.md diff --git a/.changeset/37815-body-capabilities-every-gate.md b/.changeset/37815-body-capabilities-every-gate.md new file mode 100644 index 00000000000..283cb5a8e13 --- /dev/null +++ b/.changeset/37815-body-capabilities-every-gate.md @@ -0,0 +1,27 @@ +--- +'@objectstack/lint': minor +--- + +feat(lint)!: a hook body's gated calls, and an action body's calls to every gate besides `api.write`, are refused at publish when the body is not granted the token + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: follow-up owed — skills/objectstack-ui/rules/actions.md, skills/objectstack-data/references/data-hooks.md (the two new ids and the tokens they judge; `skills/**` is outside this change) + + + +**BREAKING** for the publish of an action, an object or a hook whose L2 body calls a member the QuickJS sandbox gates without that member's token in `body.capabilities`. Such a body saved and published before; the sandbox refused the call with `403 INSUFFICIENT_PRIVILEGES` every time the body reached it, so it never worked. It is refused now, at the runtime publish door and in `os validate` / `lint` / `compile` / `build`, with the token named. The schema is unchanged and stored metadata is not rewritten or refused at boot; the refusal comes at the next publish. + +The gates are the sandbox runner's own, token by token, and the rule's list is pinned to the runner's source: the `ctx.api.object(…)` read leaves (`find`, `findOne`, `count`, `aggregate`) behind `api.read`, the write leaves behind `api.write`, `ctx.api.transaction(…)` behind `api.transaction`, `ctx.log.debug|info|warn|error(…)` behind `log`, `ctx.crypto.randomUUID()` behind `crypto.uuid`, `ctx.email.send(…)` behind `email.send`, `ctx.activity.append(…)` behind `activity.append`, and on a hook body `ctx.title(FIELD)` with an argument behind `api.read` (`ctx.title()` needs no token). + +- `hook-body-capability-undeclared` (new): an L2 hook body that calls any of those gates without its token. A hook body is never granted `email.send`, so its `ctx.email.send(…)` call is refused with the remedy that works: remove the call and send the mail from an action, a job or a flow. A hook lowered from an inline `handler` is reported at `handler`. Runs on the runtime `hook` door. +- `action-body-capability-undeclared` (new): an L2 action body that calls a gate other than the writes without its token. Runs on the runtime `action` and `object` doors. +- `action-body-write-capability-undeclared` is unchanged: an action body's write without `api.write` keeps its id and its words. + +## FROM → TO + +- Hook body (arm a). FROM: `hooks: [{ …, body: { language: 'js', source: "await ctx.api.object('task').update({ id, done: true })", capabilities: [] } }]` saved and threw at every run. TO: declare the token, `capabilities: ['api.write']`. +- Action body, other tokens (arm b). FROM: `body: { language: 'js', source: 'await ctx.api.transaction(async () => { … })', capabilities: ['api.write'] }` saved and threw at every run. TO: declare the token, `capabilities: ['api.write', 'api.transaction']` (likewise `log`, `crypto.uuid`, `email.send`, `activity.append`, `api.read` for the call the finding names). +- Hook body calling `ctx.email.send(…)`. FROM: saved and threw at every run. TO: remove the call and send the mail from an action, a job or a flow. + +`os explain hook-body-capability-undeclared` and `os explain action-body-capability-undeclared` carry an entry for each. No export of the package changes. From 3e6723acfa63c53ad0a9cb97400f06c8a7865a38 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 22:06:17 +0000 Subject: [PATCH 04/11] chore(changeset): spell the ADR-0087 disposition Claude-Session: https://claude.ai/code/session_01ADHkmSwS4mQyXWrddL4r6B Co-authored-by: Claude --- .changeset/37815-body-capabilities-every-gate.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/37815-body-capabilities-every-gate.md b/.changeset/37815-body-capabilities-every-gate.md index 283cb5a8e13..a9fb2551a58 100644 --- a/.changeset/37815-body-capabilities-every-gate.md +++ b/.changeset/37815-body-capabilities-every-gate.md @@ -8,7 +8,7 @@ Clause-②: no (narrowing) Metadata-protocol: narrowed Skills-docs: follow-up owed — skills/objectstack-ui/rules/actions.md, skills/objectstack-data/references/data-hooks.md (the two new ids and the tokens they judge; `skills/**` is outside this change) - + **BREAKING** for the publish of an action, an object or a hook whose L2 body calls a member the QuickJS sandbox gates without that member's token in `body.capabilities`. Such a body saved and published before; the sandbox refused the call with `403 INSUFFICIENT_PRIVILEGES` every time the body reached it, so it never worked. It is refused now, at the runtime publish door and in `os validate` / `lint` / `compile` / `build`, with the token named. The schema is unchanged and stored metadata is not rewritten or refused at boot; the refusal comes at the next publish. From bac75a914f1a14ecca591bf443746b04b3754482 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 22:10:06 +0000 Subject: [PATCH 05/11] fix(lint): the action explanation's covers line fits the rule line Claude-Session: https://claude.ai/code/session_01ADHkmSwS4mQyXWrddL4r6B Co-authored-by: Claude --- packages/lint/src/rule-explanations.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 2b47ce7d775..b0aef7000de 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -1544,7 +1544,7 @@ const BODY_GATES_READING = const ACTION_BODY_CAPABILITY_UNDECLARED_EXPLANATION: RuleExplanation = { rule: 'action-body-capability-undeclared', - covers: 'the grant a script action body\'s gated calls need, other than its writes', + covers: 'the grant an action body\'s other gated calls need', paragraphs: [ 'A script action body runs in the QuickJS sandbox with only the capabilities its `body.capabilities` ' + 'lists (none by default). ' + BODY_GATES_PARAGRAPH + ' The action answers that refusal every time it ' + From dd3365285e5402ee67c02f5ba12af9ab659a97a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 22:54:28 +0000 Subject: [PATCH 06/11] feat(lint,spec,cli)!: the upgrade-guide entry, the barrel export, and os build infers api.transaction Claude-Session: https://claude.ai/code/session_01ADHkmSwS4mQyXWrddL4r6B Co-authored-by: Claude --- .../37815-body-capabilities-every-gate.md | 10 ++-- packages/cli/src/utils/extract-hook-body.ts | 10 +++- packages/cli/test/extract-hook-body.test.ts | 23 +++++++++ packages/lint/src/index.ts | 6 ++- ...capabilities.hook-and-tokens-37815.test.ts | 6 ++- ...odies-calling-an-ungranted-gate-refused.ts | 49 +++++++++++++++++++ 6 files changed, 96 insertions(+), 8 deletions(-) create mode 100644 packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts diff --git a/.changeset/37815-body-capabilities-every-gate.md b/.changeset/37815-body-capabilities-every-gate.md index a9fb2551a58..13699fb5abf 100644 --- a/.changeset/37815-body-capabilities-every-gate.md +++ b/.changeset/37815-body-capabilities-every-gate.md @@ -1,14 +1,16 @@ --- '@objectstack/lint': minor +'@objectstack/spec': patch +'@objectstack/cli': patch --- feat(lint)!: a hook body's gated calls, and an action body's calls to every gate besides `api.write`, are refused at publish when the body is not granted the token Clause-②: no (narrowing) Metadata-protocol: narrowed -Skills-docs: follow-up owed — skills/objectstack-ui/rules/actions.md, skills/objectstack-data/references/data-hooks.md (the two new ids and the tokens they judge; `skills/**` is outside this change) +Skills-docs: follow-up owed — skills/objectstack-ui/rules/actions.md, skills/objectstack-data/references/data-hooks.md - + **BREAKING** for the publish of an action, an object or a hook whose L2 body calls a member the QuickJS sandbox gates without that member's token in `body.capabilities`. Such a body saved and published before; the sandbox refused the call with `403 INSUFFICIENT_PRIVILEGES` every time the body reached it, so it never worked. It is refused now, at the runtime publish door and in `os validate` / `lint` / `compile` / `build`, with the token named. The schema is unchanged and stored metadata is not rewritten or refused at boot; the refusal comes at the next publish. @@ -24,4 +26,6 @@ The gates are the sandbox runner's own, token by token, and the rule's list is p - Action body, other tokens (arm b). FROM: `body: { language: 'js', source: 'await ctx.api.transaction(async () => { … })', capabilities: ['api.write'] }` saved and threw at every run. TO: declare the token, `capabilities: ['api.write', 'api.transaction']` (likewise `log`, `crypto.uuid`, `email.send`, `activity.append`, `api.read` for the call the finding names). - Hook body calling `ctx.email.send(…)`. FROM: saved and threw at every run. TO: remove the call and send the mail from an action, a job or a flow. -`os explain hook-body-capability-undeclared` and `os explain action-body-capability-undeclared` carry an entry for each. No export of the package changes. +`os build` now infers `api.transaction` for a handler that calls `ctx.api.transaction(…)` (directly or through an alias of `ctx.api`). Before, such a handler was lowered without the grant and the sandbox refused the transaction at every run. + +`os explain hook-body-capability-undeclared` and `os explain action-body-capability-undeclared` carry an entry for each. `@objectstack/lint` exports the two rule id constants, `ACTION_BODY_CAPABILITY_UNDECLARED` and `HOOK_BODY_CAPABILITY_UNDECLARED`. `@objectstack/spec` adds only the upgrade-guide entry `hook-and-action-bodies-calling-an-ungranted-gate-refused`. diff --git a/packages/cli/src/utils/extract-hook-body.ts b/packages/cli/src/utils/extract-hook-body.ts index 0efa13cd7ed..a47b9bb3f89 100644 --- a/packages/cli/src/utils/extract-hook-body.ts +++ b/packages/cli/src/utils/extract-hook-body.ts @@ -505,7 +505,7 @@ const FORBIDDEN_PATTERNS: Array<{ rx: RegExp; reason: string; face?: LoweringFac }, ]; -const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append' }> = [ +const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append' }> = [ // Match `ctx.api.object(...)` directly OR a local alias like // `const api = ctx.api;` then `api.object(...)`. We accept any // identifier (or chain) ending in `.object(...)` followed by a known @@ -523,6 +523,12 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | ' // capability from a call that always threw is what let `os build` bless a // dead body — the inference was the amplifier, not the safety net. { rx: /ctx\.log\.(?:info|warn|error|debug)\b/, cap: 'log' }, + // [#37815] `ctx.api.transaction(fn)`, the body's transaction route, behind + // `api.transaction`. Receiver-loose like the `.object(…)` patterns: an alias + // of `ctx.api` or a rebound context reaches it as `api.transaction(…)`. With + // no pattern a handler calling it lowered without the grant, and the sandbox + // refused the transaction at every run. + { rx: /\.\s*transaction\s*(?:\?\.\s*)?\(/, cap: 'api.transaction' }, // [#11293] `ctx.title(field)` — the RELATED-record form, and only that form. // `ctx.title()` resolves this record's title (formula included) from the // state the hook is already firing on — no read over its own columns, and @@ -609,7 +615,7 @@ export interface ExtractedBody { * is retired (see this file's header). An author whose needs differ from what * inference derives writes `body.capabilities` on the hook instead. */ - capabilities: Array<'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>; + capabilities: Array<'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>; /** True when source is a single expression (arrow with implicit return). */ isExpression: boolean; } diff --git a/packages/cli/test/extract-hook-body.test.ts b/packages/cli/test/extract-hook-body.test.ts index 0d20d642f81..028b0109ea1 100644 --- a/packages/cli/test/extract-hook-body.test.ts +++ b/packages/cli/test/extract-hook-body.test.ts @@ -110,6 +110,29 @@ describe('extractHookBody', () => { expect(extractHookBody(fn, 'hook d').capabilities).toContain('log'); }); + // [#37815] The publish check reads `ctx.api.transaction(…)` against + // `api.transaction`; a handler the build lowers must carry the grant it calls. + it.each([ + ['ctx.api', async (ctx: any) => { + await ctx.api.transaction(async () => { + await ctx.api.object('foo').insert({ name: 'x' }); + }); + }], + ['an alias of ctx.api', async (ctx: any) => { + const api = ctx.api; + await api.transaction(async () => api.object('foo').insert({ name: 'x' })); + }], + ])('infers api.transaction through %s', (_shape, fn) => { + expect(extractHookBody(fn, 'hook tx').capabilities).toEqual(['api.transaction', 'api.write']); + }); + + it('infers no api.transaction from a body that never calls it (control)', () => { + const fn = async (ctx: any) => { + await ctx.api.object('foo').insert({ name: 'transaction' }); + }; + expect(extractHookBody(fn, 'hook no tx').capabilities).toEqual(['api.write']); + }); + it('rejects fetch()', () => { const fn = async (_ctx: any) => { await fetch('https://example.com'); diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 57f1d56abef..d693881b5d6 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -1164,7 +1164,11 @@ export { // `os explain` can carry an entry for each (the explanation table holds an // entry only for an id the barrel exports). The rules themselves run through // the registry and are not exported. -export { ACTION_BODY_WRITE_CAPABILITY_UNDECLARED } from './validate-action-body-capabilities.js'; +export { + ACTION_BODY_WRITE_CAPABILITY_UNDECLARED, + ACTION_BODY_CAPABILITY_UNDECLARED, + HOOK_BODY_CAPABILITY_UNDECLARED, +} from './validate-action-body-capabilities.js'; export { SEED_RECORD_UNKNOWN_FIELD } from './validate-seed-record-keys.js'; // [#35143] The Views, dashboards and app shell family's app-shell ids, all // advisory, exported for `os explain` as the two above; the rules run through diff --git a/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts b/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts index 500921f0909..b543e230f7f 100644 --- a/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts +++ b/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts @@ -147,11 +147,13 @@ describe('arm (a): a hook body is judged like an action body (#37815)', () => { }); it('a hook the build lowered from a handler is reported at handler, with the remedy the author can write', () => { - const lowered = { ...hook("await ctx.api.transaction(async () => {});", ['api.write']), handler: 'cb_stamp_fn' }; + // A read through a bound handle: a shape the build's inference does not read. + const source = "const repo = ctx.api.object('cb_ticket');\nreturn repo.findOne({});"; + const lowered = { ...hook(source, []), handler: 'cb_stamp_fn' }; const fs = validateActionBodyCapabilities({ hooks: [lowered] }, { loweredHookRefs: new Set(['cb_stamp_fn']) }); expect(fs.map((f) => [f.rule, f.path])).toEqual([[HOOK_BODY_CAPABILITY_UNDECLARED, 'hooks[0].handler']]); expect(fs[0].message).toContain('lowered from the inline handler'); - expect(fs[0].hint).toContain("write the hook's body with 'api.transaction'"); + expect(fs[0].hint).toContain("write the hook's body with 'api.read'"); }); it('a hook body’s ctx.email.send is refused with the remedy that works: no grant can fix it', () => { diff --git a/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts b/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts new file mode 100644 index 00000000000..fcade23b5da --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts @@ -0,0 +1,49 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #37815 — an L2 hook body that calls a member the QuickJS sandbox gates +// without that member's token in `body.capabilities`, and an L2 action body +// that does so for a token other than `api.write`, are refused at error as +// `hook-body-capability-undeclared` / `action-body-capability-undeclared` +// (@objectstack/lint), the check `action-body-write-capability-undeclared` +// already makes for an action body's writes. It narrows what the authoring +// doors accept; no key is removed, so there is no tombstone. Measured +// first-party exposure at this change: zero (example apps, platform objects). +// Not converted: whether the body should hold the grant or drop the call is +// the author's choice. +export const entry: SemanticMigration = { + id: 'hook-and-action-bodies-calling-an-ungranted-gate-refused', + surface: + 'hooks[].body and actions[].body (an object\'s inline actions[] included) whose body.language is js, on a hook ' + + 'or action saved or published through the metadata doors (PUT /api/v1/meta/hook/NAME, PUT ' + + '/api/v1/meta/action/NAME, an object write, POST /api/v1/packages/PKG/publish-drafts and the per-item publish) ' + + 'or loaded by os validate / os build / os lint, a hook body lowered from an inline handler included: a source ' + + 'that calls a member the sandbox gates without its token in body.capabilities. The gates: the ' + + 'ctx.api.object(…) read leaves (api.read), its write leaves (api.write), ctx.api.transaction (api.transaction), ' + + 'ctx.log.debug / info / warn / error (log), ctx.crypto.randomUUID (crypto.uuid), ctx.email.send (email.send), ' + + 'ctx.activity.append (activity.append), and on a hook body ctx.title(FIELD) with an argument (api.read)', + replacement: + 'Add the token the finding names to the body\'s capabilities (body.capabilities: [\'api.write\', ' + + '\'api.transaction\'] for a body that writes inside ctx.api.transaction), or remove the call. A hook body is ' + + 'never granted email.send: remove its ctx.email.send call and send the mail from an action, a job or a flow. ' + + 'Refused at error as `hook-body-capability-undeclared` or `action-body-capability-undeclared` (422 ' + + 'INVALID_METADATA at the hook and action doors); an action body\'s write without api.write stays ' + + '`action-body-write-capability-undeclared`.', + reason: + 'The sandbox installs each gated member behind its token and refuses a call the body was not granted with 403 ' + + 'INSUFFICIENT_PRIVILEGES at the call site. Every authoring door accepted such a body (only an action body\'s ' + + 'writes were judged), so it deployed clean and then failed at the call every time the hook or action reached ' + + 'it; under a hook\'s default onError abort, the write that ran the hook failed with it. The rule reads the ' + + 'source with strings and comments blanked, without parsing or running it, and judges exactly the gates the ' + + 'sandbox runner installs. os build now also infers api.transaction for a handler that calls ' + + 'ctx.api.transaction, so a lowered handler carries the grant it calls. Stored metadata is not rewritten or ' + + 'refused at boot; the next publish of the hook, action or object is refused with the token named. Such a call ' + + 'never succeeded, so no stored row changes shape. There is no mechanical rewrite: granting a token widens what ' + + 'the body may do, which is the author\'s decision.', + acceptanceCriteria: + 'Load every hook and action (`os validate` or `os build`): no `hook-body-capability-undeclared` finding at ' + + 'hooks[N].body.capabilities or hooks[N].handler, and no `action-body-capability-undeclared` finding at ' + + 'actions[N].body.capabilities. PUT /api/v1/meta/hook/NAME and PUT /api/v1/meta/action/NAME with each such body ' + + 'granted or corrected answer 200, and the call runs instead of answering 403.', +}; From ecf68e3e42fe86dbf9f313a553e1009ee28c75be Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 23:54:09 +0000 Subject: [PATCH 07/11] feat(lint)!: the hook arm judges authored hook bodies only; the extractor stays as on main Route C (claim amendment 2): a hook body lowered from an inline handler by os build / os verify is no longer judged by hook-body-capability-undeclared, since its grant is the build's inference; the lowered reading waits on the extractor. extract-hook-body.ts and its test are back to origin/main, and the cli changeset line is dropped. The upgrade-guide entry, the changeset rows, the explanation and the docs row say authored hook bodies only. Claude-Session: https://claude.ai/code/session_01ADHkmSwS4mQyXWrddL4r6B Co-authored-by: Claude --- .../37815-body-capabilities-every-gate.md | 11 ++--- .../docs/deployment/validating-metadata.mdx | 2 +- packages/cli/src/utils/extract-hook-body.ts | 10 +--- packages/cli/test/extract-hook-body.test.ts | 23 --------- packages/lint/src/rule-explanations.ts | 5 +- ...capabilities.hook-and-tokens-37815.test.ts | 43 +++++++++++++---- .../src/validate-action-body-capabilities.ts | 47 ++++++++++++------- ...odies-calling-an-ungranted-gate-refused.ts | 11 +++-- 8 files changed, 82 insertions(+), 70 deletions(-) diff --git a/.changeset/37815-body-capabilities-every-gate.md b/.changeset/37815-body-capabilities-every-gate.md index 13699fb5abf..b2b299a4d77 100644 --- a/.changeset/37815-body-capabilities-every-gate.md +++ b/.changeset/37815-body-capabilities-every-gate.md @@ -1,7 +1,6 @@ --- '@objectstack/lint': minor '@objectstack/spec': patch -'@objectstack/cli': patch --- feat(lint)!: a hook body's gated calls, and an action body's calls to every gate besides `api.write`, are refused at publish when the body is not granted the token @@ -12,20 +11,20 @@ Skills-docs: follow-up owed — skills/objectstack-ui/rules/actions.md, skills/o -**BREAKING** for the publish of an action, an object or a hook whose L2 body calls a member the QuickJS sandbox gates without that member's token in `body.capabilities`. Such a body saved and published before; the sandbox refused the call with `403 INSUFFICIENT_PRIVILEGES` every time the body reached it, so it never worked. It is refused now, at the runtime publish door and in `os validate` / `lint` / `compile` / `build`, with the token named. The schema is unchanged and stored metadata is not rewritten or refused at boot; the refusal comes at the next publish. +**BREAKING** for the publish of an action, an object or a hook whose L2 body (on a hook, an authored body) calls a member the QuickJS sandbox gates without that member's token in `body.capabilities`. Such a body saved and published before; the sandbox refused the call with `403 INSUFFICIENT_PRIVILEGES` every time the body reached it, so it never worked. It is refused now, at the runtime publish door and in `os validate` / `lint` / `compile` / `build`, with the token named. The schema is unchanged and stored metadata is not rewritten or refused at boot; the refusal comes at the next publish. The gates are the sandbox runner's own, token by token, and the rule's list is pinned to the runner's source: the `ctx.api.object(…)` read leaves (`find`, `findOne`, `count`, `aggregate`) behind `api.read`, the write leaves behind `api.write`, `ctx.api.transaction(…)` behind `api.transaction`, `ctx.log.debug|info|warn|error(…)` behind `log`, `ctx.crypto.randomUUID()` behind `crypto.uuid`, `ctx.email.send(…)` behind `email.send`, `ctx.activity.append(…)` behind `activity.append`, and on a hook body `ctx.title(FIELD)` with an argument behind `api.read` (`ctx.title()` needs no token). -- `hook-body-capability-undeclared` (new): an L2 hook body that calls any of those gates without its token. A hook body is never granted `email.send`, so its `ctx.email.send(…)` call is refused with the remedy that works: remove the call and send the mail from an action, a job or a flow. A hook lowered from an inline `handler` is reported at `handler`. Runs on the runtime `hook` door. +- `hook-body-capability-undeclared` (new): an authored L2 hook body that calls any of those gates without its token. A hook body is never granted `email.send`, so its `ctx.email.send(…)` call is refused with the remedy that works: remove the call and send the mail from an action, a job or a flow. Only a body the author wrote is judged: a hook body `os build` / `os verify` lowered from an inline `handler` is not, since its grant is the build's inference (the lowered reading is #38653). Runs on the runtime `hook` door. - `action-body-capability-undeclared` (new): an L2 action body that calls a gate other than the writes without its token. Runs on the runtime `action` and `object` doors. - `action-body-write-capability-undeclared` is unchanged: an action body's write without `api.write` keeps its id and its words. ## FROM → TO -- Hook body (arm a). FROM: `hooks: [{ …, body: { language: 'js', source: "await ctx.api.object('task').update({ id, done: true })", capabilities: [] } }]` saved and threw at every run. TO: declare the token, `capabilities: ['api.write']`. +- Authored hook body (arm a). FROM: `hooks: [{ …, body: { language: 'js', source: "await ctx.api.object('task').update({ id, done: true })", capabilities: [] } }]` saved and threw at every run. TO: declare the token, `capabilities: ['api.write']`. - Action body, other tokens (arm b). FROM: `body: { language: 'js', source: 'await ctx.api.transaction(async () => { … })', capabilities: ['api.write'] }` saved and threw at every run. TO: declare the token, `capabilities: ['api.write', 'api.transaction']` (likewise `log`, `crypto.uuid`, `email.send`, `activity.append`, `api.read` for the call the finding names). -- Hook body calling `ctx.email.send(…)`. FROM: saved and threw at every run. TO: remove the call and send the mail from an action, a job or a flow. +- Authored hook body calling `ctx.email.send(…)`. FROM: saved and threw at every run. TO: remove the call and send the mail from an action, a job or a flow. -`os build` now infers `api.transaction` for a handler that calls `ctx.api.transaction(…)` (directly or through an alias of `ctx.api`). Before, such a handler was lowered without the grant and the sandbox refused the transaction at every run. +A hook whose body was lowered from an inline `handler` is unchanged: FROM and TO alike, it is not judged by this rule. `os explain hook-body-capability-undeclared` and `os explain action-body-capability-undeclared` carry an entry for each. `@objectstack/lint` exports the two rule id constants, `ACTION_BODY_CAPABILITY_UNDECLARED` and `HOOK_BODY_CAPABILITY_UNDECLARED`. `@objectstack/spec` adds only the upgrade-guide entry `hook-and-action-bodies-calling-an-ungranted-gate-refused`. diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index caff21da758..3d28e549154 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -526,7 +526,7 @@ orthogonal to both, and no cell here can carry it; it is written out in | Seed record keys — a seed record key, or a seed `columns` key, that names no field of the dataset's object, no system column injected on it and none of `id` / `created_at` / `updated_at`; the engine's insert door refuses such a record and the seed load loads the rest (`seed-record-unknown-field`, #35143) | ✓ | ✓ | ✓ | ✓ˢ | | Script action bodies hold every other grant they call — an L2 action body that calls a member the sandbox gates behind a token other than `api.write` without that token in its `body.capabilities`: a `ctx.api.object(…)` read leaf (`api.read`), `ctx.api.transaction(…)` (`api.transaction`), `ctx.log.*` (`log`), `ctx.crypto.randomUUID()` (`crypto.uuid`), `ctx.email.send(…)` (`email.send`) or `ctx.activity.append(…)` (`activity.append`), each refused by the sandbox at every call (`action-body-capability-undeclared`, #37815) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | | Hook and job bodies compile in the runtime's wrapper — an L2 hook or job `body.source` that does not compile as the body of `(async (ctx) => { … })`, most often `const ctx = …` redeclaring the parameter or one name declared twice; no door publishes a job, so the publish column is the `hook` write alone (`hook-body-does-not-compile`, `job-body-does-not-compile`, #34987) | ✓ | ✓ | ✓ | ✓ʰ | -| Hook bodies hold the grant they call — an L2 hook body that calls a member the sandbox gates without its token in `body.capabilities`: a `ctx.api.object(…)` read or write leaf, `ctx.api.transaction(…)`, `ctx.log.*`, `ctx.crypto.randomUUID()`, `ctx.activity.append(…)` or the related-record form `ctx.title(FIELD)`, each refused by the sandbox at every call; and any `ctx.email.send(…)`, which a hook body is never granted (`hook-body-capability-undeclared`, #37815) | ✓ | ✓ | ✓ | ✓ʰ | +| Hook bodies hold the grant they call — an authored L2 hook body (one `os build` lowered from a `handler` is not judged) that calls a member the sandbox gates without its token in `body.capabilities`: a `ctx.api.object(…)` read or write leaf, `ctx.api.transaction(…)`, `ctx.log.*`, `ctx.crypto.randomUUID()`, `ctx.activity.append(…)` or the related-record form `ctx.title(FIELD)`, each refused by the sandbox at every call; and any `ctx.email.send(…)`, which a hook body is never granted (`hook-body-capability-undeclared`, #37815) | ✓ | ✓ | ✓ | ✓ʰ | | Approval-node approvers (ADR-0090 D3) | ✓ | ✓ | ✓ | ✓ᶠ | | Security posture (ADR-0090 — e.g. every custom object declares `sharingModel`) | ✓ | ✓ | ✓ | ✓ˢᵖᵉᵇᵒ | | Security vocabulary freeze (ADR-0090 D3 — the reserved word, replaced by `permission_set` / `position` / `business_unit`) | ✓ | ✓ | ✓ | ✓ᵒᵖᵉᵇᵖᵒᵃᵒˣ | diff --git a/packages/cli/src/utils/extract-hook-body.ts b/packages/cli/src/utils/extract-hook-body.ts index a47b9bb3f89..0efa13cd7ed 100644 --- a/packages/cli/src/utils/extract-hook-body.ts +++ b/packages/cli/src/utils/extract-hook-body.ts @@ -505,7 +505,7 @@ const FORBIDDEN_PATTERNS: Array<{ rx: RegExp; reason: string; face?: LoweringFac }, ]; -const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append' }> = [ +const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append' }> = [ // Match `ctx.api.object(...)` directly OR a local alias like // `const api = ctx.api;` then `api.object(...)`. We accept any // identifier (or chain) ending in `.object(...)` followed by a known @@ -523,12 +523,6 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | ' // capability from a call that always threw is what let `os build` bless a // dead body — the inference was the amplifier, not the safety net. { rx: /ctx\.log\.(?:info|warn|error|debug)\b/, cap: 'log' }, - // [#37815] `ctx.api.transaction(fn)`, the body's transaction route, behind - // `api.transaction`. Receiver-loose like the `.object(…)` patterns: an alias - // of `ctx.api` or a rebound context reaches it as `api.transaction(…)`. With - // no pattern a handler calling it lowered without the grant, and the sandbox - // refused the transaction at every run. - { rx: /\.\s*transaction\s*(?:\?\.\s*)?\(/, cap: 'api.transaction' }, // [#11293] `ctx.title(field)` — the RELATED-record form, and only that form. // `ctx.title()` resolves this record's title (formula included) from the // state the hook is already firing on — no read over its own columns, and @@ -615,7 +609,7 @@ export interface ExtractedBody { * is retired (see this file's header). An author whose needs differ from what * inference derives writes `body.capabilities` on the hook instead. */ - capabilities: Array<'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>; + capabilities: Array<'api.read' | 'api.write' | 'crypto.uuid' | 'log' | 'email.send' | 'activity.append'>; /** True when source is a single expression (arrow with implicit return). */ isExpression: boolean; } diff --git a/packages/cli/test/extract-hook-body.test.ts b/packages/cli/test/extract-hook-body.test.ts index 028b0109ea1..0d20d642f81 100644 --- a/packages/cli/test/extract-hook-body.test.ts +++ b/packages/cli/test/extract-hook-body.test.ts @@ -110,29 +110,6 @@ describe('extractHookBody', () => { expect(extractHookBody(fn, 'hook d').capabilities).toContain('log'); }); - // [#37815] The publish check reads `ctx.api.transaction(…)` against - // `api.transaction`; a handler the build lowers must carry the grant it calls. - it.each([ - ['ctx.api', async (ctx: any) => { - await ctx.api.transaction(async () => { - await ctx.api.object('foo').insert({ name: 'x' }); - }); - }], - ['an alias of ctx.api', async (ctx: any) => { - const api = ctx.api; - await api.transaction(async () => api.object('foo').insert({ name: 'x' })); - }], - ])('infers api.transaction through %s', (_shape, fn) => { - expect(extractHookBody(fn, 'hook tx').capabilities).toEqual(['api.transaction', 'api.write']); - }); - - it('infers no api.transaction from a body that never calls it (control)', () => { - const fn = async (ctx: any) => { - await ctx.api.object('foo').insert({ name: 'transaction' }); - }; - expect(extractHookBody(fn, 'hook no tx').capabilities).toEqual(['api.write']); - }); - it('rejects fetch()', () => { const fn = async (_ctx: any) => { await fetch('https://example.com'); diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index b0aef7000de..59b719e2892 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -1566,9 +1566,8 @@ const HOOK_BODY_CAPABILITY_UNDECLARED_EXPLANATION: RuleExplanation = { BODY_GATES_READING, 'To fix it, add the token the message names to the hook\'s `body.capabilities`, or remove the call. A hook ' + 'body is never granted `email.send`, because a message cannot be taken back if the write that runs the ' + - 'hook rolls back: remove the `ctx.email.send` call and send the mail from an action, a job or a flow. A ' + - 'hook the build lowered from an inline `handler` is reported at `handler`: the build grants it only the ' + - 'tokens it infers from the handler\'s calls, so write the hook\'s `body` with the grant instead.', + 'hook rolls back: remove the `ctx.email.send` call and send the mail from an action, a job or a flow. ' + + 'Only a body the author wrote is judged: a hook body the build lowered from an inline `handler` is not.', ], }; diff --git a/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts b/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts index b543e230f7f..39f2576591c 100644 --- a/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts +++ b/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts @@ -17,6 +17,7 @@ import { SANDBOX_CAPABILITY_GATES, SANDBOX_LOG_LEVELS, bodyGatedCalls, + isLoweredHandlerBody, validateActionBodyCapabilities, } from './validate-action-body-capabilities.js'; import { runAuthoringRules } from './authoring-rules.js'; @@ -146,14 +147,40 @@ describe('arm (a): a hook body is judged like an action body (#37815)', () => { } }); - it('a hook the build lowered from a handler is reported at handler, with the remedy the author can write', () => { - // A read through a bound handle: a shape the build's inference does not read. - const source = "const repo = ctx.api.object('cb_ticket');\nreturn repo.findOne({});"; - const lowered = { ...hook(source, []), handler: 'cb_stamp_fn' }; - const fs = validateActionBodyCapabilities({ hooks: [lowered] }, { loweredHookRefs: new Set(['cb_stamp_fn']) }); - expect(fs.map((f) => [f.rule, f.path])).toEqual([[HOOK_BODY_CAPABILITY_UNDECLARED, 'hooks[0].handler']]); - expect(fs[0].message).toContain('lowered from the inline handler'); - expect(fs[0].hint).toContain("write the hook's body with 'api.read'"); + describe('authored hook bodies only: a body lowered from a handler is not judged (#37815 route C)', () => { + // A read through a bound handle: a shape the build's inference does not read (#38653). + const READ = "const repo = ctx.api.object('cb_ticket');\nreturn repo.findOne({});"; + const lowered = { ...hook(READ, []), handler: 'cb_stamp_fn' }; + + it('an authored body with the call is refused', () => { + const fs = validateActionBodyCapabilities({ hooks: [hook(READ, [])] }, { loweredHookRefs: new Set(['cb_stamp_fn']) }); + expect(fs.map((f) => [f.rule, f.path])).toEqual([[HOOK_BODY_CAPABILITY_UNDECLARED, 'hooks[0].body.capabilities']]); + expect(fs[0].message).toContain("'api.read'"); + }); + + it('the same body lowered by os build / os validate / os verify is not judged', () => { + expect(isLoweredHandlerBody(lowered, { loweredHookRefs: new Set(['cb_stamp_fn']) })).toBe(true); + expect(validateActionBodyCapabilities({ hooks: [lowered] }, { loweredHookRefs: new Set(['cb_stamp_fn']) })).toEqual([]); + const stack = { objects: [TICKET], hooks: [lowered] }; + for (const command of ['validate', 'build', 'lint'] as const) { + const run = { normalized: stack, parsed: stack, loweredHookRefs: new Set(['cb_stamp_fn']) }; + expect(ofRule(runAuthoringRules(command, run), HOOK_BODY_CAPABILITY_UNDECLARED), command).toEqual([]); + } + }); + + it('a string handler the build did not lower leaves the authored body judged', () => { + const fs = validateActionBodyCapabilities({ hooks: [lowered] }, { loweredHookRefs: new Set(['other_fn']) }); + expect(fs.map((f) => f.path)).toEqual(['hooks[0].body.capabilities']); + }); + + it('the save door, which hands no lowered refs, does not judge a build artifact’s lowered body', () => { + const artifact = runRuntimeAuthoringRules({ type: 'hook', item: lowered, context: { objects: [TICKET] } }); + expect(ofRule(artifact.errors, HOOK_BODY_CAPABILITY_UNDECLARED)).toEqual([]); + const authored = runRuntimeAuthoringRules({ type: 'hook', item: hook(READ, []), context: { objects: [TICKET] } }); + expect(ofRule(authored.errors, HOOK_BODY_CAPABILITY_UNDECLARED).map((e) => e.path)).toEqual([ + 'hooks[0].body.capabilities', + ]); + }); }); it('a hook body’s ctx.email.send is refused with the remedy that works: no grant can fix it', () => { diff --git a/packages/lint/src/validate-action-body-capabilities.ts b/packages/lint/src/validate-action-body-capabilities.ts index 27ee34c6f42..2917a03ac8b 100644 --- a/packages/lint/src/validate-action-body-capabilities.ts +++ b/packages/lint/src/validate-action-body-capabilities.ts @@ -82,14 +82,15 @@ * back), so a hook's `ctx.email.send` call is refused with the remedy that * works: remove the call and send the mail from an action, a job or a flow. * - * A hook `os build` / `os validate` lowered from an inline handler is - * reported at `hooks[i].handler`, the key the author wrote - * (`hookBodyFindingLocation`); its grant is the build's inference, so the hint - * names the body the author can write instead. + * Authored hook bodies only. A hook body `os build` / `os verify` lowered + * from an inline handler is not judged: its grant is the build's inference, + * which does not yet read every gated shape (no `api.transaction`, no read + * through a bound handle), so a finding there would name a grant the handler + * author cannot write. {@link isLoweredHandlerBody} tells the two apart; the + * lowered reading waits on the extractor (#38653). */ import { collectActionBodies } from './validate-action-body-writes.js'; -import { hookBodyFindingLocation } from './validate-hook-body-writes.js'; import { recordsOf } from './object-graph.js'; type AnyRec = Record; @@ -366,11 +367,30 @@ function refusalClause(token: string, kind: BodyKind): string { return `so the sandbox refuses the call (403 INSUFFICIENT_PRIVILEGES) every time the ${kind} reaches it${lost}.`; } +/** + * Whether a hook's body is one the build lowered from its handler rather than + * one the author wrote (#37815, authored bodies only). Lowering replaces an + * inline handler with the string ref it registers and adds the body beside it, + * so the body was lowered when the hook carries a string `handler`: under + * `os build` / `os validate` / `os verify` exactly when `ctx.loweredHookRefs` + * holds that ref, and at a door that hands no `loweredHookRefs` (the runtime + * publish doors) whenever a string `handler` sits beside the body, the shape + * a build artifact carries. A missed finding, never a false one. + */ +export function isLoweredHandlerBody( + hook: AnyRec, + ctx: { loweredHookRefs?: ReadonlySet } | undefined, +): boolean { + const ref = hook.handler; + if (typeof ref !== 'string' || ref === '') return false; + return ctx?.loweredHookRefs ? ctx.loweredHookRefs.has(ref) : true; +} + /** * Every L2 action body, and every L2 hook body, that calls a member the * sandbox gates without granting itself the member's token (the header lists - * the gates and the ids). `ctx.loweredHookRefs` locates a hook the build - * lowered from an inline `handler` at `hooks[i].handler`. + * the gates and the ids). A hook body lowered from an inline `handler` is + * skipped ({@link isLoweredHandlerBody}). */ export function validateActionBodyCapabilities( stack: AnyRec, @@ -413,9 +433,8 @@ export function validateActionBodyCapabilities( const source = body.source; if (typeof source !== 'string' || source.trim() === '') return; const granted: readonly unknown[] = Array.isArray(body.capabilities) ? body.capabilities : []; + if (isLoweredHandlerBody(hook, ctx)) return; const name = typeof hook.name === 'string' && hook.name ? hook.name : `#${index}`; - const loc = hookBodyFindingLocation(hook, index, ctx); - const lowered = loc.path !== `hooks[${index}].body.source`; for (const { token, calls } of bodyGatedCalls(source, 'hook')) { if (granted.includes(token)) continue; const listed = calls.join(', '); @@ -424,19 +443,15 @@ export function validateActionBodyCapabilities( severity: 'error', rule: HOOK_BODY_CAPABILITY_UNDECLARED, where: `hook "${name}" › body`, - path: lowered ? loc.path : `hooks[${index}].body.capabilities`, + path: `hooks[${index}].body.capabilities`, message: (mail ? `body calls ${listed}, and a hook body is never granted 'email.send' (a message cannot be taken back ` + "if the write that runs the hook rolls back), so the sandbox refuses the call every time the hook reaches it, and no mail is sent." - : `body calls ${listed} but its capabilities do not grant '${token}', ${refusalClause(token, 'hook')}`) + - loc.messageSuffix, + : `body calls ${listed} but its capabilities do not grant '${token}', ${refusalClause(token, 'hook')}`), hint: mail ? 'Remove the ctx.email.send call, and send mail on a record change from an action, a job or a flow.' - : lowered - ? `The build grants a handler only the tokens it infers from the handler's calls, and it did not infer '${token}' ` + - `here: write the hook's body with '${token}' in body.capabilities instead of the handler, or remove the call.` - : `Add '${token}' to the hook's body.capabilities, or remove the call.`, + : `Add '${token}' to the hook's body.capabilities, or remove the call.`, }); } }); diff --git a/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts b/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts index fcade23b5da..813710eacfe 100644 --- a/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts +++ b/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts @@ -2,7 +2,7 @@ import type { SemanticMigration } from '../../types.js'; -// #37815 — an L2 hook body that calls a member the QuickJS sandbox gates +// #37815 — an authored L2 hook body that calls a member the QuickJS sandbox gates // without that member's token in `body.capabilities`, and an L2 action body // that does so for a token other than `api.write`, are refused at error as // `hook-body-capability-undeclared` / `action-body-capability-undeclared` @@ -18,7 +18,8 @@ export const entry: SemanticMigration = { 'hooks[].body and actions[].body (an object\'s inline actions[] included) whose body.language is js, on a hook ' + 'or action saved or published through the metadata doors (PUT /api/v1/meta/hook/NAME, PUT ' + '/api/v1/meta/action/NAME, an object write, POST /api/v1/packages/PKG/publish-drafts and the per-item publish) ' - + 'or loaded by os validate / os build / os lint, a hook body lowered from an inline handler included: a source ' + + 'or loaded by os validate / os build / os lint, on a hook only a body the author wrote (a hook body lowered ' + + 'from an inline handler is not judged): a source ' + 'that calls a member the sandbox gates without its token in body.capabilities. The gates: the ' + 'ctx.api.object(…) read leaves (api.read), its write leaves (api.write), ctx.api.transaction (api.transaction), ' + 'ctx.log.debug / info / warn / error (log), ctx.crypto.randomUUID (crypto.uuid), ctx.email.send (email.send), ' @@ -36,14 +37,14 @@ export const entry: SemanticMigration = { + 'writes were judged), so it deployed clean and then failed at the call every time the hook or action reached ' + 'it; under a hook\'s default onError abort, the write that ran the hook failed with it. The rule reads the ' + 'source with strings and comments blanked, without parsing or running it, and judges exactly the gates the ' - + 'sandbox runner installs. os build now also infers api.transaction for a handler that calls ' - + 'ctx.api.transaction, so a lowered handler carries the grant it calls. Stored metadata is not rewritten or ' + + 'sandbox runner installs. A hook body os build lowered from an inline handler is not judged: its grant is the ' + + 'build\'s inference, not the author\'s, so a hook written as a handler is unchanged. Stored metadata is not rewritten or ' + 'refused at boot; the next publish of the hook, action or object is refused with the token named. Such a call ' + 'never succeeded, so no stored row changes shape. There is no mechanical rewrite: granting a token widens what ' + 'the body may do, which is the author\'s decision.', acceptanceCriteria: 'Load every hook and action (`os validate` or `os build`): no `hook-body-capability-undeclared` finding at ' - + 'hooks[N].body.capabilities or hooks[N].handler, and no `action-body-capability-undeclared` finding at ' + + 'hooks[N].body.capabilities, and no `action-body-capability-undeclared` finding at ' + 'actions[N].body.capabilities. PUT /api/v1/meta/hook/NAME and PUT /api/v1/meta/action/NAME with each such body ' + 'granted or corrected answer 200, and the call runs instead of answering 403.', }; From c3319db255fed5f856fd4eb12c759b70ae10501f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 00:03:45 +0000 Subject: [PATCH 08/11] chore(changeset): the Skills-docs line names the follow-up card Claude-Session: https://claude.ai/code/session_01ADHkmSwS4mQyXWrddL4r6B Co-authored-by: Claude --- .changeset/37815-body-capabilities-every-gate.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/37815-body-capabilities-every-gate.md b/.changeset/37815-body-capabilities-every-gate.md index b2b299a4d77..d4434a34340 100644 --- a/.changeset/37815-body-capabilities-every-gate.md +++ b/.changeset/37815-body-capabilities-every-gate.md @@ -7,7 +7,7 @@ feat(lint)!: a hook body's gated calls, and an action body's calls to every gate Clause-②: no (narrowing) Metadata-protocol: narrowed -Skills-docs: follow-up owed — skills/objectstack-ui/rules/actions.md, skills/objectstack-data/references/data-hooks.md +Skills-docs: follow-up #38655 From a60a6de91546ef6125f0f421faf732765a0e7cf2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 01:27:43 +0000 Subject: [PATCH 09/11] fix(lint): the field-carrying leaves the explanation lists include updateById Claude-Session: https://claude.ai/code/session_01ADHkmSwS4mQyXWrddL4r6B Co-authored-by: Claude --- packages/lint/src/rule-explanations.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 7cbf613d9e5..a1aac405619 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -1423,8 +1423,9 @@ const ACTION_BODY_WRITE_UNKNOWN_FIELD_EXPLANATION: RuleExplanation = { covers: 'why an undeclared field write is refused', paragraphs: [ 'An action body persists records only through `ctx.api`: ' + - '`ctx.api.object(NAME).insert({ … })`, `.update({ id, … })` for one record, `.upsert(…)` or ' + - '`.updateMany(…)`, the leaves the sandbox installs that carry fields. `ctx.api` is a scoped handle on ' + + '`ctx.api.object(NAME).insert({ … })`, `.update({ id, … })` or `.updateById(id, { … })` for one record, ' + + '`.upsert(…)` or `.updateMany(…)`, the leaves the sandbox installs that carry fields. `ctx.api` is a ' + + 'scoped handle on ' + 'the running engine, so the payload arrives as an ordinary CALLER write. An action\'s `ctx.input` ' + 'is its params bag, validated against the action\'s own `params`, so it is never resolved against ' + 'fields.', From 29d3b0fea127252344c212b0c9040d09696fe559 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 01:37:48 +0000 Subject: [PATCH 10/11] fix(lint)!: an action body lowered from a target function is judged for api.write only Contract review M1: action-body-capability-undeclared no longer judges an action body os build / os verify lowered from an inline target function (isLoweredTargetBody: a string target beside the body, the shape lowering leaves), since its grant is the build's inference; its writes stay judged under action-body-write-capability-undeclared. The rule header (the third door, N2), the explanation, the upgrade-guide entry (the inline path, N2), the changeset and the docs row say so; the lowered reading stays with the extractor card. Claude-Session: https://claude.ai/code/session_01ADHkmSwS4mQyXWrddL4r6B Co-authored-by: Claude --- .../37815-body-capabilities-every-gate.md | 8 +-- .../docs/deployment/validating-metadata.mdx | 2 +- packages/lint/src/rule-explanations.ts | 4 +- ...capabilities.hook-and-tokens-37815.test.ts | 46 ++++++++++++++ .../src/validate-action-body-capabilities.ts | 62 +++++++++++++++---- ...odies-calling-an-ungranted-gate-refused.ts | 17 +++-- 6 files changed, 115 insertions(+), 24 deletions(-) diff --git a/.changeset/37815-body-capabilities-every-gate.md b/.changeset/37815-body-capabilities-every-gate.md index d4434a34340..c4f0111e975 100644 --- a/.changeset/37815-body-capabilities-every-gate.md +++ b/.changeset/37815-body-capabilities-every-gate.md @@ -11,20 +11,20 @@ Skills-docs: follow-up #38655 -**BREAKING** for the publish of an action, an object or a hook whose L2 body (on a hook, an authored body) calls a member the QuickJS sandbox gates without that member's token in `body.capabilities`. Such a body saved and published before; the sandbox refused the call with `403 INSUFFICIENT_PRIVILEGES` every time the body reached it, so it never worked. It is refused now, at the runtime publish door and in `os validate` / `lint` / `compile` / `build`, with the token named. The schema is unchanged and stored metadata is not rewritten or refused at boot; the refusal comes at the next publish. +**BREAKING** for the publish of an action, an object or a hook whose authored L2 body calls a member the QuickJS sandbox gates without that member's token in `body.capabilities`. Such a body saved and published before; the sandbox refused the call with `403 INSUFFICIENT_PRIVILEGES` every time the body reached it, so it never worked. It is refused now, at the runtime publish door and in `os validate` / `lint` / `compile` / `build`, with the token named. The schema is unchanged and stored metadata is not rewritten or refused at boot; the refusal comes at the next publish. The gates are the sandbox runner's own, token by token, and the rule's list is pinned to the runner's source: the `ctx.api.object(…)` read leaves (`find`, `findOne`, `count`, `aggregate`) behind `api.read`, the write leaves behind `api.write`, `ctx.api.transaction(…)` behind `api.transaction`, `ctx.log.debug|info|warn|error(…)` behind `log`, `ctx.crypto.randomUUID()` behind `crypto.uuid`, `ctx.email.send(…)` behind `email.send`, `ctx.activity.append(…)` behind `activity.append`, and on a hook body `ctx.title(FIELD)` with an argument behind `api.read` (`ctx.title()` needs no token). - `hook-body-capability-undeclared` (new): an authored L2 hook body that calls any of those gates without its token. A hook body is never granted `email.send`, so its `ctx.email.send(…)` call is refused with the remedy that works: remove the call and send the mail from an action, a job or a flow. Only a body the author wrote is judged: a hook body `os build` / `os verify` lowered from an inline `handler` is not, since its grant is the build's inference (the lowered reading is #38653). Runs on the runtime `hook` door. -- `action-body-capability-undeclared` (new): an L2 action body that calls a gate other than the writes without its token. Runs on the runtime `action` and `object` doors. +- `action-body-capability-undeclared` (new): an authored L2 action body that calls a gate other than the writes without its token. An action body `os build` / `os verify` lowered from an inline `target` function is not judged for these tokens, since its grant is the build's inference (the lowered reading is #38653); its writes are still judged under `action-body-write-capability-undeclared`. Runs on the runtime `action` and `object` doors. - `action-body-write-capability-undeclared` is unchanged: an action body's write without `api.write` keeps its id and its words. ## FROM → TO - Authored hook body (arm a). FROM: `hooks: [{ …, body: { language: 'js', source: "await ctx.api.object('task').update({ id, done: true })", capabilities: [] } }]` saved and threw at every run. TO: declare the token, `capabilities: ['api.write']`. -- Action body, other tokens (arm b). FROM: `body: { language: 'js', source: 'await ctx.api.transaction(async () => { … })', capabilities: ['api.write'] }` saved and threw at every run. TO: declare the token, `capabilities: ['api.write', 'api.transaction']` (likewise `log`, `crypto.uuid`, `email.send`, `activity.append`, `api.read` for the call the finding names). +- Authored action body, other tokens (arm b). FROM: `body: { language: 'js', source: 'await ctx.api.transaction(async () => { … })', capabilities: ['api.write'] }` saved and threw at every run. TO: declare the token, `capabilities: ['api.write', 'api.transaction']` (likewise `log`, `crypto.uuid`, `email.send`, `activity.append`, `api.read` for the call the finding names). - Authored hook body calling `ctx.email.send(…)`. FROM: saved and threw at every run. TO: remove the call and send the mail from an action, a job or a flow. -A hook whose body was lowered from an inline `handler` is unchanged: FROM and TO alike, it is not judged by this rule. +A hook whose body was lowered from an inline `handler` is unchanged: FROM and TO alike, it is not judged by this rule. So is an action whose body was lowered from an inline `target` function, for every token but `api.write`: FROM, `actions: [{ …, target: async (ctx) => { await ctx.api.transaction(…) } }]` built clean; TO, it still builds clean, and its writes are judged as before. `os explain hook-body-capability-undeclared` and `os explain action-body-capability-undeclared` carry an entry for each. `@objectstack/lint` exports the two rule id constants, `ACTION_BODY_CAPABILITY_UNDECLARED` and `HOOK_BODY_CAPABILITY_UNDECLARED`. `@objectstack/spec` adds only the upgrade-guide entry `hook-and-action-bodies-calling-an-ungranted-gate-refused`. diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index e908523cfe6..4d0a3f69d40 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -524,7 +524,7 @@ orthogonal to both, and no cell here can carry it; it is written out in | Script action bodies compile in the runtime's wrapper — an L2 action's `body.source` that does not compile as the body of `(async (input, ctx) => { … })`, most often `const input = …` redeclaring a parameter; an object write runs it over its inline `actions[]`, so an object write cannot republish a refused body (`action-body-does-not-compile`, #34884) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | | Script action bodies hold the grant they call — an L2 action body that calls a `ctx.api` write (`insert`, `update`, `updateById`, `delete`, `updateMany`, `deleteMany`, `upsert`) without `api.write` in its `body.capabilities`, which the sandbox refuses at every call (`action-body-write-capability-undeclared`, #35143) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | | Seed record keys — a seed record key, or a seed `columns` key, that names no field of the dataset's object, no system column injected on it and none of `id` / `created_at` / `updated_at`; the engine's insert door refuses such a record and the seed load loads the rest (`seed-record-unknown-field`, #35143) | ✓ | ✓ | ✓ | ✓ˢ | -| Script action bodies hold every other grant they call — an L2 action body that calls a member the sandbox gates behind a token other than `api.write` without that token in its `body.capabilities`: a `ctx.api.object(…)` read leaf (`api.read`), `ctx.api.transaction(…)` (`api.transaction`), `ctx.log.*` (`log`), `ctx.crypto.randomUUID()` (`crypto.uuid`), `ctx.email.send(…)` (`email.send`) or `ctx.activity.append(…)` (`activity.append`), each refused by the sandbox at every call (`action-body-capability-undeclared`, #37815) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | +| Script action bodies hold every other grant they call — an authored L2 action body (one `os build` lowered from a `target` function is judged for its writes only) that calls a member the sandbox gates behind a token other than `api.write` without that token in its `body.capabilities`: a `ctx.api.object(…)` read leaf (`api.read`), `ctx.api.transaction(…)` (`api.transaction`), `ctx.log.*` (`log`), `ctx.crypto.randomUUID()` (`crypto.uuid`), `ctx.email.send(…)` (`email.send`) or `ctx.activity.append(…)` (`activity.append`), each refused by the sandbox at every call (`action-body-capability-undeclared`, #37815) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | | Hook and job bodies compile in the runtime's wrapper — an L2 hook or job `body.source` that does not compile as the body of `(async (ctx) => { … })`, most often `const ctx = …` redeclaring the parameter or one name declared twice; no door publishes a job, so the publish column is the `hook` write alone (`hook-body-does-not-compile`, `job-body-does-not-compile`, #34987) | ✓ | ✓ | ✓ | ✓ʰ | | Hook bodies hold the grant they call — an authored L2 hook body (one `os build` lowered from a `handler` is not judged) that calls a member the sandbox gates without its token in `body.capabilities`: a `ctx.api.object(…)` read or write leaf, `ctx.api.transaction(…)`, `ctx.log.*`, `ctx.crypto.randomUUID()`, `ctx.activity.append(…)` or the related-record form `ctx.title(FIELD)`, each refused by the sandbox at every call; and any `ctx.email.send(…)`, which a hook body is never granted (`hook-body-capability-undeclared`, #37815) | ✓ | ✓ | ✓ | ✓ʰ | | Approval-node approvers (ADR-0090 D3) | ✓ | ✓ | ✓ | ✓ᶠ | diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index a1aac405619..0c6ae7875c4 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -1552,7 +1552,9 @@ const ACTION_BODY_CAPABILITY_UNDECLARED_EXPLANATION: RuleExplanation = { 'reaches the call. A write without `api.write` has its own id, `action-body-write-capability-undeclared`.', BODY_GATES_READING, 'To fix it, add the token the message names to the action\'s `body.capabilities` (Studio\'s action ' + - 'inspector draws the list), or remove the call.', + 'inspector draws the list), or remove the call. Only a body the author wrote is judged: an action body ' + + 'the build lowered from an inline `target` function is not, since its grant is the build\'s inference ' + + '(its writes are still judged under `action-body-write-capability-undeclared`).', ], }; diff --git a/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts b/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts index 39f2576591c..666930ba65d 100644 --- a/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts +++ b/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts @@ -18,6 +18,7 @@ import { SANDBOX_LOG_LEVELS, bodyGatedCalls, isLoweredHandlerBody, + isLoweredTargetBody, validateActionBodyCapabilities, } from './validate-action-body-capabilities.js'; import { runAuthoringRules } from './authoring-rules.js'; @@ -250,6 +251,51 @@ describe('arm (b): the tokens besides api.write (#37815)', () => { expect(ofRule(granted.errors, ACTION_BODY_CAPABILITY_UNDECLARED)).toEqual([]); }); + describe('authored action bodies only past the writes: a body lowered from a target is judged for api.write alone (#37815 M1)', () => { + // A transaction the build's inference does not read (#38653): the extractor grants the write only. + const TX = "await ctx.api.transaction(async () => { await ctx.api.object('cb_ticket').insert({ name: 'x' }); });"; + const authored = action(TX, ['api.write']); + const lowered = { ...authored, target: 'cb_ticket_cb_close' }; + + it('an authored body with the call is refused', () => { + expect(isLoweredTargetBody(authored)).toBe(false); + const fs = validateActionBodyCapabilities({ actions: [authored] }); + expect(fs.map((f) => [f.rule, f.path])).toEqual([[ACTION_BODY_CAPABILITY_UNDECLARED, 'actions[0].body.capabilities']]); + expect(fs[0].message).toContain("'api.transaction'"); + }); + + it('the same body lowered from a target is not judged by os validate / build / lint, top level or inline', () => { + expect(isLoweredTargetBody(lowered)).toBe(true); + expect(validateActionBodyCapabilities({ actions: [lowered] })).toEqual([]); + const top = { objects: [TICKET], actions: [lowered] }; + const inline = { objects: [{ ...TICKET, actions: [lowered] }] }; + for (const stack of [top, inline]) { + for (const command of ['validate', 'build', 'lint'] as const) { + const fs = runAuthoringRules(command, { normalized: stack, parsed: stack, loweredHookRefs: new Set() }); + expect(ofRule(fs, ACTION_BODY_CAPABILITY_UNDECLARED), command).toEqual([]); + } + } + const fs = validateActionBodyCapabilities({ objects: [{ ...TICKET, actions: [authored] }] }); + expect(fs.map((f) => f.path)).toEqual(['objects[0].actions[0].body.capabilities']); + }); + + it('the action and object doors do not judge it either, and do judge the authored body', () => { + const door = runRuntimeAuthoringRules({ type: 'action', item: lowered, context: { objects: [TICKET] } }); + expect(ofRule(door.errors, ACTION_BODY_CAPABILITY_UNDECLARED)).toEqual([]); + const objectDoor = runRuntimeAuthoringRules({ type: 'object', item: { ...TICKET, actions: [lowered] }, context: { objects: [] } }); + expect(ofRule(objectDoor.errors, ACTION_BODY_CAPABILITY_UNDECLARED)).toEqual([]); + const refused = runRuntimeAuthoringRules({ type: 'action', item: authored, context: { objects: [TICKET] } }); + expect(ofRule(refused.errors, ACTION_BODY_CAPABILITY_UNDECLARED).map((e) => e.path)).toEqual(['actions[0].body.capabilities']); + const objectRefused = runRuntimeAuthoringRules({ type: 'object', item: { ...TICKET, actions: [authored] }, context: { objects: [] } }); + expect(ofRule(objectRefused.errors, ACTION_BODY_CAPABILITY_UNDECLARED)).toHaveLength(1); + }); + + it('a lowered body still answers for its writes, under the write id and words', () => { + const fs = validateActionBodyCapabilities({ actions: [{ ...lowered, body: { ...lowered.body, capabilities: [] } }] }); + expect(fs.map((f) => f.rule)).toEqual([ACTION_BODY_WRITE_CAPABILITY_UNDECLARED]); + }); + }); + it('os explain has a page for the action id', () => { expect(explainRule(ACTION_BODY_CAPABILITY_UNDECLARED)?.paragraphs.join('\n')).toContain('api.transaction'); }); diff --git a/packages/lint/src/validate-action-body-capabilities.ts b/packages/lint/src/validate-action-body-capabilities.ts index 0b1d28714b6..8a2414f71d5 100644 --- a/packages/lint/src/validate-action-body-capabilities.ts +++ b/packages/lint/src/validate-action-body-capabilities.ts @@ -20,16 +20,19 @@ * * The grant is the author's to write: Studio's action inspector draws the * capability list (`ScriptCapabilitiesField`), and a body `os build` lowers - * from a handler gets the grant inferred from its calls: the extractor + * from a handler or a `target` function gets the grant inferred from its + * calls. For the writes the extractor * (`packages/cli/src/utils/extract-hook-body.ts`) reads each shape listed * below — a direct chain, `?.` before the leaf, an argument holding a call, a - * handle bound to `.object(…)` — so a handler the build lowers is not refused - * by the next step of the same build. Its pins hold that shape by shape. + * handle bound to `.object(…)` — so a lowered body's writes are not refused by + * the next step of the same build; its pins hold that shape by shape. For the + * other tokens it does not yet read every shape this rule reads, so a lowered + * body is judged for `api.write` only (see the last section). * * ## How the source is read * - * Read, never parsed or run: this rule gates the runtime `action` and `object` - * publish doors, where the source parsers may never load + * Read, never parsed or run: this rule gates the runtime `action`, `object` + * and `hook` publish doors, where the source parsers may never load * (`runtime-lazy-deps.test.ts`, tier 1). Strings, template literals and * comments are blanked first, so a call spelled inside one is never read as * code. Then three shapes are recognised: @@ -83,12 +86,16 @@ * back), so a hook's `ctx.email.send` call is refused with the remedy that * works: remove the call and send the mail from an action, a job or a flow. * - * Authored hook bodies only. A hook body `os build` / `os verify` lowered - * from an inline handler is not judged: its grant is the build's inference, - * which does not yet read every gated shape (no `api.transaction`, no read - * through a bound handle), so a finding there would name a grant the handler - * author cannot write. {@link isLoweredHandlerBody} tells the two apart; the - * lowered reading waits on the extractor (#38653). + * Authored bodies only, past the writes. A hook body `os build` / `os verify` + * lowered from an inline handler is not judged, and an action body lowered + * from an inline `target` function is judged for `api.write` only + * ({@link ACTION_BODY_WRITE_CAPABILITY_UNDECLARED}, unchanged). Such a grant + * is the build's inference, which does not yet read every gated shape (no + * `api.transaction`; `api.read` only on a direct chain; the other members only + * as a literal `ctx.MEMBER.LEAF`), so a finding there would name a grant the + * author never wrote and cannot write. {@link isLoweredHandlerBody} and + * {@link isLoweredTargetBody} tell the two apart; the lowered reading waits on + * the extractor (#38653). */ import { collectActionBodies } from './validate-action-body-writes.js'; @@ -388,11 +395,39 @@ export function isLoweredHandlerBody( return ctx?.loweredHookRefs ? ctx.loweredHookRefs.has(ref) : true; } +/** + * Whether an action's body is one the build lowered from its `target` + * function rather than one the author wrote (#37815). Lowering replaces an + * inline `target` function with the string ref it registers and adds the body + * beside it, and the CLI hands no lowered-action ref set, so on every door the + * body was lowered when a string `target` sits beside it: the shape a build + * artifact carries. A JS body runs only on a `script` action, where `target` + * is kept for legacy `functions` references alone, so an authored body beside + * a string `target` is not judged either: a missed finding, never a false one. + */ +export function isLoweredTargetBody(action: AnyRec): boolean { + return typeof action.target === 'string' && action.target !== '' && isRecord(action.body); +} + +/** The `…body.source` paths `collectActionBodies` reports for an action {@link isLoweredTargetBody} reads as lowered. */ +function loweredActionBodyPaths(stack: AnyRec): Set { + const paths = new Set(); + const walk = (actions: unknown, prefix: string): void => { + recordsOf(actions).forEach((action, index) => { + if (isLoweredTargetBody(action)) paths.add(`${prefix}[${index}].body.source`); + }); + }; + walk(stack.actions, 'actions'); + recordsOf(stack.objects).forEach((obj, objIndex) => walk(obj.actions, `objects[${objIndex}].actions`)); + return paths; +} + /** * Every L2 action body, and every L2 hook body, that calls a member the * sandbox gates without granting itself the member's token (the header lists * the gates and the ids). A hook body lowered from an inline `handler` is - * skipped ({@link isLoweredHandlerBody}). + * skipped ({@link isLoweredHandlerBody}); an action body lowered from a + * `target` function is judged for `api.write` only ({@link isLoweredTargetBody}). */ export function validateActionBodyCapabilities( stack: AnyRec, @@ -400,7 +435,9 @@ export function validateActionBodyCapabilities( ): ActionBodyCapabilityFinding[] { const findings: ActionBodyCapabilityFinding[] = []; if (!stack || typeof stack !== 'object') return findings; + const loweredActions = loweredActionBodyPaths(stack); for (const site of collectActionBodies(stack)) { + const lowered = loweredActions.has(site.path); for (const { token, calls } of bodyGatedCalls(site.source, 'action')) { if (site.capabilities.includes(token)) continue; const path = site.path.replace(/\.source$/, '.capabilities'); @@ -419,6 +456,7 @@ export function validateActionBodyCapabilities( }); continue; } + if (lowered) continue; findings.push({ severity: 'error', rule: ACTION_BODY_CAPABILITY_UNDECLARED, diff --git a/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts b/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts index 813710eacfe..4a7133fa77e 100644 --- a/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts +++ b/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts @@ -18,8 +18,9 @@ export const entry: SemanticMigration = { 'hooks[].body and actions[].body (an object\'s inline actions[] included) whose body.language is js, on a hook ' + 'or action saved or published through the metadata doors (PUT /api/v1/meta/hook/NAME, PUT ' + '/api/v1/meta/action/NAME, an object write, POST /api/v1/packages/PKG/publish-drafts and the per-item publish) ' - + 'or loaded by os validate / os build / os lint, on a hook only a body the author wrote (a hook body lowered ' - + 'from an inline handler is not judged): a source ' + + 'or loaded by os validate / os build / os lint, only a body the author wrote (a hook body lowered from an ' + + 'inline handler is not judged, and an action body lowered from an inline target function is judged for its ' + + 'writes alone, as before): a source ' + 'that calls a member the sandbox gates without its token in body.capabilities. The gates: the ' + 'ctx.api.object(…) read leaves (api.read), its write leaves (api.write), ctx.api.transaction (api.transaction), ' + 'ctx.log.debug / info / warn / error (log), ctx.crypto.randomUUID (crypto.uuid), ctx.email.send (email.send), ' @@ -30,21 +31,25 @@ export const entry: SemanticMigration = { + 'never granted email.send: remove its ctx.email.send call and send the mail from an action, a job or a flow. ' + 'Refused at error as `hook-body-capability-undeclared` or `action-body-capability-undeclared` (422 ' + 'INVALID_METADATA at the hook and action doors); an action body\'s write without api.write stays ' - + '`action-body-write-capability-undeclared`.', + + '`action-body-write-capability-undeclared`. A hook written as a handler, or an action written as a target ' + + 'function, needs no change for the other tokens: its lowered body is not judged for them (the lowered ' + + 'reading is #38653).', reason: 'The sandbox installs each gated member behind its token and refuses a call the body was not granted with 403 ' + 'INSUFFICIENT_PRIVILEGES at the call site. Every authoring door accepted such a body (only an action body\'s ' + 'writes were judged), so it deployed clean and then failed at the call every time the hook or action reached ' + 'it; under a hook\'s default onError abort, the write that ran the hook failed with it. The rule reads the ' + 'source with strings and comments blanked, without parsing or running it, and judges exactly the gates the ' - + 'sandbox runner installs. A hook body os build lowered from an inline handler is not judged: its grant is the ' - + 'build\'s inference, not the author\'s, so a hook written as a handler is unchanged. Stored metadata is not rewritten or ' + + 'sandbox runner installs. A hook body os build lowered from an inline handler is not judged, and an action ' + + 'body it lowered from an inline target function is judged only for api.write, as before: such a grant is the ' + + 'build\'s inference, not the author\'s, and the inference does not yet read every gated shape, so a hook ' + + 'written as a handler and an action written as a target function are unchanged. Stored metadata is not rewritten or ' + 'refused at boot; the next publish of the hook, action or object is refused with the token named. Such a call ' + 'never succeeded, so no stored row changes shape. There is no mechanical rewrite: granting a token widens what ' + 'the body may do, which is the author\'s decision.', acceptanceCriteria: 'Load every hook and action (`os validate` or `os build`): no `hook-body-capability-undeclared` finding at ' + 'hooks[N].body.capabilities, and no `action-body-capability-undeclared` finding at ' - + 'actions[N].body.capabilities. PUT /api/v1/meta/hook/NAME and PUT /api/v1/meta/action/NAME with each such body ' + + 'actions[N].body.capabilities or objects[N].actions[M].body.capabilities. PUT /api/v1/meta/hook/NAME and PUT /api/v1/meta/action/NAME with each such body ' + 'granted or corrected answer 200, and the call runs instead of answering 403.', }; From 4c07e0d7084b91115d7af589082c509787b8cbc4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 02:24:16 +0000 Subject: [PATCH 11/11] fix(spec): the upgrade-guide entry's printed guidance names no tracker Claude-Session: https://claude.ai/code/session_01ADHkmSwS4mQyXWrddL4r6B Co-authored-by: Claude --- ...ook-and-action-bodies-calling-an-ungranted-gate-refused.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts b/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts index 4a7133fa77e..5cb8412caa4 100644 --- a/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts +++ b/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts @@ -32,8 +32,8 @@ export const entry: SemanticMigration = { + 'Refused at error as `hook-body-capability-undeclared` or `action-body-capability-undeclared` (422 ' + 'INVALID_METADATA at the hook and action doors); an action body\'s write without api.write stays ' + '`action-body-write-capability-undeclared`. A hook written as a handler, or an action written as a target ' - + 'function, needs no change for the other tokens: its lowered body is not judged for them (the lowered ' - + 'reading is #38653).', + + 'function, needs no change for the other tokens: its lowered body is not judged for them (a later ' + + 'change carries the lowered reading).', reason: 'The sandbox installs each gated member behind its token and refuses a call the body was not granted with 403 ' + 'INSUFFICIENT_PRIVILEGES at the call site. Every authoring door accepted such a body (only an action body\'s '