Skip to content

Commit ef2af31

Browse files
committed
fix(sandbox): address fourth review round
- 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.
1 parent 5e7dafe commit ef2af31

16 files changed

Lines changed: 258 additions & 18 deletions

File tree

‎.github/workflows/sandbox-kubernetes-e2e.yml‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@ name: sandbox-kubernetes-e2e
2222
#
2323
# `changes` narrows each job: the suite runs for anything the provider's code paths
2424
# touch, the app image builds and the app job only for the provider, its agent, the
25-
# chart objects it installs, and the app image's inputs. Neither runs for an E2B- or Daytona-only
26-
# change; the exclusions below and in `changes` are the same list. Each job uploads
27-
# a JSON report.
25+
# chart objects it installs, and the app and migrations images' inputs. Neither runs
26+
# for an E2B- or Daytona-only change; the exclusions below and in `changes` are the
27+
# same list. Each job uploads a JSON report.
2828

2929
on:
3030
pull_request:
@@ -55,11 +55,14 @@ on:
5555
- 'helm/sim/templates/_helpers.tpl'
5656
- 'helm/sim/values.yaml'
5757
- 'helm/sim/values.schema.json'
58+
- 'helm/sim/ci/default-values.yaml'
5859
- '.github/sandbox-kubernetes-e2e/**'
60+
- '.github/actions/image/**'
5961
- '.github/actions/k3s-*/**'
6062
- '.github/workflows/sandbox-kubernetes-e2e.yml'
61-
# The app image's inputs, for the app job alone.
63+
# The app and migrations images' inputs, for the app job alone.
6264
- 'docker/app.Dockerfile'
65+
- 'docker/db.Dockerfile'
6366
- 'bun.lock'
6467
- 'apps/sim/package.json'
6568
workflow_dispatch: {}
@@ -122,7 +125,9 @@ jobs:
122125
- 'helm/sim/templates/_helpers.tpl'
123126
- 'helm/sim/values.yaml'
124127
- 'helm/sim/values.schema.json'
128+
- 'helm/sim/ci/default-values.yaml'
125129
- '.github/sandbox-kubernetes-e2e/**'
130+
- '.github/actions/image/**'
126131
- '.github/actions/k3s-*/**'
127132
- '.github/workflows/sandbox-kubernetes-e2e.yml'
128133
app:
@@ -135,10 +140,13 @@ jobs:
135140
- 'helm/sim/templates/sandbox-admission-policy.yaml'
136141
- 'helm/sim/templates/networkpolicy.yaml'
137142
- 'helm/sim/templates/_helpers.tpl'
143+
- 'helm/sim/ci/default-values.yaml'
138144
- '.github/sandbox-kubernetes-e2e/**'
145+
- '.github/actions/image/**'
139146
- '.github/actions/k3s-*/**'
140147
- '.github/workflows/sandbox-kubernetes-e2e.yml'
141148
- 'docker/app.Dockerfile'
149+
- 'docker/db.Dockerfile'
142150
- 'bun.lock'
143151
- 'apps/sim/package.json'
144152

‎apps/docs/content/docs/platform/self-hosting/environment-variables.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ Who may sign up and sign in — the allowlists, blocklists, `REGISTRATION_MODE`,
193193
| `SANDBOX_K8S_ALLOW_UNISOLATED` | `true` runs sandboxes on the node's shared kernel. Only for fully trusted workflow authors |
194194
| `SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS` | Comma-separated RuntimeClass handlers to accept as isolating, for a VM or user-space-kernel runtime Sim does not recognise. The Helm chart sets it to `sandbox.kubernetes.runtimeClass.handler`, or to the handler of a RuntimeClass it creates |
195195
| `SANDBOX_K8S_AGENT_IMAGE` / `SANDBOX_K8S_FUNCTION_IMAGE` / `SANDBOX_K8S_PI_IMAGE` | Override the images published with the release (agent init container, Function and Shell, Pi) |
196+
| `SANDBOX_K8S_IMAGE_REGISTRY` | Registry, with an optional port and path, to pull the release's agent, Function, and Pi images from instead of `ghcr.io`, under their published paths (`<registry>/simstudioai/sandbox-agent:<tag>`). An image set by its own variable is used as given. The Helm chart sets it to `global.imageRegistry` |
196197
| `SANDBOX_K8S_MOTHERSHIP_IMAGE` / `SANDBOX_K8S_DOC_IMAGE` | Private images for chat code tools and document generation. No default; those kinds fail closed until set |
197198
| `SANDBOX_K8S_IMAGE_PULL_SECRET` | docker-registry Secret in the sandbox namespace for private images |
198199
| `SANDBOX_K8S_CPU` / `SANDBOX_K8S_MEMORY` / `SANDBOX_K8S_EPHEMERAL_STORAGE` | Per-sandbox limits (default `1` / `2Gi` / `4Gi`); requests are half |

‎apps/docs/content/docs/platform/self-hosting/sandboxes.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ Narrowing the resolvers stops direct DNS to outside servers, not DNS tunneling t
254254

255255
### Images
256256

257-
Leave `sandbox.kubernetes.images.*` empty to use the images built for your Sim release. Set a `tag` or `digest` to mirror or pin one; `global.imageRegistry` rewrites these repositories as it does the app images, so an air-gapped install mirrors them along with the rest. Each image also takes its own `registry`, as the app images do.
257+
Leave `sandbox.kubernetes.images.*` empty to use the images built for your Sim release. `global.imageRegistry` applies to them as it does to the app images, so an air-gapped install mirrors them along with the rest under their published paths (`<registry>/simstudioai/sandbox-agent:<tag>`); the chart passes it to the app as `SANDBOX_K8S_IMAGE_REGISTRY`. Set a `tag` or `digest` to pin an image; an image's own `registry` and `repository` apply once it has one, as for the app images.
258258

259259
| Kind | Values key | Variable | Default |
260260
|---|---|---|---|
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
2+
import { tmpdir } from 'node:os'
3+
import path from 'node:path'
4+
import { afterAll, describe, expect, it, vi } from 'vitest'
5+
import { FileWorker } from '@/file-worker'
6+
import { FileOperationError } from '@/files'
7+
8+
/**
9+
* A stand-in worker that answers every call with the frames `FAKE_REPLY` names, so the daemon
10+
* can be fed a reply the real worker never sends. Plain JavaScript, framed as `ipc.ts` frames
11+
* (u32 length, u8 kind, u32 id), so it runs under whichever runtime executes the suite.
12+
*/
13+
const FAKE_WORKER = `
14+
const REPLIES = {
15+
end: [[4, null]],
16+
'result-then-end': [[1, '{"size":0}'], [4, null]],
17+
}
18+
const frame = (kind, id, text) => {
19+
const payload = Buffer.from(text ?? '')
20+
const header = Buffer.alloc(9)
21+
header.writeUInt32BE(payload.length, 0)
22+
header.writeUInt8(kind, 4)
23+
header.writeUInt32BE(id, 5)
24+
return Buffer.concat([header, payload])
25+
}
26+
let buffered = Buffer.alloc(0)
27+
process.stdin.on('data', (chunk) => {
28+
buffered = Buffer.concat([buffered, chunk])
29+
while (buffered.length >= 9 && buffered.length >= 9 + buffered.readUInt32BE(0)) {
30+
const kind = buffered.readUInt8(4)
31+
const id = buffered.readUInt32BE(5)
32+
buffered = buffered.subarray(9 + buffered.readUInt32BE(0))
33+
if (kind !== 0) continue
34+
for (const [replyKind, text] of REPLIES[process.env.FAKE_REPLY]) {
35+
process.stdout.write(frame(replyKind, id, text))
36+
}
37+
}
38+
})
39+
`
40+
41+
const directory = mkdtempSync(path.join(tmpdir(), 'sim-file-worker-'))
42+
const fakeWorker = path.join(directory, 'worker.cjs')
43+
writeFileSync(fakeWorker, FAKE_WORKER)
44+
45+
vi.mock('@/self', () => ({
46+
AGENT_MODES: { fileWorker: 'file-worker' },
47+
selfCommand: () => ({ file: process.execPath, args: [fakeWorker] }),
48+
}))
49+
50+
afterAll(() => {
51+
rmSync(directory, { recursive: true, force: true })
52+
})
53+
54+
function workerReplying(reply: 'end' | 'result-then-end'): FileWorker {
55+
return new FileWorker({ name: 'user', home: directory }, { FAKE_REPLY: reply })
56+
}
57+
58+
describe('file worker replies', () => {
59+
it('rejects a call the worker ends without ever settling it', { timeout: 5_000 }, async () => {
60+
const error = await workerReplying('end')
61+
.stat('notes.txt')
62+
.catch((caught: unknown) => caught)
63+
expect(error).toBeInstanceOf(FileOperationError)
64+
})
65+
66+
it('rejects a read whose stream ends before its result arrives', { timeout: 5_000 }, async () => {
67+
const error = await workerReplying('end')
68+
.read('notes.txt', undefined)
69+
.catch((caught: unknown) => caught)
70+
expect(error).toBeInstanceOf(FileOperationError)
71+
})
72+
73+
it('accepts the stream terminator once the read result has arrived', async () => {
74+
const { size, body } = await workerReplying('result-then-end').read('notes.txt', undefined)
75+
expect(size).toBe(0)
76+
expect(await new Response(body).arrayBuffer()).toEqual(new ArrayBuffer(0))
77+
})
78+
})

‎apps/sandbox-agent/src/file-worker.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -174,8 +174,10 @@ export async function runFileWorker(): Promise<void> {
174174
interface PendingCall {
175175
resolve: (value: unknown) => void
176176
reject: (error: Error) => void
177-
/** Present on a read once the worker has answered; fed by its `data` frames. */
177+
/** Present on a read; fed by its `data` frames and closed by its `end`. */
178178
download?: InboundStream
179+
/** Set once a read's result has arrived; only then may its stream end. */
180+
answered?: boolean
179181
/** Present on a write; gates the upload's `data` frames. */
180182
upload?: CreditGate
181183
}
@@ -336,7 +338,8 @@ export class FileWorker {
336338
// Decoded before the call is unregistered: a malformed reply restarts the worker, whose
337339
// exit must still find this call to reject it.
338340
const value = decodeJson(frame.payload)
339-
if (!pending.download) this.pending.delete(frame.id)
341+
if (pending.download) pending.answered = true
342+
else this.pending.delete(frame.id)
340343
pending.resolve(value)
341344
return
342345
}
@@ -361,8 +364,13 @@ export class FileWorker {
361364
}
362365
return
363366
case FRAME_KIND.end:
367+
// Only an answered read has a stream to end. Thrown, not dropped: the worker restart
368+
// that follows rejects the call, which would otherwise never settle.
369+
if (!pending.download || !pending.answered) {
370+
throw new Error('File worker ended a stream it had not opened')
371+
}
364372
this.pending.delete(frame.id)
365-
pending.download?.end()
373+
pending.download.end()
366374
return
367375
case FRAME_KIND.credit:
368376
pending.upload?.grant(decodeCredit(frame.payload))

‎apps/sim/.env.example‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ NEXT_PUBLIC_APP_URL=http://localhost:3000
7171
# SANDBOX_K8S_ALLOW_UNISOLATED= # "true" runs user code on the shared node kernel; trusted authors only
7272
# SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS= # Comma-separated handlers of VM runtimes Sim does not recognise
7373
# SANDBOX_K8S_FUNCTION_IMAGE= # Optional overrides; agent, function, and pi default to the release's images
74+
# SANDBOX_K8S_IMAGE_REGISTRY= # Mirror those defaults are pulled from instead of ghcr.io, e.g. registry.example.com/sim
7475
# SANDBOX_K8S_MOTHERSHIP_IMAGE= # Private chat code-tool image, no default
7576
# SANDBOX_K8S_DOC_IMAGE= # Private document-generation image, no default
7677
# SANDBOX_K8S_IMAGE_PULL_SECRET= # Pull Secret in the sandbox namespace for private images

‎apps/sim/lib/core/config/env.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -666,6 +666,7 @@ export const env = createEnv({
666666
SANDBOX_K8S_AGENT_IMAGE: z.string().optional(), // sim-sandbox-agent carrier image (defaults to this release's published ref)
667667
SANDBOX_K8S_FUNCTION_IMAGE: z.string().optional(), // Function code/shell image (defaults to this release's published ref)
668668
SANDBOX_K8S_PI_IMAGE: z.string().optional(), // Pi image (defaults to this release's published ref)
669+
SANDBOX_K8S_IMAGE_REGISTRY: z.string().optional(), // Registry (host[:port][/path]) the default agent, Function, and Pi refs are pulled from instead of ghcr.io
669670
SANDBOX_K8S_MOTHERSHIP_IMAGE: z.string().optional(), // Mothership shell image; no default, the kind stays off until set
670671
SANDBOX_K8S_DOC_IMAGE: z.string().optional(), // Mothership document image; no default, the kind stays off until set
671672
SANDBOX_K8S_CPU: z.string().optional(), // CPU limit per sandbox pod (default 1); the request is half
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"function": "ghcr.io/simstudioai/sandbox-function:6d7f249fa417b147",
33
"pi": "ghcr.io/simstudioai/sandbox-pi:01cb06a1b2c01cad",
4-
"agent": "ghcr.io/simstudioai/sandbox-agent:543fcb04c51f08a5"
4+
"agent": "ghcr.io/simstudioai/sandbox-agent:b55313f9b9e0274e"
55
}

‎apps/sim/lib/execution/remote-sandbox/kubernetes/pod.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,38 @@ describe('Kubernetes sandbox settings', () => {
223223
expect(imageFor('code', resolved, 'user/image:1')).toBe('user/image:1')
224224
})
225225

226+
it("pulls the release's default images from SANDBOX_K8S_IMAGE_REGISTRY, leaving set images alone", () => {
227+
const { images } = readKubernetesSandboxSettings({
228+
INTERNAL_API_SECRET: SECRET,
229+
SANDBOX_K8S_RUNTIME_CLASS: 'gvisor',
230+
SANDBOX_K8S_IMAGE_REGISTRY: 'mirror.example.com:5000/sim/',
231+
SANDBOX_K8S_FUNCTION_IMAGE: 'ghcr.io/acme/function:1',
232+
})
233+
expect(images.agent).toMatch(
234+
/^mirror\.example\.com:5000\/sim\/simstudioai\/sandbox-agent:[0-9a-f]{16}$/
235+
)
236+
expect(images.pi).toMatch(
237+
/^mirror\.example\.com:5000\/sim\/simstudioai\/sandbox-pi:[0-9a-f]{16}$/
238+
)
239+
expect(images.function).toBe('ghcr.io/acme/function:1')
240+
})
241+
242+
it('rejects a SANDBOX_K8S_IMAGE_REGISTRY that is not a registry path', () => {
243+
for (const registry of [
244+
'https://mirror.example.com',
245+
'mirror example',
246+
'mirror.example.com/sim:1',
247+
]) {
248+
expect(() =>
249+
readKubernetesSandboxSettings({
250+
INTERNAL_API_SECRET: SECRET,
251+
SANDBOX_K8S_RUNTIME_CLASS: 'gvisor',
252+
SANDBOX_K8S_IMAGE_REGISTRY: registry,
253+
})
254+
).toThrow(/SANDBOX_K8S_IMAGE_REGISTRY/)
255+
}
256+
})
257+
226258
it('rejects a malformed resource quantity or node selector by name', () => {
227259
expect(() =>
228260
readKubernetesSandboxSettings({

‎apps/sim/lib/execution/remote-sandbox/kubernetes/provider.integration.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,8 @@ class FakeKubernetes {
138138
runtimeClassReadDelayMs = 0
139139
/** When set, every pod patch is refused as forbidden. */
140140
refusePatches = false
141+
/** The bearer token every request must carry; the fixture kubeconfig holds it. */
142+
readonly token = 'service-account-token'
141143
/** When set, every request is refused as unauthenticated, as for a revoked token. */
142144
rejectCredentials = false
143145
private hung: ServerResponse[] = []
@@ -194,14 +196,14 @@ class FakeKubernetes {
194196
this.onList = () => {}
195197
}
196198

197-
kubeconfig(): string {
199+
kubeconfig(token = this.token): string {
198200
return [
199201
'apiVersion: v1',
200202
'kind: Config',
201203
'clusters:',
202204
`- name: fake\n cluster:\n server: http://127.0.0.1:${this.port}\n insecure-skip-tls-verify: true`,
203205
'users:',
204-
'- name: sim\n user:\n token: service-account-token',
206+
`- name: sim\n user:\n token: ${token}`,
205207
'contexts:',
206208
'- name: fake\n context:\n cluster: fake\n user: sim',
207209
'current-context: fake',
@@ -265,7 +267,9 @@ class FakeKubernetes {
265267
const json = (code: number, body: unknown) => {
266268
response.writeHead(code, { 'Content-Type': 'application/json' }).end(JSON.stringify(body))
267269
}
268-
if (this.rejectCredentials) return json(401, statusBody(401, 'Unauthorized', 'Unauthorized'))
270+
if (this.rejectCredentials || request.headers.authorization !== `Bearer ${this.token}`) {
271+
return json(401, statusBody(401, 'Unauthorized', 'Unauthorized'))
272+
}
269273

270274
const runtimeClass = /^\/apis\/node\.k8s\.io\/v1\/runtimeclasses\/([^/]+)$/.exec(url.pathname)
271275
if (runtimeClass && method === 'GET') {
@@ -701,6 +705,18 @@ describe('create', () => {
701705
}
702706
})
703707

708+
it('sends the kubeconfig token, and fails as configuration when the API server does not know it', async () => {
709+
const wrongToken = path.join(kubeconfigDirectory, 'wrong-token')
710+
writeFileSync(wrongToken, cluster.kubeconfig('revoked-token'))
711+
vi.stubEnv('KUBECONFIG', wrongToken)
712+
const error = await configure()
713+
.create('code', { lifetimeMs: 60_000 })
714+
.catch((caught: unknown) => caught)
715+
expect(error).toBeInstanceOf(KubernetesSandboxConfigError)
716+
expect(String(error)).toMatch(/rejected Sim's credentials/)
717+
expect(cluster.pods.size).toBe(0)
718+
})
719+
704720
it('adopts its own pod when the create it retries had already succeeded', async () => {
705721
cluster.createScript.push('store-then-drop')
706722
cluster.onCreate = (name) => startPod(name)

0 commit comments

Comments
 (0)