Repository navigation
fix: MI1 S1 — multi-user isolation hardening (R1–R8) - #350
Conversation
Per-session grants the worker carries but cannot mint, moca-egress, bundle ownership and in-memory loading, per-subject container sandboxes, and the S1 hardening requirements this branch implements. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…1 R1) createPodBashOps forwards only locale/time variables; the harness process environment no longer crosses into the sandbox. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
applyModelGateway seeds a constant sentinel instead of the caller's token. A shared prepareServerProcess() runs in startServer and the P6 worker; under MOCA_TENANCY=multi it scrubs ambient credentials and refuses SH_LOCAL_TOOLS and a missing SH_REQUIRE_AUTH. 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]>
executeTurn refuses a server-mode turn whose sandbox resolves to null, on both the /turn and the leaf path, instead of leaving Pi's local tools active. SH_LOCAL_TOOLS=1 is a single-tenant development opt-in; the CLI is unchanged. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Extract the R3 gating condition (executeTurn's inline check) into a shared assertServerSandbox helper in select-sandbox.ts, and call it from realProduceSolve and realProduceVerdict right after each resolves its sandbox, releasing any lease taken before rethrowing: a server-mode leaf with no resolvable sandbox fails with SandboxRequiredError before any sandbox extension or resource loader is built. In realProduceVerdict the check sits after the crash-recovery fast path (which must not lease a pod); in realProduceSolve it is defense in depth, since that leaf already requires a configured pool. Fixes the two test files' select-sandbox.js mocks to spread the real module via importOriginal instead of replacing it outright, so the new assertServerSandbox import doesn't become undefined at runtime. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Server-mode turns load no discovered extension files, trust no project settings or SYSTEM.md, walk no ancestor context files, and use a private per-process agent directory. The lockdown is centralized in turnLoaderInputs (harness/src/run-turn.ts) and applied at all three sites that build a server-mode resource loader: executeTurnCore, and the solve and verdict leaf producers in harness/src/run-leaf.ts, which each construct their own loader from the same TurnConfig. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
… (MI1 R5) Exec and Abort require MOCA_RELAY_EXEC_TOKEN, distinct from sandbox tokens; the relay refuses to boot without it. MOCA_RELAY_EXEC_ADDR serves SandboxExec on its own listener. The worker's exec client sends the token. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
selectPoolSandbox's real, un-exported defaultExecClient was reached by no test: every grpc-branch test in select-sandbox.test.ts injects deps.makeExecClient, bypassing it, and relay-exec-client.test.ts only exercises makeRelayExecClient with a token already supplied. Add two tests that omit deps.makeExecClient so selection reaches the real defaultExecClient: one pins the fail-closed throw naming MOCA_RELAY_EXEC_TOKEN when it is unset (and that no transport is built first), the other pins that selection proceeds past client construction once the token is set, captured via an injected makeTransport so no live relay is dialed (a grpc-js client does not connect until a call is made). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…(MI1 R5) compose and deploy/vm generate MOCA_RELAY_EXEC_TOKEN once (also on upgrade) and give it to the relay and the supervisor, never a sandbox; the Kubernetes manifests carry a dev value and the OCP overlay sources it from a Secret. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…(MI1 R6) BashRunner sets an explicit cmd.Env: the container environment minus SANDBOX_TOKEN, the worker's other settings and SH_/MOCA_ variables. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…nd env (MI1 R6) Add RELAY_TLS and WORKER_MAX_CONCURRENT to the exclusion list. Fix test comment: command is 'env', not 'printenv'. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…es (MI1 R7) Under SH_REQUIRE_AUTH=true a run needs a session token naming its session and executes on the exchanged credential; status reads are authorized by session; asynchronous runs are refused until MU2's owned runs exist. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
… runs (MI1 R7) POST /runs and GET /runs/status refuse a caller-supplied tenant with 400 tenant_not_allowed once the caller has authenticated: the session token alone scopes an authenticated run and its result. Unauthenticated callers (SH_REQUIRE_AUTH off, no token) keep the tenant parameter. authorizeRunRead now returns a boolean (true when a token was presented and verified, false when none was presented and none was required) so the route can make that tenant decision without authorizeRunRead itself knowing about key-derivation shape. GET /runs/status's authorization check now runs in the same .catch()-guarded async pattern every sibling route uses, so a throw that is not a CpError (writeAuthError rethrows those) becomes a 500 for the request rather than an unhandled exception. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…(MI1 R8) Sandboxes join moca-sandbox only; Redis and the supervisor join moca-brain only; the relay bridges both and binds SandboxExec to its brain-side address. The VM templates move the supervisor's dial to the relay's loopback exec listener. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
The Network column and three new Configuration rows added in 538a8e3 left table padding Prettier normalizes; make fmt/the pre-commit hook enforce it. Whitespace only, no content change. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…(MI1 R8) Sandboxes run on a dedicated moca-sandbox podman network; an nftables table, loaded by a oneshot unit before the relay, drops everything from that subnet to the host except the attach port and DNS. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
moca-sandbox-firewall.service carries RequiredBy=sh-relay.service podman-restart.service alongside its Before=, so neither starts at boot unless the table has loaded. ensure_sandbox_network reads back the live subnet/gateway of a pre-existing moca-sandbox network (`podman network inspect`) and fails closed, naming both the expected and actual values, when they disagree with MOCA_SANDBOX_SUBNET/MOCA_SANDBOX_GATEWAY: `--ignore` keeps a pre-existing network regardless of its config, and the firewall's rules are written against the configured subnet. The checked-in unit's ExecStart uses an @SH_ENV_DIR@ placeholder instead of a literal /etc/serverless-harness path; install_sandbox_firewall renders it into the real $SH_ENV_DIR (via sed, delimiter-safe for paths) before installing the unit, so a customized SH_ENV_DIR keeps a correct unit path. install_sandbox_firewall opens the port parsed from sandbox_relay_addr()'s return value (the substring after the last `:`) rather than relay_port()'s, since SH_SANDBOX_RELAY_ADDR can point sandboxes at a different port. Updated the SH_SANDBOX_RELAY_ADDR header comment in setup-vm.sh to match. Extended the podman test mock with MOCK_PODMAN_INSPECT (defaulting to the configured subnet/gateway, so existing tests are unaffected) and added/updated assertions in setup-vm.test.sh for all four, including one exercising the installed (placeholder-rendered) unit under the test's $SH_UNIT_DIR distinct from the checked-in source unit. 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]>
…l S2 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…entry point (MI1 R2-R4) leaf-job.ts now calls prepareServerProcess(process.env) before it touches the queue, so a queued run gets the same boot contract as startServer() and the P6 worker: an inconsistent tenancy configuration refuses to boot, ambient credentials are scrubbed under multi tenancy, and the process gets a private agent directory. Its TurnConfig now comes from server.ts's buildConfig, so serverMode and allowLocalTools follow the one rule instead of a second field list. worker-boot.test.ts pins all three entry points, including a boot of the job itself under MOCA_TENANCY=multi without SH_REQUIRE_AUTH. runs-auth-route.test.ts pins that an asynchronous run presented with a session token is refused with 501 async_runs_unavailable and never queued, while an unauthenticated one is still queued. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…n step throws (MI1 R5) selectPoolSandbox now wraps every step after a successful lease.acquire in a try: if building the relay exec client or the transport throws (MOCA_RELAY_EXEC_TOKEN unset, a constructor failure), the lease is released before the original error propagates. A failed release is swallowed so it never replaces the error that explains the failure. Tests pin the release for the missing-token case and a throwing transport constructor, with the holder id the lease was taken under, and that the original error still surfaces when the release itself fails. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…t all (MI1 R3) The reachable no-sandbox case is selectPoolSandbox resolving to null. New tests drive both leaf kinds with that shape: the verdict leaf refuses with SandboxRequiredError and never builds an agent session (so no tool of any kind is registered), with a control showing the same null sandbox still runs outside server mode; the solve leaf refuses a null sandbox in every mode before the server-mode gate is reached. Rewriting the verdict guard as `if (selected) assertServerSandbox(...)` turns the verdict test red. The existing lease-without-config tests stay as defense in depth, retitled to say what they pin. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
split-listeners.transport.test.ts starts the relay the way compose and deploy/vm run it (attach and exec on separate listeners), attaches a worker over the attach listener and runs an Exec with the exec token over the exec listener: it reaches that worker and returns its output with OK. The exec listener still refuses an Exec without the token, and the attach listener answers Exec with UNIMPLEMENTED even with the token and a worker attached. exec-auth.transport.test.ts now asserts the second half of its own title: an Attach stream opened on the exec listener ends UNIMPLEMENTED. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ox token (MI1 R5) makeExecTokenValidator now also refuses a MOCA_RELAY_EXEC_TOKEN equal to SH_RELAY_TOKEN or to any SH_RELAY_TOKEN_<id>, so the workers' credential is always distinct from every sandbox's. The error names the clashing variables and never a value. Tests cover the global and per-sandbox clash, that only the clashing variable is named, and that distinct tokens still build. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…emes (MI1 R4) turnLoaderInputs now also sets noSkills, noPromptTemplates and noThemes in server mode, so no skill, prompt template or theme is discovered from $HOME, the agent directory or the project. A promoted bundle keeps delivering its skills and prompt templates through additionalSkillPaths/additionalPromptTemplatePaths, which pi loads with discovery off. loader-lockdown.test.ts drives the real Pi loader with a temp HOME: a planted $HOME/.agents/skills skill and an agent-directory prompt template are not loaded in server mode and are loaded outside it, and a promoted bundle's skill and prompt template still load in server mode. Also: the model-synthesis comment in run-turn.ts now says applyModelGateway seeds ANTHROPIC_API_KEY only with the constant sentinel; the spec's R4 row lists the new options and what pins them, and its R2 row names the async-run job among the entry points that run prepareServerProcess(). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…exec token (MI1 R5) exec-driver reads MOCA_RELAY_EXEC_TOKEN from its environment, refuses to start without it, and sends it as `authorization: Bearer` metadata on every Exec; the token is kept out of the rung plan file. drive() refuses a plan with no token before it dials. Tests pin the bearer on every Exec of a multi-slot rung, the refusal with no Execs issued, and the env reader. The SH_LIVE_RELAY=1 gates (remote-worker/internal/session/live_test.go and packages/k8s-sandbox/test/live-relay.test.ts) read MOCA_RELAY_EXEC_TOKEN (default dev-exec-token) and present it on every SandboxExec; their documented setup, and README-worker.md's, start the relay with it. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…s path; the Secret keeps both keys (MI1 R5) remote-worker/deploy-incluster.sh writes each key of sh-relay-token on its own (create when absent, otherwise a merge patch of SH_RELAY_TOKEN), so a re-run never drops MOCA_RELAY_EXEC_TOKEN; it generates the exec key only when the Secret lacks it and never rotates an existing one, so the relay it restarts always has both. The in-cluster worker still reads only SH_RELAY_TOKEN. deploy/knative/tests/deploy-incluster.test.sh pins this against a file-backed oc mock: fresh namespace, an existing two-key Secret (exec key kept, no whole-object apply), an older one-key Secret (exec key added, relay rollout succeeds), and no exec token reaching the worker or the output. Every documented remote-sandbox enablement now gives the harness MOCA_RELAY_EXEC_TOKEN: README-worker.md Step 2, remote-worker/run-local.sh and remote-worker/DESIGN.md upsert SH_REMOTE_SANDBOX, SH_RELAY_ADDR and a secretKeyRef to the ONE key MOCA_RELAY_EXEC_TOKEN of sh-relay-token, by name, in one JSON patch (`oc set env` does not apply to a Knative Service). The kind demo (docs/demos/remote-sandbox-demo.md) mints a per-run exec token for the relay and the harness only. The documented grpcurl Execs present the token, and README-worker.md's rotation note patches one key instead of re-applying the Secret. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ner, restart owned units (MI1 R5/R8) ensure_sandbox_network creates moca-sandbox with --opt isolate=strict and reads the option back: a network that does not report isolate=strict (unset, or a weaker value) stops setup with a message naming the expected and the actual value, as the subnet/gateway check does. ensure_exec_listener keeps the relay's exec listener and the supervisor's dial address together. A pre-MI1 pair (relay.env without MOCA_RELAY_EXEC_ADDR, supervisor.env dialing 127.0.0.1:9443) migrates both files to the template's loopback exec listener, in place; a pair whose ports agree is left untouched; any other combination refuses, naming both values, and writes nothing. A re-run now applies what it wrote: sh-relay and moca-sandbox-firewall are restarted, and the supervisor is try-restarted (restarted only if running, so an unconfigured one stays stopped). setup-vm.test.sh pins the isolate create flag and read-back, the refusal for three non-strict values, the listener cases (fresh no-op, pre-MI1 migration preserving other settings and file mode, already-migrated no-op, four refusing combinations), the restarts, and that main() runs the listener check; its failure messages and comments now name the behaviour they pin. Docs: deploy/vm/README.md lists nft and an isolate=strict-capable netavark as prerequisites, documents the token and listener step, the restarts on a re-run, that the firewall unit being RequiredBy the relay and podman-restart fails closed, that the rules are IPv4-only like the network, and that SandboxExec is not served on moca-sandbox (the exec token is the control). deploy/compose/README.md lists MOCA_RELAY_EXEC_TOKEN among install.sh's outputs and in the configuration table, says the network separation holds on the Docker engine and not under podman-compose, and documents upgrading by re-running install.sh. The spec's R8 row names the isolation and its check. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…(MI1) Comments on /runs and /runs/status now say what is enforced: an authenticated request may not name a tenant, because the session token alone scopes the run; the status route runs its authorization inside a caught async function like its siblings. applyModelGateway's comment and a model-gateway test say that no caller's credential becomes process-wide. A compose test message says who may hold the exec token. Review-process labels are replaced by the behaviour they pin in server.ts, turn-auth.ts, runs-auth-route.test.ts and turn-auth.test.ts. Spec: §5's introduction states what S1 hardens and that each requirement is pinned by a test; §12.1 is titled for its content; §16's paragraph on report handling is removed; §9.4 describes the dedicated, isolated network and its gateway alias as the enforced property; §8.5 states what the address checks guarantee. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…en to it If an operator's editor leaves no final newline, `>>` glues the appended assignment onto the last line. The result is SH_RELAY_TOKEN=<t>MOCA_RELAY_EXEC_TOKEN=<hex>. That silently changes the sandbox token, and every sandbox stops attaching. compose's install.sh and deploy/vm's setup-vm.sh (both the exec token and the exec address appends) now add the newline first. Both suites gain a fixture with no final newline, and removing the helper turns each red. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…en; retitle a false test name - select-sandbox.test.ts only checked that the client defaultExecClient builds has an .exec, so building it with any token passed all the R5 tests. The test now points SH_RELAY_ADDR at a fake SandboxExec server and asserts the bearer that the built client presents. Passing "x" for the token turns it red. - turn-require-sandbox.test.ts claimed that turnErrorStatus matches on the SandboxRequiredError name, but it does not (NO_CAPACITY excludes it). The title now says what the test checks. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…create race A 409 on re-create and a 204 on deleting an unowned workload make a name's existence probeable, so the comment no longer claims otherwise. POST /workloads is check-then-act. The comment and a spec §13 row now record the concurrent-create race, and what closing it takes. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ta, and how to close it R8 filters only traffic to the host (the input hook), so 169.254.169.254 is reachable over the forward path. On an EC2 host with IMDSv1, or a hop limit of 2 or more, that exposes the instance role's credentials. The README now names the exposure and the platform mitigation (IMDSv2 with hop limit 1). A spec §13 row assigns the in-product fix to S5's egress work. Changing the live-verified firewall without a live run was not worth the risk to its fail-closed load. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
|
Round 2 is addressed at Your unanchored items
Found in self-review, fixed
Found in self-review, recorded rather than fixed, each in spec §13 with the slice that owns it:
Verification at
Assisted-By: Claude (Anthropic AI) [email protected] |
The spec's §13 rows, the create-race comment in server.ts, the deploy/vm README's metadata note and docs/context-service.md now point to the six follow-up issues rossoctl#356-rossoctl#361. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
huang195
left a comment
There was a problem hiding this comment.
Round 3: approving
Mamma mia, Paolo, this round is a pleasure to review. All 12 round-2 threads are closed, and this time I checked the mechanism, not the replies. I installed the deps and broke each guard in turn:
- the
claimNamerefusal, on each of its two terms - the
api ?? 'anthropic-messages'default - the tenancy segment rule and its service-link exemption
mayDelete- the owner strip
- the Abort token guard, which is now a real positive control
- the
sub-not-tenantidentity
Each broken guard turned its own test red, and I checked it was the test named for that guard. The self-review fixes hold up too. The drift guard reads the real linked pi-ai source, not a copy. The empty-token and newline fixes are correct, and #356–#361 all exist and match their §13 rows.
No must-fix remains. Below are suggestions and nits; two of them are worth doing before merge:
- The tenancy regression.
MOCA_TENANCIESandMOCA_MULTI_TENANTnow bootsinglewithout a word. - Unpinned GET-path
sameWorkload. Nothing tests the GET-path check.
Everything else can go to §13 or a follow-up. Bellissimo lavoro. 🍝
Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (knative-server, harness, sandbox-relay), Shell (deploy/vm, deploy-incluster, setup-ocp), Go (remote-worker), docs/spec, PR body
Agent/IDE config (.claude/.vscode): none
Commits: 67, all signed-off: yes
CI status: passing (check and proto pending when drafted)
Assisted-By: Claude Code
| return out; | ||
| } | ||
|
|
||
| const tenancyLike = (c: string): boolean => c.startsWith(CORE) || editDistanceAtMostOne(c, CORE); |
There was a problem hiding this comment.
suggestion: the segment rule is a lovely fix for the SH_TENANCY family, but it gives back some names the old prefix rule caught. I called isTenancyNearMiss directly on these, and each returns false, so it boots single in silence:
MOCA_TENANCIES: a regression. The base's/^moca_?tenanc/irefused it, and it is 2 edits fromTENANCY.MOCA_TENANT,MOCA_MULTI_TENANT,MOCA_MULTITENANT,SH_MULTI_TENANT
The docstring rightly lets bare TENANT through. But after a leading MOCA/SH/KAGENTI segment, "multi-tenant" is the first thing an operator will type. Could tenancyLike also accept a TENAN prefix once a leading word has been seen? That keeps OCI_CLI_TENANCY and MAINTENANCE_MODE out, and it needs a table row for each of the names above.
There was a problem hiding this comment.
Fixed in 5fa9745, using the rule you suggested. Once a leading MOCA/KAGENTI/SH/MULTI has been seen, as its own segment or glued on, any segment starting TENAN is refused. MOCA_TENANCIES, MOCA_TENANT, MOCA_MULTI_TENANT, MOCA_MULTITENANT, SH_MULTI_TENANT, SH_TENANT and MOCATENANT are now fixtures. A bare TENANT/TENANT_ID is still let through, and so are OCI_CLI_TENANCY and MAINTENANCE_MODE. Removing the new term reddens the suite, and the repo-wide false-positive scan still passes. §10.1 states the rule and the reserved *_TENAN* prefixes.
| // Context Service knows nothing of owners: carry the stored one over the refreshed record. | ||
| const record = withOwner(sameWorkload(await getWorkload(id), id), subject); | ||
| await saveWorkload(record); | ||
| res.writeHead(200, JSON_HEADERS).end(JSON.stringify(record)); |
There was a problem hiding this comment.
suggestion, two things on the GET path:
-
The
sameWorkloadcheck here is unpinned. Removing it leaves all 17 tests inworkload-auth-route.test.tsgreen; only the create path is pinned (:224). GET is where it matters most. Without it, a reply namingotheris saved undersh:workload:otherwith the caller asowner. One test for a mismatched GET reply, like the create one, pins it. -
This write-back is a second race that §13 / POST /workloads: concurrent create of one new name can hand the owner to the later writer #356 doesn't describe. The ownership check at
:572and thissaveWorkloadare a round trip apart. Here is how it goes wrong:- Alice's GET on
xis in flight. - She DELETEs
x, and Bob re-creates it. - Alice's GET lands and overwrites Bob's record with
owner=alice.
Bob's workload now 404s to him, and Alice owns his pool. The same write-back can also bring back a record that was just marked
deleted. A set-if-absent at create doesn't cover it. A compare-and-set againststoredwould, or at least POST /workloads: concurrent create of one new name can hand the owner to the later writer #356 and the comment at:541should say GET is a writer too. Not blocking, since the victim's timing isn't the attacker's to choose, but the tracking issue should describe the whole race. - Alice's GET on
There was a problem hiding this comment.
(1) Fixed in 4d6307b. A GET reply naming other answers 502, creates no sh:workload:other, and leaves the requested record byte-identical. Removing the GET-path sameWorkload reddens it. (2) The write-back race is now #363, which describes the whole sequence, and I commented on #356 that GET is a writer too.
| return; | ||
| } | ||
| // A caller-named claim is any PVC in the namespace: owning the workload says nothing about owning | ||
| // the volume, and nothing here or in Context Service authorizes one against the other. So it is |
There was a problem hiding this comment.
nit: "wherever callers are told apart" is a little wider than the code. With SH_REQUIRE_AUTH=false callers are told apart: Alice's owned workload is hidden from anonymous callers. Yet an anonymous caller can still name the claim behind it. docs/context-service.md already warns about this, so only the comment needs to say "from any authenticated caller".
A smaller point: the || multi term is redundant with subject !== null, because prepareServerProcess refuses multi without SH_REQUIRE_AUTH=true. The "refused under multi" test drives an anonymous caller under multi, a state production can't reach.
There was a problem hiding this comment.
Tracked in #363 for the follow-up PR, verbatim.
| * (pi-ai `env-api-keys.ts`). By shape rather than by name, so a provider pi adds later is covered | ||
| * without this list changing; `server-process.test.ts` checks it against pi's own lookup. | ||
| */ | ||
| const PROVIDER_CREDENTIAL = |
There was a problem hiding this comment.
suggestion: the shape-based scrub is perfetto for what pi reads, and the drift guard against the real env-api-keys.ts is exactly right. Two leftovers that aren't environment names pi reads:
SH_MODEL_HEADERS. It interpolates${VAR}(run-turn.ts:308), so an inline secret, or a variable named off-pattern like${LITELLM_KEY}, survives the multi scrub. That header is then sent on every caller's turn when the caller brings no credential, which is the cross-principal spend R2 forbids. It predates this round, but spec:243's new "every provider credential" says more than the code does. Undermulti, either refuse to boot with it set, or drop its interpolation.- Vertex ADC (application default credentials). Once
GOOGLE_APPLICATION_CREDENTIALSis gone, pi-ai'shasVertexAdcCredentialsfalls back to$HOME/.config/gcloud/application_default_credentials.json.GOOGLE_CLOUD_PROJECT/LOCATIONare deliberately kept, so an envelope withprovider: "google-vertex"passeshasConfiguredAuthwhenever that file exists. An env scrub can't close this. Either a §13 row, or have multi check that the file is absent. (Bedrock is fine: pi's gate checks only the scrubbedAWS_*names.)
There was a problem hiding this comment.
Tracked in #363 for the follow-up PR, verbatim.
| fi | ||
| log "migrating to the split exec listener: MOCA_RELAY_EXEC_ADDR=$new_addr in $relay," \ | ||
| "SH_RELAY_ADDR=$new_addr in $sup" | ||
| end_with_newline "$relay" |
There was a problem hiding this comment.
suggestion: deleting only this call leaves setup-vm.test.sh green. The commit's "removing the helper turns each red" holds for the helper as a whole (a no-op helper does go red in both suites), not for this call site. One fixture here with an env file lacking a final newline would pin it.
There was a problem hiding this comment.
Tracked in #363 for the follow-up PR, verbatim.
| file, keyed by the **authenticated** sandbox id — never from the sandbox's `Hello` labels, which the | ||
| sandbox chooses (§2.3). The relay writes the owner into the sandbox's record. | ||
| - **Per-sandbox tokens are required** under `multi` (`SH_RELAY_TOKEN_<id>` already exists: | ||
| `makeDefaultValidateToken`, `packages/sandbox-relay/src/main.ts:268-283`, prefers it over the global |
There was a problem hiding this comment.
suggestion: this cite went stale in this round. 8a4f66a moved makeDefaultValidateToken to main.ts:283-297 (doc comment from :275), and :268-283 is now the bindAsync tail. This is outside §2, so the base-commit disclaimer doesn't cover it. The :78-103 cite on the next line is correct.
There was a problem hiding this comment.
Tracked in #363 for the follow-up PR, verbatim.
| | --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ||
| | R1 | The sandbox receives an **explicit environment allowlist** (`LANG`, `LC_ALL`, `LC_CTYPE`, `TZ`), never the worker's process environment. It is applied in `createPodBashOps`, which both the `bash` tool and the `user_bash` hook reach — no `pi-fork` change | a planted secret-shaped variable never appears in any `Exec.command`, through the real bash tool — `packages/k8s-sandbox/test/extension.test.ts`; the allowlist prefix built by `createPodBashOps`, `test/operations.test.ts`; the allowlist itself, `test/sandbox-env.test.ts` | | ||
| | R2 | `applyModelGateway` seeds `ANTHROPIC_API_KEY` only with the constant sentinel, never a caller's token. A shared `prepareServerProcess()` runs in `startServer()`, the P6 worker and the async-run job (`leaf-job.ts`); under `multi` it deletes every provider credential pi can read from the environment (any `*_API_KEY`, `*_AUTH_TOKEN` or `*_OAUTH_TOKEN`, `HF_TOKEN`, `COPILOT_GITHUB_TOKEN`, Bedrock's `AWS_*` sources and `GOOGLE_APPLICATION_CREDENTIALS`), leaving only the sentinel, and refuses `SH_LOCAL_TOOLS=1` and `SH_REQUIRE_AUTH` other than `true`. Under `single` an operator's own ambient key is left in place | a token-less call after an authenticated one sees only the sentinel, and a caller credential on a non-Anthropic model throws — `harness/test/model-gateway.test.ts`; the multi scrub deletes the OAuth token, which outranks the sentinel, `single` keeps an operator key, and `multi` refuses both settings — `packages/knative-server/test/server-process.test.ts`; all three entry points call `prepareServerProcess` — `test/worker-boot.test.ts` | | ||
| | R3 | In server and worker mode, a turn with **no resolvable sandbox fails** rather than running tools in the worker. Local tools remain only in the CLI (`harness/src/cli.ts`), or behind an explicit `SH_LOCAL_TOOLS=1` that `multi` refuses | no sandbox → the turn fails before an agent session (and so any tool) is built — `harness/test/turn-require-sandbox.test.ts`; the guard, `assertServerSandbox`, in `test/select-sandbox.test.ts`; the solve and verdict leaves in `test/run-leaf.test.ts`; every server turn marked `serverMode`, `packages/knative-server/test/server-process.test.ts` | |
There was a problem hiding this comment.
nit: two things in the R3/R4 cells:
- "The solve and verdict leaves": there is no verdict leaf kind. This means the converge leaf's
realProduceVerdict. - Since f206676, R3 is also pinned by the prompt-leaf test (
run-leaf.test.ts:755), and the prompt leaf runsassertServerSandboxitself rather than "throughexecuteTurn". The same wording is in the amendment at:34-36and in the PR body's R3 bullet. For R4, "throughexecuteTurn" is still true.
There was a problem hiding this comment.
Tracked in #363 for the follow-up PR, verbatim.
| (`harness/src/run-turn.ts:711-765`: `SettingsManager.create`, `new DefaultResourceLoader`, | ||
| `createAgentSession`; on this branch `turnLoaderInputs`, `:629-658`, builds the settings manager and | ||
| loader options with R4's lockdown, and `executeTurn` constructs the loader and session at `:836-848`), | ||
| and the loader keeps skills in an instance field. Pi's loader also already exposes everything §7 needs |
There was a problem hiding this comment.
nit: :836-848 is inside executeTurnCore (from :780), not executeTurn (:684).
There was a problem hiding this comment.
Tracked in #363 for the follow-up PR, verbatim.
| refuses to boot without `MOCA_RELAY_EXEC_TOKEN`, which `git pull && systemctl restart | ||
| sh-relay.service` never creates. `sudo ./deploy/vm/setup-vm.sh` generates it, migrates `relay.env` | ||
| and `supervisor.env` together to the loopback exec listener, installs the sandbox network and | ||
| firewall, and restarts what it owns (step 3 below). |
There was a problem hiding this comment.
nit: "(step 3 below)": step 3 is the token migration. The restarts are step 7 and the paragraph after it.
There was a problem hiding this comment.
Tracked in #363 for the follow-up PR, verbatim.
…ossoctl#350 review round 3) The segment rule gave back names the original prefix rule caught. MOCA_TENANCIES is two edits from TENANCY, and MOCA_TENANT, MOCA_MULTI_TENANT, MOCA_MULTITENANT and SH_MULTI_TENANT are "multi-tenant" rather than "tenancy". All of them booted `single` without any error. Once a leading MOCA/KAGENTI/SH/MULTI has been seen, whether as its own segment or glued on, any segment starting TENAN is now refused. A bare TENANT (or TENANT_ID), with no leading word, is still left alone for other software. Every name above is a fixture, and removing the new term turns the suite red. The repo-wide false-positive scan still passes. Spec §10.1 states the rule and the reserved prefixes. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…#350 review round 3) Only the create path's check was pinned. Removing the GET one left all 17 tests green, although GET is the path that writes back whatever Context Service returns. A GET reply naming another workload must answer 502, create no sh:workload:<other> record, and leave the requested record untouched. Removing the check now turns this red. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…d it on every Exec (MI1 R5) e10-lifecycle.sh and e11-density.sh each generate a fresh 32-byte hex MOCA_RELAY_EXEC_TOKEN per run (SH_E10_EXEC_TOKEN / SH_E11_EXEC_TOKEN supply a reused stack's), pass it to every relay they launch, and send `authorization: Bearer` on every grpcurl SandboxExec call: E10's rung-1 Exec, E11's timed Exec and its converge. E11's Go exec-driver is launched with the token in its environment. The shell tests pin every relay launch and every grpcurl Exec call site, evaluate the generator line (64 hex characters, different each run, overridable), and the e11 seam test runs the real exec-driver both without the token (it refuses, naming MOCA_RELAY_EXEC_TOKEN) and with it. METAL-RUNBOOK.md documents the token and the reuse override. Ports this from rossoctl/moca#350's development, where it was written against deploy/microvm/. It was dropped from that PR because rossoctl/moca#344 moved these drivers (e10-lifecycle.sh, e11-density.sh, their tests, and METAL-RUNBOOK.md) out of the main repo into this repo's microvm/, so the change belongs here instead. Requires rossoctl/moca#350 to matter in practice: the relay it starts refuses to boot without MOCA_RELAY_EXEC_TOKEN and refuses every SandboxExec without it once #350 merges, and exec-driver refuses to start without it. Before #350, an older relay and exec-driver simply ignore the variable and the header, so this change is harmless to run against main today. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Mechanical rename per RA1 Phase 1 (spec §11): @sh/* -> @moca/*, the Go module path's org+repo segment, ghcr.io image names, and Serverless Harness -> MOCA in prose. Kubernetes/Knative/KEDA code is renamed in place, not removed or deprecated -- that's a separate, later, still-gated phase. Rebased onto rossoctl/main after PRs rossoctl#350 (MI1 S1 hardening) and rossoctl#364 (MU1 control plane in the compose trial) landed -- regenerated from scratch rather than replaying old commits through the ~37 files those two PRs touched, since several carry real functional changes, not just branding. Includes fixes already found and verified in the first pass through this rename (case-insensitive "serverless harness" leftovers, the mocactl layering test's escaped-regex miss, buf codegen drift, the RA1 spec's own before/after table + a new §0.9 amendment, and a handful of factual/historical-accuracy corrections: a promote.ts comment, the out-of-scope personal-notes path, and the still-unrenamed moca-experiments package name) -- applied directly this time instead of being caught by a second review round. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
The moca_sandbox table filtered only the input hook, so a sandbox could reach cloud instance metadata (169.254.169.254) through the forwarded path; on an EC2 host with IMDSv1, or IMDSv2 with hop limit >= 2, that exposes the instance role's credentials, which belong to the host and not to any session or user. Add a forward chain that drops exactly the link-local destinations arriving from the sandbox bridge -- 169.254.0.0/16 and the IPv6 metadata address fd00:ec2::254 -- and nothing else: general internet egress stays untouched until MI1 S5's moca-egress. setup-vm.test.sh's 'no forward hook' assertion becomes 'the forward hook drops only link-local metadata'. Verified live (2026-10-14) on the same Amazon Linux 2023 host as #350's run, recorded in deploy/vm/README.md: the candidate table parses and loads on nftables 1.0.4 (the fail-closed risk that kept this out of #350); with the chain loaded, the metadata endpoint that answered HTTP 401 from inside a sandbox now times out with the drop counter incrementing, while outbound internet, the relay's attach port, and the input chain's other drops are unchanged. Closes #357. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Sixteen ADRs still said Proposed although their decisions are in code on main. Each status line now names the merged PRs that implemented it and the date the core landed (format of ADR-0042), and notes what is still owed where only part is built: - 0028 (rossoctl#170, rossoctl#201, rossoctl#340; its KEDA transport removed by ADR-0041) - 0029 (rossoctl#171), 0030 (rossoctl#214), 0031 (rossoctl#214, rossoctl#225) - 0032 (rossoctl#249, rossoctl#350, as amended by MI1) - 0035 (rossoctl#251; ADR-0048 adds lease mode beside it) - 0036 (rossoctl#347), 0038 (rossoctl#458), 0039 (rossoctl#467), 0040 (rossoctl#481) - 0043 (rossoctl#560, rossoctl#588, rossoctl#600, rossoctl#615), 0044 (rossoctl#563), 0045 (rossoctl#620) - 0046 (phase 1: rossoctl#630, rossoctl#641, rossoctl#646; phase 2 owed) - 0047 (M1 and M3: rossoctl#704, rossoctl#713, rossoctl#717, rossoctl#765; M2 owed) - 0048 (rossoctl#706, rossoctl#763, rossoctl#802, rossoctl#808, rossoctl#814; off by default until the security review's lease sections are signed off) The README index follows, and its 0033 row, which still said Proposed after rossoctl#249 accepted the ADR, is corrected. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Docs and agent-facing text that the code no longer matches, found by an issue triage against main: - The microVM guest and the SBX sandbox have no network device, but reach the hosts on moca-egress's allowlist through the host's proxy (P4.1 #581-#583; SBX egress #641/#646). Concepts, guides, P4-ON-P6, the VM README, research-smoke, hardening, maturity, the demo's limits, the SBX user guide and direct-client doc said "no network" outright. So did the sandbox MCP instructions, the tool descriptions and the sbx status text agents read, which made agents refuse allowlisted calls (#779). - openapi.yaml said the worker enforces a turn's caps; nothing does yet (#391). - harness-openapi.yaml called /turn and /runs "deliberately not described", while change-policy decision 3 makes them supported aliases (#507). - The changelog is now the API changelog for both documents, with an index of the data-plane versions; both OpenAPI files point at it, and change-policy decision 5's follow-up is done (#511). - upgrades.md and change-policy: the configRef ordering only matters from before v0.5.0 or for a bundle-format change (#512, #510). - dispatch-archetypes and maturity: deploy/k8s's async drain is proven by its smoke claims (#688, #765). - Specs: slice 3's relay restart is graceful since #462 (#453); MI1 §2.2 gains a status note for the scrub (#350) and the vsock hop. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Summary
Slice S1 of MI1 (multi-user isolation on the density substrate): eight hardening requirements, R1–R8, that a worker must meet before it holds sessions of more than one user. Spec:
docs/specs/2026-09-28-moca-multi-user-isolation-design.md(§5 lists R1–R8; the amendment note under the header records what execution sharpened). This PR also adds the spec and its MI1 row in the specs registry.What each requirement now enforces:
LANG,LC_ALL,LC_CTYPE,TZ), never the worker's environment. It is applied increatePodBashOps, which both bash paths cross.applyModelGatewayseeds only a constant sentinel.prepareServerProcess()runs on every server entry point:startServer, the P6 worker and the async-run job.MOCA_TENANCY=multiit deletes every provider credential pi can read from the environment (*_API_KEY,*_AUTH_TOKEN,*_OAUTH_TOKEN,HF_TOKEN, Bedrock'sAWS_*,GOOGLE_APPLICATION_CREDENTIALS), and refusesSH_LOCAL_TOOLS=1and unauthenticated serving. No artifact in S1 setsmulti, so this part is shipped and tested but inert until S2 (spec §10.1). A near-miss variable name (SH_TENANCY,MOCA_TENENCY,MOCA_TENANCY_MODE, …; spec §10.1 states the exact rule) is a boot failure, notsingle.anthropic-messagesmodel) fails the turn instead of falling back to the shared credential./turnand to every leaf kind:converge,solveandprompt(the prompt leaf throughexecuteTurn). No local tool is registered.PI_CODING_AGENT_DIR.SandboxExecandAbortrequire a worker credential.MOCA_RELAY_EXEC_TOKEN. The relay refuses to boot without it, or when it equals any sandbox token.MOCA_RELAY_EXEC_ADDRserves Exec on its own listener. This is the default in compose anddeploy/vm.remote-workerruns commands with an explicitcmd.Envthat excludes them, while keeping the image's own environment./runsand/runs/statusfollow/turn's caller rules. Session tokens are checked, async runs return501under auth, and a caller-suppliedtenanton an authenticated request is refused./workloads(create, get, delete) authenticates the same way. Each workload records its owner, and a run inherits a workload's sandbox pool selector only when its caller owns that workload.moca-sandboxand the brain onmoca-brain, with only the relay on both.deploy/vmruns sandboxes on a strictly isolated podman network whose traffic to the host is dropped, except the relay's attach port and DNS.podman-restart, so a failed load keeps sandboxes down.Operator impact / upgrading
MOCA_RELAY_EXEC_TOKEN, and every Exec caller must present it.install.sh. A barepull && up -dwith the old compose file leaves the relay refusing to boot.deploy/vm: re-runsetup-vm.sh. It migratesrelay.envandsupervisor.envtogether to the split exec listener, fails loudly on a mismatch, and restarts the units it owns.setup-ocp.shanddeploy-incluster.shaddMOCA_RELAY_EXEC_TOKENtosh-relay-tokenonly if it is absent, so an existing exec token is never rotated. (deploy-incluster.shstill setsSH_RELAY_TOKENto itsTOKENinput on every run, as before.) The harness gets the exec key; the worker never does.404, and re-creating a live workload that another subject owns returns409.SH_REQUIRE_AUTH=trueit can no longer be read, run on or re-created, but any authenticated caller mayDELETEit, which releases its pool and frees the name. Without a token, callers keep reaching it as before.workspace.claimNameis refused (400 claim_name_not_allowed) from any authenticated caller and always underMOCA_TENANCY=multi: nothing authorizes a caller against the PVC it names. Only the anonymous caller of an unauthenticated deployment may still name one. Per-subject claim scoping is deferred (spec §4.3, §13;docs/context-service.md).deploy/vmneedsnftand a netavark that enforcesisolate=strict. Setup refuses whennftis missing or podman rejects the option. It cannot detect a netavark that stores the option without enforcing it, so use one at least as recent as the 1.17.2 verified below.deploy/vmupgrades: re-runsetup-vm.sh, as the README's new "Upgrading an existing VM" section says. A baresystemctl restart sh-relay.serviceleaves the relay without its exec token.SH_RELAY_TOKEN=(orSH_RELAY_TOKEN_<id>=) now admits no worker. Before, it admitted one presenting an empty token. The Attach comparison is now constant-time.deploy/vmsandboxes can still reach cloud instance metadata (169.254.169.254), because S1 filters only traffic to the host. On EC2, require IMDSv2 with a hop limit of 1; the README has the command.nftonPATH, rendered at setup time, rather than a hardcoded/usr/sbin/nft.rossoctl/moca-experiments: the E10/E11 drivers there (moved in refactor: split experiment/benchmark content into rossoctl/moca-experiments (RA1 Phase 2) #344) must give their relay an exec token and send it as a bearer, andexec-drivernow requiresMOCA_RELAY_EXEC_TOKEN. The patch is prepared and will be applied there separately.Test plan
make typecheckmake test: all 11 vitest packages green, no unhandled errorsgo -C remote-worker test ./...andgo vet ./...deploy/compose/tests/compose.test.sh,install.test.sh,deploy/vm/tests/setup-vm.test.sh,deploy/knative/tests/deploy-incluster.test.sh,demo-remote-worker-tokens.test.shmake linton a clean tree (prettier, shellcheck, hadolint, gitleaks)ExecInPod(R1), the real Pi loader with planted artifacts (R4), a grandchild process (R6), and split-listener Exec end to end (R5)envinside a command carries none of the worker's settings.HOME HOSTNAME LANG OLDPWD PATH PWD SHLVL _ container, and a plantedSYSTEM.md/AGENTS.md/extension did not change the system prompt.isolate=strictkeeps Redis on the default network unreachable.--restart=alwayscontainer, and mismatched env files or networks are refused.podman-restartrefuse to start.systemctl).The live run found two issues, both fixed in this PR:
0457aac). netavark leaves IPv6 on the bridge, and the first table matched IPv4 sources only. The network now has a pinned bridge name (MOCA_SANDBOX_BRIDGE), and the table matches that bridge, so everything but the established/related replies and the two IPv4 accepts is dropped.deploy/vm's default sandbox image was the Kubernetes pod image, which never attaches to the relay (b1f73e4). It now defaults to the remote-worker image compose uses.build.yamlrepublishesserverless-harness-remote-worker:lateston merge. Until then, the published image predates R6.setup-vm.shstarts the sandbox firewall unit and never restarts it: the table is loaded directly bynft -f, and a restart would propagate throughRequiredBy=topodman-restartand its containers.Known follow-up (pre-existing, minor): each
setup-vm.shrun leaves the previous Redis container's anonymous/datavolume behind (podman run --replacedoes not remove it).Follow-ups
Gaps this PR records rather than closes. Each is a row in the spec's §13 and has its own issue:
POST /workloadsconcurrent create of one new name can hand the owner to the later writerdeploy/vmsandboxes can reach cloud instance metadata (169.254.169.254); the README gives the platform mitigationclaimNamefrom authenticated callers as a stop-gap)RedisSessionBackend.list()enumerates every tenant's sessionsSH_MODEL_HEADERSunder multi, the Vertex ADC file fallback, the GET write-back race, two test pins, doc fixes)Assisted-By: Claude (Anthropic AI) [email protected]