Skip to content

feat(sbx): SBX0 1b, sandbox identity and lifecycle (sandbox profile, sandbox tokens, relay verification, mocactl sbx) - #550

Merged
pdettori merged 33 commits into
mainfrom
feat/sbx0-1b-identity
Oct 20, 2026
Merged

pdettori merged 33 commits into
mainfrom
feat/sbx0-1b-identity

Conversation

@pdettori

@pdettori pdettori commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

Increment 1b of SBX0, identity and lifecycle. It implements spec docs/specs/2026-10-15-sbx0-internal-sandbox-service-design.md (v1.1) and ADR-0042.

After this PR, a team member can log in with mocactl sbx login (GitHub device flow, github.com), create a sandbox, and get a 15-minute Ed25519 sandbox token. The token is bound to exactly one worker and one workspace key. The relay verifies it with public keys only, so one user can't reach another's sandbox. Access ends at expiry, and within one token lifetime of a delete. The prototype's static client tokens are gone. There is no proto change and no worker change.

Based on main: #546 (spec and ADR) and #547 (1a) are merged. #554 (1c) is stacked on this PR.

Control plane (@moca/control-plane)

  • Route profiles. Each route carries an allow list of the profiles that mount it, harness or sandbox. Under SH_ROUTE_PROFILE=sandbox only the login routes and the sandbox resource are mounted, and every other route returns 404 exactly like an unknown path. A test runs every harness-only route through the sandbox profile.
  • The sandbox resource. It covers templates, create, list, get, delete, token mint, and a janitor read (GET /v1/janitor/sandboxes, behind its own bearer token).
    • Records live in a Redis/Lua store. Quota checks and inserts run in one script, so racing creates can't both take the last slot.
    • Expiry is computed at read time, and terminated records are kept for a retention window.
    • A non-owner gets 404 on every id route.
    • Minting is owner-only, for admins too. One commit message (4bb7d6a) words this badly; this is the rule.
  • The sandbox token. It has typ: moca-sandbox+jwt and aud: moca-sandbox, and claims sbx/wrk/wsk. Its expiry is the earlier of now + TTL and the sandbox's expiresAt. typ is pinned on both verifiers: the harness verifier now refuses anything but typ: JWT.
  • Enrollment. SH_ALLOWED_SUBJECTS gates device-flow completion and refresh. A de-enrolled user is stopped at their next refresh, and their refresh family is revoked under its own audit reason (not_enrolled), so it never shows up as refresh_reuse_detected. The 403 names the caller's own github:<id>.
  • API version. OpenAPI is now 1.2.0, with a CHANGELOG entry.

Relay (@moca/sandbox-relay)

  • A sandbox caller kind. The relay verifies sandbox tokens against SH_SANDBOX_TOKEN_PUBLIC_KEYS, then requires an exact match on wrk/wsk before routing. It boots with no harness exec token.
  • Spec §3.6 rules:
    • each sandbox's req_ids are mapped before reaching the worker, so dedup and Abort never cross sandboxes;
    • an Exec is cancelled at its token's exp + 30 s leeway;
    • each sandbox has an in-flight cap (SH_SANDBOX_MAX_INFLIGHT, default 2);
    • Abort is checked for ownership.
  • Tests. A transport-level matrix covers every refusal in §10.2. Each of the 24 checks was deleted in turn, and each deletion made a test fail.

Deploy

  • ocp-sbx overlay.
    • Adds the control plane (sandbox profile) and an edge API Route, with a NetworkPolicy that admits only the router and allows no Kubernetes API egress.
    • Removes the relay's MOCA_RELAY_EXEC_TOKEN (an overlay test asserts that it is absent).
  • setup.sh.
    • Generates and keeps the Ed25519 signing key, and publishes its public keyset to the relay.
    • Writes the settings ConfigMaps.
    • Writes worker bundles that carry SH_WORKSPACE_IDLE = lifetime + 2 days.
    • New inputs: API host, GitHub client id, subjects, templates, workspace filesystem size, lifetime, quotas, in-flight cap, token TTL and retention.
    • Refuses SBX_CLIENTS.
    • Refuses a change to SH_WORKSPACE_IDLE on running workers unless SBX_ACK_HOSTS=1 is set.
  • Upgrade from 1a. Static client tokens and their bundles are deleted. The exec token is removed only after the new relay has rolled out. install-host.sh refuses a 1a bundle.
  • CI. The signing-key round trip (makeSigner, then the relay's verifier) is required in CI's check job.

Clients

  • mocactl sbx. Adds login, templates, create, ls, rm, token and env, HTTP only. It keeps its own sbx-auth.json, so it never displaces a MOCA login. eval "$(mocactl sbx env)" is shell-safe. mocactl still has exactly one workspace dependency.
  • Direct-client guide and Python examples. docs/api/sandbox-v1-direct-client.md and docs/api/examples/{sandbox_v1_client,sbx}.py are new on main. Their offline tests run in CI's docs job, against pinned grpcio.

Review fixes (review of 2026-10-19)

All 16 comments are fixed; each thread has a reply naming its commit.

  • Relay (24c1e33):
    • the expiry Abort is always sent, and a call already cancelled routes nothing;
    • an unacknowledged Exec gives back its slot and Abort ownership 60 s after its expiry abort (outcome: "released");
    • workerReqId is HMAC-SHA-256 under a per-boot relay key, so a sandbox can't aim at another sandbox's dedup entry.
  • Control plane (d274c67):
    • the sandbox profile mints and accepts API tokens under its own issuer (sbx-control-plane-api);
    • CREATE prunes dead index members;
    • SH_SANDBOX_TOKEN_TTL_SECONDS is capped at 3600.
  • Deploy (25ed28d):
    • setup.sh refuses a moca-mu1 it did not create;
    • the API Route key is patched onto the Route rather than going through the overlay;
    • route certificates are in the settings hash, and every Secret read is captured before use;
    • the control plane's 443 egress excludes private, CGNAT and link-local ranges;
    • the API Route refuses plain HTTP and sends HSTS;
    • the README covers rotation (a hard cut) and the one-namespace rule.
  • Docs (ac6f6da):
    • timeout_s must be sent, and a completed req_id replays its result;
    • the Python client has token slack and wraps the abort;
    • the OpenAPI declares the 503s and invalid_json.

Verification

  • make lint, make typecheck, go test ./... and make test-deploy pass, re-run after the review fixes on top of main. Every new test fails without its fix.
  • Every package suite passes when run on its own. Two load-only timeouts occasionally fail under full-parallel make test: the supervisor's shutdown-grace test, and mocactl's overlay-credentials. Neither is in code this PR touches.
  • Review: each task had a spec and quality review. The whole branch had a final review, and its fix wave was re-reviewed. feat(sbx): SBX0 1a, the front door (relay keepalive, ocp-sbx overlay, setup, host install) #547's review fixes are merged in here too.

Still owed before the cohort uses it: the live acceptance. That means the image, the OAuth app, a deploy, two-user isolation, delete timing, and a silent 5-minute command. It needs a maintainer's go-ahead and a second enrolled GitHub account.

🤖 Generated with Claude Code

…ier (SBX0 §4.3)

signJws/verifyJws generalize the Ed25519 primitive over typ (MI1 §6.1).
mintSandboxToken binds one sandbox, worker and workspace key, capped at the
sandbox's expiry; verifySandboxToken pins typ moca-sandbox+jwt, audience
moca-sandbox and the issuer, with 30 s of skew. verifyToken now refuses any
typ but JWT, so neither kind passes as the other. Adds the sandbox error codes
and CpError's extra body fields.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Every route names the control planes that mount it. The sandbox profile mounts
only the probes, discovery and the login routes so far; any other route answers
the unknown-path 404 there, and a route added without a profile is mounted
nowhere until someone lists it.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…BX0 §5)

Expiry is computed, not scheduled, so an expired sandbox reads terminated with
no job running. Quotas count live sandboxes and are checked inside one Lua
script with the insert, so racing creates cannot both take the last slot. Names
are unique among an owner's live sandboxes and free on delete or expiry;
retention is the record key's TTL. One contract suite runs on both stores.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…liveness

The name key's PXAT is now expiresAt + retention, so a Redis clock running
ahead cannot drop it while its holder is live; the live ZSET alone decides.
New contract cases: expired sandboxes do not count against the total quota,
and a name frees by the caller's clock with no wait. The memory retention
test pins the exact boundary, and a Redis test pins the name key's TTL.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…covery (SBX0 §4)

SH_ROUTE_PROFILE=sandbox boots with no credential store, KEK, exchange token
or inference settings, and refuses to boot without an allow list, templates or
an exec endpoint. SH_ROUTE_PROFILE itself accepts exactly harness or sandbox
(empty means harness); a near-miss refuses to boot rather than unmounting every
route, /healthz included. Only enrolled subjects and admins get a login,
checked before a refresh family exists, and a de-enrolled subject is stopped at
its next refresh. Discovery under sandbox answers { profile, execEndpoint,
execCa? } (spec v1.1); under harness it adds profile: 'harness'. The audit
stream gains sandboxId, and SH_JANITOR_TOKEN joins the systemd credentials.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
- mocactl contract test: resolveSchema flattens oneOf/anyOf (the union of
  every branch's properties), so the discovery oneOf resolves again.
- Templates refuse a tools list that names a tool twice.
- tokenTtlsFromEnv: one source for the API, session and refresh TTLs,
  shared by both route profiles; behaviour unchanged.
- Discovery throws internal_error on a sandbox profile with no sandbox
  config, instead of answering the harness body.
- Boot refuses an SH_ALLOWED_SUBJECTS entry outside github:<digits>
  (new GITHUB_SUBJECT_RE in identity.ts), an exec endpoint port outside
  1-65535, and an SH_SANDBOX_EXEC_CA without a PEM certificate header.
  Each refusal names the variable, never the value.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…store verifyJws comments

writeError merges CpError.extra first and error, message and sessionId last,
dropping those keys from extra, so a stray field cannot relabel the code a
client branches on. verifyJws regains the two comments Task 1 dropped: why alg
is refused before the key lookup (the JWT alg downgrade), and the bad(): never
narrowing.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Templates, create, list, get, delete and token, on the sandbox profile only,
plus the host janitor's read (GET /v1/janitor/sandboxes: live and terminated)
behind its own bearer. A non-owner gets 404 on every id route; admins may read
and delete but never mint, not even their own way into another user's sandbox.
A token is refused with its reason once a sandbox is deleted or has expired,
with no job having run. Create and delete are audited with the sandbox id.

The exchange and janitor bearers share one constant-time check,
checkStaticBearer. OpenAPI 1.2.0 documents the routes, the Sandbox schema, the
sbx- id pattern and the janitorToken scheme.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…e (SBX0 §5.1 review)

asRecord, seconds, isAdmin and auditBestEffort move to handler-util.ts, a leaf
module neither handlers file is imported by, and both use it; the inline admin
checks in listSessions and deleteConfigBundle become isAdmin. No behaviour
change.

checkStaticBearer compares SHA-256 digests with timingSafeEqual, so the
compare no longer returns early on a length mismatch and its timing reveals
nothing about the configured bearer's length; still fail-closed on a missing
value.

openapi.yaml's labels drop maxLength (characters) for the byte limit in prose,
and state the key pattern as propertyNames, pinned to LABEL_KEY_RE by the
contract test. route-profile.test.ts shares one expectUnknownPath helper.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
….6 rules (SBX0 §3)

The relay verifies a moca-sandbox+jwt with the sandbox control plane's public
keys only (control-plane's verifySandboxToken, which now also checks tenant,
iat and jti), and admits an Exec only for exactly the token's worker and
workspace key, refusing before routing. A sandbox caller may abort only an
in-flight Exec of its own sbx. The relay boots with sandbox keys and no
harness exec token; with neither it still refuses to boot, and a malformed
keyset or a missing issuer is a boot error naming the variable.

Sandbox Execs (spec v1.1 §3.6): the worker sees a per-sbx req_id
(workerReqId) and the caller only ever its own; an Exec still running at
exp + leeway is aborted at the worker and ends DEADLINE_EXCEEDED; at most
SH_SANDBOX_MAX_INFLIGHT (default 2) Execs per sbx, else RESOURCE_EXHAUSTED.
Timer, counter and ownership are released in finally on every path. Harness
callers are unchanged: checked first, unrestricted, unmapped, uncapped.

Every non-OK status goes through one grpcError(code, message) helper.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…nv names the keyset-only boot

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
The ocp-sbx overlay runs the control plane on the sandbox route profile
behind the edge Route sbx-api, with only its signing key mounted and no
service-account token. The router is the only way in. The relay reads the
public keyset, the issuer and the in-flight cap from the new settings, and
the base's harness exec token is removed (spec v1.1 §3.1).

setup.sh:
- generates the Ed25519 key with openssl (PKCS#8 DER base64, as makeSigner
  takes; kid = sha256(SPKI)[:16], as keyIdFor);
- writes moca-settings and sbx-settings, and checks templates by
  parseTemplates' rules and the disk budget;
- stamps one settings hash on both pod templates;
- derives each worker bundle's SH_WORKSPACE_IDLE from the lifetime and
  carries SH_WORKSPACE_IMAGE_MB.

It also removes all of 1a's machinery: the client tokens, their Secrets and
bundles, the client-tokens hash, and the exec token (by explicit null
patch). It refuses SBX_CLIENTS and a whitespace-only SBX_WORKERS.

install-host.sh takes the idle and the image size from the bundle.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…, CI)

- setup.sh caps SBX_MAX_TOTAL, SBX_MAX_PER_SUBJECT and
  SBX_WORKSPACE_IMAGE_MB at six digits, so the disk check's 64-bit
  product cannot wrap and pass.
- moca-relay loses a 1a MOCA_RELAY_EXEC_TOKEN only after the new relay
  has rolled out. The 1a relay's template requires that key, so a run
  failing earlier would leave a restarted pod unable to start.
- install-host.sh refuses a bundle with no SH_WORKSPACE_IDLE instead of
  defaulting it.
- The README says SBX_IMAGE must move off the 1a image.
- CI's check job runs setup.test.sh with MOCA_REQUIRE_WORKSPACE=1, so the
  signing-key round-trip cannot be skipped unseen.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…nv (SBX0 §6.1)

A command group on the sandbox service's own control plane (flag, then
MOCACTL_SBX_URL, then the URL remembered at login), dispatched before the
global flag table. Its login lives in its own file, sbx-auth.json beside
auth.json, with its own refresh lock, so it never replaces a MOCA login;
buildRuntime gains a narrow paths hook for it. login refuses a control plane
whose discovery is not the sandbox profile before showing a device code.

A user de-enrolled since login is told so at refresh (exit 1); exit 4 is kept
for network failures. env prints exports for a direct sandbox/v1 client -- a
token command, never the 15-minute token -- and writes a self-issued exec CA
to a 0600 file under an absolute path. The contract test now pins the fields
SandboxApiClient reads against openapi.yaml.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…s nits)

SBX_TOKEN_CMD names the control plane, shell-quoted, when the URL came from
--control-plane-url or MOCACTL_SBX_URL rather than config.json, so the
command works in a shell that has neither. A 401 whose forced refresh failed
now reports what the refresh hit -- a network failure exits 4, not_enrolled
exits 1 -- and only a refused login exits 3. ls sanitizes before padding and
shows a terminated sandbox with no reason as plain "terminated"; the
no-sandbox-routes 404 heuristic is explained.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… SBX0

How to call SandboxExec on the sandbox service: access through mocactl sbx,
the fields a client sets, 15-minute tokens refreshed through a command, outcomes
versus failures, limits, and the additive-only promise. The example client
speaks TLS with keepalive and retries an UNAUTHENTICATED Exec once only if it
never started.

Spec v1.1 section 7: ExecError "timeout:<n>" is a timeout (sbx.py exits 124);
DEADLINE_EXCEEDED "sandbox token expired during the Exec" and RESOURCE_EXHAUSTED
"sandbox busy" get their own messages (exit 125); before each Exec the token
must have timeout_s + 60 s left, and timeout_s defaults to, and is capped at,
the token lifetime minus 60 s. req_id is unique within the sandbox, and the
relay namespaces it per sandbox. Offline unittest, no network or relay.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…D, CA roots, CI)

A second UNAUTHENTICATED after the one token refresh now raises SandboxError
instead of escaping as an internal exception (sbx.py exits 125). The token
command's stderr reaches the user; stdout, the token, is never echoed. The CA
file is read with a context manager, and the guide says SBX_CA_FILE replaces
the default roots. sbx.py reports signal n as 128 + n and calls itself an
example. The grpcurl example keeps the token out of argv. The docs CI job runs
the examples' offline unittest with grpcio 1.84.0 in a venv.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…d pins them on ocp-sbx

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…not_enrolled

I1: refreshAuth on the sandbox profile rotated the family and then threw
403 not_enrolled, so the client kept a superseded token whose next use
tripped reuse detection (a false refresh_reuse_detected theft audit). The
handler now revokes the family with reason not_enrolled before throwing,
and mocactl drops the refresh pair from sbx-auth.json on a not_enrolled
refresh, so the token is never presented again. RefreshStore.revoke takes
an optional reason (default logout) in both stores; the contract suite
pins it, and observability.md lists the refresh_revoked reasons.

M5: the 403 not_enrolled message names the caller's own subject
(github:<id>) so the user can hand it to an operator; mocactl passes the
server message through.

Also in mocactl (M4, M7): `sbx rm` says issued tokens keep working for up
to one token lifetime plus 30 s, and the usage text calls 15 minutes the
default.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…tention inputs; no 6443

I2: raising SBX_LIFETIME_DAYS rolled the control plane at once while the
workers kept their old SH_WORKSPACE_IDLE until install-host.sh was re-run,
breaking idle > lifetime on running hosts. setup.sh now compares the
newly computed idle with each listed worker's existing
.generated/workers/<id>/worker.env and, when it differs, refuses before
applying anything unless SBX_ACK_HOSTS=1; the refusal names the variable,
both values and the workers, and says to re-run install-host.sh on every
host first (or right after, with the ack). An acknowledged run warns
again at the end, naming the hosts to reinstall.

M1: SBX_TOKEN_TTL_MINUTES (5-60, default 15) and SBX_RETENTION_DAYS
(1-90, default 14) become SH_SANDBOX_TOKEN_TTL_SECONDS and
SH_SANDBOX_RETENTION_SECONDS in sbx-settings, in the settings hash, and
in the ocp-sbx control-plane env.

M9: the ocp-sbx overlay drops the base's 6443 (Kubernetes API) egress from
the control plane's NetworkPolicy (a JSON6902 test+remove, so a reordered
base fails the render); overlay.test.sh asserts it.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
I3: /v1/auth/device/token and /v1/auth/token answer 403 not_enrolled on
the sandbox profile, but the OpenAPI document did not say so. Both now
declare it (sandbox profile only, the shared Error schema), the 1.2.0
CHANGELOG entry says so, and the contract test asserts that every route
able to throw not_enrolled declares a 403.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…bx:ended set

M2: terminatedBefore had no caller (1c's janitor reads
GET /v1/janitor/sandboxes, which lists every retained record), and the
sbx:ended sorted set was read by nothing else. Both go: the interface
method, MemorySandboxStore's and RedisSandboxStore's implementations, its
contract case, and the DELETE script's ZADD/ZREMRANGEBYSCORE upkeep. The
store contract suites stay green against both stores.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…notes

M4: the direct-client guide and deploy/sbx/README.md say that delete and
de-enrollment are not immediate: an issued token works for up to one
token lifetime plus 30 s, and an Exec running then is cancelled.
M7: the guide states the 15-minute token and 7-day sandbox as defaults.
M1/I2: README rows for SBX_TOKEN_TTL_MINUTES and SBX_RETENTION_DAYS, and
that a lifetime change needs every host's workers reinstalled (ideally
first; otherwise SBX_ACK_HOSTS=1 and right after).
M5: how to find a numeric GitHub id (gh api users/<login> --jq .id).
M8: 1a workspaces are not migrated; NODE_EXTRA_CA_CERTS when the router's
default certificate is not publicly trusted; no janitor in 1b, so
terminated workspaces stay until the worker's idle sweep.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…amed as such

The final review's residuals. Revoking a de-enrolled refresh family is best
effort: a store failure there used to surface as 503, which a client reads as
"unreachable" and so keeps the superseded token, the false theft signal the
revoke exists to prevent. setup.sh's idle guard, over a 1a bundle (which
carries no SH_WORKSPACE_IDLE), now says the bundle predates 1b instead of
blaming SBX_LIFETIME_DAYS, and the upgrade steps say to run with
SBX_ACK_HOSTS=1.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
1a fixes from 660532c..c8a860f, under 1b's design (no static client tokens, spec 3.1):
- fix 1 (CLIENT_RE without '-'): dropped as moot; 1b refuses SBX_CLIENTS at any value
- fix 2 (no cert on a failed kubectl get): kept for route_cert, with its transient-failure test adapted to 1b; the client_tokens_hash half dropped as moot
- fix 3 (mint only the delivered client pair): dropped as moot
- fix 4 (reset-failed before restart): kept (auto-merged), alongside 1b's SH_WORKSPACE_IDLE handling
- fix 5 (--uninstall removes shared units after the last worker): kept (auto-merged)
- fix 6 (ocp-sbx deletes sandbox-relay-exec/-attach Services): kept, next to 1b's control-plane policy patch
- fix 7 (scoped overlay security assertions, JSON render): kept and extended to 1b: the control plane admits only the router on 8080, no 6443 egress, only its signing key mounted; its Service/SA/NetworkPolicy now expected
- fix 8 (keepalive negative control, attach listener): kept (auto-merged); compiles against 1b's startRelay
- fix 9 (README: the sbx/relay-1a image): adapted to one mention in 1b's upgrade note
- fix 10 (anchored manifest greps): kept (auto-merged)
- fix 11 (newName strips the tag with a digest): kept, with its test adapted to 1b and a render check
- fix 12 (refusal/hash wording, first-worker note): dropped as moot; 1b's wording stays

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…re cleanup only)

The store dropped the ended set (nothing read it once the janitor lists live and
terminated sandboxes), and a name key now only records its last holder: liveness
is read from sbx:live at the caller's clock, so Redis clock skew cannot free a
live name.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
The SBX0 increments are stacked PRs (1b on 1a, 1c on 1b). With pull_request limited to main they got only DCO and kind-e2e; now lint, typecheck, tests and proto drift run on them too.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori marked this pull request as ready for review October 19, 2026 23:09
@pdettori
pdettori requested a review from cwiklik as a code owner October 19, 2026 23:09
@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Oct 19, 2026

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review of SBX0 1b. #547 merged on 2026-10-19, so this PR now targets main. I reviewed the effective diff against main cb7b5a9 (80 files, +8.5k/−0.6k). The control plane, relay, mocactl and examples, and deploy and CI were each read in full.

The security core holds up. typ is pinned on both verifiers (JWT vs moca-sandbox+jwt, with aud and iss checked too), so API and sandbox tokens cannot stand in for each other. Under SH_ROUTE_PROFILE=sandbox, every harness route 404s like an unknown path. Non-owners get 404, and minting is owner-only even for admins. The janitor bearer is compared in constant time. Quota, name check and insert run as one Lua script. The relay requires exact wrk/wsk, maps req_id per sandbox, checks Abort ownership through owned, and decrements the in-flight cap in finally on every exit path after admission. A relay that has only the keyset never accepts a harness caller. mocactl sbx env single-quotes every value (round-trip tested), and sbx-auth.json is 0600 and written atomically. The exec token is removed only after rollout status succeeds.

No must-fix. The suggestions below are defence-in-depth or doc accuracy: the relay expiry/cancel edge cases, an unbounded owner index in CREATE, the signing key and issuer being shared with any existing moca-mu1, TLS key exposure on the API Route, and the direct-client guide's timeout_s/req_id wording. Two of those repeat our #546 suggestions.

Merge state: GitHub reports dirty, but git merge-tree of this head with main cb7b5a9 is clean. CI last ran on 2026-10-17 against the 1a base, and only 8 checks ran. Merge main or rebase to get the full suite (CodeQL, Trivy, hadolint and the rest) on main as the base. The body still says "Draft until the live acceptance runs", but the PR is not marked draft. Approving the code here does not stand in for those acceptance runs.

Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (control-plane, sandbox-relay, mocactl), Python examples, Shell (deploy/sbx), Kustomize/OCP, CI, OpenAPI and docs
Agent/IDE config (.claude/.vscode): none
Commits: 28 commits, all signed-off: yes
CI status: passing (8/8 on 63750cf, against the old 1a base; not re-run against main)

Comment thread packages/sandbox-relay/src/main.ts Outdated
disarm = armDeadline(
(claims.exp + leewayS) * 1000,
() => {
if (call.cancelled) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: the expiry timer skips the Abort whenever call.cancelled is already set. This relies on pumpExec's onCancelled having sent one. If the call was already cancelled before that listener was registered, 'cancelled' does not fire again, so neither path sends an Abort. The command then runs on until its timeout_s (30 min by default, up to 2 h) and holds one of the sandbox's in-flight slots, which breaks §3.6's "no Exec outlives its token". A second Abort is a no-op on the worker (execRegistry.abort). So either always routeAbort here, or refuse at admission when call.cancelled is already true. (Medium confidence: I could not confirm against grpc-js 1.14 that a handler can start on an already-cancelled call.)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 24c1e33. The expiry timer now always sends the Abort, even on a call that is already cancelled; a second Abort is a no-op on the worker. Separately, a call that is already cancelled when its handler runs routes nothing. Unit tests cover both cases (sandbox-auth.test.ts, 'aborts at expiry even when the call was already cancelled' and 'routes nothing for a call already cancelled').

}
const entry = { wrk: sandboxId, wid };
// No Exec outlives its token (SBX0 §3.6): at exp + leeway the worker is told to abort and
// the call ends at once. The handler then drains the worker's acknowledgement without

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: bound the drain after the expiry Abort. The slot and the owned entry are released only when the worker sends a terminal frame for wid or disconnects. A wedged guest or vsock, or a lost Abort frame, would keep them held for as long as the attach stream lives. With the default cap of 2, two such Execs return RESOURCE_EXHAUSTED for the sandbox from then on, even with fresh tokens. The Go worker does always send a terminal frame today (runOne), so this is defence in depth: release after a grace period (30–60 s) and log it. The transport test's deaf mode shows that the slot stays held, but it never asserts what happens after that.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 24c1e33. After the expiry Abort, an Exec the worker hasn't ended within 60 s (SANDBOX_DRAIN_GRACE_S) gives back its in-flight slot and its Abort ownership, and the relay logs outcome: "released" with sub and sbx. A unit test asserts both: the slot is still held during the grace and is freed after it, and an Abort is permitted during the grace and refused after it. Spec §3.6 is amended to match.

* Exec. Deterministic, so a client retrying its own req_id still reaches the worker's dedup; 53
* bits, so the id survives the generated client's uint64-as-number mapping.
*/
export function workerReqId(sbx: string, reqId: number): number {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: workerReqId is an unkeyed SHA-256 truncated to 53 bits. "2^-53 per pair" covers accidental collisions only. A hostile sandbox chooses its own req_id and knows its own sbx, so it can search offline (about 2^53 hashes, which is GPU-days) for a wid equal to a victim's predictable (sbx, req_id). Abort and frame routing stay safe because of owned and the per-wid sinks. The exposure is the worker's dedup cache, which ignores workspace_key. If the attacker runs the victim's command first, the victim gets the cached result. The likelihood is low, but an HMAC with a relay-held secret closes it cheaply. Otherwise, record it as accepted until increment 3 hardens the worker.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 24c1e33 rather than accepted. workerReqId is now HMAC-SHA-256 under 32 random bytes the relay draws at boot and never shares, so a sandbox can't compute another sandbox's wid. A restart draws a new key. That costs nothing: the client re-sends a req_id only for a call that never started (§6.5). Spec §3.6 is updated with the reasoning. Tests pin a key through sandboxReqIdKey and check that the id depends on it.

redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now - ret)
if redis.call('ZCOUNT', KEYS[1], '(' .. ARGV[1], '+inf') >= tot then return 'quota_total' end
local n = 0
for _, m in ipairs(redis.call('ZRANGE', KEYS[2], 0, -1)) do

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: CREATE walks the owner's entire index inside one blocking Lua call. Only readIndex prunes sbx:owner:<hash> and sbx:all, and only on a list. The owner key has no TTL. A scripted user who creates and deletes but never lists grows the index without bound, and every later create (and Redis with it) does O(history) work. sbx:all grows the same way while the janitor isn't polling. Fix: prune dead members inside CREATE (members not in live whose record key is gone), or give the owner ZSET an EXPIREAT that follows its newest member, as refresh-redis ISSUE does.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in d274c67. While CREATE counts the subject's live sandboxes, it now also ZREMs every owner-index member whose record key is gone. It prunes the 16 oldest members of sbx:all the same way, so even with no janitor polling, each create removes more than it adds. A real-Redis test runs 20 create/delete/expire cycles with no list and asserts that both indexes stay at one or two members.

Comment thread deploy/sbx/setup.sh
# and apply_secret's environment.
ensure_signing_key() {
local json priv dir
json="$(secret_json moca-mu1)"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: the SBX stack signs API tokens with whatever moca-mu1 already holds, using MOCA's own iss/aud. A sandbox-profile login mints typ: JWT, aud: harness, iss: sh-control-plane, the same as the MOCA control plane. If SBX is installed into a namespace that already has a MOCA moca-mu1, or the Secret is copied, an SBX login produces a token that MOCA's control plane and data plane accept, and the reverse also holds. SH_ALLOWED_SUBJECTS then gates nothing on the MOCA side. Either give the sandbox profile its own issuer and check it in verifyToken, or refuse a pre-existing moca-mu1 that setup.sh didn't create (for example, mark it with a label). Separately, there is no rotation path. The keyset is always rewritten with only the current kid, so the overlap rotation the spec describes can't be done. Document hard rotation (it logs everyone out and invalidates all tokens) or accept extra public keys.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in d274c67 and 25ed28d.

  • Issuer: a sandbox-profile control plane now mints and accepts API tokens under iss: sbx-control-plane-api, and each verifier pins its own issuer. A test runs both profiles on one signing key and checks that each refuses the other's token.
  • Shared namespace: setup.sh labels the Secrets it writes and refuses a moca-mu1 it didn't create. It adopts an unlabelled moca-mu1 only when sbx-token-keys already publishes that key, which covers namespaces set up before the label existed.
  • Rotation: the README now documents it as a hard cut. Delete moca-mu1 and re-run. Every issued API token and sandbox token is refused at once; refresh tokens aren't signed, so mocactl sbx recovers on its next call. Overlap rotation is left for later.

Comment thread docs/api/sandbox-v1-direct-client.md Outdated
SBX_BEARER="$(eval "$SBX_TOKEN_CMD")" grpcurl -import-path proto -proto sandbox/v1/sandbox.proto \
${SBX_CA_FILE:+-cacert "$SBX_CA_FILE"} \
-expand-headers -H 'authorization: Bearer ${SBX_BEARER}' \
-d "{\"sandbox_id\":\"$SBX_SANDBOX_ID\",\"exec\":{\"req_id\":\"42\",\"command\":\"ls -la\",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: the snippet hard-codes "req_id":"42". The relay maps req_id to wid deterministically, and the worker's dedup cache (256 entries, keyed by id plus a fingerprint of command, stdin, timeout_s and streaming) replays completed results. So running the same snippet a second time, for example ls -la after editing a file, returns the cached end frame with no output and doesn't run the command. Generate a random id in the snippet. Also document that reusing a completed id replays the old result (L74 covers only the in-flight ALREADY_EXISTS case).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ac6f6da. The grpcurl snippet draws a fresh 48-bit id from /dev/urandom (checked on macOS and GNU). The req_id bullet now documents the replay: the worker keeps its last 256 completed results, keyed by id plus a fingerprint of command, stdin, timeout_s and streaming, and it answers a match with the cached end without running the command. The retry after UNAUTHENTICATED is noted as the one deliberate reuse.

timeout, capped = (cap, False) if requested is None else (min(requested, cap), requested > cap)
else:
timeout, capped = (requested or 120), False # a token without iat: no lifetime to cap at
# Mint at most once per Exec: a token minted just now is as fresh as one can be.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion: with the default timeout, need = timeout + 60 = life, and a cached token always has slightly less than life left. So every default-timeout Exec after the first spawns mocactl sbx token and does an HTTP mint. That is correct, but anyone who copies it into a loop will hammer the control plane. Leave some slack in the default case (for example, accept the token if it has at least half the cap plus 60 s left, and cut the timeout to fit), or document the behaviour. (This is the same issue as suggestion #1 in our #546 review.)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ac6f6da. A default-timeout Exec now keeps the held token while it has at least half the cap plus 60 s left (480 s with 15-minute tokens), and its timeout is cut to what the token has left minus 60 s. So back-to-back default Execs mint once. An explicit timeout the token can't cover still re-mints. The rule is in the docstring and in the guide's Tokens section, and tests cover all three cases.

Comment thread docs/api/examples/sandbox_v1_client.py Outdated
# The machinery failed (VM boot, worker gone): not the command's exit status.
raise SandboxError(f"exec failed: {ev.error.message}")
except KeyboardInterrupt:
self.abort(req_id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: self.abort(req_id) can raise grpc.RpcError, for example PERMISSION_DENIED when the Exec has just finished, and that error replaces the KeyboardInterrupt. Wrap it in try/except grpc.RpcError: pass. Related: the early returns on End and on timeout leave the stream iterator open, with no events.cancel().

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ac6f6da. A failed Abort on Ctrl-C is swallowed, so the KeyboardInterrupt propagates. That covers grpc.RpcError, and also the RuntimeError a failing token command raises. A finally calls events.cancel() on every exit, including the early returns after End and on timeout; it runs after the Abort, so the relay still knows the Exec. Tests cover each path.

Comment thread docs/api/openapi.yaml
Sandbox service control planes only (`SH_ROUTE_PROFILE=sandbox`); a MOCA control plane answers
404 (SBX0 §4.1).
post:
operationId: createSandbox

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: every /v1/templates and /v1/sandboxes* operation reads Redis and can answer 503 redis_unavailable (through RedisSandboxStore.guard), but none declares a 503, while the existing Redis-backed routes do. createSandbox's 400 also doesn't list invalid_json.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ac6f6da. 503 redis_unavailable is now declared on every /v1/sandboxes* operation and on /v1/janitor/sandboxes, and invalid_json is listed on createSandbox's 400. The 1.2.0 changelog entry is updated. GET /v1/templates is left out on purpose: it answers from config and a local JWT verify, never Redis, so it can't return redis_unavailable.

allowedSubjects,
lifetimeS: positive(env, 'SH_SANDBOX_LIFETIME_SECONDS', 7 * 86_400),
retentionS: positive(env, 'SH_SANDBOX_RETENTION_SECONDS', 14 * 86_400),
tokenTtlS: positive(env, 'SH_SANDBOX_TOKEN_TTL_SECONDS', 900),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: SH_SANDBOX_TOKEN_TTL_SECONDS has no upper bound. A large value is still capped at the sandbox's expiresAt, but invariant 3 (delete takes effect within one token lifetime) then quietly becomes "within 7 days". Refuse values above, say, 3600, or at least require ttl < lifetime.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in d274c67. SH_SANDBOX_TOKEN_TTL_SECONDS above 3600 now refuses to boot, which matches setup.sh's 5–60 minute range. Invariant 3 then reads 'within an hour at most'. Tested.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… the req_id mapping

PR #550 review. The expiry timer now always sends the Abort, even on a call already cancelled
(a call cancelled before pumpExec's listener existed never fires 'cancelled'), and a call already
cancelled when its handler runs routes nothing. An Exec the worker has not ended 60 s after its
expiry abort gives back its in-flight slot and Abort ownership, logged as outcome 'released'.
workerReqId is now HMAC-SHA-256 under a 32-byte key the relay draws at boot, so a sandbox cannot
search offline for a req_id that lands on another sandbox's worker id and plant a dedup result.
Spec §3.6 amended to match.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…xes on create, cap the token TTL

PR #550 review. A sandbox-profile control plane mints and accepts API tokens under
iss 'sbx-control-plane-api', so an SBX stack that shares a signing key with a MOCA one mints
nothing the other accepts. CREATE now drops dead members from the owner index, and the oldest
few of sbx:all, so a create-and-delete loop that never lists cannot grow them. SH_SANDBOX_TOKEN_TTL_SECONDS
is refused above 3600, matching setup.sh, so a delete always takes effect within an hour.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
… slack, abort and 503s

PR #550 review. The direct-client guide says the client must send timeout_s (the worker's
default is 30 min, longer than a token) and that reusing a completed req_id replays the cached
result; the grpcurl snippet draws a random id. The Python client keeps a held token for a
default-timeout call while it has half the cap plus 60 s left, swallows a failing abort on
Ctrl-C, and cancels the stream on every exit. OpenAPI declares 503 redis_unavailable on every
Redis-backed sandbox route and invalid_json on createSandbox.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…f the overlay, roll on cert renewal

PR #550 review.
- setup.sh labels the Secrets it writes and refuses a moca-mu1 it did not create (a MOCA control
  plane's key), adopting an unlabelled one only when sbx-token-keys already publishes it.
- The API Route's operator certificate is patched onto the Route from a 0700 temp dir, not put in
  the applied overlay: no copy in last-applied-configuration, none left under .generated.
- SETTINGS_HASH covers the attach and exec certificates, so a renewal rolls the relay (ghostunnel
  reads its certificate only at start); every secret_json is captured before use, so a failing
  kubectl get stops the run instead of hashing without a key or skipping the exec-token removal.
- The sandbox control plane's 443 egress excludes private, CGNAT and link-local ranges.
- The API Route refuses plain HTTP (None, not Redirect) and sends HSTS.
- README: one namespace per stack, signing-key rotation is a hard cut, who can read the Route key.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori merged commit 9627889 into main Oct 20, 2026
15 checks passed
@pdettori
pdettori deleted the feat/sbx0-1b-identity branch October 20, 2026 02:56
pdettori added a commit that referenced this pull request Oct 20, 2026
The relay fixes are carried into sandbox-caller.ts, where 1c moved the sandbox caller: the
expiry Abort on any call, nothing routed for a call already cancelled (audited 'cancelled'),
the 60 s drain grace (its own audit marker, sandbox_release), and the keyed req_id mapping, with
the key pinned in the shared test helper. setup.sh keeps 1c's janitor token beside 1b's foreign
moca-mu1 refusal.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
pdettori added a commit that referenced this pull request Oct 20, 2026
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants