Skip to content

fix(sandbox): re-enforce SDK manifest + org-slug guard on __sdk_dispatch host side#680

Merged
buremba merged 1 commit into
sec/hardening-sweepfrom
sec/7-sdk-sandbox
May 13, 2026
Merged

fix(sandbox): re-enforce SDK manifest + org-slug guard on __sdk_dispatch host side#680
buremba merged 1 commit into
sec/hardening-sweepfrom
sec/7-sdk-sandbox

Conversation

@buremba
Copy link
Copy Markdown
Member

@buremba buremba commented May 13, 2026

WS7 — isolated-vm SDK guest isolation

__sdk_dispatch(path, payloadJson, orgPath) is a guest-visible global. The guest-side Proxy only advertises manifested methods, but a malicious script can call __sdk_dispatch directly with anything. The host had a hasOwnProperty namespace guard and dry-run skipped writes for read_sdk, but run_sdk mode would actually execute an un-manifested write.

Changes (packages/server/src/sandbox/run-script.ts)

  • Re-enforce the manifest on the host. Build the same dispatchable-path set the manifest exposes (log, query, plus every ns.method in manifest.byNamespace) and reject any path not in it — regardless of run mode. Dry-run only skips writes for the modes that have it; it was never an authorization gate.
  • Org-slug guard. Reject orgPath slugs that are __proto__ / constructor / prototype, non-string, or when org isn't an own property of the target SDK — before calling target.org(slug).
  • allowCrossOrg enforced at dispatch time. If false, reject any non-empty orgPath rather than relying solely on the manifest omitting org from topLevel.
  • Dry-run / sideEffectPreview behaviour unchanged for the modes that have it.

Test

packages/server/src/__tests__/unit/sandbox/manifest-enforcement.test.ts — drives runScript with a stub SDK and a script that calls __sdk_dispatch directly:

  • run_sdk mode, un-manifested entities.wipeEverything → rejected (Unknown SDK method), handler never invoked
  • orgPath: ['__proto__'] → rejected (Invalid org slug), org() never called
  • allowCrossOrg: false + orgPath: ['other-org'] → rejected (CrossOrgAccessDenied)
  • manifested entities.list → still works

make build-packages + bun run typecheck pass; sandbox unit suite green.

…Org on __sdk_dispatch host side

A malicious guest script can call the __sdk_dispatch global directly with an
un-manifested method, a poisoned orgPath ('__proto__'/'constructor'), or a
cross-org path the manifest never advertised. Re-check all three on the host:

- reject any path not in the manifest's dispatchable set, regardless of mode
  (dry-run only skips writes for modes that have it - it is not an auth gate)
- reject org slugs that are __proto__/constructor/prototype, non-string, or
  when 'org' isn't an own property of the target SDK, before target.org(slug)
- reject any non-empty orgPath when allowCrossOrg is false

Adds packages/server/src/__tests__/unit/sandbox/manifest-enforcement.test.ts.
Copy link
Copy Markdown

@codex-approver codex-approver Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Auto-approved: Codex left a 👍 reaction (no suggestions).

@buremba buremba merged commit a96111e into sec/hardening-sweep May 13, 2026
5 checks passed
@buremba buremba deleted the sec/7-sdk-sandbox branch May 13, 2026 13:13
buremba added a commit that referenced this pull request May 13, 2026
…y, token revocation, egress timeout, sandbox, encryption-key (#692)

* fix(sandbox): re-enforce SDK manifest, org-slug guard, and allowCrossOrg on __sdk_dispatch host side (#680)

A malicious guest script can call the __sdk_dispatch global directly with an
un-manifested method, a poisoned orgPath ('__proto__'/'constructor'), or a
cross-org path the manifest never advertised. Re-check all three on the host:

- reject any path not in the manifest's dispatchable set, regardless of mode
  (dry-run only skips writes for modes that have it - it is not an auth gate)
- reject org slugs that are __proto__/constructor/prototype, non-string, or
  when 'org' isn't an own property of the target SDK, before target.org(slug)
- reject any non-empty orgPath when allowCrossOrg is false

Adds packages/server/src/__tests__/unit/sandbox/manifest-enforcement.test.ts.

* test(connections): pin webhook signature verification contract (#678)

Inbound chat-platform webhooks (/slack/events, /api/v1/webhooks/:id) are
authenticated by the Chat SDK adapter for each platform, not the HTTP
route. Verified the adapters genuinely perform the documented scheme:

- slack    → HMAC-SHA256 over `v0:{ts}:{rawBody}` vs `x-slack-signature`,
             401 on mismatch (@chat-adapter/slack `verifySignature`)
- telegram → constant-time compare of `x-telegram-bot-api-secret-token`
- discord  → Ed25519 verify of `x-signature-ed25519`/`-timestamp`
- whatsapp → HMAC-SHA256 over the body vs `x-hub-signature-256`
- teams    → Bot Framework bearer-JWT validation in `bridgeAdapter`

Adds a regression test that drives the real Slack adapter — forged
signature → 401, missing signature → 401, stale-but-signed replay → 401,
correctly-signed url_verification challenge → 200 — plus route-level
tests that the /slack/events edge keeps its freshness-window check and
delegates fresh requests to ChatInstanceManager.handleSlackAppWebhook.
Documents where verification happens in slack.ts and handleWebhook().

* fix(egress-judge): hard per-call timeout that fails closed and feeds the breaker (#677)

The LLM egress judge was awaited synchronously by the HTTP proxy with no
timeout independent of the model client's own transport timeout, so a hung
judge call could stall an outbound request indefinitely. Add a per-call
timeout (default 8s, configurable via EGRESS_JUDGE_TIMEOUT_MS or
EgressJudgeOptions.judgeTimeoutMs) that, on expiry, fails the verdict
closed (deny) and counts as a circuit-breaker failure — so a run of
timeouts opens the breaker and subsequent calls short-circuit without
invoking the model. Verdict cache untouched.

* fix(orchestrator): block Nix-expression injection in nix-shell -p (#682)

* fix(orchestrator): block Nix-expression injection in nix-shell -p

Skill-declared nixPackages were passed directly to `nix-shell -p <arg>`,
which evaluates each <arg> as a Nix expression. A skill could smuggle a
side-effecting expression — e.g. `pkgs.fetchurl; builtins.exec ...`,
`import ./evil.nix`, or `a && b` — past the previous charset-only
validator and run code at evaluation time, before the worker process
even started.

Replace the raw pass-through with strict validation: each entry must be
either a leaf identifier matching `^[a-z0-9][a-z0-9-]*$` or a
`<known-namespace>.<leaf>` attr path (only known per-language sets like
`python3Packages`, `nodePackages`, …; matches the shapes real skills
already use). Validated names are re-emitted as explicit `pkgs.<...>`
references inside a single `nix-shell -E` expression
(`let pkgs = import <nixpkgs> {}; in pkgs.mkShell { buildInputs = [ … ]; }`),
so nix-shell never parses caller-controlled text.

* fix(orchestrator): allow underscores in Nix package leaf names

NIX_LEAF_RE was /^[a-z0-9][a-z0-9-]*$/ which rejected valid nixpkgs
attributes like `poppler_utils` (used in examples/personal-finance/lobu.toml).
Underscore is a legal character in Nix attribute names and is safe here because
the injection-guard metacharacter regex already blocks ; | & etc., and the
attr is re-emitted as pkgs.<attr> — the raw string is never handed to nix.

Updated regex: /^[a-z0-9_][a-z0-9_-]*$/ (mirrors NIX_ATTR_LEAF_RE which was
already correct for namespace-qualified leaves).

Added positive test cases: poppler_utils, csvtk, cairo_2.
Added negative cases confirming semicolons are still blocked even when
combined with underscore-containing names (pkgs;builtins.exec, foo_bar;builtins.exec).

Fixes Codex P2 finding on PR #682 (sec/3-nix-injection).

* fix(proxy): harden worker egress proxy against SSRF via IPv6 normalization (#681)

* fix(proxy): harden worker egress proxy against SSRF via IPv6 normalization

Route every resolved IP and CONNECT/forward target literal through a
single normalizeIpLiteral() funnel before the blocklist check: handles
IPv4-mapped IPv6 (dotted and hex), NAT64 (64:ff9b::/96), compressed
forms, and strips zone IDs; normalized-to-IPv4 results are re-checked
against the IPv4 blocklist, and anything that looks like an IP literal
but won't parse fails closed. Validate the CONNECT port is an integer
in 1..65535. Pin connections to the already-validated address (no
re-resolve) and document that 3xx redirects re-enter the proxy and are
independently re-validated. Adds a vitest regression suite.

* fix(proxy): canonicalize IPv6 before NAT64 prefix check

The previous startsWith("64:ff9b::") check only matched compressed IPv6
spellings, so a fully-expanded form such as `64:ff9b:0:0:0:0:a9fe:a9fe`
(= 169.254.169.254 — AWS metadata endpoint) passed net.isIP() === 6,
missed the NAT64 decode, and fell through to the bare IPv6 blocklist
which does not know about embedded IPv4 addresses.

Fix: add expandIpv6ToHextets() which normalises any valid IPv6 string
into 8 unsigned 16-bit hextets (handling :: compression and dotted-quad
suffixes per RFC 4291 §2.2). The NAT64 check now verifies hextets
[0..5] === [0x0064, 0xff9b, 0, 0, 0, 0] then extracts the embedded IPv4
from hextets [6..7], so both compressed and expanded spellings produce
the same decoded IPv4 and the existing private-IP blocklist catches it.

Identified in Codex review of PR #681.

Tests: adds three new cases covering compressed-form loopback (already
blocked), expanded-form link-local (the regression — now blocked), and
expanded-form public address (still allowed).

* feat(auth): jti-based token revocation kill switch (WS5) (#683)

* feat(auth): jti-based token revocation kill switch

Worker tokens and settings session cookies are pure cryptographic
material — a leaked token used to be valid until expiry with no way
to invalidate it. Both token types now carry a random `jti` minted at
issue time, and a new `revoked_tokens` Postgres table (mirroring
`grant-store.ts`) maps revoked jtis to their original expiry.

- `generateWorkerToken` mints `jti: randomUUID()`; `WorkerTokenData`
  gains `jti?: string`.
- `setSettingsSessionCookie` mints `jti` when absent. A new local
  `SettingsSession` type widens the decoded payload so the field
  surfaces through verification without changing the shared payload
  interface.
- New `RevokedTokenStore` (Postgres-backed, in-memory TTL cache,
  lazy GC sweep, lazy `CREATE TABLE IF NOT EXISTS`).
- `createApiAuthMiddleware` calls `isRevoked(jti)` after both the
  settings-cookie path and the worker-token path; revoked tokens
  return 401.
- New `lobu token revoke <jti>` CLI subcommand writes the row via
  `DATABASE_URL`. Effective within one cache TTL (~60s).
- Vitest/bun regression test covers store revoke/isRevoked/sweep plus
  the middleware accept/reject paths.

* fix(auth): enforce jti revocation inside verifySettingsSession, not just middleware

Codex P1 finding (PR #683 sec/5-token-revocation): RevokedTokenStore.isRevoked(jti)
was only checked inside createApiAuthMiddleware. Routes that call verifySettingsSession
or verifySettingsSessionOrToken directly bypass that middleware and therefore accepted
revoked cookies until token expiry.

Previously-bypassed routes:
- packages/server/src/gateway/routes/public/agent-history.ts:275
- packages/server/src/gateway/routes/public/agent-config.ts:354,375,409
- packages/server/src/gateway/routes/public/connections.ts:473,508

Fix:
- verifySettingsSession, verifySettingsToken, and verifySettingsSessionOrToken are
  now async and perform the isRevoked check before returning the session payload.
- A setRevokedTokenStore() injector (mirroring setAuthProvider()) allows tests to
  supply a custom store without touching the process-wide singleton.
- The redundant post-check in createApiAuthMiddleware is removed; the middleware
  now delegates to the shared helper for settings session revocation.
- All call sites updated to await the now-async functions.
- Three new tests for verifySettingsSession: live jti passes, revoked jti returns
  null, injected store takes precedence over singleton.

* fix(secret-proxy): 24h orphan TTL + per-source failed-resolution throttle (#679)

Reduce the placeholder->secret mapping default TTL from ~7 days to 24h
(configurable via SECRET_PLACEHOLDER_TTL_MS) so an orphaned mapping left
behind by a worker crash / mid-day agent deletion stops being live within
a day; teardown cascade and lazy GC are unchanged. Add an in-memory
per-source (bound agentId, else client IP) cap on *failed* placeholder
resolutions: after 20 misses in 5min the source hard-fails and we log the
throttle once instead of per-attempt -- a successful lookup clears the
bucket, so legitimate high-throughput valid traffic is never throttled.
The cross-agent placeholder-binding 403 is untouched.

* fix(core): harden ENCRYPTION_KEY parsing and make worker-token clock skew configurable (#676)
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.

1 participant