diff --git a/.changeset/38630-sandbox-update-by-id.md b/.changeset/38630-sandbox-update-by-id.md new file mode 100644 index 00000000000..820ed9c7bf6 --- /dev/null +++ b/.changeset/38630-sandbox-update-by-id.md @@ -0,0 +1,28 @@ +--- +'@objectstack/runtime': patch +'@objectstack/cli': patch +'@objectstack/lint': minor +'@objectstack/spec': minor +--- + +fix(runtime,cli,lint,spec)!: a sandboxed body's `ctx.api.object(X).updateById(id, patch)` writes the row + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + + + +**BREAKING** for two authoring doors, which now refuse at save and in `os validate` a body that calls `updateById` where they already refused the same write spelled any other way: + +| FROM | TO | +|:--|:--| +| a `type: 'script'` action whose body calls `ctx.api.object(X).updateById(…)` without `api.write` in `body.capabilities`: saved, then threw at every run | refused as `action-body-write-capability-undeclared`; declare `api.write` in the action's `body.capabilities` | +| a `runAs: 'system'` hook, or a `type: 'script'` action, whose body calls `ctx.api.object('sys_user_position' \| 'sys_user_permission_set' \| 'sys_invitation' \| 'sys_member').updateById(…)`: saved, then threw `TypeError: not a function` at every run | refused at `body.source` with the existing prescription (a `runAs: 'user'` hook or flow, or the organization endpoints) | + +Neither body ever worked: before this change both threw `TypeError: not a function`, because the sandbox did not install `updateById`. Now that the call is installed, the first is refused for its missing `api.write` (INSUFFICIENT_PRIVILEGES) and the second by the run-time security middleware, and both are also refused at save. Stored metadata is not rewritten or refused at boot; the next save of such a body is refused with the fix named. + +An action body or hook body that called `ctx.api.object(X).updateById(id, patch)` threw `TypeError: not a function` and wrote nothing, although `HookObjectApi.updateById` and `IScopedObjectRepository.updateById` declare the member, the in-process repository serves it, and the hook-bodies guide teaches it as the way an action body persists. The QuickJS sandbox now installs `updateById` beside the other write leaves, behind the same `api.write` capability, so the call writes the record the id names and answers it. `update({ id, … })` is unchanged. + +The id is judged before the host is called: anything but a non-empty string or a non-zero number (an object, an array, `null`, `undefined`, `''`, `0`) is refused with `VALIDATION_ERROR` / 400 naming the call, and nothing is written. Such ids were already refused one layer down, with messages about filters; the refusal now names the argument. To write every row a filter matches, call `update(data, { where, multi: true })`. + +`objectstack build` now infers `api.write` for a lowered handler whose only write is `updateById`, so the body it produces is granted the call. The explanation of `action-body-write-capability-undeclared` and the build's `.create()` refusal list `updateById` among the sandbox's write leaves. diff --git a/content/docs/automation/hook-bodies.mdx b/content/docs/automation/hook-bodies.mdx index 4cdd61ef5f7..b97f9867fd4 100644 --- a/content/docs/automation/hook-bodies.mdx +++ b/content/docs/automation/hook-bodies.mdx @@ -323,7 +323,7 @@ The dropped case is the dangerous one: nothing fails, the step reports success, Which hooks these rules can *see* depends on the command, because every rule in this family opens on `body.language === 'js'`. A hook authored as an inline `handler` function carries no `body`, so it is judged only where the command has first lowered the handler to a metadata body: `objectstack build` always has (it lowers before it parses — see [How the build lowers a handler](#build-pipeline)), and since [#16095](https://github.com/objectstack-ai/objectstack/issues/16095) `objectstack lint` judges that same lowered view, so an author who runs only the pre-flight is told the same thing the build would refuse. Since [#16544](https://github.com/objectstack-ai/objectstack/issues/16544) `objectstack validate` lowers before it parses as well, so all three commands judge the same view of a handler-authored hook — a stack `objectstack validate` passes is one `objectstack build` does not refuse on this family. A handler the build cannot lower (a forbidden token, a module-scope identifier) has no body on any command and is reported by the lowering rules instead, never guessed at here. -Only literal object names and literal payload keys are seen; a `sudo()` chain, a dynamic object name and an object this stack does not declare are all skipped, so the rule has no opinion on them. `.create()` is skipped too, and since [#16249](https://github.com/objectstack-ai/objectstack/issues/16249) it cannot even arrive: `objectstack build` refuses `.create(` at lowering, so a handler spelling it is bundled and never becomes a `body` these rules parse, and the write-shape ledger no longer advertises the verb. The reason behind that refusal is about the **sandbox** rather than the engine: the VM-side `ctx.api.object()` installs `insert` / `update` / `delete` / `updateMany` / `deleteMany` / `upsert` and no `create` leaf, and the `IScopedObjectRepository` contract declares `insert` only — so a body calling `.create()` threw `TypeError: not a function` on its first run, aborting the triggering write under the default `onError: 'abort'`. A loud failure, never a silent drop; the same payload spelled `.insert()` is what the rules judge. The flow surface has carried the same gate as `flow-update-readonly-field` since [#3425](https://github.com/objectstack-ai/objectstack/issues/3425), and since [#15394](https://github.com/objectstack-ai/objectstack/issues/15394) it reports a non-`runAs: 'system'` `create_record` node's static-`readonly` write at the same **error**, again with no conditional finding on a create. +Only literal object names and literal payload keys are seen; a `sudo()` chain, a dynamic object name and an object this stack does not declare are all skipped, so the rule has no opinion on them. `.create()` is skipped too, and since [#16249](https://github.com/objectstack-ai/objectstack/issues/16249) it cannot even arrive: `objectstack build` refuses `.create(` at lowering, so a handler spelling it is bundled and never becomes a `body` these rules parse, and the write-shape ledger no longer advertises the verb. The reason behind that refusal is about the **sandbox** rather than the engine: the VM-side `ctx.api.object()` installs `insert` / `update` / `updateById` / `delete` / `updateMany` / `deleteMany` / `upsert` and no `create` leaf, and the `IScopedObjectRepository` contract declares `insert` only — so a body calling `.create()` threw `TypeError: not a function` on its first run, aborting the triggering write under the default `onError: 'abort'`. A loud failure, never a silent drop; the same payload spelled `.insert()` is what the rules judge. The flow surface has carried the same gate as `flow-update-readonly-field` since [#3425](https://github.com/objectstack-ai/objectstack/issues/3425), and since [#15394](https://github.com/objectstack-ai/objectstack/issues/15394) it reports a non-`runAs: 'system'` `create_record` node's static-`readonly` write at the same **error**, again with no conditional finding on a create. The table above is about a **hook** body. An **action** body is the one surface where the answer changes, so read this before you move a body from one to the other: an action body runs **elevated** — its `ctx.api` is built over the caller's envelope with `isSystem` set, which is the same trusted posture that lets an action bypass row and field permissions — and the static strip applies only to non-system callers. So `ctx.api.object('x').update({ someReadonlyField })` **lands** in an action, and there is no finding for it. Elevation does not waive the *conditional* lock, though, so that half does carry across: `action-api-update-readonly-when-field` — a **warning** — on an action body's literal `ctx.api` update to a `readonlyWhen` field ([#13770](https://github.com/objectstack-ai/objectstack/issues/13770)). Net effect when you move a body: a `readonly` write changes behaviour, a `readonlyWhen` write does not. @@ -452,7 +452,7 @@ The extractor scans each body for known patterns and adds the matching capabilit | Pattern in source | Inferred capability | |---|---| | `*.object(…).find / findOne / count / aggregate / get / list` | `api.read` | -| `*.object(…).insert / update / upsert / delete / patch / remove / create` | `api.write` | +| `*.object(…).insert / update / updateById / updateMany / upsert / delete / deleteMany / patch / remove / create` | `api.write` | | `ctx.crypto.randomUUID` | `crypto.uuid` | | `ctx.log.info / warn / error / debug` | `log` | | `*.title()` — the related-record form only; bare `ctx.title()` names this record and needs no token | `api.read` | diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 71244eff42d..4d5e76db7b2 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -522,7 +522,7 @@ orthogonal to both, and no cell here can carry it; it is written out in | Page variable declarations — each name once and never blank, a `defaultValue` of its declared type, a `source` naming a component the page holds (#28663, #28725) | ✓ | ✓ | ✓ | ✓ᵖ | | JSX / React page source parses (ADR-0080/0081) | ✓ | ✓ | ✓ | — | | Script action bodies compile in the runtime's wrapper — an L2 action's `body.source` that does not compile as the body of `(async (input, ctx) => { … })`, most often `const input = …` redeclaring a parameter; an object write runs it over its inline `actions[]`, so an object write cannot republish a refused body (`action-body-does-not-compile`, #34884) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | -| Script action bodies hold the grant they call — an L2 action body that calls a `ctx.api` write (`insert`, `update`, `delete`, `updateMany`, `deleteMany`, `upsert`) without `api.write` in its `body.capabilities`, which the sandbox refuses at every call (`action-body-write-capability-undeclared`, #35143) | ✓ | ✓ | ✓ | ✓ᵃᶜᵒ | +| 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) | ✓ | ✓ | ✓ | ✓ˢ | | 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) | ✓ | ✓ | ✓ | ✓ʰ | | Approval-node approvers (ADR-0090 D3) | ✓ | ✓ | ✓ | ✓ᶠ | diff --git a/packages/cli/src/utils/extract-hook-body.ts b/packages/cli/src/utils/extract-hook-body.ts index 0efa13cd7ed..9fcd65a4238 100644 --- a/packages/cli/src/utils/extract-hook-body.ts +++ b/packages/cli/src/utils/extract-hook-body.ts @@ -356,7 +356,7 @@ const FORBIDDEN_PATTERNS: Array<{ rx: RegExp; reason: string; face?: LoweringFac // contract `IScopedObjectRepository` declares `insert` and NOT `create` // (packages/spec/src/contracts/scoped-context.ts — `create` is listed there // as measured and deliberately excluded), and the VM installs exactly - // `insert / update / delete / updateMany / deleteMany / upsert` as the + // `insert / update / updateById / delete / updateMany / deleteMany / upsert` as the // `ctx.api.object()` write leaves (`installCtx`, // runtime/src/sandbox/quickjs-runner.ts). So a lowered body's `.create()` is // `TypeError: not a function` on its FIRST run, and under a hook's default @@ -387,7 +387,8 @@ const FORBIDDEN_PATTERNS: Array<{ rx: RegExp; reason: string; face?: LoweringFac rx: /(? { expect(extractHookBody(fn, 'hook c2').capabilities).toEqual(['api.write']); }); + // `updateById` is a sandbox `api.write` leaf too, the id-first write the spec + // contract declares. `update\b` does not match inside the name, so the verb is + // named in the pattern; a handler whose only write is it must get the grant. + it('infers api.write from a lone updateById', () => { + const fn = async (ctx: any) => { + await ctx.api.object('crm_deal').updateById(ctx.recordId, { stage: 'won' }); + }; + expect(extractHookBody(fn, 'hook c3').capabilities).toEqual(['api.write']); + }); + + it('infers api.write from updateById on a bound handle', () => { + const fn = async (ctx: any) => { + const deals = ctx.api.object('crm_deal'); + await deals.updateById(ctx.recordId, { stage: 'won' }); + }; + expect(extractHookBody(fn, 'hook c4').capabilities).toEqual(['api.write']); + }); + // [#35143] The shapes the publish check `action-body-write-capability-undeclared` // reads (`bodyApiWriteCalls`) beyond a direct chain. Each lowered without a // grant before, so `os build` lowered a handler and then refused it. @@ -414,7 +432,7 @@ describe('extractHookBody', () => { // Same family as `sudo()` above, one layer over. The host `ObjectRepository` // aliases `create(data)` to `insert(data)` and the spec contract // `IScopedObjectRepository` declares `insert` only, while the VM installs - // `insert / update / delete / updateMany / deleteMany / upsert` and no + // `insert / update / updateById / delete / updateMany / deleteMany / upsert` and no // `create` leaf — so a lowered body's `.create()` TypeErrors on its first // run and, under a hook's default `onError: 'abort'`, aborts the triggering // write. What made it worse than an omission: the extractor ledger in @@ -442,7 +460,7 @@ describe('extractHookBody', () => { message = (err as Error).message; } expect(message).toMatch(/`\.insert\(\{ \.\.\. \}\)`/); - expect(message).toMatch(/`insert` \/ `update` \/ `delete` \/ `updateMany` \/ `deleteMany` \/ `upsert`/); + expect(message).toMatch(/`insert` \/ `update` \/ `updateById` \/ `delete` \/ `updateMany` \/ `deleteMany` \/ `upsert`/); expect(message).toMatch(/no `create` leaf/); // The carve-out is stated in the refusal itself, so an author who hits it // over an `Object.create()` false positive is told it is not the subject. diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 7f72959de0a..f29f93e121a 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -3354,7 +3354,7 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ run: (stack) => validateActionBodyCompiles(stack), }, // [#35143] An L2 action body that calls a write leaf of `ctx.api` (`insert`, - // `update`, `delete`, `updateMany`, `deleteMany`, `upsert`) without granting + // `update`, `updateById`, `delete`, `updateMany`, `deleteMany`, `upsert`) without granting // itself `api.write` (`action-body-write-capability-undeclared`). The sandbox // refuses the call at the call site, so the action answers 403 on every click // that reaches it. Gating: the grant and the refusal are both facts. Read, diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index da1ba7e4f50..c75e8eae41c 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -1506,10 +1506,10 @@ const ACTION_BODY_WRITE_CAPABILITY_UNDECLARED_EXPLANATION: RuleExplanation = { covers: 'the grant a script action body\'s writes need', paragraphs: [ 'A script action body runs in the QuickJS sandbox with only the capabilities its `body.capabilities` ' + - 'lists (none by default). The sandbox installs the six `ctx.api` write leaves (`insert`, `update`, ' + - '`delete`, `updateMany`, `deleteMany`, `upsert`) behind `api.write`, and a call the body was not ' + - 'granted throws at the call site: the action answers `403 INSUFFICIENT_PRIVILEGES` every time it ' + - 'reaches the call, and nothing is written.', + 'lists (none by default). The sandbox installs the `ctx.api` write leaves (`insert`, `update`, ' + + '`updateById`, `delete`, `updateMany`, `deleteMany`, `upsert`) behind `api.write`, and a call the ' + + 'body was not granted throws at the call site: the action answers `403 INSUFFICIENT_PRIVILEGES` ' + + 'every time it reaches the call, and nothing is written.', 'The rule reads the body\'s source with comments, strings and template literals blanked, and finds ' + 'a write leaf called through `ctx.api` (with `?.` allowed), through a local bound once to `ctx.api` ' + '(`const api = ctx.api`, or `api` destructured from `ctx`), or through a handle bound once to ' + diff --git a/packages/lint/src/validate-action-body-capabilities.test.ts b/packages/lint/src/validate-action-body-capabilities.test.ts index 872fbb973f0..98d1092d9ae 100644 --- a/packages/lint/src/validate-action-body-capabilities.test.ts +++ b/packages/lint/src/validate-action-body-capabilities.test.ts @@ -58,6 +58,17 @@ describe('validateActionBodyCapabilities (#35143)', () => { expect(findings[0].hint).toContain("Add 'api.write'"); }); + // `updateById` is a write leaf the sandbox installs behind `api.write`: an + // ungranted call is refused there, so it is refused here, named as the call. + it('refuses an updateById write with no api.write grant, and passes it once granted', () => { + const source = "await ctx.api.object('pr_task').updateById(ctx.recordId, { done: true });"; + const refused = validateActionBodyCapabilities({ actions: [action(source, ['api.read'])] }); + expect(refused).toHaveLength(1); + expect(refused[0]).toMatchObject({ severity: 'error', rule: ACTION_BODY_WRITE_CAPABILITY_UNDECLARED }); + expect(bodyApiWriteCalls(source)).toEqual(['updateById']); + expect(validateActionBodyCapabilities({ actions: [action(source, ['api.write'])] })).toEqual([]); + }); + it('refuses when capabilities is absent (the spec default is none)', () => { expect( validateActionBodyCapabilities({ actions: [action("await ctx.api.object('pr_task').insert({ name: 'x' });")] }), diff --git a/packages/lint/src/validate-action-body-capabilities.ts b/packages/lint/src/validate-action-body-capabilities.ts index 01222d90333..6963e03b60d 100644 --- a/packages/lint/src/validate-action-body-capabilities.ts +++ b/packages/lint/src/validate-action-body-capabilities.ts @@ -8,8 +8,9 @@ * * An action body runs in the QuickJS sandbox with exactly the capabilities its * `body.capabilities` grants (`HookBodyCapability`, `@objectstack/spec/data`). - * The sandbox installs the six write leaves of `ctx.api.object(name)` — - * `insert`, `update`, `delete`, `updateMany`, `deleteMany`, `upsert` — behind + * The sandbox installs the write leaves of `ctx.api.object(name)` — + * `insert`, `update`, `updateById`, `delete`, `updateMany`, `deleteMany`, + * `upsert` — behind * the `api.write` token (`installCtx`, `packages/runtime/src/sandbox/ * quickjs-runner.ts`), and a call the body was not granted throws at the call * site: the action answers `403 INSUFFICIENT_PRIVILEGES` on every click that @@ -67,6 +68,7 @@ export const ACTION_BODY_WRITE_CAPABILITY_UNDECLARED = 'action-body-write-capabi export const SANDBOX_API_WRITE_METHODS: readonly string[] = [ 'insert', 'update', + 'updateById', 'delete', 'updateMany', 'deleteMany', diff --git a/packages/lint/src/validate-action-body-writes.ts b/packages/lint/src/validate-action-body-writes.ts index 6278887f019..d84822910cd 100644 --- a/packages/lint/src/validate-action-body-writes.ts +++ b/packages/lint/src/validate-action-body-writes.ts @@ -120,10 +120,11 @@ export const ACTION_RECORD_WRITE_DISCARDED = 'action-record-write-discarded'; /** * The `ctx.api.object(…)` member the `action-record-write-discarded` hint * prescribes. It must be a write leaf the sandbox installs on a body's - * `ctx.api.object(…)` (`WRITE` in packages/runtime/src/sandbox/quickjs-runner.ts): - * the hint once named `updateById`, which the host repository has and the - * sandbox does not, so following it traded a silent no-op for a - * `TypeError: not a function`. Its test pins it to `SANDBOX_API_WRITE_METHODS` + * `ctx.api.object(…)` (`WRITE` in packages/runtime/src/sandbox/quickjs-runner.ts). + * The hint once named `updateById` while the sandbox did not install it, so + * following it traded a silent no-op for a `TypeError: not a function`; the + * sandbox installs it now, and the hint keeps `update({ id, … })`, the form + * `HookObjectApi.update` documents. Its test pins it to `SANDBOX_API_WRITE_METHODS` * (validate-action-body-capabilities.ts), which is itself pinned to the * runner's list. Not re-exported from the package index. Annotated `string` * because it is a method name, not a rule id: the rule-id barrel census @@ -400,9 +401,9 @@ export function validateActionBodyWrites(stack: AnyRec): ActionBodyWriteFinding[ // The remedy names `update({ id, … })`, the single-record write the // sandbox installs (`WRITE` in packages/runtime/src/sandbox/ // quickjs-runner.ts) and the shape `HookObjectApi.update` documents: - // the id travels inside the payload. ⛔ Not `updateById`: a body's - // `ctx.api.object(…)` has no such member, so that call throws - // `TypeError: not a function` on its first run. + // the id travels inside the payload. `updateById(ctx.recordId, …)` + // is installed too and would also persist it; one prescription is + // named, and it is the one the hint has always pinned. hint: `To persist it, write through the API: ctx.api.object('').${ACTION_RECORD_WRITE_REMEDY_METHOD}(` + `{ id: ctx.recordId, ${w.field}: … })`, diff --git a/packages/lint/src/validate-hook-body-writes.ts b/packages/lint/src/validate-hook-body-writes.ts index 0130097ee64..6c803374f7e 100644 --- a/packages/lint/src/validate-hook-body-writes.ts +++ b/packages/lint/src/validate-hook-body-writes.ts @@ -317,8 +317,8 @@ const HOOK_APPLICABLE_IDS: ReadonlySet = new Set(HOOK_BODY_WRITE_PATTERN * `create(data)` to `insert(data)`, but this map grades L2 * (`language:'js'`) BODIES, which run in QuickJS, and `installCtx` * (runtime/src/sandbox/quickjs-runner.ts) installs exactly - * `insert / update / delete / updateMany / deleteMany / upsert` as - * the `ctx.api.object()` write leaves. The spec contract agrees and + * `insert / update / updateById / delete / updateMany / deleteMany / + * upsert` as the `ctx.api.object()` write leaves. The spec contract agrees and * is the authority: `IScopedObjectRepository` * (packages/spec/src/contracts/scoped-context.ts) declares `insert` * and names `create` as measured-and-excluded. So a body's diff --git a/packages/lint/src/validate-readonly-hook-writes.ts b/packages/lint/src/validate-readonly-hook-writes.ts index e75c087fc66..35a22d60441 100644 --- a/packages/lint/src/validate-readonly-hook-writes.ts +++ b/packages/lint/src/validate-readonly-hook-writes.ts @@ -56,8 +56,8 @@ // the engine — see {@link READONLY_HOOK_METHOD_EXCLUSIONS}. The host // `ObjectRepository` does alias `create()` to `insert()`, but this rule // reads L2 bodies, which run in QuickJS, and the VM-side `ctx.api.object()` -// installs exactly `insert`/`update`/`delete`/`updateMany`/`deleteMany`/ -// `upsert` (`installCtx`, runtime/src/sandbox/quickjs-runner.ts) — so a +// installs exactly `insert`/`update`/`updateById`/`delete`/`updateMany`/ +// `deleteMany`/`upsert` (`installCtx`, runtime/src/sandbox/quickjs-runner.ts) — so a // body's `.create()` was `TypeError: not a function` at run time: a LOUD // failure on the first run, not the silent no-op this rule exists to // report. Gating it as a silent drop would state something false, the @@ -292,7 +292,7 @@ export const READONLY_HOOK_METHOD_EXCLUSIONS: readonly { method: string; reason: 'lowering, so a handler spelling it is bundled and never becomes a body.source this rule can parse, ' + 'and the shared extractor no longer recognises the verb either. What that refusal encodes: this rule ' + 'reads L2 bodies, which run in QuickJS, and the VM-side ctx.api.object() installs no `create` leaf ' + - '(installCtx in runtime/src/sandbox/quickjs-runner.ts: insert / update / delete / updateMany / ' + + '(installCtx in runtime/src/sandbox/quickjs-runner.ts: insert / update / updateById / delete / updateMany / ' + 'deleteMany / upsert), while the spec contract IScopedObjectRepository declares insert and names ' + 'create as measured-and-excluded - so a body calling .create() was `TypeError: not a function` on ' + 'its first run, a LOUD failure, never the silent no-op this rule reports. The host ObjectRepository ' + diff --git a/packages/runtime/src/sandbox/body-update-by-id.integration.test.ts b/packages/runtime/src/sandbox/body-update-by-id.integration.test.ts new file mode 100644 index 00000000000..5cf62a5416b --- /dev/null +++ b/packages/runtime/src/sandbox/body-update-by-id.integration.test.ts @@ -0,0 +1,175 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A sandboxed body persists through `ctx.api.object(X).updateById(id, patch)`, + * the id-first single-record write the spec contract declares + * (`HookObjectApi.updateById`, `IScopedObjectRepository.updateById`) and + * `content/docs/automation/hook-bodies.mdx` teaches for action bodies. + * + * Measured before the leaf was installed: on this harness the call threw + * `TypeError: not a function` in an action body and in a hook body, and the + * row kept its value; `update({ id, … })` wrote. + * + * The id argument is judged at the crossing, before the host is called. The + * host repository puts it into `where: { id }`, where an object, an array or a + * missing value is a filter shape, not a record address. Measured on the host + * repository directly, every such shape was refused there too (no row moved), + * but with a message about filters or `options.multi`, and some with no code. + * At the crossing each is one coded refusal, `VALIDATION_ERROR` / 400, and the + * engine is never reached. `0` and `''` are of the declared type and are + * refused as the contract says they are: they identify no row. + * + * Measured in composition: a real `ObjectQL` on a real better-sqlite3 + * `SqlDriver`, the real `QuickJSScriptRunner` behind the real action and hook + * body factories. An engine middleware on the target object counts the update + * operations that reach the engine. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectQL, bindHooksToEngine } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { actionBodyRunnerFactory, hookBodyRunnerFactory } from './body-runner.js'; +import { QuickJSScriptRunner } from './quickjs-runner.js'; + +const DEAL = { name: 'ubi_deal', fields: { name: { type: 'text', name: 'name' }, stage: { type: 'text', name: 'stage' } } }; +const TASK = { name: 'ubi_task', fields: { title: { type: 'text', name: 'title' }, deal: { type: 'text', name: 'deal' } } }; +const SYS = { context: { isSystem: true } } as const; + +type Booted = { e: ObjectQL; won: string; other: string; updates: string[] }; + +describe('a sandboxed body writes through ctx.api.object(X).updateById(id, patch)', () => { + let engine: ObjectQL | null = null; + let dir: string | null = null; + + afterEach(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + engine = null; + if (dir) { rmSync(dir, { recursive: true, force: true }); dir = null; } + }); + + async function boot(): Promise { + dir = mkdtempSync(join(tmpdir(), 'os-body-update-by-id-')); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'data.sqlite') }, useNullAsDefault: true }); + await driver.initObjects([DEAL, TASK]); + const e = new ObjectQL(); + engine = e; + e.registerDriver(driver as any, true); + await e.init(); + for (const o of [DEAL, TASK]) e.registry.registerObject(o as any); + const won = (await e.insert('ubi_deal', { name: 'A', stage: 'open' }, SYS as any)) as { id: string }; + const other = (await e.insert('ubi_deal', { name: 'B', stage: 'open' }, SYS as any)) as { id: string }; + const updates: string[] = []; + e.registerMiddleware( + async (op, next) => { + if (op.operation === 'update') updates.push(op.operation); + await next(); + }, + { object: 'ubi_deal' }, + ); + return { e, won: won.id, other: other.id, updates }; + } + + async function stages(e: ObjectQL): Promise> { + const rows = (await e.find('ubi_deal', { context: { isSystem: true } })) as Array<{ name: string; stage: string }>; + return Object.fromEntries(rows.map((r) => [r.name, r.stage])); + } + + /** Run `source` as a script action body on `ubi_deal`, for the record `recordId`. */ + async function runAction(e: ObjectQL, recordId: string, source: string, capabilities = ['api.write']) { + const handler = actionBodyRunnerFactory(new QuickJSScriptRunner(), { ql: e, appId: 'ubi' })({ + name: 'ubi_close', + objectName: 'ubi_deal', + type: 'script', + body: { language: 'js', source, capabilities }, + }); + expect(handler, 'the action body must bind').toBeTypeOf('function'); + return handler!({ recordId, record: {}, executionContext: { userId: 'u_ubi', isSystem: true } }); + } + + /** Bind `source` as an `afterInsert` hook body on `ubi_task`, then insert a task pointing at `deal`. */ + async function runHook(e: ObjectQL, deal: string, source: string) { + const bodyRunner = hookBodyRunnerFactory(new QuickJSScriptRunner(), { ql: e, appId: 'ubi' }); + bindHooksToEngine( + e, + [{ name: 'ubi_win', object: 'ubi_task', events: ['afterInsert'], body: { language: 'js', source, capabilities: ['api.write'] } } as any], + { packageId: 'ubi', bodyRunner }, + ); + return e.insert('ubi_task', { title: 'Close it', deal }, { context: { userId: 'u_ubi', isSystem: true } } as any); + } + + it('an action body: updateById(ctx.recordId, patch) writes that row, and only that row', async () => { + const { e, won } = await boot(); + expect(await stages(e)).toEqual({ A: 'open', B: 'open' }); + const value = await runAction(e, won, ` + const row = await ctx.api.object('ubi_deal').updateById(ctx.recordId, { stage: 'won' }); + return { stage: row && row.stage };`); + expect(await stages(e)).toEqual({ A: 'won', B: 'open' }); + expect(value).toMatchObject({ stage: 'won' }); + }, 30_000); + + it('a hook body: updateById(id, patch) writes that row, and only that row', async () => { + const { e, won } = await boot(); + expect(await stages(e)).toEqual({ A: 'open', B: 'open' }); + await runHook(e, won, `await ctx.api.object('ubi_deal').updateById(ctx.input.deal, { stage: 'won' });`); + expect(await stages(e)).toEqual({ A: 'won', B: 'open' }); + }, 30_000); + + it('CONTROL: update({ id, … }) still writes, on both faces', async () => { + const { e, won, other } = await boot(); + await runAction(e, won, `await ctx.api.object('ubi_deal').update({ id: ctx.recordId, stage: 'won' });`); + expect(await stages(e)).toEqual({ A: 'won', B: 'open' }); + await runHook(e, other, `await ctx.api.object('ubi_deal').update({ id: ctx.input.deal, stage: 'lost' });`); + expect(await stages(e)).toEqual({ A: 'won', B: 'lost' }); + }, 30_000); + + it('sits behind the same api.write gate as every write leaf', async () => { + const { e, won, updates } = await boot(); + const err: any = await runAction( + e, won, `await ctx.api.object('ubi_deal').updateById(ctx.recordId, { stage: 'won' });`, ['api.read'], + ).then(() => null, (x) => x); + expect(err?.code).toBe('INSUFFICIENT_PRIVILEGES'); + expect(err?.status).toBe(403); + expect(updates).toEqual([]); + expect(await stages(e)).toEqual({ A: 'open', B: 'open' }); + }, 30_000); + + // One case per refused id shape. Each is refused at the crossing with the + // ADR-0112 envelope, no update reaches the engine, and no row moves. + it.each([ + ['an operator object', `{ $ne: null }`], + ['an array', `[ctx.recordId]`], + ['null', `null`], + ['undefined', `undefined`], + ['an empty string', `''`], + ['0', `0`], + ])('refuses %s as the id before the host is called', async (_shape, idSource) => { + const { e, won, updates } = await boot(); + const err: any = await runAction( + e, won, `await ctx.api.object('ubi_deal').updateById(${idSource}, { stage: 'won' });`, + ).then(() => null, (x) => x); + expect(err, 'the refused call must fail the action').not.toBeNull(); + expect(err.code).toBe('VALIDATION_ERROR'); + expect(err.status).toBe(400); + expect(updates).toEqual([]); + expect(await stages(e)).toEqual({ A: 'open', B: 'open' }); + }, 30_000); + + it('refuses a non-scalar id in a hook body too, and the body sees the coded refusal', async () => { + const { e, won, updates } = await boot(); + await runHook(e, won, ` + try { + await ctx.api.object('ubi_deal').updateById({ $in: [ctx.input.deal] }, { stage: 'won' }); + } catch (err) { + if (err.code === 'VALIDATION_ERROR' && err.status === 400) { + await ctx.api.object('ubi_deal').updateById(ctx.input.deal, { stage: 'refused' }); + return; + } + throw err; + }`); + expect(updates).toEqual(['update']); + expect(await stages(e)).toEqual({ A: 'refused', B: 'open' }); + }, 30_000); +}); diff --git a/packages/runtime/src/sandbox/quickjs-runner.ts b/packages/runtime/src/sandbox/quickjs-runner.ts index a6bb7af8b6e..b52e071075c 100644 --- a/packages/runtime/src/sandbox/quickjs-runner.ts +++ b/packages/runtime/src/sandbox/quickjs-runner.ts @@ -751,7 +751,10 @@ export class QuickJSScriptRunner implements ScriptRunner { const objectName = vm.getString(nameH); const wrap = vm.newObject(); const READ = ['find', 'findOne', 'count', 'aggregate'] as const; - const WRITE = ['insert', 'update', 'delete', 'updateMany', 'deleteMany', 'upsert'] as const; + // `updateById` is the id-first single-record write `HookObjectApi` and + // `IScopedObjectRepository` declare; its id argument is judged at the + // crossing ({@link ID_ARGUMENT_INDEX}). + const WRITE = ['insert', 'update', 'updateById', 'delete', 'updateMany', 'deleteMany', 'upsert'] as const; for (const m of READ) installApiMethod(vm, wrap, m, objectName, ctx, caps, 'api.read', origin, txState, deferreds, crossing); for (const m of WRITE) installApiMethod(vm, wrap, m, objectName, ctx, caps, 'api.write', origin, txState, deferreds, crossing); return wrap; @@ -1495,6 +1498,7 @@ function installApiMethod( crossing: QueryArgumentCrossing, ): void { const queryAt = QUERY_ARGUMENT_INDEX.get(method); + const idAt = ID_ARGUMENT_INDEX.get(method); const fn = vm.newFunction(method, (...argHandles) => { // Capability gate — throw synchronously so the VM sees a normal exception at // the call site (mirrors ctx.log / ctx.crypto gating). @@ -1510,6 +1514,7 @@ function installApiMethod( if (!apiAny || typeof apiAny.object !== 'function') { throwSandboxFault(vm, `ctx.api unavailable in ${origin.kind} '${origin.name}'`); } + if (idAt !== undefined) refuseNonScalarIdArgument(vm, argHandles[idAt], objectName, method); // Dump args now, while the handles are alive — they are freed when this // function returns, long before the async work below runs. The query // argument keeps every filter key the body wrote ({@link dumpQueryArgument}). @@ -1568,6 +1573,55 @@ const QUERY_ARGUMENT_INDEX: ReadonlyMap = new Map([ ['update', 1], ]); +/** + * The argument of each `ctx.api.object(name)` verb that carries a record id: + * `updateById(id, data)`. The declared type is `string | number` + * (`HookObjectApi.updateById`), and no filter key is read out of it, so + * {@link QUERY_ARGUMENT_INDEX} does not reach it. The host repository puts it + * into `where: { id }`, where an object, an array or a missing value is a + * filter shape rather than an address. {@link refuseNonScalarIdArgument} refuses + * such an id before the host is called. + */ +const ID_ARGUMENT_INDEX: ReadonlyMap = new Map([['updateById', 0]]); + +/** The code and status a refused id argument is answered with: the caller's input is invalid. */ +const ID_ARGUMENT_REFUSAL_CODE = 'VALIDATION_ERROR'; +const ID_ARGUMENT_REFUSAL_STATUS = 400; + +/** + * Refuse an id argument that is not a record id: anything but a non-empty + * string or a finite non-zero number. `0` and `''` are of the declared type, + * and `HookObjectApi.updateById` already declares them a refusal (they identify + * no row). Thrown at the call site, before any host call, as a refusal of the + * body's own input (a coded error, like a capability denial), never as a + * sandbox fault. + */ +function refuseNonScalarIdArgument( + vm: QuickJSContext, + h: QuickJSHandle | undefined, + objectName: string, + method: string, +): void { + const kind = h === undefined ? 'undefined' : vm.typeof(h); + if (kind === 'string' && vm.getString(h!).length > 0) return; + const n = kind === 'number' ? vm.getNumber(h!) : Number.NaN; + if (Number.isFinite(n) && n !== 0) return; + const shown = + kind === 'string' ? 'an empty string' + : kind === 'number' ? (n === 0 ? '0' : 'a number that is not finite') + : kind === 'object' ? (h !== undefined && vm.dump(h) === null ? 'null' : 'an object or array') + : kind; + const refusal = Object.assign( + new Error( + `ctx.api.object('${objectName}').${method}(id, data) needs the id of one record (a non-empty string or a ` + + `non-zero number) and was given ${shown}, so nothing was written. To write every row a filter matches, ` + + `call update(data, { where, multi: true }).`, + ), + { code: ID_ARGUMENT_REFUSAL_CODE, status: ID_ARGUMENT_REFUSAL_STATUS }, + ); + throw hostErrorToVm(vm, refusal); +} + /** * The keys whose value is a filter, wherever they sit in a query or options * bag: `where`, the `filter` spelling the engine folds into it, `having`, and diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index e412970962f..e5fe30e0779 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -179,8 +179,8 @@ function refuseBodyOnStoredMetadataTarget( * states; * - carrying a sandboxed JS (L2) `body` — an expression (L1) body performs no * IO, and a code `handler` is not metadata a parse can read; - * - whose `source` names a write (`insert`, `update`, `delete`, `updateMany`, - * `deleteMany`, `upsert`) on `ctx.api.object('')`, called + * - whose `source` names a write (`insert`, `update`, `updateById`, `delete`, + * `updateMany`, `deleteMany`, `upsert`) on `ctx.api.object('')`, called * on the handle or on a name the body bound it to. One issue per object, at * `body.source`. * diff --git a/packages/spec/src/identity/identity-assignment-body-writes.test.ts b/packages/spec/src/identity/identity-assignment-body-writes.test.ts index 882a17932e1..ef57959a437 100644 --- a/packages/spec/src/identity/identity-assignment-body-writes.test.ts +++ b/packages/spec/src/identity/identity-assignment-body-writes.test.ts @@ -26,7 +26,7 @@ import { const ENTRY_ID = 'hook-action-body-system-identity-assignment-write-refused'; const FOUR = [...IDENTITY_ASSIGNMENT_WRITE_OBJECTS]; -const WRITE_METHODS = ['insert', 'update', 'delete', 'updateMany', 'deleteMany', 'upsert'] as const; +const WRITE_METHODS = ['insert', 'update', 'updateById', 'delete', 'updateMany', 'deleteMany', 'upsert'] as const; const ASSIGNMENT = new Set(['sys_user_position', 'sys_user_permission_set']); const writeSource = (object: string, method: string = 'insert') => @@ -158,6 +158,30 @@ describe('ActionSchema — a script action whose body writes an identity-assignm }); }); +describe('`updateById` is one of the write methods judged', () => { + // The id-first single-record write the sandbox installs behind `api.write`. + // `update\b` does not match inside the name, so the method is listed on its + // own: without it an elevated body could write the row this way and pass save. + const byId = (object: string) => `await ctx.api.object('${object}').updateById(ctx.input.owner, { position: 'admin' });`; + + it('a runAs: \'system\' hook that writes `sys_user_position` through updateById is refused at `body.source`', () => { + const issues = issuesOf(HookSchema, hook(byId('sys_user_position'))); + expect(issues.map(({ code, path }) => ({ code, path }))).toEqual([{ code: 'custom', path: 'body.source' }]); + expect(issues[0]!.message.startsWith("`body.source` writes 'sys_user_position' and this hook runs as system")).toBe(true); + }); + + it('a script action that writes `sys_user_position` through updateById is refused at `body.source`', () => { + const issues = issuesOf(ActionSchema, action(byId('sys_user_position'))); + expect(issues.map(({ code, path }) => ({ code, path }))).toEqual([{ code: 'custom', path: 'body.source' }]); + expect(issues[0]!.message.startsWith("`body.source` writes 'sys_user_position' and an action body runs as system")).toBe(true); + }); + + it('CONTROL: the same updateById on a non-identity object parses, on both faces', () => { + expectAccepted(HookSchema, hook(byId('crm_account'))); + expectAccepted(ActionSchema, action(byId('crm_account'))); + }); +}); + describe('every door that parses a stack refuses it', () => { const stackWith = (extra: Record) => ({ manifest: { id: 'com.example.grants', name: 'grants', version: '1.0.0', type: 'app', namespace: 'grt' }, diff --git a/packages/spec/src/identity/identity-assignment-body-writes.ts b/packages/spec/src/identity/identity-assignment-body-writes.ts index b126506e753..408d74efe3c 100644 --- a/packages/spec/src/identity/identity-assignment-body-writes.ts +++ b/packages/spec/src/identity/identity-assignment-body-writes.ts @@ -45,7 +45,7 @@ const ASSIGNMENT_OBJECTS: ReadonlySet = new Set(['sys_user_position', 's * Reads (`find`, `findOne`, `count`, `aggregate`) are not judged: the run-time * refusal leaves reads of the four objects to every context. */ -const BODY_WRITE_METHODS = ['insert', 'update', 'delete', 'updateMany', 'deleteMany', 'upsert'] as const; +const BODY_WRITE_METHODS = ['insert', 'update', 'updateById', 'delete', 'updateMany', 'deleteMany', 'upsert'] as const; const OBJECT_NAMES = [...IDENTITY_ASSIGNMENT_WRITE_OBJECTS].join('|'); const WRITE_METHODS = BODY_WRITE_METHODS.join('|'); diff --git a/packages/spec/src/migrations/entries/semantic/19.hook-action-body-system-identity-assignment-update-by-id-refused.ts b/packages/spec/src/migrations/entries/semantic/19.hook-action-body-system-identity-assignment-update-by-id-refused.ts new file mode 100644 index 00000000000..c9a477cfcaf --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.hook-action-body-system-identity-assignment-update-by-id-refused.ts @@ -0,0 +1,50 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #38630 — the v19 step of the identity-assignment save refusal that +// `18.hook-action-body-system-identity-assignment-write-refused` records for +// v18. Through v18 a sandboxed body had no `ctx.api.object(X).updateById` +// leaf, so calling it threw `TypeError: not a function` and wrote nothing, and +// the v18 entry rightly does not name it. This release installs the leaf, so +// an elevated body's `updateById` write to one of the four objects would now +// reach the run-time security middleware; `HookSchema` and `ActionSchema` +// refuse it at save, as they refuse the other write calls. It narrows the +// accept set of both schemas; no key is added, removed or re-shaped, so no +// tombstone, and no D2 conversion: the move is an authoring choice no rewrite +// can make for the author. No relevance question: the surface includes the +// metadata save door, a runtime write no question over one stack can name. +export const entry: SemanticMigration = { + id: 'hook-action-body-system-identity-assignment-update-by-id-refused', + surface: + 'a hook declaring runAs system, or an action of type script, whose sandboxed js body source calls ' + + 'updateById on ctx.api.object of sys_user_position, sys_user_permission_set, sys_invitation or ' + + 'sys_member', + replacement: + 'Make the write the way the v18 entry `hook-action-body-system-identity-assignment-write-refused` ' + + 'prescribes for every other write call. For position holdings and permission-set grants, set the ' + + 'hook\'s `runAs` to `\'user\'`, or, for an action, make the grant from a flow whose `runAs` is ' + + '`\'user\'` (an action of `type: \'flow\'` runs it as the invoking user). For invitations and ' + + 'memberships, call the organization endpoints (`POST /api/v1/auth/organization/invite-member`, ' + + '`cancel-invitation`, `update-member-role`, `remove-member`).', + reason: + 'Through protocol 18 the QuickJS sandbox installed no `updateById` leaf on `ctx.api.object(...)`, so a ' + + 'body that called it threw `TypeError: not a function` at every run and wrote nothing; the protocol 18 ' + + 'save refusal of an elevated identity-assignment write judged `insert`, `update`, `delete`, ' + + '`updateMany`, `deleteMany` and `upsert` only. This release installs `updateById` behind `api.write`, ' + + 'so the save refusal judges it too: `HookSchema` refuses a hook that declares `runAs: \'system\'`, and ' + + '`ActionSchema` a `type: \'script\'` action, whose sandboxed JS (`language: \'js\'`) `body.source` calls ' + + '`updateById` on `ctx.api.object(...)` named with one of the four objects as a literal, on the handle ' + + 'or on a name the body bound it to, with one issue per object at `body.source`, at `objectstack ' + + 'validate`, at `defineStack` and at the metadata save door (a 422). At run time the data middleware ' + + 'refuses the write with `PERMISSION_DENIED` (403), as it refuses every elevated write to the four. Such ' + + 'a body never worked: before this release it threw, and from it on it is refused. Unchanged: ' + + '`updateById` on every other object, a hook under `runAs: \'user\'` or `\'inherit\'`, an expression (L1) ' + + 'body and a code `handler`. ⛔ NOT convertible, for the reasons the v18 entry gives.', + acceptanceCriteria: + '`objectstack validate` reports no issue at `body.source` of a hook or an action: no hook that declares ' + + '`runAs: \'system\'` and no `type: \'script\'` action has a sandboxed JS body that calls `updateById` on ' + + '`sys_user_position`, `sys_user_permission_set`, `sys_invitation` or `sys_member`. Saving each formerly ' + + 'affected hook or action through the metadata API succeeds instead of answering a 422 that names ' + + '`body.source`.', +};