Skip to content

feat(provisioner): per-workload sandboxes, without a PVC (phase 2, PR 2) - #588

Merged
moonlight16 merged 6 commits into
rossoctl:mainfrom
moonlight16:feat/workload-provisioner
Oct 23, 2026
Merged

moonlight16 merged 6 commits into
rossoctl:mainfrom
moonlight16:feat/workload-provisioner

Conversation

@moonlight16

Copy link
Copy Markdown
Member

Gives a workload created with sandboxes its own sandbox pods, created by a new small service, moca-provisioner. Part of #476 (per-workload sandboxes and storage). Builds on #560 (the relay trusts workload labels only from a signed token). Design: docs/specs/2026-10-16-workload-sandboxes-design.md and ADR-0043. Context still reaches the sandboxes by copy; mounting the workload's PVC (its persistent volume) is the next PR.

Off by default. Everything new lives in an opt-in Kustomize component, added only with SH_WORKLOAD_SANDBOXES=1 deploy/k8s/setup.sh. Without it, every deploy target renders byte for byte as on main, and tests check this. It needs Kubernetes 1.30+ (OpenShift 4.17+) and a separate sandbox namespace, so not ocp-single.

What it does

  • POST /workloads accepts "sandboxes": {"count": N}. On activate, the worker asks the provisioner for N sandboxes, sending its own service token and the caller's API token. The provisioner derives the owner and the workload key from that token, never from the request.
  • For each workload it creates a StatefulSet (a set of numbered pods), a headless Service and a Secret holding the signed attach token, in moca-sandbox. Pods start from an operator-editable PodTemplate, moca-workload-sandbox.
  • The workload is ready once all its sandboxes have attached. Its runs go only to its own sandboxes, and get 503 if none are up. A run without a workload stays on the shared pool.
  • Tokens are re-signed at half their lifetime, and the worker reconnects with the new one when no command is running.
  • Delete removes the sandboxes first, then the Context.

Keeping the provisioner small

  • It can't read any Secret: it writes its tokens without reading them back, and keeps their expiry on the StatefulSet.
  • A ValidatingAdmissionPolicy (a rule the Kubernetes API server enforces) lets it write only w-<hash> objects. Their pods can mount only their own token, must run as a token-less ServiceAccount, and get no host access or privileged containers.
  • Its network egress is limited to the Kubernetes API server's addresses, which setup.sh fills in; setup.sh stops if it can't find them.
  • It runs as exactly one replica, so its per-owner sandbox cap can't be raced.
  • Turning the feature off is refused while workload sandboxes exist. Delete those workloads first, or pass --delete-workload-sandboxes.

Not in this PR: the PVC mount (PR 3), the orphan cleanup sweep and the Alice/Bob demo (PR 4), and microVM sandboxes.

Tested

  • Unit and manifest tests across the packages, and setup.test.sh.
  • Kind:
    • the end-to-end flow, including the cross-user 404, the shared-pool fallback, the 503 and cleanup on delete;
    • token rotation;
    • permissions, checked with kubectl auth can-i;
    • 17 admission-policy cases that are refused or allowed;
    • refusing to turn the feature off while workloads exist.

🤖 Generated with Claude Code

@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Oct 22, 2026
moonlight16 added a commit to moonlight16/moca that referenced this pull request Oct 22, 2026
- seed budget knob, 503 when full, and the restart error on GET /workloads/{id}
- the seed port is its own listener; the attach token's second audience is stated
- only ordinal 0 seeds; the rename is the completed marker; others exit 0
- three copies for writable, and the workspace.size rule
- §4.1 points to §5.1 for the PVC permissions until rossoctl#588 merges

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Jeremy Cohn <[email protected]>
Phase 2 PR 2 (docs/specs/2026-10-16-workload-sandboxes-design.md §8).

- @moca/provisioner: PUT/GET/DELETE /internal/v1/workloads/{name}/{generation}
  with a service token and the forwarded user token; wl derived from the
  verified owner; StatefulSet, headless Service and attach-token Secret in
  moca-sandbox from the moca-workload-sandbox PodTemplate; re-mint at half
  life; per-owner cap serialized in one replica; no Secret reads
- deploy/k8s: opt-in workload-sandboxes component (SH_WORKLOAD_SANDBOXES=1):
  RBAC, API-server-only egress, ValidatingAdmissionPolicy, quota; default
  renders unchanged; disable refused while workload sandboxes exist
- workers: sandboxes on POST /workloads, provisioning status, delete order,
  workload/ownerScope on runs, 503 workload_sandbox_unavailable
- remote-worker: reconnect at the first idle moment after the token changes
- control-plane: one shared workload key derivation

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Jeremy Cohn <[email protected]>
CodeQL js/prototype-pollution-utility on the test fake's merge helper.

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.

Summary

This PR adds @moca/provisioner (per-workload StatefulSet, headless Service and attach-token Secret in moca-sandbox), the opt-in workload-sandboxes deploy component, worker-side provisioning and delete ordering, and remote-worker token-rotation reconnect. The core trust model holds up: the owner comes only from the verified API token, wl is hash-derived so a caller can't name another owner's objects, there are no Secret reads, the default render is unchanged, and internalContext is stripped at the boundary. Four must-fixes block merge: a DELETE/PUT race that leaves orphan sandboxes (which count against the owner cap, with no reconciler yet), a re-mint pass that one bad item aborts, missing OpenShift DNS for workload pods, and an admission policy that doesn't constrain Service specs.

Must-fix (also inline):

  1. DELETE isn't serialized with PUT/re-mint, so orphans are left (provisioner.ts:443 + workloads.ts:565).
  2. remintExpiring aborts the whole pass on one failing item (provisioner.ts:486).
  3. There is no openshift-dns:5353 egress for app: moca-workload-sandbox. overlays/ocp's allow-openshift-dns in moca-sandbox selects only app: moca-sandbox, so on --target ocp workload pods can't resolve the relay and never attach (network-policy.yaml:10).
  4. The admission policy checks only the name of Services, so a compromised provisioner can create w-<hex> Services with externalIPs (CVE-2020-8554), NodePort/LoadBalancer, or a selector on the shared pool (admission-policy.yaml:55).

Not inline (outside the hunks): routes.ts summaries for activate/delete are stale (activate can now return 202 provisioning, DELETE returns 202 deleting and removes the sandboxes). The /runs 409 text "has not been activated" now also covers provisioning.

Author: moonlight16 (MEMBER — maintainer)
Areas reviewed: TypeScript (provisioner, knative-server, harness, control-plane), Go (remote-worker), Helm/K8s (kustomize component, RBAC, VAP, NetworkPolicy), Shell (setup.sh), Dockerfile, Docs
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: passing (all checks green; the CodeQL prototype-pollution alert on the test fake was fixed in 4c0cb68)
Note: the base is 804dc70, and main is now at 7752522. None of the knative-server/harness/provisioner paths changed on main.

Comment thread packages/provisioner/src/provisioner.ts Outdated
* the pods still terminating. The caller repeats until none remain, and only then deletes the
* Context: Context Service refuses to delete a mounted claim (spec §6.1).
*/
export async function deleteWorkload(

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: deleteWorkload doesn't run through serialized(k.own, …), while putWorkload and the re-mint do. A DELETE can interleave with an in-flight converge (list → writeSecret → create Service → create StatefulSet). It reads sts=null, deletes nothing, sees 0 pods and returns {remaining:0}, and then converge creates the StatefulSet. The worker deletes the Context and marks the record deleted, so the orphan keeps counting toward MOCA_OWNER_MAX_SANDBOXES (the owner ends up stuck at 429). remintExpiring keeps its token fresh, and the orphan sweep only arrives in a later PR. The same race exists between the re-mint's writeSecret and DELETE, which re-creates <wl>-attach. The likely trigger is the worker's 15 s MOCA_PROVISIONER_TIMEOUT_MS giving up on a slow PUT that keeps running, followed by the client's DELETE. Fix: queue DELETE on the same per-owner queue.

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 19db220: deleteWorkload now runs through the same serialized(k.own, ...) queue as PUT and re-mint. A DELETE that arrives while a PUT is still converging (or a re-mint is writing the Secret) waits for it, then deletes what it made. Two new tests with a gated fake kube: DELETE during an in-flight PUT leaves no StatefulSet/Service/Secret and the owner cap is free again; same for a re-mint's Secret write. Both fail without the fix.

}
// Sandboxes first, and only then the Context: Context Service refuses to delete a claim a pod
// still mounts (spec §6.1). Each step tolerates "already gone", so a retry finishes the rest.
if (record.sandboxes && !(await sandboxesGone(record, userToken))) {

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 (worker side of the race above): sandboxesGone → deleteContext → deleted trusts a single remaining: 0. Once the provisioner serializes DELETE this is fine. Until then, an activate whose PUT timed out at the worker can still be converging in the provisioner. Please add a test that covers DELETE during an in-flight PUT (the provisioner unit test with a slow fake kube is enough).

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.

Added in 19db220: a worker test where the PUT times out at the worker (MOCA_PROVISIONER_TIMEOUT_MS) and the provisioner is still on it. The DELETE waits behind it, the Context is untouched until then, and it ends 204 with the PUT finished before the DELETE. remaining: 0 stays a single check, which is now safe because the provisioner serializes.

`app=${APP_LABEL},${MANAGED_BY_LABEL}=${MANAGED_BY}`,
);
let reminted = 0;
for (const s of sets) {

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: there is no per-item error handling in remintExpiring. One StatefulSet that throws aborts the whole pass for every workload listed after it, and main.ts only logs it. The throw can come from a 404 on patch after a concurrent delete, an admission/KubeError on writeSecret, or a CpError from mintAttachToken on a malformed wl/own label (the loop doesn't check gen against GENERATION_RE or wl against ATTACH_WORKLOAD_RE first, and doesn't check recordKey's shape before writing it into the Secret's annotations). In stable list order, a persistently failing entry starves the later workloads every tick until their attach tokens expire. Wrap each iteration in try/catch, log and continue, and validate labels/annotations up front.

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 19db220: each StatefulSet gets its own try/catch, so a failure is logged (object name and error only, never a token) and the pass moves on. Before minting it checks wl (ATTACH_WORKLOAD_RE), own (ATTACH_OWNER_RE), gen (GENERATION_RE), and that the record key is sh:wl:<own>:<name>. Test: two malformed items and one whose Secret write throws, all listed first; the good workload after them is still re-minted.

policyTypes: [Egress]
egress:
- to:
- namespaceSelector: { matchLabels: { kubernetes.io/metadata.name: kube-system } }

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: on OpenShift this has no effect, because DNS is openshift-dns on 5353. overlays/ocp/network-policy-ocp.yaml's allow-openshift-dns in moca-sandbox selects only app: moca-sandbox, and nothing adds 5353 for app: moca-workload-sandbox. setup.sh accepts SH_WORKLOAD_SANDBOXES=1 on --target ocp, but these pods can't resolve sandbox-relay-attach.moca.svc and never attach. Add an ocp rule for workload pods (or widen the existing selector when the component is on), and cover it in setup.test.sh.

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 19db220: new component deploy/k8s/overlays/ocp/workload-sandboxes with allow-openshift-dns-workload-sandbox (5353 to openshift-dns for app: moca-workload-sandbox). setup.sh lists it right after base/workload-sandboxes, only on --target ocp with the feature on, and the disable path removes it. Covered in setup.test.sh (ocp lists it, kind doesn't) and base-provisioner.test.ts (same egress as the shared pool's rule). Default renders are byte-identical to main for base, kind, kind-ci, ocp and ocp-single.

message: the provisioner may write only Secrets named w-<32 hex>-attach
- expression: "variables.kind != 'secrets' || request.operation == 'DELETE' || variables.secretType == 'Opaque'"
message: the provisioner may write only Opaque Secrets
- expression: "variables.kind == 'secrets' || variables.obj.metadata.name.matches('^w-[0-9a-f]{32}$')"

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 (security): for Services, the policy checks only the name. With services: create, a compromised provisioner can create w-<hex> with spec.externalIPs (CVE-2020-8554 cluster-wide MITM, not blocked by default on kind), type: NodePort/LoadBalancer, or a selector that picks the shared pool's pods. That contradicts provisioner.yaml's "nothing else anywhere". Require type == 'ClusterIP', clusterIP == 'None', no externalIPs/ports, and a selector of exactly app=moca-workload-sandbox plus this wl.

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 19db220: a Service now has to be type: ClusterIP (or unset) with clusterIP: None. No ports, externalIPs, externalName, loadBalancerIP/Class or loadBalancerSourceRanges, and the selector has to be exactly {app: moca-workload-sandbox, moca.dev/workload: <name>}. Checked on a real API server (see the kind-e2e thread): externalIPs, NodePort, LoadBalancer, ExternalName, ports, a ClusterIP with an address, the shared pool's selector, another workload's selector and a wider selector are all refused.

Comment thread harness/src/run-leaf.ts
if (err instanceof SandboxPoolSaturatedError) {
return { status: 'failed', reason: 'saturated', message: err.message };
}
// Its own reason, so the sync /runs path answers 503 workload_sandbox_unavailable rather than

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: every WorkloadSandboxUnavailableError becomes a retryable 503 workload_sandbox_unavailable + Retry-After. select-sandbox.ts:652/656 also throws it for permanent misconfiguration ("the run names no owner scope", "needs the relay sandbox pool (KAGENTI_SANDBOX_POOL_SELECTOR, SH_REMOTE_SANDBOX=1)"), so clients retry forever. Map those to error, as SandboxRequiredError is.

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 19db220: "no owner scope" and "needs the relay sandbox pool" now throw a new WorkloadSandboxMisconfiguredError. It isn't a SandboxPoolEmptyError, so run-leaf maps it to a terminal error, as it does SandboxRequiredError. Only "no live sandbox of this workload" stays workload_sandbox_unavailable + 503. Tests updated in select-sandbox-workload.test.ts, plus a run-leaf test for the error mapping.

} else if (
err instanceof ProvisionerError &&
err.code &&
(err.status === 400 || err.status === 409 || err.status === 429)

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: provisioner 400/409/429 codes pass straight through after the freeze. E.g. 400 sandboxes_count_exceeded when the provisioner's MOCA_WORKLOAD_MAX_SANDBOXES is lower than the worker's leaves the record provisioning with a count the client can't change (only DELETE gets out). The 429 has no Retry-After. Apart from the 429, none of these codes (incl. workload_object_conflict) are in docs/context-service.md.

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 19db220: the 429 pass-through carries Retry-After (30 s), 422 workload_refused passes through too, and docs/context-service.md has a table of every code the activate can pass through, with what it means and the way out. For permanent refusals (400 sandboxes_count_exceeded etc.) I kept it simple and documented it: the record stays provisioning with that error, and DELETE is the way out. Checking count against the provisioner's cap earlier would mean a new call or a shared config, which is more than this fix needs. Tested: 400 and 422 after freeze leave provisioning + error, and DELETE then frees the quota.

}
s.runOne(sl.ctx, enqueue, e)
c.reg.finish(e.GetReqId())
s.inflight.Add(-1)

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: inflight is decremented when runOne returns, but the terminal frame has only been enqueued to outbound at that point (the field comment at L100 says as much). If rotateWhenIdle cancels the stream with that frame still queued behind chunks, st.Send fails and the result is lost, which contradicts "a rotation cuts no Exec short". Decrement after the sender forwards the terminal frame, or have Idle also require an empty outbound.

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 19db220: the Session also counts frames on the outbound queue that the sender hasn't passed to Send yet (unsent). Idle needs both inflight == 0 and unsent == 0, read in that order, and runOne queues the terminal frame before inflight drops, so a queued End keeps the session busy. New test TestIdleWaitsForTheTerminalFrameToBeSent parks every Send: Idle stays false after the Exec ends until the End is actually sent. It fails without the fix.

body: { count: 2, tier: 'container', revision: REVISION },
});
expect(put!.path).toMatch(/^\/internal\/v1\/workloads\/demo\/[0-9a-f-]{36}$/);
expect(put!.user).not.toBe('undefined');

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: expect(put!.user).not.toBe('undefined') only proves the header exists, not that alice's token was forwarded, which is the property the provisioner derives the owner from. Compare to her token, and check user on the DELETE calls too. Similarly, workload-runs.test.ts:373 is titled "never persisting a result" but doesn't check that no result record was written.

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 19db220: the test now checks that the forwarded x-moca-user-token equals alice's exact token on the PUT and on every DELETE (tokens are memoized per caller). In workload-runs.test.ts the 503 case now asserts no leaf:result:* key exists for that session, and the 200 case asserts one does, so the check can't pass vacuously.

Comment thread docs/api/harness-openapi.yaml Outdated
bad_inputs,
error,
saturated,
workload_sandbox_unavailable,

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: workload_sandbox_unavailable was added to the LeafResult reason enum, but server.ts:1127-1135 always turns it into a 503 Error body and never persists it as a LeafResult.

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 19db220: removed workload_sandbox_unavailable from the LeafResult reason enum. It stays documented on the 503 response as an Error body. I also updated the 409 workload_not_ready text to cover provisioning, and the stale activate/delete summaries in routes.ts that you mentioned in the review body.

@moonlight16
moonlight16 force-pushed the feat/workload-provisioner branch from 4c0cb68 to dbaa6b8 Compare October 22, 2026 22:59
- provisioner: DELETE runs on the owner's queue with PUT and re-mint, so it
  cannot interleave and leave objects behind; a PUT that adds no replicas
  skips the owner cap; re-mint checks wl/own/gen/record key first and handles
  each StatefulSet on its own, logging and skipping a bad one
- provisioner: Kubernetes 403/422 answer 422 workload_refused, not 502
- worker: 429 pass-through carries Retry-After; 422 passes through; every
  passed-through code documented, with DELETE as the way out of a permanent
  refusal; tests for DELETE during an in-flight PUT and the forwarded token
- harness: no owner scope / no relay pool is a terminal error
  (WorkloadSandboxMisconfiguredError), not a retryable 503
- admission policy: Services must be headless, port-less, with no external
  or load-balancer fields and exactly their own selector; pod volumes are an
  allow-list (emptyDir, configMap, downwardAPI, own <wl>-attach)
- ocp: openshift-dns:5353 for workload pods (overlays/ocp/workload-sandboxes,
  listed by setup.sh only on ocp with the feature on)
- setup.sh: disable stops the provisioner before the check, one selector
  for check and delete; a kubectl failure is not reported as a missing API
- k8s-e2e: deploy/k8s/tests/workload-admission.sh runs the policy's
  positive and negative cases as server-side dry runs
- remote-worker: Idle also waits for queued frames to be sent, so a token
  rotation cannot drop a terminal frame
- openapi: workload_sandbox_unavailable is not a LeafResult reason

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

@mrsabath mrsabath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Second opinion on @ingpaolodettori-dev's review, verified against the code at 4c0cb68: all four must-fixes are real, and I found nothing that weakens them — plus two smaller things of my own. The findings are in the body rather than inline because this submission path anchors nowhere; each sits under a path:line heading.

packages/provisioner/src/provisioner.ts:443 — must-fix (confirms Paolo): DELETE is not serialized with PUT and re-mint

putWorkload runs converge under serialized(k.own, …) and remintExpiring re-reads the StatefulSet inside the owner's queue, but deleteWorkload runs outside it. The race is reachable, not theoretical: the control plane explicitly allows a repeat activation while a record is provisioning (activateWorkload → provision), so a PUT can sit in the owner queue while the DELETE handler runs concurrently. Interleaving: converge fetches the PodTemplate and writes the Secret, then pauses; deleteWorkload removes all three objects, lists pods, reports 0 remaining; the control plane (workloads.ts:565) then deletes the Context and the record; converge resumes and creates the Service and StatefulSet. The workload record is gone, so no caller will ever DELETE again — an orphaned sandbox that holds the owner's cap forever, given the orphan reconciler is explicitly a later PR. The same window inside remintExpiring re-creates a just-deleted Secret (its re-read passes, the DELETE runs between writeSecret and the annotation patch). Wrapping deleteWorkload's body in serialized(k.own, …) closes both.

packages/provisioner/src/provisioner.ts:486 — must-fix (confirms Paolo): one failing item aborts the whole re-mint pass

The loop has no per-item error handling: a writeSecret or annotation patch that throws (a 404 from a concurrent delete, a VAP refusal, an API blip) propagates out of remintExpiring and skips every remaining StatefulSet. main.ts catches the rejection so the process survives, but with the default TTL of 86400 s and re-mint at half-life, one persistently failing item starves every other owner's re-mint until their tokens expire and the relay closes their streams. Catch per item, log, continue.

deploy/k8s/base/workload-sandboxes/network-policy.yaml:10 — must-fix (confirms Paolo): no OpenShift DNS path for workload sandboxes

The repo's own pattern is that every kube-dns:53 policy gets an additive allow-openshift-dns companion (openshift-dns namespace, port 5353) in overlays/ocp/network-policy-ocp.yaml — the shared pool has one in both moca and moca-sandbox. The new allow-dns-workload-sandbox selects app: moca-workload-sandbox, which no ocp policy covers, and nothing in setup.sh's ocp path adds one — while --target ocp with SH_WORKLOAD_SANDBOXES=1 is a first-class supported combination (grant_scc grants the workload-sandbox ServiceAccount its SCC, and setup.test.sh asserts it). On ocp, workload pods cannot resolve sandbox-relay-attach.moca.svc, never attach, and activation stays provisioning forever. An allow-openshift-dns for app: moca-workload-sandbox in the ocp overlay (or the ocp rendering of this component) fixes it.

deploy/k8s/base/workload-sandboxes/admission-policy.yaml:55 — must-fix (confirms Paolo): the admission policy holds Services to their names only

The validations are thorough for Secrets (name + Opaque) and StatefulSets (labels, ServiceAccount, host namespaces, volumes, env, security context), but for Services only the ^w-[0-9a-f]{32}$ name regex applies. The Role grants create on services, so a compromised or buggy provisioner can still create a w-<hash> Service with type: LoadBalancer or NodePort, with externalIPs (the CVE-2020-8554 traffic-interception class), or with a selector over pods it does not own — the shared pool's StatefulSet moca-sandbox lives in the same namespace. Suggested constraints for kind == 'services': type ClusterIP or unset, no externalIPs/loadBalancerIP/loadBalancerSourceRanges and no nodePort in ports, selector held to app: moca-workload-sandbox, and clusterIP: 'None' as headlessService already emits. While there, spec.serviceName on StatefulSets is also unconstrained — the same kind of one-expression check if you want the set complete.

packages/provisioner/src/provisioner.ts:410 — suggestion: the re-read after a 409 StatefulSet create is not ownership-checked

In converge, when kube.create('statefulsets', …) answers 409 (reachable only through the must-fix above, since PUTs are serialized per owner and workload keys cannot collide across owners), the re-read sts = await kube.get(…) adopts whatever is under the name without the ours() check the pre-read at the top of the function performs. One line — if (sts && !ours(sts, k)) conflict('StatefulSet', k.wl) after the re-read — or it may fall out of the must-fix 1 fix for free.

packages/knative-server/src/routes.ts:156 — suggestion: stale status text

routes.ts is deliberately the documentation surface for the workload endpoints (they sit outside harness-openapi.yaml), and two summaries predate this PR's states: activate's "Freeze the uploaded revision; the workload becomes ready" — it becomes provisioning first and answers 202 until every sandbox has attached; delete's "Delete a workload and its Context" — it now deletes the workload's sandboxes first and can answer 202 while pods terminate. Likewise the /runs 409 text in docs/api/harness-openapi.yaml ("the named workload has not been activated") now also covers an activated workload still provisioning — resolveWorkloadRun answers workload_not_ready for both.


Everything else held up under a security-focused pass: the VAP's StatefulSet rules match what the Role allows, the no-Secret-reads design (blind create-or-replace, re-mint state as annotations) is consistent end to end, the owner boundary is derived from a verified token on both sides of the provisioner boundary through the one shared workload-key module, the Go token rotation is idle-gated with the inflight counter correctly drained on stream teardown, and the tests cover the serialization and cap behavior well — including "exactly one of two concurrent cap-exceeding PUTs wins". The four must-fixes are the blockers; my two additions are small.

@moonlight16

Copy link
Copy Markdown
Member Author

@ingpaolodettori-dev thanks for the thorough review. Everything is addressed in 19db220; each inline thread has a reply.

  • Must-fixes: DELETE is serialized with PUT/re-mint, the re-mint pass handles each item on its own and validates first, workload pods get openshift-dns:5353 on ocp, and the admission policy now constrains Service specs.
  • Suggestions and nits are all done. One choice to note: a permanent provisioner refusal leaves the record provisioning with its error, documented with DELETE as the way out.
  • The VAP is now evaluated by a real API server: deploy/k8s/tests/workload-admission.sh (29 server-side dry-run cases) runs in k8s-e2e after the live smoke. It passed on a fresh kind cluster.
  • Default renders are byte-identical to main for base, kind, kind-ci, ocp and ocp-single.

Could you re-review?

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

Copy link
Copy Markdown
Member Author

@mrsabath thanks for the second pass. Your review was against 4c0cb68; all four must-fixes you confirmed were already fixed in 19db220 (replies on Paolo's threads), and CI is green including a new k8s-kind-e2e step that runs the admission policy for real (29 cases).

Your two additions:

  • provisioner.ts:410, re-read after create: fixed in 7002473. The re-read is now held to the same ours() check as the pre-read, with a test where another object appears between the pre-read and the create. With DELETE serialized it should be unreachable, but it's cheap to close.
  • routes.ts:156 and the /runs 409 text: already updated in 19db220. Activate's summary now says it answers 202 while the workload's own sandboxes start, delete's says sandboxes first (202 while pods terminate) then the Context, and the 409 workload_not_ready text covers "not yet activated, or its own sandboxes are still provisioning".

@moonlight16
moonlight16 requested a review from mrsabath October 23, 2026 00:45

@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 my 4c0cb68 review. All 16 items are verified fixed in 19db220/b22077d, and 7002473 closes @mrsabath's re-read suggestion: the StatefulSet re-read after create now has the same ours() check as the pre-read, and a test covers a foreign object appearing between the pre-read and the create. Thanks for the thorough replies on every thread.

Two small, non-blocking follow-ups (fine for a later PR):

  • suggestion (deploy/k8s/base/workload-sandboxes/admission-policy.yaml): @mrsabath's "while there" note still applies. spec.serviceName on StatefulSets is unconstrained by the VAP. A one-expression rule holding it to object.metadata.name (what statefulSet() emits) would complete the set.
  • nit (packages/provisioner/src/provisioner.ts:416): the Service path has no equivalent of the new re-check. If kube.create('services', …) returns false because a foreign w-<hash> Service appeared in the same window, it's never re-read, and the StatefulSet then names it as serviceName. The VAP's headless, port-less Service shape makes this harmless in practice. A re-read plus ours() on a false create would make the two paths symmetric.

Approving: no must-fix items remain.

…Service create

- admission policy: a workload StatefulSet's serviceName must be its own name
- converge: a Service create that loses a race re-reads it under ours()
- tests: a foreign Service between pre-read and create; a foreign serviceName refused

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

Copy link
Copy Markdown
Member Author

Thanks, Paolo. I did both follow-ups here in d1c6250 rather than in a later PR:

  • spec.serviceName: the admission policy now requires a workload StatefulSet's serviceName to equal its own name, and workload-admission.sh gains a refusal case for a foreign one. I checked it on a live API server: it type-checks cleanly, refuses serviceName: sandbox-relay and admits the workload's own name.
  • Service create race: a kube.create('services', …) that returns false now re-reads the Service and holds it to ours(), the same as the StatefulSet path. A new test has a foreign Service appear between the pre-read and the create: 409 workload_object_conflict, and no StatefulSet is created.

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

Re-reviewed at d1c6250. Both follow-ups from the last round are closed:

  • admission-policy.yaml now holds a workload StatefulSet's serviceName to its own name (this also covers @mrsabath's note), and workload-admission.sh adds a deny case that k8s-kind-e2e exercises against a real API server.
  • converge re-reads a Service whose create lost a race and holds it to ours(), which matches the StatefulSet fix in 7002473. The new test covers this.

LGTM.

@mrsabath mrsabath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Re-reviewed at d1c6250, scoped to the delta since my 4c0cb68 review (b22077d, 7002473, d1c6250 — the only commits on this PR since). Both of my findings are genuinely closed, and I verified the mechanism rather than the claim:

  • packages/provisioner/src/provisioner.ts:421 — the post-create StatefulSet re-read now carries the same ours(sts, k) check as the pre-read, so a 409 can no longer adopt a foreign object. provisioner.test.ts covers a foreign object appearing between the pre-read and the create.
  • packages/provisioner/src/provisioner.ts:415 — the Service create now re-checks ownership after losing a create race. This depends on kube.create returning false rather than throwing on 409, which kube.ts:167 (return r.status !== 409) confirms.
  • deploy/k8s/base/workload-sandboxes/admission-policy.yaml:100 — serviceName == metadata.name for StatefulSets, correctly exempting DELETE (where spec is absent). The provisioner emits serviceName: k.wl on an object named k.wl, so the rule constrains an attacker without touching the happy path, and workload-admission.sh exercises the deny against a real API server in k8s-kind-e2e.

I also re-confirmed the four must-fixes from the first round at this HEAD: deleteWorkload runs through serialized(k.own, …) (provisioner.ts:465), remintExpiring isolates each item in its own try/catch, the ocp overlay adds openshift-dns 5353 for app=moca-workload-sandbox, and the Service validations now hold type, clusterIP, ports, externalIPs and selector.

One residual, not a finding: if the Service conflict() at provisioner.ts:416 throws after writeSecret has run, the Secret is left behind. It is only reachable with a foreign w-<hash> Service present — a 32-hex digest collision across owners, or an already-compromised provisioner — and the orphan reconciler is explicitly a later PR (spec §6.2). Noting it for that PR's scope rather than asking for anything here.

Areas reviewed (delta): TypeScript (provisioner), Kubernetes admission policy, deploy test scripts
Commits: 6, all signed-off: yes
CI status: all 15 checks passing
Reviewed at: d1c6250

@moonlight16
moonlight16 merged commit 8bfd971 into rossoctl:main Oct 23, 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.

5 participants