Skip to content

feat(sandbox): self-hosted Kubernetes sandbox provider - #10683

Merged
waleedlatif1 merged 82 commits into
stagingfrom
waleed/k8s-sandbox-provider
Dec 3, 2026
Merged

waleedlatif1 merged 82 commits into
stagingfrom
waleed/k8s-sandbox-provider

Conversation

@waleedlatif1

@waleedlatif1 waleedlatif1 commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Adds a kubernetes sandbox provider so self-hosters get Python, shell, JS imports, file mounts and outputs, Pi, and the Mothership workbench without E2B or Daytona ([Feature Request] Replace E2B with local Docker sandbox for self-hosted deployments #4965). Opt-in with SANDBOX_PROVIDER=kubernetes; E2B, Daytona and no-provider deployments behave as before.
  • Isolation: one pod per sandbox in a dedicated namespace, under an isolating RuntimeClass: EKS Nitro isolated-sandbox, gVisor or Kata.
    • Shared-kernel runtimes (runc/crun) are refused unless explicitly allowed, plus an operator allowlist for custom isolating handlers.
    • The chart adds a ValidatingAdmissionPolicy (k8s 1.30+) that enforces the RuntimeClass and pod hardening at the API server.
    • No pods/exec RBAC and no service-account token in the sandbox. 24h hard cap. Finished and orphaned pods are swept by the existing session cleanup cron.
  • In-sandbox agent (apps/sandbox-agent, @sim/sandbox-agent-protocol): a small daemon with envd-like semantics (process start/reattach/signal, file API), injected by an initContainer so any image works.
    • Bearer token derived per pod; the pod only holds its hash.
    • Output caps and lifetime self-termination.
    • Session commands reap their descendants and are claimed and settled like E2B's.
    • File ops run in an unprivileged uid-1000 worker.
    • createAgentSandboxHandle implements SandboxHandle over it.
  • Provider seams made generic: availability flags, Pi gate, pricing, CLI recipes, Pi lifetime from the provider, and session-process receipts that record their provider. Legacy receipts still stop through E2B.
    • The shared command-run contract (timeout/provider-limit results, launch-indeterminate mapping, streamed output) is lifted out of e2b/daytona with identical behavior.
    • Intended change: Pi cloud on Daytona follows the Daytona Pi snapshot instead of E2B_ENABLED.
  • Sandbox images: Function and Pi Dockerfiles generated from the existing package lists, with content-addressed tags in images.generated.json (the agent's tag hashes its Dockerfile and shipped bundle). Built, verified, published (staging/main only), signed and attested from one sandbox.yml workflow that also runs the e2e jobs and verifies published images on every release; ci.yml is untouched and nothing new is a required check.
  • Helm: sandbox.kubernetes.*, off by default (happy path: enabled + runtimeClass.preset); the default render is identical apart from the chart version. Adds the namespace, least-privilege Role (pods, events list), sandbox NetworkPolicy with internet/restricted egress profiles (private, link-local and metadata ranges blocked), quota, LimitRange max, PSA baseline, admission policy and optional pre-pull.
  • Docs: "Kubernetes (no third party)" section with a per-cloud quick start (EKS Auto Mode, GKE, AKS, self-managed), verify-your-install and image-signature verification steps, env vars, security table, and the Trigger.dev conflict.
  • Verified live on EKS Auto Mode with Nitro isolated-sandbox: provider live suite and a Helm-installed app running Function blocks in Nitro microVMs; issues found there (Bun TLS, Auto Mode DNS, URL-mount ownership, agent base image) are fixed in this PR.

Type of Change

  • New feature

Testing

  • Behavior parity:
    • Staging's conformance suite passes against this branch.
    • Flag equivalence: old vs new env flags over 400k env combos (only the intended Pi-on-Daytona difference); setup-wizard status over 14.5k combos.
    • E2B/Daytona command strings and env validation are identical; Helm default renders are byte-identical.
  • Conformance: E2B/Daytona 199 unit cases unchanged. The Kubernetes provider runs the same 66 shared scenarios against the real agent in conformance.integration.ts.
  • Unit and integration:
    • Kubernetes provider against a faithful fake API server: watch backoff, 409 adoption, deadlines, quota, isolation guard, sessions, stop, reaper.
    • Agent daemon (also run as root on Linux), agent handle integration suite, env-capabilities, sim-setup, sandbox-recovery.
    • Helm unittest (194).
    • Security and correctness guards each proven by reverting them and watching the test go red.
  • CI e2e (sandbox.yml, k3s + gVisor):
    • A live suite through the real app paths, covering parity, timeouts, caps, mounts and outputs, runtime deps, sessions, Pi, latency and cleanup.
    • Security checks: uid, token and env isolation; no API, metadata or app reach; runc/missing-class refusal; Trigger refusal.
    • A full-stack job that builds the app image, installs the chart with the admission policy, and runs Python/JS/file-output Function blocks through the v2 API.
  • Local: biome, targeted vitest, workspace tsc, and the sandbox-dockerfiles/generators/boundaries/client-boundary/file-names/comment-hygiene/test-patterns/utils/explicit-any/organization-egress audits.

Checklist

  • Code follows project style guidelines
  • Self-reviewed my changes
  • Tests added/updated and passing (new tests pass the test-audit authoring gate)
  • No new warnings introduced
  • I confirm that I have read and agree to the terms outlined in the Contributor License Agreement (CLA)

@waleedlatif1
waleedlatif1 requested a review from a team as a code owner December 2, 2026 22:49
@vercel

vercel Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated
docs Ignored Ignored Preview Dec 3, 2026 8:30am UTC

Request Review

@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@greptile

@greptile-apps

greptile-apps Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5RetriggerView in Greptile

[High impact] The PR adds a new route for user-authored sandbox work to run on self-hosted Kubernetes clusters.

Fix the session deadline overwrite and the repository-rule violations before merging.

Findings

  1. P1 Live workbenches get deleted ▶
  2. P2 Unit tests require live sockets ▶
  3. P2 Comments use forbidden separators ▶

Summary

Adds an opt-in Kubernetes sandbox provider, an in-pod agent, release images, and Helm isolation controls.

  • Kubernetes runs sandbox commands and files through a pod-side agent.
  • Helm can provision guarded Kubernetes sandboxes when enabled.
  • Sandbox settings and run records now account for Kubernetes.
  • Sandbox images get generated, content-addressed tags and a publish workflow.
  • Self-hosting guides now explain Kubernetes sandboxes and their settings.

The previous-review ancestry checks did not pass, so this assessment covers the full PR. Verification was by source inspection; no tests were run.

Diagram

sequenceDiagram
  participant App
  participant Kubernetes
  participant Agent
  participant Cleanup
  App->>Kubernetes: Create isolated sandbox pod
  Kubernetes->>Agent: Start with token hash and deadline
  App->>Agent: Run commands and transfer files
  App->>Kubernetes: Save extended deadline
  App->>Agent: Extend lifetime
  Cleanup->>Kubernetes: Read saved deadline
  Cleanup->>Kubernetes: Delete finished or expired pods
Loading

Reviews (2) · Last reviewed commit: "ci(sandbox): install gVisor's helper bin..." · Reviewed by Greptile

Comment thread .github/workflows/sandbox-images.yml Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All reported issues were addressed across 140 files

This PR changes infrastructure or deployment configuration. Ultrareviews find 2.4x more serious bugs than standard reviews. Comment @cubic-dev-ai ultrareview to run one.

Turn on auto-fix | Re-trigger cubic

Comment thread apps/sandbox-agent/src/ipc.ts Resolved
Comment thread apps/sandbox-agent/src/ipc.ts Resolved
Comment thread apps/sandbox-agent/src/main.ts Resolved
Comment thread docker/sandbox-agent.Dockerfile Resolved
@waleedlatif1
waleedlatif1 force-pushed the waleed/k8s-sandbox-provider branch from 1c10cea to 2068378 Compare December 2, 2026 23:29
@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@greptile

@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@cubic-dev-ai review this PR

@cubic-dev-ai

cubic-dev-ai Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

@cubic-dev-ai review this PR

@waleedlatif1 I have started the AI code review. It will take a few minutes to complete.

Comment thread docker/sandbox-agent.Dockerfile Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All reported issues were addressed across 142 files

Reply with feedback, questions, or to request a fix.

Turn on auto-fix | Re-trigger cubic

Comment thread apps/sandbox-agent/src/accounts.ts Resolved
Comment thread apps/sandbox-agent/src/descendants.ts Resolved
Comment thread helm/sim/values.schema.json Resolved
Comment thread .github/workflows/sandbox-images.yml Resolved
Comment thread apps/sandbox-agent/src/file-worker.ts Resolved
@waleedlatif1
waleedlatif1 force-pushed the waleed/k8s-sandbox-provider branch from 2068378 to ff29fc6 Compare December 3, 2026 00:49
@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@greptile

@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@cubic-dev-ai review this PR

@cubic-dev-ai

cubic-dev-ai Bot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

@cubic-dev-ai review this PR

@waleedlatif1 I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

4 issues found across 146 files

Confidence score: 3/5

  • In sandbox-kubernetes.yaml, numeric-only namespace and RuntimeClass names can render as numbers where Kubernetes requires strings, causing the generated resources to be invalid. Quote these values in the templates.
  • In values.yaml, an existing custom RuntimeClass with a non-built-in handler fails isolation because the chart only sets SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS when it creates the RuntimeClass. Pass the configured handler even when runtimeClass.create is false.
  • In sandbox-images.yml, changes to bun.lock or workspace manifests can change sandbox-agent without triggering an image rebuild, leaving the old signed image in use. Add those dependency inputs to the path filter.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="helm/sim/templates/sandbox-kubernetes.yaml">

<violation number="1" location="helm/sim/templates/sandbox-kubernetes.yaml:72">
P2: Quote `.Release.Namespace` in the RoleBinding subjects and the NetworkPolicy `matchLabels` value; otherwise installs in a numeric-only release namespace render invalid string fields.</violation>

<violation number="2" location="helm/sim/templates/sandbox-kubernetes.yaml:108">
P2: Quote `$runtimeClassName` when creating the RuntimeClass so schema-valid numeric-only names produce a valid Kubernetes string field.</violation>
</file>

<file name="helm/sim/values.yaml">

<violation number="1" location="helm/sim/values.yaml:1242">
P2: An existing `custom` RuntimeClass with a non-built-in handler always fails isolation because the chart emits `SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS` only when `runtimeClass.create` is true. Pass the configured handler for existing classes or add a separate trusted-handler value.</violation>
</file>

<file name=".github/workflows/sandbox-images.yml">

<violation number="1" location=".github/workflows/sandbox-images.yml:27">
P2: This path filter misses agent dependency inputs: changes to `bun.lock` or workspace manifests can alter `sandbox-agent` without changing `images.generated.json`, so pushes keep serving the old signed image. Include every install input in the content hash or trigger this workflow for those files.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Turn on auto-fix | Re-trigger cubic

Comment thread helm/sim/values.schema.json Resolved
Comment thread apps/sandbox-agent/src/file-worker.ts Resolved
Comment thread helm/sim/values.yaml Resolved
Comment thread .github/workflows/sandbox-images.yml Resolved
@waleedlatif1
waleedlatif1 force-pushed the waleed/k8s-sandbox-provider branch from ff29fc6 to 9e0b54f Compare December 3, 2026 01:48
@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@greptile

@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@cubic-dev-ai review this PR

@cubic-dev-ai

cubic-dev-ai Bot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

@cubic-dev-ai review this PR

@waleedlatif1 I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All reported issues were addressed across 147 files

Reply with feedback, questions, or to request a fix.

Turn on auto-fix | Re-trigger cubic

Comment thread helm/sim/templates/_helpers.tpl Resolved
Comment thread helm/sim/templates/_helpers.tpl Resolved
Comment thread apps/sandbox-agent/src/file-worker.ts Resolved
@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@greptile

@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@cubic-dev-ai review this PR

@cubic-dev-ai

cubic-dev-ai Bot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

@cubic-dev-ai review this PR

@waleedlatif1 I have started the AI code review. It will take a few minutes to complete.

@waleedlatif1
waleedlatif1 force-pushed the waleed/k8s-sandbox-provider branch from 9e0b54f to ef2af31 Compare December 3, 2026 02:34
…igns

startProxy and the bad-gateway server asked freePort for a port, closed it,
then listened on it again, leaving a window for another process to take it.
They now listen on port 0 and read the assigned port back. freePort is left
private to startTestAgent, which must name the agent's port up front.
- event-stream: require the proxy to have seen a read, so renaming the
  events field cannot leave highestRead at -1 and pass vacuously (proved by
  pointing the proxy at another property).
- function-sandbox-packages: drop the two assertions that restated the
  pinned Python and Node version literals and match any Python version in the
  digest-pinned base image reference; the parity script already checks the
  versions against the manifest.
- kubernetes live suite: import createRouteContext from its helper file
  rather than the @sim/testing barrel.
…tier

The Kubernetes leg starts a real sim-sandbox-agent per pod and drives it over
loopback HTTP with real timers, which the unit tier rules out and which the
unit job runs under the most contention (8 vCPUs shared by about 7 workers,
with child_process wrapped for test selection). Its precedent, the agent
handle suite, is an integration file.

The scenario table moves to conformance.test-helpers.ts (the
workspace-source.test-helpers.ts pattern), registered per provider:
conformance.test.ts runs it on E2B and Daytona with their SDK-only tests,
and conformance.integration.ts runs it on Kubernetes with the stand-in
cluster. All 271 test names and outcomes are unchanged: 199 E2B, Daytona and
shared tests in the unit file, and the 66 Kubernetes scenarios plus 6
skipped SDK-only ones in the integration file. The Kubernetes e2e workflow's
path filter excludes all three conformance files, as it excluded the one.
The teardown froze the agent, then awaited a timer between sweeps, which let
test code (such as a request body still uploading) run against a frozen agent
whose socket stays open. The sweep is now synchronous from SIGSTOP to the
agent's SIGKILL, each ps call pacing the next pass.
- Raise a pod's expires-at only monotonically, conditioned on the read
  resourceVersion, so a handle with an older deadline cannot shorten one
  another handle on the same session pod recorded.
- Verify RuntimeClass isolation before reusing a session pod, and let each
  caller of the shared isolation check abort only its own wait.
- Run the provider suite in the integration tier: it drives real loopback
  HTTP servers and real timers.
- Report non-UTF-8 NDJSON lines as NdjsonDecodeError.
- Let an output callback's error fail the command (stopping it) instead of
  reading as a dropped stream.
- Close a file read's descriptor when a read fails, and finish partial
  writes before committing an upload.
- Tighten the sandbox chart schema (positive quantities, string node
  selector values, toleration fields, RuntimeClass name) and quote the
  sandbox namespace name wherever it renders.
- Fail the live-suite preflight when the identity can exec into sandboxes,
  and fail the image workflow when the PR file listing cannot be read.
…tories

A one-shot Kubernetes shell run fetches URL mounts with a root shell whose
`mkdir -p` leaves /tmp/sim/inputs root-owned 0755, so a later inline mount
into the same directory, written by the agent's uid-1000 file worker,
failed with EACCES. E2B's envd (root) creates missing parents owned by the
target user, and Daytona runs everything as root, so neither hits it.

The agent now reads SIM_SANDBOX_AGENT_USER_DIRS (comma-separated absolute
paths, scrubbed from children with the other SIM_SANDBOX_* variables). As
root, before serving, it creates each missing directory and missing parent
and chowns only what it created to the sandbox user; existing directories
keep their owner. Invalid entries fail startup. The Kubernetes pod sets it
to the mount input and output directories. Shared mount code is unchanged.
- Pull the release's default sandbox images through global.imageRegistry:
  the chart passes it as SANDBOX_K8S_IMAGE_REGISTRY and the provider moves
  the published agent, Function, and Pi refs to it; set images stay as given.
- Refuse runtimeClass.create when the chart has no RuntimeClass name.
- Reject a file worker `end` frame for a call with no answered read stream,
  so a malformed reply restarts the worker and rejects the call.
- Make the fake Kubernetes API require the kubeconfig's bearer token.
- Run the Kubernetes sandbox e2e for the migrations Dockerfile, the image
  build action, and the CI Helm defaults.
…inal audit

- Admission policy enforces the sandbox pod shape without Pod Security:
  emptyDir-only volumes, no sysctls, no privilege escalation, only the six
  agent capabilities, no hostPort, Default procMount, no Unconfined seccomp
- Refuse namespace.create=false with the admission policy off
- restricted egress defaults DNS to the kube-dns pods; internet keeps port 53
- Block Azure WireServer and the NAT64 prefixes in the internet profile
- Merge sandbox-images and sandbox-kubernetes-e2e into one sandbox workflow:
  images built once per PR and reused by both e2e jobs, publishing only from
  main and staging, signer identity pinned to those refs, release and daily
  verification, a separate app image cache key, wider path filters
- OCI source labels on the sandbox images; regenerate their tags
- Docs: per-cloud quick start, install verification, image verification and
  air-gapped tags, network policy limits, podPidsLimit
@waleedlatif1
waleedlatif1 force-pushed the waleed/k8s-sandbox-provider branch from c90d803 to 05c036c Compare December 3, 2026 07:46
@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@greptile

@waleedlatif1

Copy link
Copy Markdown
Collaborator Author

@cubic-dev-ai review this PR

@cubic-dev-ai

cubic-dev-ai Bot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

@cubic-dev-ai review this PR

@waleedlatif1 I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All reported issues were addressed across 151 files

You've manually re-run cubic several times on this PR. Each manual re-review checks the full PR again and counts toward your usage quota. To preserve your usage limits, we recommend letting cubic automatically review new commits.

Turn on auto-fix | Re-trigger cubic

Comment thread .github/workflows/sandbox.yml Resolved
- sandbox.yml: pull-request and dry-run builds run in a read-only image job;
  registry-write and signing permissions live only in image-publish, gated to
  push or dispatch on main/staging. Build and verify share a composite action.
- Validate SANDBOX_K8S_NAMESPACE as a DNS-1123 label in the capability
  definition, the setup wizard, and the provider settings.
- Bound the session reconnect's lifetime read by the lookup deadline.
- Reject an absent, blank, or non-decimal X-Sim-File-Size header.
- Bound reading an error body on streaming agent requests.
- Admission policy requires every container to drop ALL capabilities.
- Quote the chart-created RuntimeClass handler.
@waleedlatif1
waleedlatif1 merged commit 0f6b0d4 into staging Dec 3, 2026
112 checks passed
@waleedlatif1
waleedlatif1 deleted the waleed/k8s-sandbox-provider branch December 3, 2026 14:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants