From ce56c0d71aebb7a365d72867eac07f8c1fa84e11 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 10:22:14 -0600 Subject: [PATCH 1/6] feat(self-hosting): add an authenticated self-check and a helm test that proves a real install works --- .github/workflows/sandbox.yml | 91 ++++++- apps/sim/app/api/cron/self-check/route.ts | 28 ++ apps/sim/lib/api/contracts/self-check.ts | 36 +++ .../execution/remote-sandbox/agent/handle.ts | 4 + .../remote-sandbox/kubernetes.live.test.ts | 178 +----------- .../kubernetes/confinement-probe.ts | 256 ++++++++++++++++++ .../remote-sandbox/kubernetes/provider.ts | 1 + .../sim/lib/execution/remote-sandbox/types.ts | 5 + apps/sim/lib/self-check/confinement.test.ts | 204 ++++++++++++++ apps/sim/lib/self-check/confinement.ts | 173 ++++++++++++ apps/sim/lib/self-check/infrastructure.ts | 71 +++++ apps/sim/lib/self-check/outcome.ts | 48 ++++ apps/sim/lib/self-check/run.test.ts | 32 +++ apps/sim/lib/self-check/run.ts | 94 +++++++ apps/sim/lib/self-check/sandbox.ts | 232 ++++++++++++++++ apps/sim/lib/self-check/types.ts | 34 +++ helm/sim/Chart.yaml | 2 +- helm/sim/README.md | 48 +++- helm/sim/images.yaml | 24 +- helm/sim/templates/networkpolicy.yaml | 22 ++ helm/sim/templates/tests/test-connection.yaml | 3 +- helm/sim/templates/tests/test-self-check.yaml | 112 ++++++++ helm/sim/tests/self-check_test.yaml | 199 ++++++++++++++ helm/sim/values.schema.json | 17 ++ helm/sim/values.yaml | 23 +- packages/db/package.json | 1 + scripts/generate-image-manifest.test.ts | 68 ++++- scripts/generate-image-manifest.ts | 147 +++++++++- scripts/sync-chart-appversion.ts | 17 +- 29 files changed, 1956 insertions(+), 214 deletions(-) create mode 100644 apps/sim/app/api/cron/self-check/route.ts create mode 100644 apps/sim/lib/api/contracts/self-check.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts create mode 100644 apps/sim/lib/self-check/confinement.test.ts create mode 100644 apps/sim/lib/self-check/confinement.ts create mode 100644 apps/sim/lib/self-check/infrastructure.ts create mode 100644 apps/sim/lib/self-check/outcome.ts create mode 100644 apps/sim/lib/self-check/run.test.ts create mode 100644 apps/sim/lib/self-check/run.ts create mode 100644 apps/sim/lib/self-check/sandbox.ts create mode 100644 apps/sim/lib/self-check/types.ts create mode 100644 helm/sim/templates/tests/test-self-check.yaml create mode 100644 helm/sim/tests/self-check_test.yaml diff --git a/.github/workflows/sandbox.yml b/.github/workflows/sandbox.yml index 745c12d9c7f..dc5a98bb3b0 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,10 @@ 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/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' @@ -210,6 +216,9 @@ jobs: - '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/app/api/cron/self-check/**' + - 'helm/sim/templates/tests/**' - 'apps/sandbox-agent/**' - 'packages/sandbox-agent-protocol/**' - 'helm/sim/templates/sandbox-kubernetes.yaml' @@ -1033,7 +1042,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 @@ -1092,6 +1101,7 @@ jobs: --set "app.env.INTERNAL_API_SECRET=${E2E_INTERNAL_SECRET}" \ --set "app.env.CRON_SECRET=${E2E_CRON_SECRET}" \ --set "postgresql.auth.password=${E2E_DB_SECRET}" \ + --set tests.selfCheck.requireEndpoint=true \ --wait --timeout 20m kubectl get pods --namespace "$RELEASE_NAMESPACE" -o wide @@ -1141,6 +1151,83 @@ 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 must exist (requireEndpoint). + - name: Run helm test + run: helm test sim --namespace "$RELEASE_NAMESPACE" --logs --timeout 10m + + # 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/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/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.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts new file mode 100644 index 00000000000..a325daa2ab7 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts @@ -0,0 +1,256 @@ +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' + +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. + */ +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 + +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:${SANDBOX_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 {} + +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)} +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 = imds_headers() + # 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 = { + 'aws instance-id': ('http://${METADATA_ADDRESS}/latest/meta-data/instance-id', aws), + 'aws user-data': ('http://${METADATA_ADDRESS}/latest/user-data', aws), + 'aws iam credentials': ('http://${METADATA_ADDRESS}/latest/meta-data/iam/security-credentials/', aws), + 'eks pod identity': ('http://169.254.170.23/v1/credentials', None), + 'ecs task credentials': ('http://169.254.170.2/v2/credentials', None), + 'gcp instance id': ('http://${METADATA_ADDRESS}/computeMetadata/v1/instance/id', {'Metadata-Flavor': 'Google'}), + 'azure instance': ('http://${METADATA_ADDRESS}/metadata/instance?api-version=2021-02-01', {'Metadata': 'true'}), + 'gcp service account token': ('http://${METADATA_ADDRESS}/computeMetadata/v1/instance/service-accounts/default/token', {'Metadata-Flavor': 'Google'}), + 'azure managed identity token': ('http://${METADATA_ADDRESS}/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/', {'Metadata': 'true'}), + } + 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) for h, p 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..dbcd340d771 --- /dev/null +++ b/apps/sim/lib/self-check/confinement.test.ts @@ -0,0 +1,204 @@ +import { describe, expect, it } from 'vitest' +import type { ConfinementFacts } 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, + 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: { 'aws iam credentials': 'unreachable', 'gcp instance id': '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 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('isProbeTargetAddress', () => { + it.each(['127.0.0.1', '::1', '169.254.169.254', 'fe80::1', '::ffff:127.0.0.1', '0.0.0.0'])( + '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'])('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..0cbbe187d2d --- /dev/null +++ b/apps/sim/lib/self-check/confinement.ts @@ -0,0 +1,173 @@ +import { isIP } from 'node:net' +import { + type ConfinementFacts, + isConfinementFacts, +} from '@/lib/execution/remote-sandbox/kubernetes/confinement-probe' +import type { CheckOutcome } from '@/lib/self-check/outcome' + +const SANDBOX_USER_ID = 1000 +/** 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 + /** + * 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`) + } + 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), + } +} + +/** + * Judges the probe's raw result. A result that is not the full set of facts the rules read fails + * the sandbox check instead of throwing, 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 } + } + try { + return { + execution: { status: 'pass', detail: 'ran user code' }, + outcomes: evaluateConfinement(value, plan), + } + } catch { + return { + execution: { status: 'fail', detail: 'the probe result could not be judged' }, + outcomes: null, + } + } +} + +/** + * 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 normalized = address.toLowerCase().replace(/^::ffff:/, '') + if (isIP(normalized) === 0) return false + return !( + normalized === '::1' || + normalized === '::' || + normalized.startsWith('127.') || + normalized.startsWith('0.') || + normalized.startsWith('169.254.') || + /^fe[89ab][0-9a-f]:/.test(normalized) + ) +} diff --git a/apps/sim/lib/self-check/infrastructure.ts b/apps/sim/lib/self-check/infrastructure.ts new file mode 100644 index 00000000000..170d9e5cff5 --- /dev/null +++ b/apps/sim/lib/self-check/infrastructure.ts @@ -0,0 +1,71 @@ +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, withTimeout } 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 withTimeout(db.execute(sql`select 1`), 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 withTimeout( + db.execute<{ latest: string | number | null }>( + sql`select max(created_at) as latest from drizzle.__drizzle_migrations` + ), + 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 () => { + if (!env.REDIS_URL) return { status: 'skip', detail: 'REDIS_URL is not set' } + await withTimeout(getRedisClient().ping(), REDIS_TIMEOUT_MS) + return { status: 'pass', detail: 'ping answered' } + }) +} + +export function checkRealtime(): Promise { + return timed('realtime', async () => { + const response = await fetch(`${getSocketServerUrl()}/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..45e1ed3f4d0 --- /dev/null +++ b/apps/sim/lib/self-check/outcome.ts @@ -0,0 +1,48 @@ +import { getPostgresErrorCode } from '@sim/utils/errors' +import type { SelfCheckName, SelfCheckResult, SelfCheckStatus } from '@/lib/self-check/types' + +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. + */ +export 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 +} + +/** 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 = { status: 'fail', detail: `error: ${errorCode(error)}` } + } + return { name, ...outcome, durationMs: Math.round(performance.now() - startedAt) } +} + +/** Rejects with a `TimeoutError` once `ms` pass; the work itself is left to settle on its own. */ +export function withTimeout(work: Promise, ms: number): Promise { + let timer: ReturnType | undefined + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => { + const error = new Error('Timed out') + error.name = 'TimeoutError' + reject(error) + }, ms) + }) + return Promise.race([work, timeout]).finally(() => clearTimeout(timer)) +} diff --git a/apps/sim/lib/self-check/run.test.ts b/apps/sim/lib/self-check/run.test.ts new file mode 100644 index 00000000000..0474c9905e1 --- /dev/null +++ b/apps/sim/lib/self-check/run.test.ts @@ -0,0 +1,32 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { checkSandbox } = vi.hoisted(() => ({ checkSandbox: vi.fn() })) + +vi.mock('@/lib/self-check/sandbox', () => ({ checkSandbox })) +vi.mock('@/lib/self-check/infrastructure', () => ({ + checkDatabase: async () => ({ name: 'database', status: 'pass', durationMs: 0, detail: '' }), + checkMigrations: async () => ({ name: 'migrations', status: 'pass', durationMs: 0, detail: '' }), + checkRedis: async () => ({ name: 'redis', status: 'pass', durationMs: 0, detail: '' }), + checkRealtime: async () => ({ name: 'realtime', status: 'pass', durationMs: 0, detail: '' }), +})) + +import { runSelfCheck } from '@/lib/self-check/run' + +describe('runSelfCheck', () => { + beforeEach(() => { + checkSandbox.mockReset() + }) + + it('reports a sandbox check that threw as a failed check instead of rejecting', async () => { + checkSandbox.mockRejectedValueOnce(new TypeError('boom')) + const report = await runSelfCheck({ sandbox: true, realtime: false }) + expect(report.ok).toBe(false) + expect(report.checks).toContainEqual( + expect.objectContaining({ + name: 'sandbox.execution', + status: 'fail', + detail: 'error: TypeError', + }) + ) + }) +}) diff --git a/apps/sim/lib/self-check/run.ts b/apps/sim/lib/self-check/run.ts new file mode 100644 index 00000000000..d401448f869 --- /dev/null +++ b/apps/sim/lib/self-check/run.ts @@ -0,0 +1,94 @@ +import { createLogger } from '@sim/logger' +import { + checkDatabase, + checkMigrations, + checkRealtime, + checkRedis, +} from '@/lib/self-check/infrastructure' +import { errorCode } 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') + +/** Starting sandboxes is the expensive part, so repeated calls inside this window reuse it. */ +const SANDBOX_RESULT_TTL_MS = 30_000 + +interface SelfCheckOptions { + sandbox: boolean + realtime: boolean +} + +const inFlight = new Map>() +/** The sandbox run in progress, or the last one until its result goes stale. */ +let sandboxRun: { checks: Promise; settledAt: number | null } | null = null + +function sandboxChecks(): Promise { + const current = sandboxRun + if ( + current && + (current.settledAt === null || Date.now() - current.settledAt < SANDBOX_RESULT_TTL_MS) + ) { + return current.checks + } + // 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 checks = checkSandbox().catch((error): SelfCheckResult[] => [ + { + name: 'sandbox.execution', + status: 'fail', + durationMs: 0, + detail: `error: ${errorCode(error)}`, + }, + ]) + const entry: { checks: Promise; settledAt: number | null } = { + checks, + settledAt: null, + } + const settle = () => { + entry.settledAt = Date.now() + } + entry.checks.then(settle, settle) + sandboxRun = entry + return entry.checks +} + +async function run(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 +} + +/** + * 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. Concurrent + * callers with the same options share one run, so a retrying client never stacks sandbox starts. + * Every check bounds itself; no caller's request signal governs a run others may be waiting on. + */ +export function runSelfCheck(options: SelfCheckOptions): Promise { + const key = `${options.sandbox}:${options.realtime}` + const existing = inFlight.get(key) + if (existing) return existing + const running = run(options).finally(() => inFlight.delete(key)) + inFlight.set(key, running) + return running +} diff --git a/apps/sim/lib/self-check/sandbox.ts b/apps/sim/lib/self-check/sandbox.ts new file mode 100644 index 00000000000..383189e88cb --- /dev/null +++ b/apps/sim/lib/self-check/sandbox.ts @@ -0,0 +1,232 @@ +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 } 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, errorCode } from '@/lib/self-check/outcome' +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}` +} + +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)) + }) +} + +/** 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) +} + +/** The data store's addresses as the app resolves them, since user code runs in another namespace. */ +async function dataStoreTargets(url: string | undefined, defaultPort: number): Promise { + if (!url) return [] + let parsed: URL + try { + parsed = new URL(url) + } catch { + return [] + } + const host = parsed.hostname.replace(/^\[|\]$/g, '') + const port = Number(parsed.port) || defaultPort + if (!host) return [] + const addresses = isIP(host) + ? [host] + : (await lookup(host, { all: true }).catch(() => [])).map(({ address }) => address) + // 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]) +} + +/** + * 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 { status: 'fail', detail: 'capacity' } + return { status: 'fail', detail: `error: ${errorCode(error)}` } +} + +/** + * Runs user code in a sandbox, as a Function block would, and checks it is confined: the sandbox + * user, no metadata credentials, no authorized Kubernetes API, and no reach into the app, its + * private data stores, or a sibling sandbox. Only for the Kubernetes provider: the hosted + * providers bill each sandbox and isolate them outside this deployment's control. + */ +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 = Number(env.PORT) || DEFAULT_APP_PORT + const lateral: Array<{ target: Target; kind: LateralTargetKind }> = [ + ...appAddresses().map((host) => ({ target: [host, appPort] as Target, kind: 'app' as const })), + ...(await dataStoreTargets(env.DATABASE_URL, 5432)).map((target) => ({ + target, + kind: 'database' as const, + })), + ...(await dataStoreTargets(env.REDIS_URL, 6379)).map((target) => ({ + target, + kind: 'redis' as const, + })), + ] + 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), + 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/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..219375e996d 100644 --- a/helm/sim/README.md +++ b/helm/sim/README.md @@ -164,11 +164,15 @@ 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. The published +chart's `images.yaml` lists the sandbox images for its appVersion (the copy in +this repository leaves them out, since their tags change with every sandbox +image rebuild). Skip the `simstudioai/copilot*` images (enterprise) and the +`simstudioai/sandbox-*` and `pause` images (the 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 before copying; the header of +`images.yaml` explains both, and the one image whose mirror path differs. ### From the Helm repository @@ -233,6 +237,33 @@ 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, both from the `curlimages/curl` image the cron jobs already +use. The first checks the app and realtime Services answer. The second calls +the app's `/api/cron/self-check` with `CRON_SECRET` and passes only when every +check does: the database answers, its migrations match the app image, Redis +answers, realtime is healthy (when enabled), and, with +`sandbox.kubernetes.enabled`, a sandbox runs user code confined. The sandbox +check starts two sandbox pods and proves user code runs as the sandbox user, +gets no cloud metadata credentials, gets no authorized Kubernetes API, and cannot +reach the app pod, a private database or Redis address, or the other sandbox's +agent (which the app itself just reached, so the refusal is the policy's). That +last one fails on a cluster whose network plugin does not enforce +NetworkPolicy. `--logs` prints the report: one line per check with `pass`, +`fail`, `warn`, or `skip` and a short reason. + +The self-check passes as skipped when `CRON_SECRET` is not in the app Secret, +and when the app image predates the endpoint (`tests.selfCheck.requireEndpoint: +true` fails instead). Disable it with `tests.selfCheck.enabled=false`, or all +test pods with `tests.enabled=false`. With `networkPolicy.enabled`, the app and +realtime policies admit the test pods (label +`simstudio.ai/component-group: helm-test`) while `tests.enabled` is true. + --- ## Verifying the chart @@ -643,6 +674,13 @@ kubectl --namespace sim logs deploy/sim-app -c migrations --- +## Upgrading to 1.22.0 + +* **`helm test` now proves the install works.** A second test pod calls the app's authenticated `/api/cron/self-check` (see [Test the install](#test-the-install)). Run `helm test` with `--timeout 10m` when the Kubernetes sandbox provider is on: the sandbox check starts two sandbox pods. +* **`tests.image` defaults to `curlimages/curl:8.5.0`**, the image the cron jobs use, instead of `busybox:1.36`. If you pinned `tests.image` to busybox, either drop the override or set it to an image that has `curl`. +* **With `networkPolicy.enabled` and the ingress disabled, `helm test` no longer times out.** The app and realtime policies admit the test pods while `tests.enabled` is true; before, nothing did. +* **`images.yaml` covers the Kubernetes sandbox provider.** It now lists the warm-capacity `pause` image and the Mothership's `copilot-sandbox-shell` and `copilot-sandbox-doc` (with the `main-REPLACE` placeholder), and the published chart's copy also lists the `simstudioai/sandbox-*` images at the tags its appVersion pins. + ## Upgrading to 1.21.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. diff --git a/helm/sim/images.yaml b/helm/sim/images.yaml index 1cd316cef0a..1a299cbff03 100644 --- a/helm/sim/images.yaml +++ b/helm/sim/images.yaml @@ -1,13 +1,15 @@ # 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. +# enabled — mirror them into a disconnected registry before installing. The +# published chart's copy also lists the sandbox images (`simstudioai/sandbox-*`) +# the app starts at run time, at the tags its appVersion pins. Some are not part of an ordinary +# install: the `simstudioai/copilot*` images (the Mothership and its sandboxes) +# require enterprise registry access, and the `simstudioai/sandbox-*` and +# `pause` images serve only the Kubernetes sandbox provider. Skip any you do not +# use. 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. # # To redirect them, set `global.imageRegistry` to your registry AND # `global.useRegistryForAllImages: true` — on its own, `imageRegistry` only @@ -27,10 +29,12 @@ # 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-sandbox-doc:main-REPLACE + mirror: simstudioai/copilot-sandbox-doc:main-REPLACE + - source: docker.io/simstudioai/copilot-sandbox-shell:main-REPLACE + mirror: simstudioai/copilot-sandbox-shell:main-REPLACE - source: docker.io/simstudioai/copilot:main-REPLACE mirror: simstudioai/copilot:main-REPLACE - source: ghcr.io/simstudioai/migrations:v0.8.26 @@ -53,3 +57,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/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/test-connection.yaml b/helm/sim/templates/tests/test-connection.yaml index 12c5dd952fd..e114e185126 100644 --- a/helm/sim/templates/tests/test-connection.yaml +++ b/helm/sim/templates/tests/test-connection.yaml @@ -7,6 +7,7 @@ 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 @@ -45,7 +46,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..2204cc4f485 --- /dev/null +++ b/helm/sim/templates/tests/test-self-check.yaml @@ -0,0 +1,112 @@ +{{- /* + Proves the install works, not only that it answers: calls the app's + /api/cron/self-check with the cron secret and passes only on {"ok":true}. + The app checks its database, migrations, Redis, realtime, and, with the + Kubernetes sandbox provider, that a sandbox runs user code confined. Runs + after the connectivity probe (hook weight), which waits out Service routing. +*/}} +{{- 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,hook-succeeded +spec: + restartPolicy: Never + automountServiceAccountToken: false + {{- with .Values.tests.image.pullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 4 }} + {{- end }} + securityContext: + runAsNonRoot: true + runAsUser: 65534 + runAsGroup: 65534 + fsGroup: 65534 + seccompProfile: + type: RuntimeDefault + containers: + - name: self-check + 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 + 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 + {{- if $selfCheck.requireEndpoint }} + echo "FAILED: the app answered 404; its image predates the self-check endpoint" + exit 1 + {{- else }} + echo "SKIP: app image predates self-check" + exit 0 + {{- end }} + 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/self-check_test.yaml b/helm/sim/tests/self-check_test.yaml new file mode 100644 index 00000000000..b26f34119cd --- /dev/null +++ b/helm/sim/tests/self-check_test.yaml @@ -0,0 +1,199 @@ +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: 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: fails rather than skips on a 404 when the endpoint is required + template: tests/test-self-check.yaml + set: + <<: *defaults + tests.selfCheck.requireEndpoint: true + asserts: + - matchRegex: + path: spec.containers[0].command[2] + pattern: 'answered 404[^\n]*\n\s*exit 1' + - notMatchRegex: + path: spec.containers[0].command[2] + pattern: 'SKIP: app image predates self-check' + + - 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..2a630194a55 100644 --- a/helm/sim/values.schema.json +++ b/helm/sim/values.schema.json @@ -913,6 +913,23 @@ } }, "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": "Limit on the self-check request; a sandbox check starts two sandbox pods" + }, + "requireEndpoint": { + "type": "boolean", + "description": "Fail instead of skipping when the app image predates the self-check endpoint" + } + } + }, "resources": { "type": "object" } } }, diff --git a/helm/sim/values.yaml b/helm/sim/values.yaml index 343649d0c50..9fcea62d2a0 100644 --- a/helm/sim/values.yaml +++ b/helm/sim/values.yaml @@ -2314,17 +2314,30 @@ 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 (helm test). Run with: helm test --logs +# A connectivity probe checks the app and realtime Services answer from inside +# the cluster; the self-check proves the install works. Both use the curl image +# the cron jobs already pull, so a mirrored registry needs nothing extra. tests: enabled: true image: - repository: busybox - tag: "1.36" + repository: curlimages/curl + tag: "8.5.0" pullPolicy: IfNotPresent pullSecrets: [] timeoutSeconds: 5 + # Calls the app's /api/cron/self-check with CRON_SECRET: database reachable, + # migrations applied, Redis answering, realtime healthy (when enabled), and, + # with sandbox.kubernetes.enabled, a sandbox that runs user code confined (no + # metadata credentials, no authorized Kubernetes API, no reach into the app, + # its private data stores, or another sandbox). Skips, passing, when + # CRON_SECRET is not in the app Secret, or when the app image predates the + # endpoint unless requireEndpoint is true. + selfCheck: + enabled: true + # The sandbox check starts two sandbox pods; a cold image pull can take minutes. + timeoutSeconds: 240 + requireEndpoint: false 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..cb8e769fede 100644 --- a/scripts/generate-image-manifest.test.ts +++ b/scripts/generate-image-manifest.test.ts @@ -1,5 +1,11 @@ import { describe, expect, it } from 'vitest' -import { collectImages, pairSources } from './generate-image-manifest' +import { + collectImages, + mergeImageEntries, + pairSources, + parseSandboxImageReferences, + sandboxImageEntries, +} from './generate-image-manifest' describe('collectImages', () => { it('finds images across every container key a pod spec can use', () => { @@ -70,3 +76,63 @@ 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/) + }) +}) + +describe('parseSandboxImageReferences', () => { + it('reads every reference the app pins', () => { + expect( + parseSandboxImageReferences( + '{"function": "ghcr.io/simstudioai/sandbox-function:a", "agent": "ghcr.io/simstudioai/sandbox-agent:b"}' + ) + ).toEqual(['ghcr.io/simstudioai/sandbox-function:a', '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 an inventory without the sandbox images', (_, json) => { + expect(() => parseSandboxImageReferences(json)).toThrow(/images.generated.json/) + }) +}) diff --git a/scripts/generate-image-manifest.ts b/scripts/generate-image-manifest.ts index 62b7c48c86d..b22feb2a52a 100644 --- a/scripts/generate-image-manifest.ts +++ b/scripts/generate-image-manifest.ts @@ -19,7 +19,14 @@ * 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 { spawnSync } from 'node:child_process' import { readFile, writeFile } from 'node:fs/promises' import { dirname, resolve } from 'node:path' import { fileURLToPath } from 'node:url' @@ -29,14 +36,19 @@ 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,31 @@ 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', +] as const + +/** + * The sandbox images the app starts at run time, which no rendered pod names. + * The app's defaults are the references this file pins, read at the release tag. + */ +const SANDBOX_IMAGES_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 Mothership's sandbox images (`sandbox.kubernetes.images.mothership` and + * `.doc`), which have no default and are versioned with the Mothership, so they + * carry its `main-REPLACE` placeholder tag. + */ +const MOTHERSHIP_SANDBOX_IMAGES = [ + 'docker.io/simstudioai/copilot-sandbox-doc:main-REPLACE', + 'docker.io/simstudioai/copilot-sandbox-shell:main-REPLACE', ] as const /** @@ -154,6 +191,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[] @@ -165,13 +232,15 @@ 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. +# enabled — mirror them into a disconnected registry before installing. The +# published chart's copy also lists the sandbox images (\`simstudioai/sandbox-*\`) +# the app starts at run time, at the tags its appVersion pins. Some are not part of an ordinary +# install: the \`simstudioai/copilot*\` images (the Mothership and its sandboxes) +# require enterprise registry access, and the \`simstudioai/sandbox-*\` and +# \`pause\` images serve only the Kubernetes sandbox provider. Skip any you do not +# use. 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. # # To redirect them, set \`global.imageRegistry\` to your registry AND # \`global.useRegistryForAllImages: true\` — on its own, \`imageRegistry\` only @@ -218,13 +287,67 @@ function renderChart(args: readonly string[] = RENDER_ARGS): unknown[] { return Array.isArray(documents) ? documents : [documents] } +function git(args: readonly string[]): { ok: boolean; stdout: string } { + const result = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' }) + return { ok: result.status === 0, stdout: result.stdout ?? '' } +} + +/** + * The sandbox image references the app at `release` defaults to. Publish jobs + * check out shallow, so the tag is fetched when absent. On the release merge + * itself the tag does not exist yet (that commit cuts it), so HEAD is read when + * its subject names the release, the same rule helm.yml resolves the version by. + */ +function releaseSandboxImages(release: string): string[] { + if (!RELEASE_TAG.test(release)) { + throw new Error(`--release must be a release tag like v1.2.3, got "${release}"`) + } + const tagRef = `refs/tags/${release}` + if (!git(['rev-parse', '--verify', '--quiet', tagRef]).ok) { + git(['fetch', '--quiet', '--no-tags', '--depth', '1', 'origin', `+${tagRef}:${tagRef}`]) + } + let ref = tagRef + if (!git(['rev-parse', '--verify', '--quiet', tagRef]).ok) { + const subject = git(['log', '-1', '--format=%s', 'HEAD']).stdout.trim() + if (!subject.startsWith(`${release}:`)) { + throw new Error(`Release ${release} has no tag and HEAD is not its release commit`) + } + ref = 'HEAD' + } + // A release from before the Kubernetes sandbox provider starts no sandbox images. + if (!git(['cat-file', '-e', `${ref}:${SANDBOX_IMAGES_PATH}`]).ok) { + console.log(`${release} has no ${SANDBOX_IMAGES_PATH}; listing no sandbox images.`) + return [] + } + const shown = git(['show', `${ref}:${SANDBOX_IMAGES_PATH}`]) + if (!shown.ok) throw new Error(`Could not read ${SANDBOX_IMAGES_PATH} at ${ref}`) + return parseSandboxImageReferences(shown.stdout) +} + +/** The references in `images.generated.json`, refusing anything that is not a string map. */ +export function parseSandboxImageReferences(json: string): string[] { + const parsed: unknown = JSON.parse(json) + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`${SANDBOX_IMAGES_PATH} is not an object of image references`) + } + const references = Object.values(parsed) + if ( + references.length > 0 && + references.every((value): value is string => typeof value === 'string') + ) { + return references + } + throw new Error(`${SANDBOX_IMAGES_PATH} holds a non-string or no image reference`) +} + 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, ...MOTHERSHIP_SANDBOX_IMAGES]) ), }) diff --git a/scripts/sync-chart-appversion.ts b/scripts/sync-chart-appversion.ts index eb56756a4cb..caa35d68526 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,14 @@ 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 + * 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}`) } From d8736b5e6dd1b404698f717765f23ee0386e2055 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 11:02:32 -0600 Subject: [PATCH 2/6] fix(self-hosting): fail-closed self-check, every database endpoint, and keep helm test pods for their logs --- .github/workflows/helm.yml | 4 +- .github/workflows/sandbox.yml | 2 + .../kubernetes/confinement-probe.ts | 56 ++++++++++++++--- apps/sim/lib/self-check/confinement.test.ts | 27 +++++++- apps/sim/lib/self-check/confinement.ts | 23 +++++++ .../sim/lib/self-check/infrastructure.test.ts | 29 +++++++++ apps/sim/lib/self-check/infrastructure.ts | 5 +- apps/sim/lib/self-check/sandbox.ts | 58 +++++++++-------- apps/sim/lib/self-check/targets.test.ts | 36 +++++++++++ apps/sim/lib/self-check/targets.ts | 63 +++++++++++++++++++ helm/sim/README.md | 3 +- helm/sim/images.yaml | 8 +-- helm/sim/templates/tests/test-connection.yaml | 2 +- helm/sim/templates/tests/test-self-check.yaml | 4 +- helm/sim/tests/helm-test-hook_test.yaml | 2 +- helm/sim/tests/self-check_test.yaml | 11 ++++ scripts/generate-image-manifest.test.ts | 34 ++++++++++ scripts/generate-image-manifest.ts | 34 ++++++---- 18 files changed, 339 insertions(+), 62 deletions(-) create mode 100644 apps/sim/lib/self-check/infrastructure.test.ts create mode 100644 apps/sim/lib/self-check/targets.test.ts create mode 100644 apps/sim/lib/self-check/targets.ts diff --git a/.github/workflows/helm.yml b/.github/workflows/helm.yml index d77d88103e9..38a96160e40 100644 --- a/.github/workflows/helm.yml +++ b/.github/workflows/helm.yml @@ -232,8 +232,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: | diff --git a/.github/workflows/sandbox.yml b/.github/workflows/sandbox.yml index dc5a98bb3b0..94ac7e48b6b 100644 --- a/.github/workflows/sandbox.yml +++ b/.github/workflows/sandbox.yml @@ -75,6 +75,7 @@ on: - '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. @@ -217,6 +218,7 @@ jobs: - '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/**' diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts index a325daa2ab7..f8d7f36f058 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts @@ -4,6 +4,49 @@ import { SIM_RESULT_PREFIX } from '@/lib/execution/remote-sandbox' const METADATA_ADDRESS = '169.254.169.254' +/** + * Endpoints that would hand user code node identity or cloud credentials. `headers` is a Python + * expression: `aws` is the IMDSv2 token header the probe fetches first. + */ +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: '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 { @@ -122,15 +165,10 @@ with ThreadPoolExecutor(max_workers=32) as pool: # 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 = { - 'aws instance-id': ('http://${METADATA_ADDRESS}/latest/meta-data/instance-id', aws), - 'aws user-data': ('http://${METADATA_ADDRESS}/latest/user-data', aws), - 'aws iam credentials': ('http://${METADATA_ADDRESS}/latest/meta-data/iam/security-credentials/', aws), - 'eks pod identity': ('http://169.254.170.23/v1/credentials', None), - 'ecs task credentials': ('http://169.254.170.2/v2/credentials', None), - 'gcp instance id': ('http://${METADATA_ADDRESS}/computeMetadata/v1/instance/id', {'Metadata-Flavor': 'Google'}), - 'azure instance': ('http://${METADATA_ADDRESS}/metadata/instance?api-version=2021-02-01', {'Metadata': 'true'}), - 'gcp service account token': ('http://${METADATA_ADDRESS}/computeMetadata/v1/instance/service-accounts/default/token', {'Metadata-Flavor': 'Google'}), - 'azure managed identity token': ('http://${METADATA_ADDRESS}/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/', {'Metadata': 'true'}), +${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) diff --git a/apps/sim/lib/self-check/confinement.test.ts b/apps/sim/lib/self-check/confinement.test.ts index dbcd340d771..e3240aae3da 100644 --- a/apps/sim/lib/self-check/confinement.test.ts +++ b/apps/sim/lib/self-check/confinement.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it } from 'vitest' -import type { ConfinementFacts } from '@/lib/execution/remote-sandbox/kubernetes/confinement-probe' +import { + type ConfinementFacts, + METADATA_ENDPOINT_NAMES, +} from '@/lib/execution/remote-sandbox/kubernetes/confinement-probe' import { type ConfinementPlan, evaluateConfinement, @@ -19,6 +22,7 @@ const plan: ConfinementPlan = { { key: REDIS, kind: 'redis' }, ], neighbor: NEIGHBOR, + apiTargets: ['kubernetes.default.svc:443', '10.43.0.1:443'], resolveNames: ['kubernetes.default.svc', 'example.com'], } @@ -41,7 +45,9 @@ function confinedFacts(overrides: Partial = {}): ConfinementFa agentWithForgedToken: 401, api: { 'kubernetes.default.svc:443': 'unreachable', '10.43.0.1:443': 'unreachable' }, metadata: false, - metadataSecrets: { 'aws iam credentials': 'unreachable', 'gcp instance id': 'unreachable' }, + 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: {}, @@ -190,6 +196,23 @@ describe('judgeProbeResult', () => { }) }) +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'])( 'drops %s, which reaches the app pod itself or its sidecar rather than a peer', diff --git a/apps/sim/lib/self-check/confinement.ts b/apps/sim/lib/self-check/confinement.ts index 0cbbe187d2d..d72383ac0b4 100644 --- a/apps/sim/lib/self-check/confinement.ts +++ b/apps/sim/lib/self-check/confinement.ts @@ -2,6 +2,7 @@ import { 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' @@ -19,6 +20,8 @@ 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[] /** * 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 @@ -129,6 +132,20 @@ export function evaluateConfinement( } } +/** + * 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 fails * the sandbox check instead of throwing, so a changed or truncated probe never turns the @@ -141,6 +158,12 @@ export function judgeProbeResult( 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, + } + } try { return { execution: { status: 'pass', detail: 'ran user code' }, 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..5b8a09dacb6 --- /dev/null +++ b/apps/sim/lib/self-check/infrastructure.test.ts @@ -0,0 +1,29 @@ +import { resetEnvMock, setEnv } from '@sim/testing/mocks/env.mock' +import { resetUrlsMock, urlsMockFns } from '@sim/testing/mocks/urls.mock' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { checkRealtime, checkRedis } from '@/lib/self-check/infrastructure' + +afterEach(() => { + resetEnvMock() + resetUrlsMock() +}) + +describe('checkRedis', () => { + it('fails when REDIS_URL is unset, since the app requires Redis', async () => { + setEnv({ REDIS_URL: undefined }) + expect(await checkRedis()).toMatchObject({ name: 'redis', status: 'fail' }) + }) +}) + +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 index 170d9e5cff5..b5f3e0c57f9 100644 --- a/apps/sim/lib/self-check/infrastructure.ts +++ b/apps/sim/lib/self-check/infrastructure.ts @@ -52,7 +52,8 @@ export function checkMigrations(): Promise { export function checkRedis(): Promise { return timed('redis', async () => { - if (!env.REDIS_URL) return { status: 'skip', detail: 'REDIS_URL is not set' } + // 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 withTimeout(getRedisClient().ping(), REDIS_TIMEOUT_MS) return { status: 'pass', detail: 'ping answered' } }) @@ -60,7 +61,7 @@ export function checkRedis(): Promise { export function checkRealtime(): Promise { return timed('realtime', async () => { - const response = await fetch(`${getSocketServerUrl()}/health`, { + const response = await fetch(`${getSocketServerUrl().replace(/\/+$/, '')}/health`, { signal: AbortSignal.timeout(REALTIME_TIMEOUT_MS), }) await response.body?.cancel() diff --git a/apps/sim/lib/self-check/sandbox.ts b/apps/sim/lib/self-check/sandbox.ts index 383189e88cb..03e96b50977 100644 --- a/apps/sim/lib/self-check/sandbox.ts +++ b/apps/sim/lib/self-check/sandbox.ts @@ -2,7 +2,7 @@ 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 } from '@/lib/core/config/env' +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' @@ -18,6 +18,7 @@ import { type LateralTargetKind, } from '@/lib/self-check/confinement' import { type CheckOutcome, errorCode } from '@/lib/self-check/outcome' +import { DATABASE_URL_NAMES, 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`. */ @@ -65,23 +66,32 @@ function appAddresses(): string[] { .filter(isProbeTargetAddress) } -/** The data store's addresses as the app resolves them, since user code runs in another namespace. */ -async function dataStoreTargets(url: string | undefined, defaultPort: number): Promise { - if (!url) return [] - let parsed: URL - try { - parsed = new URL(url) - } catch { - return [] - } - const host = parsed.hostname.replace(/^\[|\]$/g, '') - const port = Number(parsed.port) || defaultPort - if (!host) return [] - const addresses = isIP(host) - ? [host] - : (await lookup(host, { all: true }).catch(() => [])).map(({ address }) => address) - // 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]) +/** + * 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. + */ +async function dataStoreTargets(): Promise> { + const endpoints = dataStoreEndpoints({ + ...Object.fromEntries(DATABASE_URL_NAMES.map((name) => [name, env[name]])), + REDIS_URL: env.REDIS_URL, + }) + const resolved = await Promise.all( + endpoints.map(async ({ kind, host, port }) => { + const addresses = isIP(host) + ? [host] + : (await lookup(host, { all: true }).catch(() => [])).map(({ address }) => address) + // 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() + return resolved.flat().filter(({ target }) => { + if (seen.has(key(target))) return false + seen.add(key(target)) + return true + }) } /** @@ -179,17 +189,10 @@ async function probe( signal: AbortSignal, elapsed: () => number ): Promise { - const appPort = Number(env.PORT) || DEFAULT_APP_PORT + const appPort = envNumber(env.PORT, DEFAULT_APP_PORT, { min: 1, integer: true }) const lateral: Array<{ target: Target; kind: LateralTargetKind }> = [ ...appAddresses().map((host) => ({ target: [host, appPort] as Target, kind: 'app' as const })), - ...(await dataStoreTargets(env.DATABASE_URL, 5432)).map((target) => ({ - target, - kind: 'database' as const, - })), - ...(await dataStoreTargets(env.REDIS_URL, 6379)).map((target) => ({ - target, - kind: 'redis' as const, - })), + ...(await dataStoreTargets()), ] const neighborTarget: Target = [neighborAddress, SANDBOX_AGENT_PORT] const apiTargets: Target[] = [[CLUSTER_API_NAME, 443]] @@ -216,6 +219,7 @@ async function probe( const plan: ConfinementPlan = { lateral: lateral.map(({ target, kind }) => ({ key: key(target), kind })), neighbor: key(neighborTarget), + apiTargets: apiTargets.map(key), resolveNames: RESOLVE_NAMES, } const judged = judgeProbeResult(execution.result, plan) 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..26de826133e --- /dev/null +++ b/apps/sim/lib/self-check/targets.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest' +import { dataStoreEndpoints } from '@/lib/self-check/targets' + +describe('dataStoreEndpoints', () => { + it('lists every database endpoint the app may use: primary, per-role, and replicas', () => { + expect( + dataStoreEndpoints({ + DATABASE_URL: 'postgresql://u:p@primary.internal:5432/sim', + DATABASE_URL_AUTH: 'postgresql://u:p@pgbouncer.internal:6432/sim', + DATABASE_REPLICA_URL: 'postgresql://u:p@replica.internal/sim', + DATABASE_REPLICA_URL_TRIGGER: 'postgresql://u:p@[fd00::7]:5433/sim', + REDIS_URL: 'rediss://cache.internal:6380', + }) + ).toEqual([ + { kind: 'database', host: 'primary.internal', port: 5432 }, + { kind: 'database', host: 'replica.internal', port: 5432 }, + { kind: 'database', host: 'pgbouncer.internal', port: 6432 }, + { kind: 'database', host: 'fd00::7', port: 5433 }, + { kind: 'redis', host: 'cache.internal', port: 6380 }, + ]) + }) + + 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..b303748ca79 --- /dev/null +++ b/apps/sim/lib/self-check/targets.ts @@ -0,0 +1,63 @@ +/** + * Every variable the app may open a database connection from: the primary, the per-role and + * per-pool overrides `@sim/db` resolves, and the replicas. User code must reach none of them. + */ +export const DATABASE_URL_NAMES = [ + 'DATABASE_URL', + 'DATABASE_REPLICA_URL', + 'DATABASE_URL_WEB', + 'DATABASE_URL_TRIGGER', + 'DATABASE_URL_REALTIME', + 'DATABASE_URL_CLEANUP', + 'DATABASE_URL_EXEC', + 'DATABASE_URL_BILLING', + 'DATABASE_URL_AUTH', + 'DATABASE_REPLICA_URL_WEB', + 'DATABASE_REPLICA_URL_TRIGGER', + 'DATABASE_REPLICA_URL_REALTIME', +] as const + +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. Hosts stay unresolved: + * the caller resolves them as the app does, since user code runs in another namespace. + */ +export function dataStoreEndpoints( + values: Partial> +): 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/helm/sim/README.md b/helm/sim/README.md index 219375e996d..1a7810a4080 100644 --- a/helm/sim/README.md +++ b/helm/sim/README.md @@ -255,7 +255,8 @@ reach the app pod, a private database or Redis address, or the other sandbox's agent (which the app itself just reached, so the refusal is the policy's). That last one fails on a cluster whose network plugin does not enforce NetworkPolicy. `--logs` prints the report: one line per check with `pass`, -`fail`, `warn`, or `skip` and a short reason. +`fail`, `warn`, or `skip` and a short reason. The test pods stay until the next +`helm test` replaces them, so `kubectl logs` reads them afterwards too. The self-check passes as skipped when `CRON_SECRET` is not in the app Secret, and when the app image predates the endpoint (`tests.selfCheck.requireEndpoint: diff --git a/helm/sim/images.yaml b/helm/sim/images.yaml index 1a299cbff03..f57de0288c8 100644 --- a/helm/sim/images.yaml +++ b/helm/sim/images.yaml @@ -31,12 +31,12 @@ appVersion: v0.8.26 images: - source: curlimages/curl:8.5.0 mirror: curlimages/curl:8.5.0 - - source: docker.io/simstudioai/copilot-sandbox-doc:main-REPLACE - mirror: simstudioai/copilot-sandbox-doc:main-REPLACE - - source: docker.io/simstudioai/copilot-sandbox-shell:main-REPLACE - mirror: simstudioai/copilot-sandbox-shell:main-REPLACE - 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 diff --git a/helm/sim/templates/tests/test-connection.yaml b/helm/sim/templates/tests/test-connection.yaml index e114e185126..b65076df14e 100644 --- a/helm/sim/templates/tests/test-connection.yaml +++ b/helm/sim/templates/tests/test-connection.yaml @@ -10,7 +10,7 @@ metadata: 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 }} diff --git a/helm/sim/templates/tests/test-self-check.yaml b/helm/sim/templates/tests/test-self-check.yaml index 2204cc4f485..83a83f893dc 100644 --- a/helm/sim/templates/tests/test-self-check.yaml +++ b/helm/sim/templates/tests/test-self-check.yaml @@ -4,6 +4,8 @@ The app checks its database, migrations, Redis, realtime, and, with the Kubernetes sandbox provider, that a sandbox runs user code confined. Runs after the connectivity probe (hook weight), which waits out Service routing. + Both test pods stay after a pass, so `helm test --logs` and `kubectl logs` + can read them; the next `helm test` replaces them. */}} {{- if and .Values.tests.enabled .Values.tests.selfCheck.enabled }} {{- $selfCheck := .Values.tests.selfCheck }} @@ -19,7 +21,7 @@ metadata: annotations: "helm.sh/hook": test "helm.sh/hook-weight": "1" - "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded + "helm.sh/hook-delete-policy": before-hook-creation spec: restartPolicy: Never automountServiceAccountToken: false 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/self-check_test.yaml b/helm/sim/tests/self-check_test.yaml index b26f34119cd..b6bfec8f2c4 100644 --- a/helm/sim/tests/self-check_test.yaml +++ b/helm/sim/tests/self-check_test.yaml @@ -95,6 +95,17 @@ tests: 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: 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: diff --git a/scripts/generate-image-manifest.test.ts b/scripts/generate-image-manifest.test.ts index cb8e769fede..263ab679dd0 100644 --- a/scripts/generate-image-manifest.test.ts +++ b/scripts/generate-image-manifest.test.ts @@ -47,6 +47,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( diff --git a/scripts/generate-image-manifest.ts b/scripts/generate-image-manifest.ts index b22feb2a52a..db1c1d0702a 100644 --- a/scripts/generate-image-manifest.ts +++ b/scripts/generate-image-manifest.ts @@ -66,6 +66,12 @@ const RENDER_ARGS = [ '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 /** @@ -77,16 +83,6 @@ const SANDBOX_IMAGES_PATH = 'apps/sim/lib/execution/remote-sandbox/kubernetes/im /** A release tag as this repository cuts them: `v1.2.3`. */ const RELEASE_TAG = /^v\d+\.\d+\.\d+$/ -/** - * The Mothership's sandbox images (`sandbox.kubernetes.images.mothership` and - * `.doc`), which have no default and are versioned with the Mothership, so they - * carry its `main-REPLACE` placeholder tag. - */ -const MOTHERSHIP_SANDBOX_IMAGES = [ - 'docker.io/simstudioai/copilot-sandbox-doc:main-REPLACE', - 'docker.io/simstudioai/copilot-sandbox-shell:main-REPLACE', -] as const - /** * Sentinel registry used for the second render. * @@ -112,6 +108,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. * @@ -133,8 +135,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) @@ -347,7 +357,7 @@ async function main(): Promise { appVersion: readChartField(chart, 'appVersion'), images: mergeImageEntries( pairSources(collectImages(renderChart()), collectImages(renderChart(MIRROR_RENDER_ARGS))), - sandboxImageEntries([...runtimeImages, ...MOTHERSHIP_SANDBOX_IMAGES]) + sandboxImageEntries(runtimeImages) ), }) From 49d8a7c6f549c6a8237ff16a97a1067ab3d3c297 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 11:19:38 -0600 Subject: [PATCH 3/6] improvement(self-hosting): simpler self-check, logged failures, every DB pool, and helm test in the docs --- .github/workflows/helm.yml | 7 +- .github/workflows/sandbox.yml | 31 ++++++--- .../docs/platform/self-hosting/kubernetes.mdx | 4 +- .../docs/platform/self-hosting/verify.mdx | 2 + apps/sim/lib/core/config/env.ts | 1 + .../kubernetes/confinement-probe.test.ts | 19 ++++++ .../kubernetes/confinement-probe.ts | 22 ++++-- apps/sim/lib/self-check/confinement.test.ts | 6 ++ apps/sim/lib/self-check/confinement.ts | 22 +++--- .../sim/lib/self-check/infrastructure.test.ts | 12 +--- apps/sim/lib/self-check/infrastructure.ts | 10 +-- apps/sim/lib/self-check/outcome.ts | 36 ++++++---- apps/sim/lib/self-check/run.test.ts | 32 --------- apps/sim/lib/self-check/run.ts | 67 ++++++------------- apps/sim/lib/self-check/sandbox.ts | 49 +++++++------- apps/sim/lib/self-check/targets.test.ts | 31 ++++++--- apps/sim/lib/self-check/targets.ts | 31 +++++---- helm/sim/README.md | 50 ++++++-------- helm/sim/images.yaml | 16 ++--- helm/sim/templates/NOTES.txt | 3 + helm/sim/templates/tests/_pod.tpl | 37 ++++++++++ helm/sim/templates/tests/test-connection.yaml | 24 +------ helm/sim/templates/tests/test-self-check.yaml | 40 ++--------- helm/sim/tests/self-check_test.yaml | 32 +++++---- helm/sim/values.schema.json | 6 +- helm/sim/values.yaml | 14 +--- scripts/generate-image-manifest.ts | 16 ++--- scripts/sync-chart-appversion.ts | 5 +- 28 files changed, 300 insertions(+), 325 deletions(-) create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.test.ts delete mode 100644 apps/sim/lib/self-check/run.test.ts create mode 100644 helm/sim/templates/tests/_pod.tpl diff --git a/.github/workflows/helm.yml b/.github/workflows/helm.yml index 38a96160e40..22966f7bab4 100644 --- a/.github/workflows/helm.yml +++ b/.github/workflows/helm.yml @@ -12,6 +12,8 @@ on: # change to its generator has to run this workflow too. - 'scripts/generate-image-manifest.ts' - 'scripts/write-chart-sandbox-images.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 +26,8 @@ on: # change to its generator has to run this workflow too. - 'scripts/generate-image-manifest.ts' - 'scripts/write-chart-sandbox-images.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 +196,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 @@ -246,6 +250,7 @@ jobs: kubectl -n sim logs sim-test-connection || true kubectl -n sim-upgrade get pods -o wide || true kubectl -n sim-upgrade get events --sort-by=.lastTimestamp | tail -20 || true + kubectl -n sim logs sim-test-self-check || true # Resolved once and shared, so the two publish paths cannot package the same # immutable chart version with different appVersions -- they run in parallel, diff --git a/.github/workflows/sandbox.yml b/.github/workflows/sandbox.yml index 94ac7e48b6b..266e15c5ff5 100644 --- a/.github/workflows/sandbox.yml +++ b/.github/workflows/sandbox.yml @@ -214,6 +214,10 @@ 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' @@ -229,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/**' @@ -1103,7 +1109,6 @@ jobs: --set "app.env.INTERNAL_API_SECRET=${E2E_INTERNAL_SECRET}" \ --set "app.env.CRON_SECRET=${E2E_CRON_SECRET}" \ --set "postgresql.auth.password=${E2E_DB_SECRET}" \ - --set tests.selfCheck.requireEndpoint=true \ --wait --timeout 20m kubectl get pods --namespace "$RELEASE_NAMESPACE" -o wide @@ -1155,9 +1160,17 @@ jobs: # 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 must exist (requireEndpoint). + # 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: helm test sim --namespace "$RELEASE_NAMESPACE" --logs --timeout 10m + 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 @@ -1200,12 +1213,12 @@ jobs: kubernetes.io/metadata.name: ${SANDBOX_NAMESPACE} EOF report="$RUNNER_TEMP/self-check-open-boundary.json" - # The app reuses a sandbox result for 30 seconds and the policy - # controller applies policies asynchronously, so each attempt waits - # past both. - for attempt in $(seq 1 6); do - sleep 35 - status="$(curl -sS --max-time 240 -o "$report" -w '%{http_code}' \ + # The policy controller applies policies asynchronously, so each + # attempt waits for it. Bounded to about 12 minutes in all, inside + # the job's timeout. + for attempt in $(seq 1 4); do + sleep 10 + status="$(curl -sS --max-time 170 -o "$report" -w '%{http_code}' \ -H "Authorization: Bearer ${E2E_CRON_SECRET}" \ 'http://localhost:3000/api/cron/self-check?sandbox=1&realtime=0')" || status=000 echo "Attempt ${attempt}: HTTP ${status}" 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/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/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 index f8d7f36f058..edc62d4dbd8 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts @@ -68,6 +68,15 @@ interface ConfinementProbeTargets { * 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 @@ -97,13 +106,12 @@ def resolves(name): except OSError: return False -def api(host, port): +def api(host, port, url): 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 @@ -154,7 +162,13 @@ def owner(pid): def key(host, port): return '%s:%d' % (host, port) -api_targets = ${JSON.stringify(targets.apiTargets)} +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 ?? [])} @@ -172,7 +186,7 @@ ${METADATA_REQUESTS.map( } 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) for h, p in api_targets} + 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} diff --git a/apps/sim/lib/self-check/confinement.test.ts b/apps/sim/lib/self-check/confinement.test.ts index e3240aae3da..21fdaf5e853 100644 --- a/apps/sim/lib/self-check/confinement.test.ts +++ b/apps/sim/lib/self-check/confinement.test.ts @@ -23,6 +23,7 @@ const plan: ConfinementPlan = { ], neighbor: NEIGHBOR, apiTargets: ['kubernetes.default.svc:443', '10.43.0.1:443'], + unresolved: [], resolveNames: ['kubernetes.default.svc', 'example.com'], } @@ -100,6 +101,11 @@ describe('evaluateConfinement', () => { }) }) + 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 }, diff --git a/apps/sim/lib/self-check/confinement.ts b/apps/sim/lib/self-check/confinement.ts index d72383ac0b4..76885b6b9ba 100644 --- a/apps/sim/lib/self-check/confinement.ts +++ b/apps/sim/lib/self-check/confinement.ts @@ -22,6 +22,8 @@ export interface ConfinementPlan { 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 @@ -89,6 +91,7 @@ function lateral(facts: ConfinementFacts, plan: ConfinementPlan): CheckOutcome { 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)) { @@ -147,9 +150,9 @@ function coversPlan(facts: ConfinementFacts, plan: ConfinementPlan): boolean { } /** - * Judges the probe's raw result. A result that is not the full set of facts the rules read fails - * the sandbox check instead of throwing, so a changed or truncated probe never turns the - * self-check into a 500 or a pass. + * 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, @@ -164,16 +167,9 @@ export function judgeProbeResult( outcomes: null, } } - try { - return { - execution: { status: 'pass', detail: 'ran user code' }, - outcomes: evaluateConfinement(value, plan), - } - } catch { - return { - execution: { status: 'fail', detail: 'the probe result could not be judged' }, - outcomes: null, - } + return { + execution: { status: 'pass', detail: 'ran user code' }, + outcomes: evaluateConfinement(value, plan), } } diff --git a/apps/sim/lib/self-check/infrastructure.test.ts b/apps/sim/lib/self-check/infrastructure.test.ts index 5b8a09dacb6..98ced975e88 100644 --- a/apps/sim/lib/self-check/infrastructure.test.ts +++ b/apps/sim/lib/self-check/infrastructure.test.ts @@ -1,20 +1,12 @@ -import { resetEnvMock, setEnv } from '@sim/testing/mocks/env.mock' import { resetUrlsMock, urlsMockFns } from '@sim/testing/mocks/urls.mock' import { afterEach, describe, expect, it, vi } from 'vitest' -import { checkRealtime, checkRedis } from '@/lib/self-check/infrastructure' +import { checkRealtime } from '@/lib/self-check/infrastructure' +// The shared Vitest config restores the stubbed fetch after every test (unstubGlobals). afterEach(() => { - resetEnvMock() resetUrlsMock() }) -describe('checkRedis', () => { - it('fails when REDIS_URL is unset, since the app requires Redis', async () => { - setEnv({ REDIS_URL: undefined }) - expect(await checkRedis()).toMatchObject({ name: 'redis', status: 'fail' }) - }) -}) - describe('checkRealtime', () => { it('asks a SOCKET_SERVER_URL with a trailing slash for /health, not //health', async () => { urlsMockFns.mockGetSocketServerUrl.mockReturnValueOnce('http://sim-realtime:3002//') diff --git a/apps/sim/lib/self-check/infrastructure.ts b/apps/sim/lib/self-check/infrastructure.ts index b5f3e0c57f9..ab1ab1d7a0a 100644 --- a/apps/sim/lib/self-check/infrastructure.ts +++ b/apps/sim/lib/self-check/infrastructure.ts @@ -5,7 +5,7 @@ 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, withTimeout } from '@/lib/self-check/outcome' +import { timed, untilAborted } from '@/lib/self-check/outcome' import type { SelfCheckResult } from '@/lib/self-check/types' const DATABASE_TIMEOUT_MS = 5_000 @@ -17,7 +17,7 @@ const PG_INSUFFICIENT_PRIVILEGE = '42501' export function checkDatabase(): Promise { return timed('database', async () => { - await withTimeout(db.execute(sql`select 1`), DATABASE_TIMEOUT_MS) + await untilAborted(db.execute(sql`select 1`), AbortSignal.timeout(DATABASE_TIMEOUT_MS)) return { status: 'pass', detail: 'connected' } }) } @@ -31,11 +31,11 @@ export function checkMigrations(): Promise { const expected = Math.max(...journal.entries.map((entry) => entry.when)) let applied: number try { - const [row] = await withTimeout( + const [row] = await untilAborted( db.execute<{ latest: string | number | null }>( sql`select max(created_at) as latest from drizzle.__drizzle_migrations` ), - DATABASE_TIMEOUT_MS + AbortSignal.timeout(DATABASE_TIMEOUT_MS) ) applied = Number(row?.latest ?? 0) } catch (error) { @@ -54,7 +54,7 @@ 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 withTimeout(getRedisClient().ping(), REDIS_TIMEOUT_MS) + await untilAborted(getRedisClient().ping(), AbortSignal.timeout(REDIS_TIMEOUT_MS)) return { status: 'pass', detail: 'ping answered' } }) } diff --git a/apps/sim/lib/self-check/outcome.ts b/apps/sim/lib/self-check/outcome.ts index 45e1ed3f4d0..7c67fc23f05 100644 --- a/apps/sim/lib/self-check/outcome.ts +++ b/apps/sim/lib/self-check/outcome.ts @@ -1,6 +1,9 @@ -import { getPostgresErrorCode } from '@sim/utils/errors' +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}$/ /** @@ -19,6 +22,15 @@ export interface CheckOutcome { 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, @@ -29,20 +41,20 @@ export async function timed( try { outcome = await run() } catch (error) { - outcome = { status: 'fail', detail: `error: ${errorCode(error)}` } + outcome = failedWith(name, error) } return { name, ...outcome, durationMs: Math.round(performance.now() - startedAt) } } -/** Rejects with a `TimeoutError` once `ms` pass; the work itself is left to settle on its own. */ -export function withTimeout(work: Promise, ms: number): Promise { - let timer: ReturnType | undefined - const timeout = new Promise((_, reject) => { - timer = setTimeout(() => { - const error = new Error('Timed out') - error.name = 'TimeoutError' - reject(error) - }, ms) +/** + * 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)) }) - return Promise.race([work, timeout]).finally(() => clearTimeout(timer)) } diff --git a/apps/sim/lib/self-check/run.test.ts b/apps/sim/lib/self-check/run.test.ts deleted file mode 100644 index 0474c9905e1..00000000000 --- a/apps/sim/lib/self-check/run.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { checkSandbox } = vi.hoisted(() => ({ checkSandbox: vi.fn() })) - -vi.mock('@/lib/self-check/sandbox', () => ({ checkSandbox })) -vi.mock('@/lib/self-check/infrastructure', () => ({ - checkDatabase: async () => ({ name: 'database', status: 'pass', durationMs: 0, detail: '' }), - checkMigrations: async () => ({ name: 'migrations', status: 'pass', durationMs: 0, detail: '' }), - checkRedis: async () => ({ name: 'redis', status: 'pass', durationMs: 0, detail: '' }), - checkRealtime: async () => ({ name: 'realtime', status: 'pass', durationMs: 0, detail: '' }), -})) - -import { runSelfCheck } from '@/lib/self-check/run' - -describe('runSelfCheck', () => { - beforeEach(() => { - checkSandbox.mockReset() - }) - - it('reports a sandbox check that threw as a failed check instead of rejecting', async () => { - checkSandbox.mockRejectedValueOnce(new TypeError('boom')) - const report = await runSelfCheck({ sandbox: true, realtime: false }) - expect(report.ok).toBe(false) - expect(report.checks).toContainEqual( - expect.objectContaining({ - name: 'sandbox.execution', - status: 'fail', - detail: 'error: TypeError', - }) - ) - }) -}) diff --git a/apps/sim/lib/self-check/run.ts b/apps/sim/lib/self-check/run.ts index d401448f869..a241873057f 100644 --- a/apps/sim/lib/self-check/run.ts +++ b/apps/sim/lib/self-check/run.ts @@ -5,55 +5,41 @@ import { checkRealtime, checkRedis, } from '@/lib/self-check/infrastructure' -import { errorCode } from '@/lib/self-check/outcome' +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') -/** Starting sandboxes is the expensive part, so repeated calls inside this window reuse it. */ -const SANDBOX_RESULT_TTL_MS = 30_000 - interface SelfCheckOptions { sandbox: boolean realtime: boolean } -const inFlight = new Map>() -/** The sandbox run in progress, or the last one until its result goes stale. */ -let sandboxRun: { checks: Promise; settledAt: number | null } | null = null +/** The sandbox run in progress: concurrent callers share it rather than stack sandbox starts. */ +let sandboxRun: Promise | null = null function sandboxChecks(): Promise { - const current = sandboxRun - if ( - current && - (current.settledAt === null || Date.now() - current.settledAt < SANDBOX_RESULT_TTL_MS) - ) { - return current.checks - } + 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 checks = checkSandbox().catch((error): SelfCheckResult[] => [ - { - name: 'sandbox.execution', - status: 'fail', - durationMs: 0, - detail: `error: ${errorCode(error)}`, - }, - ]) - const entry: { checks: Promise; settledAt: number | null } = { - checks, - settledAt: null, - } - const settle = () => { - entry.settledAt = Date.now() - } - entry.checks.then(settle, settle) - sandboxRun = entry - return entry.checks + const running = checkSandbox() + .catch((error): SelfCheckResult[] => [ + { name: 'sandbox.execution', durationMs: 0, ...failedWith('sandbox.execution', error) }, + ]) + .finally(() => { + sandboxRun = null + }) + sandboxRun = running + return running } -async function run(options: SelfCheckOptions): Promise { +/** + * 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]), @@ -77,18 +63,3 @@ async function run(options: SelfCheckOptions): Promise { }) return report } - -/** - * 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. Concurrent - * callers with the same options share one run, so a retrying client never stacks sandbox starts. - * Every check bounds itself; no caller's request signal governs a run others may be waiting on. - */ -export function runSelfCheck(options: SelfCheckOptions): Promise { - const key = `${options.sandbox}:${options.realtime}` - const existing = inFlight.get(key) - if (existing) return existing - const running = run(options).finally(() => inFlight.delete(key)) - inFlight.set(key, running) - return running -} diff --git a/apps/sim/lib/self-check/sandbox.ts b/apps/sim/lib/self-check/sandbox.ts index 03e96b50977..bfcb7f518d7 100644 --- a/apps/sim/lib/self-check/sandbox.ts +++ b/apps/sim/lib/self-check/sandbox.ts @@ -17,8 +17,8 @@ import { judgeProbeResult, type LateralTargetKind, } from '@/lib/self-check/confinement' -import { type CheckOutcome, errorCode } from '@/lib/self-check/outcome' -import { DATABASE_URL_NAMES, dataStoreEndpoints } from '@/lib/self-check/targets' +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`. */ @@ -48,15 +48,6 @@ function key([host, port]: Target): string { return `${host}:${port}` } -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)) - }) -} - /** This pod's routable addresses: the app's own, which user code must not reach. */ function appAddresses(): string[] { return Object.values(networkInterfaces()) @@ -68,18 +59,20 @@ function appAddresses(): string[] { /** * 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. + * (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> { - const endpoints = dataStoreEndpoints({ - ...Object.fromEntries(DATABASE_URL_NAMES.map((name) => [name, env[name]])), - REDIS_URL: env.REDIS_URL, - }) +async function dataStoreTargets(): Promise<{ + targets: Array<{ target: Target; kind: LateralTargetKind }> + unresolved: ConfinementPlan['unresolved'] +}> { + const unresolved: ConfinementPlan['unresolved'] = [] const resolved = await Promise.all( - endpoints.map(async ({ kind, host, port }) => { + 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) @@ -87,11 +80,12 @@ async function dataStoreTargets(): Promise() - return resolved.flat().filter(({ target }) => { + const targets = resolved.flat().filter(({ target }) => { if (seen.has(key(target))) return false seen.add(key(target)) return true }) + return { targets, unresolved } } /** @@ -141,15 +135,16 @@ function failedToRun(outcome: CheckOutcome, durationMs: number): SelfCheckResult } function failure(error: unknown): CheckOutcome { - if (findSandboxCapacityError(error)) return { status: 'fail', detail: 'capacity' } - return { status: 'fail', detail: `error: ${errorCode(error)}` } + 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 checks it is confined: the sandbox - * user, no metadata credentials, no authorized Kubernetes API, and no reach into the app, its - * private data stores, or a sibling sandbox. Only for the Kubernetes provider: the hosted - * providers bill each sandbox and isolate them outside this deployment's control. + * 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() @@ -190,9 +185,10 @@ async function probe( 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 })), - ...(await dataStoreTargets()), + ...dataStores.targets, ] const neighborTarget: Target = [neighborAddress, SANDBOX_AGENT_PORT] const apiTargets: Target[] = [[CLUSTER_API_NAME, 443]] @@ -220,6 +216,7 @@ async function probe( 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) diff --git a/apps/sim/lib/self-check/targets.test.ts b/apps/sim/lib/self-check/targets.test.ts index 26de826133e..2f8daed1155 100644 --- a/apps/sim/lib/self-check/targets.test.ts +++ b/apps/sim/lib/self-check/targets.test.ts @@ -2,22 +2,35 @@ import { describe, expect, it } from 'vitest' import { dataStoreEndpoints } from '@/lib/self-check/targets' describe('dataStoreEndpoints', () => { - it('lists every database endpoint the app may use: primary, per-role, and replicas', () => { + 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_URL_AUTH: 'postgresql://u:p@pgbouncer.internal:6432/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([ - { kind: 'database', host: 'primary.internal', port: 5432 }, - { kind: 'database', host: 'replica.internal', port: 5432 }, - { kind: 'database', host: 'pgbouncer.internal', port: 6432 }, - { kind: 'database', host: 'fd00::7', port: 5433 }, - { kind: 'redis', host: 'cache.internal', port: 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', () => { diff --git a/apps/sim/lib/self-check/targets.ts b/apps/sim/lib/self-check/targets.ts index b303748ca79..bc287e57c4e 100644 --- a/apps/sim/lib/self-check/targets.ts +++ b/apps/sim/lib/self-check/targets.ts @@ -1,21 +1,19 @@ +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 the app may open a database connection from: the primary, the per-role and - * per-pool overrides `@sim/db` resolves, and the replicas. User code must reach none of them. + * 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. */ -export const DATABASE_URL_NAMES = [ +const DATABASE_URL_NAMES = [ 'DATABASE_URL', 'DATABASE_REPLICA_URL', - 'DATABASE_URL_WEB', - 'DATABASE_URL_TRIGGER', - 'DATABASE_URL_REALTIME', - 'DATABASE_URL_CLEANUP', - 'DATABASE_URL_EXEC', - 'DATABASE_URL_BILLING', - 'DATABASE_URL_AUTH', - 'DATABASE_REPLICA_URL_WEB', - 'DATABASE_REPLICA_URL_TRIGGER', - 'DATABASE_REPLICA_URL_REALTIME', -] as const + ...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 @@ -42,11 +40,12 @@ function endpoint( } /** - * The database and Redis endpoints the app is configured with, each once. Hosts stay unresolved: + * 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: Partial> + values: Readonly> ): DataStoreEndpoint[] { const found = [ ...DATABASE_URL_NAMES.map((name) => endpoint('database', values[name])), diff --git a/helm/sim/README.md b/helm/sim/README.md index 1a7810a4080..13528828ea4 100644 --- a/helm/sim/README.md +++ b/helm/sim/README.md @@ -164,15 +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. The published -chart's `images.yaml` lists the sandbox images for its appVersion (the copy in -this repository leaves them out, since their tags change with every sandbox -image rebuild). Skip the `simstudioai/copilot*` images (enterprise) and the -`simstudioai/sandbox-*` and `pause` images (the 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 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 @@ -243,27 +241,19 @@ helm install sim oci://ghcr.io/simstudioai/charts/sim --version "$CHART_VERSION" helm test sim --namespace sim --logs --timeout 10m ``` -Two test pods run, both from the `curlimages/curl` image the cron jobs already -use. The first checks the app and realtime Services answer. The second calls -the app's `/api/cron/self-check` with `CRON_SECRET` and passes only when every -check does: the database answers, its migrations match the app image, Redis -answers, realtime is healthy (when enabled), and, with -`sandbox.kubernetes.enabled`, a sandbox runs user code confined. The sandbox -check starts two sandbox pods and proves user code runs as the sandbox user, -gets no cloud metadata credentials, gets no authorized Kubernetes API, and cannot -reach the app pod, a private database or Redis address, or the other sandbox's -agent (which the app itself just reached, so the refusal is the policy's). That -last one fails on a cluster whose network plugin does not enforce -NetworkPolicy. `--logs` prints the report: one line per check with `pass`, -`fail`, `warn`, or `skip` and a short reason. The test pods stay until the next -`helm test` replaces them, so `kubectl logs` reads them afterwards too. - -The self-check passes as skipped when `CRON_SECRET` is not in the app Secret, -and when the app image predates the endpoint (`tests.selfCheck.requireEndpoint: -true` fails instead). Disable it with `tests.selfCheck.enabled=false`, or all -test pods with `tests.enabled=false`. With `networkPolicy.enabled`, the app and -realtime policies admit the test pods (label -`simstudio.ai/component-group: helm-test`) while `tests.enabled` is true. +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`. --- diff --git a/helm/sim/images.yaml b/helm/sim/images.yaml index f57de0288c8..e5e4e52cca8 100644 --- a/helm/sim/images.yaml +++ b/helm/sim/images.yaml @@ -1,15 +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. The -# published chart's copy also lists the sandbox images (`simstudioai/sandbox-*`) -# the app starts at run time, at the tags its appVersion pins. Some are not part of an ordinary -# install: the `simstudioai/copilot*` images (the Mothership and its sandboxes) -# require enterprise registry access, and the `simstudioai/sandbox-*` and -# `pause` images serve only the Kubernetes sandbox provider. Skip any you do not -# use. 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 diff --git a/helm/sim/templates/NOTES.txt b/helm/sim/templates/NOTES.txt index ff615667119..f67f6a4890d 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 + # Show the rendered values helm get values {{ .Release.Name }} --namespace {{ .Release.Namespace }} 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 b65076df14e..bcccc6e5863 100644 --- a/helm/sim/templates/tests/test-connection.yaml +++ b/helm/sim/templates/tests/test-connection.yaml @@ -12,30 +12,10 @@ metadata: "helm.sh/hook": test "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 diff --git a/helm/sim/templates/tests/test-self-check.yaml b/helm/sim/templates/tests/test-self-check.yaml index 83a83f893dc..9207f864f17 100644 --- a/helm/sim/templates/tests/test-self-check.yaml +++ b/helm/sim/templates/tests/test-self-check.yaml @@ -1,11 +1,7 @@ {{- /* - Proves the install works, not only that it answers: calls the app's - /api/cron/self-check with the cron secret and passes only on {"ok":true}. - The app checks its database, migrations, Redis, realtime, and, with the - Kubernetes sandbox provider, that a sandbox runs user code confined. Runs - after the connectivity probe (hook weight), which waits out Service routing. - Both test pods stay after a pass, so `helm test --logs` and `kubectl logs` - can read them; the next `helm test` replaces them. + 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 }} @@ -23,31 +19,10 @@ metadata: "helm.sh/hook-weight": "1" "helm.sh/hook-delete-policy": before-hook-creation spec: - restartPolicy: Never - automountServiceAccountToken: false - {{- 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: self-check - 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 }} env: - name: CRON_SECRET valueFrom: @@ -88,13 +63,8 @@ spec: cat /tmp/response echo if [ "$status" = "404" ]; then - {{- if $selfCheck.requireEndpoint }} - echo "FAILED: the app answered 404; its image predates the self-check endpoint" - exit 1 - {{- else }} echo "SKIP: app image predates self-check" exit 0 - {{- end }} fi if [ "$status" = "200" ] && grep -q '"ok":true' /tmp/response; then echo "OK: self-check passed" diff --git a/helm/sim/tests/self-check_test.yaml b/helm/sim/tests/self-check_test.yaml index b6bfec8f2c4..9d61413f7da 100644 --- a/helm/sim/tests/self-check_test.yaml +++ b/helm/sim/tests/self-check_test.yaml @@ -106,6 +106,25 @@ tests: 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: @@ -157,19 +176,6 @@ tests: name: SELF_CHECK_URL value: http://t-sim-app:3000/api/cron/self-check?sandbox=1&realtime=0 - - it: fails rather than skips on a 404 when the endpoint is required - template: tests/test-self-check.yaml - set: - <<: *defaults - tests.selfCheck.requireEndpoint: true - asserts: - - matchRegex: - path: spec.containers[0].command[2] - pattern: 'answered 404[^\n]*\n\s*exit 1' - - notMatchRegex: - path: spec.containers[0].command[2] - pattern: 'SKIP: app image predates self-check' - - it: skips on a 404 by default, so an older app image does not fail helm test template: tests/test-self-check.yaml set: diff --git a/helm/sim/values.schema.json b/helm/sim/values.schema.json index 2a630194a55..37942339c8c 100644 --- a/helm/sim/values.schema.json +++ b/helm/sim/values.schema.json @@ -922,11 +922,7 @@ "timeoutSeconds": { "type": "integer", "minimum": 30, - "description": "Limit on the self-check request; a sandbox check starts two sandbox pods" - }, - "requireEndpoint": { - "type": "boolean", - "description": "Fail instead of skipping when the app image predates the self-check endpoint" + "description": "Self-check request timeout; the sandbox check starts two sandbox pods" } } }, diff --git a/helm/sim/values.yaml b/helm/sim/values.yaml index 9fcea62d2a0..63cd1d2cb3c 100644 --- a/helm/sim/values.yaml +++ b/helm/sim/values.yaml @@ -2314,10 +2314,7 @@ certManager: # This is the issuer that applications should reference for obtaining certificates caIssuer: name: "sim-ca-issuer" -# Helm test hooks (helm test). Run with: helm test --logs -# A connectivity probe checks the app and realtime Services answer from inside -# the cluster; the self-check proves the install works. Both use the curl image -# the cron jobs already pull, so a mirrored registry needs nothing extra. +# helm test hooks: a connectivity probe and the authenticated self-check. Run: helm test --logs tests: enabled: true image: @@ -2326,18 +2323,11 @@ tests: pullPolicy: IfNotPresent pullSecrets: [] timeoutSeconds: 5 - # Calls the app's /api/cron/self-check with CRON_SECRET: database reachable, - # migrations applied, Redis answering, realtime healthy (when enabled), and, - # with sandbox.kubernetes.enabled, a sandbox that runs user code confined (no - # metadata credentials, no authorized Kubernetes API, no reach into the app, - # its private data stores, or another sandbox). Skips, passing, when - # CRON_SECRET is not in the app Secret, or when the app image predates the - # endpoint unless requireEndpoint is true. + # 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 - requireEndpoint: false resources: limits: cpu: 100m diff --git a/scripts/generate-image-manifest.ts b/scripts/generate-image-manifest.ts index db1c1d0702a..f89a0d17fcb 100644 --- a/scripts/generate-image-manifest.ts +++ b/scripts/generate-image-manifest.ts @@ -241,16 +241,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. The -# published chart's copy also lists the sandbox images (\`simstudioai/sandbox-*\`) -# the app starts at run time, at the tags its appVersion pins. Some are not part of an ordinary -# install: the \`simstudioai/copilot*\` images (the Mothership and its sandboxes) -# require enterprise registry access, and the \`simstudioai/sandbox-*\` and -# \`pause\` images serve only the Kubernetes sandbox provider. Skip any you do not -# use. 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 diff --git a/scripts/sync-chart-appversion.ts b/scripts/sync-chart-appversion.ts index caa35d68526..c92f716f3d9 100644 --- a/scripts/sync-chart-appversion.ts +++ b/scripts/sync-chart-appversion.ts @@ -97,8 +97,9 @@ async function main() { /** * The inventory embeds appVersion in every first-party image tag, so it has to - * 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. + * 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', From 224ab35d52d83a09a2afe68238935a6ea2c04e7b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 16:42:10 -0800 Subject: [PATCH 4/6] improvement(self-hosting): share the release image list and fold upgrade notes --- .github/workflows/helm.yml | 4 +- helm/sim/README.md | 11 +- scripts/generate-image-manifest.test.ts | 19 ---- scripts/generate-image-manifest.ts | 63 ++--------- ...ges.test.ts => release-image-list.test.ts} | 24 +++- scripts/release-image-list.ts | 105 ++++++++++++++++++ scripts/write-chart-sandbox-images.ts | 73 ++---------- 7 files changed, 150 insertions(+), 149 deletions(-) rename scripts/{write-chart-sandbox-images.test.ts => release-image-list.test.ts} (54%) create mode 100644 scripts/release-image-list.ts diff --git a/.github/workflows/helm.yml b/.github/workflows/helm.yml index 22966f7bab4..e8576116dfd 100644 --- a/.github/workflows/helm.yml +++ b/.github/workflows/helm.yml @@ -12,6 +12,7 @@ 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' @@ -26,6 +27,7 @@ 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' @@ -248,9 +250,9 @@ 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 - kubectl -n sim logs sim-test-self-check || true # Resolved once and shared, so the two publish paths cannot package the same # immutable chart version with different appVersions -- they run in parallel, diff --git a/helm/sim/README.md b/helm/sim/README.md index 13528828ea4..2c78cafc5ed 100644 --- a/helm/sim/README.md +++ b/helm/sim/README.md @@ -667,14 +667,7 @@ kubectl --namespace sim logs deploy/sim-app -c migrations ## Upgrading to 1.22.0 -* **`helm test` now proves the install works.** A second test pod calls the app's authenticated `/api/cron/self-check` (see [Test the install](#test-the-install)). Run `helm test` with `--timeout 10m` when the Kubernetes sandbox provider is on: the sandbox check starts two sandbox pods. -* **`tests.image` defaults to `curlimages/curl:8.5.0`**, the image the cron jobs use, instead of `busybox:1.36`. If you pinned `tests.image` to busybox, either drop the override or set it to an image that has `curl`. -* **With `networkPolicy.enabled` and the ingress disabled, `helm test` no longer times out.** The app and realtime policies admit the test pods while `tests.enabled` is true; before, nothing did. -* **`images.yaml` covers the Kubernetes sandbox provider.** It now lists the warm-capacity `pause` image and the Mothership's `copilot-sandbox-shell` and `copilot-sandbox-doc` (with the `main-REPLACE` placeholder), and the published chart's copy also lists the `simstudioai/sandbox-*` images at the tags its appVersion pins. - -## Upgrading to 1.21.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: @@ -688,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/scripts/generate-image-manifest.test.ts b/scripts/generate-image-manifest.test.ts index 263ab679dd0..c62af9d9569 100644 --- a/scripts/generate-image-manifest.test.ts +++ b/scripts/generate-image-manifest.test.ts @@ -3,7 +3,6 @@ import { collectImages, mergeImageEntries, pairSources, - parseSandboxImageReferences, sandboxImageEntries, } from './generate-image-manifest' @@ -152,21 +151,3 @@ describe('mergeImageEntries', () => { expect(() => mergeImageEntries([entry], [entry])).toThrow(/listed twice/) }) }) - -describe('parseSandboxImageReferences', () => { - it('reads every reference the app pins', () => { - expect( - parseSandboxImageReferences( - '{"function": "ghcr.io/simstudioai/sandbox-function:a", "agent": "ghcr.io/simstudioai/sandbox-agent:b"}' - ) - ).toEqual(['ghcr.io/simstudioai/sandbox-function:a', '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 an inventory without the sandbox images', (_, json) => { - expect(() => parseSandboxImageReferences(json)).toThrow(/images.generated.json/) - }) -}) diff --git a/scripts/generate-image-manifest.ts b/scripts/generate-image-manifest.ts index f89a0d17fcb..da508f343e4 100644 --- a/scripts/generate-image-manifest.ts +++ b/scripts/generate-image-manifest.ts @@ -26,10 +26,10 @@ * 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 { spawnSync } from 'node:child_process' 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, '..') @@ -74,15 +74,6 @@ const RENDER_ARGS = [ 'sandbox.kubernetes.images.doc.tag=main-REPLACE', ] as const -/** - * The sandbox images the app starts at run time, which no rendered pod names. - * The app's defaults are the references this file pins, read at the release tag. - */ -const SANDBOX_IMAGES_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+$/ - /** * Sentinel registry used for the second render. * @@ -293,57 +284,17 @@ function renderChart(args: readonly string[] = RENDER_ARGS): unknown[] { return Array.isArray(documents) ? documents : [documents] } -function git(args: readonly string[]): { ok: boolean; stdout: string } { - const result = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8' }) - return { ok: result.status === 0, stdout: result.stdout ?? '' } -} - /** - * The sandbox image references the app at `release` defaults to. Publish jobs - * check out shallow, so the tag is fetched when absent. On the release merge - * itself the tag does not exist yet (that commit cuts it), so HEAD is read when - * its subject names the release, the same rule helm.yml resolves the version by. + * 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[] { - if (!RELEASE_TAG.test(release)) { - throw new Error(`--release must be a release tag like v1.2.3, got "${release}"`) - } - const tagRef = `refs/tags/${release}` - if (!git(['rev-parse', '--verify', '--quiet', tagRef]).ok) { - git(['fetch', '--quiet', '--no-tags', '--depth', '1', 'origin', `+${tagRef}:${tagRef}`]) - } - let ref = tagRef - if (!git(['rev-parse', '--verify', '--quiet', tagRef]).ok) { - const subject = git(['log', '-1', '--format=%s', 'HEAD']).stdout.trim() - if (!subject.startsWith(`${release}:`)) { - throw new Error(`Release ${release} has no tag and HEAD is not its release commit`) - } - ref = 'HEAD' - } - // A release from before the Kubernetes sandbox provider starts no sandbox images. - if (!git(['cat-file', '-e', `${ref}:${SANDBOX_IMAGES_PATH}`]).ok) { - console.log(`${release} has no ${SANDBOX_IMAGES_PATH}; listing no sandbox images.`) + const list = readReleaseImageList(release) + if (!list) { + console.log(`${release} has no ${IMAGE_LIST_PATH}; listing no sandbox images.`) return [] } - const shown = git(['show', `${ref}:${SANDBOX_IMAGES_PATH}`]) - if (!shown.ok) throw new Error(`Could not read ${SANDBOX_IMAGES_PATH} at ${ref}`) - return parseSandboxImageReferences(shown.stdout) -} - -/** The references in `images.generated.json`, refusing anything that is not a string map. */ -export function parseSandboxImageReferences(json: string): string[] { - const parsed: unknown = JSON.parse(json) - if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { - throw new Error(`${SANDBOX_IMAGES_PATH} is not an object of image references`) - } - const references = Object.values(parsed) - if ( - references.length > 0 && - references.every((value): value is string => typeof value === 'string') - ) { - return references - } - throw new Error(`${SANDBOX_IMAGES_PATH} holds a non-string or no image reference`) + return Object.values(list) } async function main(): Promise { 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/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.`) From 8280b4d6193dca13aa22815456404b828618a5b3 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 17:04:13 -0800 Subject: [PATCH 5/6] fix(self-hosting): probe metadata directly, cover IPv6 IMDS, and classify IPv6 loopback numerically --- .../kubernetes/confinement-probe.ts | 37 ++++++++++++++----- apps/sim/lib/self-check/confinement.test.ts | 26 +++++++++---- apps/sim/lib/self-check/confinement.ts | 30 +++++++++------ apps/sim/lib/self-check/outcome.ts | 2 +- helm/sim/templates/NOTES.txt | 2 +- helm/sim/tests/notes_test.yaml | 16 ++++++++ 6 files changed, 83 insertions(+), 30 deletions(-) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts index edc62d4dbd8..54a0ad3f603 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts @@ -3,10 +3,13 @@ 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` is the IMDSv2 token header the probe fetches first. + * expression: `aws` and `aws6` are the IMDSv2 token headers the probe fetches first, one per + * IMDS address. */ const METADATA_REQUESTS = [ { @@ -20,6 +23,11 @@ const METADATA_REQUESTS = [ 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' }, { @@ -106,14 +114,21 @@ def resolves(name): 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' - context = ssl.create_default_context() - context.check_hostname = False - context.verify_mode = ssl.CERT_NONE try: - urllib.request.urlopen(url, context=context, timeout=5) + direct.open(url, timeout=5) return 200 except urllib.error.HTTPError as error: return error.code @@ -125,7 +140,7 @@ def agent(token): if token: request.add_header('Authorization', 'Bearer ' + token) try: - urllib.request.urlopen(request, timeout=5) + direct.open(request, timeout=5) return 200 except urllib.error.HTTPError as error: return error.code @@ -135,16 +150,16 @@ def agent(token): 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) + response = direct.open(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(): +def imds_headers(address): status, token = http_status( - 'http://${METADATA_ADDRESS}/latest/api/token', + 'http://%s/latest/api/token' % address, {'X-aws-ec2-metadata-token-ttl-seconds': '60'}, 'PUT', ) @@ -174,7 +189,9 @@ allowed_targets = ${JSON.stringify(targets.allowedTargets)} resolve_names = ${JSON.stringify(targets.resolveNames ?? [])} with ThreadPoolExecutor(max_workers=32) as pool: - aws = imds_headers() + 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. diff --git a/apps/sim/lib/self-check/confinement.test.ts b/apps/sim/lib/self-check/confinement.test.ts index 21fdaf5e853..07d36211c1a 100644 --- a/apps/sim/lib/self-check/confinement.test.ts +++ b/apps/sim/lib/self-check/confinement.test.ts @@ -220,14 +220,26 @@ describe('judgeProbeResult fails closed', () => { }) describe('isProbeTargetAddress', () => { - it.each(['127.0.0.1', '::1', '169.254.169.254', 'fe80::1', '::ffff:127.0.0.1', '0.0.0.0'])( - 'drops %s, which reaches the app pod itself or its sidecar rather than a peer', + 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(false) + expect(isProbeTargetAddress(address)).toBe(true) } ) - - it.each(['10.43.0.12', 'fd00::12', '34.1.2.3'])('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 index 76885b6b9ba..c7f1117881f 100644 --- a/apps/sim/lib/self-check/confinement.ts +++ b/apps/sim/lib/self-check/confinement.ts @@ -1,4 +1,4 @@ -import { isIP } from 'node:net' +import { BlockList, isIP } from 'node:net' import { type ConfinementFacts, isConfinementFacts, @@ -7,6 +7,21 @@ import { 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 @@ -179,14 +194,7 @@ export function judgeProbeResult( * endpoint), not the app or its data stores, so they prove nothing either way. */ export function isProbeTargetAddress(address: string): boolean { - const normalized = address.toLowerCase().replace(/^::ffff:/, '') - if (isIP(normalized) === 0) return false - return !( - normalized === '::1' || - normalized === '::' || - normalized.startsWith('127.') || - normalized.startsWith('0.') || - normalized.startsWith('169.254.') || - /^fe[89ab][0-9a-f]:/.test(normalized) - ) + 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/outcome.ts b/apps/sim/lib/self-check/outcome.ts index 7c67fc23f05..d02d38e0063 100644 --- a/apps/sim/lib/self-check/outcome.ts +++ b/apps/sim/lib/self-check/outcome.ts @@ -10,7 +10,7 @@ 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. */ -export function errorCode(error: unknown): string { +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 diff --git a/helm/sim/templates/NOTES.txt b/helm/sim/templates/NOTES.txt index f67f6a4890d..e6fa671fbd2 100644 --- a/helm/sim/templates/NOTES.txt +++ b/helm/sim/templates/NOTES.txt @@ -91,7 +91,7 @@ STORAGE_PROVIDER in values.yaml). 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 + 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/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" From 0fe9620c8b0bc43c847373acf2c5af937951cc0e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Fri, 4 Dec 2026 17:21:09 -0800 Subject: [PATCH 6/6] fix(self-hosting): keep a metadata 200 when its body fails to read --- .../remote-sandbox/kubernetes/confinement-probe.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts index 54a0ad3f603..cc25aeea268 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts @@ -151,11 +151,15 @@ 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) - return response.status, response.read(4096).decode('utf-8', 'replace') 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(