Skip to content

Commit d5763dd

Browse files
committed
feat(self-hosting): add an authenticated self-check and a helm test that proves a real install works
1 parent 22b5058 commit d5763dd

29 files changed

Lines changed: 1956 additions & 214 deletions

‎.github/workflows/sandbox.yml‎

Lines changed: 89 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,9 @@ name: sandbox
3737
# e2e-app The real app image installed by the chart, executing Function
3838
# blocks through the public API
3939
# (apps/sim/scripts/test-sandbox-kubernetes-app-e2e.ts), with the
40-
# chart's admission policy active.
40+
# chart's admission policy active; then `helm test`, whose
41+
# self-check must pass, and must fail once the sandbox network
42+
# boundary is opened.
4143
# app-image The app and migrations images, built as ci.yml builds them (runner
4244
# class, image action, layer cache budget) on their own cache key.
4345
# PR CI otherwise never builds the app image, so a dependency that
@@ -71,6 +73,10 @@ on:
7173
- 'apps/sim/app/api/cron/cleanup-session-sandboxes/**'
7274
- 'apps/sim/scripts/test-sandbox-kubernetes-e2e.ts'
7375
- 'apps/sim/scripts/test-sandbox-kubernetes-app-e2e.ts'
76+
# The self-check e2e-app runs through `helm test`, and its test pods.
77+
- 'apps/sim/lib/self-check/**'
78+
- 'apps/sim/app/api/cron/self-check/**'
79+
- 'helm/sim/templates/tests/**'
7480
# The sandbox images' recipes, content-addressed tags, and verification.
7581
- 'apps/sim/scripts/generate-sandbox-dockerfiles.ts'
7682
- 'apps/sim/scripts/function-sandbox-packages.ts'
@@ -210,6 +216,9 @@ jobs:
210216
- 'apps/sim/lib/execution/remote-sandbox/kubernetes/**'
211217
- 'apps/sim/lib/execution/remote-sandbox/agent/**'
212218
- 'apps/sim/scripts/test-sandbox-kubernetes-app-e2e.ts'
219+
- 'apps/sim/lib/self-check/**'
220+
- 'apps/sim/app/api/cron/self-check/**'
221+
- 'helm/sim/templates/tests/**'
213222
- 'apps/sandbox-agent/**'
214223
- 'packages/sandbox-agent-protocol/**'
215224
- 'helm/sim/templates/sandbox-kubernetes.yaml'
@@ -1033,7 +1042,7 @@ jobs:
10331042
(needs.image.result == 'success' || needs.image.result == 'skipped')
10341043
# GitHub-hosted: nested gVisor needs a plain VM, not a microVM runner.
10351044
runs-on: ubuntu-24.04
1036-
timeout-minutes: 40
1045+
timeout-minutes: 55
10371046
steps:
10381047
- name: Checkout code
10391048
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6
@@ -1092,6 +1101,7 @@ jobs:
10921101
--set "app.env.INTERNAL_API_SECRET=${E2E_INTERNAL_SECRET}" \
10931102
--set "app.env.CRON_SECRET=${E2E_CRON_SECRET}" \
10941103
--set "postgresql.auth.password=${E2E_DB_SECRET}" \
1104+
--set tests.selfCheck.requireEndpoint=true \
10951105
--wait --timeout 20m
10961106
kubectl get pods --namespace "$RELEASE_NAMESPACE" -o wide
10971107
@@ -1141,6 +1151,83 @@ jobs:
11411151
SANDBOX_K8S_RUNTIME_CLASS: gvisor
11421152
run: SANDBOX_K8S_APP_E2E_CRON_SECRET="$E2E_CRON_SECRET" bun run scripts/test-sandbox-kubernetes-app-e2e.ts
11431153

1154+
# What an operator runs after installing: the chart's test pods, including
1155+
# the authenticated self-check with its sandbox confinement checks. The app
1156+
# image is this checkout's, so the endpoint must exist (requireEndpoint).
1157+
- name: Run helm test
1158+
run: helm test sim --namespace "$RELEASE_NAMESPACE" --logs --timeout 10m
1159+
1160+
# The self-check's sandbox passes mean something only if it fails once the
1161+
# boundary is open. Opens it the way a misconfigured cluster would: sandbox
1162+
# pods may send and receive anything, and the app pod accepts the sandbox
1163+
# namespace. Both lateral reach (the app pod) and a sibling sandbox's agent
1164+
# must then fail.
1165+
- name: Self-check fails with the sandbox network boundary open
1166+
run: |
1167+
set -euo pipefail
1168+
trap 'kubectl delete networkpolicy self-check-open-sandboxes --namespace "$SANDBOX_NAMESPACE" --ignore-not-found
1169+
kubectl delete networkpolicy self-check-open-app --namespace "$RELEASE_NAMESPACE" --ignore-not-found' EXIT
1170+
kubectl apply -f - <<EOF
1171+
apiVersion: networking.k8s.io/v1
1172+
kind: NetworkPolicy
1173+
metadata:
1174+
name: self-check-open-sandboxes
1175+
namespace: ${SANDBOX_NAMESPACE}
1176+
spec:
1177+
podSelector: {}
1178+
policyTypes: [Ingress, Egress]
1179+
ingress: [{}]
1180+
egress: [{}]
1181+
---
1182+
apiVersion: networking.k8s.io/v1
1183+
kind: NetworkPolicy
1184+
metadata:
1185+
name: self-check-open-app
1186+
namespace: ${RELEASE_NAMESPACE}
1187+
spec:
1188+
podSelector:
1189+
matchLabels:
1190+
app.kubernetes.io/name: sim
1191+
app.kubernetes.io/instance: sim
1192+
app.kubernetes.io/component: app
1193+
policyTypes: [Ingress]
1194+
ingress:
1195+
- from:
1196+
- namespaceSelector:
1197+
matchLabels:
1198+
kubernetes.io/metadata.name: ${SANDBOX_NAMESPACE}
1199+
EOF
1200+
report="$RUNNER_TEMP/self-check-open-boundary.json"
1201+
# The app reuses a sandbox result for 30 seconds and the policy
1202+
# controller applies policies asynchronously, so each attempt waits
1203+
# past both.
1204+
for attempt in $(seq 1 6); do
1205+
sleep 35
1206+
status="$(curl -sS --max-time 240 -o "$report" -w '%{http_code}' \
1207+
-H "Authorization: Bearer ${E2E_CRON_SECRET}" \
1208+
'http://localhost:3000/api/cron/self-check?sandbox=1&realtime=0')" || status=000
1209+
echo "Attempt ${attempt}: HTTP ${status}"
1210+
if [ "$status" = 000 ]; then
1211+
if ! curl -fsS --max-time 5 http://localhost:3000/api/health > /dev/null; then
1212+
cat "$RUNNER_TEMP/port-forward.log" || true
1213+
echo "::error::The port-forward to the app is down, so the self-check could not be called"
1214+
exit 1
1215+
fi
1216+
continue
1217+
fi
1218+
jq . "$report" || cat "$report"
1219+
if [ "$status" = 503 ] && jq -e '
1220+
.ok == false and
1221+
([.checks[] | select(.name == "sandbox.lateral") | .status] == ["fail"]) and
1222+
([.checks[] | select(.name == "sandbox.neighbor") | .status] == ["fail"])
1223+
' "$report" > /dev/null; then
1224+
echo "The self-check failed lateral and sibling-sandbox reach with the boundary open."
1225+
exit 0
1226+
fi
1227+
done
1228+
echo "::error::The self-check still passed sandbox.lateral or sandbox.neighbor with the sandbox network boundary open"
1229+
exit 1
1230+
11441231
- name: Collect diagnostics
11451232
if: failure()
11461233
uses: ./.github/actions/k3s-diagnostics
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { type NextRequest, NextResponse } from 'next/server'
2+
import { type SelfCheckResponse, selfCheckContract } from '@/lib/api/contracts/self-check'
3+
import { parseRequest } from '@/lib/api/server'
4+
import { verifyCronAuth } from '@/lib/auth/internal'
5+
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
6+
import { runSelfCheck } from '@/lib/self-check/run'
7+
8+
export const dynamic = 'force-dynamic'
9+
/** Above the sandbox check's own budget, so a slow sandbox start still reports. */
10+
export const maxDuration = 180
11+
12+
/**
13+
* Post-install self-check for self-hosted deployments, called by the Helm chart's `helm test`
14+
* hook with the cron secret. 200 when nothing failed, 503 otherwise; the body is always the report.
15+
*/
16+
export const GET = withRouteHandler(async (request: NextRequest) => {
17+
const authError = verifyCronAuth(request, 'Self-check')
18+
if (authError) return authError
19+
20+
const parsed = await parseRequest(selfCheckContract, request, {})
21+
if (!parsed.success) return parsed.response
22+
23+
const report: SelfCheckResponse = await runSelfCheck({
24+
sandbox: parsed.data.query.sandbox === '1',
25+
realtime: parsed.data.query.realtime === '1',
26+
})
27+
return NextResponse.json(report, { status: report.ok ? 200 : 503 })
28+
})
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { z } from 'zod'
2+
import { defineRouteContract } from '@/lib/api/contracts/types'
3+
import { SELF_CHECK_NAMES, SELF_CHECK_STATUSES } from '@/lib/self-check/types'
4+
5+
const flagSchema = z.enum(['0', '1']).optional()
6+
7+
const selfCheckQuerySchema = z
8+
.object({
9+
/** Runs user code in a sandbox and checks it is confined (Kubernetes provider only). */
10+
sandbox: flagSchema,
11+
/** Checks the realtime server's health endpoint. */
12+
realtime: flagSchema,
13+
})
14+
.strict()
15+
16+
const selfCheckResponseSchema = z.object({
17+
ok: z.boolean(),
18+
checks: z.array(
19+
z.object({
20+
name: z.enum(SELF_CHECK_NAMES),
21+
status: z.enum(SELF_CHECK_STATUSES),
22+
durationMs: z.number().int().min(0),
23+
detail: z.string().max(500),
24+
})
25+
),
26+
})
27+
28+
export type SelfCheckResponse = z.output<typeof selfCheckResponseSchema>
29+
30+
/** 200 when every check passed, warned, or was skipped; 503 when any failed. */
31+
export const selfCheckContract = defineRouteContract({
32+
method: 'GET',
33+
path: '/api/cron/self-check',
34+
query: selfCheckQuerySchema,
35+
response: { mode: 'json', schema: selfCheckResponseSchema, status: [200, 503] },
36+
})

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ export interface AgentSandboxConnection {
8080
beforeLifetimeExtended?(expiresAtMs: number): Promise<void>
8181
/** Provider teardown (for Kubernetes, deleting the pod). */
8282
kill(): Promise<void>
83+
/** See {@link SandboxHandle.podAddress}. */
84+
podAddress?: string
8385
}
8486

8587
/**
@@ -93,6 +95,7 @@ function agentFilePath(path: string): string {
9395

9496
class AgentSandboxHandle implements SandboxHandle {
9597
readonly sandboxId: string
98+
readonly podAddress?: string
9699
readonly verifiesCliAtLaunch: boolean
97100
readonly extendLifetime?: (lifetimeMs: number) => Promise<void>
98101
readonly outlives?: (lifetimeMs: number, fromMs: number) => boolean
@@ -104,6 +107,7 @@ class AgentSandboxHandle implements SandboxHandle {
104107

105108
constructor(private readonly connection: AgentSandboxConnection) {
106109
this.sandboxId = connection.sandboxId
110+
if (connection.podAddress) this.podAddress = connection.podAddress
107111
this.client = new SandboxAgentClient(connection.baseUrl, connection.token)
108112
this.language = connection.language ?? CodeLanguage.Python
109113
this.sessionKey = connection.sessionKey

0 commit comments

Comments
 (0)