diff --git a/.github/workflows/helm.yml b/.github/workflows/helm.yml index d77d88103e9..e8576116dfd 100644 --- a/.github/workflows/helm.yml +++ b/.github/workflows/helm.yml @@ -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] @@ -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 @@ -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 @@ -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: | @@ -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 diff --git a/.github/workflows/sandbox.yml b/.github/workflows/sandbox.yml index 745c12d9c7f..266e15c5ff5 100644 --- a/.github/workflows/sandbox.yml +++ b/.github/workflows/sandbox.yml @@ -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 @@ -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/**' + - 'apps/sim/lib/api/contracts/self-check.ts' + - 'apps/sim/app/api/cron/self-check/**' + - 'helm/sim/templates/tests/**' # The sandbox images' recipes, content-addressed tags, and verification. - 'apps/sim/scripts/generate-sandbox-dockerfiles.ts' - 'apps/sim/scripts/function-sandbox-packages.ts' @@ -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' @@ -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/**' @@ -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 @@ -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 - < /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 diff --git a/apps/docs/content/docs/platform/self-hosting/kubernetes.mdx b/apps/docs/content/docs/platform/self-hosting/kubernetes.mdx index d2d40d5da3c..75c0a9f1fd9 100644 --- a/apps/docs/content/docs/platform/self-hosting/kubernetes.mdx +++ b/apps/docs/content/docs/platform/self-hosting/kubernetes.mdx @@ -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] diff --git a/apps/docs/content/docs/platform/self-hosting/verify.mdx b/apps/docs/content/docs/platform/self-hosting/verify.mdx index 451f1a0578b..31c83039718 100644 --- a/apps/docs/content/docs/platform/self-hosting/verify.mdx +++ b/apps/docs/content/docs/platform/self-hosting/verify.mdx @@ -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 diff --git a/apps/sim/app/api/cron/self-check/route.ts b/apps/sim/app/api/cron/self-check/route.ts new file mode 100644 index 00000000000..6d7a2e0c598 --- /dev/null +++ b/apps/sim/app/api/cron/self-check/route.ts @@ -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 }) +}) diff --git a/apps/sim/lib/api/contracts/self-check.ts b/apps/sim/lib/api/contracts/self-check.ts new file mode 100644 index 00000000000..2cc58a88b37 --- /dev/null +++ b/apps/sim/lib/api/contracts/self-check.ts @@ -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 + +/** 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] }, +}) diff --git a/apps/sim/lib/core/config/env.ts b/apps/sim/lib/core/config/env.ts index 37b20e6936c..756904df9cb 100644 --- a/apps/sim/lib/core/config/env.ts +++ b/apps/sim/lib/core/config/env.ts @@ -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) diff --git a/apps/sim/lib/execution/remote-sandbox/agent/handle.ts b/apps/sim/lib/execution/remote-sandbox/agent/handle.ts index e265f0ced79..70744f37f74 100644 --- a/apps/sim/lib/execution/remote-sandbox/agent/handle.ts +++ b/apps/sim/lib/execution/remote-sandbox/agent/handle.ts @@ -80,6 +80,8 @@ export interface AgentSandboxConnection { beforeLifetimeExtended?(expiresAtMs: number): Promise /** Provider teardown (for Kubernetes, deleting the pod). */ kill(): Promise + /** See {@link SandboxHandle.podAddress}. */ + podAddress?: string } /** @@ -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 readonly outlives?: (lifetimeMs: number, fromMs: number) => boolean @@ -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 diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes.live.test.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes.live.test.ts index a65b19c4984..33bf7cce516 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes.live.test.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes.live.test.ts @@ -62,6 +62,10 @@ import { SIM_RESULT_PREFIX, withPiSandbox, } from '@/lib/execution/remote-sandbox' +import { + confinementProbe, + isConfinementFacts, +} from '@/lib/execution/remote-sandbox/kubernetes/confinement-probe' import { MAX_SANDBOX_PROCESS_OUTPUT_BYTES } from '@/lib/execution/remote-sandbox/output-limits' import { SANDBOX_INPUT_DIR, SANDBOX_OUTPUT_DIR } from '@/lib/execution/remote-sandbox/paths' import { resolveProvider } from '@/lib/execution/remote-sandbox/provider' @@ -307,176 +311,6 @@ function listen(port: number, onRequest: Parameters[1]): Pr }) } -/** - * Runs as user code and reports what it can see and reach. Each probe classifies its own outcome - * so the assertions read facts, and the report keeps them for review. - */ -function securityProbe(targets: { - apiTargets: Array<[string, number]> - deniedTargets: Array<[string, number]> - allowedTargets: Array<[string, number]> - namespace: string -}): string { - return ` -import glob, json, os, socket, ssl, urllib.error, urllib.request - -def reach(host, port, timeout=4): - try: - socket.create_connection((host, port), timeout=timeout).close() - return True - except OSError: - return False - -def api(host, port): - if not reach(host, port): - return 'unreachable' - context = ssl.create_default_context() - context.check_hostname = False - context.verify_mode = ssl.CERT_NONE - url = 'https://%s:%d/api/v1/namespaces/%s/pods' % (host, port, ${JSON.stringify(targets.namespace)}) - try: - urllib.request.urlopen(url, context=context, timeout=5) - return 200 - except urllib.error.HTTPError as error: - return error.code - except Exception: - return 'unreachable' - -def agent(token): - request = urllib.request.Request('http://127.0.0.1:${AGENT_PORT}/v1/files/stat?path=/etc/hostname') - if token: - request.add_header('Authorization', 'Bearer ' + token) - try: - urllib.request.urlopen(request, timeout=5) - return 200 - except urllib.error.HTTPError as error: - return error.code - except Exception as error: - return 'error: %s' % error - -def http_status(url, headers=None, method='GET', timeout=4): - request = urllib.request.Request(url, headers=headers or {}, method=method) - try: - response = urllib.request.urlopen(request, timeout=timeout) - return response.status, response.read(4096).decode('utf-8', 'replace') - except urllib.error.HTTPError as error: - return error.code, '' - except Exception: - return 'unreachable', '' - -def imds_headers(): - status, token = http_status( - 'http://${METADATA_ADDRESS}/latest/api/token', - {'X-aws-ec2-metadata-token-ttl-seconds': '60'}, - 'PUT', - ) - return {'X-aws-ec2-metadata-token': token} if status == 200 and token else {} - -# What a metadata endpoint would hand user code: node identity and cloud credentials. Status codes -# only, never bodies. A runtime may answer on these addresses from inside the guest (Nitro's IMDSv2 -# surrogate serves region and zone only), so these, not reachability, are the boundary. -aws = imds_headers() -metadata_secrets = { - 'aws instance-id': http_status('http://${METADATA_ADDRESS}/latest/meta-data/instance-id', aws)[0], - 'aws user-data': http_status('http://${METADATA_ADDRESS}/latest/user-data', aws)[0], - 'aws iam credentials': http_status('http://${METADATA_ADDRESS}/latest/meta-data/iam/security-credentials/', aws)[0], - 'eks pod identity': http_status('http://169.254.170.23/v1/credentials')[0], - 'ecs task credentials': http_status('http://169.254.170.2/v2/credentials')[0], - 'gcp instance id': http_status('http://${METADATA_ADDRESS}/computeMetadata/v1/instance/id', {'Metadata-Flavor': 'Google'})[0], - 'azure instance': http_status('http://${METADATA_ADDRESS}/metadata/instance?api-version=2021-02-01', {'Metadata': 'true'})[0], - 'gcp service account token': http_status('http://${METADATA_ADDRESS}/computeMetadata/v1/instance/service-accounts/default/token', {'Metadata-Flavor': 'Google'})[0], - 'azure managed identity token': http_status('http://${METADATA_ADDRESS}/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/', {'Metadata': 'true'})[0], -} - -def owner(pid): - try: - for line in open('/proc/%s/status' % pid): - if line.startswith('Uid:'): - return int(line.split()[1]) - except OSError: - pass - return None - -root_agent_pids, readable_root_agent_environ, readable_environ, leaked_environ = [], [], [], [] -for path in glob.glob('/proc/[0-9]*/environ'): - pid = path.split('/')[2] - try: - cmdline = open('/proc/%s/cmdline' % pid, 'rb').read() - except OSError: - cmdline = b'' - is_root_agent = b'sim-sandbox-agent' in cmdline and owner(pid) == 0 - if is_root_agent: - root_agent_pids.append(pid) - try: - data = open(path, 'rb').read() - except OSError: - continue - if is_root_agent: - readable_root_agent_environ.append(pid) - readable_environ.append(pid) - if b'SIM_SANDBOX_' in data: - leaked_environ.append(pid) - -facts = { - 'uid': os.getuid(), - 'euid': os.geteuid(), - 'gid': os.getgid(), - 'home': os.path.expanduser('~'), - 'homeOwner': os.stat(os.path.expanduser('~')).st_uid, - 'ownEnvAgentKeys': sorted(k for k in os.environ if k.startswith('SIM_SANDBOX_')), - 'ownEnvKubernetesKeys': sorted(k for k in os.environ if k.startswith('KUBERNETES_')), - 'serviceAccountMounted': os.path.exists('/var/run/secrets/kubernetes.io/serviceaccount'), - 'rootAgentPids': root_agent_pids, - 'readableRootAgentEnviron': readable_root_agent_environ, - 'readableEnvironCount': len(readable_environ), - 'ownEnvironReadable': str(os.getpid()) in readable_environ, - 'leakedEnviron': leaked_environ, - 'agentWithoutToken': agent(None), - 'agentWithForgedToken': agent('forged-' + 'x' * 40), - 'api': {'%s:%d' % (h, p): api(h, p) for h, p in ${JSON.stringify(targets.apiTargets)}}, - 'metadata': reach('${METADATA_ADDRESS}', 80), - 'metadataSecrets': metadata_secrets, - 'denied': {'%s:%d' % (h, p): reach(h, p) for h, p in ${JSON.stringify(targets.deniedTargets)}}, - 'allowed': {'%s:%d' % (h, p): reach(h, p) for h, p in ${JSON.stringify(targets.allowedTargets)}}, -} -${pythonResult('facts')} -` -} - -interface SecurityFacts { - uid: number - euid: number - gid: number - home: string - homeOwner: number - ownEnvAgentKeys: string[] - ownEnvKubernetesKeys: string[] - serviceAccountMounted: boolean - rootAgentPids: string[] - readableRootAgentEnviron: string[] - readableEnvironCount: number - ownEnvironReadable: boolean - leakedEnviron: string[] - agentWithoutToken: number | string - agentWithForgedToken: number | string - api: Record - metadata: boolean - metadataSecrets: Record - denied: Record - allowed: Record -} - -function isSecurityFacts(value: unknown): value is SecurityFacts { - return ( - isRecordLike(value) && - typeof value.uid === 'number' && - Array.isArray(value.leakedEnviron) && - isRecordLike(value.api) && - isRecordLike(value.denied) && - isRecordLike(value.allowed) - ) -} - function parseTarget(target: string): [string, number] { const separator = target.lastIndexOf(':') const port = Number(target.slice(separator + 1)) @@ -1268,7 +1102,7 @@ describe.skipIf(!enabled)('kubernetes sandbox provider on a real cluster', () => const deniedHitsBefore = hostHits.denied const facts = await check('user-code confinement', async () => { const result = await executeInSandbox({ - code: securityProbe({ + code: confinementProbe({ apiTargets, deniedTargets, allowedTargets, @@ -1278,7 +1112,7 @@ describe.skipIf(!enabled)('kubernetes sandbox provider on a real cluster', () => timeoutMs: RUN_TIMEOUT_MS, }) expect(result.error).toBeUndefined() - if (!isSecurityFacts(result.result)) { + if (!isConfinementFacts(result.result)) { throw new Error(`Unexpected probe result: ${JSON.stringify(result.result)}`) } return result.result diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.test.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.test.ts new file mode 100644 index 00000000000..476e1ab24af --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest' +import { kubeApiPodsUrl } from '@/lib/execution/remote-sandbox/kubernetes/confinement-probe' + +describe('kubeApiPodsUrl', () => { + it('brackets an IPv6 API address, which would otherwise be read as host and port', () => { + expect(kubeApiPodsUrl('fd00:10:96::1', 443, 'sim-sandboxes')).toBe( + 'https://[fd00:10:96::1]:443/api/v1/namespaces/sim-sandboxes/pods' + ) + }) + + it('leaves IPv4 addresses and names as they are', () => { + expect(kubeApiPodsUrl('10.43.0.1', 6443, 'ns')).toBe( + 'https://10.43.0.1:6443/api/v1/namespaces/ns/pods' + ) + expect(kubeApiPodsUrl('kubernetes.default.svc', 443, 'ns')).toBe( + 'https://kubernetes.default.svc:443/api/v1/namespaces/ns/pods' + ) + }) +}) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts new file mode 100644 index 00000000000..cc25aeea268 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts @@ -0,0 +1,329 @@ +import { SANDBOX_AGENT_PORT } from '@sim/sandbox-agent-protocol' +import { isRecordLike } from '@sim/utils/object' +import { SIM_RESULT_PREFIX } from '@/lib/execution/remote-sandbox' + +const METADATA_ADDRESS = '169.254.169.254' +/** AWS's IMDS on its IPv6 address, served to Nitro instances with the IPv6 endpoint enabled. */ +const METADATA_ADDRESS_V6 = '[fd00:ec2::254]' + +/** + * Endpoints that would hand user code node identity or cloud credentials. `headers` is a Python + * expression: `aws` and `aws6` are the IMDSv2 token headers the probe fetches first, one per + * IMDS address. + */ +const METADATA_REQUESTS = [ + { + name: 'aws instance-id', + url: `http://${METADATA_ADDRESS}/latest/meta-data/instance-id`, + headers: 'aws', + }, + { name: 'aws user-data', url: `http://${METADATA_ADDRESS}/latest/user-data`, headers: 'aws' }, + { + name: 'aws iam credentials', + url: `http://${METADATA_ADDRESS}/latest/meta-data/iam/security-credentials/`, + headers: 'aws', + }, + { + name: 'aws iam credentials (ipv6)', + url: `http://${METADATA_ADDRESS_V6}/latest/meta-data/iam/security-credentials/`, + headers: 'aws6', + }, + { name: 'eks pod identity', url: 'http://169.254.170.23/v1/credentials', headers: 'None' }, + { name: 'ecs task credentials', url: 'http://169.254.170.2/v2/credentials', headers: 'None' }, + { + name: 'gcp instance id', + url: `http://${METADATA_ADDRESS}/computeMetadata/v1/instance/id`, + headers: "{'Metadata-Flavor': 'Google'}", + }, + { + name: 'azure instance', + url: `http://${METADATA_ADDRESS}/metadata/instance?api-version=2021-02-01`, + headers: "{'Metadata': 'true'}", + }, + { + name: 'gcp service account token', + url: `http://${METADATA_ADDRESS}/computeMetadata/v1/instance/service-accounts/default/token`, + headers: "{'Metadata-Flavor': 'Google'}", + }, + { + name: 'azure managed identity token', + url: `http://${METADATA_ADDRESS}/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/`, + headers: "{'Metadata': 'true'}", + }, +] as const + +/** The metadata endpoints every probe result reports on, by name. */ +export const METADATA_ENDPOINT_NAMES: readonly string[] = METADATA_REQUESTS.map(({ name }) => name) + +type Target = [host: string, port: number] + +interface ConfinementProbeTargets { + /** Kubernetes API endpoints: each is classified by what an unauthenticated pod list returns. */ + apiTargets: Target[] + /** Addresses user code must not open a TCP connection to. */ + deniedTargets: Target[] + /** Addresses user code must reach, the positive control for the denials. */ + allowedTargets: Target[] + /** Names user code resolves, the positive control that its network stack works at all. */ + resolveNames?: string[] + /** The sandbox namespace, whose pods the API probe tries to list. */ + namespace: string +} + +/** + * Python that runs as user code and reports what it can see and reach. Each probe classifies its + * own outcome so callers assert on facts, and every network probe runs concurrently so blackholed + * addresses cost one timeout rather than one per target. Status codes only, never bodies. + * Shared by the live provider suite and the app's self-check so both prove the same boundary. + */ +/** + * The pod-list URL the probe tries on one Kubernetes API endpoint. An IPv6 literal is bracketed, + * or the URL would read its last group as the port and the probe would report the API unreachable. + */ +export function kubeApiPodsUrl(host: string, port: number, namespace: string): string { + const authority = host.includes(':') ? `[${host}]` : host + return `https://${authority}:${port}/api/v1/namespaces/${encodeURIComponent(namespace)}/pods` +} + +export function confinementProbe(targets: ConfinementProbeTargets): string { + return ` +import glob, ipaddress, json, os, socket, ssl, urllib.error, urllib.request +from concurrent.futures import ThreadPoolExecutor + +def reach(host, port, timeout=4): + try: + socket.create_connection((host, port), timeout=timeout).close() + return True + except OSError: + return False + +# Not globally routable: private, shared (CGNAT), link-local, and loopback ranges all count, +# since pod and node networks use every one of them. +def private(host): + try: + return any( + not ipaddress.ip_address(info[4][0].split('%')[0]).is_global + for info in socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP) + ) + except (OSError, ValueError): + return False + +def resolves(name): + try: + return len(socket.getaddrinfo(name, None)) > 0 + except OSError: + return False + +# Every request goes direct: a proxy from the environment (HTTP_PROXY and the like) would answer +# for the target, so its refusal could hide a reachable metadata service or API. +_insecure = ssl.create_default_context() +_insecure.check_hostname = False +_insecure.verify_mode = ssl.CERT_NONE +direct = urllib.request.build_opener( + urllib.request.ProxyHandler({}), + urllib.request.HTTPSHandler(context=_insecure), +) + +def api(host, port, url): + if not reach(host, port): + return 'unreachable' + try: + direct.open(url, timeout=5) + return 200 + except urllib.error.HTTPError as error: + return error.code + except Exception: + return 'unreachable' + +def agent(token): + request = urllib.request.Request('http://127.0.0.1:${SANDBOX_AGENT_PORT}/v1/files/stat?path=/etc/hostname') + if token: + request.add_header('Authorization', 'Bearer ' + token) + try: + direct.open(request, timeout=5) + return 200 + except urllib.error.HTTPError as error: + return error.code + except Exception as error: + return 'error: %s' % error + +def http_status(url, headers=None, method='GET', timeout=4): + request = urllib.request.Request(url, headers=headers or {}, method=method) + try: + response = direct.open(request, timeout=timeout) + except urllib.error.HTTPError as error: + return error.code, '' + except Exception: + return 'unreachable', '' + # The status is the verdict; a body that fails to read must not hide a 200. + try: + return response.status, response.read(4096).decode('utf-8', 'replace') + except Exception: + return response.status, '' + +def imds_headers(address): + status, token = http_status( + 'http://%s/latest/api/token' % address, + {'X-aws-ec2-metadata-token-ttl-seconds': '60'}, + 'PUT', + ) + return {'X-aws-ec2-metadata-token': token} if status == 200 and token else {} + +def owner(pid): + try: + for line in open('/proc/%s/status' % pid): + if line.startswith('Uid:'): + return int(line.split()[1]) + except OSError: + pass + return None + +def key(host, port): + return '%s:%d' % (host, port) + +api_targets = ${JSON.stringify( + targets.apiTargets.map(([host, port]) => [ + host, + port, + kubeApiPodsUrl(host, port, targets.namespace), + ]) + )} +denied_targets = ${JSON.stringify(targets.deniedTargets)} +allowed_targets = ${JSON.stringify(targets.allowedTargets)} +resolve_names = ${JSON.stringify(targets.resolveNames ?? [])} + +with ThreadPoolExecutor(max_workers=32) as pool: + aws_token = pool.submit(imds_headers, '${METADATA_ADDRESS}') + aws6_token = pool.submit(imds_headers, '${METADATA_ADDRESS_V6}') + aws, aws6 = aws_token.result(), aws6_token.result() + # What a metadata endpoint would hand user code: node identity and cloud credentials. A + # runtime may answer on these addresses from inside the guest (Nitro's IMDSv2 surrogate + # serves region and zone only), so these, not reachability, are the boundary. + metadata_requests = { +${METADATA_REQUESTS.map( + ({ name, url, headers }) => + ` ${JSON.stringify(name)}: (${JSON.stringify(url)}, ${headers}),` +).join('\n')} + } + metadata_futures = {name: pool.submit(http_status, url, headers) for name, (url, headers) in metadata_requests.items()} + metadata_reach = pool.submit(reach, '${METADATA_ADDRESS}', 80) + api_futures = {key(h, p): pool.submit(api, h, p, u) for h, p, u in api_targets} + denied_futures = {key(h, p): pool.submit(reach, h, p) for h, p in denied_targets} + private_futures = {key(h, p): pool.submit(private, h) for h, p in denied_targets} + allowed_futures = {key(h, p): pool.submit(reach, h, p) for h, p in allowed_targets} + resolve_futures = {name: pool.submit(resolves, name) for name in resolve_names} + agent_without_token = pool.submit(agent, None) + agent_with_forged_token = pool.submit(agent, 'forged-' + 'x' * 40) + + root_agent_pids, readable_root_agent_environ, readable_environ, leaked_environ = [], [], [], [] + for path in glob.glob('/proc/[0-9]*/environ'): + pid = path.split('/')[2] + try: + cmdline = open('/proc/%s/cmdline' % pid, 'rb').read() + except OSError: + cmdline = b'' + is_root_agent = b'sim-sandbox-agent' in cmdline and owner(pid) == 0 + if is_root_agent: + root_agent_pids.append(pid) + try: + data = open(path, 'rb').read() + except OSError: + continue + if is_root_agent: + readable_root_agent_environ.append(pid) + readable_environ.append(pid) + if b'SIM_SANDBOX_' in data: + leaked_environ.append(pid) + + facts = { + 'uid': os.getuid(), + 'euid': os.geteuid(), + 'gid': os.getgid(), + 'home': os.path.expanduser('~'), + 'homeOwner': os.stat(os.path.expanduser('~')).st_uid, + 'ownEnvAgentKeys': sorted(k for k in os.environ if k.startswith('SIM_SANDBOX_')), + 'ownEnvKubernetesKeys': sorted(k for k in os.environ if k.startswith('KUBERNETES_')), + 'serviceAccountMounted': os.path.exists('/var/run/secrets/kubernetes.io/serviceaccount'), + 'rootAgentPids': root_agent_pids, + 'readableRootAgentEnviron': readable_root_agent_environ, + 'readableEnvironCount': len(readable_environ), + 'ownEnvironReadable': str(os.getpid()) in readable_environ, + 'leakedEnviron': leaked_environ, + 'agentWithoutToken': agent_without_token.result(), + 'agentWithForgedToken': agent_with_forged_token.result(), + 'api': {k: f.result() for k, f in api_futures.items()}, + 'metadata': metadata_reach.result(), + 'metadataSecrets': {k: f.result()[0] for k, f in metadata_futures.items()}, + 'denied': {k: f.result() for k, f in denied_futures.items()}, + 'deniedPrivate': {k: f.result() for k, f in private_futures.items()}, + 'allowed': {k: f.result() for k, f in allowed_futures.items()}, + 'resolved': {k: f.result() for k, f in resolve_futures.items()}, + } +print('${SIM_RESULT_PREFIX}' + json.dumps(facts)) +` +} + +export interface ConfinementFacts { + uid: number + euid: number + gid: number + home: string + homeOwner: number + ownEnvAgentKeys: string[] + ownEnvKubernetesKeys: string[] + serviceAccountMounted: boolean + rootAgentPids: string[] + readableRootAgentEnviron: string[] + readableEnvironCount: number + ownEnvironReadable: boolean + leakedEnviron: string[] + agentWithoutToken: number | string + agentWithForgedToken: number | string + /** Keyed `host:port`: `'unreachable'` or the HTTP status an unauthenticated pod list got. */ + api: Record + metadata: boolean + /** Keyed by endpoint name: `'unreachable'` or the HTTP status it answered with. */ + metadataSecrets: Record + /** Keyed `host:port`: whether a TCP connection opened. */ + denied: Record + /** Keyed `host:port`: whether the host resolves to an address that is not globally routable. */ + deniedPrivate: Record + allowed: Record + /** Keyed by name: whether it resolved. */ + resolved: Record +} + +export function isConfinementFacts(value: unknown): value is ConfinementFacts { + if (!isRecordLike(value)) return false + const numbers = ['uid', 'euid', 'gid'] as const + const booleans = ['serviceAccountMounted', 'ownEnvironReadable', 'metadata'] as const + const lists = [ + 'ownEnvAgentKeys', + 'ownEnvKubernetesKeys', + 'leakedEnviron', + 'readableRootAgentEnviron', + ] as const + const statuses = ['agentWithoutToken', 'agentWithForgedToken'] as const + const outcomeMaps = ['api', 'metadataSecrets'] as const + const flagMaps = ['denied', 'deniedPrivate', 'allowed', 'resolved'] as const + return ( + numbers.every((field) => typeof value[field] === 'number') && + booleans.every((field) => typeof value[field] === 'boolean') && + lists.every((field) => isStringList(value[field])) && + statuses.every((field) => isStatus(value[field])) && + outcomeMaps.every((field) => isMapOf(value[field], isStatus)) && + flagMaps.every((field) => isMapOf(value[field], (entry) => typeof entry === 'boolean')) + ) +} + +function isStatus(value: unknown): value is number | string { + return typeof value === 'number' || typeof value === 'string' +} + +function isStringList(value: unknown): value is string[] { + return Array.isArray(value) && value.every((entry) => typeof entry === 'string') +} + +function isMapOf(value: unknown, isEntry: (entry: unknown) => boolean): boolean { + return isRecordLike(value) && Object.values(value).every(isEntry) +} diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.ts index a2d151becbf..212a21c0208 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.ts @@ -149,6 +149,7 @@ export function createKubernetesSandboxProvider(): SandboxProvider { beforeLifetimeExtended: (expiresAtMs) => cluster.extendExpiresAt(name, expiresAtMs), ...(options.sessionKey !== undefined ? { sessionKey: options.sessionKey } : {}), ...(options.language ? { language: options.language } : {}), + ...(pod.status?.podIP ? { podAddress: pod.status.podIP } : {}), kill: () => cluster.deletePod(name), }) } diff --git a/apps/sim/lib/execution/remote-sandbox/types.ts b/apps/sim/lib/execution/remote-sandbox/types.ts index 169d3c2cc47..ac1309ac514 100644 --- a/apps/sim/lib/execution/remote-sandbox/types.ts +++ b/apps/sim/lib/execution/remote-sandbox/types.ts @@ -270,6 +270,11 @@ export interface RunCommandOptions { */ export interface SandboxHandle { readonly sandboxId: string + /** + * The sandbox pod's IP on the cluster network, for a provider that runs sandboxes as pods in + * this deployment's cluster (Kubernetes). The self-check probes it as another sandbox's peer. + */ + readonly podAddress?: string /** * Every command this session handle launches honors `verifyCli` inside its own owned process, * so a reused session needs no separate verification command. diff --git a/apps/sim/lib/self-check/confinement.test.ts b/apps/sim/lib/self-check/confinement.test.ts new file mode 100644 index 00000000000..07d36211c1a --- /dev/null +++ b/apps/sim/lib/self-check/confinement.test.ts @@ -0,0 +1,245 @@ +import { describe, expect, it } from 'vitest' +import { + type ConfinementFacts, + METADATA_ENDPOINT_NAMES, +} from '@/lib/execution/remote-sandbox/kubernetes/confinement-probe' +import { + type ConfinementPlan, + evaluateConfinement, + isProbeTargetAddress, + judgeProbeResult, +} from '@/lib/self-check/confinement' + +const APP = '10.42.0.7:3000' +const DATABASE = '10.43.0.12:5432' +const REDIS = '34.1.2.3:6379' +const NEIGHBOR = '10.42.0.9:49983' + +const plan: ConfinementPlan = { + lateral: [ + { key: APP, kind: 'app' }, + { key: DATABASE, kind: 'database' }, + { key: REDIS, kind: 'redis' }, + ], + neighbor: NEIGHBOR, + apiTargets: ['kubernetes.default.svc:443', '10.43.0.1:443'], + unresolved: [], + resolveNames: ['kubernetes.default.svc', 'example.com'], +} + +function confinedFacts(overrides: Partial = {}): ConfinementFacts { + return { + uid: 1000, + euid: 1000, + gid: 1000, + home: '/home/user', + homeOwner: 1000, + ownEnvAgentKeys: [], + ownEnvKubernetesKeys: [], + serviceAccountMounted: false, + rootAgentPids: ['1'], + readableRootAgentEnviron: [], + readableEnvironCount: 3, + ownEnvironReadable: true, + leakedEnviron: [], + agentWithoutToken: 401, + agentWithForgedToken: 401, + api: { 'kubernetes.default.svc:443': 'unreachable', '10.43.0.1:443': 'unreachable' }, + metadata: false, + metadataSecrets: Object.fromEntries( + METADATA_ENDPOINT_NAMES.map((name) => [name, 'unreachable']) + ), + denied: { [APP]: false, [DATABASE]: false, [REDIS]: false, [NEIGHBOR]: false }, + deniedPrivate: { [APP]: true, [DATABASE]: true, [REDIS]: false, [NEIGHBOR]: true }, + allowed: {}, + resolved: { 'kubernetes.default.svc': true, 'example.com': true }, + ...overrides, + } +} + +describe('evaluateConfinement', () => { + it('passes a sandbox that reaches nothing it should not', () => { + const outcomes = evaluateConfinement(confinedFacts(), plan) + expect(Object.values(outcomes).map((outcome) => outcome.status)).toEqual([ + 'pass', + 'pass', + 'pass', + 'pass', + 'pass', + ]) + }) + + it.each([ + ['refused with 401', 401, 'pass'], + ['refused with 403', 403, 'pass'], + ['listed pods', 200, 'fail'], + ['answered with another status', 500, 'fail'], + ] as const)('judges a Kubernetes API that %s', (_, outcome, status) => { + const facts = confinedFacts({ api: { 'kubernetes.default.svc:443': outcome } }) + expect(evaluateConfinement(facts, plan).kubeApi.status).toBe(status) + }) + + it('fails when a metadata endpoint serves credentials, not merely when it answers', () => { + const answering = confinedFacts({ + metadata: true, + metadataSecrets: { 'aws instance-id': 401, 'aws iam credentials': 404 }, + }) + expect(evaluateConfinement(answering, plan).metadata.status).toBe('pass') + + const serving = confinedFacts({ metadataSecrets: { 'aws iam credentials': 200 } }) + expect(evaluateConfinement(serving, plan).metadata).toEqual({ + status: 'fail', + detail: 'served: aws iam credentials', + }) + }) + + it('fails when user code reaches the app pod', () => { + const facts = confinedFacts({ denied: { ...confinedFacts().denied, [APP]: true } }) + expect(evaluateConfinement(facts, plan).lateral).toEqual({ + status: 'fail', + detail: 'app pod reachable', + }) + }) + + it('fails lateral isolation when a configured data store host did not resolve, so it went untested', () => { + const outcome = evaluateConfinement(confinedFacts(), { ...plan, unresolved: ['redis'] }) + expect(outcome.lateral).toEqual({ status: 'fail', detail: 'could not resolve redis host' }) + }) + + it('fails a data store reached at a private address and only warns at a public one', () => { + const privateDatabase = confinedFacts({ + denied: { ...confinedFacts().denied, [DATABASE]: true }, + }) + expect(evaluateConfinement(privateDatabase, plan).lateral.status).toBe('fail') + + const publicRedis = confinedFacts({ denied: { ...confinedFacts().denied, [REDIS]: true } }) + expect(evaluateConfinement(publicRedis, plan).lateral.status).toBe('warn') + }) + + it('does not pass lateral isolation when no name resolved either, since nothing proved the network works', () => { + const facts = confinedFacts({ + resolved: { 'kubernetes.default.svc': false, 'example.com': false }, + }) + expect(evaluateConfinement(facts, plan).lateral.status).toBe('warn') + }) + + it('passes lateral isolation when only a public name resolves, as with operator-supplied DNS', () => { + const facts = confinedFacts({ + resolved: { 'kubernetes.default.svc': false, 'example.com': true }, + }) + expect(evaluateConfinement(facts, plan).lateral).toEqual({ + status: 'pass', + detail: 'app pod and data stores unreachable (cluster DNS does not resolve from sandboxes)', + }) + }) + + it('fails when user code reaches a sibling sandbox agent, or the probe never tried', () => { + const reached = confinedFacts({ denied: { ...confinedFacts().denied, [NEIGHBOR]: true } }) + expect(evaluateConfinement(reached, plan).neighbor.status).toBe('fail') + + const { [NEIGHBOR]: _, ...untried } = confinedFacts().denied + expect(evaluateConfinement(confinedFacts({ denied: untried }), plan).neighbor.status).toBe( + 'fail' + ) + }) + + it('fails identity when code runs as root or sees the agent or cluster identity', () => { + for (const facts of [ + confinedFacts({ uid: 0, euid: 0 }), + confinedFacts({ ownEnvAgentKeys: ['SIM_SANDBOX_TOKEN'] }), + confinedFacts({ ownEnvKubernetesKeys: ['KUBERNETES_SERVICE_HOST'] }), + confinedFacts({ serviceAccountMounted: true }), + ]) { + expect(evaluateConfinement(facts, plan).identity.status).toBe('fail') + } + }) + + it('fails identity when another process environment leaks the agent secret', () => { + const facts = confinedFacts({ leakedEnviron: ['1'] }) + expect(evaluateConfinement(facts, plan).identity.status).toBe('fail') + }) + + it("fails identity when user code can read the root agent's environment", () => { + const facts = confinedFacts({ readableRootAgentEnviron: ['1'] }) + expect(evaluateConfinement(facts, plan).identity.status).toBe('fail') + }) + + it("fails identity when the environment scan could not read even the probe's own environment", () => { + const facts = confinedFacts({ ownEnvironReadable: false }) + expect(evaluateConfinement(facts, plan).identity.status).toBe('fail') + }) + + it.each([200, 404, 'error: refused'])( + 'fails identity when the agent answers a request without a token with %s', + (outcome) => { + const facts = confinedFacts({ agentWithoutToken: outcome }) + expect(evaluateConfinement(facts, plan).identity.status).toBe('fail') + } + ) + + it.each([200, 403])('fails identity when the agent answers a forged token with %s', (outcome) => { + const facts = confinedFacts({ agentWithForgedToken: outcome }) + expect(evaluateConfinement(facts, plan).identity.status).toBe('fail') + }) +}) + +describe('judgeProbeResult', () => { + it('judges a well-formed probe result', () => { + const judged = judgeProbeResult(confinedFacts(), plan) + expect(judged.execution.status).toBe('pass') + expect(judged.outcomes?.identity.status).toBe('pass') + }) + + it.each([ + ['no result', undefined], + ['a field the rules read is missing', { ...confinedFacts(), ownEnvAgentKeys: undefined }], + ['a field has the wrong type', { ...confinedFacts(), serviceAccountMounted: 'no' }], + ['a map holds the wrong type', { ...confinedFacts(), readableRootAgentEnviron: null }], + ])('fails the sandbox check rather than throwing when the probe returned %s', (_, value) => { + const judged = judgeProbeResult(value, plan) + expect(judged.execution.status).toBe('fail') + expect(judged.outcomes).toBeNull() + }) +}) + +describe('judgeProbeResult fails closed', () => { + it.each([ + ['a planned lateral target', 'denied', APP], + ["a planned lateral target's address class", 'deniedPrivate', DATABASE], + ['the neighbor', 'denied', NEIGHBOR], + ['a planned API target', 'api', 'kubernetes.default.svc:443'], + ['a metadata endpoint', 'metadataSecrets', 'aws iam credentials'], + ['a resolved name', 'resolved', 'example.com'], + ] as const)('fails the sandbox check when the result omits %s', (_, field, key) => { + const facts = confinedFacts() + const { [key]: _omitted, ...rest } = facts[field] as Record + const judged = judgeProbeResult({ ...facts, [field]: rest }, plan) + expect(judged.execution.status).toBe('fail') + expect(judged.outcomes).toBeNull() + }) +}) + +describe('isProbeTargetAddress', () => { + it.each([ + '127.0.0.1', + '::1', + '169.254.169.254', + 'fe80::1', + '::ffff:127.0.0.1', + '0.0.0.0', + '0:0:0:0:0:0:0:1', + '::', + 'FE80:0:0:0:0:0:0:1', + '::ffff:7f00:1', + '0:0:0:0:0:ffff:a9fe:a9fe', + ])('drops %s, which reaches the app pod itself or its sidecar rather than a peer', (address) => { + expect(isProbeTargetAddress(address)).toBe(false) + }) + + it.each(['10.43.0.12', 'fd00::12', '34.1.2.3', '::ffff:10.43.0.12', 'fe00::1'])( + 'keeps %s', + (address) => { + expect(isProbeTargetAddress(address)).toBe(true) + } + ) +}) diff --git a/apps/sim/lib/self-check/confinement.ts b/apps/sim/lib/self-check/confinement.ts new file mode 100644 index 00000000000..c7f1117881f --- /dev/null +++ b/apps/sim/lib/self-check/confinement.ts @@ -0,0 +1,200 @@ +import { BlockList, isIP } from 'node:net' +import { + type ConfinementFacts, + isConfinementFacts, + METADATA_ENDPOINT_NAMES, +} from '@/lib/execution/remote-sandbox/kubernetes/confinement-probe' +import type { CheckOutcome } from '@/lib/self-check/outcome' + +const SANDBOX_USER_ID = 1000 + +/** + * Loopback, unspecified, and link-local ranges, matched numerically so every spelling of an + * address (expanded IPv6, IPv4-mapped IPv6) is classified the same. + */ +const SELF_OR_NODE_LOCAL = new BlockList() +SELF_OR_NODE_LOCAL.addSubnet('127.0.0.0', 8, 'ipv4') +SELF_OR_NODE_LOCAL.addSubnet('169.254.0.0', 16, 'ipv4') +SELF_OR_NODE_LOCAL.addSubnet('0.0.0.0', 8, 'ipv4') +SELF_OR_NODE_LOCAL.addSubnet('::1', 128, 'ipv6') +SELF_OR_NODE_LOCAL.addSubnet('::', 128, 'ipv6') +SELF_OR_NODE_LOCAL.addSubnet('fe80::', 10, 'ipv6') +SELF_OR_NODE_LOCAL.addSubnet('::ffff:127.0.0.0', 104, 'ipv6') +SELF_OR_NODE_LOCAL.addSubnet('::ffff:169.254.0.0', 112, 'ipv6') +SELF_OR_NODE_LOCAL.addSubnet('::ffff:0.0.0.0', 104, 'ipv6') +/** What the sandbox agent answers a request without a valid token. */ +const AGENT_UNAUTHORIZED = 401 + +/** An unauthenticated pod list may be refused or never connect; anything else is a hole. */ +const ACCEPTED_API_OUTCOMES: ReadonlySet = new Set(['unreachable', 401, 403]) + +export type LateralTargetKind = 'app' | 'database' | 'redis' + +/** What the probe was asked to try, keyed as the probe keys its facts (`host:port`). */ +export interface ConfinementPlan { + lateral: Array<{ key: string; kind: LateralTargetKind }> + /** The sibling sandbox's agent address; the app reaching it is the positive control. */ + neighbor: string + /** The Kubernetes API endpoints the probe tried, keyed as in {@link ConfinementFacts.api}. */ + apiTargets: string[] + /** Configured data stores whose host the app could not resolve, so the probe never tried them. */ + unresolved: Array> + /** + * Names the probe resolves to show its network works, so unreachable means refused. The first + * is the cluster's own; any one resolving is enough, since an operator may point sandbox DNS + * at resolvers that do not serve cluster names. + */ + resolveNames: [clusterName: string, ...others: string[]] +} + +export interface ConfinementOutcomes { + identity: CheckOutcome + metadata: CheckOutcome + kubeApi: CheckOutcome + lateral: CheckOutcome + neighbor: CheckOutcome +} + +function identity(facts: ConfinementFacts): CheckOutcome { + const problems: string[] = [] + if (facts.uid !== SANDBOX_USER_ID || facts.euid !== SANDBOX_USER_ID) problems.push('uid') + if (facts.gid !== SANDBOX_USER_ID) problems.push('gid') + if (facts.ownEnvAgentKeys.length > 0) problems.push('agent env visible') + if (facts.ownEnvKubernetesKeys.length > 0) problems.push('kubernetes env visible') + if (facts.serviceAccountMounted) problems.push('service account mounted') + if (!facts.ownEnvironReadable) problems.push('environment scan did not run') + if (facts.leakedEnviron.length > 0) problems.push('agent secret in a process environment') + if (facts.readableRootAgentEnviron.length > 0) problems.push('agent environment readable') + if (facts.agentWithoutToken !== AGENT_UNAUTHORIZED) problems.push('agent accepts no token') + if (facts.agentWithForgedToken !== AGENT_UNAUTHORIZED) + problems.push('agent accepts a forged token') + return problems.length > 0 + ? { status: 'fail', detail: problems.join(', ') } + : { status: 'pass', detail: 'runs as the sandbox user with no agent or cluster identity' } +} + +function metadata(facts: ConfinementFacts): CheckOutcome { + const served = Object.entries(facts.metadataSecrets) + .filter(([, status]) => status === 200) + .map(([endpoint]) => endpoint) + return served.length > 0 + ? { status: 'fail', detail: `served: ${served.join(', ')}` } + : { status: 'pass', detail: 'no endpoint served identity or credentials' } +} + +function kubeApi(facts: ConfinementFacts): CheckOutcome { + const outcomes = Object.values(facts.api) + const open = outcomes.filter((outcome) => !ACCEPTED_API_OUTCOMES.has(outcome)) + if (open.length > 0) { + return { + status: 'fail', + detail: open.includes(200) ? 'listed sandbox pods' : `answered ${open.join(', ')}`, + } + } + return outcomes.every((outcome) => outcome === 'unreachable') + ? { status: 'pass', detail: 'unreachable' } + : { status: 'pass', detail: 'refused unauthenticated requests' } +} + +function lateral(facts: ConfinementFacts, plan: ConfinementPlan): CheckOutcome { + const failures: string[] = [] + const warnings: string[] = [] + for (const { key, kind } of plan.lateral) { + if (facts.denied[key] !== true) continue + if (kind === 'app') failures.push('app pod reachable') + else if (facts.deniedPrivate[key] === true) + failures.push(`${kind} reachable at a private address`) + else warnings.push(`${kind} reachable at a public address`) + } + for (const kind of new Set(plan.unresolved)) failures.push(`could not resolve ${kind} host`) + if (failures.length > 0) return { status: 'fail', detail: failures.join(', ') } + if (warnings.length > 0) return { status: 'warn', detail: warnings.join(', ') } + if (!plan.resolveNames.some((name) => facts.resolved[name] === true)) { + return { + status: 'warn', + detail: 'unreachable, but no name resolved either, so the denial is unproven', + } + } + if (!plan.lateral.some((target) => target.kind === 'app')) { + return { status: 'warn', detail: 'no app pod address to probe' } + } + return facts.resolved[plan.resolveNames[0]] === true + ? { status: 'pass', detail: 'app pod and data stores unreachable' } + : { + status: 'pass', + detail: 'app pod and data stores unreachable (cluster DNS does not resolve from sandboxes)', + } +} + +function neighbor(facts: ConfinementFacts, plan: ConfinementPlan): CheckOutcome { + return facts.denied[plan.neighbor] === false + ? { status: 'pass', detail: 'sibling sandbox agent unreachable' } + : { status: 'fail', detail: 'sibling sandbox agent reachable' } +} + +/** + * Judges what user code saw against what the sandbox design promises it: the sandbox user with no + * agent or cluster identity, no metadata credentials, no authorized Kubernetes API, and no reach + * into the app, its private data stores, or another sandbox. + */ +export function evaluateConfinement( + facts: ConfinementFacts, + plan: ConfinementPlan +): ConfinementOutcomes { + return { + identity: identity(facts), + metadata: metadata(facts), + kubeApi: kubeApi(facts), + lateral: lateral(facts, plan), + neighbor: neighbor(facts, plan), + } +} + +/** + * Whether the result reports on everything the plan asked for. The rules read a missing entry as + * unreachable or unserved, so a probe that skipped a target would otherwise pass it. + */ +function coversPlan(facts: ConfinementFacts, plan: ConfinementPlan): boolean { + const deniedKeys = [...plan.lateral.map(({ key }) => key), plan.neighbor] + return ( + deniedKeys.every((key) => key in facts.denied && key in facts.deniedPrivate) && + plan.apiTargets.every((key) => key in facts.api) && + plan.resolveNames.every((name) => name in facts.resolved) && + METADATA_ENDPOINT_NAMES.every((name) => name in facts.metadataSecrets) + ) +} + +/** + * Judges the probe's raw result. A result that is not the full set of facts the rules read, or + * that omits a planned target, fails the sandbox check, so a changed or truncated probe never + * turns the self-check into a 500 or a pass. + */ +export function judgeProbeResult( + value: unknown, + plan: ConfinementPlan +): { execution: CheckOutcome; outcomes: ConfinementOutcomes | null } { + if (!isConfinementFacts(value)) { + return { execution: { status: 'fail', detail: 'the probe returned no result' }, outcomes: null } + } + if (!coversPlan(value, plan)) { + return { + execution: { status: 'fail', detail: 'the probe result omits a planned target' }, + outcomes: null, + } + } + return { + execution: { status: 'pass', detail: 'ran user code' }, + outcomes: evaluateConfinement(value, plan), + } +} + +/** + * Whether an address names a peer worth probing. Loopback, unspecified, and link-local addresses + * reach the sandbox itself or a node-local service (a database sidecar proxy, the metadata + * endpoint), not the app or its data stores, so they prove nothing either way. + */ +export function isProbeTargetAddress(address: string): boolean { + const family = isIP(address) + if (family === 0) return false + return !SELF_OR_NODE_LOCAL.check(address, family === 4 ? 'ipv4' : 'ipv6') +} diff --git a/apps/sim/lib/self-check/infrastructure.test.ts b/apps/sim/lib/self-check/infrastructure.test.ts new file mode 100644 index 00000000000..98ced975e88 --- /dev/null +++ b/apps/sim/lib/self-check/infrastructure.test.ts @@ -0,0 +1,21 @@ +import { resetUrlsMock, urlsMockFns } from '@sim/testing/mocks/urls.mock' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { checkRealtime } from '@/lib/self-check/infrastructure' + +// The shared Vitest config restores the stubbed fetch after every test (unstubGlobals). +afterEach(() => { + resetUrlsMock() +}) + +describe('checkRealtime', () => { + it('asks a SOCKET_SERVER_URL with a trailing slash for /health, not //health', async () => { + urlsMockFns.mockGetSocketServerUrl.mockReturnValueOnce('http://sim-realtime:3002//') + const fetch = vi.fn(async (url: string) => + url === 'http://sim-realtime:3002/health' + ? new Response('ok', { status: 200 }) + : new Response('not found', { status: 404 }) + ) + vi.stubGlobal('fetch', fetch) + expect(await checkRealtime()).toMatchObject({ name: 'realtime', status: 'pass' }) + }) +}) diff --git a/apps/sim/lib/self-check/infrastructure.ts b/apps/sim/lib/self-check/infrastructure.ts new file mode 100644 index 00000000000..ab1ab1d7a0a --- /dev/null +++ b/apps/sim/lib/self-check/infrastructure.ts @@ -0,0 +1,72 @@ +import { db } from '@sim/db' +import journal from '@sim/db/migrations/meta/_journal.json' +import { getPostgresErrorCode } from '@sim/utils/errors' +import { sql } from 'drizzle-orm' +import { env } from '@/lib/core/config/env' +import { getRedisClient } from '@/lib/core/config/redis' +import { getSocketServerUrl } from '@/lib/core/utils/urls' +import { timed, untilAborted } from '@/lib/self-check/outcome' +import type { SelfCheckResult } from '@/lib/self-check/types' + +const DATABASE_TIMEOUT_MS = 5_000 +const REDIS_TIMEOUT_MS = 5_000 +const REALTIME_TIMEOUT_MS = 5_000 + +/** PostgreSQL's insufficient_privilege: the app's role may not read Drizzle's bookkeeping. */ +const PG_INSUFFICIENT_PRIVILEGE = '42501' + +export function checkDatabase(): Promise { + return timed('database', async () => { + await untilAborted(db.execute(sql`select 1`), AbortSignal.timeout(DATABASE_TIMEOUT_MS)) + return { status: 'pass', detail: 'connected' } + }) +} + +/** + * Compares the newest migration this build ships with the newest one applied. Drizzle records + * each applied migration's journal `when` as `created_at`, so the two maxima line up exactly. + */ +export function checkMigrations(): Promise { + return timed('migrations', async () => { + const expected = Math.max(...journal.entries.map((entry) => entry.when)) + let applied: number + try { + const [row] = await untilAborted( + db.execute<{ latest: string | number | null }>( + sql`select max(created_at) as latest from drizzle.__drizzle_migrations` + ), + AbortSignal.timeout(DATABASE_TIMEOUT_MS) + ) + applied = Number(row?.latest ?? 0) + } catch (error) { + if (getPostgresErrorCode(error) === PG_INSUFFICIENT_PRIVILEGE) { + return { status: 'warn', detail: 'cannot read the migrations table: 42501' } + } + throw error + } + if (applied < expected) return { status: 'fail', detail: 'database is behind this build' } + if (applied > expected) return { status: 'warn', detail: 'database is ahead of this build' } + return { status: 'pass', detail: 'up to date' } + }) +} + +export function checkRedis(): Promise { + return timed('redis', async () => { + // Redis is required: the app refuses to start without it, so an unset URL is a failure. + if (!env.REDIS_URL) return { status: 'fail', detail: 'REDIS_URL is not set' } + await untilAborted(getRedisClient().ping(), AbortSignal.timeout(REDIS_TIMEOUT_MS)) + return { status: 'pass', detail: 'ping answered' } + }) +} + +export function checkRealtime(): Promise { + return timed('realtime', async () => { + const response = await fetch(`${getSocketServerUrl().replace(/\/+$/, '')}/health`, { + signal: AbortSignal.timeout(REALTIME_TIMEOUT_MS), + }) + await response.body?.cancel() + return response.ok + ? { status: 'pass', detail: 'health answered' } + : { status: 'fail', detail: `health returned ${response.status}` } + }) +} diff --git a/apps/sim/lib/self-check/outcome.ts b/apps/sim/lib/self-check/outcome.ts new file mode 100644 index 00000000000..d02d38e0063 --- /dev/null +++ b/apps/sim/lib/self-check/outcome.ts @@ -0,0 +1,60 @@ +import { createLogger } from '@sim/logger' +import { getErrorMessage, getPostgresErrorCode } from '@sim/utils/errors' +import type { SelfCheckName, SelfCheckResult, SelfCheckStatus } from '@/lib/self-check/types' + +const logger = createLogger('SelfCheck') + +const SAFE_CODE_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/ + +/** + * A short, non-sensitive identifier for a failure: the PostgreSQL or Node error code, else the + * error's class name. Never the message, which can carry hosts, URLs, or credentials. + */ +function errorCode(error: unknown): string { + const code = getPostgresErrorCode(error) + if (code && SAFE_CODE_PATTERN.test(code)) return code + if (error instanceof Error && SAFE_CODE_PATTERN.test(error.name)) return error.name + return 'unknown' +} + +export interface CheckOutcome { + status: SelfCheckStatus + detail: string +} + +/** + * A failed check's outcome. The message goes to the app log only: the report is returned over + * HTTP, so it names the error's code and points there. + */ +export function failedWith(check: SelfCheckName, error: unknown): CheckOutcome { + logger.warn('Self-check failed', { check, error: getErrorMessage(error) }) + return { status: 'fail', detail: `error: ${errorCode(error)}; see app logs` } +} + +/** Runs one check, timing it and turning a throw into a failure that names only its code. */ +export async function timed( + name: SelfCheckName, + run: () => Promise +): Promise { + const startedAt = performance.now() + let outcome: CheckOutcome + try { + outcome = await run() + } catch (error) { + outcome = failedWith(name, error) + } + return { name, ...outcome, durationMs: Math.round(performance.now() - startedAt) } +} + +/** + * Settles with `work`, or rejects with the signal's reason once it aborts (a `TimeoutError` for + * `AbortSignal.timeout`). The work itself is left to settle on its own. + */ +export function untilAborted(work: Promise, signal: AbortSignal): Promise { + if (signal.aborted) return Promise.reject(signal.reason) + return new Promise((resolve, reject) => { + const onAbort = () => reject(signal.reason) + signal.addEventListener('abort', onAbort, { once: true }) + work.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort)) + }) +} diff --git a/apps/sim/lib/self-check/run.ts b/apps/sim/lib/self-check/run.ts new file mode 100644 index 00000000000..a241873057f --- /dev/null +++ b/apps/sim/lib/self-check/run.ts @@ -0,0 +1,65 @@ +import { createLogger } from '@sim/logger' +import { + checkDatabase, + checkMigrations, + checkRealtime, + checkRedis, +} from '@/lib/self-check/infrastructure' +import { failedWith } from '@/lib/self-check/outcome' +import { checkSandbox } from '@/lib/self-check/sandbox' +import type { SelfCheckReport, SelfCheckResult } from '@/lib/self-check/types' + +const logger = createLogger('SelfCheck') + +interface SelfCheckOptions { + sandbox: boolean + realtime: boolean +} + +/** The sandbox run in progress: concurrent callers share it rather than stack sandbox starts. */ +let sandboxRun: Promise | null = null + +function sandboxChecks(): Promise { + if (sandboxRun) return sandboxRun + // checkSandbox reports its own failures; this catches a throw it did not anticipate, so the + // report says so instead of the route answering 500. + const running = checkSandbox() + .catch((error): SelfCheckResult[] => [ + { name: 'sandbox.execution', durationMs: 0, ...failedWith('sandbox.execution', error) }, + ]) + .finally(() => { + sandboxRun = null + }) + sandboxRun = running + return running +} + +/** + * Checks that this deployment works end to end: the database is reachable and migrated, Redis + * answers, and, when asked, realtime is up and a sandbox runs user code confined. Every check + * bounds itself; no caller's request signal governs a sandbox run others may be waiting on. + */ +export async function runSelfCheck(options: SelfCheckOptions): Promise { + const groups = await Promise.all([ + checkDatabase().then((database) => [database]), + checkMigrations().then((migrations) => [migrations]), + checkRedis().then((redis) => [redis]), + options.realtime + ? checkRealtime().then((realtime) => [realtime]) + : Promise.resolve([ + { name: 'realtime', status: 'skip', durationMs: 0, detail: 'not requested' }, + ]), + options.sandbox + ? sandboxChecks() + : Promise.resolve([ + { name: 'sandbox.execution', status: 'skip', durationMs: 0, detail: 'not requested' }, + ]), + ]) + const checks = groups.flat() + const report = { ok: checks.every((check) => check.status !== 'fail'), checks } + logger.info('Self-check completed', { + ok: report.ok, + failed: checks.filter((check) => check.status === 'fail').map((check) => check.name), + }) + return report +} diff --git a/apps/sim/lib/self-check/sandbox.ts b/apps/sim/lib/self-check/sandbox.ts new file mode 100644 index 00000000000..bfcb7f518d7 --- /dev/null +++ b/apps/sim/lib/self-check/sandbox.ts @@ -0,0 +1,233 @@ +import { lookup } from 'node:dns/promises' +import { isIP } from 'node:net' +import { networkInterfaces } from 'node:os' +import { SANDBOX_AGENT_PORT } from '@sim/sandbox-agent-protocol' +import { env, envNumber } from '@/lib/core/config/env' +import { getSelectedSandboxProviderId } from '@/lib/core/config/env-capabilities.server' +import { CodeLanguage } from '@/lib/execution/languages' +import { executeInSandbox } from '@/lib/execution/remote-sandbox' +import { findSandboxCapacityError } from '@/lib/execution/remote-sandbox/capacity-error' +import { confinementProbe } from '@/lib/execution/remote-sandbox/kubernetes/confinement-probe' +import { readKubernetesSandboxSettings } from '@/lib/execution/remote-sandbox/kubernetes/settings' +import { resolveProvider } from '@/lib/execution/remote-sandbox/provider' +import type { SandboxHandle } from '@/lib/execution/remote-sandbox/types' +import { + type ConfinementPlan, + isProbeTargetAddress, + judgeProbeResult, + type LateralTargetKind, +} from '@/lib/self-check/confinement' +import { type CheckOutcome, failedWith, untilAborted } from '@/lib/self-check/outcome' +import { dataStoreEndpoints } from '@/lib/self-check/targets' +import type { SelfCheckName, SelfCheckResult } from '@/lib/self-check/types' + +/** Two sandbox starts and one probe, inside the route's `maxDuration`. */ +const SANDBOX_BUDGET_MS = 150_000 +/** Outlives the budget, so the pod deadline reaps the neighbor even if its delete is lost. */ +const NEIGHBOR_LIFETIME_MS = 4 * 60_000 +const DEFAULT_APP_PORT = 3000 +/** The cluster's API Service name, probed as an API target and resolved as the positive control. */ +const CLUSTER_API_NAME = 'kubernetes.default.svc' +/** + * Resolved by user code to show its network stack works, so an unreachable target was refused. + * The public name stands in when operator-supplied sandbox DNS does not serve cluster names. + */ +const RESOLVE_NAMES: ConfinementPlan['resolveNames'] = [CLUSTER_API_NAME, 'example.com'] + +const DERIVED_CHECKS = [ + 'sandbox.identity', + 'sandbox.metadata', + 'sandbox.kubeApi', + 'sandbox.lateral', + 'sandbox.neighbor', +] as const satisfies readonly SelfCheckName[] + +type Target = [string, number] + +function key([host, port]: Target): string { + return `${host}:${port}` +} + +/** This pod's routable addresses: the app's own, which user code must not reach. */ +function appAddresses(): string[] { + return Object.values(networkInterfaces()) + .flatMap((addresses) => addresses ?? []) + .filter((address) => !address.internal) + .map((address) => address.address) + .filter(isProbeTargetAddress) +} + +/** + * Every database and Redis address the app is configured with, resolved as the app resolves them + * (user code runs in another namespace, where short Service names do not resolve), each once. A + * host that does not resolve is reported, never dropped: the probe could not try it. + */ +async function dataStoreTargets(): Promise<{ + targets: Array<{ target: Target; kind: LateralTargetKind }> + unresolved: ConfinementPlan['unresolved'] +}> { + const unresolved: ConfinementPlan['unresolved'] = [] + const resolved = await Promise.all( + dataStoreEndpoints(process.env).map(async ({ kind, host, port }) => { + const addresses = isIP(host) + ? [host] + : (await lookup(host, { all: true }).catch(() => [])).map(({ address }) => address) + if (addresses.length === 0) unresolved.push(kind) + // A loopback or link-local address is a sidecar proxy in the app pod, not the data store. + return addresses + .filter(isProbeTargetAddress) + .map((address) => ({ target: [address, port] as Target, kind })) + }) + ) + const seen = new Set() + const targets = resolved.flat().filter(({ target }) => { + if (seen.has(key(target))) return false + seen.add(key(target)) + return true + }) + return { targets, unresolved } +} + +/** + * Starts a sibling sandbox and takes its pod address. Its create returns only once the app has + * reached its agent, which is the positive control: the agent listens and an allowed peer gets + * through, so a probe that cannot connect was refused by policy. + */ +async function startNeighbor( + signal: AbortSignal +): Promise<{ handle: SandboxHandle; address: string }> { + const creating = resolveProvider().create('code', { + language: CodeLanguage.Python, + lifetimeMs: NEIGHBOR_LIFETIME_MS, + }) + let handle: SandboxHandle + try { + handle = await untilAborted(creating, signal) + } catch (error) { + // A create still running at the deadline leaves a pod behind once it lands. + creating.then( + (late) => late.kill().catch(() => {}), + () => {} + ) + throw error + } + const address = handle.podAddress + if (!address || isIP(address) === 0) { + await handle.kill().catch(() => {}) + throw Object.assign(new Error('Neighbor sandbox has no pod address'), { + name: 'NeighborAddressError', + }) + } + return { handle, address } +} + +function result(name: SelfCheckName, outcome: CheckOutcome, durationMs = 0): SelfCheckResult { + return { name, ...outcome, durationMs } +} + +function failedToRun(outcome: CheckOutcome, durationMs: number): SelfCheckResult[] { + return [ + result('sandbox.execution', outcome, durationMs), + ...DERIVED_CHECKS.map((name) => + result(name, { status: 'skip', detail: 'the sandbox did not run' }) + ), + ] +} + +function failure(error: unknown): CheckOutcome { + if (findSandboxCapacityError(error)) { + return { ...failedWith('sandbox.execution', error), detail: 'capacity; see app logs' } + } + return failedWith('sandbox.execution', error) +} + +/** + * Runs user code in a sandbox, as a Function block would, and judges its confinement + * ({@link evaluateConfinement}). Kubernetes provider only: hosted providers bill per sandbox and + * isolate outside this deployment. + */ +export async function checkSandbox(): Promise { + const startedAt = performance.now() + const elapsed = () => Math.round(performance.now() - startedAt) + let namespace: string + try { + if (getSelectedSandboxProviderId() !== 'kubernetes') { + return ['sandbox.execution' as const, ...DERIVED_CHECKS].map((name) => + result(name, { status: 'skip', detail: 'provider is not kubernetes' }) + ) + } + namespace = readKubernetesSandboxSettings(env).namespace + } catch (error) { + return failedToRun(failure(error), elapsed()) + } + + const signal = AbortSignal.timeout(SANDBOX_BUDGET_MS) + let neighbor: { handle: SandboxHandle; address: string } + try { + neighbor = await startNeighbor(signal) + } catch (error) { + return failedToRun(failure(error), elapsed()) + } + + try { + return await probe(namespace, neighbor.address, signal, elapsed) + } catch (error) { + return failedToRun(failure(error), elapsed()) + } finally { + await neighbor.handle.kill().catch(() => {}) + } +} + +async function probe( + namespace: string, + neighborAddress: string, + signal: AbortSignal, + elapsed: () => number +): Promise { + const appPort = envNumber(env.PORT, DEFAULT_APP_PORT, { min: 1, integer: true }) + const dataStores = await dataStoreTargets() + const lateral: Array<{ target: Target; kind: LateralTargetKind }> = [ + ...appAddresses().map((host) => ({ target: [host, appPort] as Target, kind: 'app' as const })), + ...dataStores.targets, + ] + const neighborTarget: Target = [neighborAddress, SANDBOX_AGENT_PORT] + const apiTargets: Target[] = [[CLUSTER_API_NAME, 443]] + const serviceHost = process.env.KUBERNETES_SERVICE_HOST + const servicePort = Number(process.env.KUBERNETES_SERVICE_PORT) || 443 + if (serviceHost && isIP(serviceHost)) apiTargets.push([serviceHost, servicePort]) + + const execution = await executeInSandbox({ + code: confinementProbe({ + apiTargets, + deniedTargets: [...lateral.map(({ target }) => target), neighborTarget], + allowedTargets: [], + resolveNames: [...RESOLVE_NAMES], + namespace, + }), + language: CodeLanguage.Python, + timeoutMs: Math.max(1, SANDBOX_BUDGET_MS - elapsed()), + signal, + }) + if (execution.error) { + return failedToRun({ status: 'fail', detail: 'the probe exited with an error' }, elapsed()) + } + + const plan: ConfinementPlan = { + lateral: lateral.map(({ target, kind }) => ({ key: key(target), kind })), + neighbor: key(neighborTarget), + apiTargets: apiTargets.map(key), + unresolved: dataStores.unresolved, + resolveNames: RESOLVE_NAMES, + } + const judged = judgeProbeResult(execution.result, plan) + if (!judged.outcomes) return failedToRun(judged.execution, elapsed()) + const { outcomes } = judged + return [ + result('sandbox.execution', judged.execution, elapsed()), + result('sandbox.identity', outcomes.identity), + result('sandbox.metadata', outcomes.metadata), + result('sandbox.kubeApi', outcomes.kubeApi), + result('sandbox.lateral', outcomes.lateral), + result('sandbox.neighbor', outcomes.neighbor), + ] +} diff --git a/apps/sim/lib/self-check/targets.test.ts b/apps/sim/lib/self-check/targets.test.ts new file mode 100644 index 00000000000..2f8daed1155 --- /dev/null +++ b/apps/sim/lib/self-check/targets.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from 'vitest' +import { dataStoreEndpoints } from '@/lib/self-check/targets' + +describe('dataStoreEndpoints', () => { + it('lists every database endpoint @sim/db may open: primary, every pool, and process-role replicas', () => { + expect( + dataStoreEndpoints({ + DATABASE_URL: 'postgresql://u:p@primary.internal:5432/sim', + DATABASE_REPLICA_URL: 'postgresql://u:p@replica.internal/sim', + DATABASE_URL_SEARCH: 'postgresql://u:p@search-bouncer.internal:6432/sim', + DATABASE_URL_AUTH: 'postgresql://u:p@auth-bouncer.internal:6432/sim', + DATABASE_REPLICA_URL_TRIGGER: 'postgresql://u:p@[fd00::7]:5433/sim', + REDIS_URL: 'rediss://cache.internal:6380', + }) + ).toEqual( + expect.arrayContaining([ + { kind: 'database', host: 'primary.internal', port: 5432 }, + { kind: 'database', host: 'replica.internal', port: 5432 }, + { kind: 'database', host: 'search-bouncer.internal', port: 6432 }, + { kind: 'database', host: 'auth-bouncer.internal', port: 6432 }, + { kind: 'database', host: 'fd00::7', port: 5433 }, + { kind: 'redis', host: 'cache.internal', port: 6380 }, + ]) + ) + }) + + it('ignores a replica override for a pool @sim/db never reads one for', () => { + expect( + dataStoreEndpoints({ + DATABASE_URL: 'postgresql://u:p@db.internal/sim', + DATABASE_REPLICA_URL_EXEC: 'postgresql://u:p@unused.internal/sim', + }) + ).toEqual([{ kind: 'database', host: 'db.internal', port: 5432 }]) + }) + + it('lists an endpoint shared by several variables once', () => { + expect( + dataStoreEndpoints({ + DATABASE_URL: 'postgresql://u:p@db.internal:5432/sim', + DATABASE_URL_WEB: 'postgresql://other:p@db.internal/sim_web', + DATABASE_REPLICA_URL: 'postgresql://u:p@db.internal:5432/sim', + }) + ).toEqual([{ kind: 'database', host: 'db.internal', port: 5432 }]) + }) + + it('skips unset and unparsable values', () => { + expect(dataStoreEndpoints({ DATABASE_URL: 'not a url', REDIS_URL: undefined })).toEqual([]) + }) +}) diff --git a/apps/sim/lib/self-check/targets.ts b/apps/sim/lib/self-check/targets.ts new file mode 100644 index 00000000000..bc287e57c4e --- /dev/null +++ b/apps/sim/lib/self-check/targets.ts @@ -0,0 +1,62 @@ +import { DB_POOL_PROFILES } from '@sim/db/pool-profiles' + +/** Roles a whole process runs as (`SIM_DB_ROLE`); only these read a role-keyed replica URL. */ +const PROCESS_ROLES = ['web', 'trigger', 'realtime'] as const + +/** + * Every variable `@sim/db` may open a connection from, derived as it derives them: the primary + * and replica, `DATABASE_URL_` for every pool profile, and `DATABASE_REPLICA_URL_` for + * the process roles. A new pool profile is covered without touching this file. + */ +const DATABASE_URL_NAMES = [ + 'DATABASE_URL', + 'DATABASE_REPLICA_URL', + ...Object.keys(DB_POOL_PROFILES).map((role) => `DATABASE_URL_${role.toUpperCase()}`), + ...PROCESS_ROLES.map((role) => `DATABASE_REPLICA_URL_${role.toUpperCase()}`), +] + +const DEFAULT_PORTS = { database: 5432, redis: 6379 } as const + +interface DataStoreEndpoint { + kind: keyof typeof DEFAULT_PORTS + host: string + port: number +} + +function endpoint( + kind: DataStoreEndpoint['kind'], + url: string | undefined +): DataStoreEndpoint | null { + if (!url) return null + let parsed: URL + try { + parsed = new URL(url) + } catch { + return null + } + const host = parsed.hostname.replace(/^\[|\]$/g, '') + if (!host) return null + return { kind, host, port: Number(parsed.port) || DEFAULT_PORTS[kind] } +} + +/** + * The database and Redis endpoints the app is configured with, each once, read from the same + * process environment `@sim/db` reads. Hosts stay unresolved: + * the caller resolves them as the app does, since user code runs in another namespace. + */ +export function dataStoreEndpoints( + values: Readonly> +): DataStoreEndpoint[] { + const found = [ + ...DATABASE_URL_NAMES.map((name) => endpoint('database', values[name])), + endpoint('redis', values.REDIS_URL), + ] + const seen = new Set() + return found.filter((entry): entry is DataStoreEndpoint => { + if (!entry) return false + const key = `${entry.kind}:${entry.host}:${entry.port}` + if (seen.has(key)) return false + seen.add(key) + return true + }) +} diff --git a/apps/sim/lib/self-check/types.ts b/apps/sim/lib/self-check/types.ts new file mode 100644 index 00000000000..c1e2c6c1495 --- /dev/null +++ b/apps/sim/lib/self-check/types.ts @@ -0,0 +1,34 @@ +export const SELF_CHECK_NAMES = [ + 'database', + 'migrations', + 'redis', + 'realtime', + 'sandbox.execution', + 'sandbox.identity', + 'sandbox.metadata', + 'sandbox.kubeApi', + 'sandbox.lateral', + 'sandbox.neighbor', +] as const + +export const SELF_CHECK_STATUSES = ['pass', 'fail', 'warn', 'skip'] as const + +export type SelfCheckName = (typeof SELF_CHECK_NAMES)[number] +export type SelfCheckStatus = (typeof SELF_CHECK_STATUSES)[number] + +/** + * One check's outcome. `detail` is a fixed phrase plus, on failure, an error code or name: never + * an error message, host, URL, or credential, because the report is returned over HTTP. + */ +export interface SelfCheckResult { + name: SelfCheckName + status: SelfCheckStatus + durationMs: number + detail: string +} + +export interface SelfCheckReport { + /** False when any check failed; a warning or a skip leaves it true. */ + ok: boolean + checks: SelfCheckResult[] +} diff --git a/helm/sim/Chart.yaml b/helm/sim/Chart.yaml index 2fa06122346..58c4d257c85 100644 --- a/helm/sim/Chart.yaml +++ b/helm/sim/Chart.yaml @@ -2,7 +2,7 @@ apiVersion: v2 name: sim description: A Helm chart for Sim - the open-source AI workspace where teams build, deploy, and manage AI agents type: application -version: 1.21.0 +version: 1.22.0 appVersion: "v0.8.26" kubeVersion: ">=1.25.0-0" home: https://sim.ai diff --git a/helm/sim/README.md b/helm/sim/README.md index 6289c27847c..2c78cafc5ed 100644 --- a/helm/sim/README.md +++ b/helm/sim/README.md @@ -164,11 +164,13 @@ yq -r '.images[] | .source + " " + .mirror' images.yaml | `crane copy` keeps every architecture and the original digests. Then install with `global.imageRegistry=$REGISTRY` and `global.useRegistryForAllImages=true`, -and pin each image's `digest` to what your mirror resolved. Skip `busybox` -(used only by `helm test`) and `simstudioai/copilot` (enterprise) if you do not -use them. The Mothership's entry carries the placeholder tag `main-REPLACE`: -substitute the `main-` tag from its release notes before copying; the header of `images.yaml` explains both, and the one image whose -mirror path differs. +and pin each image's `digest` to what your mirror resolved. Mirror from the +published chart's `images.yaml`, which also lists the sandbox images its +appVersion runs. Skip the `simstudioai/copilot*` images (enterprise) and the +`simstudioai/sandbox-*` and `pause` images (Kubernetes sandbox provider) if you +do not use them. The Mothership's entries carry the placeholder tag +`main-REPLACE`: substitute the `main-` tag from its release notes. The +header of `images.yaml` covers this and the one image whose mirror path differs. ### From the Helm repository @@ -233,6 +235,26 @@ helm install sim oci://ghcr.io/simstudioai/charts/sim --version "$CHART_VERSION" --set postgresql.auth.password=$(openssl rand -base64 12 | tr -d '/+=') ``` +### Test the install + +```bash +helm test sim --namespace sim --logs --timeout 10m +``` + +Two test pods run. One checks the app and realtime Services answer. The other +calls the app's `/api/cron/self-check` with `CRON_SECRET` and passes only when +the database answers and is migrated, Redis answers, realtime is healthy (when +enabled), and, with `sandbox.kubernetes.enabled`, a sandbox runs user code +confined: as the sandbox user, with no cloud metadata credentials or Kubernetes +API, and no reach into the app, its data stores, or another sandbox. The reach +checks fail where the network plugin does not enforce NetworkPolicy. `--logs` +prints the JSON report (each check with pass, fail, warn, or skip); the pods stay +until the next `helm test`. + +The self-check skips, and passes, when `CRON_SECRET` is not in the app Secret or +the app image has no self-check endpoint. Disable it with +`tests.selfCheck.enabled=false`, or all test pods with `tests.enabled=false`. + --- ## Verifying the chart @@ -643,9 +665,9 @@ kubectl --namespace sim logs deploy/sim-app -c migrations --- -## Upgrading to 1.21.0 +## Upgrading to 1.22.0 -Covers 1.19.0–1.21.0; 1.18.0 is the previous published chart. This release refuses some values earlier charts accepted; run `helm template` with your values before upgrading. +Covers 1.19.0–1.22.0; 1.18.0 is the previous published chart. This release refuses some values earlier charts accepted; run `helm template` with your values before upgrading. * **Argo CD or `helm template | kubectl apply`: recreate the bundled Postgres StatefulSets once.** Their volume claim labels no longer carry the chart version (Kubernetes forbids changing them, which broke every upgrade). `helm upgrade` and Flux reuse the existing labels and need nothing; tools that render without `lookup` must orphan-delete first, which keeps the pods and PVCs: @@ -659,6 +681,8 @@ Covers 1.19.0–1.21.0; 1.18.0 is the previous published chart. This release ref * **External Secrets: synced keys win over `envDefaults`.** A key mapped in `externalSecrets.remoteRefs.app` is no longer masked by the chart default. No action. * **existingSecret mode applies no `envDefaults`.** Put overrides in `app.env`, which is inlined in that mode. * **New render checks.** An enabled `existingSecret` with an empty `name` (`app.secrets`, `postgresql.auth`, `externalDatabase`) fails, as does enabling both `postgresql` and `externalDatabase`, and `TRIGGER_DEV_ENABLED=true` with `sandbox.kubernetes.enabled` (unset it; Trigger.dev workers cannot reach sandbox pods). +* **`helm test` runs the authenticated self-check, and `tests.image` is now `curlimages/curl:8.5.0`.** Drop a `busybox` override of `tests.image`; with Kubernetes sandboxes run `helm test` with `--timeout 10m`. See [Test the install](#test-the-install). +* **Air-gapped mirrors: `images.yaml` adds `pause` and the `copilot-sandbox-*` images, and `busybox` is gone.** Mirror from the published chart's copy, which also lists the sandbox images its appVersion runs. * **Kubernetes sandboxes only:** * **The quota is derived.** Empty `sandbox.kubernetes.quota.cpu`/`memory`/`ephemeralStorage` (the new default) become `quota.pods` x (resources + RuntimeClass overhead); an explicit value below that floor fails. With a RuntimeClass the chart does not create, add its `overhead.podFixed` when you set quotas. * **`prePull` no longer needs `images.function.tag` on a published chart.** It defaults to the image the chart's appVersion runs; unset `images.function.tag` if you set it only for `prePull`. diff --git a/helm/sim/images.yaml b/helm/sim/images.yaml index 1cd316cef0a..e5e4e52cca8 100644 --- a/helm/sim/images.yaml +++ b/helm/sim/images.yaml @@ -1,13 +1,11 @@ # Generated by `bun run images:generate`. Do not edit this file directly. # -# Every container image this chart can render with all optional components -# enabled — mirror them into a disconnected registry before installing. Two -# entries are not part of an ordinary install: `busybox` renders only from the -# `helm test` hook, and `simstudioai/copilot` (the Mothership) requires -# enterprise registry access. Skip either if you do not use it. The Mothership is -# versioned apart from this chart: replace `main-REPLACE` with the -# `main-` tag from its release notes, and pull it from Docker Hub with -# the registry token Sim issues. +# Every container image this chart can render with all optional components enabled; mirror them +# before installing. The published chart's copy also lists the sandbox images its appVersion starts. +# Skip the `simstudioai/copilot*` images (enterprise registry access) and the `simstudioai/sandbox-*` +# and `pause` images (Kubernetes sandbox provider) if you do not use them. Replace `main-REPLACE` +# with the Mothership's `main-` tag from its release notes, and pull `simstudioai/copilot` +# from Docker Hub with the registry token Sim issues. # # To redirect them, set `global.imageRegistry` to your registry AND # `global.useRegistryForAllImages: true` — on its own, `imageRegistry` only @@ -27,12 +25,14 @@ # instead of to the `mirror` path listed below, or the pull fails. appVersion: v0.8.26 images: - - source: busybox:1.36 - mirror: busybox:1.36 - source: curlimages/curl:8.5.0 mirror: curlimages/curl:8.5.0 - source: docker.io/simstudioai/copilot:main-REPLACE mirror: simstudioai/copilot:main-REPLACE + - source: ghcr.io/simstudioai/copilot-sandbox-doc:main-REPLACE + mirror: simstudioai/copilot-sandbox-doc:main-REPLACE + - source: ghcr.io/simstudioai/copilot-sandbox-shell:main-REPLACE + mirror: simstudioai/copilot-sandbox-shell:main-REPLACE - source: ghcr.io/simstudioai/migrations:v0.8.26 mirror: simstudioai/migrations:v0.8.26 - source: ghcr.io/simstudioai/pii:v0.8.26 @@ -53,3 +53,5 @@ images: mirror: postgres:17-alpine - source: redis:7-alpine mirror: redis:7-alpine + - source: registry.k8s.io/pause:3.10 + mirror: pause:3.10 diff --git a/helm/sim/templates/NOTES.txt b/helm/sim/templates/NOTES.txt index ff615667119..e6fa671fbd2 100644 --- a/helm/sim/templates/NOTES.txt +++ b/helm/sim/templates/NOTES.txt @@ -90,6 +90,9 @@ STORAGE_PROVIDER in values.yaml). # Tail app logs kubectl --namespace {{ .Release.Namespace }} logs -f deployment/{{ include "sim.fullname" . }}-app + # Prove the install works (connectivity, database, migrations, Redis, sandboxes) + helm test {{ .Release.Name }} --namespace {{ .Release.Namespace }} --logs{{ if .Values.sandbox.kubernetes.enabled }} --timeout 10m{{ end }} + # Show the rendered values helm get values {{ .Release.Name }} --namespace {{ .Release.Namespace }} diff --git a/helm/sim/templates/networkpolicy.yaml b/helm/sim/templates/networkpolicy.yaml index 6888d043e8d..fd069b1132c 100644 --- a/helm/sim/templates/networkpolicy.yaml +++ b/helm/sim/templates/networkpolicy.yaml @@ -56,6 +56,17 @@ spec: - protocol: TCP port: {{ .Values.app.service.targetPort }} {{- end }} + # Allow ingress from the helm test pods (connectivity probe and self-check) + {{- if .Values.tests.enabled }} + - from: + - podSelector: + matchLabels: + {{- include "sim.selectorLabels" . | nindent 10 }} + simstudio.ai/component-group: helm-test + ports: + - protocol: TCP + port: {{ .Values.app.service.targetPort }} + {{- end }} # Allow custom ingress rules {{- with .Values.networkPolicy.ingress }} {{- toYaml . | nindent 2 }} @@ -234,6 +245,17 @@ spec: - protocol: TCP port: {{ .Values.realtime.service.targetPort }} {{- end }} + # Allow ingress from the helm test pods (connectivity probe) + {{- if .Values.tests.enabled }} + - from: + - podSelector: + matchLabels: + {{- include "sim.selectorLabels" . | nindent 10 }} + simstudio.ai/component-group: helm-test + ports: + - protocol: TCP + port: {{ .Values.realtime.service.targetPort }} + {{- end }} egress: # Allow egress to PostgreSQL {{- if .Values.postgresql.enabled }} diff --git a/helm/sim/templates/tests/_pod.tpl b/helm/sim/templates/tests/_pod.tpl new file mode 100644 index 00000000000..68c0b4c301b --- /dev/null +++ b/helm/sim/templates/tests/_pod.tpl @@ -0,0 +1,37 @@ +{{/* +helm test pods: the pod-level fields both test pods share (no restart, no +service account token, pull secrets, a restricted non-root security context). +Usage, under spec: {{- include "sim.tests.podSpec" . | nindent 2 }} +*/}} +{{- define "sim.tests.podSpec" -}} +restartPolicy: Never +automountServiceAccountToken: false +{{- with .Values.tests.image.pullSecrets }} +imagePullSecrets: + {{- toYaml . | nindent 2 }} +{{- end }} +securityContext: + runAsNonRoot: true + runAsUser: 65534 + runAsGroup: 65534 + fsGroup: 65534 + seccompProfile: + type: RuntimeDefault +{{- end }} + +{{/* +helm test pods: a container's image, pull policy, and restricted security context. +Usage, under a container: {{- include "sim.tests.container" . | nindent 6 }} +*/}} +{{- define "sim.tests.container" -}} +image: {{ include "sim.image" (dict "imageRoot" .Values.tests.image "global" .Values.global "chartAppVersion" .Chart.AppVersion) }} +imagePullPolicy: {{ .Values.tests.image.pullPolicy }} +securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + runAsNonRoot: true + runAsUser: 65534 + capabilities: + drop: + - ALL +{{- end }} diff --git a/helm/sim/templates/tests/test-connection.yaml b/helm/sim/templates/tests/test-connection.yaml index 12c5dd952fd..bcccc6e5863 100644 --- a/helm/sim/templates/tests/test-connection.yaml +++ b/helm/sim/templates/tests/test-connection.yaml @@ -7,34 +7,15 @@ metadata: labels: {{- include "sim.labels" . | nindent 4 }} app.kubernetes.io/component: test + simstudio.ai/component-group: helm-test annotations: "helm.sh/hook": test - "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded + "helm.sh/hook-delete-policy": before-hook-creation spec: - restartPolicy: Never - {{- with .Values.tests.image.pullSecrets }} - imagePullSecrets: - {{- toYaml . | nindent 4 }} - {{- end }} - securityContext: - runAsNonRoot: true - runAsUser: 65534 - runAsGroup: 65534 - fsGroup: 65534 - seccompProfile: - type: RuntimeDefault + {{- include "sim.tests.podSpec" . | nindent 2 }} containers: - name: probe - image: {{ include "sim.image" (dict "imageRoot" .Values.tests.image "global" .Values.global "chartAppVersion" .Chart.AppVersion) }} - imagePullPolicy: {{ .Values.tests.image.pullPolicy }} - securityContext: - allowPrivilegeEscalation: false - readOnlyRootFilesystem: true - runAsNonRoot: true - runAsUser: 65534 - capabilities: - drop: - - ALL + {{- include "sim.tests.container" . | nindent 6 }} command: - sh - -c @@ -45,7 +26,7 @@ spec: # Each URL is retried until a minute has passed, then the test fails. probe() { deadline=$(($(date +%s) + 60)) - while ! wget -q -T {{ .Values.tests.timeoutSeconds }} --spider "$1"; do + while ! curl -fsS -o /dev/null --max-time {{ .Values.tests.timeoutSeconds }} "$1"; do if [ "$(date +%s)" -ge "$deadline" ]; then echo "FAILED: $1 did not answer within 60s" return 1 diff --git a/helm/sim/templates/tests/test-self-check.yaml b/helm/sim/templates/tests/test-self-check.yaml new file mode 100644 index 00000000000..9207f864f17 --- /dev/null +++ b/helm/sim/templates/tests/test-self-check.yaml @@ -0,0 +1,84 @@ +{{- /* + Calls the app's /api/cron/self-check with the cron secret and passes only on + {"ok":true}. Runs after the connectivity probe (hook weight); both pods are + kept for their logs until the next helm test. +*/}} +{{- if and .Values.tests.enabled .Values.tests.selfCheck.enabled }} +{{- $selfCheck := .Values.tests.selfCheck }} +apiVersion: v1 +kind: Pod +metadata: + name: {{ include "sim.fullname" . }}-test-self-check + namespace: {{ .Release.Namespace }} + labels: + {{- include "sim.labels" . | nindent 4 }} + app.kubernetes.io/component: test + simstudio.ai/component-group: helm-test + annotations: + "helm.sh/hook": test + "helm.sh/hook-weight": "1" + "helm.sh/hook-delete-policy": before-hook-creation +spec: + {{- include "sim.tests.podSpec" . | nindent 2 }} + containers: + - name: self-check + {{- include "sim.tests.container" . | nindent 6 }} + env: + - name: CRON_SECRET + valueFrom: + secretKeyRef: + name: {{ include "sim.appSecretName" . }} + key: CRON_SECRET + optional: true + - name: SELF_CHECK_URL + value: "http://{{ include "sim.fullname" . }}-app:{{ .Values.app.service.port }}/api/cron/self-check?sandbox={{ ternary "1" "0" .Values.sandbox.kubernetes.enabled }}&realtime={{ ternary "1" "0" .Values.realtime.enabled }}" + command: + - sh + - -c + - | + set -eu + if [ -z "${CRON_SECRET:-}" ]; then + echo "SKIP: CRON_SECRET is not in Secret {{ include "sim.appSecretName" . }}, so the self-check cannot authenticate" + exit 0 + fi + # Only a refused connection (curl exit 7) is retried, for a minute: + # the app may still be joining its Service. Anything else, a timeout + # included, may have reached the app and started sandboxes, so it is + # never repeated. + deadline=$(($(date +%s) + 60)) + while :; do + code=0 + status=$(curl -sS --connect-timeout 5 --max-time {{ $selfCheck.timeoutSeconds }} \ + -o /tmp/response -w '%{http_code}' \ + -H "Authorization: Bearer ${CRON_SECRET}" "$SELF_CHECK_URL") || code=$? + if [ "$code" -ne 7 ]; then break; fi + if [ "$(date +%s)" -ge "$deadline" ]; then break; fi + echo "The app did not answer (curl exit $code); retrying in 5s" + sleep 5 + done + if [ "$code" -ne 0 ]; then + echo "FAILED: the self-check request failed (curl exit $code)" + exit 1 + fi + cat /tmp/response + echo + if [ "$status" = "404" ]; then + echo "SKIP: app image predates self-check" + exit 0 + fi + if [ "$status" = "200" ] && grep -q '"ok":true' /tmp/response; then + echo "OK: self-check passed" + exit 0 + fi + echo "FAILED: self-check returned HTTP $status; see the failed checks above" + exit 1 + volumeMounts: + - name: tmp + mountPath: /tmp + resources: + {{- toYaml .Values.tests.resources | nindent 8 }} + volumes: + - name: tmp + emptyDir: + sizeLimit: 16Mi +{{- end }} diff --git a/helm/sim/tests/helm-test-hook_test.yaml b/helm/sim/tests/helm-test-hook_test.yaml index ee19f4f7776..36062e8a548 100644 --- a/helm/sim/tests/helm-test-hook_test.yaml +++ b/helm/sim/tests/helm-test-hook_test.yaml @@ -21,7 +21,7 @@ tests: value: test - equal: path: 'metadata.annotations["helm.sh/hook-delete-policy"]' - value: before-hook-creation,hook-succeeded + value: before-hook-creation - equal: path: spec.restartPolicy value: Never diff --git a/helm/sim/tests/notes_test.yaml b/helm/sim/tests/notes_test.yaml index 7a124ab263a..549f88d79b0 100644 --- a/helm/sim/tests/notes_test.yaml +++ b/helm/sim/tests/notes_test.yaml @@ -26,3 +26,19 @@ tests: pattern: "helm upgrade t oci://ghcr.io/simstudioai/charts/sim --version" - notMatchRegexRaw: pattern: "\\./helm/sim" + + - it: gives helm test room for the sandbox check's two sandbox pods when Kubernetes sandboxes are on + set: + <<: *defaults + sandbox.kubernetes.enabled: true + sandbox.kubernetes.runtimeClass.preset: gvisor + asserts: + - matchRegexRaw: + pattern: "helm test t --namespace sim --logs --timeout 10m" + + - it: prints the plain helm test command without Kubernetes sandboxes + set: + <<: *defaults + asserts: + - matchRegexRaw: + pattern: "helm test t --namespace sim --logs\\n" diff --git a/helm/sim/tests/self-check_test.yaml b/helm/sim/tests/self-check_test.yaml new file mode 100644 index 00000000000..9d61413f7da --- /dev/null +++ b/helm/sim/tests/self-check_test.yaml @@ -0,0 +1,216 @@ +suite: helm test self-check pod and the helm test NetworkPolicy peer +release: + name: t + namespace: sim +defaults: &defaults + app.env.BETTER_AUTH_SECRET: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + app.env.ENCRYPTION_KEY: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + app.env.INTERNAL_API_SECRET: x + app.env.CRON_SECRET: x + postgresql.auth.password: xxxxxxxx +# The NetworkPolicy case the helm test pods used to be refused in: no ingress +# controller rule, whose default any-source peer would have admitted them. +policy: &policy + <<: *defaults + networkPolicy.enabled: true + ingress.enabled: false +helmTestPeer: &helmTestPeer + podSelector: + matchLabels: + app.kubernetes.io/name: sim + app.kubernetes.io/instance: t + simstudio.ai/component-group: helm-test + +tests: + - it: admits the helm test pods to the app when tests are enabled + template: networkpolicy.yaml + set: + <<: *policy + documentIndex: 0 + asserts: + - contains: + path: spec.ingress + content: + from: + - *helmTestPeer + ports: + - protocol: TCP + port: 3000 + + - it: admits the helm test pods to realtime when tests are enabled + template: networkpolicy.yaml + set: + <<: *policy + documentIndex: 1 + asserts: + - isSubset: + path: metadata + content: + name: t-sim-realtime + - contains: + path: spec.ingress + content: + from: + - *helmTestPeer + ports: + - protocol: TCP + port: 3002 + + - it: admits no helm test peer when tests are disabled + template: networkpolicy.yaml + set: + <<: *policy + tests.enabled: false + asserts: + - notContains: + path: spec.ingress + content: + from: + - *helmTestPeer + ports: + - protocol: TCP + port: 3000 + documentIndex: 0 + - notContains: + path: spec.ingress + content: + from: + - *helmTestPeer + ports: + - protocol: TCP + port: 3002 + documentIndex: 1 + + - it: labels both test pods so the NetworkPolicy peer selects them + templates: + - tests/test-connection.yaml + - tests/test-self-check.yaml + set: + <<: *defaults + asserts: + - isSubset: + path: metadata.labels + content: + app.kubernetes.io/name: sim + app.kubernetes.io/instance: t + simstudio.ai/component-group: helm-test + + - it: keeps both test pods after a pass so helm test --logs can read them, replacing them on the next run + templates: + - tests/test-connection.yaml + - tests/test-self-check.yaml + set: + <<: *defaults + asserts: + - equal: + path: 'metadata.annotations["helm.sh/hook-delete-policy"]' + value: before-hook-creation + + - it: mounts no service account token in either test pod + templates: + - tests/test-connection.yaml + - tests/test-self-check.yaml + set: + <<: *defaults + asserts: + - equal: + path: spec.automountServiceAccountToken + value: false + + - it: rejects the removed requireEndpoint value + template: tests/test-self-check.yaml + set: + <<: *defaults + tests.selfCheck.requireEndpoint: true + asserts: + - failedTemplate: {} + + - it: reads CRON_SECRET from the app Secret, optional so a Secret without it skips instead of failing to start + template: tests/test-self-check.yaml + set: + <<: *defaults + asserts: + - contains: + path: spec.containers[0].env + content: + name: CRON_SECRET + valueFrom: + secretKeyRef: + name: t-sim-app-secrets + key: CRON_SECRET + optional: true + + - it: reads CRON_SECRET from the existing Secret when one is configured + template: tests/test-self-check.yaml + set: + <<: *defaults + app.secrets.existingSecret.enabled: true + app.secrets.existingSecret.name: operator-app-secrets + asserts: + - equal: + path: spec.containers[0].env[0].valueFrom.secretKeyRef.name + value: operator-app-secrets + + - it: asks for the realtime check, not the sandbox check, by default + template: tests/test-self-check.yaml + set: + <<: *defaults + asserts: + - contains: + path: spec.containers[0].env + content: + name: SELF_CHECK_URL + value: http://t-sim-app:3000/api/cron/self-check?sandbox=0&realtime=1 + + - it: asks for the sandbox check when the Kubernetes sandbox provider is on, and no realtime check without realtime + template: tests/test-self-check.yaml + set: + <<: *defaults + sandbox.kubernetes.enabled: true + sandbox.kubernetes.runtimeClass.preset: gvisor + realtime.enabled: false + asserts: + - contains: + path: spec.containers[0].env + content: + name: SELF_CHECK_URL + value: http://t-sim-app:3000/api/cron/self-check?sandbox=1&realtime=0 + + - it: skips on a 404 by default, so an older app image does not fail helm test + template: tests/test-self-check.yaml + set: + <<: *defaults + asserts: + - matchRegex: + path: spec.containers[0].command[2] + pattern: 'SKIP: app image predates self-check"\s*\n\s*exit 0' + + - it: retries only a refused connection, never a timeout that may have started sandboxes + template: tests/test-self-check.yaml + set: + <<: *defaults + asserts: + - matchRegex: + path: spec.containers[0].command[2] + pattern: 'if \[ "\$code" -ne 7 \]; then break; fi' + - notMatchRegex: + path: spec.containers[0].command[2] + pattern: '-ne 28' + + - it: renders no self-check pod when selfCheck is disabled + template: tests/test-self-check.yaml + set: + <<: *defaults + tests.selfCheck.enabled: false + asserts: + - hasDocuments: + count: 0 + + - it: renders no self-check pod when tests are disabled + template: tests/test-self-check.yaml + set: + <<: *defaults + tests.enabled: false + asserts: + - hasDocuments: + count: 0 diff --git a/helm/sim/values.schema.json b/helm/sim/values.schema.json index 751703efc3c..37942339c8c 100644 --- a/helm/sim/values.schema.json +++ b/helm/sim/values.schema.json @@ -913,6 +913,19 @@ } }, "timeoutSeconds": { "type": "integer", "minimum": 1 }, + "selfCheck": { + "type": "object", + "description": "Authenticated self-check: the test pod calls the app's /api/cron/self-check with the cron secret", + "additionalProperties": false, + "properties": { + "enabled": { "type": "boolean" }, + "timeoutSeconds": { + "type": "integer", + "minimum": 30, + "description": "Self-check request timeout; the sandbox check starts two sandbox pods" + } + } + }, "resources": { "type": "object" } } }, diff --git a/helm/sim/values.yaml b/helm/sim/values.yaml index 343649d0c50..63cd1d2cb3c 100644 --- a/helm/sim/values.yaml +++ b/helm/sim/values.yaml @@ -2314,17 +2314,20 @@ certManager: # This is the issuer that applications should reference for obtaining certificates caIssuer: name: "sim-ca-issuer" -# Helm test hook (helm test) connectivity probes. -# Renders a Pod with helm.sh/hook=test that checks the app and realtime -# Services are reachable from inside the cluster. Run with: helm test +# helm test hooks: a connectivity probe and the authenticated self-check. Run: helm test --logs tests: enabled: true image: - repository: busybox - tag: "1.36" + repository: curlimages/curl + tag: "8.5.0" pullPolicy: IfNotPresent pullSecrets: [] timeoutSeconds: 5 + # Calls /api/cron/self-check with CRON_SECRET (see "Test the install" in README.md). Skips, passing, without CRON_SECRET or on an app image without the endpoint. + selfCheck: + enabled: true + # The sandbox check starts two sandbox pods; a cold image pull can take minutes. + timeoutSeconds: 240 resources: limits: cpu: 100m diff --git a/packages/db/package.json b/packages/db/package.json index 6e21fda5c05..5294bafa697 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -33,6 +33,7 @@ "types": "./sso-primary-provider.ts", "default": "./sso-primary-provider.ts" }, + "./migrations/meta/_journal.json": "./migrations/meta/_journal.json", "./testing/explain": { "types": "./testing/explain.ts", "default": "./testing/explain.ts" diff --git a/scripts/generate-image-manifest.test.ts b/scripts/generate-image-manifest.test.ts index 4c0d85ba332..c62af9d9569 100644 --- a/scripts/generate-image-manifest.test.ts +++ b/scripts/generate-image-manifest.test.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from 'vitest' -import { collectImages, pairSources } from './generate-image-manifest' +import { + collectImages, + mergeImageEntries, + pairSources, + sandboxImageEntries, +} from './generate-image-manifest' describe('collectImages', () => { it('finds images across every container key a pod spec can use', () => { @@ -41,6 +46,40 @@ describe('collectImages', () => { }) }) +describe('collectImages sandbox references', () => { + it('reads the sandbox images the chart hands the app, as it resolves their registry', () => { + const images = collectImages([ + { + kind: 'Deployment', + spec: { + template: { + spec: { + containers: [ + { + image: 'ghcr.io/simstudioai/simstudio:v1', + env: [ + { name: 'SANDBOX_K8S_IMAGE_REGISTRY', value: 'ghcr.io' }, + { + name: 'SANDBOX_K8S_MOTHERSHIP_IMAGE', + value: 'ghcr.io/simstudioai/copilot-sandbox-shell:main-REPLACE', + }, + { name: 'SANDBOX_K8S_DOC_IMAGE', valueFrom: { secretKeyRef: {} } }, + ], + }, + ], + }, + }, + }, + }, + ]) + + expect(images).toEqual([ + 'ghcr.io/simstudioai/copilot-sandbox-shell:main-REPLACE', + 'ghcr.io/simstudioai/simstudio:v1', + ]) + }) +}) + describe('pairSources', () => { it('strips the sentinel registry so the mirror path is what the chart resolves to', () => { const paired = pairSources( @@ -70,3 +109,45 @@ describe('pairSources', () => { ).toThrow(/share the name and tag/) }) }) + +describe('sandboxImageEntries', () => { + it('mirrors a run-time sandbox image under its path without the registry host, as the app moves it', () => { + expect( + sandboxImageEntries([ + 'ghcr.io/simstudioai/sandbox-function:d605a15fb5b0a189', + 'docker.io/simstudioai/copilot-sandbox-shell:main-REPLACE', + ]) + ).toEqual([ + { + source: 'ghcr.io/simstudioai/sandbox-function:d605a15fb5b0a189', + mirror: 'simstudioai/sandbox-function:d605a15fb5b0a189', + }, + { + source: 'docker.io/simstudioai/copilot-sandbox-shell:main-REPLACE', + mirror: 'simstudioai/copilot-sandbox-shell:main-REPLACE', + }, + ]) + }) + + it('refuses a reference without a registry host rather than dropping its namespace', () => { + expect(() => sandboxImageEntries(['simstudioai/sandbox-agent:abc'])).toThrow(/registry host/) + }) +}) + +describe('mergeImageEntries', () => { + it('sorts rendered and run-time images into one list by source', () => { + const merged = mergeImageEntries( + [{ source: 'redis:7-alpine', mirror: 'redis:7-alpine' }], + [{ source: 'ghcr.io/simstudioai/sandbox-pi:1', mirror: 'simstudioai/sandbox-pi:1' }] + ) + expect(merged.map((entry) => entry.source)).toEqual([ + 'ghcr.io/simstudioai/sandbox-pi:1', + 'redis:7-alpine', + ]) + }) + + it('refuses an image listed by both the chart and the sandbox inventory', () => { + const entry = { source: 'ghcr.io/simstudioai/sandbox-pi:1', mirror: 'simstudioai/sandbox-pi:1' } + expect(() => mergeImageEntries([entry], [entry])).toThrow(/listed twice/) + }) +}) diff --git a/scripts/generate-image-manifest.ts b/scripts/generate-image-manifest.ts index 62b7c48c86d..da508f343e4 100644 --- a/scripts/generate-image-manifest.ts +++ b/scripts/generate-image-manifest.ts @@ -19,24 +19,36 @@ * Usage: * bun run scripts/generate-image-manifest.ts * bun run scripts/generate-image-manifest.ts --check + * bun run scripts/generate-image-manifest.ts --release v0.8.26 + * + * `--release` is for the publish jobs only (via `sync-chart-appversion.ts`): it + * also lists the sandbox images the app at that release starts at run time. The + * committed file leaves them out, since their content-addressed tags change with + * every sandbox image rebuild and would otherwise force a chart version bump. */ import { readFile, writeFile } from 'node:fs/promises' import { dirname, resolve } from 'node:path' import { fileURLToPath } from 'node:url' +import { IMAGE_LIST_PATH, readReleaseImageList } from './release-image-list' const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)) const ROOT = resolve(SCRIPT_DIR, '..') const CHART_DIR = resolve(ROOT, 'helm/sim') const OUTPUT_PATH = resolve(CHART_DIR, 'images.yaml') const CHECK_MODE = process.argv.includes('--check') +const RELEASE_FLAG_INDEX = process.argv.indexOf('--release') +const RELEASE = RELEASE_FLAG_INDEX === -1 ? null : (process.argv[RELEASE_FLAG_INDEX + 1] ?? '') /** * Render arguments. * * `ci/full-values.yaml` is the chart's own "every optional component enabled" * profile, but it leaves `ollama.gpu.enabled` off, and the device plugin renders - * only under that key. Enabling it here is what makes this an inventory of every - * image the chart can pull rather than of one popular configuration. + * only under that key; the Kubernetes sandbox provider is off there too, and its + * warm-capacity placeholders (the `pause` image) render only with it on and a + * nonzero `warmCapacity.sandboxes`. Enabling them here is what makes this an + * inventory of every image the chart can pull rather than of one popular + * configuration. */ const RENDER_ARGS = [ 'template', @@ -48,6 +60,18 @@ const RENDER_ARGS = [ resolve(CHART_DIR, 'ci/full-values.yaml'), '--set', 'ollama.gpu.enabled=true', + '--set', + 'sandbox.kubernetes.enabled=true', + '--set', + 'sandbox.kubernetes.runtimeClass.preset=gvisor', + '--set', + 'sandbox.kubernetes.warmCapacity.sandboxes=1', + // The Mothership's sandbox images have no default; a tag makes the chart render them, at the + // registry it resolves them to, under the Mothership's placeholder tag. + '--set', + 'sandbox.kubernetes.images.mothership.tag=main-REPLACE', + '--set', + 'sandbox.kubernetes.images.doc.tag=main-REPLACE', ] as const /** @@ -75,6 +99,12 @@ const MIRROR_RENDER_ARGS = [ /** Pod-spec keys whose entries carry an image reference. */ const CONTAINER_KEYS = new Set(['containers', 'initContainers', 'ephemeralContainers']) +/** + * Container env vars through which the chart hands the app a sandbox image it starts at run + * time (`SANDBOX_K8S__IMAGE`); not `SANDBOX_K8S_IMAGE_REGISTRY`, which is a registry. + */ +const SANDBOX_IMAGE_ENV = /^SANDBOX_K8S_[A-Z]+_IMAGE$/ + /** * Collects every image reference in a set of rendered Kubernetes documents. * @@ -96,8 +126,16 @@ export function collectImages(documents: readonly unknown[]): string[] { if (CONTAINER_KEYS.has(key) && Array.isArray(value)) { for (const container of value) { if (container === null || typeof container !== 'object') continue - const image = (container as { image?: unknown }).image + const { image, env } = container as { image?: unknown; env?: unknown } if (typeof image === 'string' && image.length > 0) images.add(image) + if (Array.isArray(env)) { + for (const variable of env) { + const { name, value } = (variable ?? {}) as { name?: unknown; value?: unknown } + if (typeof name === 'string' && SANDBOX_IMAGE_ENV.test(name)) { + if (typeof value === 'string' && value.length > 0) images.add(value) + } + } + } } } visit(value) @@ -154,6 +192,36 @@ export function pairSources(sources: readonly string[], mirrored: readonly strin }) } +/** + * Pairs each run-time sandbox reference with its mirror path. The app moves a + * published reference to `SANDBOX_K8S_IMAGE_REGISTRY` (which the chart sets from + * `global.imageRegistry`) by replacing its first path segment, the registry + * host, so the mirror path is the reference without it. + */ +export function sandboxImageEntries(references: readonly string[]): ImageEntry[] { + return references.map((source) => { + const separator = source.indexOf('/') + if (separator <= 0 || !source.slice(0, separator).includes('.')) { + throw new Error(`Sandbox image ${source} does not start with a registry host`) + } + return { source, mirror: source.slice(separator + 1) } + }) +} + +/** Joins the rendered and run-time entries into one list sorted by source, refusing duplicates. */ +export function mergeImageEntries(...groups: ReadonlyArray): ImageEntry[] { + const bySource = new Map() + for (const entry of groups.flat()) { + if (bySource.has(entry.source)) { + throw new Error(`${entry.source} is listed twice`) + } + bySource.set(entry.source, entry) + } + return [...bySource.values()].sort((a, b) => + a.source < b.source ? -1 : a.source > b.source ? 1 : 0 + ) +} + export function renderManifest(input: { appVersion: string images: readonly ImageEntry[] @@ -164,14 +232,12 @@ export function renderManifest(input: { return `# Generated by \`bun run images:generate\`. Do not edit this file directly. # -# Every container image this chart can render with all optional components -# enabled — mirror them into a disconnected registry before installing. Two -# entries are not part of an ordinary install: \`busybox\` renders only from the -# \`helm test\` hook, and \`simstudioai/copilot\` (the Mothership) requires -# enterprise registry access. Skip either if you do not use it. The Mothership is -# versioned apart from this chart: replace \`main-REPLACE\` with the -# \`main-\` tag from its release notes, and pull it from Docker Hub with -# the registry token Sim issues. +# Every container image this chart can render with all optional components enabled; mirror them +# before installing. The published chart's copy also lists the sandbox images its appVersion starts. +# Skip the \`simstudioai/copilot*\` images (enterprise registry access) and the \`simstudioai/sandbox-*\` +# and \`pause\` images (Kubernetes sandbox provider) if you do not use them. Replace \`main-REPLACE\` +# with the Mothership's \`main-\` tag from its release notes, and pull \`simstudioai/copilot\` +# from Docker Hub with the registry token Sim issues. # # To redirect them, set \`global.imageRegistry\` to your registry AND # \`global.useRegistryForAllImages: true\` — on its own, \`imageRegistry\` only @@ -218,13 +284,27 @@ function renderChart(args: readonly string[] = RENDER_ARGS): unknown[] { return Array.isArray(documents) ? documents : [documents] } +/** + * The sandbox images the app at `release` starts at run time, which no rendered pod names: the + * references `images.generated.json` pins at the release tag. None for a release before the list. + */ +function releaseSandboxImages(release: string): string[] { + const list = readReleaseImageList(release) + if (!list) { + console.log(`${release} has no ${IMAGE_LIST_PATH}; listing no sandbox images.`) + return [] + } + return Object.values(list) +} + async function main(): Promise { const chart = await readFile(resolve(CHART_DIR, 'Chart.yaml'), 'utf8') + const runtimeImages = RELEASE === null ? [] : releaseSandboxImages(RELEASE) const manifest = renderManifest({ appVersion: readChartField(chart, 'appVersion'), - images: pairSources( - collectImages(renderChart()), - collectImages(renderChart(MIRROR_RENDER_ARGS)) + images: mergeImageEntries( + pairSources(collectImages(renderChart()), collectImages(renderChart(MIRROR_RENDER_ARGS))), + sandboxImageEntries(runtimeImages) ), }) diff --git a/scripts/write-chart-sandbox-images.test.ts b/scripts/release-image-list.test.ts similarity index 54% rename from scripts/write-chart-sandbox-images.test.ts rename to scripts/release-image-list.test.ts index 2feda8f6129..6e607bae5be 100644 --- a/scripts/write-chart-sandbox-images.test.ts +++ b/scripts/release-image-list.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { releaseRevision } from './write-chart-sandbox-images' +import { parseImageList, releaseRevision } from './release-image-list' describe('releaseRevision', () => { it('reads the release tag when it exists', () => { @@ -28,3 +28,25 @@ describe('releaseRevision', () => { ).toThrow(/not present and HEAD .* is not its release commit; fetching the tag failed: fatal/) }) }) + +describe('parseImageList', () => { + it('reads every reference the release pins, by kind', () => { + expect( + parseImageList( + '{"function": "ghcr.io/simstudioai/sandbox-function:a", "agent": "ghcr.io/simstudioai/sandbox-agent:b"}', + 'v1.2.3' + ) + ).toEqual({ + function: 'ghcr.io/simstudioai/sandbox-function:a', + agent: 'ghcr.io/simstudioai/sandbox-agent:b', + }) + }) + + it.each([ + ['an empty map', '{}'], + ['a non-string reference', '{"function": 1}'], + ['an array', '["ghcr.io/simstudioai/sandbox-function:a"]'], + ])('refuses %s rather than publishing a chart without the sandbox images', (_, json) => { + expect(() => parseImageList(json, 'v1.2.3')).toThrow(/images.generated.json at v1.2.3/) + }) +}) diff --git a/scripts/release-image-list.ts b/scripts/release-image-list.ts new file mode 100644 index 00000000000..c25873f6234 --- /dev/null +++ b/scripts/release-image-list.ts @@ -0,0 +1,105 @@ +/** + * Reads the sandbox image list a Sim release runs by default: + * `apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json` at the release tag. + * Shared by the chart publish steps (`write-chart-sandbox-images.ts`, and + * `generate-image-manifest.ts --release`) so they agree on which revision a release reads. + * + * The tag is fetched when the checkout lacks it (publish jobs check out shallow). On the release + * commit itself the tag may not exist yet, since publishing does not wait for the job that cuts + * it, so HEAD is read when its subject names the release (`v1.2.3: ...`, the rule helm.yml + * resolves the version by). Imports only node builtins, so it runs on a CI job with no install. + */ +import { spawnSync } from 'node:child_process' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..') + +export const IMAGE_LIST_PATH = + 'apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json' + +/** A release tag as this repository cuts them: `v1.2.3`. */ +export const RELEASE_TAG = /^v\d+\.\d+\.\d+$/ + +function git(args: readonly string[]): { ok: boolean; stdout: string; stderr: string } { + const result = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8', maxBuffer: 64 << 20 }) + return { ok: result.status === 0, stdout: result.stdout ?? '', stderr: result.stderr ?? '' } +} + +/** + * The git revision to read `version`'s image list from: its tag when present, else HEAD when + * HEAD is the release commit that will be tagged `version`. Throws otherwise, naming why. + */ +export function releaseRevision(input: { + version: string + tagPresent: boolean + headSubject: string + fetchError?: string +}): string { + if (input.tagPresent) return `refs/tags/${input.version}` + if (input.headSubject.startsWith(`${input.version}:`)) return 'HEAD' + throw new Error( + `Release tag ${input.version} is not present and HEAD ("${input.headSubject}") is not its release commit${input.fetchError ? `; fetching the tag failed: ${input.fetchError.trim()}` : ''}` + ) +} + +/** The image list's references by kind, refusing anything but a non-empty map of strings. */ +export function parseImageList(json: string, label: string): Record { + const parsed: unknown = JSON.parse(json) + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`${IMAGE_LIST_PATH} at ${label} is not an object of image references`) + } + const references: Record = {} + for (const [kind, value] of Object.entries(parsed)) { + if (typeof value !== 'string') { + throw new Error(`${IMAGE_LIST_PATH} at ${label} holds a non-string image reference`) + } + references[kind] = value + } + if (Object.keys(references).length === 0) { + throw new Error(`${IMAGE_LIST_PATH} at ${label} holds no image reference`) + } + return references +} + +/** Resolves {@link releaseRevision} against the repository, fetching the tag when absent. */ +function resolveReleaseRevision(version: string): string { + const tagRef = `refs/tags/${version}` + const hasTag = () => git(['rev-parse', '--verify', '--quiet', `${tagRef}^{commit}`]).ok + let fetchError: string | undefined + if (!hasTag()) { + const fetched = git([ + 'fetch', + '--quiet', + '--no-tags', + '--depth', + '1', + 'origin', + `+${tagRef}:${tagRef}`, + ]) + if (!fetched.ok) fetchError = fetched.stderr + } + return releaseRevision({ + version, + tagPresent: hasTag(), + headSubject: git(['log', '-1', '--format=%s', 'HEAD']).stdout.trim(), + fetchError, + }) +} + +/** + * The image references `version` runs by default, by kind, or null for a release that predates + * the list (it starts no Kubernetes sandbox images). + */ +export function readReleaseImageList(version: string): Record | null { + if (!RELEASE_TAG.test(version)) { + throw new Error(`A release must be a tag like v1.2.3, got "${version}"`) + } + const revision = resolveReleaseRevision(version) + if (!git(['cat-file', '-e', `${revision}:${IMAGE_LIST_PATH}`]).ok) return null + const shown = git(['show', `${revision}:${IMAGE_LIST_PATH}`]) + if (!shown.ok) { + throw new Error(`Could not read ${IMAGE_LIST_PATH} at ${version}: ${shown.stderr.trim()}`) + } + return parseImageList(shown.stdout, version) +} diff --git a/scripts/sync-chart-appversion.ts b/scripts/sync-chart-appversion.ts index eb56756a4cb..c92f716f3d9 100644 --- a/scripts/sync-chart-appversion.ts +++ b/scripts/sync-chart-appversion.ts @@ -24,7 +24,9 @@ * ``` * * `--check` verifies both halves: that Chart.yaml names the version and that the - * inventory generated from it is current. + * committed inventory generated from it is current. The sandbox images the + * release's app starts are written only by the publish run (without `--check`), + * so the committed inventory leaves them out and the check does too. */ import { spawnSync } from 'node:child_process' import { readFile, writeFile } from 'node:fs/promises' @@ -75,6 +77,8 @@ async function main() { * not mean the pair is consistent -- checking only half of what this script * writes would report success over a stale inventory. */ + // Without --release: the sandbox images are added only to the published copy, so the + // committed inventory is what can be checked. const verified = spawnSync('bun', ['run', 'scripts/generate-image-manifest.ts', '--check'], { cwd: ROOT, stdio: 'inherit', @@ -93,13 +97,15 @@ async function main() { /** * The inventory embeds appVersion in every first-party image tag, so it has to - * follow. Spawned rather than imported because the generator writes on import - * of its own main and owns its formatting. + * follow, and lists the sandbox images that release's app starts at run time. + * Spawned rather than imported because the generator writes on import of its + * own main and owns its formatting. */ - const generated = spawnSync('bun', ['run', 'scripts/generate-image-manifest.ts'], { - cwd: ROOT, - stdio: 'inherit', - }) + const generated = spawnSync( + 'bun', + ['run', 'scripts/generate-image-manifest.ts', '--release', version], + { cwd: ROOT, stdio: 'inherit' } + ) if (generated.status !== 0) { throw new Error(`generate-image-manifest.ts exited with ${generated.status}`) } diff --git a/scripts/write-chart-sandbox-images.ts b/scripts/write-chart-sandbox-images.ts index 2e2c9f5e9b2..9fe99cc0c35 100644 --- a/scripts/write-chart-sandbox-images.ts +++ b/scripts/write-chart-sandbox-images.ts @@ -15,12 +15,9 @@ * * Imports only node builtins and logs with console, so it runs on a CI job with no install. * - * The release tag is fetched when the checkout lacks it (publish jobs check out shallow). On - * the release commit itself the tag may not exist yet, since publishing does not wait for the - * job that cuts it, so HEAD is read when its subject names the release (`v1.2.3: ...`, the rule - * helm.yml resolves the version by). A release that predates the list gets a notice and - * no file, so its chart behaves like a checkout: pre-pull needs an explicit - * function image. + * Which revision a release reads, and how a missing tag is fetched, is + * `release-image-list.ts`'s. A release that predates the list gets a notice and no file, so its + * chart behaves like a checkout: pre-pull needs an explicit function image. * * @example * ``` @@ -31,14 +28,11 @@ import { spawnSync } from 'node:child_process' import { mkdir, writeFile } from 'node:fs/promises' import { dirname, resolve } from 'node:path' import { fileURLToPath } from 'node:url' +import { IMAGE_LIST_PATH, RELEASE_TAG, readReleaseImageList } from './release-image-list' const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..') const CHART_DIR = resolve(ROOT, 'helm/sim') const OUTPUT_PATH = resolve(CHART_DIR, 'files/sandbox-images.json') -const IMAGE_LIST_PATH = 'apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json' - -/** A release tag as this repository cuts them: `v1.2.3`. */ -const RELEASE_TAG = /^v\d+\.\d+\.\d+$/ /** The content-addressed reference `generate-sandbox-dockerfiles.ts` writes for the Function image. */ const FUNCTION_IMAGE = /^ghcr\.io\/simstudioai\/sandbox-function:[0-9a-f]{16}$/ @@ -62,57 +56,8 @@ function run(command: string, args: string[]): string { return result.stdout } -function git(args: readonly string[]): { ok: boolean; stdout: string; stderr: string } { - const result = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' }) - return { ok: result.status === 0, stdout: result.stdout ?? '', stderr: result.stderr ?? '' } -} - -/** - * The git revision to read `version`'s image list from: its tag when present, else HEAD when - * HEAD is the release commit that will be tagged `version`. Throws otherwise, naming why. - */ -export function releaseRevision(input: { - version: string - tagPresent: boolean - headSubject: string - fetchError?: string -}): string { - if (input.tagPresent) return `refs/tags/${input.version}` - if (input.headSubject.startsWith(`${input.version}:`)) return 'HEAD' - throw new Error( - `Release tag ${input.version} is not present and HEAD ("${input.headSubject}") is not its release commit${input.fetchError ? `; fetching the tag failed: ${input.fetchError.trim()}` : ''}` - ) -} - -/** Resolves {@link releaseRevision} against the repository, fetching the tag when absent. */ -function resolveReleaseRevision(version: string): string { - const tagRef = `refs/tags/${version}` - const hasTag = () => git(['rev-parse', '--verify', '--quiet', `${tagRef}^{commit}`]).ok - let fetchError: string | undefined - if (!hasTag()) { - const fetched = git([ - 'fetch', - '--quiet', - '--no-tags', - '--depth', - '1', - 'origin', - `+${tagRef}:${tagRef}`, - ]) - if (!fetched.ok) fetchError = fetched.stderr - } - return releaseRevision({ - version, - tagPresent: hasTag(), - headSubject: git(['log', '-1', '--format=%s', 'HEAD']).stdout.trim(), - fetchError, - }) -} - -function releaseFunctionImage(version: string, revision: string): string { - const list: unknown = JSON.parse(run('git', ['show', `${revision}:${IMAGE_LIST_PATH}`])) - const image = - typeof list === 'object' && list !== null && 'function' in list ? list.function : undefined +function releaseFunctionImage(version: string, list: Record): string { + const image = list.function if (typeof image !== 'string' || !FUNCTION_IMAGE.test(image)) { throw new Error(`${IMAGE_LIST_PATH} at ${version} names no Function image: ${String(image)}`) } @@ -148,14 +93,14 @@ function renderedPrePullImage(): string { async function main() { const { version, verify } = parseArgs(process.argv.slice(2)) - const revision = resolveReleaseRevision(version) - if (!git(['cat-file', '-e', `${revision}:${IMAGE_LIST_PATH}`]).ok) { + const list = readReleaseImageList(version) + if (!list) { console.log( `Notice: ${version} has no ${IMAGE_LIST_PATH}, so the chart carries no default sandbox Function image; sandbox.kubernetes.prePull needs images.function.tag or digest with it.` ) return } - const image = releaseFunctionImage(version, revision) + const image = releaseFunctionImage(version, list) await mkdir(dirname(OUTPUT_PATH), { recursive: true }) await writeFile(OUTPUT_PATH, `${JSON.stringify({ function: image }, null, 2)}\n`) console.log(`Wrote ${image} to helm/sim/files/sandbox-images.json.`)