diff --git a/.changeset/37815-body-capabilities-every-gate.md b/.changeset/37815-body-capabilities-every-gate.md new file mode 100644 index 00000000000..c4f0111e975 --- /dev/null +++ b/.changeset/37815-body-capabilities-every-gate.md @@ -0,0 +1,30 @@ +--- +'@objectstack/lint': minor +'@objectstack/spec': 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 #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. + +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. +- `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']`. +- 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. + +`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 71b0b0f54ab..4d0a3f69d40 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`, `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) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | | 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) | ✓ | ✓ | ✓ | ✓ᶠ | | 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/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 337571bb04d..43d97edfe92 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -3400,8 +3400,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/index.ts b/packages/lint/src/index.ts index 77aa5a13a74..38320b2133e 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -1165,7 +1165,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/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index af056f14e60..0c6ae7875c4 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -1423,7 +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({ … })`, or `.update({ id, … })` for one record. `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.', @@ -1522,6 +1524,56 @@ 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 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 ' + + '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`).', + ], +}; + +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. ' + + 'Only a body the author wrote is judged: a hook body the build lowered from an inline `handler` is not.', + ], +}; + const SEED_RECORD_UNKNOWN_FIELD_EXPLANATION: RuleExplanation = { rule: 'seed-record-unknown-field', covers: 'which keys a seed record may carry', @@ -7335,6 +7387,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..666930ba65d --- /dev/null +++ b/packages/lint/src/validate-action-body-capabilities.hook-and-tokens-37815.test.ts @@ -0,0 +1,323 @@ +// 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, + isLoweredHandlerBody, + isLoweredTargetBody, + 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']]); + } + }); + + 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', () => { + 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([]); + }); + + 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'); + }); + + 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); + }); + }); +}); diff --git a/packages/lint/src/validate-action-body-capabilities.ts b/packages/lint/src/validate-action-body-capabilities.ts index 6963e03b60d..8a2414f71d5 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 * @@ -19,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: @@ -52,9 +56,50 @@ * 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. + * + * 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'; +import { recordsOf } from './object-graph.js'; type AnyRec = Record; @@ -84,6 +129,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(''); @@ -120,9 +215,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, '\\$'); @@ -155,27 +252,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. @@ -196,31 +296,204 @@ 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}.`; +} + +/** + * 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}). + */ +export function validateActionBodyCapabilities( + stack: AnyRec, + ctx?: { loweredHookRefs?: ReadonlySet }, +): ActionBodyCapabilityFinding[] { const findings: ActionBodyCapabilityFinding[] = []; if (!stack || typeof stack !== 'object') return findings; + const loweredActions = loweredActionBodyPaths(stack); 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.", - }); + 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'); + 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; + } + if (lowered) 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 : []; + 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; + const listed = calls.join(', '); + const mail = token === 'email.send'; + findings.push({ + severity: 'error', + rule: HOOK_BODY_CAPABILITY_UNDECLARED, + where: `hook "${name}" › body`, + 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')}`), + hint: mail + ? 'Remove the ctx.email.send call, and send mail on a record change from an action, a job or a flow.' + : `Add '${token}' to the hook's body.capabilities, or remove the call.`, + }); + } + }); return findings; } 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..5cb8412caa4 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.hook-and-action-bodies-calling-an-ungranted-gate-refused.ts @@ -0,0 +1,55 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #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` +// (@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, 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), ' + + '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`. 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).', + 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 ' + + '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 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.', +};