Skip to content

fix(runtime): a hook refused for a missing capability answers a coded 403 naming the hook and the capability, not a bare 500 - #26963

Merged
objectstack-fleet[bot] merged 5 commits into
mainfrom
claude/project-thread-ktf17y
Oct 28, 2026
Merged

objectstack-fleet[bot] merged 5 commits into
mainfrom
claude/project-thread-ktf17y

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

Requested by Leehom · project thread

Fixes #26903

Clause-②: no
Metadata-protocol: none

维护者速读

  • 改了什么:hook 的沙箱 body 调用了没授予的能力(如没声明 api.read 却调 ctx.api.find)时,保存记录不再回 500 INTERNAL_ERROR,而是回 403 INSUFFICIENT_PRIVILEGES(标准目录已有的码,未新增任何码),消息点名是哪个 hook、缺哪个能力、怎么补。
  • 为什么改:用户和作者原来只看到「Internal server error」,不知道是哪个 hook、缺什么;这是 Studio 里写 hook 最常见的坑(Studio hooks: a hook cannot be granted capabilities in the Studio editor, and a hook refused for a missing capability answers the client 500 INTERNAL_ERROR instead of a located 4xx #26726 的服务端一半)。
  • 风险与回滚:能力检查本身一点没放松,有能力的 hook 行为不变;只改 hook 来源的拒绝怎么作答,action/job body 缺能力仍是 500。回滚即 revert 本 PR。
  • 先看:packages/runtime/src/sandbox/quickjs-runner.ts 的 throwCapabilityDenial;hook-capability-denial-is-a-refusal.integration.test.ts;hook-capability-refusal.dogfood.test.ts。
  • 两分钟验证:pnpm --filter @objectstack/runtime exec vitest run src/sandbox/hook-capability-denial-is-a-refusal.integration.test.ts,预期 15 项全过(5 个能力 × abort / log / 有能力对照)。
  • 需要你做的:无,席位落地。

What changes

  • @objectstack/runtime, quickjs-runner.ts: every capability gate (ctx.api.object(x).METHOD for api.read / api.write, ctx.api.transaction, ctx.log.*, ctx.crypto.randomUUID, ctx.title(field)) now throws through one helper, throwCapabilityDenial. In a hook body the denial crosses the VM as a coded refusal: a plain error carrying code: 'INSUFFICIENT_PRIVILEGES' and status: 403, exactly the shape a body's own throw Object.assign(new Error(…), { code, status }) has. The pump loop then builds the same SandboxError (with innerMessage, code, status) it builds for that throw, and mapDataError's sandbox unwrap arm answers it. The sentence keeps the gate's existing text and adds the remedy: capability 'api.read' not granted to hook 'H' (called ctx.api.object('OBJ').find). Grant it by adding 'api.read' to the hook's body.capabilities.
  • In an action or job body the helper calls throwSandboxFault as before, so those keep the actions: sandbox capability denial answers 400 as a deliberate rejection, not the 500 the crash contract promises #4431 fault contract (500). The seat ruling covered hook bodies only.
  • scripts/error-status-unpinned-baseline.json: INSUFFICIENT_PRIVILEGES leaves the unpinned list, because a producer now declares its status (check:error-status-conformance --update, a ratchet-down).
  • Docblocks on SandboxError.innerMessage, the pump loop's fault branch and capability-denial-is-a-fault.test.ts say a hook denial is the exception.
  • Changeset: @objectstack/runtime patch.

Why

A hook whose body calls ctx.api without the capability is a common authoring mistake (QA run G11). The gate refused it correctly, but the runner marked the denial as its own fault, so a save answered 500 INTERNAL_ERROR with Internal server error. Neither the caller nor the author learned which hook or which capability. Per the seat ruling, a capability refusal in a hook body is a refusal, and it is answered with a code the spec already declares.

Tests

  • packages/runtime/src/sandbox/hook-capability-denial-is-a-refusal.integration.test.ts (new, 15): real ObjectQL, real SqlDriver (better-sqlite3), real QuickJSScriptRunner and hook wrapper, read off mapDataError. For each of the five tokens:
    • onError: abort: 403, code: INSUFFICIENT_PRIVILEGES, the sentence names the hook, the capability and the remedy, carries neither threw: nor SandboxError, no row is written, and the BodyRunner logs one info refusal line with no error line.
    • onError: log: the save proceeds and the [hook] handler failed (onError=log; suppressing) line names the hook, object, event and the capability.
    • Control: the same body with the capability runs, and nothing is logged as refused or failed.
  • packages/qa/dogfood/test/hook-capability-refusal.dogfood.test.ts (new, 4): the real stack through POST /data/OBJECT (abort → 403 INSUFFICIENT_PRIVILEGES naming hook and api.read, nothing written; log → saved; control → saved and the body's read ran).

Acceptance notes

  • The onError: log half of the card did not reproduce on current main. At e1ab32ed the denial is already logged under log, twice at ERROR (live os dev log below; the composition log cases pass on main too). What the QA run likely read as "nothing is logged" is the body's own ctx.log.info(…) line, which the gate correctly refuses without log. This PR keeps the hook-error line (now with the remedy) and pins it. Under log the BodyRunner line moves from ERROR with a stack to the info refusal line, like every other hook refusal.
  • Code choice. INSUFFICIENT_PRIVILEGES ("Operation requires higher privileges") is a StandardErrorCode member. It is not PERMISSION_DENIED, which reads as the caller lacking a permission and whose [Security] Access denied prefix matcher would flatten it. No ledger row and no spec change. feat(spec): a hook declares its refusal catalogue, and its body refuses by code, answered in the caller's language #26831 is still open and unmerged, so no code from it was used.
  • Console. The console's isPermissionError treats every 403 as its fixed "no permission" line, so the Studio/record toast does not show this sentence until a UI card reads code. That belongs with Studio hooks: a hook cannot be granted capabilities in the Studio editor, and a hook refused for a missing capability answers the client 500 INTERNAL_ERROR instead of a located 4xx #26726 (the UI half). No UI change here.
  • Action and job bodies still answer 500 for a capability denial (capability-denial-is-a-fault.test.ts, unchanged). Aligning them is a separate decision, raised in the report.
  • Overlap with feat(spec): a hook declares its refusal catalogue, and its body refuses by code, answered in the caller's language #26831 (open, touches quickjs-runner.ts and body-runner.ts): git merge-tree with its head e5597836 auto-merges quickjs-runner.ts. Semantically its host-relay marker is set in hostErrorToVm, which this denial goes through, so a hook with a refusals catalogue passes the 403 through unchanged.
  • packages/types keeps its comment that cites a hook capability text as an example of a sandbox own fault (data-error-classification.ts). It is still true for action and job bodies and is not touched here (outside the claim's file surface).

Verification

At head 60488efa, branched from origin/main e1ab32ed. Every build and test ran under os-verify-lock.

  • Dispatch gates: node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack derived 71 families on this diff. All 71 were run with each exit code captured before any pipe, and all 71 exited 0. --ran reconciliation: 71 derived, 71 run, 0 NOT-MEASURED, 0 UNRUN, exit 0.

    • Round 1 (at 2f1dacec) had two reds, both fixed: check:driver-memory-census (the composition test first used InMemoryDriver; it now uses SqlDriver on better-sqlite3, no ledger row added) and check:error-status-conformance (INSUFFICIENT_PRIVILEGES is now status-pinned by a producer; the baseline was ratcheted down with --update).
  • Full pnpm build before the gates: exit 0 (116 of 116 tasks).

  • Live red/green through POST /api/v1/data (pnpm dev -- --fresh, showcase, a writable package app.probe1, object probe1_note, hook probe1_guard on beforeInsert, body reads ctx.api.object('probe1_note').find({})):

main (runtime rebuilt from the base blob)
abort, no capability:
{"error":"Internal server error","code":"INTERNAL_ERROR"} 500
records: ['before hooks']
log, no capability:
ERROR [BodyRunner] sandboxed hook threw {"appId":"runtime-authored","hook":"probe1_guard","error":{"message":"capability 'log' not granted to hook 'probe1_guard'", "stack": "SandboxError: …"}}
ERROR [hook] handler failed (onError=log; suppressing) {"hook":"probe1_guard","object":"probe1_note","event":"beforeInsert","error":"capability 'log' not granted to hook 'probe1_guard'"}
this branch
abort, no capability:
{"error":"capability 'api.read' not granted to hook 'probe1_guard' (called ctx.api.object('probe1_note').find). Grant it by adding 'api.read' to the hook's body.capabilities.","code":"INSUFFICIENT_PRIVILEGES","object":"probe1_note"} 403
records: ['before hooks']
control, with api.read: 201, records: ['before hooks', 'control probe (1)']
log, no capability: 201
ERROR [hook] handler failed (onError=log; suppressing) {"hook":"probe1_guard","object":"probe1_note","event":"beforeInsert","error":"hook 'probe1_guard' threw: SandboxError: capability 'log' not granted to hook 'probe1_guard'. Grant it by adding 'log' to the hook's body.capabilities."}
records: ['before hooks', 'control probe (1)', 'log probe']
  • Red first, each pin. With quickjs-runner.ts set to its e1ab32ed blob (committed fix first, restored with git checkout HEAD -- and checked by blob hash and a clean git status):
    • composition file: 5 failed, 10 passed of 15. The five failures are exactly the five onError: abort cases (expected 500 to be 403). The log and control cases pass on main, which is the measured reading above.
    • dogfood file (runtime rebuilt, ablation-dist-preflight --absent confirmed the marker gone from dist/): 1 failed, 3 passed of 4, {"error":"Internal server error","code":"INTERNAL_ERROR"}: expected 500 to be 403. Restored, rebuilt, preflight confirmed the marker back in dist/, 4 of 4 pass.
  • pnpm --filter @objectstack/runtime exec vitest run src/sandbox src/domains: 188 files, 4590 tests passed.
  • pnpm --filter @objectstack/runtime typecheck: exit 0 (tsc + check:test-typecheck).
  • eslint --no-inline-config on packages/runtime and the new dogfood file: exit 0.
  • Dogfood: not owed as a full run (no !, no narrowing arm); the one new dogfood file was run as above.

Human Minimum

  • 1. Schemas start as Zod; packages/spec holds no runtime logic.
  • 2. Every name I added uses the casing for its kind.
  • 3. No formatter ran; pnpm lint passes.
  • 4. One issue, one branch off an up-to-date main, one pull request.
  • 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset.
  • 6. packages/spec touched: not touched.
  • 7. No hand edits to content/docs/references/, packages/*/CHANGELOG.md or content/docs/releases/.
  • 8. Title, body and comments are in English.
  • The Before Submitting list in CONTRIBUTING.md is done.

Generated by Claude Code

…usal, not a 500 fault

Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEkQ5o5GCE3vGxq6G24dZu
…ract, add changeset

Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEkQ5o5GCE3vGxq6G24dZu
… the unpinned-status baseline

Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEkQ5o5GCE3vGxq6G24dZu
@github-actions github-actions Bot added size/m documentation Improvements or additions to documentation tests tooling labels Oct 27, 2026
@github-actions

github-actions Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 1 package(s): @objectstack/runtime, touching 10 documentable anchor(s).

4 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:

  • content/docs/api/error-catalog.mdx (via INSUFFICIENT_PRIVILEGES (literal, a string literal in HOOK_CAPABILITY_REFUSAL_CODE))
  • content/docs/automation/hook-bodies.mdx (via api.read (literal, a string literal in installCtx), crypto.uuid (literal, a string literal in installCtx))
  • content/docs/automation/hooks.mdx (via api.read (literal, a string literal in installCtx))
  • content/docs/automation/jobs.mdx (via api.read (literal, a string literal in installCtx), api.transaction (literal, a string literal in installCtx))
What this run could not see
  • 1 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 55 of 207 client-bound route-ledger rows — the other 152 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 152: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 55 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 97 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 27 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json fd246c22c90fc6604824b8e0d3d93d480e4d1f40 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from d774add4c32c65128504ecffef9eebebf4ab0cd6 — the merge of head a7f0a7f4a663b0abf0c327e82e46c3fd6226ec25 into base fd246c22c90fc6604824b8e0d3d93d480e4d1f40, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin d774add4c32c65128504ecffef9eebebf4ab0cd6 && git checkout d774add4c32c65128504ecffef9eebebf4ab0cd6
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin fd246c22c90fc6604824b8e0d3d93d480e4d1f40 a7f0a7f4a663b0abf0c327e82e46c3fd6226ec25 && git checkout -B drift-repro fd246c22c90fc6604824b8e0d3d93d480e4d1f40 && git merge --no-ff a7f0a7f4a663b0abf0c327e82e46c3fd6226ec25

node scripts/docs-audit/affected-docs.mjs --json fd246c22c90fc6604824b8e0d3d93d480e4d1f40

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs fd246c22c90fc6604824b8e0d3d93d480e4d1f40 → pass the list as
args.docs, on the commit named under Which tree this was computed on.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

席位核对

ACCEPT · domain:server seat 2 · os-project-manager · session_0186vfjHHMsRXC9EUT9hTFMo · 2026-10-28T01:04Z · head a7f0a7f4a6 · #26903

The maintainer's standing authorisation for landing reviewed PRs, verbatim: 「按照 pm-dispatch 规则复核过的都授权」.

  1. Shape:
    • A draft against main, assignee os-project-manager. The body carries Fixes #26903, with Clause-②: no and Metadata-protocol: none line-initial. The changeset on @objectstack/runtime repeats both lines.
    • check-governed-merges --pr 26963 reads NOT governed, 367 changed lines.
    • The claim (6454699953) names this PR's branch.
  2. Against the seat ruling (use an existing declared code, one mapping, ⛔ no new code, ⛔ no loosening):
    • In a hook body, every capability gate goes through one helper, throwCapabilityDenial in quickjs-runner.ts. The gates are api.read, api.write, api.transaction, crypto.uuid, log and ctx.title(field).
    • The helper crosses the VM as a coded refusal: INSUFFICIENT_PRIVILEGES, an existing StandardErrorCode member, at its 403. The message names the hook and the capability and gives the remedy.
    • Every data door answers it through mapDataError's existing sandbox unwrap arm. There is no new mapping site, and nothing under packages/spec/**. feat(spec): a hook declares its refusal catalogue, and its body refuses by code, answered in the caller's language #26831's codes are not used, because it is still open.
    • The check itself is as strict as before; only the answer changed. INSUFFICIENT_PRIVILEGES leaves scripts/error-status-unpinned-baseline.json, because its status is now pinned. That is a shrink of the baseline.
  3. The onError: 'log' half: it did not reproduce. The dev measured live on e1ab32ed that the denial is already logged, so the PR pins that line, now carrying the remedy, and pins that the save proceeds. The card's ask is met on both halves.
  4. Red first and ablation (the dev's):
    • The new real-stack integration file (ObjectQL + SqlDriver better-sqlite3 + QuickJS + the hook wrapper, read through mapDataError) passes 15 of 15.
    • With quickjs-runner.ts at its base blob, exactly the 5 onError: 'abort' cases fail, each expecting 403 and getting 500.
    • The new dogfood file (real stack, POST /data) passes 4 of 4. With the runtime rebuilt from the base blob it fails 1 (500 INTERNAL_ERROR), and the dist preflight checks both directions.
    • Live, the os dev showcase answered 500 on main and 403 on the branch, naming hook probe1_guard and api.read. The records were unchanged, and the control with api.read granted answered 201.
  5. Tests and gates:
    • runtime src/sandbox and src/domains: 188 files, 4,590 tests passed. Type-check and eslint exit 0.
    • Locally 71 of 71 derived gates exit 0, with 0 NOT-MEASURED.
    • At this stamp every check-run on the head reads success or skipped: 38 success, 9 skipped, none failed or in progress. GitHub reads the PR clean.
  6. The CI rework (a7f0a7f4, one commit on 60488efa): core's test:repo failed on 60488efa because import-runner-sandbox-fault-row.test.ts, which parses quickjs-runner.ts for throwSandboxFault sites, did not see the new helper. The rework changes only that test. It now enumerates the throwCapabilityDenial sites from the producer, with no hand-written list, renders each under an action origin, and pins the helper's first statement, if (origin.kind !== 'hook') throwSandboxFault(vm, message). The dev's readings: core test:repo 83 tests passing, the ablation legs red, and 73 of 73 derived gates exit 0. The PR body's Verification still names 60488efa; this ACCEPT records the rework.
  7. The open question (open_questions[0]): should action and job bodies' capability denials follow? Seat ruling: A, as its own card, ⛔ not in this PR. It is filed as runtime: an action or job body's capability denial still answers a bare 500, while a hook's now answers a coded 403 naming the capability (#26903 follow-up) #26965 for triage. Until then, an action or job denial keeps the actions: sandbox capability denial answers 400 as a deliberate rejection, not the 500 the crash contract promises #4431 fault contract (500), which capability-denial-is-a-fault.test.ts pins.
  8. Overlap: git merge-tree reports no conflict against main 3271a0834c. feat(spec): a hook declares its refusal catalogue, and its body refuses by code, answered in the caller's language #26831 is open on quickjs-runner.ts; merged with its head e5597836, that file auto-merges. Its other conflicts are with main, not with this PR. The UI half is Studio hooks: a hook cannot be granted capabilities in the Studio editor, and a hook refused for a missing capability answers the client 500 INTERNAL_ERROR instead of a located 4xx #26726. The console's fixed 403 line is that card's concern.

Generated by Claude Code

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review October 28, 2026 01:05
@objectstack-fleet
objectstack-fleet Bot enabled auto-merge October 28, 2026 01:05
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Oct 28, 2026
Merged via the queue into main with commit e46e25c Oct 28, 2026
48 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/project-thread-ktf17y branch October 28, 2026 01:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/m tests tooling

Projects

None yet

Development

Successfully merging this pull request may close these issues.

server: a hook refused for a missing capability answers the client 500 INTERNAL_ERROR instead of a coded refusal naming the hook and the capability

2 participants