Skip to content

Commit 048e203

Browse files
committed
fix(sandbox): address final review round
- 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.
1 parent 05c036c commit 048e203

14 files changed

Lines changed: 294 additions & 73 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
name: sandbox-image
2+
description: >-
3+
Build one sandbox image for one architecture into the local Docker daemon and
4+
verify its contract. Pushes nothing: sandbox.yml's read-only build job and its
5+
push-gated publish job both run these steps, so a pull request never builds in a
6+
job that holds registry or signing credentials.
7+
8+
inputs:
9+
provider:
10+
description: CI provider, as the image and setup actions take it.
11+
required: false
12+
default: ''
13+
kind:
14+
description: Sandbox image kind (agent, function, pi).
15+
required: true
16+
arch:
17+
description: Target architecture (amd64, arm64).
18+
required: true
19+
tag:
20+
description: Reference to load the built image under.
21+
required: true
22+
23+
runs:
24+
using: composite
25+
steps:
26+
- name: Build image
27+
uses: ./.github/actions/image
28+
with:
29+
provider: ${{ inputs.provider }}
30+
file: ./docker/sandbox-${{ inputs.kind }}.Dockerfile
31+
platforms: linux/${{ inputs.arch }}
32+
tags: ${{ inputs.tag }}
33+
push: 'false'
34+
load: 'true'
35+
36+
- name: Setup workspace
37+
if: inputs.kind != 'agent'
38+
uses: ./.github/actions/setup
39+
with:
40+
provider: ${{ inputs.provider }}
41+
node-version: ''
42+
43+
- name: Verify image contract
44+
if: inputs.kind != 'agent'
45+
shell: bash
46+
env:
47+
KIND: ${{ inputs.kind }}
48+
TAG: ${{ inputs.tag }}
49+
run: bun run apps/sim/scripts/verify-sandbox-image.ts --kind "$KIND" --image "$TAG"

‎.github/workflows/sandbox.yml‎

Lines changed: 75 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ on:
9090
- 'helm/sim/ci/default-values.yaml'
9191
- '.github/sandbox-kubernetes-e2e/**'
9292
- '.github/actions/image/**'
93+
- '.github/actions/sandbox-image/**'
9394
- '.github/actions/attest-image/**'
9495
- '.github/actions/k3s-*/**'
9596
- '.github/actions/setup/**'
@@ -230,6 +231,7 @@ jobs:
230231
verification:
231232
- '.github/workflows/sandbox.yml'
232233
- '.github/actions/image/**'
234+
- '.github/actions/sandbox-image/**'
233235
- 'apps/sim/scripts/verify-sandbox-image.ts'
234236
- 'apps/sim/scripts/function-sandbox-parity-manifest.ts'
235237
@@ -407,29 +409,25 @@ jobs:
407409
} >> "$GITHUB_OUTPUT"
408410
cat /tmp/legs.jsonl
409411
410-
# One leg per image and architecture, each on a native runner. The image is built
411-
# into the local daemon and verified before anything is pushed; the pushed
412-
# `<tag>-<arch>` is then signed and attested in the same leg, so a later failure
413-
# never leaves a published digest unsigned.
412+
# One leg per image and architecture, each on a native runner, built into the
413+
# local daemon and verified. Every run that does not publish (pull requests, a
414+
# dry-run or e2e dispatch) builds here, with a read-only token: a pull request's
415+
# checkout controls this job's code, and GitHub grants a same-repository pull
416+
# request's token whatever write permissions its job asks for. amd64 builds an
417+
# e2e job needs upload their archive.
414418
image:
415419
name: image (${{ matrix.kind }}, ${{ matrix.arch }})
416420
needs: [plan]
417-
if: needs.plan.outputs.legs != '[]'
421+
if: needs.plan.outputs.legs != '[]' && needs.plan.outputs.publish != 'true'
418422
runs-on: ${{ (vars.CI_PROVIDER == '' || vars.CI_PROVIDER == 'blacksmith') && (matrix.arch == 'arm64' && 'blacksmith-4vcpu-ubuntu-2404-arm' || 'blacksmith-4vcpu-ubuntu-2404') || (matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-latest') }}
419423
timeout-minutes: 45
420424
permissions:
421425
contents: read
422-
packages: write
423-
id-token: write
424-
attestations: write
425-
artifact-metadata: write
426426
strategy:
427427
fail-fast: false
428428
matrix:
429429
include: ${{ fromJSON(needs.plan.outputs.legs) }}
430430
env:
431-
# Belt and braces with the plan: nothing but a main or staging run pushes.
432-
PUBLISH: ${{ needs.plan.outputs.publish == 'true' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/staging') }}
433431
ARCHIVE: ${{ matrix.arch == 'amd64' && contains(fromJSON(needs.plan.outputs.archives), matrix.kind) }}
434432
ARCH_REF: ${{ matrix.ref }}-${{ matrix.arch }}
435433
steps:
@@ -438,41 +436,13 @@ jobs:
438436
with:
439437
persist-credentials: false
440438

441-
- name: Login to Docker Hub
442-
if: env.PUBLISH == 'true'
443-
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4
444-
with:
445-
username: ${{ secrets.DOCKERHUB_USERNAME }}
446-
password: ${{ secrets.DOCKERHUB_TOKEN }}
447-
448-
- name: Login to GHCR
449-
if: env.PUBLISH == 'true'
450-
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4
451-
with:
452-
registry: ghcr.io
453-
username: ${{ github.repository_owner }}
454-
password: ${{ secrets.GITHUB_TOKEN }}
455-
456-
- name: Build image
457-
uses: ./.github/actions/image
439+
- name: Build and verify image
440+
uses: ./.github/actions/sandbox-image
458441
with:
459442
provider: ${{ vars.CI_PROVIDER }}
460-
file: ./docker/sandbox-${{ matrix.kind }}.Dockerfile
461-
platforms: linux/${{ matrix.arch }}
462-
tags: ${{ env.ARCH_REF }}
463-
push: 'false'
464-
load: 'true'
465-
466-
- name: Setup workspace
467-
if: matrix.kind != 'agent'
468-
uses: ./.github/actions/setup
469-
with:
470-
provider: ${{ vars.CI_PROVIDER }}
471-
node-version: ''
472-
473-
- name: Verify image contract
474-
if: matrix.kind != 'agent'
475-
run: bun run apps/sim/scripts/verify-sandbox-image.ts --kind ${{ matrix.kind }} --image "$ARCH_REF"
443+
kind: ${{ matrix.kind }}
444+
arch: ${{ matrix.arch }}
445+
tag: ${{ env.ARCH_REF }}
476446

477447
# Under the reference the app defaults to, which is what pods name in k3s.
478448
- name: Save image
@@ -496,9 +466,62 @@ jobs:
496466
retention-days: 1
497467
compression-level: 1
498468

469+
# The publishing legs: the same build and verification, then the pushed
470+
# `<tag>-<arch>` is signed and attested in the same leg, so a later failure never
471+
# leaves a published digest unsigned. The only job holding registry-write and
472+
# signing permissions besides `publish`, and it never runs for a pull request:
473+
# only for a push to, or a dispatch on, main or staging.
474+
image-publish:
475+
name: image-publish (${{ matrix.kind }}, ${{ matrix.arch }})
476+
needs: [plan]
477+
if: >-
478+
needs.plan.outputs.legs != '[]' &&
479+
needs.plan.outputs.publish == 'true' &&
480+
(github.event_name == 'push' || github.event_name == 'workflow_dispatch') &&
481+
(github.ref == 'refs/heads/main' || github.ref == 'refs/heads/staging')
482+
runs-on: ${{ (vars.CI_PROVIDER == '' || vars.CI_PROVIDER == 'blacksmith') && (matrix.arch == 'arm64' && 'blacksmith-4vcpu-ubuntu-2404-arm' || 'blacksmith-4vcpu-ubuntu-2404') || (matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-latest') }}
483+
timeout-minutes: 45
484+
permissions:
485+
contents: read
486+
packages: write
487+
id-token: write
488+
attestations: write
489+
artifact-metadata: write
490+
strategy:
491+
fail-fast: false
492+
matrix:
493+
include: ${{ fromJSON(needs.plan.outputs.legs) }}
494+
env:
495+
ARCH_REF: ${{ matrix.ref }}-${{ matrix.arch }}
496+
steps:
497+
- name: Checkout code
498+
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6
499+
with:
500+
persist-credentials: false
501+
502+
- name: Login to Docker Hub
503+
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4
504+
with:
505+
username: ${{ secrets.DOCKERHUB_USERNAME }}
506+
password: ${{ secrets.DOCKERHUB_TOKEN }}
507+
508+
- name: Login to GHCR
509+
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4
510+
with:
511+
registry: ghcr.io
512+
username: ${{ github.repository_owner }}
513+
password: ${{ secrets.GITHUB_TOKEN }}
514+
515+
- name: Build and verify image
516+
uses: ./.github/actions/sandbox-image
517+
with:
518+
provider: ${{ vars.CI_PROVIDER }}
519+
kind: ${{ matrix.kind }}
520+
arch: ${{ matrix.arch }}
521+
tag: ${{ env.ARCH_REF }}
522+
499523
- name: Push image
500524
id: push
501-
if: env.PUBLISH == 'true'
502525
run: |
503526
set -euo pipefail
504527
docker push "$ARCH_REF"
@@ -511,25 +534,25 @@ jobs:
511534
echo "digest=${digest}" >> "$GITHUB_OUTPUT"
512535
513536
- name: Attest and sign image
514-
if: env.PUBLISH == 'true'
515537
uses: ./.github/actions/attest-image
516538
with:
517539
image: ${{ steps.push.outputs.image }}
518540
digest: ${{ steps.push.outputs.digest }}
519541
sbom-image: ${{ env.ARCH_REF }}
520542

521543
# Joins the two architectures under the content tag the app references, then signs
522-
# and attests that index. Runs after a failed image leg too, so the other kinds and
523-
# the index-only retry still publish; a kind joins only when both architectures are
524-
# published and signed by this workflow, so a leg that pushed but failed to attest
525-
# or sign is never exposed, and the next run rebuilds it.
544+
# and attests that index. Runs after a failed image-publish leg too, so the other
545+
# kinds and the index-only retry still publish; a kind joins only when both
546+
# architectures are published and signed by this workflow, so a leg that pushed but
547+
# failed to attest or sign is never exposed, and the next run rebuilds it.
526548
publish:
527549
name: publish (${{ matrix.kind }})
528-
needs: [plan, image]
550+
needs: [plan, image-publish]
529551
if: >-
530552
!cancelled() &&
531553
needs.plan.outputs.publish == 'true' &&
532554
needs.plan.outputs.kinds != '[]' &&
555+
(github.event_name == 'push' || github.event_name == 'workflow_dispatch') &&
533556
(github.ref == 'refs/heads/main' || github.ref == 'refs/heads/staging')
534557
runs-on: ubuntu-24.04
535558
timeout-minutes: 15
@@ -571,7 +594,7 @@ jobs:
571594
echo "::error::${REF}-${arch} is not published; not publishing ${REF}"
572595
exit 1
573596
fi
574-
# The image leg signs last, after both attestations, so a signature means
597+
# The image-publish leg signs last, after both attestations, so a signature means
575598
# the leg finished.
576599
if ! cosign verify \
577600
--certificate-identity-regexp "$SIGNER_IDENTITY_REGEXP" \

‎apps/sim/lib/execution/remote-sandbox/agent/client.ts‎

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,13 +77,25 @@ interface AgentRequestOptions {
7777
* Reads an agent's JSON reply, refusing one over `maxBytes`: the transport is the pod network, so
7878
* a reply is never trusted to be as small as the protocol makes it.
7979
*/
80-
function readAgentJson(response: Response, maxBytes: number): Promise<unknown> {
81-
return readResponseJsonWithLimit(response, { maxBytes, label: 'Sandbox agent response' })
80+
function readAgentJson(
81+
response: Response,
82+
maxBytes: number,
83+
signal?: AbortSignal
84+
): Promise<unknown> {
85+
return readResponseJsonWithLimit(response, { maxBytes, label: 'Sandbox agent response', signal })
8286
}
8387

84-
async function toRequestError(response: Response): Promise<SandboxAgentRequestError> {
88+
/**
89+
* Reads an error reply within `signal`. A streaming request has no total timeout and its header
90+
* timer has already stopped, so this deadline is all that keeps a half-sent error body from
91+
* stalling the caller.
92+
*/
93+
async function toRequestError(
94+
response: Response,
95+
signal: AbortSignal
96+
): Promise<SandboxAgentRequestError> {
8597
const parsed = sandboxAgentErrorBodySchema.safeParse(
86-
await readAgentJson(response, MAX_AGENT_JSON_BYTES).catch(() => null)
98+
await readAgentJson(response, MAX_AGENT_JSON_BYTES, signal).catch(() => null)
8799
)
88100
if (!parsed.success) {
89101
return new SandboxAgentRequestError(
@@ -167,7 +179,11 @@ export class SandboxAgentClient {
167179
clearTimeout(headersTimer)
168180
}
169181
if (response.ok) return response
170-
const requestError = await toRequestError(response)
182+
const errorBodyDeadline = AbortSignal.timeout(options.headersTimeoutMs ?? REQUEST_TIMEOUT_MS)
183+
const requestError = await toRequestError(
184+
response,
185+
options.signal ? AbortSignal.any([options.signal, errorBodyDeadline]) : errorBodyDeadline
186+
)
171187
// Reading the error body swallows a cancellation, which must still surface as one.
172188
options.signal?.throwIfAborted()
173189
throw requestError
@@ -210,13 +226,15 @@ export class SandboxAgentClient {
210226

211227
/**
212228
* The milliseconds left on the agent's deadline, by its own clock. Asks for a 1 ms lease, which
213-
* never shortens a deadline and so changes nothing on a live agent.
229+
* never shortens a deadline and so changes nothing on a live agent. `signal` bounds every
230+
* attempt and the backoff between them.
214231
*/
215-
async remainingLifetimeMs(): Promise<number> {
232+
async remainingLifetimeMs(signal?: AbortSignal): Promise<number> {
216233
const { remainingMs } = lifetimeResponseSchema.parse(
217234
await this.requestJson(SANDBOX_AGENT_ROUTES.lifetime, {
218235
method: 'POST',
219236
json: { ttlMs: 1 },
237+
signal,
220238
retry: true,
221239
})
222240
)

‎apps/sim/lib/execution/remote-sandbox/agent/handle.integration.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,27 @@ describe('files over the agent', () => {
369369
}
370370
})
371371

372+
it.each([
373+
['absent', ''],
374+
['blank', '$1: \r\n'],
375+
['hexadecimal', '$1: 0x5\r\n'],
376+
['fractional', '$1: 5.0\r\n'],
377+
])('refuses a read whose declared size is %s', async (_label, replacement) => {
378+
const proxy = await startProxy((chunk) =>
379+
chunk.replace(/(X-Sim-File-Size|x-sim-file-size): 5\r\n/, replacement)
380+
)
381+
try {
382+
const target = path.join(agent.root, `undeclared-${generateId()}`)
383+
const sandbox = createAgentSandboxHandle(connection({ baseUrl: proxy.baseUrl }))
384+
await sandbox.writeFile(target, 'hello')
385+
await expect(
386+
sandbox.readFileStream(target, { signal: AbortSignal.timeout(10_000) })
387+
).rejects.toThrow('missing its size')
388+
} finally {
389+
await proxy.close()
390+
}
391+
})
392+
372393
it('aborts a streamed upload without leaving a partial file', async () => {
373394
const sandbox = createAgentSandboxHandle(connection())
374395
const target = path.join(agent.root, `aborted-${generateId()}`)
@@ -661,6 +682,23 @@ describe('agent streams', () => {
661682
}
662683
})
663684

685+
it('bounds reading the error body of a streaming request', async () => {
686+
const server = await startFakeAgent((_request, response) => {
687+
response.writeHead(500, { 'Content-Type': 'application/json' })
688+
response.write('{"error":')
689+
})
690+
try {
691+
const client = new SandboxAgentClient(server.baseUrl, 'token')
692+
const startedAtMs = Date.now()
693+
await expect(
694+
client.request('/stalled-error', { timeout: false, headersTimeoutMs: 200 })
695+
).rejects.toMatchObject({ status: 500, code: 'unknown' })
696+
expect(Date.now() - startedAtMs).toBeLessThan(5_000)
697+
} finally {
698+
await server.close()
699+
}
700+
}, 15_000)
701+
664702
it('releases an event stream that ends the command without a terminal event', async () => {
665703
let streamClosed: () => void = () => {}
666704
const closed = new Promise<void>((resolve) => {

‎apps/sim/lib/execution/remote-sandbox/agent/handle.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,8 +226,11 @@ class AgentSandboxHandle implements SandboxHandle {
226226
}
227227
throw error
228228
}
229-
const declared = Number(response.headers.get(SANDBOX_AGENT_FILE_SIZE_HEADER))
230-
if (!response.body || !Number.isSafeInteger(declared) || declared < 0) {
229+
const declaredHeader = response.headers.get(SANDBOX_AGENT_FILE_SIZE_HEADER)
230+
// A bare `Number()` reads an absent or blank header as 0 and accepts `0x5` or `5.0`.
231+
const declared =
232+
declaredHeader !== null && /^\d+$/.test(declaredHeader) ? Number(declaredHeader) : Number.NaN
233+
if (!response.body || !Number.isSafeInteger(declared)) {
231234
await response.body?.cancel()
232235
throw new Error('Sandbox agent file read is missing its size')
233236
}

0 commit comments

Comments
 (0)