diff --git a/.changeset/37815-body-capabilities-every-gate.md b/.changeset/37815-body-capabilities-every-gate.md index c4f0111e975..68beb2b9aeb 100644 --- a/.changeset/37815-body-capabilities-every-gate.md +++ b/.changeset/37815-body-capabilities-every-gate.md @@ -11,12 +11,12 @@ Skills-docs: follow-up #38655 -**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. +**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 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 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. +- `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 body `os build` / `os verify` lowered from an inline `handler` is judged the same way: its grant is the one the build inferred from its calls, and the build reads each gated call in each spelling the rule reads. 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. An action body `os build` / `os verify` lowered from an inline `target` function is judged the same way, against the grant the build inferred from its calls. 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 @@ -25,6 +25,6 @@ The gates are the sandbox runner's own, token by token, and the rule's list is p - 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. 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. +A hook written as an inline `handler`, and an action written as an inline `target` function, need no change: the build infers the grant from each gated call in each spelling the rule reads (`?.`, whitespace or a comment between steps, the optional call), so the body it lowers carries the token. FROM, `actions: [{ …, target: async (ctx) => { await ctx.api.transaction(…) } }]` built clean; TO, it still builds clean, its lowered body granted `api.transaction`. `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/.changeset/38690-lint-lowered-bodies.md b/.changeset/38690-lint-lowered-bodies.md new file mode 100644 index 00000000000..a265996aed3 --- /dev/null +++ b/.changeset/38690-lint-lowered-bodies.md @@ -0,0 +1,24 @@ +--- +'@objectstack/lint': minor +'@objectstack/cli': patch +'@objectstack/spec': patch +--- + +feat(lint)!: a hook or action body beside a string `handler` or `target` is judged for every capability it calls, like any other body + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for the publish of a hook or action whose body sits beside a string `handler` or `target`, lowered by the build or written by hand, when that body calls a member the QuickJS sandbox gates without the member's token in `body.capabilities`. The rules took such a body for one the build lowered and skipped it: `hook-body-capability-undeclared` did not judge a hook body the build lowered, nor any hook body beside a string `handler` at the runtime publish doors, and `action-body-capability-undeclared` did not judge an action body beside a string `target` (its writes were judged, under `action-body-write-capability-undeclared`). Both judge it now, at the runtime publish doors and in `os validate` / `lint` / `compile` / `build`, with the token named. Such a body never worked: the sandbox refused the call with `403 INSUFFICIENT_PRIVILEGES` every time the body reached it. A body written by hand declares the token in `body.capabilities`; a build artifact is rebuilt. + +An inline `handler` or `target` function needs no change: `os build` infers the grant from each gated call the rule reads, in each spelling the rule reads. That is every gate of the rule's census through `ctx.MEMBER`, a local bound once to it, a destructure off `ctx`, a handle bound once to `ctx.api.object(…)` and a hook handler's destructured context parameter (and, past the rule, a renamed one), with `?.` or whitespace on either side of a step, the optional call `LEAF?.(…)`, and a comment between steps. Before this release `os build` read `ctx.log?.info(…)`, `ctx?.crypto.randomUUID()`, `ctx.activity?.append(…)`, `ctx.email?.send(…)`, `ctx.title?.(field)`, the same calls with whitespace or a comment between steps, and their rebound siblings as no call at all, so the handler lowered without the token and failed at the call; it now lowers with it. A hook handler that calls `ctx.email.send` in any of those spellings is refused by the hook parse at build, as `ctx.email.send(…)` already was: a hook body is never granted `email.send`. The build's reading is pinned against the rule's, spelling by spelling, by judging each one both ungranted (a finding) and lowered (none); it is a superset of the rule's reading by that enumeration, not by proof. Measured over the first-party example and connector apps, loaded, normalized and lowered as `os validate` does: no body newly refused. + +## FROM → TO + +- A hook body beside a string `handler`, written by hand or left by a build artifact. FROM: `hooks: [{ …, handler: 'my_hook_fn', body: { language: 'js', source: "const l = ctx.log; l.info('x')", capabilities: [] } }]` published clean and threw at every run. TO: refused with `hook-body-capability-undeclared` naming `log`; declare `capabilities: ['log']`, or rebuild the artifact (the build grants `log`). +- An action body beside a string `target`, written by hand or left by a build artifact. FROM: `actions: [{ …, target: 'my_action_fn', body: { language: 'js', source: 'await ctx.api.transaction(async () => { … })', capabilities: ['api.write'] } }]` published clean and threw at every run. TO: refused with `action-body-capability-undeclared` naming `api.transaction`; declare `capabilities: ['api.write', 'api.transaction']`, or rebuild it. +- An inline handler that spells a gated call with `?.`. FROM: `handler: async (ctx) => { ctx.log?.info('x'); }` lowered to `capabilities: []` and failed at the call. TO: it lowers to `capabilities: ['log']` and runs. + +`os explain hook-body-capability-undeclared` and `os explain action-body-capability-undeclared` no longer say a lowered body is exempt. `@objectstack/lint` now exports `SANDBOX_CAPABILITY_GATES` and its `SandboxCapabilityGate` type, the sandbox's gate census the rule judges by. `@objectstack/spec` adds only the upgrade-guide entry `lowered-hook-and-action-bodies-capabilities-judged`. diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index c34f848f26a..6167966aeed 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -524,9 +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`, `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 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) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | +| Script action bodies hold every other grant they call — an L2 action body (authored, or lowered by `os build` from a `target` function) 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) | ✓ | ✓ | ✓ | ✓ʰ | +| Hook bodies hold the grant they call — an L2 hook body (authored, or lowered by `os build` from a `handler`) 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 ef1bbd64b49..095db930d1a 100644 --- a/packages/cli/src/utils/extract-hook-body.ts +++ b/packages/cli/src/utils/extract-hook-body.ts @@ -506,6 +506,67 @@ const FORBIDDEN_PATTERNS: Array<{ rx: RegExp; reason: string; face?: LoweringFac }, ]; +/** + * [#38690] The step from a receiver to its member as the publish rule + * (`validate-action-body-capabilities`) reads it: `?.` or `.`, whitespace + * allowed on either side. `ctx.log.info`, `ctx?.log.info`, `ctx.log?.info` and + * `ctx . log . info` reach the same sandbox gate, so each infers its token. + */ +const MEMBER_STEP = String.raw`\s*\??\.\s*`; + +/** + * [#38690] A `ctx`-anchored member-leaf gate: `RECEIVER.MEMBER.LEAF` through + * {@link MEMBER_STEP} on both steps. No call is required (`\b` after the leaf, + * as before): `ctx.log.info?.(…)` and `ctx.log.info (…)` match, and so does a + * bare read of the leaf, which over-infers a grant the sandbox never checks. + */ +function memberLeafRx(receiver: string, member: string, leaves: string): RegExp { + return new RegExp(String.raw`${receiver}${MEMBER_STEP}${member}${MEMBER_STEP}(?:${leaves})\b`); +} + +/** + * [#38690] The source with each comment blanked to spaces (offsets and newlines + * kept), strings and template literals left as they are. The publish rule reads + * a body with its comments blanked, so `ctx./* … *\/log.info(…)` and a member + * step broken by a line comment are a gated call to it; the patterns below read + * this copy as well as the source itself, so a comment between the steps does + * not hide the call, and a spelling inside a comment still infers what it + * inferred before. The walk is the rule's own (`maskBodySource` in + * `@objectstack/lint`) minus its blanking of strings. + */ +function blankComments(source: string): string { + const out = source.split(''); + const blank = (from: number, to: number): void => { + for (let k = from; k < to; k++) if (out[k] !== '\n') out[k] = ' '; + }; + let i = 0; + while (i < source.length) { + const ch = source[i]; + if (ch === '/' && source[i + 1] === '/') { + const nl = source.indexOf('\n', i); + const end = nl === -1 ? source.length : nl; + blank(i, end); + i = end; + } else if (ch === '/' && source[i + 1] === '*') { + const close = source.indexOf('*/', i + 2); + const end = close === -1 ? source.length : close + 2; + blank(i, end); + i = end; + } else if (ch === '"' || ch === "'" || ch === '`') { + let j = i + 1; + while (j < source.length && source[j] !== ch) { + if (source[j] === '\\') j++; + else if (ch !== '`' && source[j] === '\n') break; + j++; + } + i = j + 1; + } else { + i++; + } + } + return out.join(''); +} + 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 @@ -540,12 +601,12 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | ' // A read of a `transaction` FIELD (`ctx.input.transaction`) is no call and // infers nothing. { rx: /\.\s*transaction\s*(?:\?\.\s*)?\(|\{[^{}]*\btransaction\b[^{}]*\}(?:\s*\})*\s*=(?![=>])/, cap: 'api.transaction' }, - { rx: /ctx\.crypto\.randomUUID\b/, cap: 'crypto.uuid' }, + { rx: memberLeafRx('ctx', 'crypto', 'randomUUID'), cap: 'crypto.uuid' }, // NO `ctx.crypto.hash` pattern: the `crypto.hash` token was removed in spec 17 // (#4391) because the sandbox never installed the function. Inferring a // 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' }, + { rx: memberLeafRx('ctx', 'log', 'info|warn|error|debug'), cap: 'log' }, // [#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 @@ -556,12 +617,14 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | ' // `ctx.api.object(...).findOne()` would do and gets the same token. // // `[^)\s]` after the paren is what distinguishes the two: `ctx.title()` and - // `ctx.title( )` do not match, `ctx.title('account_id')` does. Receiver-loose + // `ctx.title( )` do not match, `ctx.title('account_id')` does, and [#38690] + // so do the optional call `ctx.title?.('account_id')` and `ctx?.title(…)`, + // which the publish rule reads as the same call. Receiver-loose // like the `.object(...)` patterns above, for the same reason — a local alias // (`const t = ctx.title`) must not silently UNDER-infer, since that failure // arrives as a sandbox refusal at run time, far from its cause. Over-inferring // grants a token the body may not use, which the sandbox simply never checks. - { rx: /\.\s*title\s*\(\s*[^)\s]/, cap: 'api.read' }, + { rx: /\.\s*title\s*(?:\?\.\s*)?\(\s*[^)\s]/, cap: 'api.read' }, // The two platform doors: a call to the door is what its token grants. // // ⛔ An over-inferred `email.send` is NOT harmless on a hook. A hook body may @@ -574,8 +637,11 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | ' // to take the spelling out of the hook handler, and mail on a record change // goes through an action, a job or a flow. An action or a job body is // granted the token as before. - { rx: /ctx\.email\.send\b/, cap: 'email.send' }, - { rx: /ctx\.activity\.append\b/, cap: 'activity.append' }, + // [#38690] Every spelling the publish rule reads counts here too, so + // `ctx?.email.send(…)` and `ctx.email?.send(…)` on a hook are refused at + // build like `ctx.email.send(…)`. + { rx: memberLeafRx('ctx', 'email', 'send'), cap: 'email.send' }, + { rx: memberLeafRx('ctx', 'activity', 'append'), cap: 'activity.append' }, ]; /** The read leaves the `api.read` pattern above names, as one alternation. */ @@ -747,18 +813,22 @@ export function extractLoweredBody( ); } - // Infer capabilities from API surface usage. + // Infer capabilities from API surface usage, [#38690] over the source and + // over its comment-blanked copy (see blankComments). const inferred = new Set(); - for (const { rx, cap } of CAPABILITY_PATTERNS) { - if (rx.test(source)) inferred.add(cap); + const aliases = bodyMemberAliases(parsed, face); + for (const scanned of new Set([source, blankComments(source)])) { + for (const { rx, cap } of CAPABILITY_PATTERNS) { + if (rx.test(scanned)) inferred.add(cap); + } + // [#35143] [#38653] The `.object(...)` write and read shapes one regex cannot read; see the helper. + if (callsObjectWriteThroughHandle(scanned)) inferred.add('api.write'); + if (callsObjectReadThroughHandle(scanned)) inferred.add('api.read'); + // [#22837] The ctx-anchored patterns above spell `ctx.`; a rebound body + // reaches the same members through the handler's own names, and [#38690] + // any body through a local bound to `ctx.MEMBER` or destructured off `ctx`. + for (const cap of reboundCapabilities(scanned, rebind, aliases)) inferred.add(cap); } - // [#35143] [#38653] The `.object(...)` write and read shapes one regex cannot read; see the helper. - if (callsObjectWriteThroughHandle(source)) inferred.add('api.write'); - if (callsObjectReadThroughHandle(source)) inferred.add('api.read'); - // [#22837] The ctx-anchored patterns above spell `ctx.`; a rebound body - // reaches the same members through the handler's own names, and [#38690] - // any body through a local bound to `ctx.MEMBER` or destructured off `ctx`. - for (const cap of reboundCapabilities(source, rebind, bodyMemberAliases(parsed, face))) inferred.add(cap); return { source, @@ -1172,26 +1242,21 @@ function reboundCapabilities( for (const l of aliases.title) { if (new RegExp(String.raw`${aliasRoot(l)}\s*(?:\?\.\s*)?\(\s*[^)\s]`).test(source)) out.push('api.read'); } + // [#38690] Each step through MEMBER_STEP, like the ctx-anchored patterns. for (const r of rebind.contextRoots) { - if (new RegExp(String.raw`${root(r)}\.log\.(?:info|warn|error|debug)\b`).test(source)) out.push('log'); - if (new RegExp(String.raw`${root(r)}\.crypto\.randomUUID\b`).test(source)) out.push('crypto.uuid'); - if (new RegExp(String.raw`${root(r)}\.email\.send\b`).test(source)) out.push('email.send'); - if (new RegExp(String.raw`${root(r)}\.activity\.append\b`).test(source)) out.push('activity.append'); - } - for (const l of rebind.memberLocals.log) { - if (new RegExp(String.raw`${root(l)}\.(?:info|warn|error|debug)\b`).test(source)) out.push('log'); - } - for (const l of rebind.memberLocals.crypto) { - if (new RegExp(String.raw`${root(l)}\.randomUUID\b`).test(source)) out.push('crypto.uuid'); - } - for (const l of rebind.memberLocals.email) { - if (new RegExp(String.raw`${root(l)}\.send\b`).test(source)) out.push('email.send'); + for (const member of ['log', 'crypto', 'email', 'activity'] as const) { + const { leaves, cap } = MEMBER_LEAVES[member]; + if (memberLeafRx(root(r), member, leaves).test(source)) out.push(cap); + } } - for (const l of rebind.memberLocals.activity) { - if (new RegExp(String.raw`${root(l)}\.append\b`).test(source)) out.push('activity.append'); + for (const member of ['log', 'crypto', 'email', 'activity'] as const) { + const { leaves, cap } = MEMBER_LEAVES[member]; + for (const l of rebind.memberLocals[member]) { + if (new RegExp(String.raw`${root(l)}${MEMBER_STEP}(?:${leaves})\b`).test(source)) out.push(cap); + } } for (const l of rebind.memberLocals.title) { - if (new RegExp(String.raw`${root(l)}\s*\(\s*[^)\s]`).test(source)) out.push('api.read'); + if (new RegExp(String.raw`${root(l)}\s*(?:\?\.\s*)?\(\s*[^)\s]`).test(source)) out.push('api.read'); } return out; } diff --git a/packages/cli/test/extract-hook-body-local-alias-38690.test.ts b/packages/cli/test/extract-hook-body-local-alias-38690.test.ts index b89a69e3653..717cb30b310 100644 --- a/packages/cli/test/extract-hook-body-local-alias-38690.test.ts +++ b/packages/cli/test/extract-hook-body-local-alias-38690.test.ts @@ -14,12 +14,23 @@ * shipped without the token and the sandbox refused it at the call. * * These pin each member through each alias shape (refused before, inferred - * now), the controls that infer nothing, and an enumeration of every gate - * whose member is a `ctx.MEMBER` receiver. + * now), the controls that infer nothing, an enumeration of every gate of the + * rule's own census through every receiver, and the parity the rule now leans + * on: it judges a lowered body, so no call it reads may go ungranted. */ import { describe, expect, it } from 'vitest'; +import { + ACTION_BODY_CAPABILITY_UNDECLARED, + ACTION_BODY_WRITE_CAPABILITY_UNDECLARED, + HOOK_BODY_CAPABILITY_UNDECLARED, + SANDBOX_CAPABILITY_GATES, + runAuthoringRules, + type SandboxCapabilityGate, +} from '@objectstack/lint'; +import { HookSchema } from '@objectstack/spec/data'; import { extractLoweredBody, type ExtractedBody } from '../src/utils/extract-hook-body.js'; +import { lowerCallables } from '../src/utils/lower-callables.js'; type Token = ExtractedBody['capabilities'][number]; type Face = 'hook' | 'action'; @@ -80,27 +91,13 @@ describe('CONTROL: what is not a gated call through a ctx.MEMBER alias infers no }); /** - * Every capability gate the sandbox installs whose member is a `ctx.MEMBER` - * receiver, with one gated call spelled through that receiver. - * - * This mirrors `SANDBOX_CAPABILITY_GATES` in `@objectstack/lint`'s - * `validate-action-body-capabilities.ts`, which no entry of that package - * exports, so this file cannot import it. It is pinned to this package's own - * token list instead: `EVERY_TOKEN` must name each token of the published - * `ExtractedBody['capabilities']` union (a missing or extra key is a type - * error) and every token must have a gate row here. + * Every capability gate the sandbox installs, read straight off the publish + * rule's own census (`SANDBOX_CAPABILITY_GATES` in `@objectstack/lint`), so a + * gate the rule learns is a gate this enumeration spells through every + * receiver the next time it runs. `EVERY_TOKEN` must name each token of the + * published `ExtractedBody['capabilities']` union (a missing or extra key is a + * type error), and the census must cover every one of them. */ -const CTX_MEMBER_GATES: ReadonlyArray<{ token: Token; member: string; call: (receiver: string) => string; kinds: readonly Face[] }> = [ - { token: 'api.read', member: 'api', call: (r) => `await ${r}.object('x').find({});`, kinds: ['action', 'hook'] }, - { token: 'api.write', member: 'api', call: (r) => `await ${r}.object('x').update('1', {});`, kinds: ['action', 'hook'] }, - { token: 'api.transaction', member: 'api', call: (r) => `await ${r}.transaction(async () => {});`, kinds: ['action', 'hook'] }, - { token: 'log', member: 'log', call: (r) => `${r}.debug('x');`, kinds: ['action', 'hook'] }, - { token: 'crypto.uuid', member: 'crypto', call: (r) => `ctx.input.id = ${r}.randomUUID();`, kinds: ['action', 'hook'] }, - { token: 'email.send', member: 'email', call: (r) => `await ${r}.send({});`, kinds: ['action', 'hook'] }, - { token: 'activity.append', member: 'activity', call: (r) => `await ${r}.append({});`, kinds: ['action', 'hook'] }, - { token: 'api.read', member: 'title', call: (r) => `ctx.input.label = await ${r}('account_id');`, kinds: ['hook'] }, -]; - const EVERY_TOKEN = { 'api.read': true, 'api.write': true, @@ -111,25 +108,201 @@ const EVERY_TOKEN = { 'activity.append': true, } as const satisfies Record; +/** + * Each gated call a gate names, spelled through `receiver` in every way the + * publish rule reads a call (`memberLeafCalls`, `objectLeafCalls`, + * `calledWithArgument`): plain, `?.` before the leaf, the optional call + * `LEAF?.(…)` where the rule reads one, whitespace around the dot and before + * the paren, and a comment between the steps (the rule blanks comments). + */ +function gatedCalls(gate: SandboxCapabilityGate, receiver: string): string[] { + if (gate.shape === 'object-leaf') { + return gate.leaves.flatMap((leaf) => [ + `await ${receiver}.object('x').${leaf}({});`, + `await ${receiver}?.object('x')?.${leaf}({});`, + `await ${receiver} . object('x') . ${leaf} ({});`, + `await ${receiver}.object('x')/* c */.${leaf}({});`, + ]); + } + if (gate.shape === 'member-leaf') { + return gate.leaves.flatMap((leaf) => [ + `ctx.input.v = await ${receiver}.${leaf}({});`, + `ctx.input.v = await ${receiver}?.${leaf}({});`, + `ctx.input.v = await ${receiver}.${leaf}?.({});`, + `ctx.input.v = await ${receiver} . ${leaf} ({});`, + `ctx.input.v = await ${receiver}/* c */.${leaf}({});`, + `ctx.input.v = await ${receiver} // c\n .${leaf}({});`, + ]); + } + return [ + `ctx.input.label = await ${receiver}('account_id');`, + `ctx.input.label = await ${receiver}?.('account_id');`, + `ctx.input.label = await ${receiver} ( 'account_id');`, + `ctx.input.label = await ${receiver}/* c */('account_id');`, + ]; +} + +/** Every receiver of `ctx.MEMBER` the publish rule reads (`memberReceivers`). */ +const RECEIVERS: Array<{ shape: string; spell: (member: string) => { decl: string; receiver: string } }> = [ + { shape: 'ctx.MEMBER', spell: (m) => ({ decl: '', receiver: `ctx.${m}` }) }, + { shape: 'ctx?.MEMBER', spell: (m) => ({ decl: '', receiver: `ctx?.${m}` }) }, + { shape: 'ctx . MEMBER (whitespace)', spell: (m) => ({ decl: '', receiver: `ctx . ${m}` }) }, + { shape: 'ctx/* c */.MEMBER (a comment)', spell: (m) => ({ decl: '', receiver: `ctx/* c */.${m}` }) }, + { shape: 'a local bound once to ctx.MEMBER', spell: (m) => ({ decl: `const alias_${m} = ctx.${m};`, receiver: `alias_${m}` }) }, + { shape: 'a destructure off ctx', spell: (m) => ({ decl: `const { ${m} } = ctx;`, receiver: m }) }, + { shape: 'a renamed destructure off ctx', spell: (m) => ({ decl: `const { ${m}: local_${m} } = ctx;`, receiver: `local_${m}` }) }, +]; + describe('ENUMERATION: every ctx.MEMBER gate is inferred through each receiver shape', () => { - it('the gate table covers every token of the published capability union', () => { - expect([...new Set(CTX_MEMBER_GATES.map((g) => g.token))].sort()).toEqual(Object.keys(EVERY_TOKEN).sort()); + it('the census covers every token of the published capability union', () => { + expect([...new Set(SANDBOX_CAPABILITY_GATES.map((g) => g.token))].sort()).toEqual(Object.keys(EVERY_TOKEN).sort()); }); - const receivers: Array<{ shape: string; spell: (member: string) => { decl: string; receiver: string } }> = [ - { shape: 'ctx.MEMBER', spell: (m) => ({ decl: '', receiver: `ctx.${m}` }) }, - { shape: 'a local bound once to ctx.MEMBER', spell: (m) => ({ decl: `const alias_${m} = ctx.${m};`, receiver: `alias_${m}` }) }, - { shape: 'a destructure off ctx', spell: (m) => ({ decl: `const { ${m} } = ctx;`, receiver: m }) }, - { shape: 'a renamed destructure off ctx', spell: (m) => ({ decl: `const { ${m}: local_${m} } = ctx;`, receiver: `local_${m}` }) }, - ]; - for (const gate of CTX_MEMBER_GATES) { + for (const gate of SANDBOX_CAPABILITY_GATES) { + for (const face of gate.kinds) { + for (const { shape, spell } of RECEIVERS) { + it(`${gate.token} via ctx.${gate.member} through ${shape} (${face} face)`, () => { + const { decl, receiver } = spell(gate.member); + for (const call of gatedCalls(gate, receiver)) { + expect(infer(`${decl} ${call}`, face), call).toContain(gate.token); + } + }); + } + } + } +}); + +/** + * PARITY: the publish rule judges a lowered body like an authored one, so + * every gated call it reads must be one the build granted. Each spelling of + * each call of the census, through each receiver, is judged by the rule twice + * over `runAuthoringRules`: ungranted, it must draw the gate's finding (so the + * rule reads that spelling and the pin is not vacuous); lowered through + * `extractLoweredBody`, with the grant the build inferred, it must draw none. + * A hook body calling `email.send` is the one exception by design (a hook body + * is never granted it, and the hook's parse refuses the inferred grant at + * build; the ENUMERATION above holds that the build infers it). + */ +describe('PARITY: a lowered body draws no capability finding from the publish rule', () => { + // The body record the build writes beside the string ref: `lowerCallables` + // stores `{ language: 'js', source, capabilities }`. + const findings = (face: Face, extracted: Pick): string[] => { + const body = { language: 'js', source: extracted.source, capabilities: extracted.capabilities }; + const stack = + face === 'hook' + ? { hooks: [{ name: 'h', object: 'x', events: ['beforeUpdate'], handler: 'h_fn', body }] } + : { actions: [{ name: 'a', label: 'A', objectName: 'x', type: 'script', target: 'x_a', body }] }; + const run = { normalized: stack, parsed: stack, loweredHookRefs: new Set(['h_fn']) }; + return runAuthoringRules('build', run) + .filter((f) => [HOOK_BODY_CAPABILITY_UNDECLARED, ACTION_BODY_CAPABILITY_UNDECLARED, ACTION_BODY_WRITE_CAPABILITY_UNDECLARED].includes(f.rule)) + .map((f) => `${f.rule}: ${f.message}`); + }; + + for (const gate of SANDBOX_CAPABILITY_GATES) { for (const face of gate.kinds) { - for (const { shape, spell } of receivers) { + if (face === 'hook' && gate.token === 'email.send') continue; + for (const { shape, spell } of RECEIVERS) { it(`${gate.token} via ctx.${gate.member} through ${shape} (${face} face)`, () => { const { decl, receiver } = spell(gate.member); - expect(infer(`${decl} ${gate.call(receiver)}`, face)).toContain(gate.token); + for (const call of gatedCalls(gate, receiver)) { + const body = extractLoweredBody(handler(`async (ctx) => { ${decl} ${call} }`), `${face} 'h'`, face); + const ungranted = findings(face, { ...body, capabilities: [] }); + expect(ungranted.some((f) => f.includes(`'${gate.token}'`)), `the rule reads ${call}`).toBe(true); + expect(findings(face, body), call).toEqual([]); + } }); } } } }); + +/** + * The rebound siblings (#22837): a hook handler that names its context + * parameter something else, or destructures it, reaches the same gates through + * its own names, and the build rebinds them (`var hookCtx = ctx;`, + * `var { log } = ctx;`). Every spelling of every call of the census through + * each rebound shape infers its token. Where the publish rule reads the + * rebound receiver (a destructure off `ctx`, which the prologue spells), the + * ungranted body draws the gate's finding and the lowered one draws none; the + * rule does not read a renamed root (`hookCtx.log`), so there the lowered body + * draws none and the over-inference is the build's own margin. The hook face + * alone: the action face runs `(input, ctx)` and is not rebound. + */ +const REBOUND: Array<{ shape: string; spell: (member: string) => { param: string; receiver: string }; ruleReads: boolean }> = [ + { shape: 'a renamed context parameter', spell: (m) => ({ param: 'hookCtx', receiver: `hookCtx.${m}` }), ruleReads: false }, + { shape: 'a renamed context parameter, ?.', spell: (m) => ({ param: 'hookCtx', receiver: `hookCtx?.${m}` }), ruleReads: false }, + { shape: 'a renamed context parameter, whitespace', spell: (m) => ({ param: 'hookCtx', receiver: `hookCtx . ${m}` }), ruleReads: false }, + { shape: 'a destructured parameter', spell: (m) => ({ param: `{ ${m} }`, receiver: m }), ruleReads: true }, + { shape: 'a renamed destructured parameter', spell: (m) => ({ param: `{ ${m}: p_${m} }`, receiver: `p_${m}` }), ruleReads: true }, +]; + +describe('REBOUND: every gate is inferred through the handler’s own names, and the rule draws nothing on the lowered body', () => { + const lower = (param: string, body: string, face: Face): ExtractedBody => + extractLoweredBody(handler(`async (${param}) => { ${body} }`), `${face} 'h'`, face); + const judged = (face: Face, extracted: Pick): string[] => { + const body = { language: 'js', source: extracted.source, capabilities: extracted.capabilities }; + const stack = + face === 'hook' + ? { hooks: [{ name: 'h', object: 'x', events: ['beforeUpdate'], handler: 'h_fn', body }] } + : { actions: [{ name: 'a', label: 'A', objectName: 'x', type: 'script', target: 'x_a', body }] }; + return runAuthoringRules('build', { normalized: stack, parsed: stack, loweredHookRefs: new Set(['h_fn']) }) + .filter((f) => [HOOK_BODY_CAPABILITY_UNDECLARED, ACTION_BODY_CAPABILITY_UNDECLARED, ACTION_BODY_WRITE_CAPABILITY_UNDECLARED].includes(f.rule)) + .map((f) => `${f.rule}: ${f.message}`); + }; + + for (const gate of SANDBOX_CAPABILITY_GATES) { + for (const face of gate.kinds.filter((k): k is 'hook' => k === 'hook')) { + for (const { shape, spell, ruleReads } of REBOUND) { + it(`${gate.token} via ctx.${gate.member} through ${shape} (${face} face)`, () => { + const { param, receiver } = spell(gate.member); + // The body's own `ctx.input` is the context only where the parameter is named for it. + for (const call of gatedCalls(gate, receiver).map((c) => (param === 'hookCtx' ? c.replace(/^ctx\.input\./, 'hookCtx.input.') : c.replace(/^ctx\.input\.\w+ = /, 'void ')))) { + const body = lower(param, call, face); + expect(body.capabilities, call).toContain(gate.token); + if (face === 'hook' && gate.token === 'email.send') continue; + if (ruleReads) { + expect(judged(face, { ...body, capabilities: [] }).some((f) => f.includes(`'${gate.token}'`)), `the rule reads ${call}`).toBe(true); + } + expect(judged(face, body), call).toEqual([]); + } + }); + } + } + } +}); + +/** + * The one over-inference that is not harmless stays a refusal in every + * spelling: a hook handler that calls `ctx.email.send` lowers to a body granted + * `email.send`, and the hook parse every build runs after lowering refuses + * that grant (#32004), however the call is spelled. + */ +describe('a hook handler that sends mail is refused at build in every spelling the rule reads', () => { + const spellings = [ + 'await ctx.email.send({});', + 'await ctx?.email.send({});', + 'await ctx.email?.send({});', + 'await ctx.email.send?.({});', + 'await ctx . email . send ({});', + 'const { email } = ctx; await email?.send({});', + 'const e = ctx.email; await e?.send?.({});', + ]; + for (const call of spellings) { + it(call, () => { + const out = lowerCallables({ + hooks: [{ name: 'h', object: 'x', events: ['afterInsert'], handler: handler(`async (ctx) => { ${call} }`) }], + }); + const lowered = (out.lowered.hooks as Array<{ body: { capabilities: string[] } }>)[0]; + expect(lowered.body.capabilities).toContain('email.send'); + const r = HookSchema.safeParse(lowered); + expect(r.success).toBe(false); + expect(r.success ? '' : r.error.issues[0].message).toContain('A hook body cannot be granted `email.send`'); + }); + } + it('rebound: a renamed context parameter', () => { + const out = lowerCallables({ + hooks: [{ name: 'h', object: 'x', events: ['afterInsert'], handler: handler('async (hookCtx) => { await hookCtx?.email?.send({}); }') }], + }); + expect(HookSchema.safeParse((out.lowered.hooks as unknown[])[0]).success).toBe(false); + }); +}); diff --git a/packages/cli/test/lower-callables.test.ts b/packages/cli/test/lower-callables.test.ts index c7ef05dc706..1c9325e3e0a 100644 --- a/packages/cli/test/lower-callables.test.ts +++ b/packages/cli/test/lower-callables.test.ts @@ -499,14 +499,12 @@ describe('[#33214] lowerCallables — a handler hook\'s refusal catalogue', () = }); }); -// [#38653] `@objectstack/lint` tells an action body the build lowered from an -// inline `target` function apart from an authored one by its shape alone — a -// non-empty string `target` beside a body record (`isLoweredTargetBody` in -// `validate-action-body-capabilities.ts`) — and judges only the first for -// `api.write`. Its own pins build that shape by hand; this one holds it to what -// `lowerActionCallable` really emits, top-level and object-owned, so a lowering -// that stopped leaving the string ref would surface here, not as lint judging -// inferred grants as authored ones. +// [#38653] An action the build lowered from an inline `target` function keeps +// that shape — a non-empty string `target` beside a body record carrying the +// inferred grant. `@objectstack/lint`'s capability pins build the shape by +// hand (since #38690 the rule judges such a body like an authored one); this +// one holds it to what `lowerActionCallable` really emits, top-level and +// object-owned. describe('[#38653] lowerCallables — a lowered action keeps a string `target` beside its minted body', () => { const target = async (ctx: any) => { await ctx.api.object('doc').updateById(ctx.input.id, { stamped: true }); diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 6ff98f56cbd..7e71759c93a 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -3420,7 +3420,7 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // the sandbox gates (`hook-body-capability-undeclared`); no object write // carries a hook. runtimeTypes: ['action', 'object', 'hook'], - run: (stack, ctx) => validateActionBodyCapabilities(stack, ctx), + run: (stack) => validateActionBodyCapabilities(stack), }, // 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/index.ts b/packages/lint/src/index.ts index 18113c05715..155de88eaa3 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -1173,6 +1173,11 @@ export { ACTION_BODY_CAPABILITY_UNDECLARED, HOOK_BODY_CAPABILITY_UNDECLARED, } from './validate-action-body-capabilities.js'; +// [#38690] The sandbox's gate census the capability rule judges by, exported so +// the CLI's hook-body extractor pins its inference against this table itself +// rather than a copy: the rule judges a lowered body, so every gate it reads +// must be one the build infers. +export { SANDBOX_CAPABILITY_GATES, type SandboxCapabilityGate } 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/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 70202e8c570..97ec8128853 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -1552,9 +1552,8 @@ 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. 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`).', + 'inspector draws the list), or remove the call. An action body the build lowered from an inline ' + + '`target` function is judged the same way: its grant is the one the build inferred from its calls.', ], }; @@ -1570,7 +1569,8 @@ const HOOK_BODY_CAPABILITY_UNDECLARED_EXPLANATION: RuleExplanation = { '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. ' + - 'Only a body the author wrote is judged: a hook body the build lowered from an inline `handler` is not.', + 'A hook body the build lowered from an inline `handler` is judged the same way: its grant is the one the ' + + 'build inferred from its calls.', ], }; 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 666930ba65d..0b699b52426 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,8 +17,6 @@ import { SANDBOX_CAPABILITY_GATES, SANDBOX_LOG_LEVELS, bodyGatedCalls, - isLoweredHandlerBody, - isLoweredTargetBody, validateActionBodyCapabilities, } from './validate-action-body-capabilities.js'; import { runAuthoringRules } from './authoring-rules.js'; @@ -148,41 +146,8 @@ describe('arm (a): a hook body is judged like an action body (#37815)', () => { } }); - 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', - ]); - }); - }); + // [#38690] A body the build lowered is judged like an authored one: the + // pins live in `validate-action-body-capabilities.lowered-38690.test.ts`. 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'] });", [])] }); @@ -251,51 +216,6 @@ 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.lowered-38690.test.ts b/packages/lint/src/validate-action-body-capabilities.lowered-38690.test.ts new file mode 100644 index 00000000000..faf15586561 --- /dev/null +++ b/packages/lint/src/validate-action-body-capabilities.lowered-38690.test.ts @@ -0,0 +1,164 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A body the build lowered is judged like one the author wrote. + * + * `validate-action-body-capabilities` used to skip a hook body lowered from an + * inline `handler` (a string `handler` the build registered, or any string + * `handler` at a door that hands no lowered refs) and to judge an action body + * lowered from an inline `target` function for `api.write` alone. The grant on + * such a body is the build's inference, and that inference did not yet read + * every shape the rule reads, so a finding there would have named a grant the + * build forgot. The extractor now infers every gate through every receiver the + * rule reads (`ctx.MEMBER`, a local bound once to it, a destructure off `ctx`, + * a handle bound once to `.object(…)`), pinned in `@objectstack/cli` against + * this rule's own `SANDBOX_CAPABILITY_GATES`. So a lowered body that calls a + * gate without its token is one the sandbox refuses at the call, and the rule + * says so where it used to stay quiet. + * + * Each removed skip has its red-before cases (a lowered body calling a gate + * ungranted, spelled directly and through an alias), and the controls: the + * same lowered body granted is not refused. + */ + +import { describe, expect, it } from 'vitest'; + +import { + ACTION_BODY_CAPABILITY_UNDECLARED, + ACTION_BODY_WRITE_CAPABILITY_UNDECLARED, + HOOK_BODY_CAPABILITY_UNDECLARED, + validateActionBodyCapabilities, +} from './validate-action-body-capabilities.js'; +import { runAuthoringRules } from './authoring-rules.js'; +import { runRuntimeAuthoringRules } from './runtime-gate.js'; + +const TICKET = { + name: 'cb_ticket', + label: 'Ticket', + sharingModel: 'private', + fields: { name: { type: 'text', label: 'Name' }, done: { type: 'boolean', label: 'Done' } }, +}; + +/** A hook as `os build` leaves it: the string ref it registered, and the body it minted beside it. */ +const loweredHook = (source: string, capabilities: string[]) => ({ + name: 'cb_stamp', + object: 'cb_ticket', + events: ['beforeUpdate'], + handler: 'cb_stamp_fn', + body: { language: 'js', source, capabilities }, +}); + +/** An action as `os build` leaves it: the string `target` it registered, and the body it minted beside it. */ +const loweredAction = (source: string, capabilities: string[]) => ({ + name: 'cb_close', + label: 'Close', + objectName: 'cb_ticket', + type: 'script', + locations: ['record_page'], + target: 'cb_ticket_cb_close', + body: { language: 'js', source, capabilities }, +}); + +const REFS = new Set(['cb_stamp_fn']); +const ofRule = (fs: readonly T[], rule: string): T[] => fs.filter((f) => f.rule === rule); + +/** One gated call per token, spelled directly and through an alias. */ +const CALLS: ReadonlyArray<{ token: string; shape: 'direct' | 'alias'; source: string; faces: ReadonlyArray<'hook' | 'action'> }> = [ + { token: 'log', shape: 'direct', source: "ctx.log.info('x');", faces: ['hook', 'action'] }, + { token: 'log', shape: 'alias', source: "const l = ctx.log; l.info('x');", faces: ['hook', 'action'] }, + { token: 'crypto.uuid', shape: 'direct', source: 'var id = ctx.crypto.randomUUID();', faces: ['hook', 'action'] }, + { token: 'crypto.uuid', shape: 'alias', source: 'const { crypto } = ctx; var id = crypto.randomUUID();', faces: ['hook', 'action'] }, + { token: 'activity.append', shape: 'direct', source: "await ctx.activity.append({ text: 'x' });", faces: ['hook', 'action'] }, + { token: 'activity.append', shape: 'alias', source: "const { activity: a } = ctx; await a.append({ text: 'x' });", faces: ['hook', 'action'] }, + { token: 'api.transaction', shape: 'direct', source: 'await ctx.api.transaction(async () => {});', faces: ['hook', 'action'] }, + { token: 'api.transaction', shape: 'alias', source: 'const api = ctx.api; await api.transaction(async () => {});', faces: ['hook', 'action'] }, + { token: 'api.read', shape: 'direct', source: "var n = await ctx.api.object('cb_ticket').count({});", faces: ['hook', 'action'] }, + { token: 'api.read', shape: 'alias', source: "const repo = ctx.api.object('cb_ticket');\nreturn repo.findOne({});", faces: ['hook', 'action'] }, + { token: 'api.read', shape: 'direct', source: "ctx.input.label = await ctx.title('account_id');", faces: ['hook'] }, + { token: 'api.read', shape: 'alias', source: "const t = ctx.title; ctx.input.label = await t('account_id');", faces: ['hook'] }, +]; + +describe('a hook body lowered from a handler is judged (the isLoweredHandlerBody skip is gone)', () => { + for (const { token, shape, source, faces } of CALLS) { + if (!faces.includes('hook')) continue; + it(`${token}, ${shape}: refused ungranted under os validate / build / lint, and passes granted`, () => { + const refused = validateActionBodyCapabilities({ hooks: [loweredHook(source, [])] }); + expect(refused.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [HOOK_BODY_CAPABILITY_UNDECLARED, 'error', 'hooks[0].body.capabilities'], + ]); + expect(refused[0].message).toContain(`'${token}'`); + const stack = { objects: [TICKET], hooks: [loweredHook(source, [])] }; + for (const command of ['validate', 'build', 'lint'] as const) { + const run = { normalized: stack, parsed: stack, loweredHookRefs: REFS }; + expect(ofRule(runAuthoringRules(command, run), HOOK_BODY_CAPABILITY_UNDECLARED).map((f) => f.path), command).toEqual([ + 'hooks[0].body.capabilities', + ]); + } + // CONTROL: the same lowered body, granted. + expect(validateActionBodyCapabilities({ hooks: [loweredHook(source, [token])] })).toEqual([]); + }); + } + + it('the hook save door judges a build artifact’s lowered body, and admits it granted', () => { + const source = "const l = ctx.log; l.info('x');"; + const refused = runRuntimeAuthoringRules({ type: 'hook', item: loweredHook(source, []), context: { objects: [TICKET] } }); + expect(ofRule(refused.errors, HOOK_BODY_CAPABILITY_UNDECLARED).map((e) => e.path)).toEqual(['hooks[0].body.capabilities']); + const granted = runRuntimeAuthoringRules({ type: 'hook', item: loweredHook(source, ['log']), context: { objects: [TICKET] } }); + expect(ofRule(granted.errors, HOOK_BODY_CAPABILITY_UNDECLARED)).toEqual([]); + }); + + it('a lowered hook body’s ctx.email.send is refused like an authored one’s: no grant fixes it', () => { + const fs = validateActionBodyCapabilities({ hooks: [loweredHook("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'"); + }); +}); + +describe('an action body lowered from a target is judged for every token (the non-write isLoweredTargetBody skip is gone)', () => { + for (const { token, shape, source, faces } of CALLS) { + if (!faces.includes('action')) continue; + it(`${token}, ${shape}: refused ungranted, top level and inline, and passes granted`, () => { + const top = validateActionBodyCapabilities({ actions: [loweredAction(source, [])] }); + expect(top.map((f) => [f.rule, f.severity, f.path])).toEqual([ + [ACTION_BODY_CAPABILITY_UNDECLARED, 'error', 'actions[0].body.capabilities'], + ]); + expect(top[0].message).toContain(`'${token}'`); + const inline = validateActionBodyCapabilities({ objects: [{ ...TICKET, actions: [loweredAction(source, [])] }] }); + expect(inline.map((f) => f.path)).toEqual(['objects[0].actions[0].body.capabilities']); + // CONTROL: the same lowered body, granted. + expect(validateActionBodyCapabilities({ actions: [loweredAction(source, [token])] })).toEqual([]); + }); + } + + it('os validate / build / lint and the action and object doors refuse it the same way', () => { + const source = 'await ctx.api.transaction(async () => { await ctx.api.object(\'cb_ticket\').insert({ name: \'x\' }); });'; + const lowered = loweredAction(source, ['api.write']); + const top = { objects: [TICKET], actions: [lowered] }; + const inline = { objects: [{ ...TICKET, actions: [lowered] }] }; + for (const [stack, path] of [ + [top, 'actions[0].body.capabilities'], + [inline, 'objects[0].actions[0].body.capabilities'], + ] as const) { + 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).map((f) => f.path), command).toEqual([path]); + } + } + const door = runRuntimeAuthoringRules({ type: 'action', item: lowered, context: { objects: [TICKET] } }); + expect(ofRule(door.errors, ACTION_BODY_CAPABILITY_UNDECLARED).map((e) => e.path)).toEqual(['actions[0].body.capabilities']); + const objectDoor = runRuntimeAuthoringRules({ type: 'object', item: { ...TICKET, actions: [lowered] }, context: { objects: [] } }); + expect(ofRule(objectDoor.errors, ACTION_BODY_CAPABILITY_UNDECLARED)).toHaveLength(1); + // CONTROL: granted both tokens, every door admits it. + const granted = loweredAction(source, ['api.write', 'api.transaction']); + expect(validateActionBodyCapabilities({ actions: [granted] })).toEqual([]); + const grantedDoor = runRuntimeAuthoringRules({ type: 'action', item: granted, context: { objects: [TICKET] } }); + expect(ofRule(grantedDoor.errors, ACTION_BODY_CAPABILITY_UNDECLARED)).toEqual([]); + }); + + it('a lowered body’s write keeps its own id and words, beside the other tokens', () => { + const source = "await ctx.api.object('cb_ticket').insert({ name: 'x' }); ctx.log.warn('w');"; + const fs = validateActionBodyCapabilities({ actions: [loweredAction(source, [])] }); + expect(fs.map((f) => f.rule)).toEqual([ACTION_BODY_WRITE_CAPABILITY_UNDECLARED, ACTION_BODY_CAPABILITY_UNDECLARED]); + expect(fs[1].message).toContain("'log'"); + }); +}); diff --git a/packages/lint/src/validate-action-body-capabilities.ts b/packages/lint/src/validate-action-body-capabilities.ts index 8a2414f71d5..a95537eac99 100644 --- a/packages/lint/src/validate-action-body-capabilities.ts +++ b/packages/lint/src/validate-action-body-capabilities.ts @@ -25,9 +25,9 @@ * (`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 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). + * the next step of the same build; its pins hold that shape by shape. It reads + * every other gate through the same receivers too, so a lowered body is judged + * like an authored one (see the last section). * * ## How the source is read * @@ -86,16 +86,25 @@ * 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 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). + * Lowered bodies are judged like authored ones (#38690). The rule does not + * tell them apart: a body beside a string `handler` or `target` is judged + * whether `os build` / `os verify` lowered it from an inline function or the + * author wrote it by hand. A lowered body carries the grant the build inferred + * from its calls, and the cli extractor reads each gated call the way this + * rule reads it: every gate of {@link SANDBOX_CAPABILITY_GATES}, through each + * receiver (`ctx.MEMBER`, a local bound once to it, a destructure off `ctx`, a + * handle bound once to `.object(…)`, a hook handler's destructured context, + * which the build rebinds to a destructure off `ctx`), with `?.` or whitespace + * on either side of a step, the optional call `LEAF?.(…)`, and a comment + * between steps; it reads more besides (a renamed context root, a spelling + * inside a string). Its parity pin in + * `@objectstack/cli` judges each of those spellings through this rule twice, + * ungranted (a finding) and lowered (none). So a fresh build of an inline + * handler draws no finding here, and a lowered body this rule refuses is one + * whose grant was lost after the build, which the sandbox refuses at the call. + * The build's reading covers this rule's by that enumeration, not by proof: a + * spelling outside it may still diverge, and the finding then names the token + * the build missed. */ import { collectActionBodies } from './validate-action-body-writes.js'; @@ -376,68 +385,16 @@ 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; -} - -/** - * 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}); an action body lowered from a - * `target` function is judged for `api.write` only ({@link isLoweredTargetBody}). + * the gates and the ids), whether the author wrote the body or the build + * lowered it from a handler or a `target` function (#38690). */ -export function validateActionBodyCapabilities( - stack: AnyRec, - ctx?: { loweredHookRefs?: ReadonlySet }, -): ActionBodyCapabilityFinding[] { +export function validateActionBodyCapabilities(stack: AnyRec): 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'); @@ -456,7 +413,6 @@ export function validateActionBodyCapabilities( }); continue; } - if (lowered) continue; findings.push({ severity: 'error', rule: ACTION_BODY_CAPABILITY_UNDECLARED, @@ -473,7 +429,6 @@ 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}`; for (const { token, calls } of bodyGatedCalls(source, 'hook')) { if (granted.includes(token)) continue; 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 5cb8412caa4..fd4d43f80f1 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 authored L2 hook body that calls a member the QuickJS sandbox gates +// #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` @@ -18,9 +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, 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 ' + + 'or loaded by os validate / os build / os lint, whether the author wrote the body or os build lowered it from ' + + 'an inline handler or target function: 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), ' @@ -32,18 +31,20 @@ 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 (a later ' - + 'change carries the lowered reading).', + + 'function, needs no change: os build infers the grant from each gated call in each spelling the rule reads ' + + '(?., whitespace or a comment between steps, the optional call), so the body it lowers carries the token, and ' + + 'that lowered body is judged like an authored one.', 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, 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 ' + + 'sandbox runner installs. A hook body os build lowered from an inline handler, and an action body it lowered ' + + 'from an inline target function, are judged the same way: their grant is the build\'s inference, which reads ' + + 'each gated call in each spelling the rule reads, pinned spelling by spelling against the rule, so a hook ' + + 'written as a handler and an action written as a target function build clean. 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.', diff --git a/packages/spec/src/migrations/entries/semantic/19.lowered-hook-and-action-bodies-capabilities-judged.ts b/packages/spec/src/migrations/entries/semantic/19.lowered-hook-and-action-bodies-capabilities-judged.ts new file mode 100644 index 00000000000..f26773980f2 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.lowered-hook-and-action-bodies-capabilities-judged.ts @@ -0,0 +1,58 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #38690 — `hook-body-capability-undeclared` and +// `action-body-capability-undeclared` (@objectstack/lint) now judge an L2 body +// beside a string hook `handler` or action `target`, lowered by the build or +// written by hand, the way they judge any other body. Until now such a body +// was taken for one the build lowered and skipped (a lowered action body was +// judged for `api.write` alone), because the build's capability inference did +// not yet read every gated call the rule reads; it does now, in each spelling +// the rule reads (`api.transaction` and reads through a bound handle since +// #38653; the member aliases, `?.`, whitespace, the optional call and a +// comment between steps since #38690). It narrows what the authoring doors +// accept; no key is removed, so there is no tombstone. Measured first-party +// exposure at this change: zero (the example apps and the first-party +// connector apps, loaded, normalized and lowered as `os validate` does). Not +// converted: whether the body should hold the grant or drop the call is the +// author's choice. +export const entry: SemanticMigration = { + id: 'lowered-hook-and-action-bodies-capabilities-judged', + surface: + 'hooks[].body and actions[].body (an object\'s inline actions[] included) whose body.language is js and that sit ' + + 'beside a string hook handler or action target, lowered by the build (os build / os verify, from an inline ' + + 'handler or target function) or written by hand, as loaded by os validate / os build / os lint or saved ' + + 'through the metadata doors (PUT /api/v1/meta/hook/NAME, PUT /api/v1/meta/action/NAME, an object write, the ' + + 'package publish doors): a source that calls a member the sandbox gates without its token in ' + + 'body.capabilities, for every token (an action body\'s writes were already judged)', + replacement: + 'A body written by hand beside a string handler or target: declare the token the finding names in ' + + 'body.capabilities (body.capabilities: [\'api.write\', \'api.transaction\'] for a body that writes inside ' + + 'ctx.api.transaction), or remove the call. A handler or target function the build lowers needs no change: os ' + + 'build infers the grant from each gated call in each spelling the rule reads (ctx.MEMBER, a local bound once ' + + 'to it, a destructure off ctx, a handle bound once to ctx.api.object(…), a hook handler\'s destructured ' + + 'context; ?. or whitespace or a comment between steps, the optional call), so its lowered body ' + + 'carries the token. A build artifact whose lowered body lost a token is refused at error as ' + + '`hook-body-capability-undeclared` or `action-body-capability-undeclared` (422 INVALID_METADATA at the hook ' + + 'and action doors): rebuild it, or declare the token. A hook body is never granted email.send: a hook handler ' + + 'that calls ctx.email.send, in any of those spellings, is refused at build by the hook parse; send the mail ' + + 'from an action, a job or a flow.', + reason: + 'The sandbox refuses a call the body was not granted with 403 INSUFFICIENT_PRIVILEGES at the call site, whether ' + + 'the author or the build wrote the grant. A body beside a string handler or target was exempt from the check ' + + 'because the rule took it for a lowered one, whose grant was the build\'s inference, and that inference missed ' + + 'calls the rule reads, so a finding there would have named a grant the build forgot. The inference now reads ' + + 'each gate of the rule\'s own table, through each receiver and in each spelling the rule reads, pinned ' + + 'spelling by spelling against the rule (each judged ungranted, drawing the finding, and lowered, drawing ' + + 'none), so a lowered body the rule refuses is one whose grant was lost after the build and that fails at the ' + + 'call every time it runs, and a hand-written body it refuses is one that fails the same way. The exemption ' + + 'only hid that failure until runtime. 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.', + acceptanceCriteria: + 'Run `os validate` or `os build` over a stack with inline hook handlers and action target functions: no ' + + '`hook-body-capability-undeclared` finding and no `action-body-capability-undeclared` finding. PUT ' + + '/api/v1/meta/hook/NAME and PUT /api/v1/meta/action/NAME with a rebuilt artifact\'s hook or action, or with a ' + + 'hand-written body beside a string handler or target that declares each token it calls, answer 200.', +};