Skip to content

feat(relay): trusted workload labels from signed attach tokens - #560

Merged
moonlight16 merged 4 commits into
rossoctl:mainfrom
moonlight16:feat/relay-trusted-workload-labels
Oct 21, 2026
Merged

moonlight16 merged 4 commits into
rossoctl:mainfrom
moonlight16:feat/relay-trusted-workload-labels

Conversation

@moonlight16

Copy link
Copy Markdown
Member

First phase 2 PR (per-workload sandboxes) from the split of #455 (local agents delegating tasks to MOCA). It follows the merged spec from #553 (the phase 2 design).

Today a sandbox picks its own labels in Hello. With this PR, the relay takes the workload and owner labels only from a signed moca-attach+jwt token, so a sandbox cannot claim another user's workload.

  • control-plane: mintAttachToken and verifyAttachToken, reusing the signing helpers from feat(sbx): SBX0 1b, sandbox identity and lifecycle (sandbox profile, sandbox tokens, relay verification, mocactl sbx) #550 (SBX0 identity).
  • sandbox-relay:
    • MOCA_ATTACH_PUBLIC_KEYS holds the keys used to verify tokens.
    • The workload and owner labels come from the token. If a shared-pool sandbox sends them in Hello, they are dropped.
    • A sandbox id must be <wl>-<i> with i < n.
    • The stream is closed when the token expires (exp).
    • Exec refuses a request for the wrong workload with PERMISSION_DENIED.
  • proto: a new ExecRequest.workload field. It is additive and only the relay reads it.
  • harness: a workload run picks only a sandbox with the same workload and owner, and never falls back to the shared pool. Normal runs never land on a workload sandbox.
  • remote-worker: SANDBOX_TOKEN_FILE is re-read on every dial, so a renewed token is picked up.

Not in this PR, coming in PR 2: the provisioner that mints tokens, setting workload on runs, and mapping "no workload sandbox" to a 503.

Tested: control-plane 850, sandbox-relay 181, harness 728 and knative-server 590 tests pass. tsc is clean. In remote-worker, go test and go vet pass.

🤖 Generated with Claude Code

@moonlight16
moonlight16 requested a review from pdettori as a code owner October 20, 2026 17:26
@evaline-ju evaline-ju added the ready-for-ai-review Request automated AI code review from clawgenti label Oct 20, 2026
First phase 2 PR (spec docs/specs/2026-10-16-workload-sandboxes-design.md).

- control-plane: mintAttachToken/verifyAttachToken (moca-attach+jwt, exp required)
- sandbox-relay: MOCA_ATTACH_PUBLIC_KEYS; workload/owner labels stamped from the
  token, stripped from shared-pool Hellos; sandbox id bound to <wl>-<i>, i < n;
  stream closed at exp; Exec checks the requested workload
- proto: ExecRequest.workload (additive, read by the relay only)
- harness: selectSandbox matches workload and owner, no shared-pool fallback
- remote-worker: SANDBOX_TOKEN_FILE re-read on every dial

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Jeremy Cohn <[email protected]>
@moonlight16
moonlight16 force-pushed the feat/relay-trusted-workload-labels branch from 5ab117b to 1ad45f1 Compare October 20, 2026 19:20

@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.

Thanks for the rebase. The exec-stream.ts / sandbox-caller.ts move is threaded through cleanly, and CI is green apart from one job.

Blocking: proto fails at Verify no codegen drift. packages/sandbox-client/src/gen (ADR-0042) wasn't regenerated, so its ExecRequest lacks workload. Running buf generate and committing the result should fix it.

The remaining inline comments are non-blocking suggestions and a nit: the KeysetError mapping, a test and doc line for the sandbox-caller → workload refusal, the hard cut at exp versus the spec's idle reconnect, workload handling in the non-prompt leaves, and a worker log line.

// whose trusted moca.dev/workload label differs from it, and a non-empty value on a sandbox with
// no such label. A relay without them ignores it. Defense in depth against routing bugs, not a
// boundary: the worker that fills it in is still the trust root for routing.
string workload = 3;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix — proto fails "Verify no codegen drift": buf.gen.yaml also generates into packages/sandbox-client/src/gen (ADR-0042, added on main), and this PR committed only the k8s-sandbox and Go stubs, so sandbox-client's ExecRequest has no workload. Run buf generate and commit that directory. That also lets the skipped Go stub build/test steps run.

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 c5bb0a8: regenerated packages/sandbox-client/src/gen with buf 1.71.0, and buf lint passes. The sandbox-client Exec call now sends workload: '' so it typechecks against the new stub.

Comment thread packages/sandbox-relay/src/main.ts Outdated
let one: Map<string, KeyObject>;
try {
one = parseKeyset(entry);
} catch {

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 — parseKeyset throws a typed KeysetError (format / key / kid). You could map err.kind into this positional message, the way the SH_SANDBOX_TOKEN_PUBLIC_KEYS path does, instead of using one catch-all. It would still not echo the value.

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.

Done in c5bb0a8. The attach keyset now goes through the same keysetFromEnv as SH_SANDBOX_TOKEN_PUBLIC_KEYS, so the error gives the entry's position and what's wrong with it (format, key or kid) without echoing the value. A test covers all three.

if (deps.verifyAttach) {
const want = opts.workload ?? '';
const have = parked.workload ?? '';
if (have && want !== have) {

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 attach keys set, a SandboxExec from an SBX0 sandbox caller (sandbox-caller.ts → pumpExec with no workload) to a workload sandbox is refused with PERMISSION_DENIED. Failing safe is right, but nothing tests or documents it. A transport test and a line in security-model.md would make any later "pass workload through for sandbox callers" change a deliberate one.

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.

Yes, and it's deliberate: with attach keys set, a sandbox caller's Exec on a workload sandbox is refused with PERMISSION_DENIED. Added a transport test proving it, and a sentence in security-model.md (c5bb0a8).

() => {
handle = undefined;
if (sessions.get(sandboxId!) !== session) return;
console.error(`attach stream for ${sandboxId} closed: its attach token expired`);

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 — Closing on expiry tears down the session, so any in-flight Exec fails with worker disconnected. Spec §3.1 says the worker reconnects with the new token "at its next idle moment" once the file changes. This PR only re-reads the file on dial, so every workload sandbox is hard-cut at exp, possibly mid-Exec, and Execs can run up to 2 h. That's fine if PR 2's re-mint always lands well before exp, but please note in the PR or spec that idle-reconnect-on-change is deferred, or add it to the worker here.

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.

Agreed. Added a note in spec §3.1 (c5bb0a8): this PR re-reads the token file only when it dials, so the relay's close at exp is a hard cut. The idle reconnect is deferred to PR 2, and its re-mint must land well before exp.

Comment thread harness/src/run-leaf.ts
const promptTimings = leaseTimings(process.env);
const workload = env.internalContext?.workload;
const ownerScope = env.internalContext?.ownerScope;
// Checked before selection, unlike the rest of internalContext: they decide which sandbox to lease.

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 — workload / ownerScope are validated and honoured only in the prompt leaf. The solve and verdict leaves call selectPoolSandbox without them. If a later PR attaches a workload to one of those envelopes, it silently runs on the shared pool, which is the fallback §3.3 forbids. Fail closed in the other leaf kinds when internalContext.workload is set, or document that only prompt leaves can name a workload.

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.

Good catch. In c5bb0a8, a solve or verdict leaf whose context names a workload fails before it picks a sandbox ("a workload sandbox runs prompt leaves only") instead of quietly using the shared pool. Tests added.

Comment thread remote-worker/cmd/worker/main.go Outdated
attachCtx := metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer "+token)
stream, err := client.Attach(attachCtx)
// Re-read before every dial, so a rotated token file is picked up on the next reconnect.
// A read that fails after boot backs off and retries like a failed dial.

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 — A SANDBOX_TOKEN_FILE read failure after boot goes through the same backoff and is logged as "stream ended (SANDBOX_TOKEN_FILE: …)". A distinct log line would make a rotated-away or unmounted Secret easier to spot.

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 c5bb0a8. A token file the worker can't read now logs worker: cannot read SANDBOX_TOKEN_FILE: …; retrying in … instead of "stream ended", with the same backoff, and has a unit test.

- regenerate packages/sandbox-client/src/gen (buf 1.71.0); its Exec sends workload ''
- the attach keyset reuses keysetFromEnv, so errors name the entry and the defect
- test and document that a sandbox caller cannot reach a workload sandbox
- solve and verdict leaves refuse a workload instead of using the shared pool
- the worker logs an unreadable SANDBOX_TOKEN_FILE on its own line
- spec §3.1: the close at exp is a hard cut until PR 2 adds idle reconnect

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Jeremy Cohn <[email protected]>
@moonlight16

Copy link
Copy Markdown
Member Author

@ingpaolodettori-dev all six comments are addressed in c5bb0a8: the codegen drift is fixed (buf generate with 1.71.0, and buf lint passes), and the five suggestions are applied. CI is green. Could you take another look? Phase 2 PR 2 (the provisioner) stacks on this.

@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.

Thanks for the quick turnaround. I checked five of the six fixes against c5bb0a8 and they hold: the sandbox-client stubs were regenerated (proto is green), the attach keyset goes through keysetFromEnv, the sandbox-caller refusal is tested and documented, non-prompt leaves fail closed on a workload, and spec §3.1 has the hard-cut note.

One regression blocks: splitting tokenErr out of the worker loop leaves err nil when the token read fails, so the loop calls sess.Serve with a nil context and stream and panics instead of backing off (inline). Everything else looks good.

Comment thread remote-worker/cmd/worker/main.go Outdated
bearer, tokenErr := token()
var stream pb.SandboxWorker_AttachClient
var attachCtx context.Context
var err error

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix — This is a regression from splitting tokenErr out. err is now this fresh nil var, so when token() fails, if err == nil (line 247) is true and the loop calls sess.Serve(attachCtx, stream) with both nil. context.WithCancel(nil) in Serve panics, so an unreadable or empty SANDBOX_TOKEN_FILE after boot (the rotated-away/unmounted Secret case) now crashes the worker instead of backing off.

Suggest if tokenErr == nil && err == nil { (or err = tokenErr in an else), plus a test at the loop level: TestRetryLineNamesATokenFileFailure covers only the log string, not this control flow.

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.

Good catch, thanks. Fixed in 43461ad. One pass of the loop is now attachOnce, which returns before attach or serve when the token read fails, so the loop backs off instead of serving a nil stream. Loop-level tests cover a token failure (attach and serve never called), a failed attach, and a served session carrying the bearer; the token-failure test fails against the old control flow.

…a nil stream

Splitting the token error out of the reconnect loop left err nil when the
token read failed, so the loop served a nil context and stream and panicked.
Move one pass into attachOnce, which returns before attach or serve on a
token failure, and test it at the loop level.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Jeremy Cohn <[email protected]>

@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.

Follow-up to our review at c5bb0a8: the nil-stream panic is fixed. attachOnce returns before attach/serve on a token read failure and before serve on a failed attach, so the loop backs off instead of serving a nil context/stream. The 30s lasted-based backoff reset is preserved, and the new loop-level tests cover token failure, attach failure, and the bearer on a served session. All prior threads are resolved and CI is green. One nit inline.

Author: moonlight16 (MEMBER — maintainer)
Areas reviewed: Go (remote-worker worker loop, incremental diff c5bb0a8..43461ad)
Agent/IDE config (.claude/.vscode): none
Commits: 3, all signed-off: yes
CI status: passing

Comment thread remote-worker/cmd/worker/main.go Outdated
// Serve gets attachCtx — the very context this stream was created from,
// which is its documented precondition: recvLoop blocks in Recv() and is
// unblocked only by the stream being torn down. attachCtx derives from
// ctx, so the SIGTERM cancel above reaches it.

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: "the SIGTERM cancel above" no longer refers to anything now that this comment has moved into attachOnce. The signal handler is in main(). Maybe: "attachCtx derives from the caller's ctx, which main cancels on SIGTERM."

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 f6d358e: "attachCtx derives from the caller's ctx, which main cancels on SIGTERM." Thanks.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Jeremy Cohn <[email protected]>
@moonlight16
moonlight16 merged commit 921962e into rossoctl:main Oct 21, 2026
15 checks passed
pdettori added a commit to pdettori/moca that referenced this pull request Nov 16, 2026
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]>
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.

3 participants