Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions .github/workflows/helm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ on:
# change to its generator has to run this workflow too.
- 'scripts/generate-image-manifest.ts'
- 'scripts/write-chart-sandbox-images.ts'
- 'scripts/release-image-list.ts'
# The publish jobs run it to stamp appVersion and the release's sandbox images.
- 'scripts/sync-chart-appversion.ts'
- 'package.json'
pull_request:
branches: [main, staging, dev]
Expand All @@ -24,6 +27,9 @@ on:
# change to its generator has to run this workflow too.
- 'scripts/generate-image-manifest.ts'
- 'scripts/write-chart-sandbox-images.ts'
- 'scripts/release-image-list.ts'
# The publish jobs run it to stamp appVersion and the release's sandbox images.
- 'scripts/sync-chart-appversion.ts'
- 'package.json'

# Pull requests cancel a superseded run; pushes never do, so a newer push cannot cut off a chart
Expand Down Expand Up @@ -192,7 +198,7 @@ jobs:
--wait --timeout 15m
- name: Run helm test
run: helm test sim --namespace sim --timeout 5m
run: helm test sim --namespace sim --logs --timeout 5m

# Kubernetes refuses any change to a StatefulSet's volumeClaimTemplates, so
# a label that moves with the chart version there breaks every upgrade of
Expand Down Expand Up @@ -232,8 +238,8 @@ jobs:
--wait --timeout 10m
# After the test, so it also explains a failed probe, not only a failed
# install. A failed test pod is kept (the hook deletes it only on success),
# so its log says which URL refused.
# install. The test pods are kept until the next helm test, so their logs
# say which URL refused.
- name: Diagnostics on failure
if: failure()
run: |
Expand All @@ -244,6 +250,7 @@ jobs:
kubectl -n sim logs deploy/sim-app --tail=80 || true
kubectl -n sim logs deploy/sim-realtime --tail=80 || true
kubectl -n sim logs sim-test-connection || true
kubectl -n sim logs sim-test-self-check || true
kubectl -n sim-upgrade get pods -o wide || true
kubectl -n sim-upgrade get events --sort-by=.lastTimestamp | tail -20 || true
Expand Down
106 changes: 104 additions & 2 deletions .github/workflows/sandbox.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ name: sandbox
# e2e-app The real app image installed by the chart, executing Function
# blocks through the public API
# (apps/sim/scripts/test-sandbox-kubernetes-app-e2e.ts), with the
# chart's admission policy active.
# chart's admission policy active; then `helm test`, whose
# self-check must pass, and must fail once the sandbox network
# boundary is opened.
# app-image The app and migrations images, built as ci.yml builds them (runner
# class, image action, layer cache budget) on their own cache key.
# PR CI otherwise never builds the app image, so a dependency that
Expand Down Expand Up @@ -71,6 +73,11 @@ on:
- 'apps/sim/app/api/cron/cleanup-session-sandboxes/**'
- 'apps/sim/scripts/test-sandbox-kubernetes-e2e.ts'
- 'apps/sim/scripts/test-sandbox-kubernetes-app-e2e.ts'
# The self-check e2e-app runs through `helm test`, and its test pods.
- 'apps/sim/lib/self-check/**'
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
- 'apps/sim/lib/api/contracts/self-check.ts'
- 'apps/sim/app/api/cron/self-check/**'
- 'helm/sim/templates/tests/**'
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
# The sandbox images' recipes, content-addressed tags, and verification.
- 'apps/sim/scripts/generate-sandbox-dockerfiles.ts'
- 'apps/sim/scripts/function-sandbox-packages.ts'
Expand Down Expand Up @@ -207,9 +214,17 @@ jobs:
- '.github/actions/setup/**'
- '.github/workflows/sandbox.yml'
e2e_app:
- 'apps/sim/lib/execution/remote-sandbox/*.ts'
- '!apps/sim/lib/execution/remote-sandbox/e2b*.ts'
- '!apps/sim/lib/execution/remote-sandbox/daytona*.ts'
- '!apps/sim/lib/execution/remote-sandbox/conformance*.ts'
- 'apps/sim/lib/execution/remote-sandbox/kubernetes/**'
- 'apps/sim/lib/execution/remote-sandbox/agent/**'
- 'apps/sim/scripts/test-sandbox-kubernetes-app-e2e.ts'
- 'apps/sim/lib/self-check/**'
- 'apps/sim/lib/api/contracts/self-check.ts'
- 'apps/sim/app/api/cron/self-check/**'
- 'helm/sim/templates/tests/**'
- 'apps/sandbox-agent/**'
- 'packages/sandbox-agent-protocol/**'
- 'helm/sim/templates/sandbox-kubernetes.yaml'
Expand All @@ -218,6 +233,8 @@ jobs:
- 'helm/sim/templates/deployment-app.yaml'
- 'helm/sim/templates/serviceaccount.yaml'
- 'helm/sim/templates/_helpers.tpl'
- 'helm/sim/values.yaml'
- 'helm/sim/values.schema.json'
- 'helm/sim/ci/default-values.yaml'
- '.github/sandbox-kubernetes-e2e/**'
- '.github/actions/image/**'
Expand Down Expand Up @@ -1033,7 +1050,7 @@ jobs:
(needs.image.result == 'success' || needs.image.result == 'skipped')
# GitHub-hosted: nested gVisor needs a plain VM, not a microVM runner.
runs-on: ubuntu-24.04
timeout-minutes: 40
timeout-minutes: 55
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6
Expand Down Expand Up @@ -1141,6 +1158,91 @@ jobs:
SANDBOX_K8S_RUNTIME_CLASS: gvisor
run: SANDBOX_K8S_APP_E2E_CRON_SECRET="$E2E_CRON_SECRET" bun run scripts/test-sandbox-kubernetes-app-e2e.ts

# What an operator runs after installing: the chart's test pods, including
# the authenticated self-check with its sandbox confinement checks. The app
# image is this checkout's, so the endpoint exists: the self-check must
# pass, not skip as it would on an older image.
- name: Run helm test
run: |
set -euo pipefail
helm test sim --namespace "$RELEASE_NAMESPACE" --logs --timeout 10m \
| tee "$RUNNER_TEMP/helm-test.log"
if ! grep -q '^OK: self-check passed$' "$RUNNER_TEMP/helm-test.log"; then
echo "::error::helm test passed without the self-check passing (it skipped)"
exit 1
fi
# The self-check's sandbox passes mean something only if it fails once the
# boundary is open. Opens it the way a misconfigured cluster would: sandbox
# pods may send and receive anything, and the app pod accepts the sandbox
# namespace. Both lateral reach (the app pod) and a sibling sandbox's agent
# must then fail.
- name: Self-check fails with the sandbox network boundary open
run: |
set -euo pipefail
trap 'kubectl delete networkpolicy self-check-open-sandboxes --namespace "$SANDBOX_NAMESPACE" --ignore-not-found
kubectl delete networkpolicy self-check-open-app --namespace "$RELEASE_NAMESPACE" --ignore-not-found' EXIT
kubectl apply -f - <<EOF
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: self-check-open-sandboxes
namespace: ${SANDBOX_NAMESPACE}
spec:
podSelector: {}
policyTypes: [Ingress, Egress]
ingress: [{}]
egress: [{}]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: self-check-open-app
namespace: ${RELEASE_NAMESPACE}
spec:
podSelector:
matchLabels:
app.kubernetes.io/name: sim
app.kubernetes.io/instance: sim
app.kubernetes.io/component: app
policyTypes: [Ingress]
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: ${SANDBOX_NAMESPACE}
EOF
report="$RUNNER_TEMP/self-check-open-boundary.json"
# The policy controller applies policies asynchronously, so each
# attempt waits for it. Bounded to about 12 minutes in all, inside
# the job's timeout.
for attempt in $(seq 1 4); do
sleep 10
status="$(curl -sS --max-time 170 -o "$report" -w '%{http_code}' \
-H "Authorization: Bearer ${E2E_CRON_SECRET}" \
'http://localhost:3000/api/cron/self-check?sandbox=1&realtime=0')" || status=000
echo "Attempt ${attempt}: HTTP ${status}"
if [ "$status" = 000 ]; then
if ! curl -fsS --max-time 5 http://localhost:3000/api/health > /dev/null; then
cat "$RUNNER_TEMP/port-forward.log" || true
echo "::error::The port-forward to the app is down, so the self-check could not be called"
exit 1
fi
continue
fi
jq . "$report" || cat "$report"
if [ "$status" = 503 ] && jq -e '
.ok == false and
([.checks[] | select(.name == "sandbox.lateral") | .status] == ["fail"]) and
([.checks[] | select(.name == "sandbox.neighbor") | .status] == ["fail"])
' "$report" > /dev/null; then
echo "The self-check failed lateral and sibling-sandbox reach with the boundary open."
exit 0
fi
done
echo "::error::The self-check still passed sandbox.lateral or sandbox.neighbor with the sandbox network boundary open"
exit 1
- name: Collect diagnostics
if: failure()
uses: ./.github/actions/k3s-diagnostics
Expand Down
4 changes: 3 additions & 1 deletion apps/docs/content/docs/platform/self-hosting/kubernetes.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,9 @@ kubectl get cronjobs -n simstudio
curl -fsS https://sim.yourdomain.com/api/health
```

Scheduled jobs cover workflows, polling triggers, connector syncs, token cleanup, data drains, and outbox processing. Inspect failed job pods and endpoint responses, then run [Verify your install](/platform/self-hosting/verify).
Scheduled jobs cover workflows, polling triggers, connector syncs, token cleanup, data drains, and outbox processing. Inspect failed job pods and endpoint responses.

Run `helm test sim -n simstudio --logs` to prove the install works: it checks the database and its migrations, Redis, realtime, and, with the Kubernetes sandbox provider, that sandboxes run user code confined. Then run [Verify your install](/platform/self-hosting/verify).

## Verify the chart [#verifying-the-chart]

Expand Down
2 changes: 2 additions & 0 deletions apps/docs/content/docs/platform/self-hosting/verify.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ kubectl get cronjobs -n simstudio

The migrations init container must complete before the app starts. Inspect failed CronJob pods and their logs; the presence of a schedule alone does not prove the endpoint call succeeded.

Then run `helm test sim -n simstudio --logs`. One test pod checks the app and realtime Services answer; the other calls the app's authenticated self-check, which passes only when the database answers and is migrated, Redis answers, realtime is healthy, and, with the Kubernetes sandbox provider, a sandbox runs user code confined (sandbox user, no cloud metadata credentials or Kubernetes API, no reach into the app, its data stores, or another sandbox). `--logs` prints each check's result. It skips, passing, when `CRON_SECRET` is not in the app Secret.

To check whether Redis is configured without printing the connection string:

```bash
Expand Down
28 changes: 28 additions & 0 deletions apps/sim/app/api/cron/self-check/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { type NextRequest, NextResponse } from 'next/server'
import { type SelfCheckResponse, selfCheckContract } from '@/lib/api/contracts/self-check'
import { parseRequest } from '@/lib/api/server'
import { verifyCronAuth } from '@/lib/auth/internal'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { runSelfCheck } from '@/lib/self-check/run'

export const dynamic = 'force-dynamic'
/** Above the sandbox check's own budget, so a slow sandbox start still reports. */
export const maxDuration = 180

/**
* Post-install self-check for self-hosted deployments, called by the Helm chart's `helm test`
* hook with the cron secret. 200 when nothing failed, 503 otherwise; the body is always the report.
*/
export const GET = withRouteHandler(async (request: NextRequest) => {
const authError = verifyCronAuth(request, 'Self-check')
if (authError) return authError

const parsed = await parseRequest(selfCheckContract, request, {})
if (!parsed.success) return parsed.response

const report: SelfCheckResponse = await runSelfCheck({
sandbox: parsed.data.query.sandbox === '1',
realtime: parsed.data.query.realtime === '1',
})
return NextResponse.json(report, { status: report.ok ? 200 : 503 })
})
36 changes: 36 additions & 0 deletions apps/sim/lib/api/contracts/self-check.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { z } from 'zod'
import { defineRouteContract } from '@/lib/api/contracts/types'
import { SELF_CHECK_NAMES, SELF_CHECK_STATUSES } from '@/lib/self-check/types'

const flagSchema = z.enum(['0', '1']).optional()

const selfCheckQuerySchema = z
.object({
/** Runs user code in a sandbox and checks it is confined (Kubernetes provider only). */
sandbox: flagSchema,
/** Checks the realtime server's health endpoint. */
realtime: flagSchema,
})
.strict()

const selfCheckResponseSchema = z.object({
ok: z.boolean(),
checks: z.array(
z.object({
name: z.enum(SELF_CHECK_NAMES),
status: z.enum(SELF_CHECK_STATUSES),
durationMs: z.number().int().min(0),
detail: z.string().max(500),
})
),
})

export type SelfCheckResponse = z.output<typeof selfCheckResponseSchema>

/** 200 when every check passed, warned, or was skipped; 503 when any failed. */
export const selfCheckContract = defineRouteContract({
method: 'GET',
path: '/api/cron/self-check',
query: selfCheckQuerySchema,
response: { mode: 'json', schema: selfCheckResponseSchema, status: [200, 503] },
})
1 change: 1 addition & 0 deletions apps/sim/lib/core/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ export const env = createEnv({
DATABASE_URL_EXEC: z.string().url().optional(), // Sub-process pool URL override (inline execution writes, via dbFor)
DATABASE_URL_BILLING: z.string().url().optional(), // Sub-process pool URL override (usage-ledger writes, via dbFor)
DATABASE_URL_AUTH: z.string().url().optional(), // Sub-process pool URL override (session and API-key lookups, via dbFor)
DATABASE_URL_SEARCH: z.string().url().optional(), // Sub-process pool URL override (search reads, via dbFor)
DATABASE_REPLICA_URL_WEB: z.string().url().optional(), // Per-role replica URL override; falls back to DATABASE_REPLICA_URL
DATABASE_REPLICA_URL_TRIGGER: z.string().url().optional(), // Per-role replica URL override (trigger)
DATABASE_REPLICA_URL_REALTIME: z.string().url().optional(), // Per-role replica URL override (realtime)
Expand Down
4 changes: 4 additions & 0 deletions apps/sim/lib/execution/remote-sandbox/agent/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ export interface AgentSandboxConnection {
beforeLifetimeExtended?(expiresAtMs: number): Promise<void>
/** Provider teardown (for Kubernetes, deleting the pod). */
kill(): Promise<void>
/** See {@link SandboxHandle.podAddress}. */
podAddress?: string
}

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

class AgentSandboxHandle implements SandboxHandle {
readonly sandboxId: string
readonly podAddress?: string
readonly verifiesCliAtLaunch: boolean
readonly extendLifetime?: (lifetimeMs: number) => Promise<void>
readonly outlives?: (lifetimeMs: number, fromMs: number) => boolean
Expand All @@ -104,6 +107,7 @@ class AgentSandboxHandle implements SandboxHandle {

constructor(private readonly connection: AgentSandboxConnection) {
this.sandboxId = connection.sandboxId
if (connection.podAddress) this.podAddress = connection.podAddress
this.client = new SandboxAgentClient(connection.baseUrl, connection.token)
this.language = connection.language ?? CodeLanguage.Python
this.sessionKey = connection.sessionKey
Expand Down
Loading
Loading