Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .changeset/38630-sandbox-update-by-id.md
Original file line number Diff line number Diff line change
@@ -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

<!-- adr-0087: registered hook-action-body-system-identity-assignment-update-by-id-refused, publish-refuses-seeds-and-actions-that-save-and-do-not-work -->

**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.
4 changes: 2 additions & 2 deletions content/docs/automation/hook-bodies.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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(<argument>)` — the related-record form only; bare `ctx.title()` names this record and needs no token | `api.read` |
Expand Down
2 changes: 1 addition & 1 deletion content/docs/deployment/validating-metadata.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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) | ✓ | ✓ | ✓ | ✓ᶠ |
Expand Down
13 changes: 8 additions & 5 deletions packages/cli/src/utils/extract-hook-body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -387,7 +387,8 @@ const FORBIDDEN_PATTERNS: Array<{ rx: RegExp; reason: string; face?: LoweringFac
rx: /(?<!\bObject\s*)\.\s*create\s*\(/,
reason:
'`create()` is not reachable from a sandboxed body — the VM\'s `ctx.api.object()` installs '
+ '`insert` / `update` / `delete` / `updateMany` / `deleteMany` / `upsert` and no `create` leaf, so '
+ '`insert` / `update` / `updateById` / `delete` / `updateMany` / `deleteMany` / `upsert` and no '
+ '`create` leaf, so '
+ 'the call is a TypeError at run time (and under a hook\'s default `onError: \'abort\'` that aborts '
+ 'the triggering write). Spell the same payload `.insert({ ... })`, which is the member the sandbox '
+ 'actually has and the only insert verb the spec contract declares; `Object.create()` is unaffected. '
Expand Down Expand Up @@ -515,8 +516,10 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | '
// patterns at the end of this list.
{ rx: /\.object\s*\([^)]+\)\s*\.\s*(?:find|findOne|count|aggregate|get|list)\b/, cap: 'api.read' },
// [#35143] `updateMany` / `deleteMany` spelled out: `update\b` does not match
// inside either name, and both are sandbox `api.write` leaves.
{ rx: /\.object\s*\([^)]+\)\s*\.\s*(?:insert|updateMany|update|upsert|deleteMany|delete|patch|remove|create)\b/, cap: 'api.write' },
// inside either name, and both are sandbox `api.write` leaves. `updateById`
// likewise, for the same reason: the id-first single-record write the spec
// contract declares, installed behind `api.write`.
{ rx: /\.object\s*\([^)]+\)\s*\.\s*(?:insert|updateById|updateMany|update|upsert|deleteMany|delete|patch|remove|create)\b/, cap: 'api.write' },
{ rx: /ctx\.crypto\.randomUUID\b/, cap: 'crypto.uuid' },
// NO `ctx.crypto.hash` pattern: the `crypto.hash` token was removed in spec 17
// (#4391) because the sandbox never installed the function. Inferring a
Expand Down Expand Up @@ -556,7 +559,7 @@ const CAPABILITY_PATTERNS: Array<{ rx: RegExp; cap: 'api.read' | 'api.write' | '
];

/** The write leaves the `api.write` pattern above names, as one alternation. */
const OBJECT_WRITE_LEAVES = 'insert|updateMany|update|upsert|deleteMany|delete|patch|remove|create';
const OBJECT_WRITE_LEAVES = 'insert|updateById|updateMany|update|upsert|deleteMany|delete|patch|remove|create';

/** The index of the `)` closing the `(` at `open`, or -1. Counts nesting; strings are not special. */
function closingParen(source: string, open: number): number {
Expand Down
22 changes: 20 additions & 2 deletions packages/cli/test/extract-hook-body.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,24 @@ describe('extractHookBody', () => {
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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion packages/lint/src/authoring-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
8 changes: 4 additions & 4 deletions packages/lint/src/rule-explanations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ' +
Expand Down
11 changes: 11 additions & 0 deletions packages/lint/src/validate-action-body-capabilities.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' });")] }),
Expand Down
Loading
Loading