Skip to content

Fix trusted-execution body buffering, timer leaks and HEAD length; reconcile docs - #143

Merged
jimhoyd merged 2 commits into
mainfrom
claude/fix-trusted-execution-bugs
Sep 19, 2026
Merged

jimhoyd merged 2 commits into
mainfrom
claude/fix-trusted-execution-bugs

Conversation

@jimhoyd

@jimhoyd jimhoyd commented Sep 19, 2026

Copy link
Copy Markdown
Collaborator

Summary

An independent review of the trusted-by-default execution change (docs/SPIKE-DEFAULT-TRUST-MODEL.md, src/trusted-functions.ts) found three real, verified runtime bugs plus a set of documentation precision gaps, filed as #137, #138, #139 and #140. This PR fixes all four.

#137 — maxBytes checked only after buffering the whole response

TrustedFunctions read a route's Response body via a single .arrayBuffer() call, which reads everything unconditionally before the byte count is ever checked against maxBytes — a configured 1 KiB limit didn't stop a much larger body from being fully read into memory first. On a deadline timeout, the stream kept being consumed in the background instead of being cancelled. Fixed by reading the body incrementally through getReader(), counting bytes per chunk, and calling reader.cancel() the instant the running total exceeds maxBytes or the call's deadline fires (via a new AbortController wired through execute()/invoke()). Applies to the HEAD path too.

#138 — every call leaked its deadline timer

execute() created a setTimeout() for the Promise.race deadline and never cleared it when the function's own promise won the race — unref() stops it keeping the process alive, but it still fires later. Fixed by capturing the timer handle and clearTimeout()ing it in a finally covering both race outcomes.

#139 — trusted HEAD responses reported Content-Length: 0

HEAD requests skipped reading the body entirely and always reported an empty buffer, so http-response.ts's prepareResponse (which already correctly derives Content-Length from the real body and only drops the body for HEAD at write time) had nothing real to measure. Fixed by reading the body for HEAD the same way GET does, matching the convention src/assets.ts/the native-reply path already use (always determine the real body+length; let prepareResponse decide whether to transmit it).

This surfaced a stale assumption in src/policies/cache.ts's revalidation logic, which explicitly special-cased "a function's HEAD answer has no body to hash" — true only because of the #139 bug. With the fix, a function route's HEAD answer now hashes to the same ETag as its GET answer, consistent with how a respond route's HEAD already worked. Updated the stale test assertion and comment; the actual guard logic (skip when a HEAD answer genuinely has no body) is unchanged.

#140 — doc precision, no behavior change

  • SECURITY.md/docs/FUNCTION-SECURITY.md: made explicit that the "binding grants are unaffected" claim is about context/context.secrets injection, not an access-control boundary — trusted code has independent full Node access regardless of what its route was granted.
  • docs/FUNCTION-SECURITY.md: made the entry-file-only grant-invalidation scope for trusted routes (vs. full dependency graph for sandboxed) explicit and consistent everywhere it's discussed, removing an internal contradiction.
  • docs/AI-AUTHORING.md: reframed "Deciding when a route needs sandbox: true" to lead with "all public HTTP input is untrusted regardless of trust mode" as a separate axis from code trust, instead of "webhook → sandbox."
  • docs/RELEASE-READINESS.md: removed stale references to store/persistence/management-queue functionality removed from core in Remove link/dynamicLinks from core (Phase 1 of dynamic-link extraction) #126, fixed the version reference (package.json is 0.4.0-alpha.2), and corrected the npm-publish claim after actually checking the registry — npm view @jimhoyd/urlcode shows 0.3.0 published as latest and 0.4.0-alpha.1 under the alpha dist-tag, so "no published npm release" was flatly wrong.
  • docs/OPERATIONAL-PROOF.md: corrected "six Node/OS combinations" to the actual .github/workflows/ci.yml matrix — nine combinations on push to main, but a pull request runs only Linux across the three Node versions.

None of this walks back the trusted-by-default decision; it's precision and internal consistency only.

Regression tests

Added to test/trusted-functions.test.ts, each reproducing the issue's exact repro shape and confirmed failing on unmodified code, then passing after the fix (verified by reverting src/trusted-functions.ts to the pre-fix version, running the new tests, confirming the failure mode matched the bug report, then restoring the fix):

  • maxBytes streaming/cancellation: unfixed code pulled 21 of 20 finite chunks before rejecting; fixed code cancels after ~2.
  • Deadline cancels an in-flight body read: unfixed code let the reader run to completion (11 pulls); fixed code stops well short of that.
  • node:async_hooks Timeout-leak test, following the issue's exact shape (100 sequential execute calls + one setImmediate): unfixed code left 100 live Timeout resources; fixed code leaves 0.
  • Wire-level HEAD Content-Length, for both a plain response and a middleware-transformed one: unfixed code reported 0; fixed code reports the real length (5).

test/policy-cache.test.ts updated for the ETag consequence of the #139 fix described above.

Test plan

  • npm run typecheck — clean
  • npm run lint — clean
  • npm run check — clean (regenerated llms-full.txt via npm run docs:llms)
  • npm test — 492 tests, 490 pass, 0 fail, 2 pre-existing/expected skips
  • npm run build — succeeds
  • npm run test:package — passes

Out of scope / follow-ups

  • #135 (sandboxReason/audit-heuristic) and #124 (TypeScript build sandbox-rules gap) are untouched, as directed.
  • The sandboxed path (guest-api.ts/function-worker.ts) appears to have the same HEAD/Content-Length-0 pattern (it also unconditionally sends an empty body for HEAD with no separate length field) but was left untouched per this issue's scope and the file's own header comment ("the sandboxed path ... is untouched by this file"); filed separately as a new issue for review.

🤖 Generated with Claude Code

https://claude.ai/code/session_018neC2tYKPxMPbzZf1wNctr


Generated by Claude Code

TrustedFunctions read a route's Response body via a single .arrayBuffer()/
skip-for-HEAD call, which:

- Buffered the whole stream into memory before checking it against
  maxBytes, so a configured limit only ever rejected after an oversized
  body had already been fully read (#137). A deadline timeout left the
  stream being consumed in the background instead of cancelling it.
- Left every call's setTimeout() running uncleared once the call's own
  promise won the race, unref()'d but never cleared, so completed calls
  accumulated live Timeout resources for the life of the configured
  timeout (#138).
- Never read the body at all for HEAD requests, always reporting an
  empty body and therefore a false Content-Length: 0 even when the
  equivalent GET response had a real body (#139).

execute() now threads an AbortController through the call: its signal
aborts when the deadline timer fires, and the timer itself is cleared in
a finally covering both race outcomes. invoke() reads the body through a
new readBody() that pulls the stream incrementally via getReader(),
counting bytes per chunk and cancelling the reader as soon as maxBytes is
exceeded or the deadline's abort signal fires, on every path including
HEAD. HEAD now measures the real body the same way GET does (matching
the existing native/asset-path convention of always determining the full
body+length and letting http-response.ts's prepareResponse decide not to
put it on the wire for HEAD), rather than skipping the read and reporting
zero.

This surfaced a stale assumption in the cache-revalidation policy: it
special-cased "a function's HEAD answer has no body to hash" to avoid
asserting an ETag it couldn't actually verify — an assumption that only
held because of the #139 bug. Now that HEAD carries the real measured
body, it hashes to the same ETag as GET, consistent with how a respond
route's HEAD already behaved; only the comment there needed correcting,
the guard itself (skip when a HEAD answer genuinely has no body) is
unchanged.

Added regression tests reproducing each issue's exact repro shape and
verified failing on unmodified code before the fix: incremental
maxBytes cancellation (stream cut off after ~2 of 20 chunks, not all
20), deadline-triggered cancellation of an in-flight read, a
node:async_hooks Timeout-leak check over 100 sequential calls (100 live
timers before the fix, 0 after), and wire-level HEAD Content-Length
coverage for both a plain and a middleware-transformed response.

Fixes #137
Fixes #138
Fixes #139

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018neC2tYKPxMPbzZf1wNctr
No behavior change; precision/consistency fixes surfaced by an
independent review of the trusted-by-default execution change:

- SECURITY.md and docs/FUNCTION-SECURITY.md described env/secrets as
  route-granted in a way readable as an access-control guarantee on
  trusted Node code. Made explicit that this is a claim about what
  URLCode injects into context/context.secrets, not a restriction on
  what trusted (non-sandbox) code can independently do — that code has
  full Node access by design, so it can reach process.env, the
  filesystem or the network regardless of what its route was granted.
  The trust-model decision itself is unchanged; this only states its
  actual boundary precisely instead of implying a narrower one.
- docs/FUNCTION-SECURITY.md said "every config/module change
  invalidates a grant" in one place while separately noting a trusted
  route's transitive dependencies are not hashed for grant-invalidation
  purposes — contradictory on a careful read. Made the entry-file-only
  scope for a trusted route (vs. full-dependency-graph for a sandboxed
  one) explicit and consistent everywhere grant invalidation is
  discussed.
- docs/AI-AUTHORING.md's "Deciding when a route needs sandbox: true"
  led with "untrusted webhook data" as the motivating example, readable
  as implying webhooks specifically need sandboxing. Reframed: all
  public HTTP input is untrusted regardless of trust mode (a separate
  axis from whether the code processing it is trusted or sandboxed);
  sandboxing limits what the executing code can reach, it is not a
  substitute for validating/authenticating input. A route can receive
  webhooks and stay trusted if its own code is reviewed and handles
  input carefully.
- docs/RELEASE-READINESS.md still listed store/persistence/management-
  queue functionality that PR #126 removed from core (link/dynamicLinks
  extraction), fixed the version reference (package.json is actually
  0.4.0-alpha.2, not alpha.1), and corrected the npm-publish claim after
  actually checking: `npm view @jimhoyd/urlcode` shows 0.3.0 published
  as `latest` and 0.4.0-alpha.1 published under the `alpha` dist-tag, so
  "no published npm release" was flatly wrong, not just imprecise;
  Homebrew is a formula GitHub Releases attach for manual copy into a
  tap, not an automated publish, stated as such rather than lumped in
  with npm.
- docs/OPERATIONAL-PROOF.md said CI covers six Node/OS combinations;
  checked .github/workflows/ci.yml and corrected to the actual matrix —
  nine combinations (3 Node x 3 OS) on a push to main, but a pull
  request runs only the three Node versions on Linux, with macOS/Windows
  deferred to the post-merge run.

Regenerated llms-full.txt (npm run docs:llms) since it derives from the
docs touched here.

Fixes #140

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018neC2tYKPxMPbzZf1wNctr
@jimhoyd
jimhoyd merged commit 98f1a9a into main Sep 19, 2026
10 checks passed
@jimhoyd
jimhoyd deleted the claude/fix-trusted-execution-bugs branch September 19, 2026 06:00
jimhoyd added a commit that referenced this pull request Sep 19, 2026
The sandboxed (QuickJS/WASM) execution path had the same bug #143 fixed
in the trusted-execution path: guest-api.ts unconditionally serialized
body: '' for a HEAD request without ever measuring response._text, so
function-worker.ts's outgoing FunctionResult carried no length and
http-response.ts's prepareResponse advertised Content-Length: 0 for a
HEAD reply even when the equivalent GET had a real body.

The guest already holds _text as a fully materialized string, so its
byte length is known without any stream read or extra host capability.
guest-api.ts now sends that length as an optional contentLength field
alongside the empty HEAD body (computed by a small in-sandbox UTF-8
byte counter, since the guest has no TextEncoder/Buffer), threaded
through function-worker.ts's validated response and functions.ts's
FunctionWorkerMessage, mirroring how native.contentLength already
crosses the same boundary. prepareResponse is unchanged; it already
picks this up exactly as it does for the trusted/native paths.

No sandboxing guarantee changes: the module allowlist, byte budgets,
worker termination and guest capability surface are untouched — only
a length integer crosses the existing JSON boundary.

Added a regression test (test/sandbox.test.ts) mirroring #139's test
for the trusted path: confirmed it fails against unmodified guest-api.ts
(Content-Length: 0 for a nonempty GET body) and passes after the fix,
for both a plain sandboxed function and a middleware-transformed one.

Fixes #144


Claude-Session: https://claude.ai/code/session_018neC2tYKPxMPbzZf1wNctr

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants