From c89a40efc49339d545abc17f5d631b168c71e050 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 13:26:37 -0600 Subject: [PATCH 01/78] improvement(sandbox): derive provider availability and seams from declared provider traits - Sandbox kind availability (function, mothership, doc, pi) comes from the selected provider's declarations in deployment-config instead of e2b/daytona branches in env-flags. Pi cloud gates on the selected provider running Pi; E2B keeps its exact prior gate (E2B_ENABLED), Daytona now needs DAYTONA_PI_SNAPSHOT_ID. The projected deployment-shape key stays e2bEnabled. - Session-command recovery goes through an optional SandboxProvider.stopSessionProcess that E2B implements with its existing stop. - SandboxProviderId derives from SANDBOX_PROVIDER_IDS; CLI recipes, metrics, Pi lifetime ceilings, and pricing key off it, and pricing accepts an operator-paid provider priced at zero. - sim-setup derives the disabled condition, option order, and provider validation from SANDBOX_CAPABILITY. --- .../api/mothership/chat/abort/route.test.ts | 10 ++- apps/sim/blocks/blocks/pi.ts | 2 +- apps/sim/lib/api/contracts/workspaces.ts | 3 +- apps/sim/lib/billing/sandbox-pricing.ts | 16 ++++- .../config/deployment-projection.dom.test.ts | 4 +- apps/sim/lib/core/config/deployment-shape.ts | 4 +- apps/sim/lib/core/config/env-flags.ts | 71 ++++--------------- apps/sim/lib/core/execution-limits/metrics.ts | 9 +-- .../remote-sandbox/cli-tools.server.ts | 10 +-- apps/sim/lib/execution/remote-sandbox/e2b.ts | 1 + .../execution/remote-sandbox/pi-lifetime.ts | 19 +++-- .../sim/lib/execution/remote-sandbox/types.ts | 11 ++- .../request/tools/sandbox-recovery.ts | 8 ++- .../deployment-config/src/env-capabilities.ts | 55 ++++++++++++++ packages/sim-setup/src/capability-config.ts | 30 ++++---- packages/sim-setup/src/capability-status.ts | 29 +++++--- packages/testing/src/mocks/env-flags.mock.ts | 4 +- .../src/mocks/remote-sandbox-provider.mock.ts | 3 +- 18 files changed, 179 insertions(+), 110 deletions(-) diff --git a/apps/sim/app/api/mothership/chat/abort/route.test.ts b/apps/sim/app/api/mothership/chat/abort/route.test.ts index 9a14a247f78..05a48e0f743 100644 --- a/apps/sim/app/api/mothership/chat/abort/route.test.ts +++ b/apps/sim/app/api/mothership/chat/abort/route.test.ts @@ -9,6 +9,10 @@ import { organizationAuthorizationMock, organizationAuthorizationMockFns, } from '@sim/testing/mocks/organization-authorization.mock' +import { + remoteSandboxProviderMock, + remoteSandboxProviderMockFns, +} from '@sim/testing/mocks/remote-sandbox-provider.mock' import { workspaceAuthorizationMock, workspaceAuthorizationMockFns, @@ -52,7 +56,7 @@ const { vi.mock('@/lib/mothership/async-runs/repository', () => mothershipAsyncRunsMock) vi.mock('@/lib/execution/cancellation', () => ({ markExecutionCancelled: mockCancelWorkflow })) vi.mock('@/lib/execution/manual-cancellation', () => ({ abortManualExecution: mockAbortWorkflow })) -vi.mock('@/lib/execution/remote-sandbox/e2b', () => ({ stopE2BSessionProcess: mockStopProcess })) +vi.mock('@/lib/execution/remote-sandbox/provider', () => remoteSandboxProviderMock) vi.mock('@/lib/mothership/request/session', () => ({ abortActiveStream: mockAbortActiveStream, waitForPendingChatStream: mockWaitForPendingChatStream, @@ -122,6 +126,10 @@ describe('POST /api/mothership/chat/abort', () => { mockCancelWorkflow.mockResolvedValue({ durablyRecorded: true, reason: 'recorded' }) mockAbortWorkflow.mockReturnValue(false) mockStopProcess.mockResolvedValue(undefined) + remoteSandboxProviderMockFns.mockResolveProvider.mockReturnValue({ + id: 'e2b', + stopSessionProcess: mockStopProcess, + }) mockSettleProcess.mockResolvedValue(undefined) }) diff --git a/apps/sim/blocks/blocks/pi.ts b/apps/sim/blocks/blocks/pi.ts index 074d0a69ce3..2cde19af780 100644 --- a/apps/sim/blocks/blocks/pi.ts +++ b/apps/sim/blocks/blocks/pi.ts @@ -163,7 +163,7 @@ export const PiBlock: BlockConfig = { id: 'mode', title: 'Mode', type: 'dropdown', - /** Cloud modes require E2B and stay hidden when it is disabled. */ + /** Cloud modes need a sandbox provider that runs Pi and stay hidden without one. */ value: () => (getDeploymentShape().e2bEnabled ? 'cloud' : 'local'), options: () => { const options = [ diff --git a/apps/sim/lib/api/contracts/workspaces.ts b/apps/sim/lib/api/contracts/workspaces.ts index be22578691b..408010774d1 100644 --- a/apps/sim/lib/api/contracts/workspaces.ts +++ b/apps/sim/lib/api/contracts/workspaces.ts @@ -276,7 +276,8 @@ export const deploymentShapeSchema = z.object({ /** * Server-only switches, resolved on the server and projected for the browser. Optional * for rolling compatibility with app versions that predate projecting them; readers - * treat absent as `false`. + * treat absent as `false`. `e2bEnabled` means the selected sandbox provider runs Pi's + * cloud modes; it keeps the name it had before providers were selectable. */ e2bEnabled: z.boolean().optional(), slackExtendedScopes: z.boolean().optional(), diff --git a/apps/sim/lib/billing/sandbox-pricing.ts b/apps/sim/lib/billing/sandbox-pricing.ts index 2cb546ce65b..bebea399724 100644 --- a/apps/sim/lib/billing/sandbox-pricing.ts +++ b/apps/sim/lib/billing/sandbox-pricing.ts @@ -47,7 +47,18 @@ interface ProviderPricing extends Pick { resourcesByKind?: Partial> } -const PRICING_BY_PROVIDER: Record = { +/** + * A provider the operator runs on their own infrastructure: Sim still meters its + * duration, but the operator already pays for the machines, so every rate is zero. + */ +type OperatorPaid = 'operator-paid' + +const ZERO_COST_PRICING: ProviderPricing = { + resources: { vcpu: 0, memoryGiB: 0, diskGiB: 0 }, + rates: { cpuUsdPerVcpuSecond: 0, memoryUsdPerGiBSecond: 0, diskUsdPerGiBSecond: 0 }, +} + +const PRICING_BY_PROVIDER: Record = { e2b: { resources: { vcpu: FUNCTION_SANDBOX_CPU_COUNT, @@ -95,7 +106,8 @@ export function createSandboxPricing( if (!Number.isFinite(multiplier) || multiplier < 0) { throw new Error('Sandbox pricing multiplier must be a finite nonnegative number') } - const pricing = PRICING_BY_PROVIDER[provider] + const declared = PRICING_BY_PROVIDER[provider] + const pricing = declared === 'operator-paid' ? ZERO_COST_PRICING : declared const resources = pricing.resourcesByKind?.[kind] ?? pricing.resources return { provider, diff --git a/apps/sim/lib/core/config/deployment-projection.dom.test.ts b/apps/sim/lib/core/config/deployment-projection.dom.test.ts index ea6a61fe2f8..31da642e4f0 100644 --- a/apps/sim/lib/core/config/deployment-projection.dom.test.ts +++ b/apps/sim/lib/core/config/deployment-projection.dom.test.ts @@ -48,12 +48,12 @@ import { getRegistrationMode, isAccessControlEnabled, isAuditLogsEnabled, - isE2bEnabled, isEmailPasswordAuthEnabled, isEmailSignupAllowed, isInboxEnabled, isInvitationsDisabled, isOrganizationsEnabled, + isPiCloudEnabled, isPublicApiDisabled, isSandboxesEnabled, isSelfServeRegistrationClosed, @@ -88,7 +88,7 @@ describe('browser registration flags', () => { describe('browser deployment switches', () => { it('take the projected server answer over the browser environment', () => { - expect(isE2bEnabled).toBe(true) + expect(isPiCloudEnabled).toBe(true) expect(isSlackExtendedScopesEnabled).toBe(true) expect(isInvitationsDisabled).toBe(true) }) diff --git a/apps/sim/lib/core/config/deployment-shape.ts b/apps/sim/lib/core/config/deployment-shape.ts index 5fb25fc01b2..98967f7648e 100644 --- a/apps/sim/lib/core/config/deployment-shape.ts +++ b/apps/sim/lib/core/config/deployment-shape.ts @@ -19,12 +19,12 @@ import { isCustomBlocksEnabled, isDataDrainsEnabled, isDataRetentionEnabled, - isE2bEnabled, isForkingEnabled, isHosted, isInboxEnabled, isInvitationsDisabled, isOrganizationsEnabled, + isPiCloudEnabled, isPublicApiDisabled, isSandboxesEnabled, isScimEnabled, @@ -112,7 +112,7 @@ export function resolveDeploymentShape(): DeploymentShape { azureConfigured: isAzureConfigured, cohereConfigured: isCohereConfigured, registrationMode: getRegistrationMode(), - e2bEnabled: isE2bEnabled, + e2bEnabled: isPiCloudEnabled, slackExtendedScopes: isSlackExtendedScopesEnabled, invitationsDisabled: isInvitationsDisabled, publicApiDisabled: isPublicApiDisabled, diff --git a/apps/sim/lib/core/config/env-flags.ts b/apps/sim/lib/core/config/env-flags.ts index ccf6b455652..44a9867f2ce 100644 --- a/apps/sim/lib/core/config/env-flags.ts +++ b/apps/sim/lib/core/config/env-flags.ts @@ -8,21 +8,12 @@ import { type EnterpriseFeatureState, resolveEnterpriseFeatures, } from '@sim/deployment-config/enterprise-features' -import { - hasEnvCapabilityValue, - inspectCapability, - SANDBOX_CAPABILITY, -} from '@sim/deployment-config/env-capabilities' +import { isSandboxKindAvailable } from '@sim/deployment-config/env-capabilities' import { getRegistrationPolicy, type RegistrationMode, resolveRegistrationMode, } from '@sim/deployment-config/registration' -import { - isImmutableDaytonaSnapshotRef, - isImmutableE2BTemplateRef, - isValidSandboxReleaseGeneration, -} from '@sim/utils/sandbox-references' import { resolveCostMultiplier } from './cost-multiplier' import { readProjectedBoolean, @@ -457,40 +448,19 @@ export const isCredentialGroupsEnabled = enterpriseFeatures.credentialGroups export const isForkingEnabled = enterpriseFeatures.forking /** - * The selected remote sandbox provider (`SANDBOX_PROVIDER`), defaulting to E2B. - * Availability below is derived from THIS provider's credentials, so a - * Daytona-only deployment (E2B unset) still enables remote execution. - */ -const sandboxProvider = inspectCapability(SANDBOX_CAPABILITY, env).providerId - -/** - * Whether remote code/shell execution is available with the selected provider. + * Whether remote code/shell execution is available with the selected provider + * (`SANDBOX_PROVIDER`, defaulting to E2B). Availability comes from THAT + * provider's declared requirements, so a Daytona-only deployment (E2B unset) + * still enables remote execution. * Server-only: the browser cannot inspect provider credentials, and reads the * combined Sandbox availability from the deployment-shape projection instead. * - * Both providers require their credential and dedicated Function base. The old + * Every provider requires its credential and dedicated Function base. The old * Mothership shell template/snapshot names are intentionally not fallbacks: a * deployment must build and configure the Function-owned image before exposing * the runtime. */ -export const isRemoteSandboxEnabled = - sandboxProvider === 'daytona' - ? hasEnvCapabilityValue(env, 'DAYTONA_API_KEY') && - Boolean( - env.DAYTONA_FUNCTION_SNAPSHOT_ID && - isImmutableDaytonaSnapshotRef(env.DAYTONA_FUNCTION_SNAPSHOT_ID) - ) - : sandboxProvider === 'e2b' - ? isTruthy(env.E2B_ENABLED) && - hasEnvCapabilityValue(env, 'E2B_API_KEY') && - Boolean( - env.E2B_FUNCTION_TEMPLATE_ID && isImmutableE2BTemplateRef(env.E2B_FUNCTION_TEMPLATE_ID) - ) && - Boolean( - env.E2B_FUNCTION_TEMPLATE_GENERATION && - isValidSandboxReleaseGeneration(env.E2B_FUNCTION_TEMPLATE_GENERATION) - ) - : false +export const isRemoteSandboxEnabled = isSandboxKindAvailable(env, 'function') /** * Whether the complete custom-Sandbox feature is available on this deployment. @@ -511,15 +481,7 @@ export const isSandboxesEnabled = * This is intentionally independent of {@link isRemoteSandboxEnabled}: the * Function and Mothership images have separate release and rollout lifecycles. */ -export const isMothershipSandboxEnabled = - sandboxProvider === 'daytona' - ? hasEnvCapabilityValue(env, 'DAYTONA_API_KEY') && - hasEnvCapabilityValue(env, 'DAYTONA_SHELL_SNAPSHOT_ID') - : sandboxProvider === 'e2b' - ? isTruthy(env.E2B_ENABLED) && - hasEnvCapabilityValue(env, 'E2B_API_KEY') && - hasEnvCapabilityValue(env, 'MOTHERSHIP_E2B_TEMPLATE_ID') - : false +export const isMothershipSandboxEnabled = isSandboxKindAvailable(env, 'mothership') /** * Whether the document-generation sandbox is available with the selected @@ -533,15 +495,7 @@ export const isMothershipSandboxEnabled = * unavailable). Drives both the Sim compile backend and the `docCompiler` flag * sent to the copilot file subagent so the agent's output and compiler agree. */ -export const isDocSandboxEnabled = - sandboxProvider === 'daytona' - ? hasEnvCapabilityValue(env, 'DAYTONA_API_KEY') && - hasEnvCapabilityValue(env, 'DAYTONA_DOC_SNAPSHOT_ID') - : sandboxProvider === 'e2b' - ? isTruthy(env.E2B_ENABLED) && - hasEnvCapabilityValue(env, 'E2B_API_KEY') && - hasEnvCapabilityValue(env, 'MOTHERSHIP_E2B_DOC_TEMPLATE_ID') - : false +export const isDocSandboxEnabled = isSandboxKindAvailable(env, 'doc') /** * Whether Ollama is configured (OLLAMA_URL is set). @@ -582,10 +536,11 @@ export const isInvitationsDisabled = resolveServerSwitch( export const isPublicApiDisabled = resolveServerSwitch(env.DISABLE_PUBLIC_API, 'publicApiDisabled') /** - * Is the E2B code-execution provider switched on (`E2B_ENABLED`). Pi's cloud modes - * run in an E2B sandbox and stay hidden without it. + * Can the selected sandbox provider run Pi's cloud modes (Create PR, Update PR, + * Review Code); they stay hidden without it. Projected to the browser under its + * original `e2bEnabled` key, which predates provider selection. */ -export const isE2bEnabled = resolveServerSwitch(env.E2B_ENABLED, 'e2bEnabled') +export const isPiCloudEnabled = resolveServerSwitch(isSandboxKindAvailable(env, 'pi'), 'e2bEnabled') /** * Is Google OAuth login disabled diff --git a/apps/sim/lib/core/execution-limits/metrics.ts b/apps/sim/lib/core/execution-limits/metrics.ts index e97ba7bc45d..220fc102845 100644 --- a/apps/sim/lib/core/execution-limits/metrics.ts +++ b/apps/sim/lib/core/execution-limits/metrics.ts @@ -1,4 +1,5 @@ import { type Counter, type Histogram, metrics } from '@opentelemetry/api' +import type { SandboxProviderId } from '@/lib/execution/remote-sandbox/types' export type ExecutionTimeoutSource = | 'plan_default' @@ -56,7 +57,7 @@ export function recordExecutionCancellationBackendResult(params: { /** Emits when a sandbox operation reaches a provider's bounded continuous-run limit. */ export function recordSandboxProviderLimit(params: { - provider: 'e2b' | 'daytona' + provider: SandboxProviderId operation: 'code' | 'command' }): void { instruments().sandboxProviderLimits.add(1, { @@ -67,7 +68,7 @@ export function recordSandboxProviderLimit(params: { /** Emits when best-effort sandbox teardown fails after a run or abort. */ export function recordSandboxTeardownFailure(params: { - provider: 'e2b' | 'daytona' + provider: SandboxProviderId reason: 'cleanup' | 'cancellation' | 'timeout' }): void { instruments().sandboxTeardownFailures.add(1, { @@ -78,7 +79,7 @@ export function recordSandboxTeardownFailure(params: { /** Emits when best-effort cleanup cannot remove a retired provider image family. */ export function recordSandboxImageCleanupFailure(params: { - provider: 'e2b' | 'daytona' + provider: SandboxProviderId reason: 'failed_candidate' | 'lost_claim' | 'superseded' }): void { instruments().sandboxImageCleanupFailures.add(1, { @@ -88,7 +89,7 @@ export function recordSandboxImageCleanupFailure(params: { } /** Emits when a prebuilt image containing curated CLI tools fails to build. */ -export function recordSandboxCliBuildFailure(params: { provider: 'e2b' | 'daytona' }): void { +export function recordSandboxCliBuildFailure(params: { provider: SandboxProviderId }): void { instruments().sandboxCliBuildFailures.add(1, { 'sandbox.provider': params.provider, }) diff --git a/apps/sim/lib/execution/remote-sandbox/cli-tools.server.ts b/apps/sim/lib/execution/remote-sandbox/cli-tools.server.ts index 4bde374d3d5..5076804a053 100644 --- a/apps/sim/lib/execution/remote-sandbox/cli-tools.server.ts +++ b/apps/sim/lib/execution/remote-sandbox/cli-tools.server.ts @@ -1,11 +1,12 @@ +import { SANDBOX_PROVIDER_IDS } from '@sim/utils/sandbox-references' import { canonicalizeSandboxCliTools, SANDBOX_CLI_TOOLS, type SandboxCliToolId, } from '@/lib/execution/remote-sandbox/cli-tools' +import type { SandboxProviderId } from '@/lib/execution/remote-sandbox/types' -type SandboxProvider = 'e2b' | 'daytona' -type SandboxProviderCompatibility = readonly [SandboxProvider, ...SandboxProvider[]] +type SandboxProviderCompatibility = readonly [SandboxProviderId, ...SandboxProviderId[]] interface SandboxCliToolRecipe { id: Id @@ -53,7 +54,8 @@ export const SANDBOX_SYSTEM_PATH = '/usr/local/sbin:/usr/local/bin:/usr/local/games:/usr/sbin:/usr/bin:/usr/games:/sbin:/bin:/root/.local/bin' const SIM_CLI_ROOT = '/opt/sim-cli' -const DEFAULT_SUPPORTED_PROVIDERS = ['e2b', 'daytona'] as const +/** Recipes run on every provider unless they narrow `supportedProviders`. */ +const DEFAULT_SUPPORTED_PROVIDERS = SANDBOX_PROVIDER_IDS function defineVerifiedRecipe( id: Id, @@ -423,7 +425,7 @@ export function sandboxCliToolRecipes( export function assertSandboxCliToolsSupported( cliTools: readonly string[] | null | undefined, - provider: SandboxProvider + provider: SandboxProviderId ): void { for (const recipe of sandboxCliToolRecipes(cliTools)) { if (!recipe.supportedProviders.includes(provider)) { diff --git a/apps/sim/lib/execution/remote-sandbox/e2b.ts b/apps/sim/lib/execution/remote-sandbox/e2b.ts index cc1be4ee75b..6dbbc27ace7 100644 --- a/apps/sim/lib/execution/remote-sandbox/e2b.ts +++ b/apps/sim/lib/execution/remote-sandbox/e2b.ts @@ -1286,4 +1286,5 @@ export const e2bProvider: SandboxProvider = { } return Sandbox.kill(sandbox.sandboxId, requestOptions) }, + stopSessionProcess: stopE2BSessionProcess, } diff --git a/apps/sim/lib/execution/remote-sandbox/pi-lifetime.ts b/apps/sim/lib/execution/remote-sandbox/pi-lifetime.ts index d1f30ebdd8e..d56d627d696 100644 --- a/apps/sim/lib/execution/remote-sandbox/pi-lifetime.ts +++ b/apps/sim/lib/execution/remote-sandbox/pi-lifetime.ts @@ -8,11 +8,18 @@ import { inspectCapability, SANDBOX_CAPABILITY } from '@sim/deployment-config/en import { createLogger } from '@sim/logger' import { env } from '@/lib/core/config/env' import { getMaxExecutionTimeout, getRemainingExecutionMs } from '@/lib/core/execution-limits' +import type { SandboxProviderId } from '@/lib/execution/remote-sandbox/types' const logger = createLogger('PiSandboxLifetime') -/** E2B's documented continuous-runtime ceiling for a single sandbox. */ -const E2B_PI_SANDBOX_PROVIDER_LIMIT_MS = 24 * 60 * 60 * 1000 +/** + * Each provider's documented continuous-runtime ceiling for a single sandbox, or + * `null` when it imposes none below the platform ceiling. + */ +const PROVIDER_SANDBOX_LIFETIME_LIMIT_MS: Record = { + e2b: 24 * 60 * 60 * 1000, + daytona: null, +} /** * The platform-wide ceiling for one workflow execution. Provider-specific @@ -21,10 +28,12 @@ const E2B_PI_SANDBOX_PROVIDER_LIMIT_MS = 24 * 60 * 60 * 1000 export const PI_SANDBOX_MAX_LIFETIME_MS = getMaxExecutionTimeout() function providerLifetimeCeilingMs(): number { - const providerId = inspectCapability(SANDBOX_CAPABILITY, env).providerId - return providerId === 'daytona' + const providerId = + inspectCapability(SANDBOX_CAPABILITY, env).providerId ?? SANDBOX_CAPABILITY.defaultProvider.id + const providerLimitMs = PROVIDER_SANDBOX_LIFETIME_LIMIT_MS[providerId] + return providerLimitMs === null ? PI_SANDBOX_MAX_LIFETIME_MS - : Math.min(PI_SANDBOX_MAX_LIFETIME_MS, E2B_PI_SANDBOX_PROVIDER_LIMIT_MS) + : Math.min(PI_SANDBOX_MAX_LIFETIME_MS, providerLimitMs) } /** diff --git a/apps/sim/lib/execution/remote-sandbox/types.ts b/apps/sim/lib/execution/remote-sandbox/types.ts index 9c4131116da..2e62e611551 100644 --- a/apps/sim/lib/execution/remote-sandbox/types.ts +++ b/apps/sim/lib/execution/remote-sandbox/types.ts @@ -1,8 +1,10 @@ +import type { SANDBOX_PROVIDER_IDS } from '@sim/utils/sandbox-references' import type { CodePlaceholderRuntimeBinding } from '@/lib/execution/code-placeholders/types' import type { DurableSecretProvenance } from '@/lib/execution/durable-secret-provenance' import type { CodeLanguage } from '@/lib/execution/languages' import type { SandboxBuildError } from '@/lib/execution/remote-sandbox/build-errors' import type { SandboxPhaseTimings } from '@/lib/execution/remote-sandbox/phase-timing' +import type { SessionProcessIdentity } from '@/lib/execution/remote-sandbox/session-process' import type { SandboxSpec } from '@/lib/execution/remote-sandbox/spec' /** @@ -12,7 +14,7 @@ import type { SandboxSpec } from '@/lib/execution/remote-sandbox/spec' */ export type SandboxKind = 'code' | 'shell' | 'mothership' | 'doc' | 'pi' -export type SandboxProviderId = 'e2b' | 'daytona' +export type SandboxProviderId = (typeof SANDBOX_PROVIDER_IDS)[number] /** * A sandbox input file. `content` entries are written inline; `url` entries are fetched from inside @@ -515,6 +517,13 @@ export interface SandboxProvider { * resolving false when a resume got there first. Callers hold the session's lock. */ killPausedSessionSandbox?(sandbox: PausedSessionSandbox, pausedBeforeMs: number): Promise + /** + * Stops a session command this provider recorded through `recordSandboxProcess`, for a + * caller that lost its live handle. Resolves when the sandbox is already gone; throws when + * the outcome is unknown so the durable receipt stays unresolved. Providers that never + * record session processes omit it. + */ + stopSessionProcess?(process: SessionProcessIdentity, signal: AbortSignal): Promise } export interface PausedSessionSandbox { diff --git a/apps/sim/lib/mothership/request/tools/sandbox-recovery.ts b/apps/sim/lib/mothership/request/tools/sandbox-recovery.ts index 8ed6272c542..daec49c0168 100644 --- a/apps/sim/lib/mothership/request/tools/sandbox-recovery.ts +++ b/apps/sim/lib/mothership/request/tools/sandbox-recovery.ts @@ -1,6 +1,6 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' -import { stopE2BSessionProcess } from '@/lib/execution/remote-sandbox/e2b' +import { resolveProvider } from '@/lib/execution/remote-sandbox/provider' import type { SessionProcessIdentity } from '@/lib/execution/remote-sandbox/session-process' import { settleSimSandboxProcess } from '@/lib/mothership/async-runs/repository' @@ -15,7 +15,11 @@ export async function recoverSandboxProcesses( processes.map(async (process) => { try { signal.throwIfAborted() - await stopE2BSessionProcess(process, signal) + const provider = resolveProvider() + if (!provider.stopSessionProcess) { + throw new Error(`The ${provider.id} sandbox provider cannot stop session commands`) + } + await provider.stopSessionProcess(process, signal) await settleSimSandboxProcess(process.toolCallId, process.id) } catch (error) { logger.warn('Sandbox command remains unresolved', { diff --git a/packages/deployment-config/src/env-capabilities.ts b/packages/deployment-config/src/env-capabilities.ts index 857ba9c5f5b..a75441e8013 100644 --- a/packages/deployment-config/src/env-capabilities.ts +++ b/packages/deployment-config/src/env-capabilities.ts @@ -1120,6 +1120,61 @@ export const SANDBOX_CAPABILITY = defineCapability({ ], } as const) +/** + * Sandbox kinds that run on a dedicated image beyond the Function base. Each is + * optional: a deployment configures its image separately, and the feature that + * needs it stays off until it does. + */ +type DedicatedSandboxImageKind = 'mothership' | 'doc' | 'pi' + +/** + * What each provider needs, on top of its own activation, to serve each + * dedicated image kind. Keyed by every declared {@link SANDBOX_CAPABILITY} + * provider, so a new provider does not type-check until it states what it + * can run. + * + * E2B's Pi entry is empty on purpose: Pi cloud has always shown whenever E2B is + * enabled, and the adapter reports a missing `E2B_PI_TEMPLATE_ID` when the + * sandbox is created. + */ +const SANDBOX_IMAGE_KIND_REQUIREMENTS = { + e2b: { + mothership: allOf(envField('E2B_API_KEY'), envField('MOTHERSHIP_E2B_TEMPLATE_ID')), + doc: allOf(envField('E2B_API_KEY'), envField('MOTHERSHIP_E2B_DOC_TEMPLATE_ID')), + pi: allOf(), + }, + daytona: { + mothership: allOf(envField('DAYTONA_API_KEY'), envField('DAYTONA_SHELL_SNAPSHOT_ID')), + doc: allOf(envField('DAYTONA_API_KEY'), envField('DAYTONA_DOC_SNAPSHOT_ID')), + pi: allOf(envField('DAYTONA_API_KEY'), envField('DAYTONA_PI_SNAPSHOT_ID')), + }, +} as const satisfies Record< + DeclaredProviderId, + Record +> + +/** + * Whether the selected sandbox provider can serve `kind` with this environment. + * + * `function` is the selected provider being fully configured, credential and + * immutable Function base included. A dedicated image kind needs only the + * selected provider to be active plus that kind's own requirements, because the + * Function and dedicated images have separate release and rollout lifecycles. + */ +export function isSandboxKindAvailable( + values: EnvCapabilityValues, + kind: 'function' | DedicatedSandboxImageKind +): boolean { + const inspection = inspectCapability(SANDBOX_CAPABILITY, values) + const selected = inspection.providers.find((provider) => provider.id === inspection.providerId) + if (!selected) return false + if (kind === 'function') return selected.state === 'ready' + return ( + selected.active && + inspectRequirement(SANDBOX_IMAGE_KIND_REQUIREMENTS[selected.id][kind], values).ready + ) +} + export const ASYNC_JOBS_CAPABILITY = defineCapability({ strategy: 'selected', id: 'jobs', diff --git a/packages/sim-setup/src/capability-config.ts b/packages/sim-setup/src/capability-config.ts index 0cd70a912df..720642f58cb 100644 --- a/packages/sim-setup/src/capability-config.ts +++ b/packages/sim-setup/src/capability-config.ts @@ -539,6 +539,19 @@ export const STORAGE_SETUP = defineCapabilitySetup(STORAGE_CAPABILITY, { optionOrder: ['local', 's3', 'azure', 'gcs'], }) +/** Sandboxes are disabled while no provider's activation keys switch it on. */ +const NO_SANDBOX_PROVIDER_ACTIVE: SetupCondition = { + kind: 'all', + conditions: SANDBOX_CAPABILITY.providers.flatMap((provider): SetupCondition[] => + provider.activation.mode === 'enabled' + ? [{ kind: 'not', condition: { kind: 'truthy', key: provider.activation.key } }] + : provider.activation.keys.map((key) => ({ + kind: 'not', + condition: { kind: 'present', key }, + })) + ), +} + export const SANDBOX_SETUP = defineCapabilitySetup(SANDBOX_CAPABILITY, { label: 'Function sandboxes', message: 'Function sandbox provider?', @@ -546,20 +559,7 @@ export const SANDBOX_SETUP = defineCapabilitySetup(SANDBOX_CAPABILITY, { disabled: { label: 'Disabled', hint: 'local JavaScript execution only', - currentWhen: { - kind: 'all', - conditions: [ - { kind: 'not', condition: { kind: 'truthy', key: 'E2B_ENABLED' } }, - { - kind: 'not', - condition: { kind: 'present', key: 'DAYTONA_API_KEY' }, - }, - { - kind: 'not', - condition: { kind: 'present', key: 'DAYTONA_FUNCTION_SNAPSHOT_ID' }, - }, - ], - }, + currentWhen: NO_SANDBOX_PROVIDER_ACTIVE, }, }, providers: { @@ -606,7 +606,7 @@ export const SANDBOX_SETUP = defineCapabilitySetup(SANDBOX_CAPABILITY, { ], }, }, - optionOrder: ['disabled', 'e2b', 'daytona'], + optionOrder: ['disabled', ...SANDBOX_CAPABILITY.providers.map((provider) => provider.id)], }) export const JOBS_SETUP = defineCapabilitySetup(ASYNC_JOBS_CAPABILITY, { diff --git a/packages/sim-setup/src/capability-status.ts b/packages/sim-setup/src/capability-status.ts index cb81156c950..a8c2595b8ad 100644 --- a/packages/sim-setup/src/capability-status.ts +++ b/packages/sim-setup/src/capability-status.ts @@ -13,13 +13,13 @@ import { hasEnvCapabilityValue, inspectCapability, inspectOAuthClientCapability, - isTruthyEnvCapabilityValue, KNOWLEDGE_EMBEDDINGS_CAPABILITY, LLM_KEY_POOLS, OAUTH_CLIENT_CAPABILITIES, type OAuthClientCapabilityId, OCR_CAPABILITY, type ProviderConfigurationState, + type ProviderId, type ProviderInspection, SANDBOX_CAPABILITY, STORAGE_CAPABILITY, @@ -63,8 +63,18 @@ export interface StorageCapabilityStatus extends FeatureStatusBase<'storage'> { providers: readonly ProviderInspection<(typeof STORAGE_CAPABILITY.providers)[number]['id']>[] } +type SandboxProviderId = ProviderId + +const SANDBOX_CAPABILITY_PROVIDER_IDS: readonly string[] = SANDBOX_CAPABILITY.providers.map( + (provider) => provider.id +) + +function isSandboxProviderId(value: string): value is SandboxProviderId { + return SANDBOX_CAPABILITY_PROVIDER_IDS.includes(value) +} + export interface SandboxCapabilityStatus extends FeatureStatusBase<'sandbox'> { - providerId: 'disabled' | 'e2b' | 'daytona' | null + providerId: 'disabled' | SandboxProviderId | null } export interface JobsCapabilityStatus extends FeatureStatusBase<'jobs'> { @@ -236,8 +246,11 @@ function inspectSandbox(values: EnvCapabilityValues): SandboxCapabilityStatus { const requestedProvider = readConfiguredString(values, SANDBOX_CAPABILITY.selectorKey) ?? SANDBOX_CAPABILITY.defaultProvider.id + const selectedProvider = inspection.providers.find( + (provider) => provider.id === inspection.providerId + ) const providerId = - inspection.providerId === 'e2b' && !isTruthyEnvCapabilityValue(values, 'E2B_ENABLED') + selectedProvider && !selectedProvider.active && selectedProvider.state === 'absent' ? 'disabled' : inspection.providerId @@ -249,11 +262,9 @@ function inspectSandbox(values: EnvCapabilityValues): SandboxCapabilityStatus { } } - const knownProvider = requestedProvider === 'e2b' || requestedProvider === 'daytona' - const selectedProvider = inspection.providers.find( - (provider) => provider.id === requestedProvider - ) - const state = !knownProvider || selectedProvider?.state === 'invalid' ? 'invalid' : 'missing' + const knownProvider = isSandboxProviderId(requestedProvider) + const requested = inspection.providers.find((provider) => provider.id === requestedProvider) + const state = !knownProvider || requested?.state === 'invalid' ? 'invalid' : 'missing' return { ...featureMetadata('sandbox'), @@ -264,7 +275,7 @@ function inspectSandbox(values: EnvCapabilityValues): SandboxCapabilityStatus { inspection.error, knownProvider ? inspection.error.message - : 'Unknown SANDBOX_PROVIDER. Expected one of: e2b, daytona' + : `Unknown SANDBOX_PROVIDER. Expected one of: ${SANDBOX_CAPABILITY_PROVIDER_IDS.join(', ')}` ), } } diff --git a/packages/testing/src/mocks/env-flags.mock.ts b/packages/testing/src/mocks/env-flags.mock.ts index 8dbfddd8ad5..a15898e1706 100644 --- a/packages/testing/src/mocks/env-flags.mock.ts +++ b/packages/testing/src/mocks/env-flags.mock.ts @@ -51,7 +51,7 @@ interface EnvFlagsMockState { isOllamaConfigured: boolean isAzureConfigured: boolean isCohereConfigured: boolean - isE2bEnabled: boolean + isPiCloudEnabled: boolean isInvitationsDisabled: boolean isPublicApiDisabled: boolean isGoogleAuthDisabled: boolean @@ -104,7 +104,7 @@ const defaultEnvFlagsState: EnvFlagsMockState = { isOllamaConfigured: false, isAzureConfigured: false, isCohereConfigured: false, - isE2bEnabled: false, + isPiCloudEnabled: false, isInvitationsDisabled: false, isPublicApiDisabled: false, isGoogleAuthDisabled: false, diff --git a/packages/testing/src/mocks/remote-sandbox-provider.mock.ts b/packages/testing/src/mocks/remote-sandbox-provider.mock.ts index 73f9ac87918..feaa5fcc76f 100644 --- a/packages/testing/src/mocks/remote-sandbox-provider.mock.ts +++ b/packages/testing/src/mocks/remote-sandbox-provider.mock.ts @@ -5,7 +5,8 @@ import { vi } from 'vitest' * * Default: `mockResolveProvider` returns a fresh `{ id: 'e2b' }` — the provider id every local * stub agreed on, with no adapter methods. Give it the methods a test exercises - * (`create`, `findSessionSandbox`, `resolveLifetimeMs`, `dependencyStrategy`, `images`). + * (`create`, `findSessionSandbox`, `stopSessionProcess`, `resolveLifetimeMs`, `dependencyStrategy`, + * `images`). * * @example * ```ts From bcc30322d79e7ea4105eeb4aa34bc9faaa76e24a Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 13:26:39 -0600 Subject: [PATCH 02/78] improvement(sandbox): parameterize provider conformance suite by a fixture table --- .../remote-sandbox/conformance.test.ts | 1240 +++++++++-------- 1 file changed, 626 insertions(+), 614 deletions(-) diff --git a/apps/sim/lib/execution/remote-sandbox/conformance.test.ts b/apps/sim/lib/execution/remote-sandbox/conformance.test.ts index a4f8e5bacd4..1b96051b9af 100644 --- a/apps/sim/lib/execution/remote-sandbox/conformance.test.ts +++ b/apps/sim/lib/execution/remote-sandbox/conformance.test.ts @@ -6,7 +6,7 @@ */ import { Readable } from 'node:stream' import { envMock, setEnv } from '@sim/testing/mocks/env.mock' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from 'vitest' import { CodeLanguage } from '@/lib/execution/languages' import { SANDBOX_OUTPUT_DIR_SENTINEL } from '@/lib/execution/remote-sandbox/paths' @@ -125,98 +125,141 @@ import { resolvePiSandboxLifetimeMs, } from '@/lib/execution/remote-sandbox/pi-lifetime' import { resolveProvider } from '@/lib/execution/remote-sandbox/provider' +import type { SandboxProviderId } from '@/lib/execution/remote-sandbox/types' -type Provider = 'e2b' | 'daytona' -const PROVIDERS: Provider[] = ['e2b', 'daytona'] - -describe('provider-effective sandbox lifetimes', () => { - it('matches E2B second and Daytona minute rounding', () => { - expect(resolveE2BSandboxLifetimeMs(1001)).toBe(2000) - expect(resolveDaytonaSandboxLifetimeMs(1001)).toBe(60_000) - }) - - it.each(PROVIDERS)('reports the %s SDK create dispatch time', async (provider) => { - useProvider(provider) - const onProviderRequestStarted = vi.fn() - const createMock = provider === 'e2b' ? mockE2BCreate : mockDaytonaCreate - - await resolveProvider().create('code', { lifetimeMs: 1000, onProviderRequestStarted }) - - expect(onProviderRequestStarted).toHaveBeenCalledOnce() - expect(onProviderRequestStarted).toHaveBeenCalledWith(expect.any(Number)) - expect(onProviderRequestStarted.mock.invocationCallOrder[0]).toBeLessThan( - createMock.mock.invocationCallOrder[0] - ) - }) -}) - -setEnv({ - SANDBOX_PROVIDER: 'e2b', - PI_SANDBOX_LIFETIME_MS: undefined, - E2B_ENABLED: 'true', - E2B_API_KEY: 'test-key', - E2B_FUNCTION_TEMPLATE_ID: 'sim-function:f47ac10b-58cc-4372-a567-0e02b2c3d479', - E2B_FUNCTION_TEMPLATE_GENERATION: '1785792000000', - MOTHERSHIP_E2B_TEMPLATE_ID: 'mothership-shell', - MOTHERSHIP_E2B_DOC_TEMPLATE_ID: 'mothership-docs', - E2B_PI_TEMPLATE_ID: 'sim-pi', - DAYTONA_API_KEY: 'test-key', - DAYTONA_FUNCTION_SNAPSHOT_ID: '7d9d12d6-5f2a-44df-9cc2-a20203f3813b', - DAYTONA_SHELL_SNAPSHOT_ID: 'mothership-shell:v1', - DAYTONA_DOC_SNAPSHOT_ID: 'mothership-docs:v1', - DAYTONA_PI_SNAPSHOT_ID: 'sim-pi:v1', -}) -const mockEnv = envMock.env - -/** Points the shared layer at one provider via the SANDBOX_PROVIDER env var. */ -function useProvider(provider: Provider) { - mockEnv.SANDBOX_PROVIDER = provider +interface CapturedSandboxWrite { + path: string + content: unknown + order: number } -function providerTimeoutError(provider: Provider): Error { - const error = new Error( - provider === 'e2b' - ? 'Execution timed out — the timeoutMs option was reached' - : 'Execution timed out: operation exceeded the configured timeout' - ) - error.name = provider === 'e2b' ? 'TimeoutError' : 'DaytonaTimeoutError' - return error +interface OutputDirListingEntry { + path: string + size: number + kind?: 'file' | 'dir' } -function emitDaytonaStreamReady(onStdout: (chunk: string) => void): void { - const command = mockExecuteSessionCommand.mock.calls.at(-1)?.[1]?.command - if (typeof command === 'string' && command.includes('__SIM_DAYTONA_STREAM_READY__')) { - onStdout('__SIM_DAYTONA_STREAM_READY__\n') - } +/** + * Everything a shared conformance scenario needs to drive or observe one provider. Adding a + * provider is one entry in {@link CONFORMANCE_PROVIDERS}; a scenario never branches on the id. + */ +interface ConformanceProviderFixture { + /** Images the env configures for each kind, as the provider's create call names them. */ + images: { function: string; mothership: string; doc: string } + /** A failed command's stderr also reaches stdout. */ + mergesStderrIntoStdout: boolean + createMock: Mock + killMock: Mock + writeMock: Mock + readMock: Mock + inspectMock: Mock + listMock: Mock + removeMock: Mock + /** Starts a process inside the sandbox. */ + launchMock: Mock + /** Settles a started process: its output callbacks and its outcome. */ + processMock: Mock + timeoutError(): Error + stubCodeRun(stdout: string): void + stubShellCommand(stdout: string, stderr: string, exitCode: number): void + /** Streams one chunk from the next started process after the stream handshake. */ + stubStreamedStdoutOnce(chunk: string): void + /** Streams one chunk to a Pi runner's stdout and completes it successfully. */ + stubPiStdoutOnce(chunk: string): void + stubPiStderrOnce(chunk: string): void + /** Runs `effect` inside the next process, which then ends as timed out. */ + stubTimedOutProcessAfterOnce(effect: () => void): void + stubMountFetchFailure(): void + stubOutputFileSizes(...sizes: number[]): void + stubNonRegularOutputFile(): void + stubOutputFileRead(content: string | Uint8Array, onRead?: () => void): void + stubOutputDirListing(entries: OutputDirListingEntry[]): void + /** The object a stalled create resolves with after the caller gave up. */ + lateSandbox(): unknown + /** Every file write in call order, including the runtime's own files. */ + writes(): CapturedSandboxWrite[] + launchedCommands(): string[] + /** + * Asserts the first command's environment holds `expected` and never `secret`, and reports + * when that environment was delivered and when the command launched. + */ + expectCommandEnvironment( + expected: Record, + secret?: string + ): { deliveredAt: number; launchedAt: number } + expectCommandEnvironmentLacks(name: string): void + expectCreatedWithImage(image: string, nth?: number): void + expectLifetimeBudget(budgetMs: number): void + expectCommandBudget(budgetMs: number, exclusiveFloorMs: number): void + expectJavaScriptPreloadLaunch(): void } -/** Stubs a code execution that prints `stdout` and emits `result` via the marker. */ -function stubCodeRun(provider: Provider, stdout: string) { - if (provider === 'e2b') { - mockE2BCommandsRun.mockResolvedValue({ stdout, stderr: '', exitCode: 0 }) - } else { - mockGetSessionCommandLogs.mockImplementation( - async (_sessionId: string, _commandId: string, onStdout: (chunk: string) => void) => { - emitDaytonaStreamReady(onStdout) - if (stdout) onStdout(stdout) - } - ) - mockGetSessionCommand.mockResolvedValue({ exitCode: 0 }) - } +function daytonaEnvironmentFile(fixture: ConformanceProviderFixture): string | undefined { + const environmentWrite = fixture.writes().find((write) => write.path.startsWith('/tmp/.sim-env-')) + return environmentWrite ? sandboxWriteBuffer(environmentWrite.content).toString() : undefined } -function stubOutputFileSizes(provider: Provider, ...sizes: number[]) { - for (const size of sizes) { - if (provider === 'e2b') { +const e2bFixture: ConformanceProviderFixture = { + images: { + function: 'sim-function:f47ac10b-58cc-4372-a567-0e02b2c3d479', + mothership: 'mothership-shell', + doc: 'mothership-docs', + }, + mergesStderrIntoStdout: false, + createMock: mockE2BCreate, + killMock: mockE2BKill, + writeMock: mockE2BFilesWrite, + readMock: mockE2BFilesRead, + inspectMock: mockE2BFilesGetInfo, + listMock: mockE2BFilesList, + removeMock: mockE2BFilesRemove, + launchMock: mockE2BCommandsRun, + processMock: mockE2BCommandsRun, + timeoutError() { + const error = new Error('Execution timed out — the timeoutMs option was reached') + error.name = 'TimeoutError' + return error + }, + stubCodeRun(stdout) { + mockE2BCommandsRun.mockResolvedValue({ stdout, stderr: '', exitCode: 0 }) + }, + stubShellCommand(stdout, stderr, exitCode) { + mockE2BCommandsRun.mockResolvedValueOnce({ stdout, stderr, exitCode }) + }, + stubStreamedStdoutOnce(chunk) { + mockE2BCommandsRun.mockImplementationOnce(async (_command, options) => { + options.onStdout(chunk) + }) + }, + stubPiStdoutOnce(chunk) { + mockE2BCommandsRun.mockImplementationOnce(async (_command, options) => { + options.onStdout?.(chunk) + return { stdout: chunk, stderr: '', exitCode: 0 } + }) + }, + stubPiStderrOnce(chunk) { + mockE2BCommandsRun.mockImplementationOnce(async (_command, options) => { + options.onStderr(chunk) + }) + }, + stubTimedOutProcessAfterOnce(effect) { + mockE2BCommandsRun.mockImplementationOnce(async () => { + effect() + throw e2bFixture.timeoutError() + }) + }, + stubMountFetchFailure() { + mockE2BCommandsRun.mockRejectedValue(new Error('curl: (22) 404')) + }, + stubOutputFileSizes(...sizes) { + for (const size of sizes) { mockE2BFilesGetInfo.mockResolvedValueOnce({ size, type: 'file' }) - } else { - mockGetFileDetails.mockResolvedValueOnce({ size, isDir: false, mode: '-rw-r--r--' }) } - } -} - -function stubOutputFileRead(provider: Provider, content: string | Uint8Array, onRead?: () => void) { - if (provider === 'e2b') { + }, + stubNonRegularOutputFile() { + mockE2BFilesGetInfo.mockResolvedValueOnce({ size: 1, type: 'symlink' }) + }, + stubOutputFileRead(content, onRead) { mockE2BFilesRead.mockImplementationOnce(async () => { onRead?.() return new ReadableStream({ @@ -226,57 +269,292 @@ function stubOutputFileRead(provider: Provider, content: string | Uint8Array, on }, }) }) - } else { + }, + stubOutputDirListing(entries) { + mockE2BFilesList.mockResolvedValueOnce( + entries.map((entry) => ({ + name: entry.path.split('/').pop(), + path: entry.path, + size: entry.size, + type: entry.kind === 'dir' ? 'dir' : 'file', + })) + ) + }, + lateSandbox() { + return { + sandboxId: 'late-sandbox', + commands: { run: mockE2BCommandsRun }, + files: { + getInfo: mockE2BFilesGetInfo, + read: mockE2BFilesRead, + remove: mockE2BFilesRemove, + write: mockE2BFilesWrite, + }, + kill: mockE2BKill, + } + }, + writes() { + return mockE2BFilesWrite.mock.calls.map((call, index) => ({ + path: String(call[0]), + content: call[1], + order: mockE2BFilesWrite.mock.invocationCallOrder[index], + })) + }, + launchedCommands() { + return mockE2BCommandsRun.mock.calls.map((call) => call[0]) + }, + expectCommandEnvironment(expected, secret) { + const [, options] = mockE2BCommandsRun.mock.calls[0] + expect(options.envs).toMatchObject(expected) + if (secret !== undefined) expect(JSON.stringify(options.envs)).not.toContain(secret) + const launchedAt = mockE2BCommandsRun.mock.invocationCallOrder[0] + return { deliveredAt: launchedAt, launchedAt } + }, + expectCommandEnvironmentLacks(name) { + expect(mockE2BCommandsRun.mock.calls[0][1].envs?.[name]).toBe(undefined) + }, + expectCreatedWithImage(image, nth) { + if (nth === undefined) { + expect(mockE2BCreate).toHaveBeenCalledWith(image, expect.anything()) + } else { + expect(mockE2BCreate).toHaveBeenNthCalledWith(nth, image, expect.anything()) + } + }, + expectLifetimeBudget(budgetMs) { + const sandboxTimeoutMs = mockE2BCreate.mock.calls[0][1].timeoutMs + expect(sandboxTimeoutMs).toBeGreaterThan(budgetMs - 1000) + expect(sandboxTimeoutMs).toBeLessThanOrEqual(budgetMs) + }, + expectCommandBudget(budgetMs, exclusiveFloorMs) { + const commandTimeoutMs = mockE2BCommandsRun.mock.calls.at(-1)?.[1].timeoutMs + expect(commandTimeoutMs).toBeGreaterThan(exclusiveFloorMs) + expect(commandTimeoutMs).toBeLessThanOrEqual(budgetMs) + }, + expectJavaScriptPreloadLaunch() { + expect(mockE2BCommandsRun.mock.calls.at(-1)?.[1].envs.SIM_PRELOAD_PATH).toMatch( + /^\.\/\.sim-function-[A-Za-z0-9_-]+\.cjs$/ + ) + }, +} + +const daytonaFixture: ConformanceProviderFixture = { + images: { + function: '7d9d12d6-5f2a-44df-9cc2-a20203f3813b', + mothership: 'mothership-shell:v1', + doc: 'mothership-docs:v1', + }, + mergesStderrIntoStdout: true, + createMock: mockDaytonaCreate, + killMock: mockDelete, + writeMock: mockUploadFile, + readMock: mockDownloadFileStream, + inspectMock: mockGetFileDetails, + listMock: mockListFiles, + removeMock: mockDeleteFile, + launchMock: mockExecuteSessionCommand, + processMock: mockGetSessionCommandLogs, + timeoutError() { + const error = new Error('Execution timed out: operation exceeded the configured timeout') + error.name = 'DaytonaTimeoutError' + return error + }, + stubCodeRun(stdout) { + mockGetSessionCommandLogs.mockImplementation( + async (_sessionId: string, _commandId: string, onStdout: (chunk: string) => void) => { + emitDaytonaStreamReady(onStdout) + if (stdout) onStdout(stdout) + } + ) + mockGetSessionCommand.mockResolvedValue({ exitCode: 0 }) + }, + stubShellCommand(stdout, stderr, exitCode) { + mockGetSessionCommandLogs.mockImplementationOnce( + async ( + _sessionId: string, + _commandId: string, + onStdout: (chunk: string) => void, + onStderr: (chunk: string) => void + ) => { + emitDaytonaStreamReady(onStdout) + if (stdout) onStdout(stdout) + if (stderr) onStderr(stderr) + } + ) + mockGetSessionCommand.mockResolvedValueOnce({ exitCode }) + }, + stubStreamedStdoutOnce(chunk) { + mockGetSessionCommandLogs.mockImplementationOnce(async (_sessionId, _commandId, onStdout) => { + emitDaytonaStreamReady(onStdout) + onStdout(chunk) + }) + }, + stubPiStdoutOnce(chunk) { + mockGetSessionCommandLogs.mockImplementationOnce( + async (_sessionId: string, _commandId: string, onStdout: (chunk: string) => void) => { + onStdout(chunk) + } + ) + mockGetSessionCommand.mockResolvedValue({ exitCode: 0 }) + }, + stubPiStderrOnce(chunk) { + mockGetSessionCommandLogs.mockImplementationOnce( + async ( + _sessionId: string, + _commandId: string, + _onStdout: (chunk: string) => void, + onStderr: (chunk: string) => void + ) => { + onStderr(chunk) + } + ) + }, + stubTimedOutProcessAfterOnce(effect) { + mockGetSessionCommandLogs.mockImplementationOnce(async () => { + effect() + }) + mockGetSessionCommand.mockResolvedValueOnce({ exitCode: 124 }) + }, + stubMountFetchFailure() { + daytonaFixture.stubShellCommand('', 'curl: (22) 404', 22) + }, + stubOutputFileSizes(...sizes) { + for (const size of sizes) { + mockGetFileDetails.mockResolvedValueOnce({ size, isDir: false, mode: '-rw-r--r--' }) + } + }, + stubNonRegularOutputFile() { + mockGetFileDetails.mockResolvedValueOnce({ size: 1, isDir: false, mode: 'prw-r--r--' }) + }, + stubOutputFileRead(content, onRead) { mockDownloadFileStream.mockImplementationOnce(async () => { onRead?.() return Readable.from([typeof content === 'string' ? Buffer.from(content) : content]) }) - } -} - -function stubShellCommand(provider: Provider, stdout: string, stderr: string, exitCode: number) { - if (provider === 'e2b') { - mockE2BCommandsRun.mockResolvedValueOnce({ stdout, stderr, exitCode }) - return - } - mockGetSessionCommandLogs.mockImplementationOnce( - async ( - _sessionId: string, - _commandId: string, - onStdout: (chunk: string) => void, - onStderr: (chunk: string) => void - ) => { - emitDaytonaStreamReady(onStdout) - if (stdout) onStdout(stdout) - if (stderr) onStderr(stderr) + }, + stubOutputDirListing(entries) { + mockListFiles.mockResolvedValueOnce( + entries.map((entry) => ({ + name: entry.path.split('/').pop(), + path: entry.path, + size: entry.size, + isDir: entry.kind === 'dir', + mode: entry.kind === 'dir' ? 'drwxr-xr-x' : '-rw-r--r--', + })) + ) + }, + lateSandbox() { + return { + id: 'late-sandbox', + process: { + createSession: mockCreateSession, + executeSessionCommand: mockExecuteSessionCommand, + getSessionCommandLogs: mockGetSessionCommandLogs, + getSessionCommand: mockGetSessionCommand, + deleteSession: mockDeleteSession, + }, + fs: { + deleteFile: mockDeleteFile, + uploadFile: mockUploadFile, + downloadFileStream: mockDownloadFileStream, + getFileDetails: mockGetFileDetails, + }, + delete: mockDelete, } - ) - mockGetSessionCommand.mockResolvedValueOnce({ exitCode }) + }, + writes() { + return mockUploadFile.mock.calls.map((call, index) => ({ + path: String(call[1]), + content: call[0], + order: mockUploadFile.mock.invocationCallOrder[index], + })) + }, + launchedCommands() { + return mockExecuteSessionCommand.mock.calls.map((call) => call[1].command) + }, + expectCommandEnvironment(expected, secret) { + const environmentWrite = daytonaFixture + .writes() + .find((write) => write.path.startsWith('/tmp/.sim-env-')) + expect(environmentWrite).toBeDefined() + const environmentFile = sandboxWriteBuffer(environmentWrite?.content).toString() + for (const [name, value] of Object.entries(expected)) { + expect(environmentFile).toContain(`${name}='${value ?? ''}'`) + } + if (secret !== undefined) expect(environmentFile).not.toContain(secret) + return { + deliveredAt: environmentWrite?.order ?? 0, + launchedAt: mockExecuteSessionCommand.mock.invocationCallOrder[0], + } + }, + expectCommandEnvironmentLacks(name) { + expect(daytonaEnvironmentFile(daytonaFixture) ?? '').not.toContain(`${name}=`) + }, + expectCreatedWithImage(image, nth) { + if (nth === undefined) { + expect(mockDaytonaCreate).toHaveBeenCalledWith(expect.objectContaining({ snapshot: image })) + } else { + expect(mockDaytonaCreate).toHaveBeenNthCalledWith( + nth, + expect.objectContaining({ snapshot: image }) + ) + } + }, + expectLifetimeBudget(budgetMs) { + expect(mockDaytonaCreate.mock.calls[0][0]).toMatchObject({ + ephemeral: true, + ttlMinutes: Math.ceil(budgetMs / 60_000), + }) + }, + expectCommandBudget(budgetMs) { + expect(mockExecuteSessionCommand.mock.calls.at(-1)?.[2]).toBe(Math.ceil(budgetMs / 1000)) + }, + expectJavaScriptPreloadLaunch() { + const uploadedFunctionPaths = mockUploadFile.mock.calls + .map(([, path]) => String(path)) + .filter((path) => path.includes('.sim-function-')) + expect(uploadedFunctionPaths).toHaveLength(3) + expect(uploadedFunctionPaths).toEqual( + expect.arrayContaining([ + expect.stringMatching(/^\.sim-function-[A-Za-z0-9_-]+\.mjs$/), + expect.stringMatching(/^\.sim-function-[A-Za-z0-9_-]+\.cjs$/), + expect.stringMatching(/^\.sim-function-[A-Za-z0-9_-]+\.sh$/), + ]) + ) + const environmentWrite = mockUploadFile.mock.calls.find(([, path]) => + String(path).startsWith('/tmp/.sim-env-') + )?.[0] + const environment = sandboxWriteBuffer(environmentWrite).toString('utf8') + expect(environment).toMatch(/SIM_CODE_PATH='\.sim-function-[A-Za-z0-9_-]+\.mjs'/) + expect(environment).toMatch(/SIM_PRELOAD_PATH='\.\/\.sim-function-[A-Za-z0-9_-]+\.cjs'/) + const launcher = mockUploadFile.mock.calls.find(([, path]) => String(path).endsWith('.sh'))?.[0] + expect(sandboxWriteBuffer(launcher).toString('utf8')).toContain( + 'ln -s "$SIM_NODE_MODULES_PATH" node_modules' + ) + }, } -interface CapturedSandboxWrite { - path: string - content: unknown - order: number +const CONFORMANCE_PROVIDERS = { + e2b: e2bFixture, + daytona: daytonaFixture, +} satisfies Record + +const PROVIDERS = Object.keys(CONFORMANCE_PROVIDERS) as SandboxProviderId[] + +/** Points the shared layer at one provider via the SANDBOX_PROVIDER env var. */ +function useProvider(provider: SandboxProviderId) { + mockEnv.SANDBOX_PROVIDER = provider } -function capturedSandboxWrites(provider: Provider): CapturedSandboxWrite[] { - if (provider === 'e2b') { - return mockE2BFilesWrite.mock.calls - .map((call, index) => ({ - path: String(call[0]), - content: call[1], - order: mockE2BFilesWrite.mock.invocationCallOrder[index], - })) - .filter((write) => !write.path.includes('.sim-function-')) +function emitDaytonaStreamReady(onStdout: (chunk: string) => void): void { + const command = mockExecuteSessionCommand.mock.calls.at(-1)?.[1]?.command + if (typeof command === 'string' && command.includes('__SIM_DAYTONA_STREAM_READY__')) { + onStdout('__SIM_DAYTONA_STREAM_READY__\n') } - return mockUploadFile.mock.calls - .map((call, index) => ({ - path: String(call[1]), - content: call[0], - order: mockUploadFile.mock.invocationCallOrder[index], - })) - .filter((write) => !write.path.includes('.sim-function-')) +} + +/** Writes the code under test asked for, excluding the runtime's own function files. */ +function capturedSandboxWrites(fixture: ConformanceProviderFixture): CapturedSandboxWrite[] { + return fixture.writes().filter((write) => !write.path.includes('.sim-function-')) } function sandboxWriteBuffer(content: unknown): Buffer { @@ -288,18 +566,56 @@ function sandboxWriteBuffer(content: unknown): Buffer { throw new Error('Unexpected sandbox write content') } -function expectPrivateInputsUseSandboxTeardown(provider: Provider): void { - const writes = capturedSandboxWrites(provider).filter((write) => +function expectPrivateInputsUseSandboxTeardown(fixture: ConformanceProviderFixture): void { + const writes = capturedSandboxWrites(fixture).filter((write) => write.path.startsWith('/tmp/.sim-private-input-') ) expect(writes.length).toBeGreaterThan(0) - const remove = provider === 'e2b' ? mockE2BFilesRemove : mockDeleteFile - const removed = remove.mock.calls.filter(([path]) => + const removed = fixture.removeMock.mock.calls.filter(([path]) => String(path).startsWith('/tmp/.sim-private-input-') ) expect(removed).toEqual([]) } +describe('provider-effective sandbox lifetimes', () => { + it('matches E2B second and Daytona minute rounding', () => { + expect(resolveE2BSandboxLifetimeMs(1001)).toBe(2000) + expect(resolveDaytonaSandboxLifetimeMs(1001)).toBe(60_000) + }) + + it.each(PROVIDERS)('reports the %s SDK create dispatch time', async (provider) => { + useProvider(provider) + const fixture = CONFORMANCE_PROVIDERS[provider] + const onProviderRequestStarted = vi.fn() + + await resolveProvider().create('code', { lifetimeMs: 1000, onProviderRequestStarted }) + + expect(onProviderRequestStarted).toHaveBeenCalledOnce() + expect(onProviderRequestStarted).toHaveBeenCalledWith(expect.any(Number)) + expect(onProviderRequestStarted.mock.invocationCallOrder[0]).toBeLessThan( + fixture.createMock.mock.invocationCallOrder[0] + ) + }) +}) + +setEnv({ + SANDBOX_PROVIDER: 'e2b', + PI_SANDBOX_LIFETIME_MS: undefined, + E2B_ENABLED: 'true', + E2B_API_KEY: 'test-key', + E2B_FUNCTION_TEMPLATE_ID: 'sim-function:f47ac10b-58cc-4372-a567-0e02b2c3d479', + E2B_FUNCTION_TEMPLATE_GENERATION: '1785792000000', + MOTHERSHIP_E2B_TEMPLATE_ID: 'mothership-shell', + MOTHERSHIP_E2B_DOC_TEMPLATE_ID: 'mothership-docs', + E2B_PI_TEMPLATE_ID: 'sim-pi', + DAYTONA_API_KEY: 'test-key', + DAYTONA_FUNCTION_SNAPSHOT_ID: '7d9d12d6-5f2a-44df-9cc2-a20203f3813b', + DAYTONA_SHELL_SNAPSHOT_ID: 'mothership-shell:v1', + DAYTONA_DOC_SNAPSHOT_ID: 'mothership-docs:v1', + DAYTONA_PI_SNAPSHOT_ID: 'sim-pi:v1', +}) +const mockEnv = envMock.env + beforeEach(() => { vi.resetAllMocks() @@ -369,10 +685,11 @@ beforeEach(() => { const TRUNCATION_NOTE_ALLOWANCE_BYTES = 256 describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { + const fixture = CONFORMANCE_PROVIDERS[provider] beforeEach(() => useProvider(provider)) it('parses the __SIM_RESULT__ marker and strips it from stdout', async () => { - stubCodeRun(provider, `hello\n${SIM_RESULT_PREFIX}{"ok":true}`) + fixture.stubCodeRun(`hello\n${SIM_RESULT_PREFIX}{"ok":true}`) const res = await executeInSandbox({ code: 'x', @@ -387,7 +704,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('adds provider cost to a metered successful code result', async () => { - stubCodeRun(provider, `${SIM_RESULT_PREFIX}{"ok":true}`) + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}{"ok":true}`) let now = 1_800_000_000_000 const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => ++now) @@ -412,7 +729,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('adds provider cost to a metered successful shell result', async () => { - stubShellCommand(provider, 'ok', '', 0) + fixture.stubShellCommand('ok', '', 0) let now = 1_800_000_000_000 const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => ++now) @@ -437,8 +754,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('takes the LAST marker so user output cannot shadow the real result', async () => { - stubCodeRun( - provider, + fixture.stubCodeRun( `${SIM_RESULT_PREFIX}{"decoy":true}\nnoise\n${SIM_RESULT_PREFIX}{"real":true}` ) @@ -452,7 +768,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('refuses to return a corrupted marker payload', async () => { - stubCodeRun(provider, `${SIM_RESULT_PREFIX}{"truncated":`) + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}{"truncated":`) const res = await executeInSandbox({ code: 'x', @@ -468,7 +784,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { it('survives a large single-line payload without chunk corruption', async () => { const blob = 'x'.repeat(200_000) - stubCodeRun(provider, `${SIM_RESULT_PREFIX}${JSON.stringify({ blob })}`) + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}${JSON.stringify({ blob })}`) const res = await executeInSandbox({ code: 'x', @@ -481,16 +797,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { it('terminates code execution when streamed process output exceeds the byte budget', async () => { const oversized = 'x'.repeat(MAX_SANDBOX_PROCESS_OUTPUT_BYTES + 1) - if (provider === 'e2b') { - mockE2BCommandsRun.mockImplementationOnce(async (_code, options) => { - options.onStdout(oversized) - }) - } else { - mockGetSessionCommandLogs.mockImplementationOnce(async (_sessionId, _commandId, onStdout) => { - emitDaytonaStreamReady(onStdout) - onStdout(oversized) - }) - } + fixture.stubStreamedStdoutOnce(oversized) const error = await executeInSandbox({ code: 'x', @@ -505,24 +812,12 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { limitBytes: MAX_SANDBOX_PROCESS_OUTPUT_BYTES, }) expect(readTrustedSandboxOutputCost(error)).toBeUndefined() - expect(provider === 'e2b' ? mockE2BKill : mockDelete).toHaveBeenCalledTimes(1) + expect(fixture.killMock).toHaveBeenCalledTimes(1) }) it('keeps only a diagnostic tail from a caller-consumed stream', async () => { const streamedOutput = 'x'.repeat(MAX_SANDBOX_STREAMED_OUTPUT_TAIL_BYTES + 1024) - if (provider === 'e2b') { - mockE2BCommandsRun.mockImplementationOnce(async (_cmd, options) => { - options.onStdout(`${streamedOutput}TAIL_MARKER`) - return { stdout: `${streamedOutput}TAIL_MARKER`, stderr: '', exitCode: 0 } - }) - } else { - mockGetSessionCommandLogs.mockImplementationOnce( - async (_sessionId: string, _commandId: string, onStdout: (chunk: string) => void) => { - onStdout(`${streamedOutput}TAIL_MARKER`) - } - ) - mockGetSessionCommand.mockResolvedValue({ exitCode: 0 }) - } + fixture.stubPiStdoutOnce(`${streamedOutput}TAIL_MARKER`) let streamedBytes = 0 const result = await withPiSandbox({}, (runner) => @@ -551,19 +846,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { // The Daytona appender only collapses once the accumulator passes twice the tail, so a stream // finishing inside that band is the case where the two providers can disagree. const midBand = 'y'.repeat(Math.floor(MAX_SANDBOX_STREAMED_OUTPUT_TAIL_BYTES * 1.5)) - if (provider === 'e2b') { - mockE2BCommandsRun.mockImplementationOnce(async (_cmd, options) => { - options.onStdout?.(midBand) - return { stdout: midBand, stderr: '', exitCode: 0 } - }) - } else { - mockGetSessionCommandLogs.mockImplementationOnce( - async (_sessionId: string, _commandId: string, onStdout: (chunk: string) => void) => { - onStdout(midBand) - } - ) - mockGetSessionCommand.mockResolvedValue({ exitCode: 0 }) - } + fixture.stubPiStdoutOnce(midBand) const result = await withPiSandbox({}, (runner) => runner.run('pi run', { timeoutMs: 1000, onStdout: () => {} }) @@ -577,22 +860,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { it('still bounds a stream the caller does not consume', async () => { const oversized = 'x'.repeat(MAX_SANDBOX_PROCESS_OUTPUT_BYTES + 1) - if (provider === 'e2b') { - mockE2BCommandsRun.mockImplementationOnce(async (_cmd, options) => { - options.onStderr(oversized) - }) - } else { - mockGetSessionCommandLogs.mockImplementationOnce( - async ( - _sessionId: string, - _commandId: string, - _onStdout: (chunk: string) => void, - onStderr: (chunk: string) => void - ) => { - onStderr(oversized) - } - ) - } + fixture.stubPiStderrOnce(oversized) /** A stdout callback must not exempt unconsumed stderr from the process-output budget. */ await expect( @@ -601,7 +869,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('normalizes execution errors to the same shape', async () => { - stubShellCommand(provider, '', 'Traceback...\nValueError: boom', 1) + fixture.stubShellCommand('', 'Traceback...\nValueError: boom', 1) const res = await executeInSandbox({ code: 'raise ValueError("boom")', @@ -622,11 +890,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('normalizes Python code budget expiry to a typed timeout abort', async () => { - if (provider === 'e2b') { - mockE2BCommandsRun.mockRejectedValueOnce(providerTimeoutError(provider)) - } else { - mockGetSessionCommandLogs.mockRejectedValueOnce(providerTimeoutError(provider)) - } + fixture.processMock.mockRejectedValueOnce(fixture.timeoutError()) await expect( executeInSandbox({ code: 'sleep()', language: CodeLanguage.Python, timeoutMs: 1000 }) @@ -634,11 +898,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('normalizes JavaScript code budget expiry to a typed timeout abort', async () => { - if (provider === 'e2b') { - mockE2BCommandsRun.mockRejectedValueOnce(providerTimeoutError(provider)) - } else { - mockGetSessionCommandLogs.mockRejectedValueOnce(providerTimeoutError(provider)) - } + fixture.processMock.mockRejectedValueOnce(fixture.timeoutError()) await expect( executeInSandbox({ @@ -655,11 +915,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { controller.abort(new DOMException('user', 'AbortError')) throw new Error('sandbox deleted') } - if (provider === 'e2b') { - mockE2BCommandsRun.mockImplementationOnce(rejectAfterCancellation) - } else { - mockGetSessionCommandLogs.mockImplementationOnce(rejectAfterCancellation) - } + fixture.processMock.mockImplementationOnce(rejectAfterCancellation) await expect( executeInSandbox({ @@ -672,7 +928,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('fetches url-mounted files inside the sandbox and never inlines the url', async () => { - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) await executeInSandbox({ code: 'x', @@ -683,31 +939,18 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { ], }) - const [command, options] = - provider === 'e2b' - ? mockE2BCommandsRun.mock.calls[0] - : [mockExecuteSessionCommand.mock.calls[0][1].command, undefined] + const [command] = fixture.launchedCommands() expect(command).toContain('curl') // The presigned URL must travel as an env var, never interpolated into the shell. expect(command).not.toContain('presigned') - if (provider === 'e2b') { - expect(options.envs).toMatchObject({ - URL: 'https://example/presigned?x=1', - DST: '/mnt/data/in.csv', - }) - } else { - const envFile = mockUploadFile.mock.calls[0][0].toString('utf8') - expect(envFile).toContain("URL='https://example/presigned?x=1'") - expect(envFile).toContain("DST='/mnt/data/in.csv'") - } + fixture.expectCommandEnvironment({ + URL: 'https://example/presigned?x=1', + DST: '/mnt/data/in.csv', + }) }) it('throws rather than running user code against a missing mount', async () => { - if (provider === 'e2b') { - mockE2BCommandsRun.mockRejectedValue(new Error('curl: (22) 404')) - } else { - stubShellCommand(provider, '', 'curl: (22) 404', 22) - } + fixture.stubMountFetchFailure() await expect( executeInSandbox({ @@ -719,38 +962,12 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { ).rejects.toThrow(/Failed to fetch mounted file/) }) - /** Stubs one directory listing in whichever shape the provider returns. */ - function stubOutputDirListing( - entries: Array<{ path: string; size: number; kind?: 'file' | 'dir' }> - ) { - if (provider === 'e2b') { - mockE2BFilesList.mockResolvedValueOnce( - entries.map((entry) => ({ - name: entry.path.split('/').pop(), - path: entry.path, - size: entry.size, - type: entry.kind === 'dir' ? 'dir' : 'file', - })) - ) - } else { - mockListFiles.mockResolvedValueOnce( - entries.map((entry) => ({ - name: entry.path.split('/').pop(), - path: entry.path, - size: entry.size, - isDir: entry.kind === 'dir', - mode: entry.kind === 'dir' ? 'drwxr-xr-x' : '-rw-r--r--', - })) - ) - } - } - it('bills a completed run whose harvest produced more files than it can export', async () => { // The sandbox executed and was paid for; the refusal is about what the code // wrote, so it belongs with the post-completion export failures rather than // the provider failures the policy absorbs. - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) - stubOutputDirListing( + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) + fixture.stubOutputDirListing( Array.from({ length: MAX_SANDBOX_OUTPUT_FILES + 1 }, (_, index) => ({ path: `/tmp/sim/outputs/file-${index}.txt`, size: 1, @@ -775,8 +992,8 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('creates the output directory before user code runs', async () => { - stubCodeRun(provider, `__SIM_RESULT__=${JSON.stringify('done')}`) - stubOutputDirListing([]) + fixture.stubCodeRun(`__SIM_RESULT__=${JSON.stringify('done')}`) + fixture.stubOutputDirListing([]) await executeInSandbox({ code: 'x', @@ -790,10 +1007,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { // runtime prologue instead, calling executeInSandbox directly left user // code writing into a directory that did not exist, and every write was // ENOENT. The sentinel must be written before the code file that runs. - const writeMock = provider === 'e2b' ? mockE2BFilesWrite : mockUploadFile - const writtenPaths = writeMock.mock.calls.map((call) => - provider === 'e2b' ? call[0] : call[1] - ) + const writtenPaths = fixture.writes().map((write) => write.path) const sentinelIndex = writtenPaths.findIndex((path: string) => path?.includes('/tmp/sim/outputs/.sim-keep') ) @@ -804,13 +1018,13 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('keeps the directory sentinel out of the harvest', async () => { - stubCodeRun(provider, `__SIM_RESULT__=${JSON.stringify('done')}`) - stubOutputDirListing([ + fixture.stubCodeRun(`__SIM_RESULT__=${JSON.stringify('done')}`) + fixture.stubOutputDirListing([ { path: `/tmp/sim/outputs/${SANDBOX_OUTPUT_DIR_SENTINEL}`, size: 0 }, { path: '/tmp/sim/outputs/real.txt', size: 4 }, ]) - stubOutputFileSizes(provider, 4) - stubOutputFileRead(provider, 'real') + fixture.stubOutputFileSizes(4) + fixture.stubOutputFileRead('real') const result = await executeInSandbox({ code: 'x', @@ -823,10 +1037,10 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('harvests files written to the output directory', async () => { - stubCodeRun(provider, `__SIM_RESULT__=${JSON.stringify('done')}`) - stubOutputDirListing([{ path: '/tmp/sim/outputs/report.csv', size: 5 }]) - stubOutputFileSizes(provider, 5) - stubOutputFileRead(provider, 'a,b\n1') + fixture.stubCodeRun(`__SIM_RESULT__=${JSON.stringify('done')}`) + fixture.stubOutputDirListing([{ path: '/tmp/sim/outputs/report.csv', size: 5 }]) + fixture.stubOutputFileSizes(5) + fixture.stubOutputFileRead('a,b\n1') const result = await executeInSandbox({ code: 'x', @@ -848,8 +1062,8 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('excludes directories from the harvest', async () => { - stubCodeRun(provider, `__SIM_RESULT__=${JSON.stringify('done')}`) - stubOutputDirListing([{ path: '/tmp/sim/outputs/nested', size: 0, kind: 'dir' }]) + fixture.stubCodeRun(`__SIM_RESULT__=${JSON.stringify('done')}`) + fixture.stubOutputDirListing([{ path: '/tmp/sim/outputs/nested', size: 0, kind: 'dir' }]) const result = await executeInSandbox({ code: 'x', @@ -862,11 +1076,11 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('refuses a harvest whose nesting outran the listing depth', async () => { - stubCodeRun(provider, `__SIM_RESULT__=${JSON.stringify('done')}`) + fixture.stubCodeRun(`__SIM_RESULT__=${JSON.stringify('done')}`) // A directory reported at the traversal limit still holds unlisted files. // Returning the shallow ones would drop the rest without a word. const deep = Array.from({ length: 12 }, (_, index) => `l${index + 1}`).join('/') - stubOutputDirListing([ + fixture.stubOutputDirListing([ { path: '/tmp/sim/outputs/shallow.txt', size: 4 }, { path: `/tmp/sim/outputs/${deep}`, size: 0, kind: 'dir' }, ]) @@ -882,8 +1096,8 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('refuses a harvest over the output file count rather than truncating it', async () => { - stubCodeRun(provider, `__SIM_RESULT__=${JSON.stringify('done')}`) - stubOutputDirListing( + fixture.stubCodeRun(`__SIM_RESULT__=${JSON.stringify('done')}`) + fixture.stubOutputDirListing( Array.from({ length: 21 }, (_, index) => ({ path: `/tmp/sim/outputs/file-${index}.txt`, size: 1, @@ -903,9 +1117,9 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { it('spends one file ceiling across declared and harvested outputs', async () => { // The limit is what an execution exports, not what one directory holds, so a // request that both declares and harvests cannot take 20 of each. - stubCodeRun(provider, `__SIM_RESULT__=${JSON.stringify('done')}`) - stubOutputFileSizes(provider, 1, 1) - stubOutputDirListing( + fixture.stubCodeRun(`__SIM_RESULT__=${JSON.stringify('done')}`) + fixture.stubOutputFileSizes(1, 1) + fixture.stubOutputDirListing( Array.from({ length: MAX_SANDBOX_OUTPUT_FILES - 1 }, (_, index) => ({ path: `/tmp/sim/outputs/file-${index}.txt`, size: 1, @@ -926,17 +1140,17 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { it('does not charge a declared path inside the harvest directory to the ceiling twice', async () => { // The directory holds exactly the limit and the request names one of those // files. Charging it on both sides would refuse a run exporting 20 files. - stubCodeRun(provider, `__SIM_RESULT__=${JSON.stringify('done')}`) + fixture.stubCodeRun(`__SIM_RESULT__=${JSON.stringify('done')}`) // One inspection for the declared path, then one per file actually read. - stubOutputFileSizes(provider, ...Array.from({ length: MAX_SANDBOX_OUTPUT_FILES + 1 }, () => 1)) - stubOutputDirListing( + fixture.stubOutputFileSizes(...Array.from({ length: MAX_SANDBOX_OUTPUT_FILES + 1 }, () => 1)) + fixture.stubOutputDirListing( Array.from({ length: MAX_SANDBOX_OUTPUT_FILES }, (_, index) => ({ path: `/tmp/sim/outputs/file-${index}.txt`, size: 1, })) ) for (let index = 0; index < MAX_SANDBOX_OUTPUT_FILES; index += 1) { - stubOutputFileRead(provider, 'x') + fixture.stubOutputFileRead('x') } const result = await executeInSandbox({ @@ -954,7 +1168,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('does not list the output directory when no harvest was requested', async () => { - stubCodeRun(provider, `__SIM_RESULT__=${JSON.stringify('done')}`) + fixture.stubCodeRun(`__SIM_RESULT__=${JSON.stringify('done')}`) const result = await executeInSandbox({ code: 'x', @@ -963,7 +1177,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) expect(result.collectedFiles).toBeUndefined() - expect(provider === 'e2b' ? mockE2BFilesList : mockListFiles).not.toHaveBeenCalled() + expect(fixture.listMock).not.toHaveBeenCalled() }) it('materializes private code inputs after dependencies and user files', async () => { @@ -981,7 +1195,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { SELECTED_ONLY: 'selected-value', }, }) - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) await executeInSandbox({ code: 'x', @@ -994,7 +1208,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { ], }) - const writes = capturedSandboxWrites(provider) + const writes = capturedSandboxWrites(fixture) const userWrite = writes.find((write) => write.path === '/mnt/user-input.txt') const privateWrites = writes.filter((write) => /^\/tmp\/\.sim-private-input-[A-Za-z0-9_-]+-[01]$/.test(write.path) @@ -1015,27 +1229,15 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { PRIVATE_BYTES_PATH: privateBytesWrite?.path, SELECTED_ONLY: 'selected-value', } - let executionOrder: number - if (provider === 'e2b') { - const [, runOptions] = mockE2BCommandsRun.mock.calls[0] - expect(runOptions.envs).toMatchObject(expectedEnvironment) - expect(JSON.stringify(runOptions.envs)).not.toContain(privateText) - executionOrder = mockE2BCommandsRun.mock.invocationCallOrder[0] - } else { - const environmentWrite = writes.find((write) => write.path.startsWith('/tmp/.sim-env-')) - expect(environmentWrite).toBeDefined() - const environmentFile = sandboxWriteBuffer(environmentWrite?.content).toString() - expect(environmentFile).toContain(`PRIVATE_TEXT_PATH='${privateTextWrite?.path ?? ''}'`) - expect(environmentFile).toContain(`PRIVATE_BYTES_PATH='${privateBytesWrite?.path ?? ''}'`) - expect(environmentFile).toContain("SELECTED_ONLY='selected-value'") - expect(environmentFile).not.toContain(privateText) - executionOrder = mockExecuteSessionCommand.mock.invocationCallOrder[0] - } + const { launchedAt: executionOrder } = fixture.expectCommandEnvironment( + expectedEnvironment, + privateText + ) expect(mockProvisionRuntime.mock.invocationCallOrder[0]).toBeLessThan(userWrite?.order ?? 0) expect(userWrite?.order).toBeLessThan(privateTextWrite?.order ?? 0) expect(privateBytesWrite?.order).toBeLessThan(executionOrder) - expectPrivateInputsUseSandboxTeardown(provider) - expect(provider === 'e2b' ? mockE2BKill : mockDelete).toHaveBeenCalledTimes(1) + expectPrivateInputsUseSandboxTeardown(fixture) + expect(fixture.killMock).toHaveBeenCalledTimes(1) }) it('passes private shell input paths after selected and caller environment values', async () => { @@ -1051,7 +1253,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { SELECTED_ONLY: 'selected-value', }, }) - stubShellCommand(provider, '', '', 0) + fixture.stubShellCommand('', '', 0) await executeShellInSandbox({ code: 'cat "$PRIVATE_HEREDOC_PATH"', @@ -1064,7 +1266,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { privateInputs: [{ environmentVariable: 'PRIVATE_HEREDOC_PATH', content: privateContent }], }) - const writes = capturedSandboxWrites(provider) + const writes = capturedSandboxWrites(fixture) const userWrite = writes.find((write) => write.path === '/mnt/shell-user-input.txt') const privateWrite = writes.find((write) => /^\/tmp\/\.sim-private-input-[A-Za-z0-9_-]+-0$/.test(write.path) @@ -1076,30 +1278,18 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { expect(mockProvisionRuntime.mock.invocationCallOrder[0]).toBeLessThan(userWrite?.order ?? 0) expect(userWrite?.order).toBeLessThan(privateWrite?.order ?? 0) - if (provider === 'e2b') { - const [, options] = mockE2BCommandsRun.mock.calls[0] - expect(options.envs).toMatchObject({ + const { deliveredAt, launchedAt } = fixture.expectCommandEnvironment( + { PRIVATE_HEREDOC_PATH: privateWrite?.path, SELECTED_ONLY: 'selected-value', CALLER_ONLY: 'caller-value', - }) - expect(JSON.stringify(options.envs)).not.toContain(privateContent) - expect(privateWrite?.order).toBeLessThan(mockE2BCommandsRun.mock.invocationCallOrder[0]) - } else { - const environmentWrite = writes.find((write) => write.path.startsWith('/tmp/.sim-env-')) - expect(environmentWrite).toBeDefined() - const environmentFile = sandboxWriteBuffer(environmentWrite?.content).toString() - expect(environmentFile).toContain(`PRIVATE_HEREDOC_PATH='${privateWrite?.path ?? ''}'`) - expect(environmentFile).toContain("SELECTED_ONLY='selected-value'") - expect(environmentFile).toContain("CALLER_ONLY='caller-value'") - expect(environmentFile).not.toContain(privateContent) - expect(privateWrite?.order).toBeLessThan(environmentWrite?.order ?? 0) - expect(environmentWrite?.order).toBeLessThan( - mockExecuteSessionCommand.mock.invocationCallOrder[0] - ) - } - expectPrivateInputsUseSandboxTeardown(provider) - expect(provider === 'e2b' ? mockE2BKill : mockDelete).toHaveBeenCalledTimes(1) + }, + privateContent + ) + expect(privateWrite?.order).toBeLessThan(deliveredAt) + expect(deliveredAt).toBeLessThanOrEqual(launchedAt) + expectPrivateInputsUseSandboxTeardown(fixture) + expect(fixture.killMock).toHaveBeenCalledTimes(1) }) it('tears down without running code when private input materialization is aborted', async () => { @@ -1107,11 +1297,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { const abortWrite = async () => { controller.abort(new DOMException('private input cancelled', 'AbortError')) } - if (provider === 'e2b') { - mockE2BFilesWrite.mockImplementationOnce(abortWrite) - } else { - mockUploadFile.mockImplementationOnce(abortWrite) - } + fixture.writeMock.mockImplementationOnce(abortWrite) await expect( executeInSandbox({ @@ -1123,21 +1309,15 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) ).rejects.toMatchObject({ name: 'AbortError', message: 'private input cancelled' }) - expectPrivateInputsUseSandboxTeardown(provider) + expectPrivateInputsUseSandboxTeardown(fixture) - expect( - provider === 'e2b' ? mockE2BCommandsRun : mockExecuteSessionCommand - ).not.toHaveBeenCalled() - expect(provider === 'e2b' ? mockE2BKill : mockDelete).toHaveBeenCalledTimes(1) + expect(fixture.launchMock).not.toHaveBeenCalled() + expect(fixture.killMock).toHaveBeenCalledTimes(1) }) it('tears down without running code when a private input write fails', async () => { const writeError = new Error('private input write failed') - if (provider === 'e2b') { - mockE2BFilesWrite.mockRejectedValueOnce(writeError) - } else { - mockUploadFile.mockRejectedValueOnce(writeError) - } + fixture.writeMock.mockRejectedValueOnce(writeError) await expect( executeInSandbox({ @@ -1148,19 +1328,16 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) ).rejects.toBe(writeError) - expectPrivateInputsUseSandboxTeardown(provider) + expectPrivateInputsUseSandboxTeardown(fixture) - expect( - provider === 'e2b' ? mockE2BCommandsRun : mockExecuteSessionCommand - ).not.toHaveBeenCalled() - expect(provider === 'e2b' ? mockE2BKill : mockDelete).toHaveBeenCalledTimes(1) + expect(fixture.launchMock).not.toHaveBeenCalled() + expect(fixture.killMock).toHaveBeenCalledTimes(1) }) it.each(['code', 'shell'])( 'uses one-shot sandbox teardown for failed private uploads before %s can start', async (kind) => { - const upload = provider === 'e2b' ? mockE2BFilesWrite : mockUploadFile - upload + fixture.writeMock .mockResolvedValueOnce(undefined) .mockRejectedValueOnce(new Error('Upload acknowledgement lost')) const request = { @@ -1176,11 +1353,9 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { ? executeInSandbox({ ...request, language: CodeLanguage.Python }) : executeShellInSandbox({ ...request, envs: {} }) ).rejects.toThrow('Upload acknowledgement lost') - expectPrivateInputsUseSandboxTeardown(provider) - expect(provider === 'e2b' ? mockE2BKill : mockDelete).toHaveBeenCalledTimes(1) - expect( - provider === 'e2b' ? mockE2BCommandsRun : mockExecuteSessionCommand - ).not.toHaveBeenCalled() + expectPrivateInputsUseSandboxTeardown(fixture) + expect(fixture.killMock).toHaveBeenCalledTimes(1) + expect(fixture.launchMock).not.toHaveBeenCalled() } ) @@ -1188,32 +1363,23 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { 'preserves the one-shot %s environment when collecting exported files', async (kind) => { const outputSandboxDir = '/tmp/sim/outputs/call-specific' - if (kind === 'code') stubCodeRun(provider, `${SIM_RESULT_PREFIX}true`) - else stubShellCommand(provider, '', '', 0) - stubOutputDirListing([]) + if (kind === 'code') fixture.stubCodeRun(`${SIM_RESULT_PREFIX}true`) + else fixture.stubShellCommand('', '', 0) + fixture.stubOutputDirListing([]) const request = { code: 'export', outputSandboxDir, timeoutMs: 10_000 } if (kind === 'code') await executeInSandbox({ ...request, language: CodeLanguage.Python }) else await executeShellInSandbox({ ...request, envs: { SIM_OUTPUT_DIR: 'caller-override' } }) - if (provider === 'e2b') { - expect(mockE2BCommandsRun.mock.calls[0][1].envs?.SIM_OUTPUT_DIR).toBe( - kind === 'shell' ? 'caller-override' : undefined - ) + if (kind === 'shell') { + fixture.expectCommandEnvironment({ SIM_OUTPUT_DIR: 'caller-override' }) } else { - const environmentWrite = capturedSandboxWrites(provider).find(({ path }) => - path.startsWith('/tmp/.sim-env-') - ) - const environment = environmentWrite - ? sandboxWriteBuffer(environmentWrite.content).toString() - : '' - if (kind === 'shell') expect(environment).toContain("SIM_OUTPUT_DIR='caller-override'") - else expect(environment).not.toContain('SIM_OUTPUT_DIR=') + fixture.expectCommandEnvironmentLacks('SIM_OUTPUT_DIR') } } ) it('treats a non-JSON shell marker as a plain string, not corruption', async () => { const stdout = `${SIM_RESULT_PREFIX}PLAIN_STATUS` - stubShellCommand(provider, stdout, '', 0) + fixture.stubShellCommand(stdout, '', 0) const res = await executeShellInSandbox({ code: 'echo hi', envs: {}, timeoutMs: 1000 }) @@ -1223,7 +1389,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { it('returns ordinary successful shell output through stdout', async () => { const stdout = 'Client Version: v1.36.3\nKustomize Version: v5.7.1' - stubShellCommand(provider, stdout, '', 0) + fixture.stubShellCommand(stdout, '', 0) const res = await executeShellInSandbox({ code: 'kubectl version --client', @@ -1241,7 +1407,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { * E2B populates stderr. Daytona merges both streams into stdout, so failures * must fall back to stdout instead of displaying only a generic exit code. */ - stubShellCommand(provider, provider === 'daytona' ? 'boom detail' : '', 'boom detail', 3) + fixture.stubShellCommand(fixture.mergesStderrIntoStdout ? 'boom detail' : '', 'boom detail', 3) const res = await executeShellInSandbox({ code: 'false', @@ -1263,7 +1429,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { it("leads a failed command's error with its exit code and the signal it stands for", async () => { const warning = 'Warning: You are sending unauthenticated requests to the HF Hub.' - stubShellCommand(provider, provider === 'daytona' ? warning : '', warning, 137) + fixture.stubShellCommand(fixture.mergesStderrIntoStdout ? warning : '', warning, 137) const res = await executeShellInSandbox({ code: 'python train.py', envs: {}, timeoutMs: 1000 }) @@ -1275,16 +1441,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { it('terminates shell execution when streamed process output exceeds the byte budget', async () => { const oversized = 'x'.repeat(MAX_SANDBOX_PROCESS_OUTPUT_BYTES + 1) - if (provider === 'e2b') { - mockE2BCommandsRun.mockImplementationOnce(async (_command, options) => { - options.onStdout(oversized) - }) - } else { - mockGetSessionCommandLogs.mockImplementationOnce(async (_sessionId, _commandId, onStdout) => { - emitDaytonaStreamReady(onStdout) - onStdout(oversized) - }) - } + fixture.stubStreamedStdoutOnce(oversized) await expect( executeShellInSandbox({ code: 'echo forever', timeoutMs: 1000 }) @@ -1293,15 +1450,11 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { outputKind: 'process', limitBytes: MAX_SANDBOX_PROCESS_OUTPUT_BYTES, }) - expect(provider === 'e2b' ? mockE2BKill : mockDelete).toHaveBeenCalledTimes(1) + expect(fixture.killMock).toHaveBeenCalledTimes(1) }) it('normalizes shell command budget expiry to a typed timeout abort', async () => { - if (provider === 'e2b') { - mockE2BCommandsRun.mockRejectedValueOnce(providerTimeoutError(provider)) - } else { - mockGetSessionCommandLogs.mockRejectedValueOnce(providerTimeoutError(provider)) - } + fixture.processMock.mockRejectedValueOnce(fixture.timeoutError()) await expect( executeShellInSandbox({ code: 'sleep infinity', timeoutMs: 1000 }) @@ -1309,7 +1462,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('preserves a user process exit code 124 as an ordinary failure', async () => { - stubShellCommand(provider, 'user selected exit 124', '', 124) + fixture.stubShellCommand('user selected exit 124', '', 124) const result = await executeShellInSandbox({ code: 'exit 124', @@ -1321,7 +1474,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('preserves code-runner exit 124 as an ordinary execution error', async () => { - stubShellCommand(provider, '', 'IntentionalError: user exit 124', 124) + fixture.stubShellCommand('', 'IntentionalError: user exit 124', 124) const result = await executeInSandbox({ code: 'raise SystemExit(124)', @@ -1335,17 +1488,9 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { it('classifies an abort observed after a shell command instead of returning a provider error', async () => { const controller = new AbortController() - if (provider === 'e2b') { - mockE2BCommandsRun.mockImplementationOnce(async () => { - controller.abort(new DOMException('user', 'AbortError')) - throw providerTimeoutError(provider) - }) - } else { - mockGetSessionCommandLogs.mockImplementationOnce(async () => { - controller.abort(new DOMException('user', 'AbortError')) - }) - mockGetSessionCommand.mockResolvedValueOnce({ exitCode: 124 }) - } + fixture.stubTimedOutProcessAfterOnce(() => { + controller.abort(new DOMException('user', 'AbortError')) + }) await expect( executeShellInSandbox({ code: 'sleep 10', timeoutMs: 10_000, signal: controller.signal }) @@ -1353,9 +1498,9 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('exports binary output files as base64', async () => { - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) - stubOutputFileSizes(provider, 6, 6) - stubOutputFileRead(provider, 'BASE64') + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) + fixture.stubOutputFileSizes(6, 6) + fixture.stubOutputFileRead('BASE64') const res = await executeInSandbox({ code: 'x', @@ -1369,8 +1514,8 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('rejects an oversized output before reading provider file bytes', async () => { - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) - stubOutputFileSizes(provider, MAX_SANDBOX_OUTPUT_BYTES + 1) + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) + fixture.stubOutputFileSizes(MAX_SANDBOX_OUTPUT_BYTES + 1) const error = await executeInSandbox({ code: 'x', @@ -1392,13 +1537,13 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { raw: expect.any(Number), }) - expect(provider === 'e2b' ? mockE2BFilesRead : mockDownloadFileStream).not.toHaveBeenCalled() + expect(fixture.readMock).not.toHaveBeenCalled() }) it('rejects cumulative output size before reading any provider file bytes', async () => { - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) const fileSize = MAX_SANDBOX_OUTPUT_BYTES / 2 + 1 - stubOutputFileSizes(provider, fileSize, fileSize) + fixture.stubOutputFileSizes(fileSize, fileSize) await expect( executeInSandbox({ @@ -1413,13 +1558,13 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { limitBytes: MAX_SANDBOX_OUTPUT_BYTES, }) - expect(provider === 'e2b' ? mockE2BFilesRead : mockDownloadFileStream).not.toHaveBeenCalled() + expect(fixture.readMock).not.toHaveBeenCalled() }) it('enforces the file limit while reading when a file grows after inspection', async () => { - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) - stubOutputFileSizes(provider, 1, 1) - stubOutputFileRead(provider, Buffer.alloc(MAX_SANDBOX_OUTPUT_BYTES + 1, 97)) + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) + fixture.stubOutputFileSizes(1, 1) + fixture.stubOutputFileRead(Buffer.alloc(MAX_SANDBOX_OUTPUT_BYTES + 1, 97)) await expect( executeInSandbox({ @@ -1436,12 +1581,8 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('rejects symlinks and other non-regular output paths', async () => { - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) - if (provider === 'e2b') { - mockE2BFilesGetInfo.mockResolvedValueOnce({ size: 1, type: 'symlink' }) - } else { - mockGetFileDetails.mockResolvedValueOnce({ size: 1, isDir: false, mode: 'prw-r--r--' }) - } + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) + fixture.stubNonRegularOutputFile() const error = await executeInSandbox({ code: 'x', @@ -1458,19 +1599,17 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { total: expect.any(Number), raw: expect.any(Number), }) - expect(provider === 'e2b' ? mockE2BFilesRead : mockDownloadFileStream).not.toHaveBeenCalled() + expect(fixture.readMock).not.toHaveBeenCalled() }) it.each(['oversized', 'non-regular'] as const)( 'retains metered shell cost for a completed execution with %s output', async (failure) => { - stubShellCommand(provider, '', '', 0) + fixture.stubShellCommand('', '', 0) if (failure === 'oversized') { - stubOutputFileSizes(provider, MAX_SANDBOX_OUTPUT_BYTES + 1) - } else if (provider === 'e2b') { - mockE2BFilesGetInfo.mockResolvedValueOnce({ size: 1, type: 'symlink' }) + fixture.stubOutputFileSizes(MAX_SANDBOX_OUTPUT_BYTES + 1) } else { - mockGetFileDetails.mockResolvedValueOnce({ size: 1, isDir: false, mode: 'prw-r--r--' }) + fixture.stubNonRegularOutputFile() } const error = await executeShellInSandbox({ @@ -1495,14 +1634,10 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { ) it('does not attach cost to a generic provider failure during output collection', async () => { - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) - stubOutputFileSizes(provider, 1, 1) + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) + fixture.stubOutputFileSizes(1, 1) const failure = new Error('provider file read failed') - if (provider === 'e2b') { - mockE2BFilesRead.mockRejectedValueOnce(failure) - } else { - mockDownloadFileStream.mockRejectedValueOnce(failure) - } + fixture.readMock.mockRejectedValueOnce(failure) const error = await executeInSandbox({ code: 'x', @@ -1517,13 +1652,9 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { }) it('does not attach cost to a generic provider failure during output inspection', async () => { - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) const failure = new Error('provider file metadata failed') - if (provider === 'e2b') { - mockE2BFilesGetInfo.mockRejectedValueOnce(failure) - } else { - mockGetFileDetails.mockRejectedValueOnce(failure) - } + fixture.inspectMock.mockRejectedValueOnce(failure) const error = await executeInSandbox({ code: 'x', @@ -1539,9 +1670,9 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { it('does not return code results when cancellation arrives during output collection', async () => { const controller = new AbortController() - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) - stubOutputFileSizes(provider, 6, 6) - stubOutputFileRead(provider, 'report', () => { + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) + fixture.stubOutputFileSizes(6, 6) + fixture.stubOutputFileRead('report', () => { controller.abort(new DOMException('user', 'AbortError')) }) @@ -1558,9 +1689,9 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { it('does not return shell results when cancellation arrives during output collection', async () => { const controller = new AbortController() - stubShellCommand(provider, '', '', 0) - stubOutputFileSizes(provider, 6, 6) - stubOutputFileRead(provider, 'report', () => { + fixture.stubShellCommand('', '', 0) + fixture.stubOutputFileSizes(6, 6) + fixture.stubOutputFileRead('report', () => { controller.abort(new DOMException('user', 'AbortError')) }) @@ -1579,53 +1710,21 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { const stalledCreate = new Promise((resolve) => { resolveCreate = resolve }) - if (provider === 'e2b') mockE2BCreate.mockReturnValueOnce(stalledCreate) - else mockDaytonaCreate.mockReturnValueOnce(stalledCreate) + fixture.createMock.mockReturnValueOnce(stalledCreate) await expect( executeInSandbox({ code: 'x', language: CodeLanguage.Python, timeoutMs: 25 }) ).rejects.toMatchObject({ name: 'AbortError', message: 'timeout' }) - resolveCreate( - provider === 'e2b' - ? { - sandboxId: 'late-sandbox', - commands: { run: mockE2BCommandsRun }, - files: { - getInfo: mockE2BFilesGetInfo, - read: mockE2BFilesRead, - remove: mockE2BFilesRemove, - write: mockE2BFilesWrite, - }, - kill: mockE2BKill, - } - : { - id: 'late-sandbox', - process: { - createSession: mockCreateSession, - executeSessionCommand: mockExecuteSessionCommand, - getSessionCommandLogs: mockGetSessionCommandLogs, - getSessionCommand: mockGetSessionCommand, - deleteSession: mockDeleteSession, - }, - fs: { - deleteFile: mockDeleteFile, - uploadFile: mockUploadFile, - downloadFileStream: mockDownloadFileStream, - getFileDetails: mockGetFileDetails, - }, - delete: mockDelete, - } - ) + resolveCreate(fixture.lateSandbox()) await vi.waitFor(() => { - expect(provider === 'e2b' ? mockE2BKill : mockDelete).toHaveBeenCalledTimes(1) + expect(fixture.killMock).toHaveBeenCalledTimes(1) }) }) it('enforces the wall-clock budget while materializing mounted files', async () => { const stalledWrite = () => new Promise(() => {}) - if (provider === 'e2b') mockE2BFilesWrite.mockImplementationOnce(stalledWrite) - else mockUploadFile.mockImplementationOnce(stalledWrite) + fixture.writeMock.mockImplementationOnce(stalledWrite) await expect( executeInSandbox({ @@ -1635,18 +1734,17 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { sandboxFiles: [{ path: '/mnt/input.txt', content: 'input' }], }) ).rejects.toMatchObject({ name: 'AbortError', message: 'timeout' }) - expect(provider === 'e2b' ? mockE2BKill : mockDelete).toHaveBeenCalledTimes(1) + expect(fixture.killMock).toHaveBeenCalledTimes(1) }) it('enforces the wall-clock budget while writing provider runtime files', async () => { const stalledWrite = () => new Promise(() => {}) - if (provider === 'e2b') mockE2BFilesWrite.mockImplementationOnce(stalledWrite) - else mockUploadFile.mockImplementationOnce(stalledWrite) + fixture.writeMock.mockImplementationOnce(stalledWrite) await expect( executeInSandbox({ code: 'x', language: CodeLanguage.Python, timeoutMs: 25 }) ).rejects.toMatchObject({ name: 'AbortError', message: 'timeout' }) - expect(provider === 'e2b' ? mockE2BKill : mockDelete).toHaveBeenCalledTimes(1) + expect(fixture.killMock).toHaveBeenCalledTimes(1) }) it('enforces the wall-clock budget while provisioning dependencies', async () => { @@ -1662,14 +1760,13 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { await expect( executeInSandbox({ code: 'x', language: CodeLanguage.Python, timeoutMs: 25 }) ).rejects.toMatchObject({ name: 'AbortError', message: 'timeout' }) - expect(provider === 'e2b' ? mockE2BKill : mockDelete).toHaveBeenCalledTimes(1) + expect(fixture.killMock).toHaveBeenCalledTimes(1) }) it('enforces the wall-clock budget while collecting output files', async () => { - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) const stalledInspection = () => new Promise(() => {}) - if (provider === 'e2b') mockE2BFilesGetInfo.mockImplementationOnce(stalledInspection) - else mockGetFileDetails.mockImplementationOnce(stalledInspection) + fixture.inspectMock.mockImplementationOnce(stalledInspection) await expect( executeInSandbox({ @@ -1679,30 +1776,22 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { outputSandboxPath: '/out/report.txt', }) ).rejects.toMatchObject({ name: 'AbortError', message: 'timeout' }) - expect(provider === 'e2b' ? mockE2BKill : mockDelete).toHaveBeenCalledTimes(1) + expect(fixture.killMock).toHaveBeenCalledTimes(1) }) it('always kills the sandbox, even when execution throws', async () => { - if (provider === 'e2b') { - mockE2BCommandsRun.mockRejectedValue(new Error('kaboom')) - } else { - mockGetSessionCommandLogs.mockRejectedValue(new Error('kaboom')) - } + fixture.processMock.mockRejectedValue(new Error('kaboom')) await expect( executeInSandbox({ code: 'x', language: CodeLanguage.Python, timeoutMs: 1000 }) ).rejects.toThrow('kaboom') - expect(provider === 'e2b' ? mockE2BKill : mockDelete).toHaveBeenCalledTimes(1) + expect(fixture.killMock).toHaveBeenCalledTimes(1) }) it('records a bounded metric when best-effort teardown fails', async () => { - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) - if (provider === 'e2b') { - mockE2BKill.mockRejectedValueOnce(new Error('kill failed')) - } else { - mockDelete.mockRejectedValueOnce(new Error('delete failed')) - } + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) + fixture.killMock.mockRejectedValueOnce(new Error('teardown failed')) await executeInSandbox({ code: 'x', language: CodeLanguage.Python, timeoutMs: 1000 }) @@ -1710,7 +1799,7 @@ describe.each(PROVIDERS)('sandbox conformance [%s]', (provider) => { provider, reason: 'cleanup', }) - expect(provider === 'e2b' ? mockE2BKill : mockDelete).toHaveBeenCalledTimes(2) + expect(fixture.killMock).toHaveBeenCalledTimes(2) }) }) @@ -2020,7 +2109,8 @@ describe('provider stream recovery', () => { describe('custom dependency sets', () => { it.each(PROVIDERS)('honors imageRef for code executions [%s]', async (provider) => { useProvider(provider) - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) + const fixture = CONFORMANCE_PROVIDERS[provider] + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) mockResolveSandbox.mockResolvedValue({ id: 'sbx-1', name: 'etl', @@ -2038,18 +2128,13 @@ describe('custom dependency sets', () => { sandboxId: 'sbx-1', }) - if (provider === 'e2b') { - expect(mockE2BCreate).toHaveBeenCalledWith('sim-sbx-abc', expect.anything()) - } else { - expect(mockDaytonaCreate).toHaveBeenCalledWith( - expect.objectContaining({ snapshot: 'sim-sbx-abc' }) - ) - } + fixture.expectCreatedWithImage('sim-sbx-abc') }) it.each(PROVIDERS)('refuses to let a sandbox displace the doc image [%s]', async (provider) => { useProvider(provider) - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) + const fixture = CONFORMANCE_PROVIDERS[provider] + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) // Even if resolution somehow yields a ref, the provider gates on the kind. mockResolveSandbox.mockResolvedValue({ id: 'sbx-1', @@ -2069,20 +2154,15 @@ describe('custom dependency sets', () => { sandboxId: 'sbx-1', }) - if (provider === 'e2b') { - expect(mockE2BCreate).toHaveBeenCalledWith('mothership-docs', expect.anything()) - } else { - expect(mockDaytonaCreate).toHaveBeenCalledWith( - expect.objectContaining({ snapshot: 'mothership-docs:v1' }) - ) - } + fixture.expectCreatedWithImage(fixture.images.doc) }) it.each(PROVIDERS)( 'spends the runtime install out of the caller budget, not on top of it [%s]', async (provider) => { useProvider(provider) - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) + const fixture = CONFORMANCE_PROVIDERS[provider] + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) mockResolveSandbox.mockResolvedValue({ id: 'sbx-1', name: 'etl', @@ -2118,7 +2198,8 @@ describe('custom dependency sets', () => { 'caps the install at its own ceiling when the budget is generous [%s]', async (provider) => { useProvider(provider) - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) + const fixture = CONFORMANCE_PROVIDERS[provider] + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) mockResolveSandbox.mockResolvedValue({ id: 'sbx-1', name: 'etl', @@ -2145,20 +2226,12 @@ describe('custom dependency sets', () => { it.each(PROVIDERS)('uses the env template when nothing is selected [%s]', async (provider) => { useProvider(provider) - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) + const fixture = CONFORMANCE_PROVIDERS[provider] + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) await executeInSandbox({ code: 'x', language: CodeLanguage.Python, timeoutMs: 1000 }) - if (provider === 'e2b') { - expect(mockE2BCreate).toHaveBeenCalledWith( - 'sim-function:f47ac10b-58cc-4372-a567-0e02b2c3d479', - expect.anything() - ) - } else { - expect(mockDaytonaCreate).toHaveBeenCalledWith( - expect.objectContaining({ snapshot: '7d9d12d6-5f2a-44df-9cc2-a20203f3813b' }) - ) - } + fixture.expectCreatedWithImage(fixture.images.function) // No selection means no install step, on either strategy. Code itself now // deliberately runs through the bounded process stream. expect(mockProvisionRuntime).not.toHaveBeenCalled() @@ -2169,7 +2242,8 @@ describe('custom dependency sets', () => { 'uses the Mothership image for trusted code and shell executions [%s]', async (provider) => { useProvider(provider) - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) + const fixture = CONFORMANCE_PROVIDERS[provider] + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) await executeInSandbox({ code: 'x', @@ -2183,19 +2257,8 @@ describe('custom dependency sets', () => { sandboxKind: 'mothership', }) - if (provider === 'e2b') { - expect(mockE2BCreate).toHaveBeenNthCalledWith(1, 'mothership-shell', expect.anything()) - expect(mockE2BCreate).toHaveBeenNthCalledWith(2, 'mothership-shell', expect.anything()) - } else { - expect(mockDaytonaCreate).toHaveBeenNthCalledWith( - 1, - expect.objectContaining({ snapshot: 'mothership-shell:v1' }) - ) - expect(mockDaytonaCreate).toHaveBeenNthCalledWith( - 2, - expect.objectContaining({ snapshot: 'mothership-shell:v1' }) - ) - } + fixture.expectCreatedWithImage(fixture.images.mothership, 1) + fixture.expectCreatedWithImage(fixture.images.mothership, 2) expect(mockResolveSandbox).toHaveBeenNthCalledWith( 1, expect.objectContaining({ kind: 'mothership' }) @@ -2211,17 +2274,12 @@ describe('custom dependency sets', () => { 'does not let a workspace image displace the Mothership image [%s]', async (provider) => { useProvider(provider) + const fixture = CONFORMANCE_PROVIDERS[provider] const sandbox = await resolveProvider().create('mothership', { imageRef: 'workspace-controlled-image', }) - if (provider === 'e2b') { - expect(mockE2BCreate).toHaveBeenCalledWith('mothership-shell', expect.anything()) - } else { - expect(mockDaytonaCreate).toHaveBeenCalledWith( - expect.objectContaining({ snapshot: 'mothership-shell:v1' }) - ) - } + fixture.expectCreatedWithImage(fixture.images.mothership) await sandbox.kill() } ) @@ -2380,7 +2438,8 @@ describe('custom dependency sets', () => { 'propagates the execution budget to sandbox lifetime and code timeout [%s]', async (provider) => { useProvider(provider) - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) + const fixture = CONFORMANCE_PROVIDERS[provider] + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) await executeInSandbox({ code: 'x', @@ -2388,26 +2447,15 @@ describe('custom dependency sets', () => { timeoutMs: 46_000, }) - if (provider === 'e2b') { - const sandboxTimeoutMs = mockE2BCreate.mock.calls[0][1].timeoutMs - expect(sandboxTimeoutMs).toBeGreaterThan(45_000) - expect(sandboxTimeoutMs).toBeLessThanOrEqual(46_000) - const commandTimeoutMs = mockE2BCommandsRun.mock.calls.at(-1)?.[1].timeoutMs - expect(commandTimeoutMs).toBeGreaterThan(45_000) - expect(commandTimeoutMs).toBeLessThanOrEqual(46_000) - } else { - expect(mockDaytonaCreate.mock.calls[0][0]).toMatchObject({ - ephemeral: true, - ttlMinutes: 1, - }) - expect(mockExecuteSessionCommand.mock.calls.at(-1)?.[2]).toBe(46) - } + fixture.expectLifetimeBudget(46_000) + fixture.expectCommandBudget(46_000, 45_000) } ) it.each(PROVIDERS)('does not raise a sub-15s caller budget [%s]', async (provider) => { useProvider(provider) - stubCodeRun(provider, `${SIM_RESULT_PREFIX}null`) + const fixture = CONFORMANCE_PROVIDERS[provider] + fixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) await executeInSandbox({ code: 'x', @@ -2415,20 +2463,14 @@ describe('custom dependency sets', () => { timeoutMs: 1000, }) - if (provider === 'e2b') { - const commandTimeoutMs = mockE2BCommandsRun.mock.calls.at(-1)?.[1].timeoutMs - expect(commandTimeoutMs).toBeGreaterThan(0) - expect(commandTimeoutMs).toBeLessThanOrEqual(1000) - } else { - expect(mockExecuteSessionCommand.mock.calls.at(-1)?.[2]).toBe(1) - } + fixture.expectCommandBudget(1000, 0) }) }) describe('provider selection', () => { it('routes by SANDBOX_PROVIDER, defaulting to E2B when unset', async () => { - stubCodeRun('e2b', `${SIM_RESULT_PREFIX}null`) - stubCodeRun('daytona', `${SIM_RESULT_PREFIX}null`) + e2bFixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) + daytonaFixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) mockEnv.SANDBOX_PROVIDER = undefined await executeInSandbox({ code: 'x', language: CodeLanguage.Python, timeoutMs: 1000 }) @@ -2481,7 +2523,7 @@ describe('provider selection', () => { it('resolves SANDBOX_PROVIDER case-insensitively', async () => { mockEnv.SANDBOX_PROVIDER = 'Daytona' - stubCodeRun('daytona', `${SIM_RESULT_PREFIX}null`) + daytonaFixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) await executeInSandbox({ code: 'x', language: CodeLanguage.Python, timeoutMs: 1000 }) @@ -2491,7 +2533,7 @@ describe('provider selection', () => { it('binds language at create time so JS never runs through the Python toolbox', async () => { useProvider('daytona') - stubShellCommand('daytona', `${SIM_RESULT_PREFIX}null`, '', 0) + daytonaFixture.stubShellCommand(`${SIM_RESULT_PREFIX}null`, '', 0) await executeInSandbox({ code: 'x', language: CodeLanguage.JavaScript, timeoutMs: 1000 }) @@ -2507,7 +2549,8 @@ describe('provider selection', () => { it.each(PROVIDERS)('runs the trusted JavaScript preload on %s', async (provider) => { useProvider(provider) - stubShellCommand(provider, `${SIM_RESULT_PREFIX}null`, '', 0) + const fixture = CONFORMANCE_PROVIDERS[provider] + fixture.stubShellCommand(`${SIM_RESULT_PREFIX}null`, '', 0) await executeInSandbox({ code: 'return null', @@ -2516,43 +2559,12 @@ describe('provider selection', () => { runtimeBindings: [{ name: '__opaque_intrinsic', kind: 'javascript-runtime' }], }) - const preloadContent = - provider === 'e2b' - ? mockE2BFilesWrite.mock.calls.find(([path]) => String(path).endsWith('.cjs'))?.[1] - : mockUploadFile.mock.calls.find(([, path]) => String(path).endsWith('.cjs'))?.[0] + const preloadContent = fixture.writes().find(({ path }) => path.endsWith('.cjs'))?.content expect(sandboxWriteBuffer(preloadContent).toString('utf8')).toContain( 'objectConstructor.defineProperty(globalThis, "__opaque_intrinsic"' ) - if (provider === 'e2b') { - expect(mockE2BCommandsRun.mock.calls.at(-1)?.[1].envs.SIM_PRELOAD_PATH).toMatch( - /^\.\/\.sim-function-[A-Za-z0-9_-]+\.cjs$/ - ) - } else { - const uploadedFunctionPaths = mockUploadFile.mock.calls - .map(([, path]) => String(path)) - .filter((path) => path.includes('.sim-function-')) - expect(uploadedFunctionPaths).toHaveLength(3) - expect(uploadedFunctionPaths).toEqual( - expect.arrayContaining([ - expect.stringMatching(/^\.sim-function-[A-Za-z0-9_-]+\.mjs$/), - expect.stringMatching(/^\.sim-function-[A-Za-z0-9_-]+\.cjs$/), - expect.stringMatching(/^\.sim-function-[A-Za-z0-9_-]+\.sh$/), - ]) - ) - const environmentWrite = mockUploadFile.mock.calls.find(([, path]) => - String(path).startsWith('/tmp/.sim-env-') - )?.[0] - const environment = sandboxWriteBuffer(environmentWrite).toString('utf8') - expect(environment).toMatch(/SIM_CODE_PATH='\.sim-function-[A-Za-z0-9_-]+\.mjs'/) - expect(environment).toMatch(/SIM_PRELOAD_PATH='\.\/\.sim-function-[A-Za-z0-9_-]+\.cjs'/) - const launcher = mockUploadFile.mock.calls.find(([, path]) => - String(path).endsWith('.sh') - )?.[0] - expect(sandboxWriteBuffer(launcher).toString('utf8')).toContain( - 'ln -s "$SIM_NODE_MODULES_PATH" node_modules' - ) - } + fixture.expectJavaScriptPreloadLaunch() }) it('hard-stops Daytona JavaScript output through the streamed module runner', async () => { @@ -2754,7 +2766,7 @@ describe('Pi sandbox lifetime', () => { it('propagates short-lived execution budgets to E2B', async () => { useProvider('e2b') - stubCodeRun('e2b', `${SIM_RESULT_PREFIX}null`) + e2bFixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) await executeInSandbox({ code: 'x', language: CodeLanguage.Python, timeoutMs: 1000 }) @@ -2765,7 +2777,7 @@ describe('Pi sandbox lifetime', () => { it('caps a long workflow call to E2B continuous lifetime without rejecting it', async () => { useProvider('e2b') - stubCodeRun('e2b', `${SIM_RESULT_PREFIX}null`) + e2bFixture.stubCodeRun(`${SIM_RESULT_PREFIX}null`) await executeInSandbox({ code: 'x', @@ -2791,7 +2803,7 @@ describe('Pi sandbox lifetime', () => { it('does not call an early timeout the 24-hour provider limit', async () => { useProvider('e2b') - mockE2BCommandsRun.mockRejectedValueOnce(providerTimeoutError('e2b')) + mockE2BCommandsRun.mockRejectedValueOnce(e2bFixture.timeoutError()) await expect( executeInSandbox({ @@ -2806,7 +2818,7 @@ describe('Pi sandbox lifetime', () => { it('does not call cancellation near 24 hours a provider-limit event', async () => { useProvider('e2b') const controller = new AbortController() - const timeoutError = providerTimeoutError('e2b') + const timeoutError = e2bFixture.timeoutError() mockE2BCommandsRun.mockImplementationOnce(async () => { controller.abort(new DOMException('user', 'AbortError')) throw timeoutError From c0c827de70084616f959d713900780f78f6605c9 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 13:35:15 -0600 Subject: [PATCH 03/78] improvement(sandbox): pin provider lists, test the kind gate, and document Pi visibility - Decision-table test for isSandboxKindAvailable covering E2B on/off per kind, Daytona with and without its Pi snapshot, and Daytona with a leftover E2B_ENABLED. - deployment-config fails type-check when SANDBOX_PROVIDER_IDS and the sandbox capability's providers diverge. - CLI recipes default to an explicit verified provider list again. - Docs: Pi cloud modes appear when the selected provider is enabled with its Pi image; E2B_ENABLED alone still suffices on E2B. - Session recovery TSDoc notes it uses the selected provider; conformance Daytona budgets assert literal values; minor TSDoc and status nits. --- .../docs/platform/self-hosting/sandboxes.mdx | 2 +- .../docs/platform/self-hosting/security.mdx | 2 +- .../docs/content/docs/workflows/blocks/pi.mdx | 2 +- .../lib/core/config/env-capabilities.test.ts | 73 +++++++++++++++++++ apps/sim/lib/core/config/env-flags.ts | 4 +- .../remote-sandbox/cli-tools.server.ts | 8 +- .../remote-sandbox/conformance.test.ts | 20 ++++- .../request/tools/sandbox-recovery.ts | 7 +- .../deployment-config/src/env-capabilities.ts | 17 ++++- packages/sim-setup/src/capability-status.ts | 5 +- 10 files changed, 124 insertions(+), 16 deletions(-) diff --git a/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx b/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx index 2fca0deee9a..861d55b1e73 100644 --- a/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx +++ b/apps/docs/content/docs/platform/self-hosting/sandboxes.mdx @@ -134,7 +134,7 @@ MOTHERSHIP_E2B_TEMPLATE_ID= DAYTONA_SHELL_SNAPSHOT_ID= ``` -These values do not replace `E2B_FUNCTION_TEMPLATE_ID` or `DAYTONA_FUNCTION_SNAPSHOT_ID`. Shell, Function, document, and Pi images have separate package contracts and release cadences. Pi also needs `E2B_PI_TEMPLATE_ID` or `DAYTONA_PI_SNAPSHOT_ID`; `E2B_ENABLED` reveals the Pi cloud modes but does not supply that image. +These values do not replace `E2B_FUNCTION_TEMPLATE_ID` or `DAYTONA_FUNCTION_SNAPSHOT_ID`. Shell, Function, document, and Pi images have separate package contracts and release cadences. Pi also needs `E2B_PI_TEMPLATE_ID` or `DAYTONA_PI_SNAPSHOT_ID`. The Pi cloud modes appear when the selected provider is enabled and has its Pi image configured: on Daytona that means `DAYTONA_API_KEY` and `DAYTONA_PI_SNAPSHOT_ID`; on E2B, `E2B_ENABLED` alone still reveals them, but runs fail closed until `E2B_PI_TEMPLATE_ID` is set. ## Related docs diff --git a/apps/docs/content/docs/platform/self-hosting/security.mdx b/apps/docs/content/docs/platform/self-hosting/security.mdx index 0babcb06fb5..8aa76cbe1ab 100644 --- a/apps/docs/content/docs/platform/self-hosting/security.mdx +++ b/apps/docs/content/docs/platform/self-hosting/security.mdx @@ -195,7 +195,7 @@ no remote provider is configured. Without valid provider credentials and the required Function image, code that needs a remote sandbox fails with a configuration error. Verify readiness before enabling its browser controls. -The Function block's Sandbox selector, Shell, and **Settings → Sandboxes** follow the server's own readiness check; no browser variable is involved. The E2B-backed Pi block modes appear when `E2B_ENABLED` is set. Revealing them is not enough to make them run — Pi executes on its own image, pinned with `E2B_PI_TEMPLATE_ID` or `DAYTONA_PI_SNAPSHOT_ID`, and fails closed without it. See [Sandboxes](/platform/self-hosting/sandboxes) for the base-image build and promotion procedure. +The Function block's Sandbox selector, Shell, and **Settings → Sandboxes** follow the server's own readiness check; no browser variable is involved. The Pi block's cloud modes appear when the selected sandbox provider is enabled and has its Pi image configured (`DAYTONA_PI_SNAPSHOT_ID` on Daytona). On E2B, `E2B_ENABLED` alone still reveals them, but revealing them is not enough to make them run — Pi executes on its own image, pinned with `E2B_PI_TEMPLATE_ID`, and fails closed without it. See [Sandboxes](/platform/self-hosting/sandboxes) for the base-image build and promotion procedure. With the default local sandbox, treat everyone who can author a workflow as someone running code in your app container's security context. If your Sim instance is open to a wide or partly-trusted audience, use a remote sandbox provider and enable the NetworkPolicy egress restrictions. diff --git a/apps/docs/content/docs/workflows/blocks/pi.mdx b/apps/docs/content/docs/workflows/blocks/pi.mdx index c7301eb3876..a0b7d415efe 100644 --- a/apps/docs/content/docs/workflows/blocks/pi.mdx +++ b/apps/docs/content/docs/workflows/blocks/pi.mdx @@ -232,7 +232,7 @@ Enable the Pi sandbox as below and supply a provider BYOK key. For private repos Create PR runs in a sandbox image with the Pi CLI, Git, Node.js, and Bun baked in. Repository dependencies are not preinstalled; Pi can run `bun install` when a repository needs them. -1. **Enable sandbox execution.** On self-hosted Sim, set `E2B_ENABLED=true`, `E2B_API_KEY`, and `E2B_PI_TEMPLATE_ID` (the Pi template id). Build the template with `bun run apps/sim/scripts/build-pi-e2b-template.ts`. Plan, Create PR, Update PR, and Review Code stay hidden until `E2B_ENABLED` is set. +1. **Enable sandbox execution.** On self-hosted Sim, set `E2B_ENABLED=true`, `E2B_API_KEY`, and `E2B_PI_TEMPLATE_ID` (the Pi template id). Build the template with `bun run apps/sim/scripts/build-pi-e2b-template.ts`. Plan, Create PR, Update PR, and Review Code stay hidden until the selected sandbox provider is enabled with its Pi image configured: on E2B, `E2B_ENABLED` is enough to show them; on Daytona (`SANDBOX_PROVIDER=daytona`), set `DAYTONA_API_KEY` and `DAYTONA_PI_SNAPSHOT_ID`. The repository template requests **4 vCPU and 8 GiB of RAM**. Confirm your account’s build and session limits against [E2B pricing](https://e2b.dev/pricing); account limits can be lower than Sim’s requested lifetime. Sizing is fixed when the template is built — E2B has no per-sandbox override — so changing it means rebuilding the template, not restarting Sim. Sandboxes are billed per second against the resources they are allocated, not the ones they use. Both numbers live in `apps/sim/scripts/pi-sandbox-packages.ts` and are shared with the Daytona snapshot so the failover image cannot drift from the primary. diff --git a/apps/sim/lib/core/config/env-capabilities.test.ts b/apps/sim/lib/core/config/env-capabilities.test.ts index 00d7eb5af12..a900dbbdfef 100644 --- a/apps/sim/lib/core/config/env-capabilities.test.ts +++ b/apps/sim/lib/core/config/env-capabilities.test.ts @@ -6,6 +6,7 @@ import { envField, getRedisConfigurationError, inspectCapability, + isSandboxKindAvailable, KNOWLEDGE_EMBEDDINGS_CAPABILITY, OCR_CAPABILITY, requireCapability, @@ -704,3 +705,75 @@ describe('env capabilities', () => { }) }) }) + +describe('sandbox kind availability', () => { + const E2B_FULL = { + E2B_ENABLED: 'true', + E2B_API_KEY: 'e2b-key', + E2B_FUNCTION_TEMPLATE_ID, + E2B_FUNCTION_TEMPLATE_GENERATION: '1', + MOTHERSHIP_E2B_TEMPLATE_ID: 'mothership-shell', + MOTHERSHIP_E2B_DOC_TEMPLATE_ID: 'mothership-docs', + } + const DAYTONA_WITHOUT_PI = { + SANDBOX_PROVIDER: 'daytona', + DAYTONA_API_KEY: 'daytona-key', + DAYTONA_FUNCTION_SNAPSHOT_ID, + DAYTONA_SHELL_SNAPSHOT_ID: 'mothership-shell:v1', + DAYTONA_DOC_SNAPSHOT_ID: 'mothership-docs:v1', + } + + it.each([ + { + name: 'E2B enabled with every image', + values: E2B_FULL, + expected: { function: true, mothership: true, doc: true, pi: true }, + }, + { + name: 'E2B enabled without a Pi template still shows Pi cloud', + values: { ...E2B_FULL, E2B_PI_TEMPLATE_ID: undefined }, + expected: { function: true, mothership: true, doc: true, pi: true }, + }, + { + name: 'E2B switched off', + values: { ...E2B_FULL, E2B_ENABLED: 'false', E2B_PI_TEMPLATE_ID: 'sim-pi' }, + expected: { function: false, mothership: false, doc: false, pi: false }, + }, + { + name: 'E2B unset entirely', + values: {}, + expected: { function: false, mothership: false, doc: false, pi: false }, + }, + { + name: 'Daytona with its Pi snapshot', + values: { ...DAYTONA_WITHOUT_PI, DAYTONA_PI_SNAPSHOT_ID: 'sim-pi:v1' }, + expected: { function: true, mothership: true, doc: true, pi: true }, + }, + { + name: 'Daytona without a Pi snapshot', + values: DAYTONA_WITHOUT_PI, + expected: { function: true, mothership: true, doc: true, pi: false }, + }, + { + name: 'Daytona with a leftover E2B_ENABLED and no Pi snapshot', + values: { ...DAYTONA_WITHOUT_PI, E2B_ENABLED: 'true', E2B_API_KEY: 'e2b-key' }, + expected: { function: true, mothership: true, doc: true, pi: false }, + }, + { + name: 'Daytona Pi snapshot without the Daytona key', + values: { + ...DAYTONA_WITHOUT_PI, + DAYTONA_API_KEY: undefined, + DAYTONA_PI_SNAPSHOT_ID: 'sim-pi:v1', + }, + expected: { function: false, mothership: false, doc: false, pi: false }, + }, + ])('$name', ({ values, expected }) => { + expect({ + function: isSandboxKindAvailable(values, 'function'), + mothership: isSandboxKindAvailable(values, 'mothership'), + doc: isSandboxKindAvailable(values, 'doc'), + pi: isSandboxKindAvailable(values, 'pi'), + }).toEqual(expected) + }) +}) diff --git a/apps/sim/lib/core/config/env-flags.ts b/apps/sim/lib/core/config/env-flags.ts index 44a9867f2ce..3bc4029bb0a 100644 --- a/apps/sim/lib/core/config/env-flags.ts +++ b/apps/sim/lib/core/config/env-flags.ts @@ -536,8 +536,8 @@ export const isInvitationsDisabled = resolveServerSwitch( export const isPublicApiDisabled = resolveServerSwitch(env.DISABLE_PUBLIC_API, 'publicApiDisabled') /** - * Can the selected sandbox provider run Pi's cloud modes (Create PR, Update PR, - * Review Code); they stay hidden without it. Projected to the browser under its + * Can the selected sandbox provider run Pi's cloud modes (Plan, Create PR, + * Update PR, Review Code); they stay hidden without it. Projected to the browser under its * original `e2bEnabled` key, which predates provider selection. */ export const isPiCloudEnabled = resolveServerSwitch(isSandboxKindAvailable(env, 'pi'), 'e2bEnabled') diff --git a/apps/sim/lib/execution/remote-sandbox/cli-tools.server.ts b/apps/sim/lib/execution/remote-sandbox/cli-tools.server.ts index 5076804a053..5e3a44b7ddb 100644 --- a/apps/sim/lib/execution/remote-sandbox/cli-tools.server.ts +++ b/apps/sim/lib/execution/remote-sandbox/cli-tools.server.ts @@ -1,4 +1,3 @@ -import { SANDBOX_PROVIDER_IDS } from '@sim/utils/sandbox-references' import { canonicalizeSandboxCliTools, SANDBOX_CLI_TOOLS, @@ -54,8 +53,11 @@ export const SANDBOX_SYSTEM_PATH = '/usr/local/sbin:/usr/local/bin:/usr/local/games:/usr/sbin:/usr/bin:/usr/games:/sbin:/bin:/root/.local/bin' const SIM_CLI_ROOT = '/opt/sim-cli' -/** Recipes run on every provider unless they narrow `supportedProviders`. */ -const DEFAULT_SUPPORTED_PROVIDERS = SANDBOX_PROVIDER_IDS +/** + * Providers every recipe has been verified on. A new provider opts in here only after its + * recipes are verified, rather than inheriting support from the provider list. + */ +const DEFAULT_SUPPORTED_PROVIDERS: [SandboxProviderId, ...SandboxProviderId[]] = ['e2b', 'daytona'] function defineVerifiedRecipe( id: Id, diff --git a/apps/sim/lib/execution/remote-sandbox/conformance.test.ts b/apps/sim/lib/execution/remote-sandbox/conformance.test.ts index 1b96051b9af..8de3c9c169e 100644 --- a/apps/sim/lib/execution/remote-sandbox/conformance.test.ts +++ b/apps/sim/lib/execution/remote-sandbox/conformance.test.ts @@ -337,6 +337,20 @@ const e2bFixture: ConformanceProviderFixture = { }, } +/** Hand-computed Daytona rounding for the budgets the scenarios use: whole minutes, whole seconds. */ +const DAYTONA_ROUNDED_BUDGETS: Readonly< + Record +> = { + 46000: { ttlMinutes: 1, commandSeconds: 46 }, + 1000: { ttlMinutes: 1, commandSeconds: 1 }, +} + +function daytonaRoundedBudget(budgetMs: number): { ttlMinutes: number; commandSeconds: number } { + const rounded = DAYTONA_ROUNDED_BUDGETS[budgetMs] + if (!rounded) throw new Error(`No expected Daytona rounding for a ${budgetMs}ms budget`) + return rounded +} + const daytonaFixture: ConformanceProviderFixture = { images: { function: '7d9d12d6-5f2a-44df-9cc2-a20203f3813b', @@ -502,11 +516,13 @@ const daytonaFixture: ConformanceProviderFixture = { expectLifetimeBudget(budgetMs) { expect(mockDaytonaCreate.mock.calls[0][0]).toMatchObject({ ephemeral: true, - ttlMinutes: Math.ceil(budgetMs / 60_000), + ttlMinutes: daytonaRoundedBudget(budgetMs).ttlMinutes, }) }, expectCommandBudget(budgetMs) { - expect(mockExecuteSessionCommand.mock.calls.at(-1)?.[2]).toBe(Math.ceil(budgetMs / 1000)) + expect(mockExecuteSessionCommand.mock.calls.at(-1)?.[2]).toBe( + daytonaRoundedBudget(budgetMs).commandSeconds + ) }, expectJavaScriptPreloadLaunch() { const uploadedFunctionPaths = mockUploadFile.mock.calls diff --git a/apps/sim/lib/mothership/request/tools/sandbox-recovery.ts b/apps/sim/lib/mothership/request/tools/sandbox-recovery.ts index daec49c0168..734b119b954 100644 --- a/apps/sim/lib/mothership/request/tools/sandbox-recovery.ts +++ b/apps/sim/lib/mothership/request/tools/sandbox-recovery.ts @@ -6,7 +6,12 @@ import { settleSimSandboxProcess } from '@/lib/mothership/async-runs/repository' const logger = createLogger('MothershipSandboxRecovery') -/** A failed provider call leaves its durable ownership receipt unresolved. */ +/** + * A failed provider call leaves its durable ownership receipt unresolved. + * + * Stops through the currently selected provider: `SessionProcessIdentity` records no provider + * id, so receipts left by a provider the deployment has since switched away from stay unresolved. + */ export async function recoverSandboxProcesses( processes: Array, signal: AbortSignal diff --git a/packages/deployment-config/src/env-capabilities.ts b/packages/deployment-config/src/env-capabilities.ts index a75441e8013..d684121fccd 100644 --- a/packages/deployment-config/src/env-capabilities.ts +++ b/packages/deployment-config/src/env-capabilities.ts @@ -10,6 +10,7 @@ import { isImmutableDaytonaSnapshotRef, isImmutableE2BTemplateRef, isValidSandboxReleaseGeneration, + type SANDBOX_PROVIDER_IDS, SANDBOX_RELEASE_GENERATION_ERROR, } from '@sim/utils/sandbox-references' @@ -1137,6 +1138,19 @@ type DedicatedSandboxImageKind = 'mothership' | 'doc' | 'pi' * enabled, and the adapter reports a missing `E2B_PI_TEMPLATE_ID` when the * sandbox is created. */ +/** + * `unknown` when `SANDBOX_PROVIDER_IDS` (which validates `SANDBOX_PROVIDER` and types the + * adapters) and {@link SANDBOX_CAPABILITY} declare the same providers; otherwise a type with + * an unsatisfiable property, so adding an id to only one list fails the table below. + */ +type SandboxProviderListsMatch = [(typeof SANDBOX_PROVIDER_IDS)[number]] extends [ + DeclaredProviderId, +] + ? [DeclaredProviderId] extends [(typeof SANDBOX_PROVIDER_IDS)[number]] + ? unknown + : { sandboxCapabilityProviderMissingFromSandboxProviderIds: never } + : { sandboxProviderIdMissingFromSandboxCapability: never } + const SANDBOX_IMAGE_KIND_REQUIREMENTS = { e2b: { mothership: allOf(envField('E2B_API_KEY'), envField('MOTHERSHIP_E2B_TEMPLATE_ID')), @@ -1151,7 +1165,8 @@ const SANDBOX_IMAGE_KIND_REQUIREMENTS = { } as const satisfies Record< DeclaredProviderId, Record -> +> & + SandboxProviderListsMatch /** * Whether the selected sandbox provider can serve `kind` with this environment. diff --git a/packages/sim-setup/src/capability-status.ts b/packages/sim-setup/src/capability-status.ts index a8c2595b8ad..c14011f966b 100644 --- a/packages/sim-setup/src/capability-status.ts +++ b/packages/sim-setup/src/capability-status.ts @@ -249,10 +249,7 @@ function inspectSandbox(values: EnvCapabilityValues): SandboxCapabilityStatus { const selectedProvider = inspection.providers.find( (provider) => provider.id === inspection.providerId ) - const providerId = - selectedProvider && !selectedProvider.active && selectedProvider.state === 'absent' - ? 'disabled' - : inspection.providerId + const providerId = selectedProvider?.state === 'absent' ? 'disabled' : inspection.providerId if (!inspection.error) { return { From a9b21f00f76ea1852a62646d2720ea381fd13417 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 13:39:42 -0600 Subject: [PATCH 04/78] feat(sandbox): generate content-addressed Function and Pi sandbox images for the Kubernetes provider Render docker/sandbox-function.Dockerfile and docker/sandbox-pi.Dockerfile from the single-source package lists the E2B and Daytona builders consume, behind a generate:sandbox-dockerfiles / check:sandbox-dockerfiles pair. Both images use the Daytona base digest, run the Daytona install steps and build-time asserts, install Node from a checksum-verified archive per architecture, add the E2B user (uid/gid 1000, home /home/user), and keep root as the default user. The agent binary is injected by the pod's initContainer, not baked in. The Function Python surface is pinned by function-sandbox-manifest.json, in the parity-manifest format Daytona takes from an accepted E2B run. The generator also writes apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json, mapping each kind (function, pi, agent) to ghcr.io/simstudioai/sandbox-:, where the tag is the first 16 hex chars of a sha256 over the image's declared inputs, so a Sim release references exact images without a per-release build. verify-sandbox-image.ts checks a built image with the local Docker daemon: root default user, the uid 1000 contract, and the Function parity probe against the manifest (or the Pi runtime asserts). E2B and Daytona builders are unchanged. --- .../kubernetes/images.generated.json | 5 + .../scripts/function-sandbox-manifest.json | 310 +++++++++++++++++ apps/sim/scripts/function-sandbox-packages.ts | 13 +- .../scripts/generate-sandbox-dockerfiles.ts | 328 ++++++++++++++++++ apps/sim/scripts/pi-sandbox-packages.ts | 19 +- apps/sim/scripts/verify-sandbox-image.ts | 166 +++++++++ docker/sandbox-function.Dockerfile | 143 ++++++++ docker/sandbox-pi.Dockerfile | 54 +++ package.json | 2 + 9 files changed, 1036 insertions(+), 4 deletions(-) create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json create mode 100644 apps/sim/scripts/function-sandbox-manifest.json create mode 100644 apps/sim/scripts/generate-sandbox-dockerfiles.ts create mode 100644 apps/sim/scripts/verify-sandbox-image.ts create mode 100644 docker/sandbox-function.Dockerfile create mode 100644 docker/sandbox-pi.Dockerfile diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json b/apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json new file mode 100644 index 00000000000..ee2cf830032 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json @@ -0,0 +1,5 @@ +{ + "function": "ghcr.io/simstudioai/sandbox-function:6d7f249fa417b147", + "pi": "ghcr.io/simstudioai/sandbox-pi:01cb06a1b2c01cad", + "agent": "ghcr.io/simstudioai/sandbox-agent:f78259477207d674" +} diff --git a/apps/sim/scripts/function-sandbox-manifest.json b/apps/sim/scripts/function-sandbox-manifest.json new file mode 100644 index 00000000000..ec7bbc67101 --- /dev/null +++ b/apps/sim/scripts/function-sandbox-manifest.json @@ -0,0 +1,310 @@ +{ + "schemaVersion": 1, + "runtime": { + "node": "20.20.2", + "python": "3.13.14" + }, + "pythonPackages": [ + { + "distribution": "numpy", + "importName": "numpy", + "version": "2.3.5" + }, + { + "distribution": "pandas", + "importName": "pandas", + "version": "2.2.3" + }, + { + "distribution": "scipy", + "importName": "scipy", + "version": "1.17.1" + }, + { + "distribution": "sympy", + "importName": "sympy", + "version": "1.14.0" + }, + { + "distribution": "numba", + "importName": "numba", + "version": "0.66.0" + }, + { + "distribution": "xarray", + "importName": "xarray", + "version": "2025.4.0" + }, + { + "distribution": "networkx", + "importName": "networkx", + "version": "3.7" + }, + { + "distribution": "scikit-learn", + "importName": "sklearn", + "version": "1.6.1" + }, + { + "distribution": "scikit-image", + "importName": "skimage", + "version": "0.25.2" + }, + { + "distribution": "matplotlib", + "importName": "matplotlib", + "version": "3.11.2" + }, + { + "distribution": "seaborn", + "importName": "seaborn", + "version": "0.13.2" + }, + { + "distribution": "plotly", + "importName": "plotly", + "version": "6.0.1" + }, + { + "distribution": "bokeh", + "importName": "bokeh", + "version": "3.9.1" + }, + { + "distribution": "kaleido", + "importName": "kaleido", + "version": "1.3.0" + }, + { + "distribution": "pillow", + "importName": "PIL", + "version": "13.0.0" + }, + { + "distribution": "imageio", + "importName": "imageio", + "version": "2.37.3" + }, + { + "distribution": "tifffile", + "importName": "tifffile", + "version": "2026.11.26" + }, + { + "distribution": "opencv-python", + "importName": "cv2", + "version": "4.11.0.86" + }, + { + "distribution": "librosa", + "importName": "librosa", + "version": "0.11.0" + }, + { + "distribution": "soundfile", + "importName": "soundfile", + "version": "0.13.1" + }, + { + "distribution": "spacy", + "importName": "spacy", + "version": "3.8.14" + }, + { + "distribution": "nltk", + "importName": "nltk", + "version": "3.10.4" + }, + { + "distribution": "textblob", + "importName": "textblob", + "version": "0.19.0" + }, + { + "distribution": "gensim", + "importName": "gensim", + "version": "4.4.0" + }, + { + "distribution": "beautifulsoup4", + "importName": "bs4", + "version": "4.15.0" + }, + { + "distribution": "lxml", + "importName": "lxml", + "version": "6.2.1" + }, + { + "distribution": "requests", + "importName": "requests", + "version": "2.33.0" + }, + { + "distribution": "openpyxl", + "importName": "openpyxl", + "version": "3.1.5" + }, + { + "distribution": "xlrd", + "importName": "xlrd", + "version": "2.0.2" + }, + { + "distribution": "python-docx", + "importName": "docx", + "version": "1.1.2" + }, + { + "distribution": "xmltodict", + "importName": "xmltodict", + "version": "1.0.4" + }, + { + "distribution": "PyYAML", + "importName": "yaml", + "version": "6.0.4" + }, + { + "distribution": "tomlkit", + "importName": "tomlkit", + "version": "0.15.0" + }, + { + "distribution": "simplejson", + "importName": "simplejson", + "version": "4.3.0" + }, + { + "distribution": "orjson", + "importName": "orjson", + "version": "3.11.9" + }, + { + "distribution": "SQLAlchemy", + "importName": "sqlalchemy", + "version": "2.0.51" + }, + { + "distribution": "rich", + "importName": "rich", + "version": "15.0.0" + }, + { + "distribution": "typer", + "importName": "typer", + "version": "0.29.3" + }, + { + "distribution": "click", + "importName": "click", + "version": "8.5.1" + }, + { + "distribution": "tqdm", + "importName": "tqdm", + "version": "4.70.1" + }, + { + "distribution": "Jinja2", + "importName": "jinja2", + "version": "3.1.6" + }, + { + "distribution": "pydantic", + "importName": "pydantic", + "version": "2.14.4" + }, + { + "distribution": "python-dateutil", + "importName": "dateutil", + "version": "4.0.0" + }, + { + "distribution": "pytz", + "importName": "pytz", + "version": "2025.2" + }, + { + "distribution": "psutil", + "importName": "psutil", + "version": "7.2.2" + }, + { + "distribution": "filetype", + "importName": "filetype", + "version": "1.2.0" + }, + { + "distribution": "python-slugify", + "importName": "slugify", + "version": "8.0.4" + }, + { + "distribution": "parsedatetime", + "importName": "parsedatetime", + "version": "2.6" + }, + { + "distribution": "pytimeparse", + "importName": "pytimeparse", + "version": "1.1.8" + } + ], + "pipCliPackages": [ + { + "package": "yq", + "version": "4.1.2" + }, + { + "package": "csvkit", + "version": "2.2.0" + } + ], + "npmCliPackages": [ + { + "package": "zx", + "version": "8.8.5" + } + ], + "commands": [ + "bash", + "bat", + "bc", + "bzip2", + "convert", + "csvcut", + "csvtool", + "curl", + "dig", + "dos2unix", + "dpkg-deb", + "fd", + "ffmpeg", + "file", + "git", + "gzip", + "http", + "install", + "ip", + "jq", + "nc", + "node", + "npm", + "python3", + "rg", + "sha256sum", + "ag", + "sqlite3", + "tar", + "tree", + "unzip", + "wget", + "xmlstarlet", + "xz", + "yq", + "7z", + "zip", + "zx" + ] +} diff --git a/apps/sim/scripts/function-sandbox-packages.ts b/apps/sim/scripts/function-sandbox-packages.ts index b000a585dc7..53eda494330 100644 --- a/apps/sim/scripts/function-sandbox-packages.ts +++ b/apps/sim/scripts/function-sandbox-packages.ts @@ -1,9 +1,11 @@ /** * Single source of truth for the dedicated Function sandbox base. * - * Both provider renderers consume these lists: + * Every renderer consumes these lists: * - `build-function-e2b-template.ts` layers them onto E2B's code-interpreter base. * - `build-function-daytona-snapshot.ts` builds the equivalent Daytona snapshot. + * - `generate-sandbox-dockerfiles.ts` renders `docker/sandbox-function.Dockerfile` + * for the self-hosted Kubernetes provider, pinned by `function-sandbox-manifest.json`. * * Mothership, document generation, and Pi deliberately own separate images and * package manifests. A change here affects only Function code, Shell, and custom @@ -33,6 +35,15 @@ export const FUNCTION_DAYTONA_NODE_INSTALL = [ `rm -f '/tmp/${FUNCTION_DAYTONA_NODE_ARCHIVE}'`, ].join(' && ') +/** + * Checksums of the pinned Node archive per architecture, keyed by Node's archive + * suffix, for the multi-arch self-hosted image. x64 is the Daytona archive. + */ +export const FUNCTION_NODE_ARCHIVE_SHA256 = { + x64: FUNCTION_DAYTONA_NODE_SHA256, + arm64: '73093db209e4e9e09dd7d15a47aeaab1b74833830df03efa5f942a1122c5fa71', +} as const + /** * Universal command-line utilities available to JavaScript, Python, and Shell. * Provider bootstrap packages live here too so E2B and Daytona cannot drift. diff --git a/apps/sim/scripts/generate-sandbox-dockerfiles.ts b/apps/sim/scripts/generate-sandbox-dockerfiles.ts new file mode 100644 index 00000000000..c0b3a9d9336 --- /dev/null +++ b/apps/sim/scripts/generate-sandbox-dockerfiles.ts @@ -0,0 +1,328 @@ +#!/usr/bin/env bun + +/** + * Renders the self-hosted Kubernetes sandbox images from the same single-source + * package lists the E2B and Daytona builders consume: + * + * - `docker/sandbox-function.Dockerfile` from `function-sandbox-packages.ts`, with + * the Python surface pinned by `function-sandbox-manifest.json` exactly as the + * Daytona snapshot pins it from an accepted E2B parity manifest. + * - `docker/sandbox-pi.Dockerfile` from `pi-sandbox-packages.ts`. + * + * Both images run the Daytona builders' install steps and build-time asserts on + * the same digest-pinned base, installing Node from a checksum-verified archive + * for each published architecture. They add the E2B user contract (`user`, + * uid/gid 1000, home `/home/user`) and keep root as the default user: the + * in-sandbox agent runs as root and drops to uid 1000 for user code. The agent + * binary is not baked in; the pod's initContainer injects it. + * + * To move the Function Python surface, replace `function-sandbox-manifest.json` + * with an accepted E2B parity manifest (`SANDBOX_PARITY_MANIFEST_OUT` from + * `verify-sandbox-parity.ts`) and regenerate. + * + * It also writes `lib/execution/remote-sandbox/kubernetes/images.generated.json`, + * mapping each sandbox kind to a content-addressed reference + * `ghcr.io/simstudioai/sandbox-:`. The tag is the first 16 hex chars of + * a sha256 over the image's declared build inputs ({@link SANDBOX_IMAGES}), so a + * Sim release references exact images without rebuilding them per release, and + * `.github/workflows/sandbox-images.yml` publishes a tag only when it is missing. + * + * Usage: + * bun run apps/sim/scripts/generate-sandbox-dockerfiles.ts # rewrite the Dockerfiles and image refs + * bun run apps/sim/scripts/generate-sandbox-dockerfiles.ts --check # fail when any is stale + */ + +import { spawnSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { existsSync } from 'node:fs' +import { mkdir, readFile, writeFile } from 'node:fs/promises' +import { dirname, relative, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' +import { compareStrings } from '@sim/utils/string' +import { + FUNCTION_APT_PACKAGES, + FUNCTION_COMMAND_ALIASES_ASSERT, + FUNCTION_COMMAND_ALIASES_SETUP, + FUNCTION_COMMANDS_ASSERT, + FUNCTION_DAYTONA_BASE_IMAGE, + FUNCTION_DAYTONA_NODE_VERSION, + FUNCTION_DAYTONA_NODE_VERSION_ASSERT, + FUNCTION_DAYTONA_PYTHON_VERSION, + FUNCTION_NODE_ARCHIVE_SHA256, + FUNCTION_NODE_VERSION_ASSERT, + FUNCTION_NPM_CLI_PACKAGES, + FUNCTION_NPM_CLI_VERSIONS_ASSERT, + FUNCTION_PIP_CLI_PACKAGES, + FUNCTION_PIP_CLI_VERSIONS_ASSERT, + FUNCTION_PYTHON_IMPORTS_ASSERT, + FUNCTION_PYTHON_VERSION_ASSERT, +} from '@/scripts/function-sandbox-packages' +import { + createFunctionPythonVersionsAssert, + type FunctionSandboxParityManifest, + getPinnedFunctionPythonPackages, + readFunctionSandboxParityManifest, +} from '@/scripts/function-sandbox-parity-manifest' +import { + PI_APT, + PI_BUN_VERSION_ASSERT, + PI_GLOBAL_NPM_PACKAGES, + PI_NODE_ARCHIVE_SHA256, + PI_NODE_VERSION, + PI_NODE_VERSION_ASSERT, +} from '@/scripts/pi-sandbox-packages' + +const logger = createLogger('GenerateSandboxDockerfiles') + +const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)) +const ROOT = resolve(SCRIPT_DIR, '../../..') +const FUNCTION_MANIFEST_PATH = resolve(SCRIPT_DIR, 'function-sandbox-manifest.json') +const FUNCTION_DOCKERFILE_PATH = resolve(ROOT, 'docker/sandbox-function.Dockerfile') +const PI_DOCKERFILE_PATH = resolve(ROOT, 'docker/sandbox-pi.Dockerfile') +const IMAGE_REFS_PATH = resolve( + SCRIPT_DIR, + '../lib/execution/remote-sandbox/kubernetes/images.generated.json' +) +const IMAGE_REPOSITORY_PREFIX = 'ghcr.io/simstudioai/sandbox-' +const CONTENT_TAG_LENGTH = 16 + +/** + * Every sandbox image and the repo paths (files or directories, as git pathspecs) + * its build reads. Function and Pi COPY nothing, so their Dockerfile is the whole + * input. The agent image compiles `apps/sandbox-agent` with the workspace packages + * it imports; keep its list in step with `docker/sandbox-agent.Dockerfile`. + */ +const SANDBOX_IMAGES = [ + { kind: 'function', inputs: ['docker/sandbox-function.Dockerfile'] }, + { kind: 'pi', inputs: ['docker/sandbox-pi.Dockerfile'] }, + { + kind: 'agent', + inputs: [ + 'docker/sandbox-agent.Dockerfile', + '.dockerignore', + 'package.json', + 'bun.lock', + 'apps/sandbox-agent', + 'packages/sandbox-agent-protocol', + 'packages/logger', + 'packages/utils', + 'packages/tsconfig', + ], + }, +] as const + +const APT_INSTALL = 'DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends' +const CONTINUATION = ' \\\n ' + +/** The E2B sandbox user, which the agent switches to for user code. */ +const CREATE_SANDBOX_USER = [ + 'groupadd --gid 1000 user', + 'useradd --uid 1000 --gid 1000 --create-home --home-dir /home/user --shell /bin/bash user', + 'mkdir -p /workspace /opt/sim-deps', + 'chown user:user /workspace', +].join(' && ') + +interface NodeArchiveChecksums { + x64: string + arm64: string +} + +/** Installs an exact Node release for the build's target architecture, refusing any other. */ +function nodeArchiveInstall(version: string, checksums: NodeArchiveChecksums): string { + return [ + 'case "$TARGETARCH" in', + `amd64) node_arch=x64; node_sha256=${checksums.x64} ;;`, + `arm64) node_arch=arm64; node_sha256=${checksums.arm64} ;;`, + '*) echo "unsupported TARGETARCH: $TARGETARCH" >&2; exit 1 ;;', + 'esac', + `&& archive="node-v${version}-linux-$node_arch.tar.xz"`, + `&& curl -fsSL --retry 3 --retry-all-errors "https://nodejs.org/dist/v${version}/$archive" -o "/tmp/$archive"`, + '&& echo "$node_sha256 /tmp/$archive" | sha256sum -c -', + '&& tar -xJf "/tmp/$archive" -C /usr/local --strip-components=1', + '&& rm -f "/tmp/$archive"', + ].join(CONTINUATION) +} + +function aptInstall(packages: readonly string[]): string { + return `apt-get update && ${APT_INSTALL}${CONTINUATION}${packages.join(CONTINUATION)}${CONTINUATION}&& rm -rf /var/lib/apt/lists/*` +} + +function run(command: string): string { + return `RUN ${command}` +} + +function header(sources: string, purpose: string): string { + return [ + '# Generated by apps/sim/scripts/generate-sandbox-dockerfiles.ts — do not edit.', + `# Source: ${sources}`, + '# Regenerate with `bun run generate:sandbox-dockerfiles`.', + '#', + `# ${purpose}`, + '# Root stays the default user: the in-sandbox agent, injected by the pod', + '# initContainer rather than baked in, runs as root and drops to `user`', + '# (uid/gid 1000, home /home/user) for user code.', + ].join('\n') +} + +function renderFunctionDockerfile(manifest: FunctionSandboxParityManifest): string { + const pipPackages = [...getPinnedFunctionPythonPackages(manifest), ...FUNCTION_PIP_CLI_PACKAGES] + const asserts = [ + FUNCTION_NODE_VERSION_ASSERT, + FUNCTION_DAYTONA_NODE_VERSION_ASSERT, + FUNCTION_PYTHON_VERSION_ASSERT, + FUNCTION_COMMANDS_ASSERT, + FUNCTION_COMMAND_ALIASES_ASSERT, + FUNCTION_PIP_CLI_VERSIONS_ASSERT, + FUNCTION_NPM_CLI_VERSIONS_ASSERT, + FUNCTION_PYTHON_IMPORTS_ASSERT, + createFunctionPythonVersionsAssert(manifest), + ] + return [ + header( + 'apps/sim/scripts/function-sandbox-packages.ts, apps/sim/scripts/function-sandbox-manifest.json', + 'Function sandbox (JavaScript, Python, Shell) for the Kubernetes sandbox provider.' + ), + `FROM ${FUNCTION_DAYTONA_BASE_IMAGE}`, + 'ARG TARGETARCH', + run(aptInstall(FUNCTION_APT_PACKAGES)), + run(nodeArchiveInstall(FUNCTION_DAYTONA_NODE_VERSION, FUNCTION_NODE_ARCHIVE_SHA256)), + run(`python3 -m pip install --no-cache-dir${CONTINUATION}${pipPackages.join(CONTINUATION)}`), + run(`npm install -g ${FUNCTION_NPM_CLI_PACKAGES.join(' ')}`), + run(FUNCTION_COMMAND_ALIASES_SETUP), + run(CREATE_SANDBOX_USER), + ...asserts.map(run), + 'WORKDIR /home/user\n', + ].join('\n\n') +} + +function renderPiDockerfile(): string { + const exactNodeAssert = `test "$(node --version)" = "v${PI_NODE_VERSION}"` + return [ + header( + 'apps/sim/scripts/pi-sandbox-packages.ts', + 'Pi sandbox (Create PR, Review Code) for the Kubernetes sandbox provider.' + ), + `FROM ${FUNCTION_DAYTONA_BASE_IMAGE}`, + 'ARG TARGETARCH', + run(aptInstall(['curl', 'ca-certificates', 'gnupg', 'xz-utils'])), + run( + `${nodeArchiveInstall(PI_NODE_VERSION, PI_NODE_ARCHIVE_SHA256)}${CONTINUATION}&& ${PI_NODE_VERSION_ASSERT}${CONTINUATION}&& ${exactNodeAssert}` + ), + run(aptInstall(PI_APT)), + run(`npm install -g${CONTINUATION}${PI_GLOBAL_NPM_PACKAGES.join(CONTINUATION)}`), + run(PI_BUN_VERSION_ASSERT), + run(CREATE_SANDBOX_USER), + 'WORKDIR /home/user\n', + ].join('\n\n') +} + +function readFunctionManifest(): FunctionSandboxParityManifest { + const manifest = readFunctionSandboxParityManifest(FUNCTION_MANIFEST_PATH) + if (manifest.runtime.node !== FUNCTION_DAYTONA_NODE_VERSION) { + throw new Error( + `function-sandbox-manifest.json requires Node ${manifest.runtime.node}, but the image is pinned to ${FUNCTION_DAYTONA_NODE_VERSION}` + ) + } + if (manifest.runtime.python !== FUNCTION_DAYTONA_PYTHON_VERSION) { + throw new Error( + `function-sandbox-manifest.json requires Python ${manifest.runtime.python}, but the base image is pinned to ${FUNCTION_DAYTONA_PYTHON_VERSION}` + ) + } + return manifest +} + +async function readIfExists(path: string): Promise { + return existsSync(path) ? readFile(path, 'utf8') : null +} + +/** + * Files matched by the given pathspecs, tracked or not (gitignored files excluded), + * so a fresh checkout and a working tree with new files hash the same set. + */ +function listInputFiles(pathspecs: readonly string[]): string[] { + const result = spawnSync( + 'git', + ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', ...pathspecs], + { cwd: ROOT, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 } + ) + if (result.status !== 0) { + throw new Error(`git ls-files failed: ${result.stderr || result.error}`) + } + const files = new Set(result.stdout.split('\0').filter(Boolean)) + return [...files].filter((file) => existsSync(resolve(ROOT, file))).sort(compareStrings) +} + +function sha256(content: string | Buffer): string { + return createHash('sha256').update(content).digest('hex') +} + +/** + * The content tag of one image: a hash over each input's path and content hash. + * Rendered Dockerfiles are hashed from memory, so the tag never lags the render. + */ +async function contentTag( + pathspecs: readonly string[], + rendered: ReadonlyMap +): Promise { + const files = new Set(listInputFiles(pathspecs)) + for (const path of rendered.keys()) { + if (pathspecs.includes(path)) files.add(path) + } + const digest = createHash('sha256') + for (const file of [...files].sort(compareStrings)) { + const content = rendered.get(file) ?? (await readFile(resolve(ROOT, file))) + digest.update(`${file}\0${sha256(content)}\n`) + } + return digest.digest('hex').slice(0, CONTENT_TAG_LENGTH) +} + +async function renderImageRefs(rendered: ReadonlyMap): Promise { + const refs: Record = {} + for (const image of SANDBOX_IMAGES) { + const tag = await contentTag(image.inputs, rendered) + refs[image.kind] = `${IMAGE_REPOSITORY_PREFIX}${image.kind}:${tag}` + } + return `${JSON.stringify(refs, null, 2)}\n` +} + +async function main(): Promise { + const check = process.argv.includes('--check') + const functionDockerfile = renderFunctionDockerfile(readFunctionManifest()) + const piDockerfile = renderPiDockerfile() + const rendered = new Map([ + [relative(ROOT, FUNCTION_DOCKERFILE_PATH), functionDockerfile], + [relative(ROOT, PI_DOCKERFILE_PATH), piDockerfile], + ]) + const outputs = [ + { path: FUNCTION_DOCKERFILE_PATH, content: functionDockerfile }, + { path: PI_DOCKERFILE_PATH, content: piDockerfile }, + { path: IMAGE_REFS_PATH, content: await renderImageRefs(rendered) }, + ] + + const stale: string[] = [] + for (const output of outputs) { + const current = await readIfExists(output.path) + if (current === output.content) continue + if (check) { + stale.push(relative(ROOT, output.path)) + continue + } + await mkdir(dirname(output.path), { recursive: true }) + await writeFile(output.path, output.content, 'utf8') + logger.info('Wrote sandbox image artifact', { path: relative(ROOT, output.path) }) + } + + if (stale.length > 0) { + logger.error('Sandbox image artifacts are stale; run `bun run generate:sandbox-dockerfiles`', { + stale, + }) + process.exitCode = 1 + } +} + +main().catch((error: unknown) => { + logger.error('Sandbox Dockerfile generation failed', { error: getErrorMessage(error) }) + process.exitCode = 1 +}) diff --git a/apps/sim/scripts/pi-sandbox-packages.ts b/apps/sim/scripts/pi-sandbox-packages.ts index b67cc4eb68b..c971d487bd7 100644 --- a/apps/sim/scripts/pi-sandbox-packages.ts +++ b/apps/sim/scripts/pi-sandbox-packages.ts @@ -1,9 +1,11 @@ /** * The single source of truth for what goes into the Pi sandbox image. * - * Two renderers consume these lists: - * - `build-pi-e2b-template.ts` — E2B template, via the `Template()` builder DSL - * - `build-pi-daytona-snapshot.ts` — Daytona snapshot, via the `Image` builder + * Three renderers consume these lists: + * - `build-pi-e2b-template.ts` — E2B template, via the `Template()` builder DSL + * - `build-pi-daytona-snapshot.ts` — Daytona snapshot, via the `Image` builder + * - `generate-sandbox-dockerfiles.ts` — `docker/sandbox-pi.Dockerfile`, the + * self-hosted Kubernetes image * * A package added here reaches both providers. Adding one to only a single * renderer is the drift that makes a failover fail at the worst moment. @@ -54,6 +56,17 @@ export const PI_APT = [ */ export const PI_NODE_MAJOR = 22 +/** + * Exact Node release the self-hosted image installs from nodejs.org, verified per + * architecture (keyed by Node's archive suffix). E2B and Daytona take NodeSource's + * current 22.x instead, so this pin only has to satisfy {@link PI_NODE_VERSION_ASSERT}. + */ +export const PI_NODE_VERSION = '22.23.5' +export const PI_NODE_ARCHIVE_SHA256 = { + x64: 'cdeb8670a0c81f51b4dc4ac61919f9b1ad917b304bf8221eb939570663d240f8', + arm64: '2babb9eb5264860d540849f4b064a6fbdebcdc323657d9d382ce23d313fd5e09', +} as const + /** Fails the build loudly if the installed Node is older than Pi supports. */ export const PI_NODE_VERSION_ASSERT = 'node -e "const [major, minor] = process.versions.node.split(\'.\').map(Number); if (major < 22 || (major === 22 && minor < 19)) process.exit(1)"' diff --git a/apps/sim/scripts/verify-sandbox-image.ts b/apps/sim/scripts/verify-sandbox-image.ts new file mode 100644 index 00000000000..833511b2b2f --- /dev/null +++ b/apps/sim/scripts/verify-sandbox-image.ts @@ -0,0 +1,166 @@ +#!/usr/bin/env bun + +/** + * Verifies a built self-hosted sandbox image (`docker/sandbox-.Dockerfile`) + * by running it with the local Docker daemon, so CI can check an image before + * its tags are published. + * + * Every kind must keep root as the default user (the in-sandbox agent runs as + * root) and carry the E2B user contract: `user`, uid/gid 1000, a writable home + * at `/home/user`, plus `/workspace` and `/opt/sim-deps`. The Function image + * then runs the provider-parity probe as that user and must reproduce + * `function-sandbox-manifest.json` exactly. The Pi image re-runs its runtime + * asserts and checks the tools the Pi flows invoke by path or name. + * + * `verify-sandbox-parity.ts` cannot do this: it drives a live provider through + * `executeInSandbox`, and no provider runs a local image. + * + * Usage: + * bun run apps/sim/scripts/verify-sandbox-image.ts --kind function --image + * bun run apps/sim/scripts/verify-sandbox-image.ts --kind pi --image + */ + +import { spawnSync } from 'node:child_process' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' +import { + assertFunctionSandboxParityMatches, + createFunctionSandboxParityProbe, + parseFunctionSandboxParityManifest, + readFunctionSandboxParityManifest, +} from '@/scripts/function-sandbox-parity-manifest' +import { PI_BUN_VERSION_ASSERT, PI_NODE_VERSION_ASSERT } from '@/scripts/pi-sandbox-packages' + +const logger = createLogger('VerifySandboxImage') + +const RESULT_PREFIX = '__SIM_RESULT__=' +const FUNCTION_MANIFEST_PATH = resolve( + dirname(fileURLToPath(import.meta.url)), + 'function-sandbox-manifest.json' +) +const DOCKER_OUTPUT_LIMIT_BYTES = 16 * 1024 * 1024 + +const USER_CONTRACT_CHECK = [ + 'test "$(id -un):$(id -u):$(id -g)" = "user:1000:1000"', + 'test "$HOME" = /home/user', + 'test -w /home/user', + 'test -w /workspace', + 'test -d /opt/sim-deps', +].join(' && ') + +const PI_TOOLS_CHECK = [ + PI_NODE_VERSION_ASSERT, + PI_BUN_VERSION_ASSERT, + 'test -x /usr/bin/git', + 'command -v gh rg fdfind ssh >/dev/null', +].join(' && ') + +type SandboxImageKind = 'function' | 'pi' + +/** Runs a Docker CLI command, naming the failed step rather than echoing its arguments. */ +function docker(step: string, args: string[]): string { + const result = spawnSync('docker', args, { + encoding: 'utf8', + maxBuffer: DOCKER_OUTPUT_LIMIT_BYTES, + stdio: ['ignore', 'pipe', 'inherit'], + }) + if (result.error) throw new Error(`${step}: ${getErrorMessage(result.error)}`) + if (result.status !== 0) throw new Error(`${step} failed (exit ${result.status})`) + return result.stdout +} + +/** Runs a bash script in a fresh, network-less container as the given user. */ +function runInImage(step: string, image: string, user: string, script: string): string { + return docker(step, [ + 'run', + '--rm', + '--network', + 'none', + '--user', + user, + '--entrypoint', + '/bin/bash', + image, + '-c', + script, + ]) +} + +function assertRootDefaultUser(image: string): void { + const configuredUser = docker('Inspect image', [ + 'image', + 'inspect', + '--format', + '{{.Config.User}}', + image, + ]).trim() + if (configuredUser !== '' && configuredUser !== 'root' && configuredUser !== '0') { + throw new Error( + `Image default user must be root for the sandbox agent, got "${configuredUser}"` + ) + } + const uid = docker('Read default uid', [ + 'run', + '--rm', + '--network', + 'none', + '--entrypoint', + 'id', + image, + '-u', + ]).trim() + if (uid !== '0') throw new Error(`Image runs as uid ${uid} by default, expected 0`) +} + +function verifyFunctionManifest(image: string): void { + const output = runInImage( + 'Function parity probe', + image, + 'user', + createFunctionSandboxParityProbe(RESULT_PREFIX) + ) + const line = output.split('\n').find((candidate) => candidate.startsWith(RESULT_PREFIX)) + if (!line) throw new Error('The Function parity probe printed no manifest') + const actual = parseFunctionSandboxParityManifest(JSON.parse(line.slice(RESULT_PREFIX.length))) + assertFunctionSandboxParityMatches( + readFunctionSandboxParityManifest(FUNCTION_MANIFEST_PATH), + actual + ) +} + +function parseArgs(): { kind: SandboxImageKind; image: string } { + const args = process.argv.slice(2) + const kindIndex = args.indexOf('--kind') + const imageIndex = args.indexOf('--image') + const kind = kindIndex === -1 ? undefined : args[kindIndex + 1] + const image = imageIndex === -1 ? undefined : args[imageIndex + 1] + if (kind !== 'function' && kind !== 'pi') { + throw new Error('--kind must be function or pi') + } + if (!image || image.startsWith('--')) throw new Error('--image is required') + return { kind, image } +} + +function main(): void { + const { kind, image } = parseArgs() + logger.info('Verifying sandbox image', { kind, image }) + + assertRootDefaultUser(image) + runInImage('User contract check', image, 'user', USER_CONTRACT_CHECK) + if (kind === 'function') { + verifyFunctionManifest(image) + } else { + runInImage('Pi runtime check', image, 'user', PI_TOOLS_CHECK) + } + + logger.info('Sandbox image verified', { kind, image }) +} + +try { + main() +} catch (error) { + logger.error('Sandbox image verification failed', { error: getErrorMessage(error) }) + process.exitCode = 1 +} diff --git a/docker/sandbox-function.Dockerfile b/docker/sandbox-function.Dockerfile new file mode 100644 index 00000000000..c6ef1dcdb6f --- /dev/null +++ b/docker/sandbox-function.Dockerfile @@ -0,0 +1,143 @@ +# Generated by apps/sim/scripts/generate-sandbox-dockerfiles.ts — do not edit. +# Source: apps/sim/scripts/function-sandbox-packages.ts, apps/sim/scripts/function-sandbox-manifest.json +# Regenerate with `bun run generate:sandbox-dockerfiles`. +# +# Function sandbox (JavaScript, Python, Shell) for the Kubernetes sandbox provider. +# Root stays the default user: the in-sandbox agent, injected by the pod +# initContainer rather than baked in, runs as root and drops to `user` +# (uid/gid 1000, home /home/user) for user code. + +FROM python:3.13.14-slim-trixie@sha256:6771159cd4fa5d9bba1258caf0b82e6b73458c694d178ad97c5e925c2d0e1a91 + +ARG TARGETARCH + +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + bash \ + bat \ + bc \ + bzip2 \ + ca-certificates \ + coreutils \ + csvtool \ + curl \ + dnsutils \ + dos2unix \ + dpkg \ + fd-find \ + ffmpeg \ + file \ + git \ + gnupg \ + gzip \ + httpie \ + imagemagick \ + iproute2 \ + jq \ + libgl1 \ + libglib2.0-0 \ + libsndfile1 \ + netcat-openbsd \ + openssh-client \ + p7zip-full \ + procps \ + ripgrep \ + silversearcher-ag \ + sqlite3 \ + tar \ + tree \ + unzip \ + wget \ + xmlstarlet \ + xz-utils \ + zip \ + && rm -rf /var/lib/apt/lists/* + +RUN case "$TARGETARCH" in \ + amd64) node_arch=x64; node_sha256=df770b2a6f130ed8627c9782c988fda9669fa23898329a61a871e32f965e007d ;; \ + arm64) node_arch=arm64; node_sha256=73093db209e4e9e09dd7d15a47aeaab1b74833830df03efa5f942a1122c5fa71 ;; \ + *) echo "unsupported TARGETARCH: $TARGETARCH" >&2; exit 1 ;; \ + esac \ + && archive="node-v20.20.2-linux-$node_arch.tar.xz" \ + && curl -fsSL --retry 3 --retry-all-errors "https://nodejs.org/dist/v20.20.2/$archive" -o "/tmp/$archive" \ + && echo "$node_sha256 /tmp/$archive" | sha256sum -c - \ + && tar -xJf "/tmp/$archive" -C /usr/local --strip-components=1 \ + && rm -f "/tmp/$archive" + +RUN python3 -m pip install --no-cache-dir \ + numpy==2.3.5 \ + pandas==2.2.3 \ + scipy==1.17.1 \ + sympy==1.14.0 \ + numba==0.66.0 \ + xarray==2025.4.0 \ + networkx==3.7 \ + scikit-learn==1.6.1 \ + scikit-image==0.25.2 \ + matplotlib==3.11.2 \ + seaborn==0.13.2 \ + plotly==6.0.1 \ + bokeh==3.9.1 \ + kaleido==1.3.0 \ + pillow==13.0.0 \ + imageio==2.37.3 \ + tifffile==2026.11.26 \ + opencv-python==4.11.0.86 \ + librosa==0.11.0 \ + soundfile==0.13.1 \ + spacy==3.8.14 \ + nltk==3.10.4 \ + textblob==0.19.0 \ + gensim==4.4.0 \ + beautifulsoup4==4.15.0 \ + lxml==6.2.1 \ + requests==2.33.0 \ + openpyxl==3.1.5 \ + xlrd==2.0.2 \ + python-docx==1.1.2 \ + xmltodict==1.0.4 \ + PyYAML==6.0.4 \ + tomlkit==0.15.0 \ + simplejson==4.3.0 \ + orjson==3.11.9 \ + SQLAlchemy==2.0.51 \ + rich==15.0.0 \ + typer==0.29.3 \ + click==8.5.1 \ + tqdm==4.70.1 \ + Jinja2==3.1.6 \ + pydantic==2.14.4 \ + python-dateutil==4.0.0 \ + pytz==2025.2 \ + psutil==7.2.2 \ + filetype==1.2.0 \ + python-slugify==8.0.4 \ + parsedatetime==2.6 \ + pytimeparse==1.1.8 \ + yq==4.1.2 \ + csvkit==2.2.0 + +RUN npm install -g zx@8.8.5 + +RUN if command -v fdfind >/dev/null; then ln -sfn "$(command -v fdfind)" /usr/local/bin/fd; fi && if command -v batcat >/dev/null; then ln -sfn "$(command -v batcat)" /usr/local/bin/bat; fi + +RUN groupadd --gid 1000 user && useradd --uid 1000 --gid 1000 --create-home --home-dir /home/user --shell /bin/bash user && mkdir -p /workspace /opt/sim-deps && chown user:user /workspace + +RUN node -e "if (Number(process.versions.node.split('.')[0]) !== 20) process.exit(1)" + +RUN node -e "if (process.versions.node !== '20.20.2') process.exit(1)" + +RUN python3 -c "import sys; raise SystemExit(0 if sys.version_info[:2] == (3, 13) else 1)" + +RUN for command in bash bat bc bzip2 convert csvcut csvtool curl dig dos2unix dpkg-deb fd ffmpeg file git gzip http install ip jq nc node npm python3 rg sha256sum ag sqlite3 tar tree unzip wget xmlstarlet xz yq 7z zip zx; do command -v "$command" >/dev/null || exit 1; done + +RUN fd --version >/dev/null && bat --version >/dev/null + +RUN python3 -c 'import importlib.metadata as metadata; packages = [{"package":"yq","version":"4.1.2"},{"package":"csvkit","version":"2.2.0"}]; assert all(metadata.version(item["package"]) == item["version"] for item in packages)' + +RUN node -e 'const { execFileSync } = require("node:child_process"); const { readFileSync } = require("node:fs"); const { join } = require("node:path"); const root = execFileSync("npm", ["root", "--global"], { encoding: "utf8" }).trim(); const packages = [{"package":"zx","version":"8.8.5"}]; for (const item of packages) { const manifest = JSON.parse(readFileSync(join(root, item.package, "package.json"), "utf8")); if (manifest.version !== item.version) process.exit(1) }' + +RUN python3 -c 'import importlib, importlib.metadata as metadata; packages = [{"distribution":"numpy","importName":"numpy"},{"distribution":"pandas","importName":"pandas"},{"distribution":"scipy","importName":"scipy"},{"distribution":"sympy","importName":"sympy"},{"distribution":"numba","importName":"numba"},{"distribution":"xarray","importName":"xarray"},{"distribution":"networkx","importName":"networkx"},{"distribution":"scikit-learn","importName":"sklearn"},{"distribution":"scikit-image","importName":"skimage"},{"distribution":"matplotlib","importName":"matplotlib"},{"distribution":"seaborn","importName":"seaborn"},{"distribution":"plotly","importName":"plotly"},{"distribution":"bokeh","importName":"bokeh"},{"distribution":"kaleido","importName":"kaleido"},{"distribution":"pillow","importName":"PIL"},{"distribution":"imageio","importName":"imageio"},{"distribution":"tifffile","importName":"tifffile"},{"distribution":"opencv-python","importName":"cv2"},{"distribution":"librosa","importName":"librosa"},{"distribution":"soundfile","importName":"soundfile"},{"distribution":"spacy","importName":"spacy"},{"distribution":"nltk","importName":"nltk"},{"distribution":"textblob","importName":"textblob"},{"distribution":"gensim","importName":"gensim"},{"distribution":"beautifulsoup4","importName":"bs4"},{"distribution":"lxml","importName":"lxml"},{"distribution":"requests","importName":"requests"},{"distribution":"openpyxl","importName":"openpyxl"},{"distribution":"xlrd","importName":"xlrd"},{"distribution":"python-docx","importName":"docx"},{"distribution":"xmltodict","importName":"xmltodict"},{"distribution":"PyYAML","importName":"yaml"},{"distribution":"tomlkit","importName":"tomlkit"},{"distribution":"simplejson","importName":"simplejson"},{"distribution":"orjson","importName":"orjson"},{"distribution":"SQLAlchemy","importName":"sqlalchemy"},{"distribution":"rich","importName":"rich"},{"distribution":"typer","importName":"typer"},{"distribution":"click","importName":"click"},{"distribution":"tqdm","importName":"tqdm"},{"distribution":"Jinja2","importName":"jinja2"},{"distribution":"pydantic","importName":"pydantic"},{"distribution":"python-dateutil","importName":"dateutil"},{"distribution":"pytz","importName":"pytz"},{"distribution":"psutil","importName":"psutil"},{"distribution":"filetype","importName":"filetype"},{"distribution":"python-slugify","importName":"slugify"},{"distribution":"parsedatetime","importName":"parsedatetime"},{"distribution":"pytimeparse","importName":"pytimeparse"}]; [(metadata.version(item["distribution"]), importlib.import_module(item["importName"])) for item in packages]' + +RUN python3 -c 'import importlib.metadata as metadata; packages = [{"distribution":"numpy","version":"2.3.5"},{"distribution":"pandas","version":"2.2.3"},{"distribution":"scipy","version":"1.17.1"},{"distribution":"sympy","version":"1.14.0"},{"distribution":"numba","version":"0.66.0"},{"distribution":"xarray","version":"2025.4.0"},{"distribution":"networkx","version":"3.7"},{"distribution":"scikit-learn","version":"1.6.1"},{"distribution":"scikit-image","version":"0.25.2"},{"distribution":"matplotlib","version":"3.11.2"},{"distribution":"seaborn","version":"0.13.2"},{"distribution":"plotly","version":"6.0.1"},{"distribution":"bokeh","version":"3.9.1"},{"distribution":"kaleido","version":"1.3.0"},{"distribution":"pillow","version":"13.0.0"},{"distribution":"imageio","version":"2.37.3"},{"distribution":"tifffile","version":"2026.11.26"},{"distribution":"opencv-python","version":"4.11.0.86"},{"distribution":"librosa","version":"0.11.0"},{"distribution":"soundfile","version":"0.13.1"},{"distribution":"spacy","version":"3.8.14"},{"distribution":"nltk","version":"3.10.4"},{"distribution":"textblob","version":"0.19.0"},{"distribution":"gensim","version":"4.4.0"},{"distribution":"beautifulsoup4","version":"4.15.0"},{"distribution":"lxml","version":"6.2.1"},{"distribution":"requests","version":"2.33.0"},{"distribution":"openpyxl","version":"3.1.5"},{"distribution":"xlrd","version":"2.0.2"},{"distribution":"python-docx","version":"1.1.2"},{"distribution":"xmltodict","version":"1.0.4"},{"distribution":"PyYAML","version":"6.0.4"},{"distribution":"tomlkit","version":"0.15.0"},{"distribution":"simplejson","version":"4.3.0"},{"distribution":"orjson","version":"3.11.9"},{"distribution":"SQLAlchemy","version":"2.0.51"},{"distribution":"rich","version":"15.0.0"},{"distribution":"typer","version":"0.29.3"},{"distribution":"click","version":"8.5.1"},{"distribution":"tqdm","version":"4.70.1"},{"distribution":"Jinja2","version":"3.1.6"},{"distribution":"pydantic","version":"2.14.4"},{"distribution":"python-dateutil","version":"4.0.0"},{"distribution":"pytz","version":"2025.2"},{"distribution":"psutil","version":"7.2.2"},{"distribution":"filetype","version":"1.2.0"},{"distribution":"python-slugify","version":"8.0.4"},{"distribution":"parsedatetime","version":"2.6"},{"distribution":"pytimeparse","version":"1.1.8"}]; assert all(metadata.version(item["distribution"]) == item["version"] for item in packages)' + +WORKDIR /home/user diff --git a/docker/sandbox-pi.Dockerfile b/docker/sandbox-pi.Dockerfile new file mode 100644 index 00000000000..ecc515f3174 --- /dev/null +++ b/docker/sandbox-pi.Dockerfile @@ -0,0 +1,54 @@ +# Generated by apps/sim/scripts/generate-sandbox-dockerfiles.ts — do not edit. +# Source: apps/sim/scripts/pi-sandbox-packages.ts +# Regenerate with `bun run generate:sandbox-dockerfiles`. +# +# Pi sandbox (Create PR, Review Code) for the Kubernetes sandbox provider. +# Root stays the default user: the in-sandbox agent, injected by the pod +# initContainer rather than baked in, runs as root and drops to `user` +# (uid/gid 1000, home /home/user) for user code. + +FROM python:3.13.14-slim-trixie@sha256:6771159cd4fa5d9bba1258caf0b82e6b73458c694d178ad97c5e925c2d0e1a91 + +ARG TARGETARCH + +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + curl \ + ca-certificates \ + gnupg \ + xz-utils \ + && rm -rf /var/lib/apt/lists/* + +RUN case "$TARGETARCH" in \ + amd64) node_arch=x64; node_sha256=cdeb8670a0c81f51b4dc4ac61919f9b1ad917b304bf8221eb939570663d240f8 ;; \ + arm64) node_arch=arm64; node_sha256=2babb9eb5264860d540849f4b064a6fbdebcdc323657d9d382ce23d313fd5e09 ;; \ + *) echo "unsupported TARGETARCH: $TARGETARCH" >&2; exit 1 ;; \ + esac \ + && archive="node-v22.23.5-linux-$node_arch.tar.xz" \ + && curl -fsSL --retry 3 --retry-all-errors "https://nodejs.org/dist/v22.23.5/$archive" -o "/tmp/$archive" \ + && echo "$node_sha256 /tmp/$archive" | sha256sum -c - \ + && tar -xJf "/tmp/$archive" -C /usr/local --strip-components=1 \ + && rm -f "/tmp/$archive" \ + && node -e "const [major, minor] = process.versions.node.split('.').map(Number); if (major < 22 || (major === 22 && minor < 19)) process.exit(1)" \ + && test "$(node --version)" = "v22.23.5" + +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + git \ + gh \ + openssh-client \ + ca-certificates \ + ripgrep \ + fd-find \ + && rm -rf /var/lib/apt/lists/* + +RUN npm install -g \ + bun@1.4.4 \ + @earendil-works/pi-coding-agent@1.5.0 \ + @earendil-works/pi-agent-core@1.5.0 \ + @earendil-works/pi-ai@1.5.0 \ + @earendil-works/pi-tui@1.5.0 + +RUN test "$(bun --version)" = "1.4.4" + +RUN groupadd --gid 1000 user && useradd --uid 1000 --gid 1000 --create-home --home-dir /home/user --shell /bin/bash user && mkdir -p /workspace /opt/sim-deps && chown user:user /workspace + +WORKDIR /home/user diff --git a/package.json b/package.json index 2519259013b..cebc2042a72 100644 --- a/package.json +++ b/package.json @@ -109,6 +109,8 @@ "generate:sdk-fixture-catalog": "bun run apps/sim/scripts/generate-sdk-fixture-catalog.ts", "check:sdk-fixture-catalog": "bun run apps/sim/scripts/generate-sdk-fixture-catalog.ts --check", "check:sdk-names-frozen": "bun run scripts/check-sdk-names-frozen.ts", + "generate:sandbox-dockerfiles": "bun run apps/sim/scripts/generate-sandbox-dockerfiles.ts", + "check:sandbox-dockerfiles": "bun run apps/sim/scripts/generate-sandbox-dockerfiles.ts --check", "generate:docs": "bun run scripts/generate-docs.ts", "check:docs": "bun run scripts/generate-docs.ts --check", "generate:deployment-config": "bun run scripts/generate-deployment-config.ts", From d55d2c2c1dfe0b2f05447f690aafd4317781a2e2 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 13:39:43 -0600 Subject: [PATCH 05/78] feat(sandbox): publish the sandbox images from their own workflow .github/workflows/sandbox-images.yml publishes the content-addressed refs in images.generated.json, off the core pipeline: nothing in ci.yml waits on it, and no mutable tag moves. - Pull requests build each changed image for amd64 and arm64 without publishing and run verify-sandbox-image.ts; a verification-only change rebuilds amd64. - Pushes to staging/main skip a kind whose index exists and carries this workflow's cosign signature. When both per-arch images are already published and signed, only the index is joined and signed; otherwise both architectures build natively, are verified, pushed as -, and signed and attested (provenance, SBOM) in the same leg, then joined under and signed. Registry errors fail the plan. Its own concurrency group, fail-fast off, timeouts on every job. The image action gains push/load inputs (defaults unchanged) for build-and-verify. --- .github/actions/image/action.yml | 16 +- .github/workflows/sandbox-images.yml | 395 +++++++++++++++++++++++++++ 2 files changed, 408 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/sandbox-images.yml diff --git a/.github/actions/image/action.yml b/.github/actions/image/action.yml index 73654b5fae4..8b8d4f5f607 100644 --- a/.github/actions/image/action.yml +++ b/.github/actions/image/action.yml @@ -17,8 +17,16 @@ inputs: description: Target platforms, e.g. linux/amd64. required: true tags: - description: Comma-separated list of tags to push. + description: Comma-separated list of tags to push (or to load, when push is off). required: true + push: + description: Push the tags to their registries. 'false' builds without publishing, for validation. + required: false + default: 'true' + load: + description: Load the built image into the runner's Docker daemon, so later steps can run it. + required: false + default: 'false' build-args: description: Newline-separated Docker build arguments. required: false @@ -78,7 +86,8 @@ runs: context: ${{ inputs.context }} file: ${{ inputs.file }} platforms: ${{ inputs.platforms }} - push: true + push: ${{ inputs.push }} + load: ${{ inputs.load }} tags: ${{ inputs.tags }} build-args: ${{ inputs.build-args }} target: ${{ inputs.target }} @@ -185,7 +194,8 @@ runs: context: ${{ inputs.context }} file: ${{ inputs.file }} platforms: ${{ inputs.platforms }} - push: true + push: ${{ inputs.push }} + load: ${{ inputs.load }} tags: ${{ inputs.tags }} build-args: ${{ inputs.build-args }} target: ${{ inputs.target }} diff --git a/.github/workflows/sandbox-images.yml b/.github/workflows/sandbox-images.yml new file mode 100644 index 00000000000..85bcc7113a1 --- /dev/null +++ b/.github/workflows/sandbox-images.yml @@ -0,0 +1,395 @@ +name: sandbox-images + +# Publishes the sandbox images Sim's self-hosted Kubernetes provider runs: +# ghcr.io/simstudioai/sandbox-function, sandbox-pi and sandbox-agent. +# +# Every image is content-addressed. `bun run generate:sandbox-dockerfiles` hashes each +# image's declared build inputs into its tag and commits the references to +# apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json, which the +# app and the Helm chart default to. A Sim release therefore references exact images +# and needs no per-release build: a push publishes a reference only when it is +# missing from GHCR or not yet signed by this workflow, and no mutable tag +# (latest, version) ever moves. +# +# Its own workflow rather than ci.yml jobs: the multi-arch builds run far longer than +# a deploy, ci.yml's concurrency group would hold the next deploy behind them, and +# nothing in ci.yml (promote, ghcr, attest, release) may wait on these images. Every +# change to an image's inputs changes images.generated.json (check:sandbox-dockerfiles +# fails otherwise), so that file is the path filter. +# +# Pull requests build each changed image for both architectures without publishing +# and verify it. A change to this workflow or the verification only rebuilds amd64. + +on: + push: + branches: [main, staging] + paths: + - 'apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json' + - '.github/workflows/sandbox-images.yml' + pull_request: + branches: [main, staging, dev] + paths: + - 'apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json' + - 'apps/sim/scripts/verify-sandbox-image.ts' + - 'apps/sim/scripts/function-sandbox-parity-manifest.ts' + - '.github/actions/image/**' + - '.github/workflows/sandbox-images.yml' + workflow_dispatch: {} + +permissions: + contents: read + +concurrency: + group: ${{ github.event_name == 'pull_request' && format('sandbox-images-pr-{0}', github.event.pull_request.number) || format('sandbox-images-{0}', github.ref_name) }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + # Decides which image/architecture legs to build. A pull request builds an image + # whose reference differs from the base branch's. A push or dispatch skips an + # image whose index exists and carries this workflow's signature, only joins and + # signs the index when both per-arch images are already published and signed (a + # publish that failed before signing), and otherwise builds both architectures. + plan: + name: plan + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + packages: read + pull-requests: read + outputs: + matrix: ${{ steps.plan.outputs.matrix }} + publish: ${{ steps.plan.outputs.publish }} + kinds: ${{ steps.plan.outputs.kinds }} + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + with: + persist-credentials: false + + - name: Login to GHCR + if: github.event_name != 'pull_request' + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4 + with: + registry: ghcr.io + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Install Cosign + if: github.event_name != 'pull_request' + uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4 + + - name: Plan builds + id: plan + env: + GH_TOKEN: ${{ github.token }} + EVENT_NAME: ${{ github.event_name }} + REPO: ${{ github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} + BASE_SHA: ${{ github.event.pull_request.base.sha }} + MANIFEST: apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json + run: | + set -euo pipefail + + # Succeeds when the reference exists, fails when the registry says it is + # unknown, and aborts on anything else: treating a registry hiccup as + # "absent" would only rebuild, but treating it as "present" would skip a + # publish, so neither is guessed. + image_exists() { + local ref="$1" attempt err absent=0 + for attempt in 1 2 3; do + if docker buildx imagetools inspect "$ref" > /dev/null 2> /tmp/inspect.err; then + return 0 + fi + err="$(cat /tmp/inspect.err)" + case "$err" in + *"not found"*|*MANIFEST_UNKNOWN*|*"no such manifest"*|*NAME_UNKNOWN*) absent=1 ;; + *) absent=0 ;; + esac + if [ "$attempt" -lt 3 ]; then + sleep "$((attempt * 3))" + fi + done + if [ "$absent" -eq 1 ]; then + return 1 + fi + echo "::error::Could not inspect ${ref} after 3 attempts: ${err}" >&2 + exit 1 + } + + # Signed by this workflow on any branch: build and publish sign with the + # runner's OIDC identity, which names this file and the ref it ran on. + # Any failure counts as unsigned, which only ever means more work. + is_signed() { + cosign verify \ + --certificate-identity-regexp "^https://github\\.com/${REPO}/\\.github/workflows/sandbox-images\\.yml@refs/heads/.+$" \ + --certificate-oidc-issuer https://token.actions.githubusercontent.com \ + "$1" > /dev/null 2>&1 + } + + # Published means the index exists and is signed, and so is each + # per-arch image under it. + is_published_and_signed() { + local ref="$1" + image_exists "$ref" && is_signed "$ref" + } + + arch_images_ready() { + local ref="$1" arch + for arch in amd64 arm64; do + image_exists "${ref}-${arch}" || return 1 + is_signed "${ref}-${arch}" || return 1 + done + } + + : > /tmp/legs.jsonl + : > /tmp/kinds.jsonl + add_legs() { + local kind="$1" ref="$2" arch + shift 2 + for arch in "$@"; do + jq -nc --arg kind "$kind" --arg ref "$ref" --arg arch "$arch" \ + '{kind: $kind, ref: $ref, arch: $arch}' >> /tmp/legs.jsonl + done + } + + if [ "$EVENT_NAME" = "pull_request" ]; then + publish=false + if base_json="$(gh api "repos/${REPO}/contents/${MANIFEST}?ref=${BASE_SHA}" --jq .content 2> /tmp/gh.err)"; then + base_manifest="$(printf '%s' "$base_json" | base64 -d)" + elif grep -q 'HTTP 404' /tmp/gh.err; then + base_manifest='{}' + else + echo "::error::Could not read the base branch's image references: $(cat /tmp/gh.err)" + exit 1 + fi + verification_changed=false + if gh api --paginate "repos/${REPO}/pulls/${PR_NUMBER}/files" --jq '.[].filename' \ + | grep -qE '^(\.github/workflows/sandbox-images\.yml|\.github/actions/image/.*|apps/sim/scripts/(verify-sandbox-image|function-sandbox-parity-manifest)\.ts)$'; then + verification_changed=true + fi + else + publish=true + fi + + for kind in $(jq -r 'keys_unsorted[]' "$MANIFEST"); do + ref="$(jq -r --arg kind "$kind" '.[$kind]' "$MANIFEST")" + if [ "$publish" = "true" ]; then + if is_published_and_signed "$ref"; then + echo "${ref} is published and signed; skipping." + continue + fi + if arch_images_ready "$ref"; then + echo "${ref}: both architectures are published and signed; publishing the index only." + else + echo "${ref} is missing or unsigned; building." + add_legs "$kind" "$ref" amd64 arm64 + fi + jq -nc --arg kind "$kind" --arg ref "$ref" '{kind: $kind, ref: $ref}' >> /tmp/kinds.jsonl + else + base_ref="$(printf '%s' "$base_manifest" | jq -r --arg kind "$kind" '.[$kind] // empty')" + if [ "$ref" != "$base_ref" ]; then + echo "${kind} inputs changed (${base_ref:-none} -> ${ref}); building both architectures." + add_legs "$kind" "$ref" amd64 arm64 + elif [ "$verification_changed" = "true" ]; then + echo "Verification changed; building ${kind} for amd64." + add_legs "$kind" "$ref" amd64 + fi + fi + done + + { + echo "publish=${publish}" + echo "matrix=$(jq -sc . /tmp/legs.jsonl)" + echo "kinds=$(jq -sc . /tmp/kinds.jsonl)" + } >> "$GITHUB_OUTPUT" + cat /tmp/legs.jsonl + + # One leg per image and architecture, each on a native runner. The image is built + # into the local daemon and verified before anything is pushed; the pushed + # `-` is then signed and attested in the same leg, so a later failure + # never leaves a published digest unsigned. + build: + name: build (${{ matrix.kind }}, ${{ matrix.arch }}) + needs: [plan] + if: needs.plan.outputs.matrix != '[]' + runs-on: ${{ (vars.CI_PROVIDER == '' || vars.CI_PROVIDER == 'blacksmith') && (matrix.arch == 'arm64' && 'blacksmith-4vcpu-ubuntu-2404-arm' || 'blacksmith-4vcpu-ubuntu-2404') || (matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-latest') }} + timeout-minutes: 60 + permissions: + contents: read + packages: write + id-token: write + attestations: write + artifact-metadata: write + strategy: + fail-fast: false + matrix: + include: ${{ fromJSON(needs.plan.outputs.matrix) }} + env: + PUBLISH: ${{ needs.plan.outputs.publish }} + ARCH_REF: ${{ matrix.ref }}-${{ matrix.arch }} + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + with: + persist-credentials: false + + - name: Login to Docker Hub + if: env.PUBLISH == 'true' + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Login to GHCR + if: env.PUBLISH == 'true' + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4 + with: + registry: ghcr.io + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build image + uses: ./.github/actions/image + with: + provider: ${{ vars.CI_PROVIDER }} + file: ./docker/sandbox-${{ matrix.kind }}.Dockerfile + platforms: linux/${{ matrix.arch }} + tags: ${{ env.ARCH_REF }} + push: 'false' + load: 'true' + + - name: Setup workspace + if: matrix.kind != 'agent' + uses: ./.github/actions/setup + with: + provider: ${{ vars.CI_PROVIDER }} + node-version: '' + + - name: Verify image contract + if: matrix.kind != 'agent' + run: bun run apps/sim/scripts/verify-sandbox-image.ts --kind ${{ matrix.kind }} --image "$ARCH_REF" + + - name: Push image + id: push + if: env.PUBLISH == 'true' + run: | + set -euo pipefail + docker push "$ARCH_REF" + digest="$(docker buildx imagetools inspect "$ARCH_REF" --format '{{json .Manifest}}' | jq -r '.digest // empty')" + if [ -z "$digest" ]; then + echo "::error::Pushed ${ARCH_REF} but could not resolve its digest" + exit 1 + fi + echo "image=${ARCH_REF%:*}" >> "$GITHUB_OUTPUT" + echo "digest=${digest}" >> "$GITHUB_OUTPUT" + + - name: Generate SBOM + if: env.PUBLISH == 'true' + uses: anchore/sbom-action@dfcb83b97731532d72be422cbc51ee64adb6fd56 # v0.24.4 + with: + image: ${{ env.ARCH_REF }} + format: spdx-json + output-file: sbom.spdx.json + upload-artifact: false + upload-release-assets: false + + - name: Attest SBOM + if: env.PUBLISH == 'true' + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ steps.push.outputs.image }} + subject-digest: ${{ steps.push.outputs.digest }} + sbom-path: sbom.spdx.json + push-to-registry: true + + - name: Attest build provenance + if: env.PUBLISH == 'true' + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ steps.push.outputs.image }} + subject-digest: ${{ steps.push.outputs.digest }} + push-to-registry: true + + - name: Install Cosign + if: env.PUBLISH == 'true' + uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4 + + - name: Sign image + if: env.PUBLISH == 'true' + env: + IMAGE: ${{ steps.push.outputs.image }} + DIGEST: ${{ steps.push.outputs.digest }} + run: cosign sign --yes "${IMAGE}@${DIGEST}" + + # Joins the two architectures under the content tag the app references, then signs + # and attests that index. A kind whose architecture legs did not both publish + # fails here instead of exposing a single-architecture reference. + publish: + name: publish (${{ matrix.kind }}) + needs: [plan, build] + if: >- + !cancelled() && + needs.plan.outputs.publish == 'true' && + needs.plan.outputs.kinds != '[]' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + packages: write + id-token: write + attestations: write + artifact-metadata: write + strategy: + fail-fast: false + matrix: + include: ${{ fromJSON(needs.plan.outputs.kinds) }} + steps: + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4 + with: + registry: ghcr.io + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Publish the multi-arch content tag + id: index + env: + REF: ${{ matrix.ref }} + run: | + set -euo pipefail + for arch in amd64 arm64; do + if ! docker buildx imagetools inspect "${REF}-${arch}" > /dev/null; then + echo "::error::${REF}-${arch} is not published; not publishing ${REF}" + exit 1 + fi + done + docker buildx imagetools create -t "$REF" "${REF}-amd64" "${REF}-arm64" + digest="$(docker buildx imagetools inspect "$REF" --format '{{json .Manifest}}' | jq -r '.digest // empty')" + if [ -z "$digest" ]; then + echo "::error::Published ${REF} but could not resolve its digest" + exit 1 + fi + echo "image=${REF%:*}" >> "$GITHUB_OUTPUT" + echo "digest=${digest}" >> "$GITHUB_OUTPUT" + { + echo "### sandbox-${{ matrix.kind }}" + echo + echo "\`${REF}@${digest}\`" + } >> "$GITHUB_STEP_SUMMARY" + + - name: Attest build provenance + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ steps.index.outputs.image }} + subject-digest: ${{ steps.index.outputs.digest }} + push-to-registry: true + + - name: Install Cosign + uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4 + + - name: Sign image + env: + IMAGE: ${{ steps.index.outputs.image }} + DIGEST: ${{ steps.index.outputs.digest }} + run: cosign sign --yes "${IMAGE}@${DIGEST}" From 0a72df4b8cf3af7ee35218b910601400fc3954b6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 13:47:09 -0600 Subject: [PATCH 06/78] feat(sandbox): add sim-sandbox-agent and its wire protocol sim-sandbox-agent is the daemon inside every self-hosted sandbox: an authenticated HTTP/1.1 + NDJSON API for launching processes and moving files, compiled by bun build --compile into one binary per Linux arch. @sim/sandbox-agent-protocol holds the constants, zod schemas, closed error codes, and the NDJSON encoder/decoder both sides share. The daemon checks a bearer token against its SHA-256 in constant time, starts children from a fixed base environment, runs each process in its own group (timeouts and output budgets kill the whole group), switches user processes to uid 1000 (creating the account when an image lacks it), launches a processKey at most once with seq-numbered reattach, verifies session CLI digests as the sandbox user before launch, bounds file reads to the size at open, and exits after killing every group when its lifetime ends. It can also copy itself to a shared volume (install) so a carrier image needs no shell. --- apps/sandbox-agent/package.json | 35 ++ apps/sandbox-agent/src/accounts.test.ts | 41 +++ apps/sandbox-agent/src/accounts.ts | 129 ++++++++ apps/sandbox-agent/src/auth.ts | 14 + apps/sandbox-agent/src/config.ts | 67 ++++ apps/sandbox-agent/src/files.test.ts | 153 +++++++++ apps/sandbox-agent/src/files.ts | 225 +++++++++++++ apps/sandbox-agent/src/install.test.ts | 38 +++ apps/sandbox-agent/src/install.ts | 30 ++ apps/sandbox-agent/src/lifetime.ts | 44 +++ apps/sandbox-agent/src/main.ts | 65 ++++ apps/sandbox-agent/src/processes.test.ts | 227 +++++++++++++ apps/sandbox-agent/src/processes.ts | 306 ++++++++++++++++++ apps/sandbox-agent/src/server.test.ts | 79 +++++ apps/sandbox-agent/src/server.ts | 293 +++++++++++++++++ apps/sandbox-agent/src/test-agent.ts | 143 ++++++++ apps/sandbox-agent/src/verify-cli.ts | 107 ++++++ apps/sandbox-agent/tsconfig.json | 10 + apps/sandbox-agent/vitest.config.ts | 21 ++ bun.lock | 34 ++ packages/sandbox-agent-protocol/package.json | 35 ++ .../sandbox-agent-protocol/src/constants.ts | 86 +++++ packages/sandbox-agent-protocol/src/index.ts | 9 + .../sandbox-agent-protocol/src/ndjson.test.ts | 29 ++ packages/sandbox-agent-protocol/src/ndjson.ts | 62 ++++ packages/sandbox-agent-protocol/src/paths.ts | 14 + .../sandbox-agent-protocol/src/schemas.ts | 211 ++++++++++++ packages/sandbox-agent-protocol/tsconfig.json | 5 + .../sandbox-agent-protocol/vitest.config.ts | 11 + 29 files changed, 2523 insertions(+) create mode 100644 apps/sandbox-agent/package.json create mode 100644 apps/sandbox-agent/src/accounts.test.ts create mode 100644 apps/sandbox-agent/src/accounts.ts create mode 100644 apps/sandbox-agent/src/auth.ts create mode 100644 apps/sandbox-agent/src/config.ts create mode 100644 apps/sandbox-agent/src/files.test.ts create mode 100644 apps/sandbox-agent/src/files.ts create mode 100644 apps/sandbox-agent/src/install.test.ts create mode 100644 apps/sandbox-agent/src/install.ts create mode 100644 apps/sandbox-agent/src/lifetime.ts create mode 100644 apps/sandbox-agent/src/main.ts create mode 100644 apps/sandbox-agent/src/processes.test.ts create mode 100644 apps/sandbox-agent/src/processes.ts create mode 100644 apps/sandbox-agent/src/server.test.ts create mode 100644 apps/sandbox-agent/src/server.ts create mode 100644 apps/sandbox-agent/src/test-agent.ts create mode 100644 apps/sandbox-agent/src/verify-cli.ts create mode 100644 apps/sandbox-agent/tsconfig.json create mode 100644 apps/sandbox-agent/vitest.config.ts create mode 100644 packages/sandbox-agent-protocol/package.json create mode 100644 packages/sandbox-agent-protocol/src/constants.ts create mode 100644 packages/sandbox-agent-protocol/src/index.ts create mode 100644 packages/sandbox-agent-protocol/src/ndjson.test.ts create mode 100644 packages/sandbox-agent-protocol/src/ndjson.ts create mode 100644 packages/sandbox-agent-protocol/src/paths.ts create mode 100644 packages/sandbox-agent-protocol/src/schemas.ts create mode 100644 packages/sandbox-agent-protocol/tsconfig.json create mode 100644 packages/sandbox-agent-protocol/vitest.config.ts diff --git a/apps/sandbox-agent/package.json b/apps/sandbox-agent/package.json new file mode 100644 index 00000000000..a6e94932f84 --- /dev/null +++ b/apps/sandbox-agent/package.json @@ -0,0 +1,35 @@ +{ + "name": "@sim/sandbox-agent", + "version": "0.1.0", + "private": true, + "license": "Apache-2.0", + "type": "module", + "engines": { + "bun": ">=1.4.4" + }, + "scripts": { + "dev": "bun src/main.ts", + "build": "bun run build:linux-x64 && bun run build:linux-arm64", + "build:linux-x64": "NODE_ENV=production bun build --compile --minify --target=bun-linux-x64 src/main.ts --outfile dist/linux-x64/sim-sandbox-agent", + "build:linux-arm64": "NODE_ENV=production bun build --compile --minify --target=bun-linux-arm64 src/main.ts --outfile dist/linux-arm64/sim-sandbox-agent", + "type-check": "tsc --noEmit", + "lint": "biome check --write --unsafe .", + "lint:check": "biome check .", + "format": "biome format --write .", + "format:check": "biome format .", + "test": "vitest run" + }, + "dependencies": { + "@sim/logger": "workspace:*", + "@sim/sandbox-agent-protocol": "workspace:*", + "@sim/utils": "workspace:*", + "zod": "4.3.6" + }, + "devDependencies": { + "@sim/tsconfig": "workspace:*", + "@types/bun": "1.4.4", + "@types/node": "24.19.2", + "typescript": "^7.0.2", + "vitest": "^5.1.0" + } +} diff --git a/apps/sandbox-agent/src/accounts.test.ts b/apps/sandbox-agent/src/accounts.test.ts new file mode 100644 index 00000000000..db75d8d10b9 --- /dev/null +++ b/apps/sandbox-agent/src/accounts.test.ts @@ -0,0 +1,41 @@ +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { ensureSandboxUserEntry } from '@/accounts' + +let root: string + +beforeEach(() => { + root = mkdtempSync(path.join(tmpdir(), 'sim-sandbox-accounts-')) + mkdirSync(path.join(root, 'etc')) +}) + +afterEach(() => { + rmSync(root, { recursive: true, force: true }) +}) + +describe('ensureSandboxUserEntry', () => { + it('adds the sandbox user once, however many times the agent starts', () => { + writeFileSync(path.join(root, 'etc/passwd'), 'root:x:0:0:root:/root:/bin/bash') + writeFileSync(path.join(root, 'etc/group'), 'root:x:0:\n') + writeFileSync(path.join(root, 'etc/shadow'), 'root:*:1::::::\n') + + expect(ensureSandboxUserEntry(root)).toEqual({ uid: 1000, gid: 1000, home: '/home/user' }) + ensureSandboxUserEntry(root) + + const passwd = readFileSync(path.join(root, 'etc/passwd'), 'utf8') + expect(passwd).toBe('root:x:0:0:root:/root:/bin/bash\nuser:x:1000:1000::/home/user:/bin/bash\n') + expect(readFileSync(path.join(root, 'etc/group'), 'utf8')).toBe('root:x:0:\nuser:x:1000:\n') + expect(readFileSync(path.join(root, 'etc/shadow'), 'utf8').split('\n')).toContain( + 'user:!:1::::::' + ) + }) + + it('keeps an existing sandbox user as the image defines it', () => { + const passwd = 'user:x:1001:1002::/srv/user:/bin/sh\n' + writeFileSync(path.join(root, 'etc/passwd'), passwd) + expect(ensureSandboxUserEntry(root)).toEqual({ uid: 1001, gid: 1002, home: '/srv/user' }) + expect(readFileSync(path.join(root, 'etc/passwd'), 'utf8')).toBe(passwd) + }) +}) diff --git a/apps/sandbox-agent/src/accounts.ts b/apps/sandbox-agent/src/accounts.ts new file mode 100644 index 00000000000..4a4dc92fdbc --- /dev/null +++ b/apps/sandbox-agent/src/accounts.ts @@ -0,0 +1,129 @@ +import { appendFileSync, chownSync, existsSync, mkdirSync, readFileSync, statSync } from 'node:fs' +import { homedir, userInfo } from 'node:os' +import path from 'node:path' +import { createLogger } from '@sim/logger' +import { SANDBOX_AGENT_USER } from '@sim/sandbox-agent-protocol' +import { getErrorMessage } from '@sim/utils/errors' + +const logger = createLogger('SandboxAgentAccounts') + +/** Who a child runs as. `uid`/`gid` are present only when the agent switches identity. */ +export interface ProcessIdentity { + name: string + home: string + uid?: number + gid?: number +} + +/** Maps a request's `user` to the identity its process runs as. */ +export interface Accounts { + /** True when the agent is root and so can run `user` processes as the sandbox user. */ + readonly privileged: boolean + identityFor(user: 'root' | 'user'): ProcessIdentity +} + +interface SandboxUserEntry { + uid: number + gid: number + home: string +} + +function findPasswdEntry(passwd: string, name: string): SandboxUserEntry | null { + for (const line of passwd.split('\n')) { + const fields = line.split(':') + if (fields[0] !== name || fields.length < 7) continue + const uid = Number(fields[2]) + const gid = Number(fields[3]) + if (!Number.isInteger(uid) || !Number.isInteger(gid)) continue + return { uid, gid, home: fields[5] || SANDBOX_AGENT_USER.home } + } + return null +} + +function hasEntry(contents: string, name: string): boolean { + return contents.split('\n').some((line) => line.split(':')[0] === name) +} + +function appendLine(file: string, line: string): void { + const current = existsSync(file) ? readFileSync(file, 'utf8') : '' + appendFileSync(file, `${current && !current.endsWith('\n') ? '\n' : ''}${line}\n`) +} + +/** + * Makes sure the account database under `rootDir` names the sandbox user, adding it (uid/gid + * 1000, home `/home/user`, as in E2B's images) when absent. Idempotent: an existing `user` entry + * is used as it is, whatever its uid. Writes the files directly rather than running `useradd`, + * which arbitrary images need not ship. + */ +export function ensureSandboxUserEntry(rootDir: string): SandboxUserEntry { + const etc = path.join(rootDir, 'etc') + const passwdFile = path.join(etc, 'passwd') + const existing = existsSync(passwdFile) + ? findPasswdEntry(readFileSync(passwdFile, 'utf8'), SANDBOX_AGENT_USER.name) + : null + if (existing) return existing + + const { name, uid, gid, home } = SANDBOX_AGENT_USER + mkdirSync(etc, { recursive: true }) + appendLine(passwdFile, `${name}:x:${uid}:${gid}::${home}:/bin/bash`) + const groupFile = path.join(etc, 'group') + if (!existsSync(groupFile) || !hasEntry(readFileSync(groupFile, 'utf8'), name)) { + appendLine(groupFile, `${name}:x:${gid}:`) + } + const shadowFile = path.join(etc, 'shadow') + if (existsSync(shadowFile) && !hasEntry(readFileSync(shadowFile, 'utf8'), name)) { + appendLine(shadowFile, `${name}:!:1::::::`) + } + return { uid, gid, home } +} + +/** + * Resolves the identities processes run as. + * + * As root (production), `user` is the sandbox user: its account entry and home directory are + * created if missing, and the agent drops its own supplementary groups so a child switched to + * uid 1000 cannot keep root's groups. Bun's spawn clears them too when it switches uid; dropping + * them here keeps that true whatever the runtime does. A read-only `/etc` is tolerated: the switch is by numeric + * id and `HOME` is set explicitly, so the entry is a convenience for tools like `whoami`. + * + * Unprivileged, the agent cannot switch identity, so both `root` and `user` run as the agent + * itself with its own home. That is never more privilege than requested: it is how the agent runs + * on a developer machine or in CI. + */ +export function resolveAccounts(): Accounts { + if (process.getuid?.() !== 0) { + const self: ProcessIdentity = { + name: userInfo().username, + home: process.env.HOME || homedir(), + } + logger.warn('Sandbox agent is unprivileged; every process runs as the agent user') + return { privileged: false, identityFor: () => self } + } + + let entry: SandboxUserEntry = { + uid: SANDBOX_AGENT_USER.uid, + gid: SANDBOX_AGENT_USER.gid, + home: SANDBOX_AGENT_USER.home, + } + try { + entry = ensureSandboxUserEntry('/') + } catch (error) { + logger.warn('Could not record the sandbox user in /etc', { error: getErrorMessage(error) }) + } + mkdirSync(entry.home, { recursive: true }) + const homeStat = statSync(entry.home) + if (homeStat.uid !== entry.uid || homeStat.gid !== entry.gid) { + chownSync(entry.home, entry.uid, entry.gid) + } + if (!process.setgroups) throw new Error('Cannot drop the agent supplementary groups') + process.setgroups([]) + + const root: ProcessIdentity = { name: 'root', home: '/root' } + const user: ProcessIdentity = { + name: SANDBOX_AGENT_USER.name, + home: entry.home, + uid: entry.uid, + gid: entry.gid, + } + return { privileged: true, identityFor: (requested) => (requested === 'root' ? root : user) } +} diff --git a/apps/sandbox-agent/src/auth.ts b/apps/sandbox-agent/src/auth.ts new file mode 100644 index 00000000000..be6a07cd36e --- /dev/null +++ b/apps/sandbox-agent/src/auth.ts @@ -0,0 +1,14 @@ +import { createHash, timingSafeEqual } from 'node:crypto' + +/** + * Checks an RFC 6750 `Authorization: Bearer ` header against the configured digest. + * Hashing first makes both operands 32 bytes, so `timingSafeEqual` never sees a length mismatch + * and the comparison time says nothing about the token. + */ +export function isAuthorized(header: string | null, expectedSha256: Buffer): boolean { + if (!header) return false + const match = /^Bearer ([\x21-\x7e]+)$/.exec(header) + if (!match) return false + const presented = createHash('sha256').update(match[1], 'utf8').digest() + return timingSafeEqual(presented, expectedSha256) +} diff --git a/apps/sandbox-agent/src/config.ts b/apps/sandbox-agent/src/config.ts new file mode 100644 index 00000000000..1b5d2f282ae --- /dev/null +++ b/apps/sandbox-agent/src/config.ts @@ -0,0 +1,67 @@ +import { + SANDBOX_AGENT_ENV_PREFIX, + SANDBOX_AGENT_EXPIRES_AT_ENV, + SANDBOX_AGENT_HOST_ENV, + SANDBOX_AGENT_PORT, + SANDBOX_AGENT_PORT_ENV, + SANDBOX_AGENT_TOKEN_SHA256_ENV, +} from '@sim/sandbox-agent-protocol' + +/** Everything the agent reads from its environment, captured once at startup. */ +export interface AgentConfig { + tokenSha256: Buffer + expiresAtMs?: number + host: string + port: number + /** Environment every child starts from, before the request's own `envs`. */ + baseEnvironment: Record +} + +const DEFAULT_PATH = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' + +/** Variables a child inherits from the agent; everything else in the agent's env stays behind. */ +const INHERITED_VARIABLES = ['PATH', 'LANG', 'TZ'] as const + +/** + * Reads the agent's configuration and then deletes every `SIM_SANDBOX_*` variable from its own + * environment, so nothing later in the process (a child spawned without an explicit env, a + * diagnostic dump) can pass them on. Throws on a missing or malformed token hash: an agent that + * cannot authenticate must not start. + */ +export function readAgentConfig(env: NodeJS.ProcessEnv): AgentConfig { + const tokenHex = env[SANDBOX_AGENT_TOKEN_SHA256_ENV]?.trim().toLowerCase() ?? '' + if (!/^[0-9a-f]{64}$/.test(tokenHex)) { + throw new Error(`${SANDBOX_AGENT_TOKEN_SHA256_ENV} must be a hex SHA-256 digest`) + } + + const expiresRaw = env[SANDBOX_AGENT_EXPIRES_AT_ENV]?.trim() + const expiresAtMs = expiresRaw ? Number(expiresRaw) : undefined + if (expiresAtMs !== undefined && (!Number.isSafeInteger(expiresAtMs) || expiresAtMs <= 0)) { + throw new Error(`${SANDBOX_AGENT_EXPIRES_AT_ENV} must be epoch milliseconds`) + } + + const portRaw = env[SANDBOX_AGENT_PORT_ENV]?.trim() + const port = portRaw ? Number(portRaw) : SANDBOX_AGENT_PORT + if (!Number.isInteger(port) || port < 0 || port > 65_535) { + throw new Error(`${SANDBOX_AGENT_PORT_ENV} must be a TCP port`) + } + + const baseEnvironment: Record = { PATH: DEFAULT_PATH } + for (const name of INHERITED_VARIABLES) { + const value = env[name] + if (value) baseEnvironment[name] = value + } + + const config: AgentConfig = { + tokenSha256: Buffer.from(tokenHex, 'hex'), + ...(expiresAtMs !== undefined ? { expiresAtMs } : {}), + host: env[SANDBOX_AGENT_HOST_ENV]?.trim() || '0.0.0.0', + port, + baseEnvironment, + } + + for (const name of Object.keys(env)) { + if (name.startsWith(SANDBOX_AGENT_ENV_PREFIX)) delete env[name] + } + return config +} diff --git a/apps/sandbox-agent/src/files.test.ts b/apps/sandbox-agent/src/files.test.ts new file mode 100644 index 00000000000..748098504cf --- /dev/null +++ b/apps/sandbox-agent/src/files.test.ts @@ -0,0 +1,153 @@ +import { mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import { + directoryEntrySchema, + SANDBOX_AGENT_FILE_SIZE_HEADER, + SANDBOX_AGENT_ROUTES, + sandboxAgentProcessSignalPath, +} from '@sim/sandbox-agent-protocol' +import { generateId } from '@sim/utils/id' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { readEvents, startTestAgent, type TestAgent } from '@/test-agent' + +let agent: TestAgent + +beforeAll(async () => { + agent = await startTestAgent() +}) + +afterAll(async () => { + await agent.stop() +}) + +const fileRoute = (route: string, query: Record) => + `${route}?${new URLSearchParams(query).toString()}` + +describe('path validation', () => { + it.each([ + ['a relative path', 'tmp/file'], + ['a NUL byte', '/tmp/a\0b'], + ['a parent segment', '/tmp/../etc/passwd'], + ])('refuses %s', async (_, target) => { + const response = await agent.request(fileRoute(SANDBOX_AGENT_ROUTES.fileStat, { path: target })) + expect(response.status).toBe(400) + expect(await response.json()).toMatchObject({ error: { code: 'invalid_path' } }) + }) +}) + +describe('file reads', () => { + it('refuses a file larger than maxBytes before sending any byte', async () => { + const target = path.join(agent.root, `big-${generateId()}`) + writeFileSync(target, 'x'.repeat(100)) + const response = await agent.request( + fileRoute(SANDBOX_AGENT_ROUTES.files, { path: target, maxBytes: '10' }) + ) + expect(response.status).toBe(413) + expect(await response.json()).toMatchObject({ + error: { code: 'too_large', observedBytes: 100 }, + }) + }) + + it('never sends more than the size at open while the file keeps growing', async () => { + const target = path.join(agent.root, `growing-${generateId()}`) + const maxBytes = 64 * 1024 * 1024 + writeFileSync(target, Buffer.alloc(32 * 1024 * 1024, 'a')) + const writerKey = generateId() + const writer = await agent.startProcess({ + processKey: writerKey, + shell: `while true; do head -c 1048576 /dev/zero >> ${target}; done`, + timeoutMs: 20_000, + }) + try { + const response = await agent.request( + fileRoute(SANDBOX_AGENT_ROUTES.files, { path: target, maxBytes: String(maxBytes) }) + ) + expect(response.status).toBe(200) + const declared = Number(response.headers.get(SANDBOX_AGENT_FILE_SIZE_HEADER)) + const body = Buffer.from(await response.arrayBuffer()) + expect(body.byteLength).toBe(declared) + expect(body.byteLength).toBeLessThanOrEqual(maxBytes) + expect(statSync(target).size).toBeGreaterThan(body.byteLength) + } finally { + await agent.request(sandboxAgentProcessSignalPath(writerKey), { + method: 'POST', + body: JSON.stringify({ signal: 'SIGKILL' }), + }) + await readEvents(writer) + } + }) + + it('refuses to read a directory as a file', async () => { + const response = await agent.request( + fileRoute(SANDBOX_AGENT_ROUTES.files, { path: agent.root }) + ) + expect(response.status).toBe(400) + expect(await response.json()).toMatchObject({ error: { code: 'not_a_file' } }) + }) +}) + +describe('file writes', () => { + it('creates parents and replaces the file whole, leaving no staging file behind', async () => { + const directory = path.join(agent.root, `nested-${generateId()}`, 'a', 'b') + const target = path.join(directory, 'file.txt') + for (const content of ['first version', 'second']) { + const response = await agent.request( + fileRoute(SANDBOX_AGENT_ROUTES.files, { path: target }), + { + method: 'PUT', + body: content, + } + ) + expect(response.status).toBe(204) + } + expect(readFileSync(target, 'utf8')).toBe('second') + expect(statSync(target).mode & 0o777).toBe(0o644) + expect(readdirSync(directory)).toEqual(['file.txt']) + }) + + it('deletes a file and reports a missing one as not found', async () => { + const target = path.join(agent.root, `doomed-${generateId()}`) + writeFileSync(target, 'x') + const route = fileRoute(SANDBOX_AGENT_ROUTES.files, { path: target }) + expect((await agent.request(route, { method: 'DELETE' })).status).toBe(204) + const again = await agent.request(route, { method: 'DELETE' }) + expect(again.status).toBe(404) + }) +}) + +describe('directory listing', () => { + it('follows symlinks, includes directories, and skips dangling links', async () => { + const listed = path.join(agent.root, `listed-${generateId()}`) + const outside = path.join(agent.root, `outside-${generateId()}`) + mkdirSync(path.join(listed, 'sub'), { recursive: true }) + mkdirSync(outside) + writeFileSync(path.join(listed, 'sub', 'deep.txt'), 'deep') + writeFileSync(path.join(outside, 'target.txt'), 'linked bytes') + symlinkSync(path.join(outside, 'target.txt'), path.join(listed, 'file-link')) + symlinkSync(outside, path.join(listed, 'dir-link')) + symlinkSync(path.join(outside, 'missing'), path.join(listed, 'dangling')) + + const response = await agent.request( + fileRoute(SANDBOX_AGENT_ROUTES.fileList, { path: listed, depth: '2' }) + ) + const { entries } = (await response.json()) as { entries: unknown[] } + const parsed = entries.map((entry) => directoryEntrySchema.parse(entry)) + const byPath = new Map(parsed.map((entry) => [path.relative(listed, entry.path), entry])) + expect([...byPath.keys()].sort()).toEqual( + ['dir-link', 'dir-link/target.txt', 'file-link', 'sub', 'sub/deep.txt'].sort() + ) + expect(byPath.get('file-link')).toMatchObject({ kind: 'file', size: 'linked bytes'.length }) + expect(byPath.get('dir-link')).toMatchObject({ kind: 'directory' }) + }) + + it('stops at the requested depth while still reporting the directory at the limit', async () => { + const listed = path.join(agent.root, `shallow-${generateId()}`) + mkdirSync(path.join(listed, 'a', 'b'), { recursive: true }) + writeFileSync(path.join(listed, 'a', 'b', 'leaf.txt'), 'x') + const response = await agent.request( + fileRoute(SANDBOX_AGENT_ROUTES.fileList, { path: listed, depth: '1' }) + ) + const { entries } = (await response.json()) as { entries: Array<{ path: string }> } + expect(entries.map((entry) => path.relative(listed, entry.path))).toEqual(['a']) + }) +}) diff --git a/apps/sandbox-agent/src/files.ts b/apps/sandbox-agent/src/files.ts new file mode 100644 index 00000000000..4ea5b1bc63c --- /dev/null +++ b/apps/sandbox-agent/src/files.ts @@ -0,0 +1,225 @@ +import { constants } from 'node:fs' +import { type FileHandle, mkdir, open, readdir, rename, rm, stat, unlink } from 'node:fs/promises' +import path from 'node:path' +import { + type FileStatResponse, + type ListFilesResponse, + SANDBOX_AGENT_MAX_LIST_ENTRIES, + type SandboxAgentErrorCode, +} from '@sim/sandbox-agent-protocol' +import { generateShortId } from '@sim/utils/id' +import type { ProcessIdentity } from '@/accounts' + +const READ_CHUNK_BYTES = 64 * 1024 + +/** A file operation failure the server maps to an HTTP status and protocol error code. */ +export class FileOperationError extends Error { + constructor( + readonly code: SandboxAgentErrorCode, + message: string, + readonly observedBytes?: number + ) { + super(message) + this.name = 'FileOperationError' + } +} + +function errnoOf(error: unknown): string | undefined { + return error instanceof Error && 'code' in error && typeof error.code === 'string' + ? error.code + : undefined +} + +/** Translates a filesystem errno into the protocol's closed error set; rethrows anything else. */ +function translate(error: unknown, target: string): never { + switch (errnoOf(error)) { + case 'ENOENT': + throw new FileOperationError('not_found', `No such file or directory: ${target}`) + case 'ENOTDIR': + throw new FileOperationError( + 'not_a_directory', + `A path component is not a directory: ${target}` + ) + case 'EISDIR': + throw new FileOperationError('not_a_file', `Path is a directory: ${target}`) + case 'EACCES': + case 'EPERM': + throw new FileOperationError('permission_denied', `Permission denied: ${target}`) + case 'ELOOP': + throw new FileOperationError('invalid_path', `Too many symbolic links: ${target}`) + default: + throw error + } +} + +export async function statFile(target: string): Promise { + const info = await stat(target).catch((error: unknown) => translate(error, target)) + return { + size: info.size, + kind: info.isFile() ? 'file' : info.isDirectory() ? 'directory' : 'other', + } +} + +/** + * Opens a regular file for reading and returns a stream of exactly the size it had when opened. + * + * Read-limit semantics: when `maxBytes` is given and the file is larger at open, the read is + * refused with `too_large` (HTTP 413) before any byte is sent. Otherwise the response declares + * that size in `X-Sim-File-Size` and sends exactly that many bytes from the opened descriptor, + * so bytes appended later are never sent and the response can never exceed the limit. A file + * that shrinks mid-read cannot fill the declared size, so the stream errors, the connection is + * cut, and the client sees a failed or short body rather than a success. Replacing the path after open is invisible, since + * the descriptor keeps the original inode. + */ +export async function openFileForRead( + target: string, + maxBytes: number | undefined +): Promise<{ size: number; body: ReadableStream }> { + const handle = await open(target, constants.O_RDONLY | constants.O_NONBLOCK).catch( + (error: unknown) => translate(error, target) + ) + let size: number + try { + const info = await handle.stat() + if (!info.isFile()) throw new FileOperationError('not_a_file', `Not a regular file: ${target}`) + size = info.size + if (maxBytes !== undefined && size > maxBytes) { + throw new FileOperationError( + 'too_large', + `File is ${size} bytes, over the ${maxBytes}-byte limit`, + size + ) + } + } catch (error) { + await handle.close() + throw error + } + return { size, body: sizedFileStream(handle, size) } +} + +function sizedFileStream(handle: FileHandle, size: number): ReadableStream { + let position = 0 + let closed = false + const close = async () => { + if (closed) return + closed = true + await handle.close() + } + return new ReadableStream({ + async pull(controller) { + if (position >= size) { + await close() + controller.close() + return + } + const buffer = new Uint8Array(Math.min(READ_CHUNK_BYTES, size - position)) + const { bytesRead } = await handle.read(buffer, 0, buffer.byteLength, position) + if (bytesRead === 0) { + await close() + controller.error(new Error('File shrank while it was being read')) + return + } + position += bytesRead + controller.enqueue(buffer.subarray(0, bytesRead)) + }, + async cancel() { + await close() + }, + }) +} + +/** Creates `directory` and any missing parents, handing each new one to `owner`. */ +async function makeParents(directory: string, owner: ProcessIdentity): Promise { + const first = await mkdir(directory, { recursive: true }).catch((error: unknown) => + translate(error, directory) + ) + if (first === undefined || owner.uid === undefined || owner.gid === undefined) return + const created: string[] = [] + for (let current = directory; ; current = path.dirname(current)) { + created.push(current) + if (current === first || current === path.dirname(current)) break + } + for (const entry of created.reverse()) { + const handle = await open(entry, constants.O_RDONLY | constants.O_DIRECTORY) + try { + await handle.chown(owner.uid, owner.gid) + } finally { + await handle.close() + } + } +} + +/** + * Streams `body` into a sibling temp file and renames it over `target`, so a reader never sees + * a partial file and a failed upload leaves the previous content. Missing parents are created. + * The file is mode 0644 and, when the agent switches identities, owned by `owner`. + */ +export async function writeFileAtomically( + target: string, + body: ReadableStream | null, + owner: ProcessIdentity +): Promise { + const directory = path.dirname(target) + await makeParents(directory, owner) + const staged = path.join(directory, `.${path.basename(target)}.sim-upload-${generateShortId(12)}`) + const handle = await open(staged, 'wx', 0o644).catch((error: unknown) => translate(error, target)) + let committed = false + try { + if (body) { + for await (const chunk of body) await handle.write(chunk) + } + await handle.chmod(0o644) + if (owner.uid !== undefined && owner.gid !== undefined) { + await handle.chown(owner.uid, owner.gid) + } + await handle.close() + await rename(staged, target).catch((error: unknown) => translate(error, target)) + committed = true + } finally { + if (!committed) { + await handle.close().catch(() => {}) + await unlink(staged).catch(() => {}) + } + } +} + +export async function removePath(target: string): Promise { + await stat(target).catch((error: unknown) => translate(error, target)) + await rm(target, { recursive: true }).catch((error: unknown) => translate(error, target)) +} + +/** + * Lists `root` to `depth` levels, following symlinks and reporting what they resolve to. A + * dangling link or an entry that is neither a file nor a directory is skipped. Directories are + * included, since one at the depth limit is the caller's only evidence the walk was cut short. + */ +export async function listDirectory(root: string, depth: number): Promise { + const info = await stat(root).catch((error: unknown) => translate(error, root)) + if (!info.isDirectory()) { + throw new FileOperationError('not_a_directory', `Not a directory: ${root}`) + } + const entries: ListFilesResponse['entries'] = [] + const walk = async (directory: string, level: number): Promise => { + const names = await readdir(directory).catch((error: unknown) => translate(error, directory)) + for (const name of names) { + const entryPath = path.join(directory, name) + const entryInfo = await stat(entryPath).catch(() => null) + if (!entryInfo || (!entryInfo.isFile() && !entryInfo.isDirectory())) continue + if (entries.length >= SANDBOX_AGENT_MAX_LIST_ENTRIES) { + throw new FileOperationError( + 'too_large', + `Listing exceeds ${SANDBOX_AGENT_MAX_LIST_ENTRIES} entries` + ) + } + const isDirectory = entryInfo.isDirectory() + entries.push({ + path: entryPath, + kind: isDirectory ? 'directory' : 'file', + size: entryInfo.size, + }) + if (isDirectory && level < depth) await walk(entryPath, level + 1) + } + } + await walk(root, 1) + return { entries } +} diff --git a/apps/sandbox-agent/src/install.test.ts b/apps/sandbox-agent/src/install.test.ts new file mode 100644 index 00000000000..fe80de3328f --- /dev/null +++ b/apps/sandbox-agent/src/install.test.ts @@ -0,0 +1,38 @@ +import { spawnSync } from 'node:child_process' +import { mkdtempSync, rmSync, statSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' + +let directory: string + +beforeAll(() => { + directory = mkdtempSync(path.join(tmpdir(), 'sim-sandbox-agent-install-')) +}) + +afterAll(() => { + rmSync(directory, { recursive: true, force: true }) +}) + +describe('install', () => { + it('copies the compiled binary to an executable destination that runs as the agent', () => { + const binary = path.join(directory, 'carrier') + const build = spawnSync( + 'bun', + ['build', '--compile', path.resolve(__dirname, 'main.ts'), '--outfile', binary], + // Bun inlines NODE_ENV at build time; the release build sets production, as here. + { encoding: 'utf8', env: { ...process.env, NODE_ENV: 'production' } } + ) + expect(build.status, build.stderr).toBe(0) + + const destination = path.join(directory, 'shared', 'sim-sandbox-agent') + spawnSync('mkdir', ['-p', path.dirname(destination)]) + const install = spawnSync(binary, ['install', destination], { encoding: 'utf8' }) + expect(install.status, install.stderr).toBe(0) + expect(statSync(destination).mode & 0o777).toBe(0o755) + + const run = spawnSync(destination, [], { encoding: 'utf8', env: { PATH: '/usr/bin:/bin' } }) + expect(run.status).toBe(1) + expect(run.stdout + run.stderr).toContain('SIM_SANDBOX_AGENT_TOKEN_SHA256') + }) +}) diff --git a/apps/sandbox-agent/src/install.ts b/apps/sandbox-agent/src/install.ts new file mode 100644 index 00000000000..37f90162f8b --- /dev/null +++ b/apps/sandbox-agent/src/install.ts @@ -0,0 +1,30 @@ +import { chmod, copyFile, rename, rm } from 'node:fs/promises' +import path from 'node:path' +import { generateShortId } from '@sim/utils/id' + +/** True when running as a `bun build --compile` binary rather than from source. */ +export function isCompiledBinary(): boolean { + return Bun.main.startsWith('/$bunfs/') +} + +/** + * Copies this binary to `destination` (staged beside it, then renamed) with mode 0755. The agent + * image has no shell or `cp`, so a Kubernetes init container runs + * `/sim-sandbox-agent install /opt/sim-agent/sim-sandbox-agent` to hand the binary to the sandbox + * container through a shared volume, letting any image run the agent without baking it in. + */ +export async function installSelf(destination: string): Promise { + if (!isCompiledBinary()) throw new Error('install runs only from the compiled agent binary') + if (!path.isAbsolute(destination)) throw new Error('install needs an absolute destination path') + const staged = path.join( + path.dirname(destination), + `.${path.basename(destination)}.${generateShortId(12)}` + ) + try { + await copyFile(process.execPath, staged) + await chmod(staged, 0o755) + await rename(staged, destination) + } finally { + await rm(staged, { force: true }) + } +} diff --git a/apps/sandbox-agent/src/lifetime.ts b/apps/sandbox-agent/src/lifetime.ts new file mode 100644 index 00000000000..985cd3c546d --- /dev/null +++ b/apps/sandbox-agent/src/lifetime.ts @@ -0,0 +1,44 @@ +/** `setTimeout` cannot wait longer than this; a longer deadline is re-armed in steps. */ +const MAX_TIMER_MS = 2 ** 31 - 1 + +/** + * The sandbox's self-termination deadline. It only ever moves later, so two callers extending + * for different durations can never shorten each other's lease. When it passes, `onExpire` runs + * once. + */ +export class Lifetime { + private timer?: ReturnType + private expired = false + + constructor( + private deadlineMs: number | undefined, + private readonly onExpire: () => void + ) { + this.arm() + } + + get expiresAtMs(): number | undefined { + return this.deadlineMs + } + + /** Moves the deadline to `expiresAtMs` unless it is already later; returns the deadline in force. */ + extend(expiresAtMs: number): number { + if (this.deadlineMs === undefined || expiresAtMs > this.deadlineMs) { + this.deadlineMs = expiresAtMs + this.arm() + } + return this.deadlineMs + } + + private arm(): void { + clearTimeout(this.timer) + if (this.deadlineMs === undefined || this.expired) return + const remaining = this.deadlineMs - Date.now() + if (remaining <= 0) { + this.expired = true + this.onExpire() + return + } + this.timer = setTimeout(() => this.arm(), Math.min(remaining, MAX_TIMER_MS)) + } +} diff --git a/apps/sandbox-agent/src/main.ts b/apps/sandbox-agent/src/main.ts new file mode 100644 index 00000000000..fbe1c1d8509 --- /dev/null +++ b/apps/sandbox-agent/src/main.ts @@ -0,0 +1,65 @@ +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' +import { resolveAccounts } from '@/accounts' +import { readAgentConfig } from '@/config' +import { installSelf } from '@/install' +import { Lifetime } from '@/lifetime' +import { ProcessTable } from '@/processes' +import { SANDBOX_AGENT_VERSION, startAgentServer } from '@/server' +import { runCliVerifier, VERIFY_CLI_MODE, VERIFY_CLI_MODE_ENV } from '@/verify-cli' + +const logger = createLogger('SandboxAgent') + +async function serve(): Promise { + const config = readAgentConfig(process.env) + const accounts = resolveAccounts() + const processes = new ProcessTable(accounts, config.baseEnvironment) + const shutdown = (reason: string) => { + logger.info('Sandbox agent stopping every process', { reason }) + processes.killAll() + process.exit(0) + } + const lifetime = new Lifetime(config.expiresAtMs, () => shutdown('lifetime ended')) + // As a container's PID 1 the agent gets no default signal handling, so a pod deletion's + // SIGTERM would otherwise wait out the whole grace period. + process.on('SIGTERM', () => shutdown('SIGTERM')) + process.on('SIGINT', () => shutdown('SIGINT')) + const server = startAgentServer({ + tokenSha256: config.tokenSha256, + host: config.host, + port: config.port, + accounts, + processes, + lifetime, + }) + logger.info('Sandbox agent listening', { + host: config.host, + port: server.port, + version: SANDBOX_AGENT_VERSION, + privileged: accounts.privileged, + expiresAtMs: lifetime.expiresAtMs, + }) +} + +async function verify(): Promise { + const input = await new Response(Bun.stdin.stream()).text() + process.exit(await runCliVerifier(input)) +} + +async function install(): Promise { + const destination = process.argv[3] + if (!destination) throw new Error('Usage: sim-sandbox-agent install ') + await installSelf(destination) + logger.info('Installed sandbox agent', { destination }) +} + +const mode = + process.env[VERIFY_CLI_MODE_ENV] === VERIFY_CLI_MODE + ? verify + : process.argv[2] === 'install' + ? install + : serve +mode().catch((error: unknown) => { + logger.error('Sandbox agent failed', { error: getErrorMessage(error) }) + process.exit(1) +}) diff --git a/apps/sandbox-agent/src/processes.test.ts b/apps/sandbox-agent/src/processes.test.ts new file mode 100644 index 00000000000..5b681007296 --- /dev/null +++ b/apps/sandbox-agent/src/processes.test.ts @@ -0,0 +1,227 @@ +import { createHash } from 'node:crypto' +import { existsSync, lstatSync, readFileSync, readlinkSync, statSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import { + NdjsonDecoder, + processEventSchema, + sandboxAgentProcessEventsPath, + sandboxAgentProcessSignalPath, +} from '@sim/sandbox-agent-protocol' +import { generateId } from '@sim/utils/id' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { isAlive, readEvents, startTestAgent, stdoutOf, type TestAgent } from '@/test-agent' + +let agent: TestAgent + +beforeAll(async () => { + agent = await startTestAgent({ env: { UNRELATED_AGENT_SECRET: 'must-not-leak' } }) +}) + +afterAll(async () => { + await agent.stop() +}) + +describe('process launch', () => { + it('streams output and the exit code as numbered events', async () => { + const events = await readEvents( + await agent.startProcess({ shell: 'printf out; printf err >&2; exit 3' }) + ) + expect(events.map((event) => event.seq)).toEqual(events.map((_, index) => index)) + expect(events[0]).toMatchObject({ type: 'started' }) + expect(stdoutOf(events)).toBe('out') + expect(events.find((event) => event.type === 'stderr')).toMatchObject({ data: 'err' }) + expect(events.at(-1)).toMatchObject({ type: 'exit', exitCode: 3 }) + }) + + it('gives children only the fixed base environment plus the request envs', async () => { + const events = await readEvents( + await agent.startProcess({ argv: ['env'], envs: { MINE: '1' } }) + ) + const names = stdoutOf(events) + .split('\n') + .filter(Boolean) + .map((line) => line.slice(0, line.indexOf('='))) + expect(names).toContain('MINE') + expect(names).toContain('HOME') + expect(names.filter((name) => name.startsWith('SIM_SANDBOX_'))).toEqual([]) + expect(names).not.toContain('UNRELATED_AGENT_SECRET') + }) + + it('rejects a relative working directory', async () => { + const response = await agent.startProcess({ shell: 'true', cwd: 'relative/dir' }) + expect(response.status).toBe(400) + expect(await response.json()).toMatchObject({ error: { code: 'invalid_path' } }) + }) + + it('reports a spawn failure as a rejection that ran nothing', async () => { + const events = await readEvents(await agent.startProcess({ argv: ['/nonexistent/binary'] })) + expect(events).toEqual([expect.objectContaining({ type: 'rejected', reason: 'spawn_failed' })]) + }) +}) + +describe('process budgets', () => { + it('stops a process whose output exceeds the byte budget and reports it', async () => { + const events = await readEvents( + await agent.startProcess({ shell: 'yes overflow', maxOutputBytes: 4096 }) + ) + const delivered = events.reduce( + (total, event) => total + (event.type === 'stdout' ? Buffer.byteLength(event.data) : 0), + 0 + ) + expect(delivered).toBeLessThanOrEqual(4096) + expect(events.at(-1)).toMatchObject({ type: 'exit', outputLimitExceeded: true }) + }) + + it('kills the whole process group on timeout, grandchildren included', async () => { + const pidFile = path.join(agent.root, `grandchild-${generateId()}`) + const events = await readEvents( + await agent.startProcess({ + shell: `sleep 600 & echo $! > ${pidFile}; wait`, + timeoutMs: 1_000, + }) + ) + expect(events.at(-1)).toMatchObject({ type: 'exit', exitCode: 124, timedOut: true }) + const grandchild = Number(readFileSync(pidFile, 'utf8').trim()) + await vi.waitFor(() => expect(isAlive(grandchild)).toBe(false), { timeout: 5_000 }) + }) + + it('signals the whole group on request', async () => { + const processKey = generateId() + const response = await agent.startProcess({ processKey, shell: 'sleep 600' }) + const signal = await agent.request(sandboxAgentProcessSignalPath(processKey), { + method: 'POST', + body: JSON.stringify({ signal: 'SIGKILL' }), + }) + expect(await signal.json()).toEqual({ delivered: true }) + expect((await readEvents(response)).at(-1)).toMatchObject({ type: 'exit', exitCode: 137 }) + }) +}) + +describe('idempotent launch and reattach', () => { + it('never launches a processKey twice, attaching the repeat to the first run', async () => { + const processKey = generateId() + const marker = path.join(agent.root, `runs-${processKey}`) + const body = { processKey, shell: `echo run >> ${marker}; sleep 0.3; echo done` } + const [first, second] = await Promise.all([ + agent.startProcess(body).then(readEvents), + agent.startProcess(body).then(readEvents), + ]) + const third = await readEvents(await agent.startProcess(body)) + expect(readFileSync(marker, 'utf8')).toBe('run\n') + expect(second).toEqual(first) + expect(third).toEqual(first) + }) + + it('refuses a processKey reused for a different request', async () => { + const processKey = generateId() + await readEvents(await agent.startProcess({ processKey, shell: 'true' })) + const conflict = await agent.startProcess({ processKey, shell: 'false' }) + expect(conflict.status).toBe(409) + expect(await conflict.json()).toMatchObject({ error: { code: 'process_key_conflict' } }) + }) + + it('reattaches from a sequence number, replaying only later events', async () => { + const processKey = generateId() + const response = await agent.startProcess({ + processKey, + shell: 'echo one; sleep 0.5; echo two; sleep 0.5; echo three', + }) + const reader = response.body?.getReader() + const decoder = new NdjsonDecoder() + let firstOutput: number | undefined + while (firstOutput === undefined && reader) { + const { value, done } = await reader.read() + if (done) break + for (const raw of decoder.push(value)) { + const event = processEventSchema.parse(raw) + if (event.type === 'stdout') firstOutput = event.seq + } + } + await reader?.cancel() + expect(firstOutput).toBeDefined() + + const resumed = await readEvents( + await agent.request( + `${sandboxAgentProcessEventsPath(processKey)}?from=${(firstOutput ?? 0) + 1}` + ) + ) + expect(resumed[0].seq).toBe((firstOutput ?? 0) + 1) + expect(stdoutOf(resumed)).toBe('two\nthree\n') + expect(resumed.at(-1)).toMatchObject({ type: 'exit', exitCode: 0 }) + }) + + it('answers 404 for an unknown processKey', async () => { + const response = await agent.request(sandboxAgentProcessEventsPath(generateId())) + expect(response.status).toBe(404) + }) +}) + +describe('CLI verification at launch', () => { + const sha256 = (content: string) => createHash('sha256').update(content).digest('hex') + + it('runs nothing when an artifact no longer matches its digest', async () => { + const cli = path.join(agent.root, `cli-${generateId()}`) + const marker = path.join(agent.root, `ran-${generateId()}`) + writeFileSync(cli, 'current release') + const events = await readEvents( + await agent.startProcess({ + shell: `touch ${marker}`, + verifyCli: { path: cli, artifacts: { [cli]: sha256('previous release') } }, + }) + ) + expect(events).toEqual([expect.objectContaining({ type: 'rejected', reason: 'cli_stale' })]) + expect(existsSync(marker)).toBe(false) + }) + + it('refuses a symlinked artifact even when its target matches', async () => { + const directory = path.join(agent.root, `cli-dir-${generateId()}`) + const real = path.join(agent.root, `real-${generateId()}`) + writeFileSync(real, 'release') + await readEvents(await agent.startProcess({ argv: ['mkdir', directory] })) + const link = path.join(directory, 'sim-cli') + await readEvents(await agent.startProcess({ argv: ['ln', '-s', real, link] })) + const events = await readEvents( + await agent.startProcess({ + shell: 'true', + verifyCli: { path: link, artifacts: { [link]: sha256('release') } }, + }) + ) + expect(events).toEqual([expect.objectContaining({ type: 'rejected', reason: 'cli_stale' })]) + }) + + it('runs the command and repairs the launcher when every artifact matches', async () => { + const directory = path.join(agent.root, `release-${generateId()}`) + await readEvents(await agent.startProcess({ argv: ['mkdir', directory] })) + const cli = path.join(directory, 'sim-1.2.3') + writeFileSync(cli, '#!/bin/sh\necho cli\n', { mode: 0o600 }) + const events = await readEvents( + await agent.startProcess({ + shell: 'echo ran', + verifyCli: { path: cli, artifacts: { [cli]: sha256('#!/bin/sh\necho cli\n') } }, + }) + ) + expect(stdoutOf(events)).toBe('ran\n') + expect(statSync(cli).mode & 0o7777).toBe(0o755) + expect(lstatSync(path.join(directory, 'sim')).isSymbolicLink()).toBe(true) + expect(readlinkSync(path.join(directory, 'sim'))).toBe('sim-1.2.3') + }) +}) + +describe('identity switch', () => { + const uid = process.getuid?.() + const canSwitch = uid === 0 + + it.skipIf(!canSwitch)( + `runs user processes as uid 1000 and root processes as root${canSwitch ? '' : ` [skipped: switching uid needs root; this run is uid ${uid}]`}`, + async () => { + const asUser = stdoutOf(await readEvents(await agent.startProcess({ argv: ['id', '-u'] }))) + const asRoot = stdoutOf( + await readEvents(await agent.startProcess({ argv: ['id', '-u'], user: 'root' })) + ) + const groups = stdoutOf(await readEvents(await agent.startProcess({ argv: ['id', '-G'] }))) + expect(asUser.trim()).toBe('1000') + expect(asRoot.trim()).toBe('0') + expect(groups.trim()).toBe('1000') + } + ) +}) diff --git a/apps/sandbox-agent/src/processes.ts b/apps/sandbox-agent/src/processes.ts new file mode 100644 index 00000000000..d84c6706b91 --- /dev/null +++ b/apps/sandbox-agent/src/processes.ts @@ -0,0 +1,306 @@ +import { type ChildProcess, spawn } from 'node:child_process' +import { createHash } from 'node:crypto' +import { constants } from 'node:os' +import { createLogger } from '@sim/logger' +import { + type ProcessEvent, + SANDBOX_AGENT_MAX_EVENT_DATA_BYTES, + type SandboxAgentRejectionReason, + type StartProcessRequest, +} from '@sim/sandbox-agent-protocol' +import { getErrorMessage } from '@sim/utils/errors' +import type { Accounts } from '@/accounts' +import { verifyCliAsUser } from '@/verify-cli' + +const logger = createLogger('SandboxAgentProcesses') + +/** An event as stored and replayed; heartbeats are per-connection and never stored. */ +export type RecordedEvent = Exclude + +/** Exit status reported when the agent's own timeout stopped the process (as E2B reports it). */ +const TIMEOUT_EXIT_CODE = 124 + +/** + * How long a finished process's output pipes may stay open after the process itself exited. + * A background grandchild that kept stdout open would otherwise hold the command open until + * its timeout; after the grace the pipes are closed and the exit is reported. + */ +const PIPE_DRAIN_GRACE_MS = 2_000 + +/** A finished process stays attachable this long, so a client that lost its stream can read the exit. */ +const FINISHED_RETENTION_MS = 10 * 60 * 1000 +const MAX_RUNNING_PROCESSES = 64 +const MAX_RECORDED_PROCESSES = 1024 +/** Output retained across finished processes before the oldest are forgotten. */ +const MAX_FINISHED_OUTPUT_BYTES = 64 * 1024 * 1024 + +type ProcessState = 'launching' | 'running' | 'finished' + +/** One launched (or refused) process and every event it produced. */ +export class ProcessRecord { + readonly events: RecordedEvent[] = [] + state: ProcessState = 'launching' + finishedAtMs?: number + outputBytes = 0 + private readonly listeners = new Set<(event: RecordedEvent) => void>() + private child?: ChildProcess + private cancelled = false + + constructor( + readonly key: string, + readonly fingerprint: string + ) {} + + get finished(): boolean { + return this.state === 'finished' + } + + /** Appends the next event, numbering it, and hands it to every attached stream. */ + emit(event: DistributiveOmit): void { + if (this.finished) return + const recorded = { ...event, seq: this.events.length } as RecordedEvent + this.events.push(recorded) + if (recorded.type === 'exit' || recorded.type === 'rejected') { + this.state = 'finished' + this.finishedAtMs = Date.now() + } + for (const listener of this.listeners) listener(recorded) + if (this.finished) this.listeners.clear() + } + + /** + * Replays every event from `from` onward, then follows live events until the record finishes. + * Returns the detach function. + */ + subscribe(from: number, listener: (event: RecordedEvent) => void): () => void { + for (const event of this.events.slice(from)) listener(event) + if (this.finished) return () => {} + this.listeners.add(listener) + return () => { + this.listeners.delete(listener) + } + } + + attach(child: ChildProcess): void { + this.child = child + this.state = 'running' + } + + /** True when a launch still in its CLI check was cancelled by a signal. */ + get wasCancelled(): boolean { + return this.cancelled + } + + /** + * Signals the whole process group. Before launch, a signal cancels the launch instead, so a + * client that gave up on a start can be sure nothing runs afterwards. + */ + signal(signal: 'SIGTERM' | 'SIGKILL'): boolean { + if (this.finished) return false + if (this.state === 'launching') { + this.cancelled = true + return true + } + return killGroup(this.child?.pid, signal) + } +} + +type DistributiveOmit = T extends unknown ? Omit : never + +/** Sends `signal` to every process in the group led by `pid`; false when none remain. */ +function killGroup(pid: number | undefined, signal: NodeJS.Signals): boolean { + if (pid === undefined) return false + try { + process.kill(-pid, signal) + return true + } catch { + return false + } +} + +function fingerprintOf(request: StartProcessRequest): string { + return createHash('sha256').update(JSON.stringify(request)).digest('hex') +} + +export type StartOutcome = + | { record: ProcessRecord } + | { error: 'process_key_conflict' | 'too_many_processes' } + +/** + * Every process the agent launched, keyed by the client's idempotency key. A key launches at most + * once: a repeated start with the same request attaches to the existing record instead. + */ +export class ProcessTable { + private readonly records = new Map() + + constructor( + private readonly accounts: Accounts, + private readonly baseEnvironment: Record + ) {} + + get(key: string): ProcessRecord | undefined { + return this.records.get(key) + } + + start(request: StartProcessRequest): StartOutcome { + const fingerprint = fingerprintOf(request) + const existing = this.records.get(request.processKey) + if (existing) { + return existing.fingerprint === fingerprint + ? { record: existing } + : { error: 'process_key_conflict' } + } + this.evictFinished() + const active = [...this.records.values()].filter((record) => !record.finished).length + if (active >= MAX_RUNNING_PROCESSES || this.records.size >= MAX_RECORDED_PROCESSES) { + return { error: 'too_many_processes' } + } + const record = new ProcessRecord(request.processKey, fingerprint) + this.records.set(request.processKey, record) + void this.launch(record, request).catch((error: unknown) => { + logger.error('Process launch failed', { error: getErrorMessage(error) }) + record.emit({ type: 'rejected', reason: 'spawn_failed', message: getErrorMessage(error) }) + }) + return { record } + } + + /** Kills every running process group; used when the sandbox's lifetime ends. */ + killAll(): void { + for (const record of this.records.values()) record.signal('SIGKILL') + } + + private evictFinished(): void { + const now = Date.now() + const finished = [...this.records.values()] + .filter((record) => record.finished) + .sort((left, right) => (left.finishedAtMs ?? 0) - (right.finishedAtMs ?? 0)) + let retainedBytes = finished.reduce((total, record) => total + record.outputBytes, 0) + let count = this.records.size + for (const record of finished) { + const expired = now - (record.finishedAtMs ?? now) > FINISHED_RETENTION_MS + if (!expired && retainedBytes <= MAX_FINISHED_OUTPUT_BYTES && count < MAX_RECORDED_PROCESSES) + break + this.records.delete(record.key) + retainedBytes -= record.outputBytes + count -= 1 + } + } + + private reject(record: ProcessRecord, reason: SandboxAgentRejectionReason, message?: string) { + record.emit({ type: 'rejected', reason, ...(message ? { message } : {}) }) + } + + private async launch(record: ProcessRecord, request: StartProcessRequest): Promise { + const identity = this.accounts.identityFor(request.user) + if (request.verifyCli) { + const verdict = await verifyCliAsUser( + request.verifyCli, + this.accounts.identityFor('user'), + this.baseEnvironment + ) + if (record.wasCancelled) return this.reject(record, 'cancelled') + if (verdict === 'stale') return this.reject(record, 'cli_stale') + if (verdict === 'failed') return this.reject(record, 'cli_check_failed') + } + if (record.wasCancelled) return this.reject(record, 'cancelled') + + const [file, ...args] = request.argv ?? ['/bin/bash', '-c', request.shell ?? ''] + const child = spawn(file, args, { + cwd: request.cwd ?? identity.home, + env: { + ...this.baseEnvironment, + HOME: identity.home, + USER: identity.name, + LOGNAME: identity.name, + ...request.envs, + }, + detached: true, + stdio: ['ignore', 'pipe', 'pipe'], + ...(identity.uid !== undefined ? { uid: identity.uid, gid: identity.gid } : {}), + }) + const pid = child.pid + if (pid === undefined) { + const failure = await new Promise((resolve) => { + child.once('error', (error) => resolve(getErrorMessage(error))) + }) + return this.reject(record, 'spawn_failed', failure) + } + record.attach(child) + record.emit({ type: 'started', pid }) + superviseProcess(record, child, pid, request) + } +} + +/** Streams output into events, enforces the timeout and output budget, and reports the exit. */ +function superviseProcess( + record: ProcessRecord, + child: ChildProcess, + pid: number, + request: StartProcessRequest +): void { + let timedOut = false + let outputLimitExceeded = false + let exit: { code: number | null; signal: NodeJS.Signals | null } | undefined + let drainTimer: ReturnType | undefined + + const timeoutTimer = setTimeout(() => { + timedOut = true + killGroup(pid, 'SIGKILL') + }, request.timeoutMs) + + const forward = (stream: NodeJS.ReadableStream | null, type: 'stdout' | 'stderr') => { + const decoder = new TextDecoder('utf-8') + stream?.on('data', (chunk: Buffer) => { + if (outputLimitExceeded) return + if (record.outputBytes + chunk.byteLength > request.maxOutputBytes) { + outputLimitExceeded = true + killGroup(pid, 'SIGKILL') + return + } + record.outputBytes += chunk.byteLength + for ( + let offset = 0; + offset < chunk.byteLength; + offset += SANDBOX_AGENT_MAX_EVENT_DATA_BYTES + ) { + const data = decoder.decode( + chunk.subarray(offset, offset + SANDBOX_AGENT_MAX_EVENT_DATA_BYTES), + { stream: true } + ) + if (data) record.emit({ type, data }) + } + }) + stream?.on('end', () => { + const tail = decoder.decode() + if (tail && !outputLimitExceeded) record.emit({ type, data: tail }) + }) + } + forward(child.stdout, 'stdout') + forward(child.stderr, 'stderr') + + const finish = () => { + if (record.finished || !exit) return + clearTimeout(timeoutTimer) + clearTimeout(drainTimer) + const signalNumber = exit.signal ? constants.signals[exit.signal] : undefined + const exitCode = timedOut + ? TIMEOUT_EXIT_CODE + : (exit.code ?? (signalNumber !== undefined ? 128 + signalNumber : 1)) + record.emit({ + type: 'exit', + exitCode, + ...(timedOut ? { timedOut: true } : {}), + ...(outputLimitExceeded ? { outputLimitExceeded: true } : {}), + }) + } + + child.on('exit', (code, signal) => { + exit = { code, signal } + drainTimer = setTimeout(() => { + child.stdout?.destroy() + child.stderr?.destroy() + finish() + }, PIPE_DRAIN_GRACE_MS) + }) + child.on('close', finish) +} diff --git a/apps/sandbox-agent/src/server.test.ts b/apps/sandbox-agent/src/server.test.ts new file mode 100644 index 00000000000..ef51d785836 --- /dev/null +++ b/apps/sandbox-agent/src/server.test.ts @@ -0,0 +1,79 @@ +import { readFileSync } from 'node:fs' +import path from 'node:path' +import { + healthzResponseSchema, + SANDBOX_AGENT_EXPIRES_AT_ENV, + SANDBOX_AGENT_ROUTES, +} from '@sim/sandbox-agent-protocol' +import { generateId } from '@sim/utils/id' +import { describe, expect, it, vi } from 'vitest' +import { isAlive, startTestAgent } from '@/test-agent' + +describe('authentication', () => { + it('serves /healthz without a token and refuses every other route without the right one', async () => { + const agent = await startTestAgent() + try { + const health = await fetch(`${agent.baseUrl}${SANDBOX_AGENT_ROUTES.healthz}`) + expect(healthzResponseSchema.parse(await health.json())).toMatchObject({ protocol: 1 }) + + const route = `${agent.baseUrl}${SANDBOX_AGENT_ROUTES.fileStat}?path=/tmp` + const attempts: Record[] = [ + {}, + { Authorization: `Bearer ${agent.token}x` }, + { Authorization: `Basic ${agent.token}` }, + { Authorization: `Bearer ${agent.token}` }, + ] + for (const headers of attempts) { + const response = await fetch(route, { headers }) + expect(response.status).toBe(401) + expect(response.headers.get('www-authenticate')).toBe('Bearer') + expect(await response.json()).toMatchObject({ error: { code: 'unauthorized' } }) + } + const authorized = await fetch(route, { headers: { Authorization: `Bearer ${agent.token}` } }) + expect(authorized.status).toBe(200) + } finally { + await agent.stop() + } + }) +}) + +describe('lifetime', () => { + it('never shortens the deadline', async () => { + const agent = await startTestAgent() + try { + const extend = async (expiresAtMs: number) => { + const response = await agent.request(SANDBOX_AGENT_ROUTES.lifetime, { + method: 'POST', + body: JSON.stringify({ expiresAtMs }), + }) + return ((await response.json()) as { expiresAtMs: number }).expiresAtMs + } + const later = Date.now() + 3_600_000 + expect(await extend(later)).toBe(later) + expect(await extend(later - 60_000)).toBe(later) + } finally { + await agent.stop() + } + }) + + it('kills every process group and exits 0 when the deadline passes', async () => { + const agent = await startTestAgent({ + env: { [SANDBOX_AGENT_EXPIRES_AT_ENV]: String(Date.now() + 3_000) }, + }) + try { + const pidFile = path.join(agent.root, `survivor-${generateId()}`) + void agent.startProcess({ + shell: `sleep 600 & echo $! > ${pidFile}; wait`, + timeoutMs: 60_000, + }) + await vi.waitFor(() => expect(readFileSync(pidFile, 'utf8')).toMatch(/^\d+\n$/), { + timeout: 5_000, + }) + const grandchild = Number(readFileSync(pidFile, 'utf8')) + expect(await agent.exited).toBe(0) + await vi.waitFor(() => expect(isAlive(grandchild)).toBe(false), { timeout: 5_000 }) + } finally { + await agent.stop() + } + }) +}) diff --git a/apps/sandbox-agent/src/server.ts b/apps/sandbox-agent/src/server.ts new file mode 100644 index 00000000000..2256e725dd6 --- /dev/null +++ b/apps/sandbox-agent/src/server.ts @@ -0,0 +1,293 @@ +import { createLogger } from '@sim/logger' +import { + encodeNdjson, + fileStatResponseSchema, + type HealthzResponse, + lifetimeRequestSchema, + listFilesQuerySchema, + NDJSON_CONTENT_TYPE, + pathQuerySchema, + readFileQuerySchema, + SANDBOX_AGENT_FILE_SIZE_HEADER, + SANDBOX_AGENT_HEARTBEAT_MS, + SANDBOX_AGENT_PROTOCOL_VERSION, + SANDBOX_AGENT_ROUTES, + type SandboxAgentErrorBody, + type SandboxAgentErrorCode, + sandboxAgentProcessKeySchema, + signalProcessRequestSchema, + startProcessRequestSchema, + writeFileQuerySchema, +} from '@sim/sandbox-agent-protocol' +import { getErrorMessage } from '@sim/utils/errors' +import type { z } from 'zod' +import type { Accounts } from '@/accounts' +import { isAuthorized } from '@/auth' +import { + FileOperationError, + listDirectory, + openFileForRead, + removePath, + statFile, + writeFileAtomically, +} from '@/files' +import type { Lifetime } from '@/lifetime' +import type { ProcessRecord, ProcessTable, RecordedEvent } from '@/processes' + +const logger = createLogger('SandboxAgentServer') + +/** Version reported by `/healthz`; tracks this package's version. */ +export const SANDBOX_AGENT_VERSION = '0.1.0' + +/** Largest JSON request body the agent reads. */ +const MAX_JSON_BODY_BYTES = 1024 * 1024 + +/** + * Largest file upload. Bun refuses bigger bodies before the handler runs; sandbox disk is + * bounded far below this by the pod's ephemeral-storage limit. + */ +const MAX_UPLOAD_BYTES = 16 * 1024 * 1024 * 1024 + +/** Seconds a connection may sit with no traffic; event streams send heartbeats well inside it. */ +const IDLE_TIMEOUT_SECONDS = 120 + +const STATUS_BY_CODE: Record = { + unauthorized: 401, + invalid_request: 400, + invalid_path: 400, + not_found: 404, + not_a_file: 400, + not_a_directory: 400, + permission_denied: 403, + too_large: 413, + process_key_conflict: 409, + too_many_processes: 429, + method_not_allowed: 405, + internal: 500, +} + +export interface AgentServerDependencies { + tokenSha256: Buffer + host: string + port: number + accounts: Accounts + processes: ProcessTable + lifetime: Lifetime +} + +class RequestError extends Error { + constructor( + readonly code: SandboxAgentErrorCode, + message: string, + readonly observedBytes?: number + ) { + super(message) + this.name = 'RequestError' + } +} + +function json(value: unknown, status = 200): Response { + return Response.json(value, { status }) +} + +function errorResponse(code: SandboxAgentErrorCode, message: string, observedBytes?: number) { + const body: SandboxAgentErrorBody = { + error: { code, message, ...(observedBytes !== undefined ? { observedBytes } : {}) }, + } + const response = json(body, STATUS_BY_CODE[code]) + if (code === 'unauthorized') response.headers.set('WWW-Authenticate', 'Bearer') + return response +} + +function parse(schema: T, value: unknown): z.infer { + const result = schema.safeParse(value) + if (!result.success) { + const issue = result.error.issues[0] + throw new RequestError( + issue?.path.includes('path') || issue?.path.includes('cwd') + ? 'invalid_path' + : 'invalid_request', + issue ? `${issue.path.join('.') || 'body'}: ${issue.message}` : 'Invalid request' + ) + } + return result.data +} + +function queryOf(url: URL): Record { + return Object.fromEntries(url.searchParams.entries()) +} + +async function readJson(request: Request): Promise { + const declared = Number(request.headers.get('content-length') ?? '0') + if (declared > MAX_JSON_BODY_BYTES) throw new RequestError('too_large', 'JSON body is too large') + const text = await request.text() + if (Buffer.byteLength(text) > MAX_JSON_BODY_BYTES) { + throw new RequestError('too_large', 'JSON body is too large') + } + try { + return JSON.parse(text) + } catch { + throw new RequestError('invalid_request', 'Body is not valid JSON') + } +} + +/** + * Streams a record's events from `from` as NDJSON until the record finishes, with heartbeats + * while it is quiet. Disconnecting detaches the stream and leaves the process running. + */ +function eventStream(record: ProcessRecord, from: number): Response { + let detach = () => {} + let heartbeat: ReturnType | undefined + let closed = false + const stop = () => { + closed = true + detach() + clearInterval(heartbeat) + } + const body = new ReadableStream({ + start(controller) { + const end = () => { + if (closed) return + stop() + controller.close() + } + const send = (event: RecordedEvent) => { + if (closed) return + controller.enqueue(encodeNdjson(event)) + if (event.type === 'exit' || event.type === 'rejected') end() + } + heartbeat = setInterval(() => { + if (!closed) controller.enqueue(encodeNdjson({ type: 'heartbeat' })) + }, SANDBOX_AGENT_HEARTBEAT_MS) + detach = record.subscribe(from, send) + if (closed) detach() + if (record.finished) end() + }, + cancel: stop, + }) + return new Response(body, { headers: { 'Content-Type': NDJSON_CONTENT_TYPE } }) +} + +function parseSeq(value: string | null): number { + if (value === null) return 0 + const seq = Number(value) + if (!Number.isSafeInteger(seq) || seq < 0) { + throw new RequestError('invalid_request', 'from must be a non-negative integer') + } + return seq +} + +async function route(request: Request, url: URL, deps: AgentServerDependencies) { + const { pathname } = url + const method = request.method + + if (pathname === SANDBOX_AGENT_ROUTES.processes) { + if (method !== 'POST') throw new RequestError('method_not_allowed', 'Use POST') + const start = parse(startProcessRequestSchema, await readJson(request)) + const outcome = deps.processes.start(start) + if ('error' in outcome) { + throw new RequestError( + outcome.error, + outcome.error === 'process_key_conflict' + ? 'This processKey already names a different request' + : 'Too many processes are running' + ) + } + return eventStream(outcome.record, 0) + } + + const processRoute = /^\/v1\/processes\/([^/]+)\/(events|signal)$/.exec(pathname) + if (processRoute) { + const key = parse(sandboxAgentProcessKeySchema, decodeURIComponent(processRoute[1])) + const record = deps.processes.get(key) + if (!record) throw new RequestError('not_found', 'No process has this processKey') + if (processRoute[2] === 'events') { + if (method !== 'GET') throw new RequestError('method_not_allowed', 'Use GET') + return eventStream(record, parseSeq(url.searchParams.get('from'))) + } + if (method !== 'POST') throw new RequestError('method_not_allowed', 'Use POST') + const { signal } = parse(signalProcessRequestSchema, await readJson(request)) + return json({ delivered: record.signal(signal) }) + } + + if (pathname === SANDBOX_AGENT_ROUTES.fileStat) { + if (method !== 'GET') throw new RequestError('method_not_allowed', 'Use GET') + const { path } = parse(pathQuerySchema, queryOf(url)) + return json(fileStatResponseSchema.parse(await statFile(path))) + } + + if (pathname === SANDBOX_AGENT_ROUTES.fileList) { + if (method !== 'GET') throw new RequestError('method_not_allowed', 'Use GET') + const { path, depth } = parse(listFilesQuerySchema, queryOf(url)) + return json(await listDirectory(path, depth)) + } + + if (pathname === SANDBOX_AGENT_ROUTES.files) { + if (method === 'GET') { + const { path, maxBytes } = parse(readFileQuerySchema, queryOf(url)) + const { size, body } = await openFileForRead(path, maxBytes) + return new Response(body, { + headers: { + 'Content-Type': 'application/octet-stream', + [SANDBOX_AGENT_FILE_SIZE_HEADER]: String(size), + }, + }) + } + if (method === 'PUT') { + const { path, owner } = parse(writeFileQuerySchema, queryOf(url)) + await writeFileAtomically(path, request.body, deps.accounts.identityFor(owner)) + return new Response(null, { status: 204 }) + } + if (method === 'DELETE') { + const { path } = parse(pathQuerySchema, queryOf(url)) + await removePath(path) + return new Response(null, { status: 204 }) + } + throw new RequestError('method_not_allowed', 'Use GET, PUT, or DELETE') + } + + if (pathname === SANDBOX_AGENT_ROUTES.lifetime) { + if (method !== 'POST') throw new RequestError('method_not_allowed', 'Use POST') + const { expiresAtMs } = parse(lifetimeRequestSchema, await readJson(request)) + return json({ expiresAtMs: deps.lifetime.extend(expiresAtMs) }) + } + + throw new RequestError('not_found', 'No such route') +} + +/** Serves the protocol until the process exits. */ +export function startAgentServer(deps: AgentServerDependencies) { + return Bun.serve({ + hostname: deps.host, + port: deps.port, + idleTimeout: IDLE_TIMEOUT_SECONDS, + maxRequestBodySize: MAX_UPLOAD_BYTES, + async fetch(request) { + const url = new URL(request.url) + if (url.pathname === SANDBOX_AGENT_ROUTES.healthz && request.method === 'GET') { + const health: HealthzResponse = { + ok: true, + protocol: SANDBOX_AGENT_PROTOCOL_VERSION, + agentVersion: SANDBOX_AGENT_VERSION, + } + return json(health) + } + if (!isAuthorized(request.headers.get('authorization'), deps.tokenSha256)) { + return errorResponse('unauthorized', 'A valid bearer token is required') + } + try { + return await route(request, url, deps) + } catch (error) { + if (error instanceof RequestError || error instanceof FileOperationError) { + return errorResponse(error.code, error.message, error.observedBytes) + } + logger.error('Sandbox agent request failed', { + method: request.method, + route: url.pathname, + error: getErrorMessage(error), + }) + return errorResponse('internal', 'Internal agent error') + } + }, + }) +} diff --git a/apps/sandbox-agent/src/test-agent.ts b/apps/sandbox-agent/src/test-agent.ts new file mode 100644 index 00000000000..cf6be1adae7 --- /dev/null +++ b/apps/sandbox-agent/src/test-agent.ts @@ -0,0 +1,143 @@ +import { type ChildProcess, spawn } from 'node:child_process' +import { createHash } from 'node:crypto' +import { chmodSync, mkdtempSync, realpathSync, rmSync } from 'node:fs' +import { createServer } from 'node:net' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { + NdjsonDecoder, + type ProcessEvent, + processEventSchema, + SANDBOX_AGENT_HOST_ENV, + SANDBOX_AGENT_PORT_ENV, + SANDBOX_AGENT_ROUTES, + SANDBOX_AGENT_TOKEN_SHA256_ENV, + type StartProcessRequest, +} from '@sim/sandbox-agent-protocol' +import { generateId } from '@sim/utils/id' +import { vi } from 'vitest' + +const ENTRY = path.resolve(__dirname, 'main.ts') + +/** A real agent process on a loopback port, with a private scratch directory as its HOME. */ +export interface TestAgent { + baseUrl: string + token: string + /** Scratch directory, also the agent's HOME (where unprivileged `user` processes start). */ + root: string + child: ChildProcess + exited: Promise + request(route: string, init?: RequestInit): Promise + startProcess(request: Partial): Promise + stop(): Promise +} + +async function freePort(): Promise { + return new Promise((resolve, reject) => { + const server = createServer() + server.once('error', reject) + server.listen(0, '127.0.0.1', () => { + const address = server.address() + server.close(() => + typeof address === 'object' && address + ? resolve(address.port) + : reject(new Error('no port')) + ) + }) + }) +} + +/** Starts the agent from source with `bun` and waits until `/healthz` answers. */ +export async function startTestAgent(options: { env?: Record } = {}) { + const root = realpathSync(mkdtempSync(path.join(tmpdir(), 'sim-sandbox-agent-'))) + // A root agent runs `user` processes as uid 1000, which must be able to write here too. + if (process.getuid?.() === 0) chmodSync(root, 0o777) + const token = generateId() + const port = await freePort() + const child = spawn('bun', [ENTRY], { + env: { + PATH: process.env.PATH ?? '/usr/bin:/bin', + HOME: root, + [SANDBOX_AGENT_TOKEN_SHA256_ENV]: createHash('sha256').update(token).digest('hex'), + [SANDBOX_AGENT_PORT_ENV]: String(port), + [SANDBOX_AGENT_HOST_ENV]: '127.0.0.1', + ...options.env, + }, + stdio: ['ignore', 'ignore', 'ignore'], + }) + const exited = new Promise((resolve) => child.once('exit', resolve)) + const baseUrl = `http://127.0.0.1:${port}` + await vi.waitFor( + async () => { + const response = await fetch(`${baseUrl}${SANDBOX_AGENT_ROUTES.healthz}`) + if (!response.ok) throw new Error('agent not ready') + }, + { timeout: 15_000, interval: 50 } + ) + + const request = (route: string, init: RequestInit = {}) => + fetch(`${baseUrl}${route}`, { + ...init, + headers: { Authorization: `Bearer ${token}`, ...init.headers }, + }) + + const agent: TestAgent = { + baseUrl, + token, + root, + child, + exited, + request, + startProcess: (body) => + request(SANDBOX_AGENT_ROUTES.processes, { + method: 'POST', + body: JSON.stringify({ + processKey: generateId(), + envs: {}, + user: 'user', + timeoutMs: 10_000, + maxOutputBytes: 1024 * 1024, + ...body, + }), + }), + async stop() { + if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL') + await exited + rmSync(root, { recursive: true, force: true }) + }, + } + return agent +} + +/** A stored process event: every event but the per-connection heartbeat. */ +type StreamEvent = Exclude + +/** Reads an NDJSON event stream to its end, dropping heartbeats. */ +export async function readEvents(response: Response): Promise { + if (!response.body) throw new Error('No event stream') + const decoder = new NdjsonDecoder() + const events: StreamEvent[] = [] + for await (const chunk of response.body) { + for (const value of decoder.push(chunk)) { + const event = processEventSchema.parse(value) + if (event.type !== 'heartbeat') events.push(event) + } + } + decoder.finish() + return events +} + +/** Concatenated `stdout` data from a list of events. */ +export function stdoutOf(events: StreamEvent[]): string { + return events.map((event) => (event.type === 'stdout' ? event.data : '')).join('') +} + +/** True while a process with this pid exists (a zombie counts until it is reaped). */ +export function isAlive(pid: number): boolean { + try { + process.kill(pid, 0) + return true + } catch { + return false + } +} diff --git a/apps/sandbox-agent/src/verify-cli.ts b/apps/sandbox-agent/src/verify-cli.ts new file mode 100644 index 00000000000..e6271a7fa98 --- /dev/null +++ b/apps/sandbox-agent/src/verify-cli.ts @@ -0,0 +1,107 @@ +import { spawn } from 'node:child_process' +import { createHash } from 'node:crypto' +import { constants } from 'node:fs' +import { chmod, lstat, mkdtemp, open, readlink, rename, rm, stat, symlink } from 'node:fs/promises' +import path from 'node:path' +import { + type SandboxAgentCliVerification, + sandboxAgentCliVerificationSchema, +} from '@sim/sandbox-agent-protocol' +import type { ProcessIdentity } from '@/accounts' +import { isCompiledBinary } from '@/install' + +/** Environment variable that starts the agent binary in verifier mode instead of serving. */ +export const VERIFY_CLI_MODE_ENV = 'SIM_SANDBOX_AGENT_MODE' +export const VERIFY_CLI_MODE = 'verify-cli' + +/** Exit status for a mismatched, missing, or non-regular artifact (the same as the app's check). */ +const STALE_EXIT_CODE = 10 +const VERIFY_TIMEOUT_MS = 30_000 + +async function artifactMatches(artifact: string, expected: string): Promise { + let handle: Awaited> + try { + handle = await open(artifact, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK) + } catch { + return false + } + try { + if (!(await handle.stat()).isFile()) return false + const digest = createHash('sha256') + for await (const chunk of handle.createReadStream({ autoClose: false })) digest.update(chunk) + return digest.digest('hex') === expected + } finally { + await handle.close() + } +} + +/** + * The verifier itself, run in a child as the sandbox user. Mirrors the app's + * `SESSION_CLI_CHECK_SCRIPT`: every artifact must be a regular, non-symlink file with the + * expected digest; then the CLI is made executable and its `sim` launcher symlink repaired. + * Exits 0 when verified, 10 when stale, and 1 on any other failure. + */ +export async function runCliVerifier(input: string): Promise { + const verification = sandboxAgentCliVerificationSchema.parse(JSON.parse(input)) + for (const [artifact, expected] of Object.entries(verification.artifacts)) { + if (!(await artifactMatches(artifact, expected))) return STALE_EXIT_CODE + } + if (((await stat(verification.path)).mode & 0o7777) !== 0o755) { + await chmod(verification.path, 0o755) + } + const directory = path.dirname(verification.path) + const target = path.basename(verification.path) + const launcher = path.join(directory, 'sim') + const current = await lstat(launcher).catch(() => null) + if (!current?.isSymbolicLink() || (await readlink(launcher)) !== target) { + const staging = await mkdtemp(path.join(directory, '.sim-link-')) + try { + await symlink(target, path.join(staging, 'sim')) + await rename(path.join(staging, 'sim'), launcher) + } finally { + await rm(staging, { recursive: true, force: true }) + } + } + return 0 +} + +/** argv that re-enters this program: a compiled binary is its own entry, a script needs its path. */ +function selfInvocation(): string[] { + return isCompiledBinary() ? [] : [Bun.main] +} + +/** + * Checks `verifyCli` as the sandbox user, in a child of this binary. Running it unprivileged is + * what keeps a user-planted symlink from steering a root `chmod` or launcher write elsewhere. + */ +export function verifyCliAsUser( + verification: SandboxAgentCliVerification, + identity: ProcessIdentity, + baseEnvironment: Record +): Promise<'verified' | 'stale' | 'failed'> { + return new Promise((resolve) => { + let child: ReturnType + try { + child = spawn(process.execPath, [...selfInvocation()], { + cwd: '/', + env: { ...baseEnvironment, HOME: identity.home, [VERIFY_CLI_MODE_ENV]: VERIFY_CLI_MODE }, + stdio: ['pipe', 'ignore', 'ignore'], + ...(identity.uid !== undefined ? { uid: identity.uid, gid: identity.gid } : {}), + }) + } catch { + resolve('failed') + return + } + const timer = setTimeout(() => child.kill('SIGKILL'), VERIFY_TIMEOUT_MS) + child.on('error', () => { + clearTimeout(timer) + resolve('failed') + }) + child.on('close', (code) => { + clearTimeout(timer) + resolve(code === 0 ? 'verified' : code === STALE_EXIT_CODE ? 'stale' : 'failed') + }) + child.stdin?.on('error', () => {}) + child.stdin?.end(JSON.stringify(verification)) + }) +} diff --git a/apps/sandbox-agent/tsconfig.json b/apps/sandbox-agent/tsconfig.json new file mode 100644 index 00000000000..c0c88d25a9f --- /dev/null +++ b/apps/sandbox-agent/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@sim/tsconfig/base.json", + "compilerOptions": { + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": ["node", "bun"], + "paths": { "@/*": ["./src/*"] } + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/apps/sandbox-agent/vitest.config.ts b/apps/sandbox-agent/vitest.config.ts new file mode 100644 index 00000000000..152f206cfbd --- /dev/null +++ b/apps/sandbox-agent/vitest.config.ts @@ -0,0 +1,21 @@ +import path from 'node:path' +import { defineConfig, mergeConfig } from 'vitest/config' +import sharedConfig from '../../vitest.shared' + +/** + * Tests start the real agent with `bun` on a loopback port and drive it over HTTP, so each one + * pays a process start and waits on real process exits. + */ +export default mergeConfig( + sharedConfig, + defineConfig({ + test: { + include: ['src/**/*.test.ts'], + testTimeout: 30_000, + hookTimeout: 30_000, + }, + resolve: { + alias: [{ find: '@', replacement: path.resolve(__dirname, 'src') }], + }, + }) +) diff --git a/bun.lock b/bun.lock index a1f7f99cdbe..ecaf6e2d979 100644 --- a/bun.lock +++ b/bun.lock @@ -211,6 +211,23 @@ "vitest": "^5.1.0", }, }, + "apps/sandbox-agent": { + "name": "@sim/sandbox-agent", + "version": "0.1.0", + "dependencies": { + "@sim/logger": "workspace:*", + "@sim/sandbox-agent-protocol": "workspace:*", + "@sim/utils": "workspace:*", + "zod": "4.3.6", + }, + "devDependencies": { + "@sim/tsconfig": "workspace:*", + "@types/bun": "1.4.4", + "@types/node": "24.19.2", + "typescript": "^7.0.2", + "vitest": "^5.1.0", + }, + }, "apps/sim": { "name": "@sim/app", "version": "0.1.0", @@ -742,6 +759,19 @@ "vitest": "^5.1.0", }, }, + "packages/sandbox-agent-protocol": { + "name": "@sim/sandbox-agent-protocol", + "version": "0.1.0", + "dependencies": { + "zod": "4.3.6", + }, + "devDependencies": { + "@sim/tsconfig": "workspace:*", + "@types/node": "24.19.2", + "typescript": "^7.0.2", + "vitest": "^5.1.0", + }, + }, "packages/security": { "name": "@sim/security", "version": "0.1.0", @@ -2141,6 +2171,10 @@ "@sim/runtime-secrets": ["@sim/runtime-secrets@workspace:packages/runtime-secrets"], + "@sim/sandbox-agent": ["@sim/sandbox-agent@workspace:apps/sandbox-agent"], + + "@sim/sandbox-agent-protocol": ["@sim/sandbox-agent-protocol@workspace:packages/sandbox-agent-protocol"], + "@sim/security": ["@sim/security@workspace:packages/security"], "@sim/table-cells": ["@sim/table-cells@workspace:packages/table-cells"], diff --git a/packages/sandbox-agent-protocol/package.json b/packages/sandbox-agent-protocol/package.json new file mode 100644 index 00000000000..448b6c9f14a --- /dev/null +++ b/packages/sandbox-agent-protocol/package.json @@ -0,0 +1,35 @@ +{ + "name": "@sim/sandbox-agent-protocol", + "version": "0.1.0", + "private": true, + "sideEffects": false, + "type": "module", + "license": "Apache-2.0", + "engines": { + "bun": ">=1.4.4", + "node": ">=20.0.0" + }, + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + } + }, + "scripts": { + "type-check": "tsc --noEmit", + "test": "vitest run", + "lint": "biome check --write --unsafe .", + "lint:check": "biome check .", + "format": "biome format --write .", + "format:check": "biome format ." + }, + "dependencies": { + "zod": "4.3.6" + }, + "devDependencies": { + "@sim/tsconfig": "workspace:*", + "@types/node": "24.19.2", + "typescript": "^7.0.2", + "vitest": "^5.1.0" + } +} diff --git a/packages/sandbox-agent-protocol/src/constants.ts b/packages/sandbox-agent-protocol/src/constants.ts new file mode 100644 index 00000000000..ca40c4a6833 --- /dev/null +++ b/packages/sandbox-agent-protocol/src/constants.ts @@ -0,0 +1,86 @@ +/** Port the agent listens on inside every sandbox (the same default as E2B's `envd`). */ +export const SANDBOX_AGENT_PORT = 49983 + +/** Wire protocol version reported by `GET /healthz`; bumped on any incompatible change. */ +export const SANDBOX_AGENT_PROTOCOL_VERSION = 1 + +/** + * Hex SHA-256 of the bearer token. The agent never sees the plaintext token, so a process that + * reads the agent's environment learns nothing it can authenticate with. + */ +export const SANDBOX_AGENT_TOKEN_SHA256_ENV = 'SIM_SANDBOX_AGENT_TOKEN_SHA256' + +/** Epoch milliseconds at which the agent kills every process and exits. Optional. */ +export const SANDBOX_AGENT_EXPIRES_AT_ENV = 'SIM_SANDBOX_EXPIRES_AT_MS' + +/** Listen port override, for running more than one agent on a host (tests). */ +export const SANDBOX_AGENT_PORT_ENV = 'SIM_SANDBOX_AGENT_PORT' + +/** Listen address override; the default binds every interface, as a pod IP requires. */ +export const SANDBOX_AGENT_HOST_ENV = 'SIM_SANDBOX_AGENT_HOST' + +/** Every agent-owned variable starts with this, so the agent can delete them all at startup. */ +export const SANDBOX_AGENT_ENV_PREFIX = 'SIM_SANDBOX_' + +export const NDJSON_CONTENT_TYPE = 'application/x-ndjson' + +/** + * Response header on `GET /v1/files` carrying the exact number of bytes the body will hold: the + * file's size when the agent opened it. A body that ends short of it was truncated in transit. + */ +export const SANDBOX_AGENT_FILE_SIZE_HEADER = 'X-Sim-File-Size' + +/** Ceiling on a process timeout; E2B's continuous-runtime cap, which a sandbox never outlives. */ +export const SANDBOX_AGENT_MAX_TIMEOUT_MS = 24 * 60 * 60 * 1000 + +/** Ceiling on a process's retained stdout plus stderr. */ +export const SANDBOX_AGENT_MAX_OUTPUT_BYTES = 64 * 1024 * 1024 + +/** + * Largest `data` payload in one output event. Bounds every NDJSON line, so a decoder can refuse + * an oversized line as corruption instead of buffering it. + */ +export const SANDBOX_AGENT_MAX_EVENT_DATA_BYTES = 64 * 1024 + +/** Upper bound for one NDJSON line, including JSON escaping of a maximal output event. */ +export const SANDBOX_AGENT_MAX_NDJSON_LINE_BYTES = 1024 * 1024 + +/** + * How often an event stream carries a heartbeat while its process is silent. Keeps a quiet + * process's stream inside HTTP client body timeouts (undici's default is 300 s). + */ +export const SANDBOX_AGENT_HEARTBEAT_MS = 15_000 + +/** Deepest `depth` a directory listing accepts; symlinked directories make deeper walks unbounded. */ +export const SANDBOX_AGENT_MAX_LIST_DEPTH = 32 + +/** Most entries one listing returns before it refuses with `too_large`. */ +export const SANDBOX_AGENT_MAX_LIST_ENTRIES = 10_000 + +/** Identity untrusted code runs as, matching E2B's sandbox user. */ +export const SANDBOX_AGENT_USER = { + name: 'user', + uid: 1000, + gid: 1000, + home: '/home/user', +} as const + +/** Route paths, relative to the agent's base URL. */ +export const SANDBOX_AGENT_ROUTES = { + healthz: '/healthz', + processes: '/v1/processes', + files: '/v1/files', + fileStat: '/v1/files/stat', + fileList: '/v1/files/list', + lifetime: '/v1/lifetime', +} as const + +/** `GET /v1/processes/{processKey}/events`. */ +export function sandboxAgentProcessEventsPath(processKey: string): string { + return `${SANDBOX_AGENT_ROUTES.processes}/${encodeURIComponent(processKey)}/events` +} + +/** `POST /v1/processes/{processKey}/signal`. */ +export function sandboxAgentProcessSignalPath(processKey: string): string { + return `${SANDBOX_AGENT_ROUTES.processes}/${encodeURIComponent(processKey)}/signal` +} diff --git a/packages/sandbox-agent-protocol/src/index.ts b/packages/sandbox-agent-protocol/src/index.ts new file mode 100644 index 00000000000..b6ef90a697e --- /dev/null +++ b/packages/sandbox-agent-protocol/src/index.ts @@ -0,0 +1,9 @@ +/** + * Wire protocol between Sim and `sim-sandbox-agent`, the daemon inside every self-hosted sandbox. + * HTTP/1.1 + JSON under `/v1`, process output as NDJSON, file bodies as raw octet streams, every + * route but `/healthz` behind an RFC 6750 bearer token. + */ +export * from './constants' +export * from './ndjson' +export * from './paths' +export * from './schemas' diff --git a/packages/sandbox-agent-protocol/src/ndjson.test.ts b/packages/sandbox-agent-protocol/src/ndjson.test.ts new file mode 100644 index 00000000000..9e5396aa2b1 --- /dev/null +++ b/packages/sandbox-agent-protocol/src/ndjson.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest' +import { encodeNdjson, NdjsonDecodeError, NdjsonDecoder } from './ndjson' + +const bytes = (text: string) => new TextEncoder().encode(text) + +describe('NdjsonDecoder', () => { + it('reassembles values split across chunks, including inside a multi-byte character', () => { + const wire = bytes(encodeNdjson({ data: 'é\nline' }) + encodeNdjson({ seq: 2 })) + const decoder = new NdjsonDecoder() + const values = [...wire].flatMap((byte) => decoder.push(Uint8Array.of(byte))) + decoder.finish() + expect(values).toEqual([{ data: 'é\nline' }, { seq: 2 }]) + }) + + it('refuses a line longer than its bound instead of buffering it', () => { + const decoder = new NdjsonDecoder(16) + expect(() => decoder.push(bytes(`"${'x'.repeat(32)}`))).toThrow(NdjsonDecodeError) + }) + + it('treats a stream that ends mid-line as truncated', () => { + const decoder = new NdjsonDecoder() + decoder.push(bytes('{"type":"exit"')) + expect(() => decoder.finish()).toThrow(NdjsonDecodeError) + }) + + it('rejects a line that is not JSON', () => { + expect(() => new NdjsonDecoder().push(bytes('not json\n'))).toThrow(NdjsonDecodeError) + }) +}) diff --git a/packages/sandbox-agent-protocol/src/ndjson.ts b/packages/sandbox-agent-protocol/src/ndjson.ts new file mode 100644 index 00000000000..fe332c7ed51 --- /dev/null +++ b/packages/sandbox-agent-protocol/src/ndjson.ts @@ -0,0 +1,62 @@ +import { SANDBOX_AGENT_MAX_NDJSON_LINE_BYTES } from './constants' + +/** One NDJSON line: compact JSON plus a newline. JSON escapes every newline inside a string. */ +export function encodeNdjson(value: unknown): string { + return `${JSON.stringify(value)}\n` +} + +/** A line exceeded the decoder's bound, or the stream ended mid-line. */ +export class NdjsonDecodeError extends Error { + constructor(message: string) { + super(message) + this.name = 'NdjsonDecodeError' + } +} + +/** + * Incremental NDJSON decoder over a byte stream. Chunks may split lines and multi-byte + * characters anywhere. A line longer than `maxLineBytes` throws instead of buffering without + * bound, and {@link finish} throws when the stream ended mid-line, since a truncated final event + * is a transport failure rather than an event. + */ +export class NdjsonDecoder { + private readonly decoder = new TextDecoder('utf-8', { fatal: true }) + private pending = '' + + constructor(private readonly maxLineBytes = SANDBOX_AGENT_MAX_NDJSON_LINE_BYTES) {} + + /** Returns every value completed by this chunk, in order. */ + push(chunk: Uint8Array): unknown[] { + this.pending += this.decoder.decode(chunk, { stream: true }) + const values: unknown[] = [] + let newline = this.pending.indexOf('\n') + while (newline !== -1) { + const line = this.pending.slice(0, newline) + this.pending = this.pending.slice(newline + 1) + if (line.trim()) values.push(this.parse(line)) + newline = this.pending.indexOf('\n') + } + if (this.pending.length > this.maxLineBytes) { + throw new NdjsonDecodeError(`NDJSON line exceeds ${this.maxLineBytes} bytes`) + } + return values + } + + /** Asserts the stream ended on a line boundary. */ + finish(): void { + this.pending += this.decoder.decode() + if (this.pending.trim()) throw new NdjsonDecodeError('NDJSON stream ended mid-line') + this.pending = '' + } + + private parse(line: string): unknown { + if (line.length > this.maxLineBytes) { + throw new NdjsonDecodeError(`NDJSON line exceeds ${this.maxLineBytes} bytes`) + } + try { + return JSON.parse(line) + } catch { + throw new NdjsonDecodeError('NDJSON line is not valid JSON') + } + } +} diff --git a/packages/sandbox-agent-protocol/src/paths.ts b/packages/sandbox-agent-protocol/src/paths.ts new file mode 100644 index 00000000000..50f2cb0fd55 --- /dev/null +++ b/packages/sandbox-agent-protocol/src/paths.ts @@ -0,0 +1,14 @@ +/** + * Why a file-API path is refused, or null when it is acceptable. + * + * Paths must be absolute so neither side resolves them against a working directory the other + * cannot see. NUL cannot cross a syscall, so it would silently truncate the path. `..` segments + * are refused rather than normalized: the app only ever names canonical paths, so one arriving is + * a bug or an attempt to reach somewhere the request did not appear to name. + */ +export function sandboxAgentPathError(path: string): string | null { + if (path.includes('\0')) return 'Path cannot contain a NUL byte' + if (!path.startsWith('/')) return 'Path must be absolute' + if (path.split('/').includes('..')) return 'Path cannot contain a ".." segment' + return null +} diff --git a/packages/sandbox-agent-protocol/src/schemas.ts b/packages/sandbox-agent-protocol/src/schemas.ts new file mode 100644 index 00000000000..9140b1f2e6f --- /dev/null +++ b/packages/sandbox-agent-protocol/src/schemas.ts @@ -0,0 +1,211 @@ +import { z } from 'zod' +import { + SANDBOX_AGENT_MAX_LIST_DEPTH, + SANDBOX_AGENT_MAX_OUTPUT_BYTES, + SANDBOX_AGENT_MAX_TIMEOUT_MS, + SANDBOX_AGENT_PROTOCOL_VERSION, +} from './constants' +import { sandboxAgentPathError } from './paths' + +/** Closed set of error codes an agent response may carry. */ +const SANDBOX_AGENT_ERROR_CODES = [ + 'unauthorized', + 'invalid_request', + 'invalid_path', + 'not_found', + 'not_a_file', + 'not_a_directory', + 'permission_denied', + 'too_large', + 'process_key_conflict', + 'too_many_processes', + 'method_not_allowed', + 'internal', +] as const + +export type SandboxAgentErrorCode = (typeof SANDBOX_AGENT_ERROR_CODES)[number] + +/** + * Every non-2xx response body. `observedBytes` accompanies `too_large` on a file read, carrying + * the size the agent saw when it refused. + */ +export const sandboxAgentErrorBodySchema = z.object({ + error: z.object({ + code: z.enum(SANDBOX_AGENT_ERROR_CODES), + message: z.string(), + observedBytes: z.number().int().nonnegative().optional(), + }), +}) + +export type SandboxAgentErrorBody = z.infer + +/** An absolute sandbox path without NUL bytes or `..` segments. */ +const sandboxAgentPathSchema = z.string().superRefine((path, context) => { + const problem = sandboxAgentPathError(path) + if (problem) context.addIssue({ code: 'custom', message: problem }) +}) + +/** Client-generated idempotency key; one key names at most one launched process. */ +export const sandboxAgentProcessKeySchema = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/) + +const ENVIRONMENT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/ + +/** NUL cannot cross `execve`, so a name or value containing one is refused rather than truncated. */ +const sandboxAgentEnvironmentSchema = z.record( + z.string().regex(ENVIRONMENT_NAME), + z.string().refine((value) => !value.includes('\0'), 'Environment values cannot contain NUL') +) + +const sha256HexSchema = z.string().regex(/^[0-9a-f]{64}$/) + +/** Same shape as the app's `SessionCliVerification`: expected SHA-256 per artifact path. */ +export const sandboxAgentCliVerificationSchema = z.object({ + path: sandboxAgentPathSchema, + artifacts: z.record(sandboxAgentPathSchema, sha256HexSchema), +}) + +export type SandboxAgentCliVerification = z.infer + +const sandboxAgentProcessUserSchema = z.enum(['root', 'user']) + +/** + * `POST /v1/processes`. Exactly one of `argv` (executed directly) or `shell` (run by + * `/bin/bash -c`) names the command. + */ +export const startProcessRequestSchema = z + .object({ + processKey: sandboxAgentProcessKeySchema, + argv: z + .array(z.string().refine((value) => !value.includes('\0'))) + .min(1) + .optional(), + shell: z + .string() + .refine((value) => !value.includes('\0')) + .optional(), + envs: sandboxAgentEnvironmentSchema, + cwd: sandboxAgentPathSchema.optional(), + user: sandboxAgentProcessUserSchema, + timeoutMs: z.number().int().positive().max(SANDBOX_AGENT_MAX_TIMEOUT_MS), + maxOutputBytes: z.number().int().positive().max(SANDBOX_AGENT_MAX_OUTPUT_BYTES), + verifyCli: sandboxAgentCliVerificationSchema.optional(), + }) + .refine((request) => (request.argv === undefined) !== (request.shell === undefined), { + message: 'Exactly one of argv or shell is required', + }) + +export type StartProcessRequest = z.infer + +/** + * Why a process was refused before it started. A rejection is a receipt that nothing ran: + * `cli_stale` (an artifact no longer matches), `cli_check_failed` (the check could not finish), + * `cancelled` (a signal arrived before launch), `spawn_failed` (the OS refused the exec). + */ +const SANDBOX_AGENT_REJECTION_REASONS = [ + 'cli_stale', + 'cli_check_failed', + 'cancelled', + 'spawn_failed', +] as const + +export type SandboxAgentRejectionReason = (typeof SANDBOX_AGENT_REJECTION_REASONS)[number] + +const seqSchema = z.number().int().nonnegative() + +/** + * One NDJSON line of a process event stream. Every event but `heartbeat` carries a monotonic + * `seq` starting at 0, which `GET .../events?from=` resumes from. A stream ends after `exit` or + * `rejected`, which are mutually exclusive and final. + */ +export const processEventSchema = z.discriminatedUnion('type', [ + z.object({ type: z.literal('started'), seq: seqSchema, pid: z.number().int().positive() }), + z.object({ type: z.literal('stdout'), seq: seqSchema, data: z.string() }), + z.object({ type: z.literal('stderr'), seq: seqSchema, data: z.string() }), + z.object({ + type: z.literal('exit'), + seq: seqSchema, + exitCode: z.number().int(), + timedOut: z.boolean().optional(), + outputLimitExceeded: z.boolean().optional(), + }), + z.object({ + type: z.literal('rejected'), + seq: seqSchema, + reason: z.enum(SANDBOX_AGENT_REJECTION_REASONS), + message: z.string().optional(), + }), + z.object({ type: z.literal('heartbeat') }), +]) + +export type ProcessEvent = z.infer + +/** + * `POST /v1/processes/{processKey}/signal`. The signal reaches the whole process group, or + * cancels a launch still verifying its CLI. Answers `{ delivered }`, false once the process + * has finished. + */ +export const signalProcessRequestSchema = z.object({ + signal: z.enum(['SIGTERM', 'SIGKILL']), +}) + +/** `POST /v1/lifetime`. A request never shortens an existing deadline. */ +export const lifetimeRequestSchema = z.object({ + expiresAtMs: z.number().int().positive(), +}) + +/** The deadline in force after the request. */ +export const lifetimeResponseSchema = z.object({ + expiresAtMs: z.number().int().positive(), +}) + +/** `GET /v1/files/stat`. Symlinks are followed; `other` is a FIFO, socket, or device. */ +export const fileStatResponseSchema = z.object({ + size: z.number().int().nonnegative(), + kind: z.enum(['file', 'directory', 'other']), +}) + +export type FileStatResponse = z.infer + +/** `depth` counts path segments below the listed directory: `a/b/leaf.txt` is depth 3. */ +export const listFilesQuerySchema = z.object({ + path: sandboxAgentPathSchema, + depth: z.coerce.number().int().min(1).max(SANDBOX_AGENT_MAX_LIST_DEPTH).default(1), +}) + +/** + * One listed entry, with its absolute path. Symlinks are followed and reported as what they + * resolve to; dangling links and non-regular, non-directory entries are omitted. + */ +export const directoryEntrySchema = z.object({ + path: z.string(), + kind: z.enum(['file', 'directory']), + size: z.number().int().nonnegative(), +}) + +export const listFilesResponseSchema = z.object({ + entries: z.array(directoryEntrySchema), +}) + +export type ListFilesResponse = z.infer + +/** `GET /v1/files`. Without `maxBytes` the read is unbounded (session snapshots stream it). */ +export const readFileQuerySchema = z.object({ + path: sandboxAgentPathSchema, + maxBytes: z.coerce.number().int().nonnegative().optional(), +}) + +/** `PUT /v1/files`. New files and parents belong to the sandbox user unless `owner=root`. */ +export const writeFileQuerySchema = z.object({ + path: sandboxAgentPathSchema, + owner: z.enum(['root', 'user']).default('user'), +}) + +export const pathQuerySchema = z.object({ path: sandboxAgentPathSchema }) + +export const healthzResponseSchema = z.object({ + ok: z.literal(true), + protocol: z.literal(SANDBOX_AGENT_PROTOCOL_VERSION), + agentVersion: z.string(), +}) + +export type HealthzResponse = z.infer diff --git a/packages/sandbox-agent-protocol/tsconfig.json b/packages/sandbox-agent-protocol/tsconfig.json new file mode 100644 index 00000000000..1ffa3d2e844 --- /dev/null +++ b/packages/sandbox-agent-protocol/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "@sim/tsconfig/library.json", + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/sandbox-agent-protocol/vitest.config.ts b/packages/sandbox-agent-protocol/vitest.config.ts new file mode 100644 index 00000000000..6f729af4c84 --- /dev/null +++ b/packages/sandbox-agent-protocol/vitest.config.ts @@ -0,0 +1,11 @@ +import { defineConfig, mergeConfig } from 'vitest/config' +import sharedConfig from '../../vitest.shared' + +export default mergeConfig( + sharedConfig, + defineConfig({ + test: { + include: ['src/**/*.test.ts'], + }, + }) +) From cb75282eeacccbbecb9b5616b634d6e8f46bdbf9 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 13:47:22 -0600 Subject: [PATCH 07/78] refactor(sandbox): share process-backed runCode between providers Moves the code file, CommonJS preload, launch command, and failure parsing out of the E2B adapter into runCodeAsProcess, so the agent-backed handle runs code exactly as E2B does. E2B passes its provider-limit error and keeps the same file writes, command, environment, and cleanup order. --- .../execution/remote-sandbox/code-process.ts | 98 +++++++++++++++++++ apps/sim/lib/execution/remote-sandbox/e2b.ts | 95 ++++-------------- scripts/check-unused-exports.baseline.json | 1 - 3 files changed, 118 insertions(+), 76 deletions(-) create mode 100644 apps/sim/lib/execution/remote-sandbox/code-process.ts diff --git a/apps/sim/lib/execution/remote-sandbox/code-process.ts b/apps/sim/lib/execution/remote-sandbox/code-process.ts new file mode 100644 index 00000000000..43634ff426c --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/code-process.ts @@ -0,0 +1,98 @@ +import { generateShortId } from '@sim/utils/id' +import { CodeLanguage } from '@/lib/execution/languages' +import { processCodeFailure } from '@/lib/execution/remote-sandbox/code-failure' +import type { + RunCommandOptions, + SandboxCodeError, + SandboxCodeResult, + SandboxCommandResult, + SandboxHandle, +} from '@/lib/execution/remote-sandbox/types' + +/** The options {@link SandboxHandle.runCode} accepts. */ +export type CodeRunOptions = Parameters[1] + +/** The three sandbox operations a code run needs, supplied by the provider adapter. */ +export interface CodeProcessIo { + /** Writes a file at a path relative to the sandbox user's home, the command's working directory. */ + writeFile(path: string, content: string): Promise + removeFile(path: string): Promise + /** Runs the launch command at most once, as the sandbox user, from its home directory. */ + run(command: string, options: RunCommandOptions): Promise +} + +const PYTHON_COMMAND = 'python3 "$SIM_CODE_PATH"' +const JAVASCRIPT_COMMAND = + 'set -e; if [ -n "$SIM_NODE_MODULES_PATH" ] && [ ! -e node_modules ]; then ln -s "$SIM_NODE_MODULES_PATH" node_modules; fi; node --require "$SIM_PRELOAD_PATH" "$SIM_CODE_PATH"' + +/** + * Runs code as a plain process: the source goes to a home-relative file (plus, for JavaScript, a + * CommonJS preload that restores `require` and installs runtime bindings), and a shell command + * starts `python3` or `node --require` on it. The result travels on stdout, and a failure is + * parsed from the traceback by {@link processCodeFailure}. Every process-backed provider shares + * this so `runCode` behaves the same whichever runs it. The files are removed afterwards whatever + * the outcome. + * + * @param providerLimitError Reported in place of the traceback when the provider ended the run at + * its own lifetime cap (`providerFailure: 'provider_limit'`). + */ +export async function runCodeAsProcess( + io: CodeProcessIo, + language: CodeLanguage, + code: string, + options: CodeRunOptions, + providerLimitError?: SandboxCodeError +): Promise { + const runId = generateShortId(12) + const isPython = language === CodeLanguage.Python + const codePath = `.sim-function-${runId}.${isPython ? 'py' : 'mjs'}` + const preloadPath = `.sim-function-${runId}.cjs` + + try { + await io.writeFile(codePath, code) + if (!isPython) { + const preload = ['global.require = require', options.javascriptPreload] + .filter(Boolean) + .join('\n') + await io.writeFile(preloadPath, `${preload}\n`) + } + + const result = await io.run(isPython ? PYTHON_COMMAND : JAVASCRIPT_COMMAND, { + timeoutMs: options.timeoutMs, + maxOutputBytes: options.maxOutputBytes, + signal: options.signal, + atMostOnce: true, + verifyCli: options.verifyCli, + envs: { + ...options.envs, + SIM_CODE_PATH: codePath, + ...(!isPython + ? { + SIM_NODE_MODULES_PATH: options.envs?.NODE_PATH ?? '', + SIM_PRELOAD_PATH: `./${preloadPath}`, + } + : {}), + }, + }) + + if (result.timedOut) { + return { text: '', stdout: result.stdout, stderr: result.stderr, timedOut: true } + } + if (result.exitCode !== 0) { + if (result.providerFailure === 'provider_limit' && providerLimitError) { + return { + text: '', + stdout: result.stdout, + stderr: result.stderr, + error: providerLimitError, + providerFailure: result.providerFailure, + } + } + return processCodeFailure(result) + } + return { text: '', stdout: result.stdout, stderr: result.stderr } + } finally { + await io.removeFile(codePath).catch(() => {}) + if (!isPython) await io.removeFile(preloadPath).catch(() => {}) + } +} diff --git a/apps/sim/lib/execution/remote-sandbox/e2b.ts b/apps/sim/lib/execution/remote-sandbox/e2b.ts index 6dbbc27ace7..104ad578fac 100644 --- a/apps/sim/lib/execution/remote-sandbox/e2b.ts +++ b/apps/sim/lib/execution/remote-sandbox/e2b.ts @@ -7,7 +7,7 @@ import type { } from '@e2b/code-interpreter' import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' -import { generateId, generateShortId } from '@sim/utils/id' +import { generateId } from '@sim/utils/id' import { isRecordLike } from '@sim/utils/object' import { IMMUTABLE_E2B_TEMPLATE_REF_ERROR, @@ -34,7 +34,7 @@ import { sandboxCliToolRecipes, sandboxCliVerificationCommand, } from '@/lib/execution/remote-sandbox/cli-tools.server' -import { processCodeFailure } from '@/lib/execution/remote-sandbox/code-failure' +import { type CodeRunOptions, runCodeAsProcess } from '@/lib/execution/remote-sandbox/code-process' import { FUNCTION_SANDBOX_CPU_COUNT, FUNCTION_SANDBOX_MATERIALIZER_REVISION, @@ -87,7 +87,6 @@ import type { SandboxImageMaterialization, SandboxKind, SandboxProvider, - SessionCliVerification, } from '@/lib/execution/remote-sandbox/types' const logger = createLogger('E2BSandboxProvider') @@ -450,80 +449,26 @@ class E2BSandboxHandle implements SandboxHandle { if (this.sessionKey !== undefined) this.recordSessionDeadline(requestedAtMs + timeoutMs) } - async runCode( - code: string, - options: { - timeoutMs: number - envs?: Record - javascriptPreload?: string - maxOutputBytes?: number - signal?: AbortSignal - verifyCli?: SessionCliVerification - } - ): Promise { - const runId = generateShortId(12) - const isPython = this.language === CodeLanguage.Python - const codePath = `.sim-function-${runId}.${isPython ? 'py' : 'mjs'}` - const preloadPath = `.sim-function-${runId}.cjs` - - try { - await this.sandbox.files.write(codePath, code) - if (!isPython) { - const preload = ['global.require = require', options.javascriptPreload] - .filter(Boolean) - .join('\n') - await this.sandbox.files.write(preloadPath, `${preload}\n`) - } - - const command = isPython - ? 'python3 "$SIM_CODE_PATH"' - : 'set -e; if [ -n "$SIM_NODE_MODULES_PATH" ] && [ ! -e node_modules ]; then ln -s "$SIM_NODE_MODULES_PATH" node_modules; fi; node --require "$SIM_PRELOAD_PATH" "$SIM_CODE_PATH"' - const result = await this.runCommandInternal( - command, - { - timeoutMs: options.timeoutMs, - maxOutputBytes: options.maxOutputBytes, - signal: options.signal, - atMostOnce: true, - verifyCli: options.verifyCli, - envs: { - ...options.envs, - SIM_CODE_PATH: codePath, - ...(!isPython - ? { - SIM_NODE_MODULES_PATH: options.envs?.NODE_PATH ?? '', - SIM_PRELOAD_PATH: `./${preloadPath}`, - } - : {}), - }, + async runCode(code: string, options: CodeRunOptions): Promise { + return runCodeAsProcess( + { + writeFile: async (path, content) => { + await this.sandbox.files.write(path, content) }, - 'code' - ) - - if (result.timedOut) { - return { text: '', stdout: result.stdout, stderr: result.stderr, timedOut: true } - } - if (result.exitCode !== 0) { - if (result.providerFailure === 'provider_limit') { - return { - text: '', - stdout: result.stdout, - stderr: result.stderr, - error: { - name: 'E2BProviderLimitError', - value: E2B_PROVIDER_LIMIT_ERROR, - traceback: E2B_PROVIDER_LIMIT_ERROR, - }, - providerFailure: result.providerFailure, - } - } - return processCodeFailure(result) + removeFile: async (path) => { + await this.sandbox.files.remove(path) + }, + run: (command, runOptions) => this.runCommandInternal(command, runOptions, 'code'), + }, + this.language, + code, + options, + { + name: 'E2BProviderLimitError', + value: E2B_PROVIDER_LIMIT_ERROR, + traceback: E2B_PROVIDER_LIMIT_ERROR, } - return { text: '', stdout: result.stdout, stderr: result.stderr } - } finally { - await this.sandbox.files.remove(codePath).catch(() => {}) - if (!isPython) await this.sandbox.files.remove(preloadPath).catch(() => {}) - } + ) } async runCommand(command: string, options: RunCommandOptions): Promise { diff --git a/scripts/check-unused-exports.baseline.json b/scripts/check-unused-exports.baseline.json index 6b0d940964e..1b5ca3d7857 100644 --- a/scripts/check-unused-exports.baseline.json +++ b/scripts/check-unused-exports.baseline.json @@ -4280,7 +4280,6 @@ "apps/sim/lib/execution/remote-sandbox/output-limits.ts#SANDBOX_OUTPUT_NOT_EXPORTABLE_CODE", "apps/sim/lib/execution/remote-sandbox/spec.ts#MAX_DEPENDENCY_LENGTH", "apps/sim/lib/execution/remote-sandbox/spec.ts#MAX_SYSTEM_PACKAGE_LENGTH", - "apps/sim/lib/execution/remote-sandbox/types.ts#SandboxCodeError", "apps/sim/lib/execution/remote-sandbox/workspace-sandboxes.ts#SandboxSpecUpdate", "apps/sim/lib/execution/remote-sandbox/workspace-sandboxes.ts#WORKSPACE_SANDBOX_NAME_INDEX", "apps/sim/lib/execution/remote-sandbox/workspace-sandboxes.ts#WorkspaceSandboxNotFoundError", From 0aa8f31bd1aa2e69cf57845c14ed697688c79a8b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 13:47:30 -0600 Subject: [PATCH 08/78] feat(sandbox): add a SandboxHandle over the sandbox agent protocol createAgentSandboxHandle implements the full SandboxHandle against sim-sandbox-agent, independent of the control plane that made the sandbox. runCode goes through the shared runCodeAsProcess. Commands launch under a fresh processKey and reattach from the last seq when the stream drops, so atMostOnce holds through transport failures and an unobservable outcome fails as SandboxLaunchIndeterminateError. File reads check the declared size, uploads stream, and session handles verify CLIs at launch and extend the agent lifetime without shortening it. Tests drive the handle against the real agent on loopback, including a proxy that cuts the event stream mid-run. --- .../execution/remote-sandbox/agent/client.ts | 109 ++++ .../remote-sandbox/agent/handle.test.ts | 289 +++++++++ .../execution/remote-sandbox/agent/handle.ts | 555 ++++++++++++++++++ apps/sim/package.json | 1 + bun.lock | 1 + knip.jsonc | 5 +- 6 files changed, 959 insertions(+), 1 deletion(-) create mode 100644 apps/sim/lib/execution/remote-sandbox/agent/client.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/agent/handle.test.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/agent/handle.ts diff --git a/apps/sim/lib/execution/remote-sandbox/agent/client.ts b/apps/sim/lib/execution/remote-sandbox/agent/client.ts new file mode 100644 index 00000000000..1bf985bde15 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/agent/client.ts @@ -0,0 +1,109 @@ +import { createLogger } from '@sim/logger' +import { + type SandboxAgentErrorCode, + sandboxAgentErrorBodySchema, +} from '@sim/sandbox-agent-protocol' +import { sleep } from '@sim/utils/helpers' +import { backoffWithJitter } from '@sim/utils/retry' + +const logger = createLogger('SandboxAgentClient') + +/** Bound on one non-streaming agent request; a reachable agent answers far faster. */ +const REQUEST_TIMEOUT_MS = 30_000 +const MAX_ATTEMPTS = 3 +const RETRY_BACKOFF = { baseMs: 200, maxMs: 2_000 } + +/** The agent answered with a protocol error: the request was refused, so nothing it named ran. */ +export class SandboxAgentRequestError extends Error { + constructor( + readonly status: number, + readonly code: SandboxAgentErrorCode | 'unknown', + message: string, + readonly observedBytes?: number + ) { + super(message) + this.name = 'SandboxAgentRequestError' + } +} + +export interface AgentRequestOptions { + method?: 'GET' | 'POST' | 'PUT' | 'DELETE' + query?: Record + json?: unknown + body?: BodyInit + signal?: AbortSignal + /** Applies {@link REQUEST_TIMEOUT_MS}; streaming reads and uploads opt out. */ + timeout?: boolean + /** + * Retries a request that failed before any response arrived. Only for requests that are safe + * to repeat: reads, deletes, lifetime extensions, signals, and starts carrying a processKey. + */ + retry?: boolean +} + +async function toRequestError(response: Response): Promise { + const parsed = sandboxAgentErrorBodySchema.safeParse(await response.json().catch(() => null)) + if (!parsed.success) { + return new SandboxAgentRequestError( + response.status, + 'unknown', + `Sandbox agent request failed (${response.status})` + ) + } + const { code, message, observedBytes } = parsed.data.error + return new SandboxAgentRequestError(response.status, code, message, observedBytes) +} + +/** Authenticated requests to one sandbox's agent. */ +export class SandboxAgentClient { + constructor( + private readonly baseUrl: string, + private readonly token: string + ) {} + + /** Returns a 2xx response, or throws {@link SandboxAgentRequestError} for a protocol error. */ + async request(route: string, options: AgentRequestOptions = {}): Promise { + const query = options.query ? `?${new URLSearchParams(options.query).toString()}` : '' + const url = `${this.baseUrl.replace(/\/$/, '')}${route}${query}` + const attempts = options.retry ? MAX_ATTEMPTS : 1 + for (let attempt = 1; ; attempt++) { + const signals = [ + ...(options.signal ? [options.signal] : []), + ...(options.timeout === false ? [] : [AbortSignal.timeout(REQUEST_TIMEOUT_MS)]), + ] + /** A streamed upload must declare half-duplex, which the DOM `RequestInit` type omits. */ + const init: RequestInit & { duplex?: 'half' } = { + method: options.method ?? 'GET', + headers: { + Authorization: `Bearer ${this.token}`, + ...(options.json !== undefined ? { 'Content-Type': 'application/json' } : {}), + }, + body: options.json !== undefined ? JSON.stringify(options.json) : options.body, + signal: signals.length > 0 ? AbortSignal.any(signals) : undefined, + ...(options.body instanceof ReadableStream ? { duplex: 'half' } : {}), + } + let response: Response + try { + // egress-direct: the sandbox agent is an operator-local pod endpoint, never a workspace egress target + response = await fetch(url, init) + } catch (error) { + options.signal?.throwIfAborted() + if (attempt >= attempts) throw error + logger.warn('Sandbox agent request failed before a response; retrying', { + route, + attempt, + }) + await sleep(backoffWithJitter(attempt, null, RETRY_BACKOFF)) + continue + } + if (response.ok) return response + throw await toRequestError(response) + } + } + + /** Requests JSON and returns the parsed body. */ + async requestJson(route: string, options: AgentRequestOptions = {}): Promise { + const response = await this.request(route, options) + return response.json() + } +} diff --git a/apps/sim/lib/execution/remote-sandbox/agent/handle.test.ts b/apps/sim/lib/execution/remote-sandbox/agent/handle.test.ts new file mode 100644 index 00000000000..262223d0576 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/agent/handle.test.ts @@ -0,0 +1,289 @@ +import { type ChildProcess, spawn } from 'node:child_process' +import { createHash } from 'node:crypto' +import { existsSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync } from 'node:fs' +import { createServer, type Server, Socket } from 'node:net' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { + SANDBOX_AGENT_HOST_ENV, + SANDBOX_AGENT_PORT_ENV, + SANDBOX_AGENT_ROUTES, + SANDBOX_AGENT_TOKEN_SHA256_ENV, +} from '@sim/sandbox-agent-protocol' +import { generateId } from '@sim/utils/id' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { CodeLanguage } from '@/lib/execution/languages' +import { isSandboxLaunchIndeterminateError } from '@/lib/execution/non-retryable-error' +import { + type AgentSandboxConnection, + createAgentSandboxHandle, +} from '@/lib/execution/remote-sandbox/agent/handle' +import { SessionCliStaleError } from '@/lib/execution/remote-sandbox/session-cli' + +/** + * Drives the handle against the real `sim-sandbox-agent`, started from source with `bun` on a + * loopback port. Every agent route, the NDJSON stream, and reattachment cross a real HTTP + * connection; a byte-counting TCP proxy stands in for a network that drops a stream mid-flight. + */ +const AGENT_ENTRY = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../../../sandbox-agent/src/main.ts' +) + +let agent: ChildProcess +let agentPort: number +let home: string +const token = generateId() + +async function freePort(): Promise { + return new Promise((resolve, reject) => { + const server = createServer() + server.once('error', reject) + server.listen(0, '127.0.0.1', () => { + const address = server.address() + server.close(() => + typeof address === 'object' && address + ? resolve(address.port) + : reject(new Error('no port')) + ) + }) + }) +} + +function connection(overrides: Partial = {}): AgentSandboxConnection { + return { + sandboxId: 'sbx-test', + baseUrl: `http://127.0.0.1:${agentPort}`, + token, + expiresAtMs: Date.now() + 60_000, + userHome: home, + kill: async () => {}, + ...overrides, + } +} + +/** + * Forwards to the agent, but cuts a connection as soon as the bytes it relayed back to the client + * contain `after`, for the first `drops` connections that get that far. + */ +async function startDroppingProxy(options: { drops: number; after: string }) { + const port = await freePort() + let remaining = options.drops + const sockets = new Set() + const server: Server = createServer((client) => { + const upstream = new Socket() + sockets.add(client) + sockets.add(upstream) + let relayed = '' + upstream.connect(agentPort, '127.0.0.1') + client.on('data', (chunk) => upstream.write(chunk)) + upstream.on('data', (chunk: Buffer) => { + relayed += chunk.toString('latin1') + client.write(chunk) + if (remaining > 0 && relayed.includes(options.after)) { + remaining -= 1 + client.destroy() + upstream.destroy() + } + }) + client.on('error', () => upstream.destroy()) + upstream.on('error', () => client.destroy()) + client.on('close', () => upstream.destroy()) + upstream.on('close', () => client.destroy()) + }) + await new Promise((resolve) => server.listen(port, '127.0.0.1', resolve)) + return { + baseUrl: `http://127.0.0.1:${port}`, + close: () => + new Promise((resolve) => { + for (const socket of sockets) socket.destroy() + server.close(() => resolve()) + }), + } +} + +beforeAll(async () => { + home = realpathSync(mkdtempSync(path.join(tmpdir(), 'sim-agent-handle-'))) + agentPort = await freePort() + agent = spawn('bun', [AGENT_ENTRY], { + env: { + PATH: process.env.PATH ?? '/usr/bin:/bin', + HOME: home, + [SANDBOX_AGENT_TOKEN_SHA256_ENV]: createHash('sha256').update(token).digest('hex'), + [SANDBOX_AGENT_PORT_ENV]: String(agentPort), + [SANDBOX_AGENT_HOST_ENV]: '127.0.0.1', + }, + stdio: 'ignore', + }) + await vi.waitFor( + async () => { + const response = await fetch(`http://127.0.0.1:${agentPort}${SANDBOX_AGENT_ROUTES.healthz}`) + if (!response.ok) throw new Error('agent not ready') + }, + { timeout: 15_000, interval: 50 } + ) +}, 30_000) + +afterAll(() => { + agent.kill('SIGKILL') + rmSync(home, { recursive: true, force: true }) +}) + +describe('runCode over the agent', () => { + it('runs Python from a home-relative file and removes it afterwards', async () => { + const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.Python })) + const result = await sandbox.runCode( + 'import json, os\nprint("__SIM_RESULT__=" + json.dumps({"cwd": os.getcwd(), "v": os.environ["MINE"]}))', + { timeoutMs: 20_000, envs: { MINE: 'set' } } + ) + expect(result.error).toBeUndefined() + const marker = result.stdout.trim().split('\n').at(-1) ?? '' + expect(JSON.parse(marker.slice('__SIM_RESULT__='.length))).toEqual({ cwd: home, v: 'set' }) + expect(readdirSync(home).filter((name) => name.startsWith('.sim-function-'))).toEqual([]) + }) + + it('runs JavaScript through the CommonJS preload with require and runtime bindings', async () => { + const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.JavaScript })) + const result = await sandbox.runCode( + 'const os = require("node:os")\nconsole.log("__SIM_RESULT__=" + JSON.stringify({ binding: globalThis.__simBinding, eol: os.EOL }))', + { timeoutMs: 20_000, javascriptPreload: 'globalThis.__simBinding = 42' } + ) + expect(result.error).toBeUndefined() + expect(result.stdout).toContain('__SIM_RESULT__={"binding":42,"eol":"\\n"}') + }) + + it('reports a Python exception in the shared error shape', async () => { + const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.Python })) + const result = await sandbox.runCode('raise ValueError("boom")', { timeoutMs: 20_000 }) + expect(result.error).toMatchObject({ name: 'ValueError', value: 'boom' }) + expect(result.error?.traceback).toContain('Traceback') + }) + + it('reports a timeout as timedOut rather than an error', async () => { + const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.Python })) + const result = await sandbox.runCode('import time\ntime.sleep(60)', { timeoutMs: 1_000 }) + expect(result.timedOut).toBe(true) + expect(result.error).toBeUndefined() + }) + + it('fails with the process output limit when code prints past its budget', async () => { + const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.Python })) + await expect( + sandbox.runCode('while True: print("x" * 1000)', { + timeoutMs: 20_000, + maxOutputBytes: 10_000, + }) + ).rejects.toMatchObject({ code: 'sandbox_output_limit_exceeded', outputKind: 'process' }) + }) +}) + +describe('at-most-once commands over a failing network', () => { + it('reattaches after the stream drops mid-run and runs the command exactly once', async () => { + const proxy = await startDroppingProxy({ drops: 1, after: '"type":"started"' }) + try { + const marker = path.join(home, `runs-${generateId()}`) + const sandbox = createAgentSandboxHandle(connection({ baseUrl: proxy.baseUrl })) + const result = await sandbox.runCommand( + `echo run >> ${marker}; sleep 0.5; echo first; sleep 0.5; echo second`, + { timeoutMs: 20_000, atMostOnce: true } + ) + expect(result).toMatchObject({ exitCode: 0, stdout: 'first\nsecond\n' }) + expect(readFileSync(marker, 'utf8')).toBe('run\n') + } finally { + await proxy.close() + } + }) + + it('fails indeterminate, never rerunning, when the outcome cannot be observed', async () => { + const proxy = await startDroppingProxy({ drops: 1_000, after: 'HTTP/1.1' }) + try { + const marker = path.join(home, `runs-${generateId()}`) + const sandbox = createAgentSandboxHandle(connection({ baseUrl: proxy.baseUrl })) + const outcome = await sandbox + .runCommand(`echo run >> ${marker}; sleep 2`, { timeoutMs: 20_000, atMostOnce: true }) + .catch((error: unknown) => error) + expect(isSandboxLaunchIndeterminateError(outcome)).toBe(true) + await vi.waitFor(() => expect(existsSync(marker)).toBe(true)) + expect(readFileSync(marker, 'utf8')).toBe('run\n') + } finally { + await proxy.close() + } + }) +}) + +describe('files over the agent', () => { + it('round-trips buffered and streamed files and lists them relative to the directory', async () => { + const sandbox = createAgentSandboxHandle(connection()) + const directory = path.join(home, `out-${generateId()}`) + await sandbox.writeFile(path.join(directory, 'a.txt'), 'alpha') + await sandbox.writeFileStream( + path.join(directory, 'nested', 'b.bin'), + new Blob([new Uint8Array([0, 1, 2, 255])]).stream(), + { signal: AbortSignal.timeout(10_000) } + ) + + expect(await sandbox.readFile(path.join(directory, 'a.txt'))).toBe('alpha') + const binary = await sandbox.readFileWithLimit(path.join(directory, 'nested', 'b.bin'), { + maxBytes: 4, + encoding: 'base64', + }) + expect(binary).toEqual({ + content: Buffer.from([0, 1, 2, 255]).toString('base64'), + byteLength: 4, + }) + const stream = await sandbox.readFileStream(path.join(directory, 'a.txt'), { + signal: AbortSignal.timeout(10_000), + }) + expect(await new Response(stream).text()).toBe('alpha') + + const entries = await sandbox.listFiles(directory, { depth: 2 }) + expect(entries.map((entry) => [entry.relativePath, entry.kind]).sort()).toEqual([ + ['a.txt', 'file'], + ['nested', 'directory'], + ['nested/b.bin', 'file'], + ]) + }) + + it('refuses a file over the read limit and a directory read as a file', async () => { + const sandbox = createAgentSandboxHandle(connection()) + const target = path.join(home, `large-${generateId()}`) + await sandbox.writeFile(target, 'x'.repeat(100)) + await expect( + sandbox.readFileWithLimit(target, { maxBytes: 10, encoding: 'utf8' }) + ).rejects.toMatchObject({ code: 'sandbox_output_limit_exceeded' }) + await expect(sandbox.getFileSize(home)).rejects.toMatchObject({ + code: 'sandbox_output_file_invalid', + }) + }) +}) + +describe('session semantics', () => { + it('extends the agent lifetime without shortening it and reports the window it covers', async () => { + const sandbox = createAgentSandboxHandle(connection({ session: true, expiresAtMs: Date.now() })) + expect(sandbox.verifiesCliAtLaunch).toBe(true) + expect(sandbox.outlives?.(60_000, Date.now())).toBe(false) + await sandbox.extendLifetime?.(3_600_000) + expect(sandbox.outlives?.(3_000_000, Date.now())).toBe(true) + }) + + it('omits lifetime control from a one-shot sandbox', () => { + const sandbox = createAgentSandboxHandle(connection()) + expect(sandbox.extendLifetime).toBeUndefined() + expect(sandbox.verifiesCliAtLaunch).toBe(false) + }) + + it('refuses a command whose CLI is stale, running nothing', async () => { + const sandbox = createAgentSandboxHandle(connection({ session: true })) + const cli = path.join(home, `cli-${generateId()}`) + const marker = path.join(home, `ran-${generateId()}`) + await sandbox.writeFile(cli, 'current') + await expect( + sandbox.runCommand(`touch ${marker}`, { + timeoutMs: 10_000, + verifyCli: { path: cli, artifacts: { [cli]: '0'.repeat(64) } }, + }) + ).rejects.toBeInstanceOf(SessionCliStaleError) + expect(existsSync(marker)).toBe(false) + }) +}) diff --git a/apps/sim/lib/execution/remote-sandbox/agent/handle.ts b/apps/sim/lib/execution/remote-sandbox/agent/handle.ts new file mode 100644 index 00000000000..e67a84aa6d9 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/agent/handle.ts @@ -0,0 +1,555 @@ +import { posix } from 'node:path' +import { createLogger } from '@sim/logger' +import { + fileStatResponseSchema, + lifetimeResponseSchema, + listFilesResponseSchema, + NdjsonDecoder, + type ProcessEvent, + processEventSchema, + SANDBOX_AGENT_FILE_SIZE_HEADER, + SANDBOX_AGENT_MAX_OUTPUT_BYTES, + SANDBOX_AGENT_MAX_TIMEOUT_MS, + SANDBOX_AGENT_ROUTES, + SANDBOX_AGENT_USER, + type StartProcessRequest, + sandboxAgentProcessEventsPath, + sandboxAgentProcessSignalPath, +} from '@sim/sandbox-agent-protocol' +import { getErrorMessage } from '@sim/utils/errors' +import { generateId } from '@sim/utils/id' +import { isTimeoutAbortReason } from '@/lib/core/execution-limits' +import { + isPayloadSizeLimitError, + readStreamToBufferWithLimit, +} from '@/lib/core/utils/stream-limits' +import { CodeLanguage } from '@/lib/execution/languages' +import { SandboxLaunchIndeterminateError } from '@/lib/execution/non-retryable-error' +import { + SandboxAgentClient, + SandboxAgentRequestError, +} from '@/lib/execution/remote-sandbox/agent/client' +import { type CodeRunOptions, runCodeAsProcess } from '@/lib/execution/remote-sandbox/code-process' +import { + appendStreamedSandboxOutput, + MAX_SANDBOX_OUTPUT_BYTES, + MAX_SANDBOX_PROCESS_OUTPUT_BYTES, + SandboxOutputFileError, + SandboxOutputLimitError, + SandboxProcessOutputBudget, + tailStreamedSandboxOutput, +} from '@/lib/execution/remote-sandbox/output-limits' +import { resolveSandboxDirectoryEntryPath } from '@/lib/execution/remote-sandbox/paths' +import { + SessionCliStaleError, + SessionCliVerificationError, +} from '@/lib/execution/remote-sandbox/session-cli' +import type { + RunCommandOptions, + SandboxCodeResult, + SandboxCommandResult, + SandboxDirectoryEntry, + SandboxHandle, +} from '@/lib/execution/remote-sandbox/types' + +const logger = createLogger('AgentSandboxHandle') + +/** Name used in launch-indeterminate errors; the handle does not know which control plane made the sandbox. */ +const PROVIDER_LABEL = 'The sandbox agent' + +/** Reconnects a single command may make after its event stream drops. */ +const MAX_STREAM_RECONNECTS = 20 + +/** How long a cancelled command may take to report its exit before the cancellation returns. */ +const CANCEL_SETTLE_MS = 5_000 + +/** How to reach one sandbox's agent, supplied by the control plane that created the sandbox. */ +export interface AgentSandboxConnection { + sandboxId: string + /** Agent base URL, such as `http://10.0.3.17:49983`. */ + baseUrl: string + /** Plaintext bearer token. The agent holds only its digest. */ + token: string + /** Bound at create, per {@link SandboxHandle.runCode}. Defaults to Python. */ + language?: CodeLanguage + /** + * Enables session semantics: {@link SandboxHandle.extendLifetime}, {@link SandboxHandle.outlives}, + * and {@link SandboxHandle.verifiesCliAtLaunch}. + */ + session?: boolean + /** The agent's self-termination deadline when the handle was made. */ + expiresAtMs: number + /** + * Home directory of the identity code runs as; relative file paths resolve against it, as on + * E2B. Only an unprivileged agent (a developer machine or CI) has one other than `/home/user`. + */ + userHome?: string + /** Provider teardown (for Kubernetes, deleting the pod). */ + kill(): Promise +} + +type TerminalEvent = Extract + +/** The stream ended or broke before a terminal event; the process may still be running. */ +class StreamInterruptedError extends Error { + constructor(cause?: unknown) { + super('Sandbox agent event stream ended before the process finished', { cause }) + this.name = 'StreamInterruptedError' + } +} + +/** Wraps a body so it errors unless exactly `expectedBytes` arrive. */ +function exactLength( + body: ReadableStream, + expectedBytes: number +): ReadableStream { + let received = 0 + return body.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + received += chunk.byteLength + if (received > expectedBytes) { + controller.error(new Error('Sandbox agent sent more bytes than the file held')) + return + } + controller.enqueue(chunk) + }, + flush(controller) { + if (received !== expectedBytes) { + controller.error(new Error('Sandbox agent file read was truncated')) + } + }, + }) + ) +} + +class AgentSandboxHandle implements SandboxHandle { + readonly sandboxId: string + readonly verifiesCliAtLaunch: boolean + readonly extendLifetime?: (lifetimeMs: number) => Promise + readonly outlives?: (lifetimeMs: number, fromMs: number) => boolean + private readonly client: SandboxAgentClient + private readonly language: CodeLanguage + private readonly home: string + private deadlineAtMs: number + private killPromise: Promise | null = null + private killed = false + + constructor(private readonly connection: AgentSandboxConnection) { + this.sandboxId = connection.sandboxId + this.client = new SandboxAgentClient(connection.baseUrl, connection.token) + this.language = connection.language ?? CodeLanguage.Python + this.home = connection.userHome ?? SANDBOX_AGENT_USER.home + this.deadlineAtMs = connection.expiresAtMs + this.verifiesCliAtLaunch = connection.session === true + if (connection.session) { + this.outlives = (lifetimeMs, fromMs) => this.deadlineAtMs >= fromMs + lifetimeMs + this.extendLifetime = (lifetimeMs) => this.extendDeadline(lifetimeMs) + } + } + + private async extendDeadline(lifetimeMs: number): Promise { + const now = Date.now() + if (this.deadlineAtMs >= now + lifetimeMs) return + const granted = lifetimeResponseSchema.parse( + await this.client.requestJson(SANDBOX_AGENT_ROUTES.lifetime, { + method: 'POST', + json: { expiresAtMs: now + lifetimeMs }, + retry: true, + }) + ) + this.deadlineAtMs = Math.max(this.deadlineAtMs, granted.expiresAtMs) + } + + /** Absolute paths pass through; relative ones resolve against the user's home, as on E2B. */ + private resolve(path: string): string { + return path.startsWith('/') ? path : posix.join(this.home, path) + } + + runCode(code: string, options: CodeRunOptions): Promise { + return runCodeAsProcess( + { + writeFile: (path, content) => this.writeFile(path, content), + removeFile: (path) => this.removeFile(path), + run: (command, runOptions) => this.runCommand(command, runOptions), + }, + this.language, + code, + options + ) + } + + /** + * Launches under a fresh processKey and follows its event stream, reattaching from the last + * sequence number whenever the stream drops. The key makes every start and reattach safe to + * repeat: the agent launches a key at most once, so `atMostOnce` holds through any transport + * failure. When the outcome can no longer be observed, an `atMostOnce` command fails with + * {@link SandboxLaunchIndeterminateError} rather than being run again. + */ + async runCommand(command: string, options: RunCommandOptions): Promise { + options.signal?.throwIfAborted() + const processKey = generateId() + const maxOutputBytes = options.maxOutputBytes ?? MAX_SANDBOX_PROCESS_OUTPUT_BYTES + const timeoutMs = Math.max( + 1, + Math.min(Math.ceil(options.timeoutMs), SANDBOX_AGENT_MAX_TIMEOUT_MS) + ) + const request: StartProcessRequest = { + processKey, + shell: command, + envs: options.envs ?? {}, + user: options.rootUser ? 'root' : 'user', + timeoutMs, + maxOutputBytes: Math.min(maxOutputBytes, SANDBOX_AGENT_MAX_OUTPUT_BYTES), + ...(options.verifyCli ? { verifyCli: options.verifyCli } : {}), + } + + const budget = new SandboxProcessOutputBudget(maxOutputBytes) + const retainStdout = options.onStdout === undefined + const retainStderr = options.onStderr === undefined + let stdout = '' + let stderr = '' + let lastSeq = -1 + let started = false + + const collected = () => ({ + stdout: retainStdout ? stdout : tailStreamedSandboxOutput(stdout), + stderr: retainStderr ? stderr : tailStreamedSandboxOutput(stderr), + }) + /** Matches the E2B adapter: exit 124, with a note when the command printed nothing to stderr. */ + const timedOutResult = (): SandboxCommandResult => { + const output = collected() + return { + ...output, + stderr: output.stderr || `Command timed out after ${options.timeoutMs}ms`, + exitCode: 124, + timedOut: true, + } + } + + const streamAbort = new AbortController() + const onAbort = () => streamAbort.abort(options.signal?.reason) + options.signal?.addEventListener('abort', onAbort, { once: true }) + + const apply = (event: ProcessEvent): TerminalEvent | undefined => { + if (event.type === 'heartbeat' || event.seq <= lastSeq) return undefined + lastSeq = event.seq + switch (event.type) { + case 'started': + started = true + return undefined + case 'stdout': + case 'stderr': { + budget.add(event.data) + const isStdout = event.type === 'stdout' + const callback = isStdout ? options.onStdout : options.onStderr + callback?.(event.data) + if (isStdout) { + stdout = retainStdout + ? stdout + event.data + : appendStreamedSandboxOutput(stdout, event.data) + } else { + stderr = retainStderr + ? stderr + event.data + : appendStreamedSandboxOutput(stderr, event.data) + } + return undefined + } + default: + return event + } + } + + const follow = async (response: Response): Promise => { + if (!response.body) throw new StreamInterruptedError() + const decoder = new NdjsonDecoder() + try { + for await (const chunk of response.body) { + for (const value of decoder.push(chunk)) { + const terminal = apply(processEventSchema.parse(value)) + if (terminal) return terminal + } + } + decoder.finish() + } catch (error) { + if (error instanceof SandboxOutputLimitError) throw error + throw new StreamInterruptedError(error) + } + throw new StreamInterruptedError() + } + + try { + let terminal: TerminalEvent | undefined + let response: Response + try { + response = await this.client.request(SANDBOX_AGENT_ROUTES.processes, { + method: 'POST', + json: request, + signal: streamAbort.signal, + timeout: false, + retry: true, + }) + } catch (error) { + options.signal?.throwIfAborted() + if (error instanceof SandboxAgentRequestError) throw error + if (options.atMostOnce) + throw new SandboxLaunchIndeterminateError(PROVIDER_LABEL, { cause: error }) + throw error + } + + for (let reconnects = 0; terminal === undefined; reconnects++) { + try { + terminal = await follow(response) + } catch (error) { + if (!(error instanceof StreamInterruptedError) || options.signal?.aborted) throw error + if (reconnects >= MAX_STREAM_RECONNECTS) throw this.unobservable(error, started, options) + logger.warn('Sandbox agent event stream dropped; reattaching to the same process', { + sandboxId: this.sandboxId, + processKey, + lastSeq, + }) + try { + response = await this.client.request(sandboxAgentProcessEventsPath(processKey), { + query: { from: String(lastSeq + 1) }, + signal: streamAbort.signal, + timeout: false, + retry: true, + }) + } catch (reattachError) { + options.signal?.throwIfAborted() + throw this.unobservable(reattachError, started, options) + } + } + } + + if (terminal.type === 'rejected') { + if (terminal.reason === 'cli_stale') throw new SessionCliStaleError() + if (terminal.reason === 'cli_check_failed') throw new SessionCliVerificationError() + options.signal?.throwIfAborted() + throw new Error( + `Sandbox command did not start (${terminal.reason})${terminal.message ? `: ${terminal.message}` : ''}` + ) + } + if (terminal.outputLimitExceeded) { + throw new SandboxOutputLimitError(maxOutputBytes + 1, maxOutputBytes, 'process') + } + if (terminal.timedOut) return timedOutResult() + return { ...collected(), exitCode: terminal.exitCode } + } catch (error) { + if (budget.error || options.signal?.aborted) { + await this.stopProcess(processKey, lastSeq) + } + if (budget.error) throw budget.error + if (options.signal?.aborted) { + // A session caller's own deadline can stop the command before the agent's timeout does, + // as on E2B; a Stop stays a cancellation. + if (this.connection.session && isTimeoutAbortReason(options.signal.reason)) { + return timedOutResult() + } + throw options.signal.reason + } + throw error + } finally { + options.signal?.removeEventListener('abort', onAbort) + } + } + + /** The process's outcome can no longer be observed; an at-most-once caller must not rerun it. */ + private unobservable(error: unknown, started: boolean, options: RunCommandOptions): Error { + if (options.atMostOnce) + return new SandboxLaunchIndeterminateError(PROVIDER_LABEL, { cause: error }) + return new Error( + `Lost the sandbox command's ${started ? 'output' : 'start'}: ${getErrorMessage(error)}`, + { cause: error } + ) + } + + /** Kills a command's process group (or cancels its pending launch) and waits briefly for its exit. */ + private async stopProcess(processKey: string, lastSeq: number): Promise { + const signal = AbortSignal.timeout(CANCEL_SETTLE_MS) + try { + await this.client.request(sandboxAgentProcessSignalPath(processKey), { + method: 'POST', + json: { signal: 'SIGKILL' }, + signal, + retry: true, + }) + const response = await this.client.request(sandboxAgentProcessEventsPath(processKey), { + query: { from: String(lastSeq + 1) }, + signal, + timeout: false, + }) + await response.body?.pipeTo(new WritableStream()) + } catch (error) { + logger.warn('Could not confirm a cancelled sandbox command stopped', { + sandboxId: this.sandboxId, + processKey, + error: getErrorMessage(error), + }) + } + } + + async getFileSize(path: string): Promise { + const stat = fileStatResponseSchema.parse( + await this.client.requestJson(SANDBOX_AGENT_ROUTES.fileStat, { + query: { path: this.resolve(path) }, + retry: true, + }) + ) + if (stat.kind !== 'file') throw new SandboxOutputFileError(path) + return stat.size + } + + readFile(path: string): Promise { + return this.readFileWithLimit(path, { + maxBytes: MAX_SANDBOX_OUTPUT_BYTES, + encoding: 'utf8', + }).then(({ content }) => content) + } + + private async openRead( + path: string, + maxBytes: number | undefined, + signal: AbortSignal | undefined + ): Promise> { + let response: Response + try { + response = await this.client.request(SANDBOX_AGENT_ROUTES.files, { + query: { + path: this.resolve(path), + ...(maxBytes !== undefined ? { maxBytes: String(maxBytes) } : {}), + }, + signal, + timeout: false, + retry: true, + }) + } catch (error) { + if (error instanceof SandboxAgentRequestError) { + if (error.code === 'too_large' && maxBytes !== undefined) { + throw new SandboxOutputLimitError(error.observedBytes ?? maxBytes + 1, maxBytes) + } + if (error.code === 'not_a_file') throw new SandboxOutputFileError(path) + } + throw error + } + const declared = Number(response.headers.get(SANDBOX_AGENT_FILE_SIZE_HEADER)) + if (!response.body || !Number.isSafeInteger(declared) || declared < 0) { + throw new Error('Sandbox agent file read is missing its size') + } + return exactLength(response.body, declared) + } + + async readFileStream( + path: string, + options: { signal: AbortSignal } + ): Promise> { + options.signal.throwIfAborted() + return this.openRead(path, undefined, options.signal) + } + + async readFileWithLimit( + path: string, + options: { maxBytes: number; encoding: 'utf8' | 'base64'; signal?: AbortSignal } + ): Promise<{ content: string; byteLength: number }> { + const size = await this.getFileSize(path) + if (size > options.maxBytes) throw new SandboxOutputLimitError(size, options.maxBytes) + const stream = await this.openRead(path, options.maxBytes, options.signal) + try { + const buffer = await readStreamToBufferWithLimit(stream, { + maxBytes: options.maxBytes, + label: 'Sandbox output file', + signal: options.signal, + }) + return { + content: buffer.toString(options.encoding === 'base64' ? 'base64' : 'utf8'), + byteLength: buffer.byteLength, + } + } catch (error) { + if (isPayloadSizeLimitError(error)) { + throw new SandboxOutputLimitError( + error.observedBytes ?? options.maxBytes + 1, + options.maxBytes + ) + } + throw error + } + } + + async writeFile(path: string, content: string | ArrayBuffer): Promise { + await this.client.request(SANDBOX_AGENT_ROUTES.files, { + method: 'PUT', + query: { path: this.resolve(path) }, + body: content, + retry: true, + }) + } + + async writeFileStream( + path: string, + content: ReadableStream, + options: { signal: AbortSignal } + ): Promise { + options.signal.throwIfAborted() + await this.client.request(SANDBOX_AGENT_ROUTES.files, { + method: 'PUT', + query: { path: this.resolve(path) }, + body: content, + signal: options.signal, + timeout: false, + }) + options.signal.throwIfAborted() + } + + async removeFile(path: string): Promise { + await this.client.request(SANDBOX_AGENT_ROUTES.files, { + method: 'DELETE', + query: { path: this.resolve(path) }, + retry: true, + }) + } + + async listFiles(path: string, options?: { depth?: number }): Promise { + const listing = listFilesResponseSchema.parse( + await this.client.requestJson(SANDBOX_AGENT_ROUTES.fileList, { + query: { + path: this.resolve(path), + ...(options?.depth !== undefined ? { depth: String(options.depth) } : {}), + }, + retry: true, + }) + ) + const directory = this.resolve(path) + const entries: SandboxDirectoryEntry[] = [] + for (const entry of listing.entries) { + const resolved = resolveSandboxDirectoryEntryPath(directory, entry.path) + if (!resolved) continue + entries.push({ ...resolved, kind: entry.kind, size: entry.size }) + } + return entries + } + + async kill(): Promise { + if (this.killed) return + this.killPromise ??= this.connection + .kill() + .then(() => { + this.killed = true + }) + .finally(() => { + if (!this.killed) this.killPromise = null + }) + await this.killPromise + } +} + +/** + * A {@link SandboxHandle} over `sim-sandbox-agent`'s protocol, independent of the control plane + * that created the sandbox. `runCode` runs exactly as the E2B adapter's does (the same files, + * preload, and failure parsing, via {@link runCodeAsProcess}); commands and file operations go to + * the agent over HTTP. File streaming is always available, as workbench uploads require. + */ +export function createAgentSandboxHandle( + connection: AgentSandboxConnection +): SandboxHandle & Required> { + return new AgentSandboxHandle(connection) +} diff --git a/apps/sim/package.json b/apps/sim/package.json index 8928359d079..f2d667339dc 100644 --- a/apps/sim/package.json +++ b/apps/sim/package.json @@ -167,6 +167,7 @@ "@sim/platform-authz": "workspace:*", "@sim/realtime-protocol": "workspace:*", "@sim/runtime-secrets": "workspace:*", + "@sim/sandbox-agent-protocol": "workspace:*", "@sim/security": "workspace:*", "@sim/table-cells": "workspace:*", "@sim/terminal-protocol": "workspace:*", diff --git a/bun.lock b/bun.lock index ecaf6e2d979..5f9c86c2bf0 100644 --- a/bun.lock +++ b/bun.lock @@ -329,6 +329,7 @@ "@sim/platform-authz": "workspace:*", "@sim/realtime-protocol": "workspace:*", "@sim/runtime-secrets": "workspace:*", + "@sim/sandbox-agent-protocol": "workspace:*", "@sim/security": "workspace:*", "@sim/table-cells": "workspace:*", "@sim/terminal-protocol": "workspace:*", diff --git a/knip.jsonc b/knip.jsonc index 3eac2e454e4..159b2dc5cb1 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -40,7 +40,10 @@ // Compile-time fixture compatibility assertion, included by tsconfig. "lib/table/fixture-contract.ts", // scripts/generate-docs.ts imports this through pathToFileURL. - "app/(landing)/integrations/data/landing-content.ts" + "app/(landing)/integrations/data/landing-content.ts", + // Sandbox-agent handle consumed only by the stacked Kubernetes sandbox provider. Remove + // this entry once that provider imports it. + "lib/execution/remote-sandbox/agent/handle.ts" ], // Required/discoverable barrels whose children have direct live imports. // Ignore only the barrel file finding, so it cannot keep dead children alive. From a832bdc951d363983abe0d9f111c82db45d56b82 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 13:47:35 -0600 Subject: [PATCH 09/78] feat(sandbox): add the sandbox-agent carrier image docker/sandbox-agent.Dockerfile compiles sim-sandbox-agent for the build platform on Debian (glibc) Bun and ships it alone in a scratch image at /sim-sandbox-agent. An init container copies it into a shared volume with its install command. Publishing is wired separately. --- docker/sandbox-agent.Dockerfile | 59 +++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 docker/sandbox-agent.Dockerfile diff --git a/docker/sandbox-agent.Dockerfile b/docker/sandbox-agent.Dockerfile new file mode 100644 index 00000000000..cc8f5e6c038 --- /dev/null +++ b/docker/sandbox-agent.Dockerfile @@ -0,0 +1,59 @@ +# ======================================== +# Carrier image for sim-sandbox-agent, the daemon inside every self-hosted sandbox. +# +# Holds one file, /sim-sandbox-agent, compiled for the platform being built +# (`docker buildx build --platform linux/amd64,linux/arm64`). It never runs as a +# sandbox itself: a Kubernetes init container runs +# `/sim-sandbox-agent install /opt/sim-agent/sim-sandbox-agent` to copy the +# binary into a shared volume, so any sandbox image can start the agent without +# baking it in. +# ======================================== + +# ======================================== +# Base Stage: Debian (glibc) Bun, matching the Debian sandbox images +# ======================================== +FROM oven/bun:1.4.4-slim AS base + +# ======================================== +# Pruner Stage: Emit the monorepo subset @sim/sandbox-agent builds from +# ======================================== +FROM base AS pruner +WORKDIR /app + +COPY . . + +RUN TURBO_VERSION="$(bun -e "console.log(require('./package.json').devDependencies.turbo)")" && \ + bunx --bun "turbo@${TURBO_VERSION}" prune @sim/sandbox-agent --docker + +# ======================================== +# Builder Stage: Compile a single self-contained binary +# ======================================== +FROM base AS builder +WORKDIR /app + +COPY --from=pruner /app/out/json/ ./ +COPY --from=pruner /app/out/bun.lock ./bun.lock + +# Not --frozen-lockfile: the narrowed manifests no longer match the pruned +# lockfile. Bun keeps every locked resolution, and full-repository CI owns +# frozen-lockfile validation. +RUN --mount=type=cache,id=bun-cache,target=/root/.bun/install/cache \ + bun install --linker=hoisted --omit=dev --ignore-scripts + +COPY --from=pruner /app/out/full/ ./ + +# Compiles for the build container's own platform, which buildx sets to the +# target platform. Bun inlines NODE_ENV at build time. +RUN cd apps/sandbox-agent && \ + NODE_ENV=production bun build --compile --minify src/main.ts --outfile /out/sim-sandbox-agent && \ + /out/sim-sandbox-agent install /out/verified-copy && \ + rm /out/verified-copy + +# ======================================== +# Runner Stage: The binary alone +# ======================================== +FROM scratch + +COPY --from=builder /out/sim-sandbox-agent /sim-sandbox-agent + +ENTRYPOINT ["/sim-sandbox-agent"] From 2c437e7dc095096168eefdb8e1148a54c2216da9 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 13:49:26 -0600 Subject: [PATCH 10/78] fix(sandbox): pass the image environment to sandbox processes Children now start from the agent's startup environment, so variables an image declares with ENV reach commands as they do on E2B, minus every SIM_SANDBOX_* variable (the token digest included) and the service variables Kubernetes injects (KUBERNETES_*, _SERVICE_*, and link-style _PORT*). Identity variables and the request's envs apply on top. The agent also warns at startup when it is PID 1, where orphaned processes are never reaped. --- apps/sandbox-agent/src/config.ts | 37 ++++++++++++++++---- apps/sandbox-agent/src/main.ts | 5 +++ apps/sandbox-agent/src/processes.test.ts | 43 ++++++++++++++++++------ 3 files changed, 67 insertions(+), 18 deletions(-) diff --git a/apps/sandbox-agent/src/config.ts b/apps/sandbox-agent/src/config.ts index 1b5d2f282ae..d26270e012f 100644 --- a/apps/sandbox-agent/src/config.ts +++ b/apps/sandbox-agent/src/config.ts @@ -19,8 +19,35 @@ export interface AgentConfig { const DEFAULT_PATH = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' -/** Variables a child inherits from the agent; everything else in the agent's env stays behind. */ -const INHERITED_VARIABLES = ['PATH', 'LANG', 'TZ'] as const +/** + * Variables Kubernetes injects describing cluster services: `KUBERNETES_*` always, plus Docker + * link-style service variables (`_SERVICE_HOST`, `_SERVICE_PORT[_]`, + * `_PORT[__[_PROTO|_PORT|_ADDR]]`) unless `enableServiceLinks` is off. They name + * orchestrator internals, not anything the image defined, so children never see them. + */ +const ORCHESTRATOR_VARIABLE = + /^(KUBERNETES_\w*|[A-Z0-9_]+_SERVICE_(HOST|PORT(_\w+)?)|[A-Z0-9_]+_PORT(_\d+_(TCP|UDP|SCTP)(_(PROTO|PORT|ADDR))?)?)$/ + +/** + * The environment a child starts from: the agent's own startup environment (so variables an + * image declares with `ENV` reach commands, as on E2B) minus every agent-owned `SIM_SANDBOX_*` + * variable and every orchestrator-injected one. A bare `_PORT` is dropped only when it + * holds a link URL (`tcp://…`), so an image's own `FOO_PORT=8080` survives. + */ +function childBaseEnvironment(env: NodeJS.ProcessEnv): Record { + const base: Record = {} + for (const [name, value] of Object.entries(env)) { + if (value === undefined || name.startsWith(SANDBOX_AGENT_ENV_PREFIX)) continue + if (ORCHESTRATOR_VARIABLE.test(name)) { + const isBarePort = + !name.startsWith('KUBERNETES_') && /_PORT$/.test(name) && !/_SERVICE_PORT$/.test(name) + if (!isBarePort || /^(tcp|udp|sctp):\/\//.test(value)) continue + } + base[name] = value + } + base.PATH ||= DEFAULT_PATH + return base +} /** * Reads the agent's configuration and then deletes every `SIM_SANDBOX_*` variable from its own @@ -46,11 +73,7 @@ export function readAgentConfig(env: NodeJS.ProcessEnv): AgentConfig { throw new Error(`${SANDBOX_AGENT_PORT_ENV} must be a TCP port`) } - const baseEnvironment: Record = { PATH: DEFAULT_PATH } - for (const name of INHERITED_VARIABLES) { - const value = env[name] - if (value) baseEnvironment[name] = value - } + const baseEnvironment = childBaseEnvironment(env) const config: AgentConfig = { tokenSha256: Buffer.from(tokenHex, 'hex'), diff --git a/apps/sandbox-agent/src/main.ts b/apps/sandbox-agent/src/main.ts index fbe1c1d8509..37a23cc6f7d 100644 --- a/apps/sandbox-agent/src/main.ts +++ b/apps/sandbox-agent/src/main.ts @@ -32,6 +32,11 @@ async function serve(): Promise { processes, lifetime, }) + if (process.pid === 1) { + // With `shareProcessNamespace: true` the pod's pause container is PID 1 and reaps orphans; + // the agent cannot, so as PID 1 every exited grandchild stays a zombie. + logger.warn('Sandbox agent is PID 1; orphaned processes will not be reaped') + } logger.info('Sandbox agent listening', { host: config.host, port: server.port, diff --git a/apps/sandbox-agent/src/processes.test.ts b/apps/sandbox-agent/src/processes.test.ts index 5b681007296..5c84cac0de3 100644 --- a/apps/sandbox-agent/src/processes.test.ts +++ b/apps/sandbox-agent/src/processes.test.ts @@ -14,7 +14,18 @@ import { isAlive, readEvents, startTestAgent, stdoutOf, type TestAgent } from '@ let agent: TestAgent beforeAll(async () => { - agent = await startTestAgent({ env: { UNRELATED_AGENT_SECRET: 'must-not-leak' } }) + agent = await startTestAgent({ + env: { + IMAGE_DEFINED: 'from-image', + APP_PORT: '8080', + KUBERNETES_SERVICE_HOST: '10.0.0.1', + KUBERNETES_PORT: 'tcp://10.0.0.1:443', + KUBERNETES_PORT_443_TCP_PORT: '443', + REDIS_SERVICE_PORT: '6379', + REDIS_PORT: 'tcp://10.0.0.9:6379', + REDIS_PORT_6379_TCP_ADDR: '10.0.0.9', + }, + }) }) afterAll(async () => { @@ -33,18 +44,28 @@ describe('process launch', () => { expect(events.at(-1)).toMatchObject({ type: 'exit', exitCode: 3 }) }) - it('gives children only the fixed base environment plus the request envs', async () => { + it('passes image variables to children but never agent-owned or orchestrator ones', async () => { const events = await readEvents( - await agent.startProcess({ argv: ['env'], envs: { MINE: '1' } }) + await agent.startProcess({ argv: ['env'], envs: { MINE: '1', HOME: '/override' } }) + ) + const environment = Object.fromEntries( + stdoutOf(events) + .split('\n') + .filter(Boolean) + .map((line) => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)]) ) - const names = stdoutOf(events) - .split('\n') - .filter(Boolean) - .map((line) => line.slice(0, line.indexOf('='))) - expect(names).toContain('MINE') - expect(names).toContain('HOME') - expect(names.filter((name) => name.startsWith('SIM_SANDBOX_'))).toEqual([]) - expect(names).not.toContain('UNRELATED_AGENT_SECRET') + expect(environment).toMatchObject({ + MINE: '1', + HOME: '/override', + IMAGE_DEFINED: 'from-image', + APP_PORT: '8080', + }) + expect( + Object.keys(environment).filter( + (name) => name.startsWith('SIM_SANDBOX_') || name.startsWith('KUBERNETES_') + ) + ).toEqual([]) + expect(Object.keys(environment).filter((name) => name.startsWith('REDIS_'))).toEqual([]) }) it('rejects a relative working directory', async () => { From bc309e137a078711330f2bdd0f07144787224ea1 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:02:52 -0600 Subject: [PATCH 11/78] fix(sandbox): run sandbox-user file operations in an unprivileged worker File operations for the sandbox user ran in the root daemon, which followed symlinks in user-writable parents: a PUT to /home/user/inputs/passwd with inputs -> /etc replaced /etc/passwd, and recursive deletes and the parent chown could be steered the same way. Every file route now takes user=root|user (default user, as E2B's files API acts as the sandbox user; PUT's owner parameter becomes user). User operations go to a long-lived file worker: the agent re-executed from /proc/self/exe as uid/gid 1000, talking over credit-controlled framed IPC on stdio, so bodies stream with per-stream backpressure and the kernel checks every path component. Only user=root operations run in the daemon. The daemon bounds and validates every worker frame, since session code can run as the worker's uid. --- apps/sandbox-agent/src/file-worker.ts | 322 ++++++++++++++++++ apps/sandbox-agent/src/files.test.ts | 36 ++ apps/sandbox-agent/src/files.ts | 33 +- apps/sandbox-agent/src/install.ts | 6 +- apps/sandbox-agent/src/ipc.test.ts | 41 +++ apps/sandbox-agent/src/ipc.ts | 275 +++++++++++++++ apps/sandbox-agent/src/main.ts | 17 +- apps/sandbox-agent/src/processes.test.ts | 7 +- apps/sandbox-agent/src/self.ts | 24 ++ apps/sandbox-agent/src/server.ts | 49 ++- apps/sandbox-agent/src/verify-cli.ts | 8 +- .../execution/remote-sandbox/agent/handle.ts | 4 +- .../sandbox-agent-protocol/src/schemas.ts | 19 +- 13 files changed, 773 insertions(+), 68 deletions(-) create mode 100644 apps/sandbox-agent/src/file-worker.ts create mode 100644 apps/sandbox-agent/src/ipc.test.ts create mode 100644 apps/sandbox-agent/src/ipc.ts create mode 100644 apps/sandbox-agent/src/self.ts diff --git a/apps/sandbox-agent/src/file-worker.ts b/apps/sandbox-agent/src/file-worker.ts new file mode 100644 index 00000000000..6c0ccc696a8 --- /dev/null +++ b/apps/sandbox-agent/src/file-worker.ts @@ -0,0 +1,322 @@ +import { type ChildProcess, spawn } from 'node:child_process' +import { createLogger } from '@sim/logger' +import { + type FileStatResponse, + fileStatResponseSchema, + type ListFilesResponse, + listFilesResponseSchema, + sandboxAgentErrorBodySchema, +} from '@sim/sandbox-agent-protocol' +import { getErrorMessage } from '@sim/utils/errors' +import { z } from 'zod' +import type { ProcessIdentity } from '@/accounts' +import { + FileOperationError, + listDirectory, + openFileForRead, + removePath, + statFile, + writeFileAtomically, +} from '@/files' +import { + CreditGate, + decodeCredit, + decodeJson, + encodeCreditFrame, + encodeFrame, + encodeJsonFrame, + FRAME_KIND, + type Frame, + FrameDecoder, + InboundStream, + pumpData, +} from '@/ipc' +import { AGENT_MODE_ENV, AGENT_MODES, selfCommand } from '@/self' + +const logger = createLogger('SandboxAgentFileWorker') + +const fileCallSchema = z.discriminatedUnion('op', [ + z.object({ op: z.literal('stat'), path: z.string() }), + z.object({ op: z.literal('list'), path: z.string(), depth: z.number().int().positive() }), + z.object({ op: z.literal('remove'), path: z.string() }), + z.object({ op: z.literal('read'), path: z.string(), maxBytes: z.number().int().optional() }), + z.object({ op: z.literal('write'), path: z.string() }), +]) + +type FileCall = z.infer + +const readResultSchema = z.object({ size: z.number().int().nonnegative() }) + +function errorPayload(error: unknown) { + if (error instanceof FileOperationError) { + return { + error: { + code: error.code, + message: error.message, + ...(error.observedBytes !== undefined ? { observedBytes: error.observedBytes } : {}), + }, + } + } + return { error: { code: 'internal', message: getErrorMessage(error) } } +} + +/** + * The worker side: serves file operations over stdin/stdout until stdin closes. It runs as the + * sandbox user, so the kernel checks every path component (a symlinked parent pointing at `/etc` + * is just a directory the user cannot write). It never logs: stdout carries frames. + */ +export async function runFileWorker(): Promise { + const decoder = new FrameDecoder() + const send = (frame: Uint8Array) => process.stdout.write(frame) + const uploads = new Map() + const downloads = new Map() + + const settle = (id: number, value: unknown): void => { + send(encodeJsonFrame(FRAME_KIND.result, id, value)) + } + const fail = (id: number, error: unknown): void => { + send(encodeJsonFrame(FRAME_KIND.error, id, errorPayload(error))) + } + + const handle = async (id: number, call: FileCall): Promise => { + switch (call.op) { + case 'stat': + return settle(id, await statFile(call.path)) + case 'list': + return settle(id, await listDirectory(call.path, call.depth)) + case 'remove': + await removePath(call.path) + return settle(id, {}) + case 'read': { + const { size, body } = await openFileForRead(call.path, call.maxBytes) + const gate = new CreditGate() + downloads.set(id, gate) + settle(id, { size }) + try { + await pumpData(body, gate, send, id) + } finally { + downloads.delete(id) + } + return + } + case 'write': { + const inbound = new InboundStream( + (bytes) => send(encodeCreditFrame(id, bytes)), + () => {} + ) + uploads.set(id, inbound) + try { + await writeFileAtomically(call.path, inbound.stream) + } finally { + uploads.delete(id) + } + return settle(id, {}) + } + } + } + + const dispatch = (frame: Frame) => { + switch (frame.kind) { + case FRAME_KIND.call: { + const parsed = fileCallSchema.safeParse(decodeJson(frame.payload)) + if (!parsed.success) return fail(frame.id, new Error('Malformed file call')) + void handle(frame.id, parsed.data).catch((error: unknown) => fail(frame.id, error)) + return + } + case FRAME_KIND.data: + if (!uploads.get(frame.id)?.push(frame.payload)) { + uploads.get(frame.id)?.fail(new Error('Upload overran its credit')) + } + return + case FRAME_KIND.end: + uploads.get(frame.id)?.end() + return + case FRAME_KIND.credit: + downloads.get(frame.id)?.grant(decodeCredit(frame.payload)) + return + case FRAME_KIND.cancel: + uploads.get(frame.id)?.fail(new Error('Upload cancelled')) + downloads.get(frame.id)?.close() + return + } + } + + await new Promise((resolve, reject) => { + process.stdin.on('data', (chunk: Buffer) => { + try { + for (const frame of decoder.push(chunk)) dispatch(frame) + } catch (error) { + reject(error) + } + }) + process.stdin.on('end', resolve) + }) +} + +interface PendingCall { + resolve: (value: unknown) => void + reject: (error: Error) => void + /** Present on a read once the worker has answered; fed by its `data` frames. */ + download?: InboundStream + /** Present on a write; gates the upload's `data` frames. */ + upload?: CreditGate +} + +/** + * The daemon side: one long-lived worker process running as `identity`, restarted on demand if + * it dies. Every reply is validated, since the worker's uid is one sandbox code can also hold. + */ +export class FileWorker { + private child?: ChildProcess + private decoder = new FrameDecoder() + private nextId = 1 + private readonly pending = new Map() + + constructor( + private readonly identity: ProcessIdentity, + private readonly baseEnvironment: Record + ) {} + + async stat(path: string): Promise { + return fileStatResponseSchema.parse(await this.call({ op: 'stat', path })) + } + + async list(path: string, depth: number): Promise { + return listFilesResponseSchema.parse(await this.call({ op: 'list', path, depth })) + } + + async remove(path: string): Promise { + await this.call({ op: 'remove', path }) + } + + async read( + path: string, + maxBytes: number | undefined + ): Promise<{ size: number; body: ReadableStream }> { + const id = this.nextId++ + const download = new InboundStream( + (bytes) => this.send(encodeCreditFrame(id, bytes)), + () => { + this.pending.delete(id) + this.send(encodeFrame(FRAME_KIND.cancel, id)) + } + ) + const result = readResultSchema.parse( + await this.call({ op: 'read', path, ...(maxBytes !== undefined ? { maxBytes } : {}) }, id, { + download, + }) + ) + return { size: result.size, body: download.stream } + } + + async write(path: string, body: ReadableStream | null): Promise { + const id = this.nextId++ + const upload = new CreditGate() + const settled = this.call({ op: 'write', path }, id, { upload }) + const source = body ?? new ReadableStream({ start: (c) => c.close() }) + const pumped = pumpData(source, upload, (frame) => this.send(frame), id).catch( + (error: unknown) => { + this.send(encodeFrame(FRAME_KIND.cancel, id)) + throw error + } + ) + const [, sent] = await Promise.all([settled, pumped]) + if (!sent) throw new FileOperationError('internal', 'Upload was refused mid-stream') + } + + private call( + call: FileCall, + id = this.nextId++, + streams: Pick = {} + ): Promise { + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve, reject, ...streams }) + this.send(encodeJsonFrame(FRAME_KIND.call, id, call)) + }) + } + + private send(frame: Uint8Array): void { + this.ensureStarted().stdin?.write(frame) + } + + private ensureStarted(): ChildProcess { + if (this.child) return this.child + const { file, args } = selfCommand() + const child = spawn(file, args, { + cwd: this.identity.home, + env: { + ...this.baseEnvironment, + HOME: this.identity.home, + [AGENT_MODE_ENV]: AGENT_MODES.fileWorker, + }, + stdio: ['pipe', 'pipe', 'inherit'], + ...(this.identity.uid !== undefined + ? { uid: this.identity.uid, gid: this.identity.gid } + : {}), + }) + this.child = child + this.decoder = new FrameDecoder() + child.stdin?.on('error', () => {}) + child.stdout?.on('data', (chunk: Buffer) => { + try { + for (const frame of this.decoder.push(chunk)) this.receive(frame) + } catch (error) { + logger.error('File worker sent a malformed frame; restarting it', { + error: getErrorMessage(error), + }) + child.kill('SIGKILL') + } + }) + child.on('exit', () => { + if (this.child === child) this.child = undefined + const failure = new FileOperationError('internal', 'The file worker exited') + for (const pending of this.pending.values()) { + pending.reject(failure) + pending.download?.fail(failure) + pending.upload?.close() + } + this.pending.clear() + }) + return child + } + + private receive(frame: Frame): void { + const pending = this.pending.get(frame.id) + if (!pending) return + switch (frame.kind) { + case FRAME_KIND.result: + if (!pending.download) this.pending.delete(frame.id) + pending.resolve(decodeJson(frame.payload)) + return + case FRAME_KIND.error: { + this.pending.delete(frame.id) + const parsed = sandboxAgentErrorBodySchema.safeParse(decodeJson(frame.payload)) + const failure = parsed.success + ? new FileOperationError( + parsed.data.error.code, + parsed.data.error.message, + parsed.data.error.observedBytes + ) + : new FileOperationError('internal', 'The file worker failed') + pending.reject(failure) + pending.download?.fail(failure) + pending.upload?.close() + return + } + case FRAME_KIND.data: + if (!pending.download?.push(frame.payload)) { + throw new Error('File worker overran its credit') + } + return + case FRAME_KIND.end: + this.pending.delete(frame.id) + pending.download?.end() + return + case FRAME_KIND.credit: + pending.upload?.grant(decodeCredit(frame.payload)) + return + default: + throw new Error('Unexpected frame from the file worker') + } + } +} diff --git a/apps/sandbox-agent/src/files.test.ts b/apps/sandbox-agent/src/files.test.ts index 748098504cf..2ca8ca4fc68 100644 --- a/apps/sandbox-agent/src/files.test.ts +++ b/apps/sandbox-agent/src/files.test.ts @@ -56,6 +56,7 @@ describe('file reads', () => { const writer = await agent.startProcess({ processKey: writerKey, shell: `while true; do head -c 1048576 /dev/zero >> ${target}; done`, + user: 'root', timeoutMs: 20_000, }) try { @@ -151,3 +152,38 @@ describe('directory listing', () => { expect(entries.map((entry) => path.relative(listed, entry.path))).toEqual(['a']) }) }) + +describe('file identity', () => { + const uid = process.getuid?.() + const isRoot = uid === 0 + + it('runs a user=root write in the daemon itself', async () => { + const target = path.join(agent.root, `as-root-${generateId()}`) + const response = await agent.request( + fileRoute(SANDBOX_AGENT_ROUTES.files, { path: target, user: 'root' }), + { method: 'PUT', body: 'root write' } + ) + expect(response.status).toBe(204) + expect(readFileSync(target, 'utf8')).toBe('root write') + }) + + it.skipIf(!isRoot)( + `refuses a user write steered through a symlinked parent into a root-owned directory${isRoot ? '' : ` [skipped: needs root to run the file worker as uid 1000; this run is uid ${uid}]`}`, + async () => { + const protectedDir = path.join(agent.root, `protected-${generateId()}`) + mkdirSync(protectedDir, { mode: 0o755 }) + writeFileSync(path.join(protectedDir, 'passwd'), 'original') + const link = path.join(agent.root, `inputs-${generateId()}`) + symlinkSync(protectedDir, link) + + const response = await agent.request( + fileRoute(SANDBOX_AGENT_ROUTES.files, { path: path.join(link, 'passwd') }), + { method: 'PUT', body: 'replaced' } + ) + expect(response.status).toBe(403) + expect(await response.json()).toMatchObject({ error: { code: 'permission_denied' } }) + expect(readFileSync(path.join(protectedDir, 'passwd'), 'utf8')).toBe('original') + expect(statSync(path.join(protectedDir, 'passwd')).uid).toBe(0) + } + ) +}) diff --git a/apps/sandbox-agent/src/files.ts b/apps/sandbox-agent/src/files.ts index 4ea5b1bc63c..be91b1c4ee4 100644 --- a/apps/sandbox-agent/src/files.ts +++ b/apps/sandbox-agent/src/files.ts @@ -8,7 +8,6 @@ import { type SandboxAgentErrorCode, } from '@sim/sandbox-agent-protocol' import { generateShortId } from '@sim/utils/id' -import type { ProcessIdentity } from '@/accounts' const READ_CHUNK_BYTES = 64 * 1024 @@ -128,39 +127,18 @@ function sizedFileStream(handle: FileHandle, size: number): ReadableStream { - const first = await mkdir(directory, { recursive: true }).catch((error: unknown) => - translate(error, directory) - ) - if (first === undefined || owner.uid === undefined || owner.gid === undefined) return - const created: string[] = [] - for (let current = directory; ; current = path.dirname(current)) { - created.push(current) - if (current === first || current === path.dirname(current)) break - } - for (const entry of created.reverse()) { - const handle = await open(entry, constants.O_RDONLY | constants.O_DIRECTORY) - try { - await handle.chown(owner.uid, owner.gid) - } finally { - await handle.close() - } - } -} - /** * Streams `body` into a sibling temp file and renames it over `target`, so a reader never sees * a partial file and a failed upload leaves the previous content. Missing parents are created. - * The file is mode 0644 and, when the agent switches identities, owned by `owner`. + * The file is mode 0644, owned by whoever runs this: the file worker (the sandbox user) or, for + * an explicit `user=root` request, the daemon. */ export async function writeFileAtomically( target: string, - body: ReadableStream | null, - owner: ProcessIdentity + body: ReadableStream | null ): Promise { const directory = path.dirname(target) - await makeParents(directory, owner) + await mkdir(directory, { recursive: true }).catch((error: unknown) => translate(error, directory)) const staged = path.join(directory, `.${path.basename(target)}.sim-upload-${generateShortId(12)}`) const handle = await open(staged, 'wx', 0o644).catch((error: unknown) => translate(error, target)) let committed = false @@ -169,9 +147,6 @@ export async function writeFileAtomically( for await (const chunk of body) await handle.write(chunk) } await handle.chmod(0o644) - if (owner.uid !== undefined && owner.gid !== undefined) { - await handle.chown(owner.uid, owner.gid) - } await handle.close() await rename(staged, target).catch((error: unknown) => translate(error, target)) committed = true diff --git a/apps/sandbox-agent/src/install.ts b/apps/sandbox-agent/src/install.ts index 37f90162f8b..b631d600016 100644 --- a/apps/sandbox-agent/src/install.ts +++ b/apps/sandbox-agent/src/install.ts @@ -1,11 +1,7 @@ import { chmod, copyFile, rename, rm } from 'node:fs/promises' import path from 'node:path' import { generateShortId } from '@sim/utils/id' - -/** True when running as a `bun build --compile` binary rather than from source. */ -export function isCompiledBinary(): boolean { - return Bun.main.startsWith('/$bunfs/') -} +import { isCompiledBinary } from '@/self' /** * Copies this binary to `destination` (staged beside it, then renamed) with mode 0755. The agent diff --git a/apps/sandbox-agent/src/ipc.test.ts b/apps/sandbox-agent/src/ipc.test.ts new file mode 100644 index 00000000000..5644ca98eb0 --- /dev/null +++ b/apps/sandbox-agent/src/ipc.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it } from 'vitest' +import { + encodeFrame, + FRAME_KIND, + FrameDecoder, + INITIAL_CREDIT_BYTES, + InboundStream, + MAX_FRAME_PAYLOAD_BYTES, +} from '@/ipc' + +describe('FrameDecoder', () => { + it('reassembles frames split at every byte boundary', () => { + const wire = new Uint8Array([ + ...encodeFrame(FRAME_KIND.data, 7, new Uint8Array([1, 2, 3])), + ...encodeFrame(FRAME_KIND.end, 7), + ]) + const decoder = new FrameDecoder() + const frames = [...wire].flatMap((byte) => decoder.push(Uint8Array.of(byte))) + expect(frames.map((frame) => [frame.kind, frame.id, [...frame.payload]])).toEqual([ + [FRAME_KIND.data, 7, [1, 2, 3]], + [FRAME_KIND.end, 7, []], + ]) + }) + + it('refuses a header announcing more than the payload limit before buffering it', () => { + const header = new Uint8Array(9) + new DataView(header.buffer).setUint32(0, MAX_FRAME_PAYLOAD_BYTES + 1) + expect(() => new FrameDecoder().push(header)).toThrow('payload limit') + }) +}) + +describe('InboundStream', () => { + it('rejects data beyond the credit the sender was granted', () => { + const inbound = new InboundStream( + () => {}, + () => {} + ) + expect(inbound.push(new Uint8Array(INITIAL_CREDIT_BYTES))).toBe(true) + expect(inbound.push(new Uint8Array(1))).toBe(false) + }) +}) diff --git a/apps/sandbox-agent/src/ipc.ts b/apps/sandbox-agent/src/ipc.ts new file mode 100644 index 00000000000..50b759fa248 --- /dev/null +++ b/apps/sandbox-agent/src/ipc.ts @@ -0,0 +1,275 @@ +/** + * Framing for the stdio link between the root daemon and its unprivileged file worker. + * + * A frame is a 9-byte header (u32 payload length, u8 kind, u32 stream id, all big-endian) and its + * payload. Each operation is one stream id: the daemon opens it with `call`, data flows as `data` + * frames closed by `end`, and the worker settles it with `result` or `error`. Data is + * credit-controlled per stream and direction: a sender starts with {@link INITIAL_CREDIT_BYTES} + * and may send only what the receiver has granted with `credit` frames as it consumes, so a slow + * reader on one stream holds back only that stream and buffered bytes stay bounded. + * + * The daemon treats everything the worker sends as untrusted: the worker runs as the sandbox user, + * which session code can also run as, so frames are size-bounded and payloads validated. + */ + +export const FRAME_KIND = { + call: 0, + result: 1, + error: 2, + data: 3, + end: 4, + credit: 5, + cancel: 6, +} as const + +export type FrameKind = (typeof FRAME_KIND)[keyof typeof FRAME_KIND] + +export interface Frame { + kind: FrameKind + id: number + payload: Uint8Array +} + +const HEADER_BYTES = 9 + +/** Largest payload either side accepts; a listing result is the biggest legitimate frame. */ +export const MAX_FRAME_PAYLOAD_BYTES = 16 * 1024 * 1024 + +/** Bytes a data sender may have outstanding per stream before the receiver grants more. */ +export const INITIAL_CREDIT_BYTES = 256 * 1024 + +/** Largest `data` payload a sender emits. */ +const MAX_DATA_FRAME_BYTES = 64 * 1024 + +const KINDS = new Set(Object.values(FRAME_KIND)) + +export function encodeFrame(kind: FrameKind, id: number, payload?: Uint8Array): Uint8Array { + const body = payload ?? new Uint8Array(0) + const frame = new Uint8Array(HEADER_BYTES + body.byteLength) + const view = new DataView(frame.buffer) + view.setUint32(0, body.byteLength) + view.setUint8(4, kind) + view.setUint32(5, id) + frame.set(body, HEADER_BYTES) + return frame +} + +export function encodeJsonFrame(kind: FrameKind, id: number, value: unknown): Uint8Array { + return encodeFrame(kind, id, new TextEncoder().encode(JSON.stringify(value))) +} + +export function encodeCreditFrame(id: number, bytes: number): Uint8Array { + const payload = new Uint8Array(4) + new DataView(payload.buffer).setUint32(0, bytes) + return encodeFrame(FRAME_KIND.credit, id, payload) +} + +export function decodeCredit(payload: Uint8Array): number { + if (payload.byteLength !== 4) throw new Error('Malformed credit frame') + return new DataView(payload.buffer, payload.byteOffset, 4).getUint32(0) +} + +export function decodeJson(payload: Uint8Array): unknown { + return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(payload)) +} + +/** Reassembles frames from arbitrarily split chunks without re-copying the backlog per chunk. */ +export class FrameDecoder { + private chunks: Uint8Array[] = [] + private buffered = 0 + + push(chunk: Uint8Array): Frame[] { + this.chunks.push(chunk) + this.buffered += chunk.byteLength + const frames: Frame[] = [] + while (this.buffered >= HEADER_BYTES) { + const header = this.peek(HEADER_BYTES) + const view = new DataView(header.buffer, header.byteOffset, HEADER_BYTES) + const length = view.getUint32(0) + const kind = view.getUint8(4) + if (length > MAX_FRAME_PAYLOAD_BYTES) throw new Error('Frame exceeds the payload limit') + if (!KINDS.has(kind)) throw new Error('Unknown frame kind') + if (this.buffered < HEADER_BYTES + length) break + const frame = this.take(HEADER_BYTES + length) + frames.push({ + kind: kind as FrameKind, + id: view.getUint32(5), + payload: frame.subarray(HEADER_BYTES), + }) + } + return frames + } + + private peek(bytes: number): Uint8Array { + if (this.chunks[0].byteLength >= bytes) return this.chunks[0] + this.chunks = [this.concat(this.buffered)] + return this.chunks[0] + } + + private take(bytes: number): Uint8Array { + const first = this.chunks[0] + const taken = + first.byteLength >= bytes ? first.subarray(0, bytes) : this.concat(bytes).subarray(0, bytes) + this.consume(bytes) + return taken + } + + private concat(bytes: number): Uint8Array { + const out = new Uint8Array(Math.min(bytes, this.buffered)) + let offset = 0 + for (const chunk of this.chunks) { + if (offset >= out.byteLength) break + const part = chunk.subarray(0, out.byteLength - offset) + out.set(part, offset) + offset += part.byteLength + } + return out + } + + private consume(bytes: number): void { + let remaining = bytes + this.buffered -= bytes + while (remaining > 0) { + const first = this.chunks[0] + if (first.byteLength <= remaining) { + remaining -= first.byteLength + this.chunks.shift() + } else { + this.chunks[0] = first.subarray(remaining) + remaining = 0 + } + } + } +} + +/** + * Data-sending half of one stream: waits for credit before each chunk, so the sender never has + * more than the receiver granted outstanding. + */ +export class CreditGate { + private available = INITIAL_CREDIT_BYTES + private waiter?: () => void + private closed = false + + grant(bytes: number): void { + this.available += bytes + this.waiter?.() + } + + close(): void { + this.closed = true + this.waiter?.() + } + + get isClosed(): boolean { + return this.closed + } + + /** Resolves with how many bytes may be sent now (at most `wanted`), or 0 once closed. */ + async acquire(wanted: number): Promise { + while (this.available <= 0 && !this.closed) { + await new Promise((resolve) => { + this.waiter = resolve + }) + this.waiter = undefined + } + if (this.closed) return 0 + const granted = Math.min(wanted, this.available) + this.available -= granted + return granted + } +} + +/** + * Sends a byte stream as credit-gated `data` frames followed by `end`. Returns false when the + * gate closed first (the receiver cancelled). + */ +export async function pumpData( + source: ReadableStream, + gate: CreditGate, + send: (frame: Uint8Array) => void, + id: number +): Promise { + const reader = source.getReader() + try { + while (true) { + const { value, done } = await reader.read() + if (done) break + for (let offset = 0; offset < value.byteLength; ) { + const allowed = await gate.acquire( + Math.min(MAX_DATA_FRAME_BYTES, value.byteLength - offset) + ) + if (allowed === 0) { + await reader.cancel() + return false + } + send(encodeFrame(FRAME_KIND.data, id, value.subarray(offset, offset + allowed))) + offset += allowed + } + } + send(encodeFrame(FRAME_KIND.end, id)) + return true + } finally { + reader.releaseLock() + } +} + +/** + * Receiving half of one stream: a pull-based byte stream fed by `data` frames that grants credit + * back as its consumer reads, so at most {@link INITIAL_CREDIT_BYTES} wait in memory. + */ +export class InboundStream { + private readonly queue: Uint8Array[] = [] + private ended = false + private failure?: Error + private wake?: () => void + /** Bytes received but not yet granted back; the sender's credit is the window minus this. */ + private outstanding = 0 + readonly stream: ReadableStream + + constructor(grant: (bytes: number) => void, onCancel: () => void) { + this.stream = new ReadableStream({ + pull: async (controller) => { + while (this.queue.length === 0 && !this.ended && !this.failure) { + await new Promise((resolve) => { + this.wake = resolve + }) + this.wake = undefined + } + const chunk = this.queue.shift() + if (chunk) { + controller.enqueue(chunk) + this.outstanding -= chunk.byteLength + grant(chunk.byteLength) + return + } + if (this.failure) controller.error(this.failure) + else controller.close() + }, + cancel: () => { + this.ended = true + onCancel() + }, + }) + } + + /** Accepts a data frame; false when the sender overran the credit it was granted. */ + push(chunk: Uint8Array): boolean { + this.outstanding += chunk.byteLength + if (this.outstanding > INITIAL_CREDIT_BYTES) return false + if (this.ended) return true + this.queue.push(chunk) + this.wake?.() + return true + } + + end(): void { + this.ended = true + this.wake?.() + } + + fail(error: Error): void { + this.failure = error + this.wake?.() + } +} diff --git a/apps/sandbox-agent/src/main.ts b/apps/sandbox-agent/src/main.ts index 37a23cc6f7d..c52573f4d96 100644 --- a/apps/sandbox-agent/src/main.ts +++ b/apps/sandbox-agent/src/main.ts @@ -2,11 +2,13 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { resolveAccounts } from '@/accounts' import { readAgentConfig } from '@/config' +import { FileWorker, runFileWorker } from '@/file-worker' import { installSelf } from '@/install' import { Lifetime } from '@/lifetime' import { ProcessTable } from '@/processes' +import { AGENT_MODE_ENV, AGENT_MODES } from '@/self' import { SANDBOX_AGENT_VERSION, startAgentServer } from '@/server' -import { runCliVerifier, VERIFY_CLI_MODE, VERIFY_CLI_MODE_ENV } from '@/verify-cli' +import { runCliVerifier } from '@/verify-cli' const logger = createLogger('SandboxAgent') @@ -28,7 +30,7 @@ async function serve(): Promise { tokenSha256: config.tokenSha256, host: config.host, port: config.port, - accounts, + userFiles: new FileWorker(accounts.identityFor('user'), config.baseEnvironment), processes, lifetime, }) @@ -58,12 +60,15 @@ async function install(): Promise { logger.info('Installed sandbox agent', { destination }) } +const helperMode = process.env[AGENT_MODE_ENV] const mode = - process.env[VERIFY_CLI_MODE_ENV] === VERIFY_CLI_MODE + helperMode === AGENT_MODES.verifyCli ? verify - : process.argv[2] === 'install' - ? install - : serve + : helperMode === AGENT_MODES.fileWorker + ? runFileWorker + : process.argv[2] === 'install' + ? install + : serve mode().catch((error: unknown) => { logger.error('Sandbox agent failed', { error: getErrorMessage(error) }) process.exit(1) diff --git a/apps/sandbox-agent/src/processes.test.ts b/apps/sandbox-agent/src/processes.test.ts index 5c84cac0de3..7a800752386 100644 --- a/apps/sandbox-agent/src/processes.test.ts +++ b/apps/sandbox-agent/src/processes.test.ts @@ -4,6 +4,7 @@ import path from 'node:path' import { NdjsonDecoder, processEventSchema, + SANDBOX_AGENT_ROUTES, sandboxAgentProcessEventsPath, sandboxAgentProcessSignalPath, } from '@sim/sandbox-agent-protocol' @@ -214,7 +215,11 @@ describe('CLI verification at launch', () => { const directory = path.join(agent.root, `release-${generateId()}`) await readEvents(await agent.startProcess({ argv: ['mkdir', directory] })) const cli = path.join(directory, 'sim-1.2.3') - writeFileSync(cli, '#!/bin/sh\necho cli\n', { mode: 0o600 }) + const upload = await agent.request( + `${SANDBOX_AGENT_ROUTES.files}?${new URLSearchParams({ path: cli }).toString()}`, + { method: 'PUT', body: '#!/bin/sh\necho cli\n' } + ) + expect(upload.status).toBe(204) const events = await readEvents( await agent.startProcess({ shell: 'echo ran', diff --git a/apps/sandbox-agent/src/self.ts b/apps/sandbox-agent/src/self.ts new file mode 100644 index 00000000000..1caad4e5899 --- /dev/null +++ b/apps/sandbox-agent/src/self.ts @@ -0,0 +1,24 @@ +import { existsSync } from 'node:fs' + +/** Environment variable that starts the agent binary in a helper mode instead of serving. */ +export const AGENT_MODE_ENV = 'SIM_SANDBOX_AGENT_MODE' + +/** Helper modes the agent re-executes itself in, always as the sandbox user. */ +export const AGENT_MODES = { verifyCli: 'verify-cli', fileWorker: 'file-worker' } as const + +/** True when running as a `bun build --compile` binary rather than from source. */ +export function isCompiledBinary(): boolean { + return Bun.main.startsWith('/$bunfs/') +} + +/** + * The command that re-executes this program. On Linux it is `/proc/self/exe`, the image the + * kernel actually loaded, so no path a user could replace is involved; elsewhere (development) + * it falls back to `process.execPath`. A script run by `bun` also needs its entry path. + */ +export function selfCommand(): { file: string; args: string[] } { + return { + file: existsSync('/proc/self/exe') ? '/proc/self/exe' : process.execPath, + args: isCompiledBinary() ? [] : [Bun.main], + } +} diff --git a/apps/sandbox-agent/src/server.ts b/apps/sandbox-agent/src/server.ts index 2256e725dd6..b18d1c01d34 100644 --- a/apps/sandbox-agent/src/server.ts +++ b/apps/sandbox-agent/src/server.ts @@ -1,8 +1,10 @@ import { createLogger } from '@sim/logger' import { encodeNdjson, + type FileStatResponse, fileStatResponseSchema, type HealthzResponse, + type ListFilesResponse, lifetimeRequestSchema, listFilesQuerySchema, NDJSON_CONTENT_TYPE, @@ -17,11 +19,9 @@ import { sandboxAgentProcessKeySchema, signalProcessRequestSchema, startProcessRequestSchema, - writeFileQuerySchema, } from '@sim/sandbox-agent-protocol' import { getErrorMessage } from '@sim/utils/errors' import type { z } from 'zod' -import type { Accounts } from '@/accounts' import { isAuthorized } from '@/auth' import { FileOperationError, @@ -70,11 +70,32 @@ export interface AgentServerDependencies { tokenSha256: Buffer host: string port: number - accounts: Accounts + /** File operations for `user=user` requests: the unprivileged file worker. */ + userFiles: FileAccess processes: ProcessTable lifetime: Lifetime } +/** One identity's file operations; the daemon's own (root) or the file worker's. */ +interface FileAccess { + stat(path: string): Promise + list(path: string, depth: number): Promise + remove(path: string): Promise + read( + path: string, + maxBytes: number | undefined + ): Promise<{ size: number; body: ReadableStream }> + write(path: string, body: ReadableStream | null): Promise +} + +const ROOT_FILES: FileAccess = { + stat: statFile, + list: listDirectory, + remove: removePath, + read: openFileForRead, + write: writeFileAtomically, +} + class RequestError extends Error { constructor( readonly code: SandboxAgentErrorCode, @@ -210,22 +231,24 @@ async function route(request: Request, url: URL, deps: AgentServerDependencies) return json({ delivered: record.signal(signal) }) } + const files = (user: 'root' | 'user') => (user === 'root' ? ROOT_FILES : deps.userFiles) + if (pathname === SANDBOX_AGENT_ROUTES.fileStat) { if (method !== 'GET') throw new RequestError('method_not_allowed', 'Use GET') - const { path } = parse(pathQuerySchema, queryOf(url)) - return json(fileStatResponseSchema.parse(await statFile(path))) + const { path, user } = parse(pathQuerySchema, queryOf(url)) + return json(fileStatResponseSchema.parse(await files(user).stat(path))) } if (pathname === SANDBOX_AGENT_ROUTES.fileList) { if (method !== 'GET') throw new RequestError('method_not_allowed', 'Use GET') - const { path, depth } = parse(listFilesQuerySchema, queryOf(url)) - return json(await listDirectory(path, depth)) + const { path, depth, user } = parse(listFilesQuerySchema, queryOf(url)) + return json(await files(user).list(path, depth)) } if (pathname === SANDBOX_AGENT_ROUTES.files) { if (method === 'GET') { - const { path, maxBytes } = parse(readFileQuerySchema, queryOf(url)) - const { size, body } = await openFileForRead(path, maxBytes) + const { path, maxBytes, user } = parse(readFileQuerySchema, queryOf(url)) + const { size, body } = await files(user).read(path, maxBytes) return new Response(body, { headers: { 'Content-Type': 'application/octet-stream', @@ -234,13 +257,13 @@ async function route(request: Request, url: URL, deps: AgentServerDependencies) }) } if (method === 'PUT') { - const { path, owner } = parse(writeFileQuerySchema, queryOf(url)) - await writeFileAtomically(path, request.body, deps.accounts.identityFor(owner)) + const { path, user } = parse(pathQuerySchema, queryOf(url)) + await files(user).write(path, request.body) return new Response(null, { status: 204 }) } if (method === 'DELETE') { - const { path } = parse(pathQuerySchema, queryOf(url)) - await removePath(path) + const { path, user } = parse(pathQuerySchema, queryOf(url)) + await files(user).remove(path) return new Response(null, { status: 204 }) } throw new RequestError('method_not_allowed', 'Use GET, PUT, or DELETE') diff --git a/apps/sandbox-agent/src/verify-cli.ts b/apps/sandbox-agent/src/verify-cli.ts index e6271a7fa98..07af6f624b1 100644 --- a/apps/sandbox-agent/src/verify-cli.ts +++ b/apps/sandbox-agent/src/verify-cli.ts @@ -8,11 +8,7 @@ import { sandboxAgentCliVerificationSchema, } from '@sim/sandbox-agent-protocol' import type { ProcessIdentity } from '@/accounts' -import { isCompiledBinary } from '@/install' - -/** Environment variable that starts the agent binary in verifier mode instead of serving. */ -export const VERIFY_CLI_MODE_ENV = 'SIM_SANDBOX_AGENT_MODE' -export const VERIFY_CLI_MODE = 'verify-cli' +import { AGENT_MODE_ENV, AGENT_MODES, isCompiledBinary } from '@/self' /** Exit status for a mismatched, missing, or non-regular artifact (the same as the app's check). */ const STALE_EXIT_CODE = 10 @@ -84,7 +80,7 @@ export function verifyCliAsUser( try { child = spawn(process.execPath, [...selfInvocation()], { cwd: '/', - env: { ...baseEnvironment, HOME: identity.home, [VERIFY_CLI_MODE_ENV]: VERIFY_CLI_MODE }, + env: { ...baseEnvironment, HOME: identity.home, [AGENT_MODE_ENV]: AGENT_MODES.verifyCli }, stdio: ['pipe', 'ignore', 'ignore'], ...(identity.uid !== undefined ? { uid: identity.uid, gid: identity.gid } : {}), }) diff --git a/apps/sim/lib/execution/remote-sandbox/agent/handle.ts b/apps/sim/lib/execution/remote-sandbox/agent/handle.ts index e67a84aa6d9..d3058eb0f40 100644 --- a/apps/sim/lib/execution/remote-sandbox/agent/handle.ts +++ b/apps/sim/lib/execution/remote-sandbox/agent/handle.ts @@ -546,7 +546,9 @@ class AgentSandboxHandle implements SandboxHandle { * A {@link SandboxHandle} over `sim-sandbox-agent`'s protocol, independent of the control plane * that created the sandbox. `runCode` runs exactly as the E2B adapter's does (the same files, * preload, and failure parsing, via {@link runCodeAsProcess}); commands and file operations go to - * the agent over HTTP. File streaming is always available, as workbench uploads require. + * the agent over HTTP. File streaming is always available, as workbench uploads require. Every + * file operation uses the agent's default `user` identity, as E2B's files API acts as the sandbox + * user: the agent runs it in its unprivileged file worker, so the kernel's permission checks apply. */ export function createAgentSandboxHandle( connection: AgentSandboxConnection diff --git a/packages/sandbox-agent-protocol/src/schemas.ts b/packages/sandbox-agent-protocol/src/schemas.ts index 9140b1f2e6f..8e15fffbf8e 100644 --- a/packages/sandbox-agent-protocol/src/schemas.ts +++ b/packages/sandbox-agent-protocol/src/schemas.ts @@ -166,10 +166,19 @@ export const fileStatResponseSchema = z.object({ export type FileStatResponse = z.infer +/** + * Identity a file operation runs as, on every file route. `user` (the default, matching E2B's + * files API) runs it in the agent's file worker as the sandbox user, so the kernel's permission + * checks apply to every path component; `root` runs it in the daemon. New files and parents are + * owned by that identity. + */ +const fileUserSchema = z.enum(['root', 'user']).default('user') + /** `depth` counts path segments below the listed directory: `a/b/leaf.txt` is depth 3. */ export const listFilesQuerySchema = z.object({ path: sandboxAgentPathSchema, depth: z.coerce.number().int().min(1).max(SANDBOX_AGENT_MAX_LIST_DEPTH).default(1), + user: fileUserSchema, }) /** @@ -192,15 +201,11 @@ export type ListFilesResponse = z.infer export const readFileQuerySchema = z.object({ path: sandboxAgentPathSchema, maxBytes: z.coerce.number().int().nonnegative().optional(), + user: fileUserSchema, }) -/** `PUT /v1/files`. New files and parents belong to the sandbox user unless `owner=root`. */ -export const writeFileQuerySchema = z.object({ - path: sandboxAgentPathSchema, - owner: z.enum(['root', 'user']).default('user'), -}) - -export const pathQuerySchema = z.object({ path: sandboxAgentPathSchema }) +/** `PUT /v1/files`, `DELETE /v1/files`, and `GET /v1/files/stat`. */ +export const pathQuerySchema = z.object({ path: sandboxAgentPathSchema, user: fileUserSchema }) export const healthzResponseSchema = z.object({ ok: z.literal(true), From 9febebd4c0d88c31c42bbf962eb02ead927ded40 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:04:30 -0600 Subject: [PATCH 12/78] fix(sandbox): coalesce process output and stream events on demand A program writing one byte at a time produced one ~4-byte event per write: millions of events held in agent memory and parsed by the app. Output now coalesces per stream, flushing at 64 KiB or after 50 ms, and every output event is charged a fixed 64-byte overhead against maxOutputBytes, so the budget bounds the event count too. Event streams are pull-based: each reader keeps a cursor into the shared event log and the next batch is serialized only when the socket asks for it, so a slow reader or a reattach never builds up a copy of the retained output. --- apps/sandbox-agent/src/event-stream.test.ts | 38 ++++++++ apps/sandbox-agent/src/event-stream.ts | 53 +++++++++++ apps/sandbox-agent/src/processes.test.ts | 28 ++++++ apps/sandbox-agent/src/processes.ts | 93 ++++++++++++++----- apps/sandbox-agent/src/server.ts | 40 +------- .../sandbox-agent-protocol/src/constants.ts | 6 ++ 6 files changed, 197 insertions(+), 61 deletions(-) create mode 100644 apps/sandbox-agent/src/event-stream.test.ts create mode 100644 apps/sandbox-agent/src/event-stream.ts diff --git a/apps/sandbox-agent/src/event-stream.test.ts b/apps/sandbox-agent/src/event-stream.test.ts new file mode 100644 index 00000000000..5c64e502496 --- /dev/null +++ b/apps/sandbox-agent/src/event-stream.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' +import { processEventStream } from '@/event-stream' +import { ProcessRecord, type RecordedEvent } from '@/processes' + +describe('processEventStream', () => { + it('serializes only what the reader pulls, not the whole retained log', async () => { + const record = new ProcessRecord('key', 'fingerprint') + record.emit({ type: 'started', pid: 1 }) + for (let index = 0; index < 2_000; index++) { + record.emit({ type: 'stdout', data: 'x'.repeat(1024) }) + } + let highestRead = -1 + const tracked = new Proxy(record.events, { + get(target, property, receiver) { + if (typeof property === 'string' && /^\d+$/.test(property)) { + highestRead = Math.max(highestRead, Number(property)) + } + return Reflect.get(target, property, receiver) + }, + }) satisfies RecordedEvent[] + Object.defineProperty(record, 'events', { value: tracked }) + + const reader = processEventStream(record, 0).getReader() + const { value } = await reader.read() + await reader.cancel() + + expect(value?.length).toBeLessThanOrEqual(80 * 1024) + expect(highestRead).toBeLessThan(100) + }) + + it('ends after the terminal event when replaying a finished record', async () => { + const record = new ProcessRecord('key', 'fingerprint') + record.emit({ type: 'started', pid: 1 }) + record.emit({ type: 'exit', exitCode: 0 }) + const text = await new Response(processEventStream(record, 1)).text() + expect(text).toBe('{"type":"exit","exitCode":0,"seq":1}\n') + }) +}) diff --git a/apps/sandbox-agent/src/event-stream.ts b/apps/sandbox-agent/src/event-stream.ts new file mode 100644 index 00000000000..e78e3d203c0 --- /dev/null +++ b/apps/sandbox-agent/src/event-stream.ts @@ -0,0 +1,53 @@ +import { encodeNdjson, SANDBOX_AGENT_HEARTBEAT_MS } from '@sim/sandbox-agent-protocol' +import type { ProcessRecord } from '@/processes' + +/** Most NDJSON text one pull serializes; the stream holds at most about this much per reader. */ +const MAX_BATCH_CHARS = 64 * 1024 + +const encoder = new TextEncoder() +const HEARTBEAT = encoder.encode(encodeNdjson({ type: 'heartbeat' })) + +/** + * A record's events from `from` onward as NDJSON, ending after `exit` or `rejected`. Pull-based: + * the next batch is serialized only when the consumer (the HTTP socket) asks for it, so a slow + * or stalled reader costs a cursor into the shared event log, never a growing copy of it. A + * heartbeat goes out whenever the process is quiet for {@link SANDBOX_AGENT_HEARTBEAT_MS}. + */ +export function processEventStream( + record: ProcessRecord, + from: number +): ReadableStream { + let cursor = from + let cancelled = false + return new ReadableStream( + { + async pull(controller) { + while (cursor >= record.events.length && !record.finished) { + const woke = await record.waitForEvents(cursor, SANDBOX_AGENT_HEARTBEAT_MS) + if (cancelled) return + if (!woke) { + controller.enqueue(HEARTBEAT) + return + } + } + let batch = '' + while (cursor < record.events.length && batch.length < MAX_BATCH_CHARS) { + const event = record.events[cursor] + cursor += 1 + batch += encodeNdjson(event) + if (event.type === 'exit' || event.type === 'rejected') { + controller.enqueue(encoder.encode(batch)) + controller.close() + return + } + } + if (batch) controller.enqueue(encoder.encode(batch)) + else controller.close() + }, + cancel() { + cancelled = true + }, + }, + { highWaterMark: 0 } + ) +} diff --git a/apps/sandbox-agent/src/processes.test.ts b/apps/sandbox-agent/src/processes.test.ts index 7a800752386..29faaaeeb36 100644 --- a/apps/sandbox-agent/src/processes.test.ts +++ b/apps/sandbox-agent/src/processes.test.ts @@ -94,6 +94,34 @@ describe('process budgets', () => { expect(events.at(-1)).toMatchObject({ type: 'exit', outputLimitExceeded: true }) }) + it('coalesces a byte-at-a-time writer into a handful of events', async () => { + const events = await readEvents( + await agent.startProcess({ + argv: [ + 'python3', + '-c', + 'import sys\nfor _ in range(20000):\n sys.stdout.write("x")\n sys.stdout.flush()', + ], + }) + ) + expect(stdoutOf(events)).toBe('x'.repeat(20_000)) + expect(events.filter((event) => event.type === 'stdout').length).toBeLessThan(200) + }) + + it('charges each output event against the budget, not only its bytes', async () => { + const events = await readEvents( + await agent.startProcess({ + argv: [ + 'python3', + '-c', + 'import sys, time\nfor _ in range(10):\n sys.stdout.write("x" * 20)\n sys.stdout.flush()\n time.sleep(0.1)', + ], + maxOutputBytes: 600, + }) + ) + expect(events.at(-1)).toMatchObject({ type: 'exit', outputLimitExceeded: true }) + }) + it('kills the whole process group on timeout, grandchildren included', async () => { const pidFile = path.join(agent.root, `grandchild-${generateId()}`) const events = await readEvents( diff --git a/apps/sandbox-agent/src/processes.ts b/apps/sandbox-agent/src/processes.ts index d84c6706b91..1be75f735c6 100644 --- a/apps/sandbox-agent/src/processes.ts +++ b/apps/sandbox-agent/src/processes.ts @@ -5,6 +5,7 @@ import { createLogger } from '@sim/logger' import { type ProcessEvent, SANDBOX_AGENT_MAX_EVENT_DATA_BYTES, + SANDBOX_AGENT_OUTPUT_EVENT_OVERHEAD_BYTES, type SandboxAgentRejectionReason, type StartProcessRequest, } from '@sim/sandbox-agent-protocol' @@ -27,6 +28,9 @@ const TIMEOUT_EXIT_CODE = 124 */ const PIPE_DRAIN_GRACE_MS = 2_000 +/** Longest an output byte waits before it is sent as part of a coalesced event. */ +const OUTPUT_FLUSH_MS = 50 + /** A finished process stays attachable this long, so a client that lost its stream can read the exit. */ const FINISHED_RETENTION_MS = 10 * 60 * 1000 const MAX_RUNNING_PROCESSES = 64 @@ -42,7 +46,7 @@ export class ProcessRecord { state: ProcessState = 'launching' finishedAtMs?: number outputBytes = 0 - private readonly listeners = new Set<(event: RecordedEvent) => void>() + private readonly waiters = new Set<() => void>() private child?: ChildProcess private cancelled = false @@ -55,7 +59,7 @@ export class ProcessRecord { return this.state === 'finished' } - /** Appends the next event, numbering it, and hands it to every attached stream. */ + /** Appends the next event, numbering it, and wakes every waiting reader. */ emit(event: DistributiveOmit): void { if (this.finished) return const recorded = { ...event, seq: this.events.length } as RecordedEvent @@ -64,21 +68,28 @@ export class ProcessRecord { this.state = 'finished' this.finishedAtMs = Date.now() } - for (const listener of this.listeners) listener(recorded) - if (this.finished) this.listeners.clear() + for (const waiter of this.waiters) waiter() + this.waiters.clear() } /** - * Replays every event from `from` onward, then follows live events until the record finishes. - * Returns the detach function. + * Resolves true once the record holds more than `count` events or has finished, or false after + * `timeoutMs` with nothing new. Readers pull from {@link events} themselves, so a slow reader + * holds a cursor rather than a copy of the output. */ - subscribe(from: number, listener: (event: RecordedEvent) => void): () => void { - for (const event of this.events.slice(from)) listener(event) - if (this.finished) return () => {} - this.listeners.add(listener) - return () => { - this.listeners.delete(listener) - } + waitForEvents(count: number, timeoutMs: number): Promise { + if (this.events.length > count || this.finished) return Promise.resolve(true) + return new Promise((resolve) => { + const waiter = () => { + clearTimeout(timer) + resolve(true) + } + const timer = setTimeout(() => { + this.waiters.delete(waiter) + resolve(false) + }, timeoutMs) + this.waiters.add(waiter) + }) } attach(child: ChildProcess): void { @@ -248,38 +259,70 @@ function superviseProcess( killGroup(pid, 'SIGKILL') }, request.timeoutMs) + /** Charges `bytes` against the budget, stopping the process group once it is exceeded. */ + const charge = (bytes: number): boolean => { + if (outputLimitExceeded) return false + if (record.outputBytes + bytes > request.maxOutputBytes) { + outputLimitExceeded = true + killGroup(pid, 'SIGKILL') + return false + } + record.outputBytes += bytes + return true + } + + /** + * Coalesces one stream's output: chunks accumulate until {@link SANDBOX_AGENT_MAX_EVENT_DATA_BYTES} + * or {@link OUTPUT_FLUSH_MS} pass, so a program writing a byte at a time produces a few events a + * second rather than one per write. Each event is also charged a fixed overhead, which bounds + * the event count (and its JSON framing) by the same budget as the bytes. + */ const forward = (stream: NodeJS.ReadableStream | null, type: 'stdout' | 'stderr') => { const decoder = new TextDecoder('utf-8') - stream?.on('data', (chunk: Buffer) => { - if (outputLimitExceeded) return - if (record.outputBytes + chunk.byteLength > request.maxOutputBytes) { - outputLimitExceeded = true - killGroup(pid, 'SIGKILL') - return - } - record.outputBytes += chunk.byteLength + let pending: Buffer[] = [] + let pendingBytes = 0 + let timer: ReturnType | undefined + const flush = () => { + clearTimeout(timer) + timer = undefined + if (pendingBytes === 0) return + const bytes = Buffer.concat(pending, pendingBytes) + pending = [] + pendingBytes = 0 for ( let offset = 0; - offset < chunk.byteLength; + offset < bytes.byteLength; offset += SANDBOX_AGENT_MAX_EVENT_DATA_BYTES ) { + if (!charge(SANDBOX_AGENT_OUTPUT_EVENT_OVERHEAD_BYTES)) return const data = decoder.decode( - chunk.subarray(offset, offset + SANDBOX_AGENT_MAX_EVENT_DATA_BYTES), + bytes.subarray(offset, offset + SANDBOX_AGENT_MAX_EVENT_DATA_BYTES), { stream: true } ) if (data) record.emit({ type, data }) } + } + stream?.on('data', (chunk: Buffer) => { + if (!charge(chunk.byteLength)) return + pending.push(chunk) + pendingBytes += chunk.byteLength + if (pendingBytes >= SANDBOX_AGENT_MAX_EVENT_DATA_BYTES) flush() + else timer ??= setTimeout(flush, OUTPUT_FLUSH_MS) }) stream?.on('end', () => { + flush() const tail = decoder.decode() if (tail && !outputLimitExceeded) record.emit({ type, data: tail }) }) + return flush } - forward(child.stdout, 'stdout') - forward(child.stderr, 'stderr') + const flushStdout = forward(child.stdout, 'stdout') + const flushStderr = forward(child.stderr, 'stderr') const finish = () => { if (record.finished || !exit) return + flushStdout() + flushStderr() clearTimeout(timeoutTimer) clearTimeout(drainTimer) const signalNumber = exit.signal ? constants.signals[exit.signal] : undefined diff --git a/apps/sandbox-agent/src/server.ts b/apps/sandbox-agent/src/server.ts index b18d1c01d34..ee55ed46ee4 100644 --- a/apps/sandbox-agent/src/server.ts +++ b/apps/sandbox-agent/src/server.ts @@ -1,6 +1,5 @@ import { createLogger } from '@sim/logger' import { - encodeNdjson, type FileStatResponse, fileStatResponseSchema, type HealthzResponse, @@ -11,7 +10,6 @@ import { pathQuerySchema, readFileQuerySchema, SANDBOX_AGENT_FILE_SIZE_HEADER, - SANDBOX_AGENT_HEARTBEAT_MS, SANDBOX_AGENT_PROTOCOL_VERSION, SANDBOX_AGENT_ROUTES, type SandboxAgentErrorBody, @@ -23,6 +21,7 @@ import { import { getErrorMessage } from '@sim/utils/errors' import type { z } from 'zod' import { isAuthorized } from '@/auth' +import { processEventStream } from '@/event-stream' import { FileOperationError, listDirectory, @@ -32,7 +31,7 @@ import { writeFileAtomically, } from '@/files' import type { Lifetime } from '@/lifetime' -import type { ProcessRecord, ProcessTable, RecordedEvent } from '@/processes' +import type { ProcessRecord, ProcessTable } from '@/processes' const logger = createLogger('SandboxAgentServer') @@ -152,41 +151,10 @@ async function readJson(request: Request): Promise { } } -/** - * Streams a record's events from `from` as NDJSON until the record finishes, with heartbeats - * while it is quiet. Disconnecting detaches the stream and leaves the process running. - */ function eventStream(record: ProcessRecord, from: number): Response { - let detach = () => {} - let heartbeat: ReturnType | undefined - let closed = false - const stop = () => { - closed = true - detach() - clearInterval(heartbeat) - } - const body = new ReadableStream({ - start(controller) { - const end = () => { - if (closed) return - stop() - controller.close() - } - const send = (event: RecordedEvent) => { - if (closed) return - controller.enqueue(encodeNdjson(event)) - if (event.type === 'exit' || event.type === 'rejected') end() - } - heartbeat = setInterval(() => { - if (!closed) controller.enqueue(encodeNdjson({ type: 'heartbeat' })) - }, SANDBOX_AGENT_HEARTBEAT_MS) - detach = record.subscribe(from, send) - if (closed) detach() - if (record.finished) end() - }, - cancel: stop, + return new Response(processEventStream(record, from), { + headers: { 'Content-Type': NDJSON_CONTENT_TYPE }, }) - return new Response(body, { headers: { 'Content-Type': NDJSON_CONTENT_TYPE } }) } function parseSeq(value: string | null): number { diff --git a/packages/sandbox-agent-protocol/src/constants.ts b/packages/sandbox-agent-protocol/src/constants.ts index ca40c4a6833..e97078d3433 100644 --- a/packages/sandbox-agent-protocol/src/constants.ts +++ b/packages/sandbox-agent-protocol/src/constants.ts @@ -42,6 +42,12 @@ export const SANDBOX_AGENT_MAX_OUTPUT_BYTES = 64 * 1024 * 1024 */ export const SANDBOX_AGENT_MAX_EVENT_DATA_BYTES = 64 * 1024 +/** + * Bytes every output event costs against `maxOutputBytes` on top of its data, so a program + * writing tiny chunks exhausts its budget in events rather than flooding the stream with them. + */ +export const SANDBOX_AGENT_OUTPUT_EVENT_OVERHEAD_BYTES = 64 + /** Upper bound for one NDJSON line, including JSON escaping of a maximal output event. */ export const SANDBOX_AGENT_MAX_NDJSON_LINE_BYTES = 1024 * 1024 From 5fd65a6dff5eb5e2474c1d5e01e1df759ffe6fa6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:09:39 -0600 Subject: [PATCH 13/78] fix(sandbox): bound agent request bodies, in-flight requests, and idle sockets JSON bodies were read whole before their size was checked, so a chunked body could grow without bound; the 1 MiB cap is now enforced while reading. Requests beyond 256 in flight are refused with 503 overloaded before authentication, and idle connections (including ones that never finish their headers, since Bun has no separate header timeout) close after 30 s; event streams heartbeat well inside that. The Bearer scheme now matches case-insensitively, per RFC 6750. --- apps/sandbox-agent/src/auth.ts | 3 +- apps/sandbox-agent/src/server.test.ts | 45 +++++++++++++++++++ apps/sandbox-agent/src/server.ts | 38 +++++++++++++--- .../sandbox-agent-protocol/src/schemas.ts | 1 + 4 files changed, 79 insertions(+), 8 deletions(-) diff --git a/apps/sandbox-agent/src/auth.ts b/apps/sandbox-agent/src/auth.ts index be6a07cd36e..7cdde7a2e46 100644 --- a/apps/sandbox-agent/src/auth.ts +++ b/apps/sandbox-agent/src/auth.ts @@ -7,7 +7,8 @@ import { createHash, timingSafeEqual } from 'node:crypto' */ export function isAuthorized(header: string | null, expectedSha256: Buffer): boolean { if (!header) return false - const match = /^Bearer ([\x21-\x7e]+)$/.exec(header) + // RFC 6750 auth schemes are case-insensitive. + const match = /^Bearer ([\x21-\x7e]+)$/i.exec(header) if (!match) return false const presented = createHash('sha256').update(match[1], 'utf8').digest() return timingSafeEqual(presented, expectedSha256) diff --git a/apps/sandbox-agent/src/server.test.ts b/apps/sandbox-agent/src/server.test.ts index ef51d785836..02dccffcd02 100644 --- a/apps/sandbox-agent/src/server.test.ts +++ b/apps/sandbox-agent/src/server.test.ts @@ -4,6 +4,7 @@ import { healthzResponseSchema, SANDBOX_AGENT_EXPIRES_AT_ENV, SANDBOX_AGENT_ROUTES, + sandboxAgentProcessEventsPath, } from '@sim/sandbox-agent-protocol' import { generateId } from '@sim/utils/id' import { describe, expect, it, vi } from 'vitest' @@ -31,6 +32,50 @@ describe('authentication', () => { } const authorized = await fetch(route, { headers: { Authorization: `Bearer ${agent.token}` } }) expect(authorized.status).toBe(200) + const lowercase = await fetch(route, { headers: { Authorization: `bearer ${agent.token}` } }) + expect(lowercase.status).toBe(200) + } finally { + await agent.stop() + } + }) +}) + +describe('request limits', () => { + it('refuses an oversized chunked JSON body while it is still arriving', async () => { + const agent = await startTestAgent() + try { + const chunk = new TextEncoder().encode(' '.repeat(64 * 1024)) + const endless = new ReadableStream({ + pull(controller) { + controller.enqueue(chunk) + }, + }) + const init: RequestInit & { duplex: 'half' } = { + method: 'POST', + body: endless, + duplex: 'half', + signal: AbortSignal.timeout(10_000), + } + const response = await agent.request(SANDBOX_AGENT_ROUTES.processes, init) + expect(response.status).toBe(413) + expect(await response.json()).toMatchObject({ error: { code: 'too_large' } }) + } finally { + await agent.stop() + } + }) + + it('refuses requests beyond the in-flight cap before authenticating them', async () => { + const agent = await startTestAgent() + try { + const processKey = generateId() + const running = await agent.startProcess({ processKey, shell: 'sleep 30', timeoutMs: 30_000 }) + const streams = await Promise.all( + Array.from({ length: 260 }, () => agent.request(sandboxAgentProcessEventsPath(processKey))) + ) + const refused = await fetch(`${agent.baseUrl}${SANDBOX_AGENT_ROUTES.fileStat}?path=/tmp`) + expect(refused.status).toBe(503) + expect(await refused.json()).toMatchObject({ error: { code: 'overloaded' } }) + for (const stream of [running, ...streams]) await stream.body?.cancel() } finally { await agent.stop() } diff --git a/apps/sandbox-agent/src/server.ts b/apps/sandbox-agent/src/server.ts index ee55ed46ee4..e05a6064d99 100644 --- a/apps/sandbox-agent/src/server.ts +++ b/apps/sandbox-agent/src/server.ts @@ -47,8 +47,18 @@ const MAX_JSON_BODY_BYTES = 1024 * 1024 */ const MAX_UPLOAD_BYTES = 16 * 1024 * 1024 * 1024 -/** Seconds a connection may sit with no traffic; event streams send heartbeats well inside it. */ -const IDLE_TIMEOUT_SECONDS = 120 +/** + * Seconds a connection may sit with no traffic, including one that never finishes its headers + * (Bun exposes no separate header timeout). Event streams heartbeat well inside it. + */ +const IDLE_TIMEOUT_SECONDS = 30 + +/** + * Requests in flight before new ones are refused with 503, checked before authentication so an + * unauthenticated flood from inside the sandbox cannot pile up handlers. Bun has no + * connection cap; idle sockets are bounded by {@link IDLE_TIMEOUT_SECONDS} instead. + */ +const MAX_PENDING_REQUESTS = 256 const STATUS_BY_CODE: Record = { unauthorized: 401, @@ -62,6 +72,7 @@ const STATUS_BY_CODE: Record = { process_key_conflict: 409, too_many_processes: 429, method_not_allowed: 405, + overloaded: 503, internal: 500, } @@ -140,12 +151,22 @@ function queryOf(url: URL): Record { async function readJson(request: Request): Promise { const declared = Number(request.headers.get('content-length') ?? '0') if (declared > MAX_JSON_BODY_BYTES) throw new RequestError('too_large', 'JSON body is too large') - const text = await request.text() - if (Buffer.byteLength(text) > MAX_JSON_BODY_BYTES) { - throw new RequestError('too_large', 'JSON body is too large') + // Counted while reading: a chunked body declares no length, and must not be buffered whole. + const chunks: Uint8Array[] = [] + let received = 0 + const reader = request.body?.getReader() + while (reader) { + const { value, done } = await reader.read() + if (done) break + received += value.byteLength + if (received > MAX_JSON_BODY_BYTES) { + await reader.cancel() + throw new RequestError('too_large', 'JSON body is too large') + } + chunks.push(value) } try { - return JSON.parse(text) + return JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { throw new RequestError('invalid_request', 'Body is not valid JSON') } @@ -253,7 +274,10 @@ export function startAgentServer(deps: AgentServerDependencies) { port: deps.port, idleTimeout: IDLE_TIMEOUT_SECONDS, maxRequestBodySize: MAX_UPLOAD_BYTES, - async fetch(request) { + async fetch(request, server) { + if (server.pendingRequests > MAX_PENDING_REQUESTS) { + return errorResponse('overloaded', 'Too many requests are in flight') + } const url = new URL(request.url) if (url.pathname === SANDBOX_AGENT_ROUTES.healthz && request.method === 'GET') { const health: HealthzResponse = { diff --git a/packages/sandbox-agent-protocol/src/schemas.ts b/packages/sandbox-agent-protocol/src/schemas.ts index 8e15fffbf8e..5b79e7eb9a8 100644 --- a/packages/sandbox-agent-protocol/src/schemas.ts +++ b/packages/sandbox-agent-protocol/src/schemas.ts @@ -20,6 +20,7 @@ const SANDBOX_AGENT_ERROR_CODES = [ 'process_key_conflict', 'too_many_processes', 'method_not_allowed', + 'overloaded', 'internal', ] as const From f0ad9f7d6fdce9eb8d6d3f0d980c1ce6d7935ad0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:11:06 -0600 Subject: [PATCH 14/78] fix(sandbox): bound directory walks by names visited and shorten staging names A listing counted only the entries it returned, so a directory of dangling links or sockets could be walked without bound while returning nothing. The walk now streams names with opendir and counts every one visited against the entry cap. Upload staging files were named after the target plus a suffix, which exceeded NAME_MAX for long basenames; they now use a short random name in the same directory. --- apps/sandbox-agent/src/files.test.ts | 22 ++++++++++++++++++++++ apps/sandbox-agent/src/files.ts | 21 +++++++++++++-------- 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/apps/sandbox-agent/src/files.test.ts b/apps/sandbox-agent/src/files.test.ts index 2ca8ca4fc68..c9c6f3a7f84 100644 --- a/apps/sandbox-agent/src/files.test.ts +++ b/apps/sandbox-agent/src/files.test.ts @@ -3,6 +3,7 @@ import path from 'node:path' import { directoryEntrySchema, SANDBOX_AGENT_FILE_SIZE_HEADER, + SANDBOX_AGENT_MAX_LIST_ENTRIES, SANDBOX_AGENT_ROUTES, sandboxAgentProcessSignalPath, } from '@sim/sandbox-agent-protocol' @@ -106,6 +107,16 @@ describe('file writes', () => { expect(readdirSync(directory)).toEqual(['file.txt']) }) + it('writes a file whose name is as long as the filesystem allows', async () => { + const target = path.join(agent.root, 'n'.repeat(250)) + const response = await agent.request(fileRoute(SANDBOX_AGENT_ROUTES.files, { path: target }), { + method: 'PUT', + body: 'long name', + }) + expect(response.status).toBe(204) + expect(readFileSync(target, 'utf8')).toBe('long name') + }) + it('deletes a file and reports a missing one as not found', async () => { const target = path.join(agent.root, `doomed-${generateId()}`) writeFileSync(target, 'x') @@ -117,6 +128,17 @@ describe('file writes', () => { }) describe('directory listing', () => { + it('counts skipped names against the entry cap', async () => { + const listed = path.join(agent.root, `dangling-${generateId()}`) + mkdirSync(listed) + for (let index = 0; index <= SANDBOX_AGENT_MAX_LIST_ENTRIES; index++) { + symlinkSync(path.join(listed, 'missing'), path.join(listed, `link-${index}`)) + } + const response = await agent.request(fileRoute(SANDBOX_AGENT_ROUTES.fileList, { path: listed })) + expect(response.status).toBe(413) + expect(await response.json()).toMatchObject({ error: { code: 'too_large' } }) + }) + it('follows symlinks, includes directories, and skips dangling links', async () => { const listed = path.join(agent.root, `listed-${generateId()}`) const outside = path.join(agent.root, `outside-${generateId()}`) diff --git a/apps/sandbox-agent/src/files.ts b/apps/sandbox-agent/src/files.ts index be91b1c4ee4..cdb5c4ccd40 100644 --- a/apps/sandbox-agent/src/files.ts +++ b/apps/sandbox-agent/src/files.ts @@ -1,5 +1,5 @@ import { constants } from 'node:fs' -import { type FileHandle, mkdir, open, readdir, rename, rm, stat, unlink } from 'node:fs/promises' +import { type FileHandle, mkdir, open, opendir, rename, rm, stat, unlink } from 'node:fs/promises' import path from 'node:path' import { type FileStatResponse, @@ -139,7 +139,8 @@ export async function writeFileAtomically( ): Promise { const directory = path.dirname(target) await mkdir(directory, { recursive: true }).catch((error: unknown) => translate(error, directory)) - const staged = path.join(directory, `.${path.basename(target)}.sim-upload-${generateShortId(12)}`) + // A fixed short name: a long target basename plus a suffix could exceed NAME_MAX. + const staged = path.join(directory, `.sim-upload-${generateShortId(16)}`) const handle = await open(staged, 'wx', 0o644).catch((error: unknown) => translate(error, target)) let committed = false try { @@ -174,18 +175,22 @@ export async function listDirectory(root: string, depth: number): Promise => { - const names = await readdir(directory).catch((error: unknown) => translate(error, directory)) - for (const name of names) { - const entryPath = path.join(directory, name) - const entryInfo = await stat(entryPath).catch(() => null) - if (!entryInfo || (!entryInfo.isFile() && !entryInfo.isDirectory())) continue - if (entries.length >= SANDBOX_AGENT_MAX_LIST_ENTRIES) { + const handle = await opendir(directory).catch((error: unknown) => translate(error, directory)) + for await (const dirent of handle) { + visited += 1 + if (visited > SANDBOX_AGENT_MAX_LIST_ENTRIES) { throw new FileOperationError( 'too_large', `Listing exceeds ${SANDBOX_AGENT_MAX_LIST_ENTRIES} entries` ) } + const entryPath = path.join(directory, dirent.name) + const entryInfo = await stat(entryPath).catch(() => null) + if (!entryInfo || (!entryInfo.isFile() && !entryInfo.isDirectory())) continue const isDirectory = entryInfo.isDirectory() entries.push({ path: entryPath, From 9525aac55e682a26c7a325a9dff6e56830e8dc13 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:16:32 -0600 Subject: [PATCH 15/78] test(sandbox): hold the agent's in-flight cap open with raw sockets The in-flight cap test opened 260 event streams through fetch, whose client pool can hold requests back before they reach the agent, so it timed out on Linux. Raw sockets sending an authorized request whose body never arrives hold each handler in flight regardless of the client. --- apps/sandbox-agent/src/server.test.ts | 30 +++++++++++++++++++-------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/apps/sandbox-agent/src/server.test.ts b/apps/sandbox-agent/src/server.test.ts index 02dccffcd02..0bd03acd89b 100644 --- a/apps/sandbox-agent/src/server.test.ts +++ b/apps/sandbox-agent/src/server.test.ts @@ -1,10 +1,10 @@ import { readFileSync } from 'node:fs' +import { connect, type Socket } from 'node:net' import path from 'node:path' import { healthzResponseSchema, SANDBOX_AGENT_EXPIRES_AT_ENV, SANDBOX_AGENT_ROUTES, - sandboxAgentProcessEventsPath, } from '@sim/sandbox-agent-protocol' import { generateId } from '@sim/utils/id' import { describe, expect, it, vi } from 'vitest' @@ -66,17 +66,29 @@ describe('request limits', () => { it('refuses requests beyond the in-flight cap before authenticating them', async () => { const agent = await startTestAgent() + const sockets: Socket[] = [] try { - const processKey = generateId() - const running = await agent.startProcess({ processKey, shell: 'sleep 30', timeoutMs: 30_000 }) - const streams = await Promise.all( - Array.from({ length: 260 }, () => agent.request(sandboxAgentProcessEventsPath(processKey))) + // Raw sockets, so no client connection pool limits how many requests reach the agent: each + // sends an authorized request whose body never arrives, holding its handler in flight. + const port = Number(new URL(agent.baseUrl).port) + for (let index = 0; index < 260; index++) { + const socket = connect(port, '127.0.0.1') + socket.on('error', () => {}) + socket.write( + `POST ${SANDBOX_AGENT_ROUTES.lifetime} HTTP/1.1\r\nHost: agent\r\nAuthorization: Bearer ${agent.token}\r\nContent-Length: 64\r\n\r\n` + ) + sockets.push(socket) + } + await vi.waitFor( + async () => { + const refused = await fetch(`${agent.baseUrl}${SANDBOX_AGENT_ROUTES.fileStat}?path=/tmp`) + expect(refused.status).toBe(503) + expect(await refused.json()).toMatchObject({ error: { code: 'overloaded' } }) + }, + { timeout: 10_000, interval: 100 } ) - const refused = await fetch(`${agent.baseUrl}${SANDBOX_AGENT_ROUTES.fileStat}?path=/tmp`) - expect(refused.status).toBe(503) - expect(await refused.json()).toMatchObject({ error: { code: 'overloaded' } }) - for (const stream of [running, ...streams]) await stream.body?.cancel() } finally { + for (const socket of sockets) socket.destroy() await agent.stop() } }) From fefbbecb8a5dded9d07d5094d88ee511ede9e172 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:16:33 -0600 Subject: [PATCH 16/78] fix(sandbox): refuse a root sandbox user and only hand over homes the agent creates An image whose user account had uid or gid 0 would have run user code as root; the agent now refuses to start. The agent chowned the user's home whatever it was, so an image could point the account at a system directory and have it handed to uid 1000; it now creates and hands over only a missing home directly under /home, and leaves existing homes alone (tolerating a concurrent creator). --- apps/sandbox-agent/src/accounts.test.ts | 45 +++++++++++++++++++++-- apps/sandbox-agent/src/accounts.ts | 47 ++++++++++++++++++++----- 2 files changed, 81 insertions(+), 11 deletions(-) diff --git a/apps/sandbox-agent/src/accounts.test.ts b/apps/sandbox-agent/src/accounts.test.ts index db75d8d10b9..3acfd36d653 100644 --- a/apps/sandbox-agent/src/accounts.test.ts +++ b/apps/sandbox-agent/src/accounts.test.ts @@ -1,8 +1,16 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs' import { tmpdir } from 'node:os' import path from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { ensureSandboxUserEntry } from '@/accounts' +import { ensureSandboxUserEntry, prepareSandboxHome, RootSandboxUserError } from '@/accounts' let root: string @@ -38,4 +46,37 @@ describe('ensureSandboxUserEntry', () => { expect(ensureSandboxUserEntry(root)).toEqual({ uid: 1001, gid: 1002, home: '/srv/user' }) expect(readFileSync(path.join(root, 'etc/passwd'), 'utf8')).toBe(passwd) }) + + it.each([ + ['uid', 'user:x:0:1000::/home/user:/bin/sh\n'], + ['gid', 'user:x:1000:0::/home/user:/bin/sh\n'], + ])('refuses an image sandbox user with root %s', (_, passwd) => { + writeFileSync(path.join(root, 'etc/passwd'), passwd) + expect(() => ensureSandboxUserEntry(root)).toThrow(RootSandboxUserError) + }) +}) + +describe('prepareSandboxHome', () => { + const uid = process.getuid?.() ?? 0 + const gid = process.getgid?.() ?? 0 + + it('creates and hands over a missing home directly under the home root', () => { + const home = path.join(root, 'user') + prepareSandboxHome({ uid, gid, home }, root) + expect(statSync(home).isDirectory()).toBe(true) + }) + + it('leaves an existing home with its owner', () => { + const home = path.join(root, 'existing') + mkdirSync(home) + const owner = statSync(home).uid + expect(() => prepareSandboxHome({ uid: 4242, gid: 4242, home }, root)).not.toThrow() + expect(statSync(home).uid).toBe(owner) + }) + + it('never creates a home outside the home root', () => { + const home = path.join(root, 'etc', 'elsewhere') + prepareSandboxHome({ uid, gid, home }, root) + expect(existsSync(home)).toBe(false) + }) }) diff --git a/apps/sandbox-agent/src/accounts.ts b/apps/sandbox-agent/src/accounts.ts index 4a4dc92fdbc..032ef430bd4 100644 --- a/apps/sandbox-agent/src/accounts.ts +++ b/apps/sandbox-agent/src/accounts.ts @@ -1,4 +1,4 @@ -import { appendFileSync, chownSync, existsSync, mkdirSync, readFileSync, statSync } from 'node:fs' +import { appendFileSync, chownSync, existsSync, mkdirSync, readFileSync } from 'node:fs' import { homedir, userInfo } from 'node:os' import path from 'node:path' import { createLogger } from '@sim/logger' @@ -28,6 +28,14 @@ interface SandboxUserEntry { home: string } +/** The image names the sandbox user with root's uid or gid; running user code as it would be root. */ +export class RootSandboxUserError extends Error { + constructor() { + super(`The image's "${SANDBOX_AGENT_USER.name}" account has uid or gid 0; refusing to start`) + this.name = 'RootSandboxUserError' + } +} + function findPasswdEntry(passwd: string, name: string): SandboxUserEntry | null { for (const line of passwd.split('\n')) { const fields = line.split(':') @@ -35,11 +43,35 @@ function findPasswdEntry(passwd: string, name: string): SandboxUserEntry | null const uid = Number(fields[2]) const gid = Number(fields[3]) if (!Number.isInteger(uid) || !Number.isInteger(gid)) continue + if (uid === 0 || gid === 0) throw new RootSandboxUserError() return { uid, gid, home: fields[5] || SANDBOX_AGENT_USER.home } } return null } +/** + * Creates the sandbox user's home when it is missing and sits directly under `homeRoot`, handing + * it to the user. An existing home is left as the image (or volume) made it, and a home elsewhere + * is never created: chowning a path an image chose could give the user a system directory. + */ +export function prepareSandboxHome(entry: SandboxUserEntry, homeRoot = '/home'): void { + if (existsSync(entry.home)) return + if (path.dirname(entry.home) !== homeRoot) { + logger.warn('Sandbox user home is missing and outside the home root; not creating it', { + home: entry.home, + }) + return + } + try { + mkdirSync(entry.home) + } catch (error) { + // Created by someone else in the meantime: not ours to hand over. + if (error instanceof Error && 'code' in error && error.code === 'EEXIST') return + throw error + } + chownSync(entry.home, entry.uid, entry.gid) +} + function hasEntry(contents: string, name: string): boolean { return contents.split('\n').some((line) => line.split(':')[0] === name) } @@ -52,7 +84,7 @@ function appendLine(file: string, line: string): void { /** * Makes sure the account database under `rootDir` names the sandbox user, adding it (uid/gid * 1000, home `/home/user`, as in E2B's images) when absent. Idempotent: an existing `user` entry - * is used as it is, whatever its uid. Writes the files directly rather than running `useradd`, + * is used as it is, unless it has uid or gid 0 ({@link RootSandboxUserError}). Writes the files directly rather than running `useradd`, * which arbitrary images need not ship. */ export function ensureSandboxUserEntry(rootDir: string): SandboxUserEntry { @@ -80,8 +112,8 @@ export function ensureSandboxUserEntry(rootDir: string): SandboxUserEntry { /** * Resolves the identities processes run as. * - * As root (production), `user` is the sandbox user: its account entry and home directory are - * created if missing, and the agent drops its own supplementary groups so a child switched to + * As root (production), `user` is the sandbox user: its account entry is created if missing (an + * image entry with uid or gid 0 stops the agent), its home is created only under `/home`, and the agent drops its own supplementary groups so a child switched to * uid 1000 cannot keep root's groups. Bun's spawn clears them too when it switches uid; dropping * them here keeps that true whatever the runtime does. A read-only `/etc` is tolerated: the switch is by numeric * id and `HOME` is set explicitly, so the entry is a convenience for tools like `whoami`. @@ -108,13 +140,10 @@ export function resolveAccounts(): Accounts { try { entry = ensureSandboxUserEntry('/') } catch (error) { + if (error instanceof RootSandboxUserError) throw error logger.warn('Could not record the sandbox user in /etc', { error: getErrorMessage(error) }) } - mkdirSync(entry.home, { recursive: true }) - const homeStat = statSync(entry.home) - if (homeStat.uid !== entry.uid || homeStat.gid !== entry.gid) { - chownSync(entry.home, entry.uid, entry.gid) - } + prepareSandboxHome(entry) if (!process.setgroups) throw new Error('Cannot drop the agent supplementary groups') process.setgroups([]) From 87a75eba836f81542210d3c399ddf74da0016edf Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:17:23 -0600 Subject: [PATCH 17/78] fix(sandbox): re-exec the CLI verifier from /proc/self/exe and document accepted gaps The verifier now re-executes the image the kernel loaded rather than process.execPath, matching the file worker, so no replaceable path is involved (the agent volume is mounted read-only as well). Documents that verifyCli is a staleness check, not a security control, since the session user owns the artifacts, and that a descendant calling setsid escapes the group kill: an accepted gap bounded by the sandbox lifetime and pod deletion. --- apps/sandbox-agent/src/processes.ts | 10 +++++++++- apps/sandbox-agent/src/verify-cli.ts | 20 +++++++++++--------- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/apps/sandbox-agent/src/processes.ts b/apps/sandbox-agent/src/processes.ts index 1be75f735c6..e5668cd6945 100644 --- a/apps/sandbox-agent/src/processes.ts +++ b/apps/sandbox-agent/src/processes.ts @@ -118,7 +118,15 @@ export class ProcessRecord { type DistributiveOmit = T extends unknown ? Omit : never -/** Sends `signal` to every process in the group led by `pid`; false when none remain. */ +/** + * Sends `signal` to every process in the group led by `pid`; false when none remain. + * + * Accepted gap: a descendant that starts its own session (`setsid`) or process group leaves this + * group and survives a timeout or Stop. The agent has no PID namespace (that needs + * CAP_SYS_ADMIN), and killing every uid-1000 process would also kill a session's deliberate + * background work. Such a process is bounded by the sandbox's lifetime, when the agent kills + * what it can and exits, and by pod deletion, which ends every process in the pod. + */ function killGroup(pid: number | undefined, signal: NodeJS.Signals): boolean { if (pid === undefined) return false try { diff --git a/apps/sandbox-agent/src/verify-cli.ts b/apps/sandbox-agent/src/verify-cli.ts index 07af6f624b1..8fd5ce9c807 100644 --- a/apps/sandbox-agent/src/verify-cli.ts +++ b/apps/sandbox-agent/src/verify-cli.ts @@ -8,7 +8,7 @@ import { sandboxAgentCliVerificationSchema, } from '@sim/sandbox-agent-protocol' import type { ProcessIdentity } from '@/accounts' -import { AGENT_MODE_ENV, AGENT_MODES, isCompiledBinary } from '@/self' +import { AGENT_MODE_ENV, AGENT_MODES, selfCommand } from '@/self' /** Exit status for a mismatched, missing, or non-regular artifact (the same as the app's check). */ const STALE_EXIT_CODE = 10 @@ -61,14 +61,15 @@ export async function runCliVerifier(input: string): Promise { return 0 } -/** argv that re-enters this program: a compiled binary is its own entry, a script needs its path. */ -function selfInvocation(): string[] { - return isCompiledBinary() ? [] : [Bun.main] -} - /** - * Checks `verifyCli` as the sandbox user, in a child of this binary. Running it unprivileged is - * what keeps a user-planted symlink from steering a root `chmod` or launcher write elsewhere. + * Checks `verifyCli` as the sandbox user, in a child re-executed from `/proc/self/exe`. Running it + * unprivileged is what keeps a user-planted symlink from steering a root `chmod` or launcher + * write elsewhere. + * + * This is a staleness check, not a security control: it answers whether the CLI a session + * installed still matches this release, so a deploy never runs a command against an old CLI. The + * artifacts live in a directory the sandbox user owns, so code in the session can change them at + * any moment after the check passes. */ export function verifyCliAsUser( verification: SandboxAgentCliVerification, @@ -78,7 +79,8 @@ export function verifyCliAsUser( return new Promise((resolve) => { let child: ReturnType try { - child = spawn(process.execPath, [...selfInvocation()], { + const self = selfCommand() + child = spawn(self.file, self.args, { cwd: '/', env: { ...baseEnvironment, HOME: identity.home, [AGENT_MODE_ENV]: AGENT_MODES.verifyCli }, stdio: ['pipe', 'ignore', 'ignore'], From 4fe1ccadb6747235766d9309405459b0075364f6 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:18:00 -0600 Subject: [PATCH 18/78] build(sandbox): pin the sandbox-agent builder base image by digest Pins oven/bun:1.4.4-slim to its multi-arch index digest, so a retagged base cannot change what the carrier binary is compiled from. --- docker/sandbox-agent.Dockerfile | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docker/sandbox-agent.Dockerfile b/docker/sandbox-agent.Dockerfile index cc8f5e6c038..7ce415db40e 100644 --- a/docker/sandbox-agent.Dockerfile +++ b/docker/sandbox-agent.Dockerfile @@ -10,9 +10,10 @@ # ======================================== # ======================================== -# Base Stage: Debian (glibc) Bun, matching the Debian sandbox images +# Base Stage: Debian (glibc) Bun, matching the Debian sandbox images. Pinned by +# digest (the multi-arch index), so a retagged base cannot change the binary. # ======================================== -FROM oven/bun:1.4.4-slim AS base +FROM oven/bun:1.4.4-slim@sha256:1846adf22496bd711036aae8be147e57bdebbaea2e5264e3e0b5af1db187d9a4 AS base # ======================================== # Pruner Stage: Emit the monorepo subset @sim/sandbox-agent builds from From 1f87d740d7be9af17c8a703b3ff455a3063694cf Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:30:15 -0600 Subject: [PATCH 19/78] fix(sandbox): settle session commands and report lifetime expiry in the agent - Session commands (reapDescendants) carry a per-command marker in their environment. Before their exit is reported, the agent kills the group and sweeps /proc for every process in the command's session or group, or carrying its marker, which covers background jobs, double forks and setsid, like E2B's PID-namespace launcher. The root daemon lacks CAP_SYS_PTRACE and cannot read uid-1000 environments, so the file worker repeats the sweep as the sandbox user. env -i plus setsid remains an accepted escape bounded by lifetime and pod deletion. - Lifetime expiry and SIGTERM end every live record with a final exit flagged lifetimeExpired (or a cancelled refusal before launch) and give attached streams a second to carry it before the agent exits. - A signal for a key no start has named leaves a tombstone, so a start that arrives after its own Stop is refused as cancelled. - Shell commands run as /bin/bash -l -c, as E2B's commands.run does. - POST /v1/lifetime takes a relative ttlMs and answers remainingMs, so the app's and the pod's clocks need not agree. --- apps/sandbox-agent/src/descendants.ts | 75 ++++++++++++ apps/sandbox-agent/src/file-worker.ts | 14 +++ apps/sandbox-agent/src/lifetime.ts | 15 ++- apps/sandbox-agent/src/main.ts | 18 ++- apps/sandbox-agent/src/processes.test.ts | 66 +++++++++++ apps/sandbox-agent/src/processes.ts | 107 +++++++++++++++--- apps/sandbox-agent/src/server.test.ts | 31 ++--- apps/sandbox-agent/src/server.ts | 10 +- apps/sandbox-agent/src/test-agent.ts | 14 ++- .../sandbox-agent-protocol/src/schemas.ts | 25 +++- 10 files changed, 326 insertions(+), 49 deletions(-) create mode 100644 apps/sandbox-agent/src/descendants.ts diff --git a/apps/sandbox-agent/src/descendants.ts b/apps/sandbox-agent/src/descendants.ts new file mode 100644 index 00000000000..007a4ef1b64 --- /dev/null +++ b/apps/sandbox-agent/src/descendants.ts @@ -0,0 +1,75 @@ +import { existsSync, readdirSync, readFileSync } from 'node:fs' + +/** + * Environment variable the agent sets on every reaped command, carrying its processKey. It is how + * a descendant that left the command's session and process group is still recognized. + */ +export const COMMAND_MARKER_ENV = 'SIM_AGENT_COMMAND_KEY' + +const MARKER_PREFIX = Buffer.from(`${COMMAND_MARKER_ENV}=`) +const MAX_SWEEPS = 5 + +/** The command marker in a process's environment block, or null when it carries none. */ +function markerOf(environment: Buffer): string | null { + let start = environment.indexOf(MARKER_PREFIX) + while (start > 0 && environment[start - 1] !== 0) { + start = environment.indexOf(MARKER_PREFIX, start + 1) + } + if (start < 0) return null + const valueStart = start + MARKER_PREFIX.byteLength + const end = environment.indexOf(0, valueStart) + return environment.subarray(valueStart, end < 0 ? undefined : end).toString('utf8') +} + +/** + * SIGKILLs every process that belongs to the command led by `leaderPid` (already killed as a + * group by the caller), so a session command settles like E2B's, whose PID-namespace launcher + * takes every descendant down with it. Without a PID namespace (`unshare` needs CAP_SYS_ADMIN, + * which Pod Security "baseline" forbids) a process belongs to the command when: + * - its environment carries this command's marker, which covers `sleep 999 &`, double forks and + * `setsid`; or + * - it carries no marker but its session or process group is the command's. + * + * A process carrying another command's marker is never touched, even if the leader's pid was + * reused for it. Sweeps repeat while they find anything, since a dying process may fork. + * + * Reading another process's environment needs ptrace read access: the same uid, or + * CAP_SYS_PTRACE, which the pod drops. So the root daemon sweeps root's processes and the file + * worker repeats the sweep as the sandbox user; an unreadable process is matched by session and + * group alone. A setuid program the user runs (`ping`, `sudo`) is not readable by either. + * + * Accepted gap: a descendant that both clears its environment (`env -i`) and leaves the session + * (`setsid`) is not found. It can only affect the caller's own session and ends with the + * sandbox's lifetime or the pod. Without `/proc` (a developer machine) only the group kill applies. + */ +export function reapCommandProcesses(leaderPid: number, marker: string): void { + if (!existsSync('/proc')) return + for (let sweep = 0; sweep < MAX_SWEEPS; sweep++) { + let killed = 0 + for (const name of readdirSync('/proc')) { + if (!/^\d+$/.test(name)) continue + const pid = Number(name) + if (pid === process.pid) continue + let stat: string + let environment: Buffer + try { + stat = readFileSync(`/proc/${name}/stat`, 'utf8') + environment = readFileSync(`/proc/${name}/environ`) + } catch { + continue + } + const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ') + if (fields[0] === 'Z') continue + const carried = markerOf(environment) + const belongs = + carried === marker || + (carried === null && (Number(fields[2]) === leaderPid || Number(fields[3]) === leaderPid)) + if (!belongs) continue + try { + process.kill(pid, 'SIGKILL') + killed += 1 + } catch {} + } + if (killed === 0) return + } +} diff --git a/apps/sandbox-agent/src/file-worker.ts b/apps/sandbox-agent/src/file-worker.ts index 6c0ccc696a8..d13e774d417 100644 --- a/apps/sandbox-agent/src/file-worker.ts +++ b/apps/sandbox-agent/src/file-worker.ts @@ -10,6 +10,7 @@ import { import { getErrorMessage } from '@sim/utils/errors' import { z } from 'zod' import type { ProcessIdentity } from '@/accounts' +import { reapCommandProcesses } from '@/descendants' import { FileOperationError, listDirectory, @@ -41,6 +42,11 @@ const fileCallSchema = z.discriminatedUnion('op', [ z.object({ op: z.literal('remove'), path: z.string() }), z.object({ op: z.literal('read'), path: z.string(), maxBytes: z.number().int().optional() }), z.object({ op: z.literal('write'), path: z.string() }), + z.object({ + op: z.literal('reap'), + leaderPid: z.number().int().positive(), + marker: z.string(), + }), ]) type FileCall = z.infer @@ -87,6 +93,9 @@ export async function runFileWorker(): Promise { case 'remove': await removePath(call.path) return settle(id, {}) + case 'reap': + reapCommandProcesses(call.leaderPid, call.marker) + return settle(id, {}) case 'read': { const { size, body } = await openFileForRead(call.path, call.maxBytes) const gate = new CreditGate() @@ -189,6 +198,11 @@ export class FileWorker { await this.call({ op: 'remove', path }) } + /** Runs a command's descendant sweep as the sandbox user (see {@link reapCommandProcesses}). */ + async reap(leaderPid: number, marker: string): Promise { + await this.call({ op: 'reap', leaderPid, marker }) + } + async read( path: string, maxBytes: number | undefined diff --git a/apps/sandbox-agent/src/lifetime.ts b/apps/sandbox-agent/src/lifetime.ts index 985cd3c546d..b7be6e7f718 100644 --- a/apps/sandbox-agent/src/lifetime.ts +++ b/apps/sandbox-agent/src/lifetime.ts @@ -21,13 +21,18 @@ export class Lifetime { return this.deadlineMs } - /** Moves the deadline to `expiresAtMs` unless it is already later; returns the deadline in force. */ - extend(expiresAtMs: number): number { - if (this.deadlineMs === undefined || expiresAtMs > this.deadlineMs) { - this.deadlineMs = expiresAtMs + /** + * Keeps the sandbox alive at least `ttlMs` from now, unless the deadline is already later, and + * returns the milliseconds remaining. Durations rather than instants keep the app's and the + * pod's clocks from having to agree. + */ + extend(ttlMs: number): number { + const requested = Date.now() + ttlMs + if (this.deadlineMs === undefined || requested > this.deadlineMs) { + this.deadlineMs = requested this.arm() } - return this.deadlineMs + return Math.max(0, this.deadlineMs - Date.now()) } private arm(): void { diff --git a/apps/sandbox-agent/src/main.ts b/apps/sandbox-agent/src/main.ts index c52573f4d96..e7373898633 100644 --- a/apps/sandbox-agent/src/main.ts +++ b/apps/sandbox-agent/src/main.ts @@ -12,14 +12,24 @@ import { runCliVerifier } from '@/verify-cli' const logger = createLogger('SandboxAgent') +/** How long a stopping agent waits for clients to read the final exit events. */ +const SHUTDOWN_FLUSH_MS = 1_000 + async function serve(): Promise { const config = readAgentConfig(process.env) const accounts = resolveAccounts() - const processes = new ProcessTable(accounts, config.baseEnvironment) + const userFiles = new FileWorker(accounts.identityFor('user'), config.baseEnvironment) + const processes = new ProcessTable(accounts, config.baseEnvironment, (leaderPid, marker) => + userFiles.reap(leaderPid, marker) + ) + let stopping = false const shutdown = (reason: string) => { + if (stopping) return + stopping = true logger.info('Sandbox agent stopping every process', { reason }) - processes.killAll() - process.exit(0) + processes.expireAll() + // Attached streams get a moment to carry the final exit events before the agent is gone. + setTimeout(() => process.exit(0), SHUTDOWN_FLUSH_MS) } const lifetime = new Lifetime(config.expiresAtMs, () => shutdown('lifetime ended')) // As a container's PID 1 the agent gets no default signal handling, so a pod deletion's @@ -30,7 +40,7 @@ async function serve(): Promise { tokenSha256: config.tokenSha256, host: config.host, port: config.port, - userFiles: new FileWorker(accounts.identityFor('user'), config.baseEnvironment), + userFiles, processes, lifetime, }) diff --git a/apps/sandbox-agent/src/processes.test.ts b/apps/sandbox-agent/src/processes.test.ts index 29faaaeeb36..cf76cc75d75 100644 --- a/apps/sandbox-agent/src/processes.test.ts +++ b/apps/sandbox-agent/src/processes.test.ts @@ -69,6 +69,13 @@ describe('process launch', () => { expect(Object.keys(environment).filter((name) => name.startsWith('REDIS_'))).toEqual([]) }) + it('runs shell commands in a login shell, as E2B does', async () => { + const events = await readEvents( + await agent.startProcess({ shell: 'shopt -q login_shell && echo login' }) + ) + expect(stdoutOf(events)).toBe('login\n') + }) + it('rejects a relative working directory', async () => { const response = await agent.startProcess({ shell: 'true', cwd: 'relative/dir' }) expect(response.status).toBe(400) @@ -206,6 +213,65 @@ describe('idempotent launch and reattach', () => { }) }) +describe('Stop before start', () => { + it('tombstones a signalled key so a start racing in afterwards runs nothing', async () => { + const processKey = generateId() + const marker = path.join(agent.root, `ran-${generateId()}`) + const signal = await agent.request(sandboxAgentProcessSignalPath(processKey), { + method: 'POST', + body: JSON.stringify({ signal: 'SIGKILL' }), + }) + expect(await signal.json()).toEqual({ delivered: false }) + const events = await readEvents( + await agent.startProcess({ processKey, shell: `touch ${marker}` }) + ) + expect(events).toEqual([expect.objectContaining({ type: 'rejected', reason: 'cancelled' })]) + expect(existsSync(marker)).toBe(false) + }) +}) + +describe('session descendant cleanup', () => { + const hasProc = existsSync('/proc') + const skipped = hasProc ? '' : ' [skipped: needs /proc (Linux) to find escaped descendants]' + const pidsIn = (file: string) => + readFileSync(file, 'utf8').trim().split('\n').filter(Boolean).map(Number) + + it.skipIf(!hasProc)( + `kills background, double-forked, and setsid descendants before reporting exit${skipped}`, + async () => { + const pidFile = path.join(agent.root, `descendants-${generateId()}`) + const events = await readEvents( + await agent.startProcess({ + reapDescendants: true, + shell: [ + `sleep 600 & echo $! >> ${pidFile}`, + `( sleep 600 & echo $! >> ${pidFile} ) &`, + `setsid sleep 600 & echo $! >> ${pidFile}`, + 'sleep 0.3', + ].join('\n'), + }) + ) + expect(events.at(-1)).toMatchObject({ type: 'exit', exitCode: 0 }) + const pids = pidsIn(pidFile) + expect(pids).toHaveLength(3) + await vi.waitFor(() => expect(pids.filter(isAlive)).toEqual([]), { timeout: 5_000 }) + } + ) + + it.skipIf(!hasProc)( + `leaves a one-shot command's background process running${skipped}`, + async () => { + const pidFile = path.join(agent.root, `background-${generateId()}`) + await readEvents( + await agent.startProcess({ shell: `setsid sleep 600 & echo $! > ${pidFile}` }) + ) + const [pid] = pidsIn(pidFile) + expect(isAlive(pid)).toBe(true) + process.kill(pid, 'SIGKILL') + } + ) +}) + describe('CLI verification at launch', () => { const sha256 = (content: string) => createHash('sha256').update(content).digest('hex') diff --git a/apps/sandbox-agent/src/processes.ts b/apps/sandbox-agent/src/processes.ts index e5668cd6945..aa382ff9c03 100644 --- a/apps/sandbox-agent/src/processes.ts +++ b/apps/sandbox-agent/src/processes.ts @@ -11,6 +11,7 @@ import { } from '@sim/sandbox-agent-protocol' import { getErrorMessage } from '@sim/utils/errors' import type { Accounts } from '@/accounts' +import { COMMAND_MARKER_ENV, reapCommandProcesses } from '@/descendants' import { verifyCliAsUser } from '@/verify-cli' const logger = createLogger('SandboxAgentProcesses') @@ -21,6 +22,11 @@ export type RecordedEvent = Exclude /** Exit status reported when the agent's own timeout stopped the process (as E2B reports it). */ const TIMEOUT_EXIT_CODE = 124 +/** Exit status reported for a process the sandbox's lifetime ended (SIGKILL's shell code). */ +const LIFETIME_EXIT_CODE = 137 + +/** How long a signal for a key no start has named keeps that key refused. */ + /** * How long a finished process's output pipes may stay open after the process itself exited. * A background grandchild that kept stdout open would otherwise hold the command open until @@ -50,11 +56,21 @@ export class ProcessRecord { private child?: ChildProcess private cancelled = false + /** + * @param fingerprint Digest of the start request, or null for a tombstone: a key signalled + * before any start arrived, which any later start attaches to and finds already refused. + * @param reapDescendants Whether the command's whole process tree dies with it (sessions). + */ constructor( readonly key: string, - readonly fingerprint: string + readonly fingerprint: string | null, + readonly reapDescendants = false ) {} + get pid(): number | undefined { + return this.child?.pid + } + get finished(): boolean { return this.state === 'finished' } @@ -114,6 +130,25 @@ export class ProcessRecord { } return killGroup(this.child?.pid, signal) } + + /** + * Ends the record because the sandbox's lifetime ran out: kills its processes and reports a + * final `exit` flagged `lifetimeExpired` (or, before launch, a `cancelled` refusal) right away, + * so attached clients learn the outcome before the agent exits. + */ + expire(): void { + if (this.finished) return + if (this.state === 'launching') { + this.cancelled = true + this.emit({ type: 'rejected', reason: 'cancelled' }) + return + } + killGroup(this.child?.pid, 'SIGKILL') + if (this.reapDescendants && this.child?.pid !== undefined) { + reapCommandProcesses(this.child.pid, this.key) + } + this.emit({ type: 'exit', exitCode: LIFETIME_EXIT_CODE, lifetimeExpired: true }) + } } type DistributiveOmit = T extends unknown ? Omit : never @@ -141,6 +176,12 @@ function fingerprintOf(request: StartProcessRequest): string { return createHash('sha256').update(JSON.stringify(request)).digest('hex') } +/** + * Login shell, as E2B's `commands.run` invokes it (`/bin/bash -l -c`), so profile scripts the + * image installs apply exactly as they do there. + */ +const SHELL = ['/bin/bash', '-l', '-c'] as const + export type StartOutcome = | { record: ProcessRecord } | { error: 'process_key_conflict' | 'too_many_processes' } @@ -152,9 +193,16 @@ export type StartOutcome = export class ProcessTable { private readonly records = new Map() + /** + * @param reapAsUser Repeats a command's descendant sweep as the sandbox user. The root daemon + * runs without CAP_SYS_PTRACE, so it cannot read another uid's `/proc//environ`; the + * sandbox user can read its own processes', which is how a `setsid` escapee running as the + * user is still found by its marker. + */ constructor( private readonly accounts: Accounts, - private readonly baseEnvironment: Record + private readonly baseEnvironment: Record, + private readonly reapAsUser: (leaderPid: number, marker: string) => Promise ) {} get(key: string): ProcessRecord | undefined { @@ -165,7 +213,7 @@ export class ProcessTable { const fingerprint = fingerprintOf(request) const existing = this.records.get(request.processKey) if (existing) { - return existing.fingerprint === fingerprint + return existing.fingerprint === fingerprint || existing.fingerprint === null ? { record: existing } : { error: 'process_key_conflict' } } @@ -174,7 +222,11 @@ export class ProcessTable { if (active >= MAX_RUNNING_PROCESSES || this.records.size >= MAX_RECORDED_PROCESSES) { return { error: 'too_many_processes' } } - const record = new ProcessRecord(request.processKey, fingerprint) + const record = new ProcessRecord( + request.processKey, + fingerprint, + request.reapDescendants === true + ) this.records.set(request.processKey, record) void this.launch(record, request).catch((error: unknown) => { logger.error('Process launch failed', { error: getErrorMessage(error) }) @@ -183,9 +235,25 @@ export class ProcessTable { return { record } } - /** Kills every running process group; used when the sandbox's lifetime ends. */ - killAll(): void { - for (const record of this.records.values()) record.signal('SIGKILL') + /** + * Signals a process by key. A key no start has named yet gets a tombstone: a finished record + * refused as `cancelled`, which a start racing in afterwards attaches to instead of launching, + * so a Stop that overtakes its own start still prevents the run. Returns whether a live process + * (or pending launch) was signalled. + */ + signal(key: string, signal: 'SIGTERM' | 'SIGKILL'): boolean { + const record = this.records.get(key) + if (record) return record.signal(signal) + this.evictFinished() + const tombstone = new ProcessRecord(key, null) + tombstone.emit({ type: 'rejected', reason: 'cancelled' }) + this.records.set(key, tombstone) + return false + } + + /** Ends every live record; used when the sandbox's lifetime ends or the pod is stopping. */ + expireAll(): void { + for (const record of this.records.values()) record.expire() } private evictFinished(): void { @@ -223,7 +291,7 @@ export class ProcessTable { } if (record.wasCancelled) return this.reject(record, 'cancelled') - const [file, ...args] = request.argv ?? ['/bin/bash', '-c', request.shell ?? ''] + const [file, ...args] = request.argv ?? [...SHELL, request.shell ?? ''] const child = spawn(file, args, { cwd: request.cwd ?? identity.home, env: { @@ -232,6 +300,7 @@ export class ProcessTable { USER: identity.name, LOGNAME: identity.name, ...request.envs, + ...(request.reapDescendants ? { [COMMAND_MARKER_ENV]: request.processKey } : {}), }, detached: true, stdio: ['ignore', 'pipe', 'pipe'], @@ -246,7 +315,7 @@ export class ProcessTable { } record.attach(child) record.emit({ type: 'started', pid }) - superviseProcess(record, child, pid, request) + superviseProcess(record, child, pid, request, this.reapAsUser) } } @@ -255,9 +324,12 @@ function superviseProcess( record: ProcessRecord, child: ChildProcess, pid: number, - request: StartProcessRequest + request: StartProcessRequest, + reapAsUser: (leaderPid: number, marker: string) => Promise ): void { let timedOut = false + /** Settles once a reaped command's descendants are gone; the exit is reported after it. */ + let reaped: Promise = Promise.resolve() let outputLimitExceeded = false let exit: { code: number | null; signal: NodeJS.Signals | null } | undefined let drainTimer: ReturnType | undefined @@ -327,8 +399,10 @@ function superviseProcess( const flushStdout = forward(child.stdout, 'stdout') const flushStderr = forward(child.stderr, 'stderr') - const finish = () => { + const finish = async () => { if (record.finished || !exit) return + await reaped + if (record.finished) return flushStdout() flushStderr() clearTimeout(timeoutTimer) @@ -347,11 +421,18 @@ function superviseProcess( child.on('exit', (code, signal) => { exit = { code, signal } + if (record.reapDescendants) { + killGroup(pid, 'SIGKILL') + reapCommandProcesses(pid, record.key) + reaped = reapAsUser(pid, record.key).catch((error: unknown) => { + logger.warn('Sandbox-user descendant sweep failed', { error: getErrorMessage(error) }) + }) + } drainTimer = setTimeout(() => { child.stdout?.destroy() child.stderr?.destroy() - finish() + void finish() }, PIPE_DRAIN_GRACE_MS) }) - child.on('close', finish) + child.on('close', () => void finish()) } diff --git a/apps/sandbox-agent/src/server.test.ts b/apps/sandbox-agent/src/server.test.ts index 0bd03acd89b..a74eb917504 100644 --- a/apps/sandbox-agent/src/server.test.ts +++ b/apps/sandbox-agent/src/server.test.ts @@ -8,7 +8,7 @@ import { } from '@sim/sandbox-agent-protocol' import { generateId } from '@sim/utils/id' import { describe, expect, it, vi } from 'vitest' -import { isAlive, startTestAgent } from '@/test-agent' +import { isAlive, readEvents, startTestAgent } from '@/test-agent' describe('authentication', () => { it('serves /healthz without a token and refuses every other route without the right one', async () => { @@ -95,38 +95,43 @@ describe('request limits', () => { }) describe('lifetime', () => { - it('never shortens the deadline', async () => { + it('extends by a relative duration and never shortens the deadline', async () => { const agent = await startTestAgent() try { - const extend = async (expiresAtMs: number) => { + const extend = async (ttlMs: number) => { const response = await agent.request(SANDBOX_AGENT_ROUTES.lifetime, { method: 'POST', - body: JSON.stringify({ expiresAtMs }), + body: JSON.stringify({ ttlMs }), }) - return ((await response.json()) as { expiresAtMs: number }).expiresAtMs + return ((await response.json()) as { remainingMs: number }).remainingMs } - const later = Date.now() + 3_600_000 - expect(await extend(later)).toBe(later) - expect(await extend(later - 60_000)).toBe(later) + const first = await extend(3_600_000) + expect(first).toBeGreaterThan(3_590_000) + expect(first).toBeLessThanOrEqual(3_600_000) + expect(await extend(60_000)).toBeGreaterThan(3_500_000) } finally { await agent.stop() } }) - it('kills every process group and exits 0 when the deadline passes', async () => { + it('reports lifetime expiry to attached clients, kills every group, and exits 0', async () => { const agent = await startTestAgent({ env: { [SANDBOX_AGENT_EXPIRES_AT_ENV]: String(Date.now() + 3_000) }, }) try { const pidFile = path.join(agent.root, `survivor-${generateId()}`) - void agent.startProcess({ - shell: `sleep 600 & echo $! > ${pidFile}; wait`, - timeoutMs: 60_000, - }) + const stream = agent + .startProcess({ shell: `sleep 600 & echo $! > ${pidFile}; wait`, timeoutMs: 60_000 }) + .then(readEvents) await vi.waitFor(() => expect(readFileSync(pidFile, 'utf8')).toMatch(/^\d+\n$/), { timeout: 5_000, }) const grandchild = Number(readFileSync(pidFile, 'utf8')) + expect((await stream).at(-1)).toMatchObject({ + type: 'exit', + exitCode: 137, + lifetimeExpired: true, + }) expect(await agent.exited).toBe(0) await vi.waitFor(() => expect(isAlive(grandchild)).toBe(false), { timeout: 5_000 }) } finally { diff --git a/apps/sandbox-agent/src/server.ts b/apps/sandbox-agent/src/server.ts index e05a6064d99..a9302dc52fb 100644 --- a/apps/sandbox-agent/src/server.ts +++ b/apps/sandbox-agent/src/server.ts @@ -209,15 +209,15 @@ async function route(request: Request, url: URL, deps: AgentServerDependencies) const processRoute = /^\/v1\/processes\/([^/]+)\/(events|signal)$/.exec(pathname) if (processRoute) { const key = parse(sandboxAgentProcessKeySchema, decodeURIComponent(processRoute[1])) - const record = deps.processes.get(key) - if (!record) throw new RequestError('not_found', 'No process has this processKey') if (processRoute[2] === 'events') { if (method !== 'GET') throw new RequestError('method_not_allowed', 'Use GET') + const record = deps.processes.get(key) + if (!record) throw new RequestError('not_found', 'No process has this processKey') return eventStream(record, parseSeq(url.searchParams.get('from'))) } if (method !== 'POST') throw new RequestError('method_not_allowed', 'Use POST') const { signal } = parse(signalProcessRequestSchema, await readJson(request)) - return json({ delivered: record.signal(signal) }) + return json({ delivered: deps.processes.signal(key, signal) }) } const files = (user: 'root' | 'user') => (user === 'root' ? ROOT_FILES : deps.userFiles) @@ -260,8 +260,8 @@ async function route(request: Request, url: URL, deps: AgentServerDependencies) if (pathname === SANDBOX_AGENT_ROUTES.lifetime) { if (method !== 'POST') throw new RequestError('method_not_allowed', 'Use POST') - const { expiresAtMs } = parse(lifetimeRequestSchema, await readJson(request)) - return json({ expiresAtMs: deps.lifetime.extend(expiresAtMs) }) + const { ttlMs } = parse(lifetimeRequestSchema, await readJson(request)) + return json({ remainingMs: deps.lifetime.extend(ttlMs) }) } throw new RequestError('not_found', 'No such route') diff --git a/apps/sandbox-agent/src/test-agent.ts b/apps/sandbox-agent/src/test-agent.ts index cf6be1adae7..26a11391c20 100644 --- a/apps/sandbox-agent/src/test-agent.ts +++ b/apps/sandbox-agent/src/test-agent.ts @@ -1,6 +1,6 @@ import { type ChildProcess, spawn } from 'node:child_process' import { createHash } from 'node:crypto' -import { chmodSync, mkdtempSync, realpathSync, rmSync } from 'node:fs' +import { chmodSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs' import { createServer } from 'node:net' import { tmpdir } from 'node:os' import path from 'node:path' @@ -132,12 +132,20 @@ export function stdoutOf(events: StreamEvent[]): string { return events.map((event) => (event.type === 'stdout' ? event.data : '')).join('') } -/** True while a process with this pid exists (a zombie counts until it is reaped). */ +/** + * True while a process with this pid is running. A zombie counts as gone: it has exited and only + * waits for a parent to reap it, which in a container without an init can be never. + */ export function isAlive(pid: number): boolean { try { process.kill(pid, 0) - return true } catch { return false } + try { + const stat = readFileSync(`/proc/${pid}/stat`, 'utf8') + return stat.slice(stat.lastIndexOf(')') + 2, stat.lastIndexOf(')') + 3) !== 'Z' + } catch { + return true + } } diff --git a/packages/sandbox-agent-protocol/src/schemas.ts b/packages/sandbox-agent-protocol/src/schemas.ts index 5b79e7eb9a8..3ce28ff8fac 100644 --- a/packages/sandbox-agent-protocol/src/schemas.ts +++ b/packages/sandbox-agent-protocol/src/schemas.ts @@ -90,6 +90,12 @@ export const startProcessRequestSchema = z timeoutMs: z.number().int().positive().max(SANDBOX_AGENT_MAX_TIMEOUT_MS), maxOutputBytes: z.number().int().positive().max(SANDBOX_AGENT_MAX_OUTPUT_BYTES), verifyCli: sandboxAgentCliVerificationSchema.optional(), + /** + * When the command's leader exits (or is stopped), also kill every process it started, + * including ones that left its session, before reporting `exit`. Session commands set it, to + * settle like E2B's namespace-launched session commands. + */ + reapDescendants: z.boolean().optional(), }) .refine((request) => (request.argv === undefined) !== (request.shell === undefined), { message: 'Exactly one of argv or shell is required', @@ -128,6 +134,8 @@ export const processEventSchema = z.discriminatedUnion('type', [ exitCode: z.number().int(), timedOut: z.boolean().optional(), outputLimitExceeded: z.boolean().optional(), + /** The sandbox's lifetime ended the process: a provider limit, not the program's outcome. */ + lifetimeExpired: z.boolean().optional(), }), z.object({ type: z.literal('rejected'), @@ -142,21 +150,26 @@ export type ProcessEvent = z.infer /** * `POST /v1/processes/{processKey}/signal`. The signal reaches the whole process group, or - * cancels a launch still verifying its CLI. Answers `{ delivered }`, false once the process - * has finished. + * cancels a launch still verifying its CLI. Answers `{ delivered }`, false once the process has + * finished. A key no start has named yet is tombstoned: a later start with it is refused as + * `cancelled`, so a Stop that overtakes its start still prevents the run. */ export const signalProcessRequestSchema = z.object({ signal: z.enum(['SIGTERM', 'SIGKILL']), }) -/** `POST /v1/lifetime`. A request never shortens an existing deadline. */ +/** + * `POST /v1/lifetime`: keep the sandbox alive at least `ttlMs` from when the agent receives it. + * Relative, so the caller's and the pod's clocks never have to agree. A request never shortens + * an existing deadline. + */ export const lifetimeRequestSchema = z.object({ - expiresAtMs: z.number().int().positive(), + ttlMs: z.number().int().positive(), }) -/** The deadline in force after the request. */ +/** Milliseconds left on the deadline in force after the request, by the agent's clock. */ export const lifetimeResponseSchema = z.object({ - expiresAtMs: z.number().int().positive(), + remainingMs: z.number().int().nonnegative(), }) /** `GET /v1/files/stat`. Symlinks are followed; `other` is a FIFO, socket, or device. */ From 31e9b02917e331699eee2de2299adbfab41e0344 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:31:12 -0600 Subject: [PATCH 20/78] refactor(sandbox): share login-shell PATH handling and environment validation Moves E2B's PATH alias for bash -l -c (preserveLoginShellPath, alias prefix unchanged) and Daytona's environment check (assertSafeProcessEnvironment, same messages) into provider-neutral modules, so the agent-backed handle applies both identically. --- .../lib/execution/remote-sandbox/daytona.ts | 16 +------------ apps/sim/lib/execution/remote-sandbox/e2b.ts | 19 ++------------- .../execution/remote-sandbox/login-shell.ts | 23 +++++++++++++++++++ .../remote-sandbox/process-environment.ts | 18 +++++++++++++++ 4 files changed, 44 insertions(+), 32 deletions(-) create mode 100644 apps/sim/lib/execution/remote-sandbox/login-shell.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/process-environment.ts diff --git a/apps/sim/lib/execution/remote-sandbox/daytona.ts b/apps/sim/lib/execution/remote-sandbox/daytona.ts index 48ed98056bf..c48ca3968a1 100644 --- a/apps/sim/lib/execution/remote-sandbox/daytona.ts +++ b/apps/sim/lib/execution/remote-sandbox/daytona.ts @@ -29,6 +29,7 @@ import { tailStreamedSandboxOutput, } from '@/lib/execution/remote-sandbox/output-limits' import { resolveSandboxDirectoryEntryPath } from '@/lib/execution/remote-sandbox/paths' +import { assertSafeProcessEnvironment } from '@/lib/execution/remote-sandbox/process-environment' import type { CreateSandboxOptions, RunCommandOptions, @@ -59,21 +60,6 @@ function isDaytonaExecutionTimeout(error: unknown): boolean { return error.name === 'DaytonaTimeoutError' || error.name === 'TimeoutError' } -const ENVIRONMENT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/ - -function assertSafeProcessEnvironment(envs: Record | undefined): void { - for (const [name, value] of Object.entries(envs ?? {})) { - if (!ENVIRONMENT_NAME_PATTERN.test(name)) { - throw new Error( - 'Sandbox environment variable names must start with a letter or underscore and contain only letters, numbers, and underscores' - ) - } - if (value.includes('\0')) { - throw new Error('Sandbox environment variable values may not contain null bytes') - } - } -} - function snapshotFor(kind: SandboxKind, imageRef?: string): string { if (kind === 'mothership') { const snapshot = env.DAYTONA_SHELL_SNAPSHOT_ID?.trim() diff --git a/apps/sim/lib/execution/remote-sandbox/e2b.ts b/apps/sim/lib/execution/remote-sandbox/e2b.ts index 104ad578fac..7ce0f75f390 100644 --- a/apps/sim/lib/execution/remote-sandbox/e2b.ts +++ b/apps/sim/lib/execution/remote-sandbox/e2b.ts @@ -40,6 +40,7 @@ import { FUNCTION_SANDBOX_MATERIALIZER_REVISION, FUNCTION_SANDBOX_MEMORY_MB, } from '@/lib/execution/remote-sandbox/function-resources' +import { preserveLoginShellPath } from '@/lib/execution/remote-sandbox/login-shell' import { recordSandboxProcess, reportUnsettledSandboxProcess, @@ -162,22 +163,6 @@ function isE2BExecutionTimeout(error: unknown): boolean { return name === 'TimeoutError' && E2B_TIMEOUT_MESSAGE_PATTERN.test(message) } -function prepareE2BCommand( - command: string, - envs: Record | undefined -): { command: string; envs?: Record } { - if (!envs || !Object.hasOwn(envs, 'PATH')) return { command, ...(envs ? { envs } : {}) } - - let pathAlias = E2B_COMMAND_PATH_ALIAS_PREFIX - while (Object.hasOwn(envs, pathAlias)) pathAlias += '_' - - const { PATH, ...rest } = envs - return { - command: `export PATH="$${pathAlias}"; unset ${pathAlias}\n${command}`, - envs: { ...rest, [pathAlias]: PATH }, - } -} - /** Only a command whose own timeout would outlive the cap can have been ended by it. */ function reachedE2BProviderLimit( error: unknown, @@ -565,7 +550,7 @@ class E2BSandboxHandle implements SandboxHandle { processRecorded = true options.signal?.throwIfAborted() } - const prepared = prepareE2BCommand(command, options.envs) + const prepared = preserveLoginShellPath(command, options.envs, E2B_COMMAND_PATH_ALIAS_PREFIX) const processOptions = { ...(prepared.envs ? { envs: prepared.envs } : {}), timeoutMs: e2bTimeoutMs(options.timeoutMs), diff --git a/apps/sim/lib/execution/remote-sandbox/login-shell.ts b/apps/sim/lib/execution/remote-sandbox/login-shell.ts new file mode 100644 index 00000000000..e69a8b432ee --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/login-shell.ts @@ -0,0 +1,23 @@ +/** + * Carries a caller's `PATH` through a login shell. `bash -l` sources `/etc/profile`, which on + * Debian resets `PATH`, so the value travels under an alias variable and is restored after + * startup, before the command runs. The value is never inlined into the command text, so it is + * never parsed as shell. Shared by every provider that starts commands as `bash -l -c` (E2B's + * `commands.run`, the sandbox agent). + */ +export function preserveLoginShellPath( + command: string, + envs: Record | undefined, + aliasPrefix: string +): { command: string; envs?: Record } { + if (!envs || !Object.hasOwn(envs, 'PATH')) return { command, ...(envs ? { envs } : {}) } + + let pathAlias = aliasPrefix + while (Object.hasOwn(envs, pathAlias)) pathAlias += '_' + + const { PATH, ...rest } = envs + return { + command: `export PATH="$${pathAlias}"; unset ${pathAlias}\n${command}`, + envs: { ...rest, [pathAlias]: PATH }, + } +} diff --git a/apps/sim/lib/execution/remote-sandbox/process-environment.ts b/apps/sim/lib/execution/remote-sandbox/process-environment.ts new file mode 100644 index 00000000000..dd42a788c3e --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/process-environment.ts @@ -0,0 +1,18 @@ +const ENVIRONMENT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/ + +/** + * Refuses environment variables a process cannot receive intact: a name outside the portable + * shell set, or a value containing NUL (which `execve` would silently truncate). + */ +export function assertSafeProcessEnvironment(envs: Record | undefined): void { + for (const [name, value] of Object.entries(envs ?? {})) { + if (!ENVIRONMENT_NAME_PATTERN.test(name)) { + throw new Error( + 'Sandbox environment variable names must start with a letter or underscore and contain only letters, numbers, and underscores' + ) + } + if (value.includes('\0')) { + throw new Error('Sandbox environment variable values may not contain null bytes') + } + } +} From be2741c2a46fe7150eeb565cd5ae709a7e5db17b Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:43:03 -0600 Subject: [PATCH 21/78] fix(sandbox): settle agent session commands like E2B and surface lifetime limits Session sandboxes are now identified by sessionKey (replacing session: true). Session commands are claimed with recordSandboxProcess before launch, launched with reapDescendants so the agent kills their whole process tree, and settled or reported unsettled afterwards, as E2B's are. SandboxAgentClient.stopProcess signals (or tombstones) a processKey and waits for its terminal event; a provider's stopSessionProcess can call it with the recorded process id. - An exit flagged lifetimeExpired, or an unobservable outcome past the deadline, becomes providerFailure provider_limit, and runCode reports SandboxLifetimeLimitError, matching E2B's 24-hour cap. - Reattaching resets its budget whenever events arrived and backs off with jitter; an event stream silent for three heartbeats counts as dropped; Zod or NDJSON protocol violations fail at once. - An unrecognized error status on an at-most-once start is indeterminate. - Commands run through E2B's login-shell PATH handling; environment names are checked with Daytona's message; absolute paths are normalized. - extendLifetime sends a relative ttlMs; retry sleeps are abortable; response bodies are consumed; file reads fail after 120 s idle; the process output limit reported is the one the agent enforced. - The handle tests become handle.integration.ts (real agent over HTTP), adding abort, session timeout, callbacks, rootUser, cli_check_failed, short reads, upload and read cancellation, lifetime, claim and settle, and descendant cleanup, and dropping a declaration-only test. Because the integration suite now reaches handle.ts, the knip entry for it is gone. --- .../execution/remote-sandbox/agent/client.ts | 75 ++- .../agent/handle.integration.ts | 579 ++++++++++++++++++ .../remote-sandbox/agent/handle.test.ts | 289 --------- .../execution/remote-sandbox/agent/handle.ts | 360 +++++++---- .../execution/remote-sandbox/code-process.ts | 2 +- knip.jsonc | 5 +- 6 files changed, 905 insertions(+), 405 deletions(-) create mode 100644 apps/sim/lib/execution/remote-sandbox/agent/handle.integration.ts delete mode 100644 apps/sim/lib/execution/remote-sandbox/agent/handle.test.ts diff --git a/apps/sim/lib/execution/remote-sandbox/agent/client.ts b/apps/sim/lib/execution/remote-sandbox/agent/client.ts index 1bf985bde15..012ba0f689c 100644 --- a/apps/sim/lib/execution/remote-sandbox/agent/client.ts +++ b/apps/sim/lib/execution/remote-sandbox/agent/client.ts @@ -1,9 +1,13 @@ import { createLogger } from '@sim/logger' import { + NdjsonDecoder, + processEventSchema, type SandboxAgentErrorCode, sandboxAgentErrorBodySchema, + sandboxAgentProcessEventsPath, + sandboxAgentProcessSignalPath, } from '@sim/sandbox-agent-protocol' -import { sleep } from '@sim/utils/helpers' +import { getErrorMessage } from '@sim/utils/errors' import { backoffWithJitter } from '@sim/utils/retry' const logger = createLogger('SandboxAgentClient') @@ -13,8 +17,12 @@ const REQUEST_TIMEOUT_MS = 30_000 const MAX_ATTEMPTS = 3 const RETRY_BACKOFF = { baseMs: 200, maxMs: 2_000 } -/** The agent answered with a protocol error: the request was refused, so nothing it named ran. */ +/** The agent answered with an error status: the request was refused or failed there. */ export class SandboxAgentRequestError extends Error { + /** + * @param code The protocol error code, or `unknown` when the body was not a protocol error + * (a proxy or a crashed agent), in which case nothing is known about what ran. + */ constructor( readonly status: number, readonly code: SandboxAgentErrorCode | 'unknown', @@ -26,7 +34,7 @@ export class SandboxAgentRequestError extends Error { } } -export interface AgentRequestOptions { +interface AgentRequestOptions { method?: 'GET' | 'POST' | 'PUT' | 'DELETE' query?: Record json?: unknown @@ -54,6 +62,25 @@ async function toRequestError(response: Response): Promise { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason) + return + } + const onAbort = () => { + clearTimeout(timer) + reject(signal?.reason) + } + const timer = setTimeout(() => { + signal?.removeEventListener('abort', onAbort) + resolve() + }, ms) + signal?.addEventListener('abort', onAbort, { once: true }) + }) +} + /** Authenticated requests to one sandbox's agent. */ export class SandboxAgentClient { constructor( @@ -61,7 +88,7 @@ export class SandboxAgentClient { private readonly token: string ) {} - /** Returns a 2xx response, or throws {@link SandboxAgentRequestError} for a protocol error. */ + /** Returns a 2xx response, or throws {@link SandboxAgentRequestError} for an error status. */ async request(route: string, options: AgentRequestOptions = {}): Promise { const query = options.query ? `?${new URLSearchParams(options.query).toString()}` : '' const url = `${this.baseUrl.replace(/\/$/, '')}${route}${query}` @@ -93,7 +120,7 @@ export class SandboxAgentClient { route, attempt, }) - await sleep(backoffWithJitter(attempt, null, RETRY_BACKOFF)) + await abortableSleep(backoffWithJitter(attempt, null, RETRY_BACKOFF), options.signal) continue } if (response.ok) return response @@ -106,4 +133,42 @@ export class SandboxAgentClient { const response = await this.request(route, options) return response.json() } + + /** + * SIGKILLs a process (or tombstones a key the agent has not seen, so a start arriving later + * runs nothing) and waits for its terminal event, which for a session command means every + * descendant is gone. Resolves true once that is confirmed, false when it could not be within + * `signal`. A provider's `stopSessionProcess` calls this with the recorded process id. + */ + async stopProcess(processKey: string, fromSeq: number, signal: AbortSignal): Promise { + try { + const stopped = await this.request(sandboxAgentProcessSignalPath(processKey), { + method: 'POST', + json: { signal: 'SIGKILL' }, + signal, + retry: true, + }) + await stopped.body?.cancel() + const events = await this.request(sandboxAgentProcessEventsPath(processKey), { + query: { from: String(fromSeq) }, + signal, + timeout: false, + }) + if (!events.body) return false + const decoder = new NdjsonDecoder() + for await (const chunk of events.body) { + for (const value of decoder.push(chunk)) { + const event = processEventSchema.parse(value) + if (event.type === 'exit' || event.type === 'rejected') return true + } + } + return false + } catch (error) { + logger.warn('Could not confirm a sandbox agent process stopped', { + processKey, + error: getErrorMessage(error), + }) + return false + } + } } diff --git a/apps/sim/lib/execution/remote-sandbox/agent/handle.integration.ts b/apps/sim/lib/execution/remote-sandbox/agent/handle.integration.ts new file mode 100644 index 00000000000..8be17def907 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/agent/handle.integration.ts @@ -0,0 +1,579 @@ +import { type ChildProcess, spawn } from 'node:child_process' +import { createHash } from 'node:crypto' +import { + chmodSync, + existsSync, + mkdtempSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, +} from 'node:fs' +import { createServer as createHttpServer } from 'node:http' +import { createServer, type Server, Socket } from 'node:net' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { + SANDBOX_AGENT_EXPIRES_AT_ENV, + SANDBOX_AGENT_HOST_ENV, + SANDBOX_AGENT_PORT_ENV, + SANDBOX_AGENT_ROUTES, + SANDBOX_AGENT_TOKEN_SHA256_ENV, +} from '@sim/sandbox-agent-protocol' +import { generateId } from '@sim/utils/id' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { CodeLanguage } from '@/lib/execution/languages' +import { isSandboxLaunchIndeterminateError } from '@/lib/execution/non-retryable-error' +import { + type AgentSandboxConnection, + createAgentSandboxHandle, +} from '@/lib/execution/remote-sandbox/agent/handle' +import { observeSandboxExecution } from '@/lib/execution/remote-sandbox/observer' +import { + SessionCliStaleError, + SessionCliVerificationError, +} from '@/lib/execution/remote-sandbox/session-cli' +import type { SessionProcessIdentity } from '@/lib/execution/remote-sandbox/session-process' + +/** + * Drives the handle against the real `sim-sandbox-agent`, started from source with `bun` on a + * loopback port. Every agent route, the NDJSON stream, and reattachment cross a real HTTP + * connection; byte-level TCP proxies stand in for a network that drops or alters traffic. + * Needs `bun`, `python3` and `node` on PATH; the descendant-cleanup cases need Linux `/proc`. + */ +const AGENT_ENTRY = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../../../../sandbox-agent/src/main.ts' +) + +interface RunningAgent { + port: number + home: string + child: ChildProcess + exited: Promise +} + +const token = generateId() +let agent: RunningAgent + +async function freePort(): Promise { + return new Promise((resolve, reject) => { + const server = createServer() + server.once('error', reject) + server.listen(0, '127.0.0.1', () => { + const address = server.address() + server.close(() => + typeof address === 'object' && address + ? resolve(address.port) + : reject(new Error('no port')) + ) + }) + }) +} + +async function startAgent(env: Record = {}): Promise { + const home = realpathSync(mkdtempSync(path.join(tmpdir(), 'sim-agent-handle-'))) + const port = await freePort() + const child = spawn('bun', [AGENT_ENTRY], { + env: { + PATH: process.env.PATH ?? '/usr/bin:/bin', + HOME: home, + [SANDBOX_AGENT_TOKEN_SHA256_ENV]: createHash('sha256').update(token).digest('hex'), + [SANDBOX_AGENT_PORT_ENV]: String(port), + [SANDBOX_AGENT_HOST_ENV]: '127.0.0.1', + ...env, + }, + stdio: 'ignore', + }) + const exited = new Promise((resolve) => child.once('exit', resolve)) + await vi.waitFor( + async () => { + const response = await fetch(`http://127.0.0.1:${port}${SANDBOX_AGENT_ROUTES.healthz}`) + if (!response.ok) throw new Error('agent not ready') + }, + { timeout: 15_000, interval: 50 } + ) + return { port, home, child, exited } +} + +async function stopAgent(running: RunningAgent): Promise { + if (running.child.exitCode === null && running.child.signalCode === null) { + running.child.kill('SIGKILL') + } + await running.exited + rmSync(running.home, { recursive: true, force: true }) +} + +function connection(overrides: Partial = {}): AgentSandboxConnection { + return { + sandboxId: 'sbx-test', + baseUrl: `http://127.0.0.1:${agent.port}`, + token, + expiresAtMs: Date.now() + 600_000, + userHome: agent.home, + kill: async () => {}, + ...overrides, + } +} + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0) + } catch { + return false + } + try { + const stat = readFileSync(`/proc/${pid}/stat`, 'utf8') + return stat.slice(stat.lastIndexOf(')') + 2, stat.lastIndexOf(')') + 3) !== 'Z' + } catch { + return true + } +} + +/** + * Forwards to the agent, rewriting what the agent sends back: `transform` sees each + * response chunk (latin1) and returns what to relay, or null to cut the connection there. + */ +async function startProxy(transform: (chunk: string, connection: number) => string | null) { + const port = await freePort() + const sockets = new Set() + let connections = 0 + const server: Server = createServer((client) => { + const upstream = new Socket() + const index = connections++ + sockets.add(client) + sockets.add(upstream) + upstream.connect(agent.port, '127.0.0.1') + client.on('data', (chunk) => upstream.write(chunk)) + upstream.on('data', (chunk: Buffer) => { + const relayed = transform(chunk.toString('latin1'), index) + if (relayed === null) { + client.destroy() + upstream.destroy() + return + } + client.write(Buffer.from(relayed, 'latin1')) + }) + client.on('error', () => upstream.destroy()) + upstream.on('error', () => client.destroy()) + client.on('close', () => upstream.destroy()) + upstream.on('close', () => client.destroy()) + }) + await new Promise((resolve) => server.listen(port, '127.0.0.1', resolve)) + return { + baseUrl: `http://127.0.0.1:${port}`, + close: () => + new Promise((resolve) => { + for (const socket of sockets) socket.destroy() + server.close(() => resolve()) + }), + } +} + +/** A proxy that cuts the first `drops` responses as soon as they contain `after`. */ +function startDroppingProxy(options: { drops: number; after: string }) { + let remaining = options.drops + const seen = new Map() + return startProxy((chunk, index) => { + const relayed = (seen.get(index) ?? '') + chunk + seen.set(index, relayed) + if (remaining > 0 && relayed.includes(options.after)) { + remaining -= 1 + return null + } + return chunk + }) +} + +beforeAll(async () => { + agent = await startAgent() +}, 30_000) + +afterAll(async () => { + await stopAgent(agent) +}) + +describe('runCode over the agent', () => { + it('runs Python from a home-relative file and removes it afterwards', async () => { + const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.Python })) + const result = await sandbox.runCode( + 'import json, os\nprint("__SIM_RESULT__=" + json.dumps({"cwd": os.getcwd(), "v": os.environ["MINE"]}))', + { timeoutMs: 20_000, envs: { MINE: 'set' } } + ) + expect(result.error).toBeUndefined() + const marker = result.stdout.trim().split('\n').at(-1) ?? '' + expect(JSON.parse(marker.slice('__SIM_RESULT__='.length))).toEqual({ + cwd: agent.home, + v: 'set', + }) + expect(readdirSync(agent.home).filter((name) => name.startsWith('.sim-function-'))).toEqual([]) + }) + + it('runs JavaScript through the CommonJS preload with require and runtime bindings', async () => { + const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.JavaScript })) + const result = await sandbox.runCode( + 'const os = require("node:os")\nconsole.log("__SIM_RESULT__=" + JSON.stringify({ binding: globalThis.__simBinding, eol: os.EOL }))', + { timeoutMs: 20_000, javascriptPreload: 'globalThis.__simBinding = 42' } + ) + expect(result.error).toBeUndefined() + expect(result.stdout).toContain('__SIM_RESULT__={"binding":42,"eol":"\\n"}') + }) + + it('reports a Python exception in the shared error shape', async () => { + const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.Python })) + const result = await sandbox.runCode('raise ValueError("boom")', { timeoutMs: 20_000 }) + expect(result.error).toMatchObject({ name: 'ValueError', value: 'boom' }) + expect(result.error?.traceback).toContain('Traceback') + }) + + it('reports a timeout as timedOut rather than an error', async () => { + const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.Python })) + const result = await sandbox.runCode('import time\ntime.sleep(60)', { timeoutMs: 1_000 }) + expect(result.timedOut).toBe(true) + expect(result.error).toBeUndefined() + }) + + it('fails with the enforced process output limit when code prints past its budget', async () => { + const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.Python })) + await expect( + sandbox.runCode('while True: print("x" * 1000)', { + timeoutMs: 20_000, + maxOutputBytes: 10_000, + }) + ).rejects.toMatchObject({ + code: 'sandbox_output_limit_exceeded', + outputKind: 'process', + limitBytes: 10_000, + }) + }) +}) + +describe('commands over the agent', () => { + it('runs in a login shell and still honours the caller PATH', async () => { + const sandbox = createAgentSandboxHandle(connection()) + const result = await sandbox.runCommand( + 'shopt -q login_shell && echo login; echo "$PATH"; env | grep -c __SIM_COMMAND_PATH', + { timeoutMs: 10_000, envs: { PATH: `/custom/bin:${process.env.PATH ?? '/usr/bin:/bin'}` } } + ) + const [shell, pathLine, aliasCount] = result.stdout.trim().split('\n') + expect(shell).toBe('login') + expect(pathLine.startsWith('/custom/bin:')).toBe(true) + expect(aliasCount).toBe('0') + }) + + it('streams output to callbacks while keeping only a tail', async () => { + const sandbox = createAgentSandboxHandle(connection()) + const seen: string[] = [] + const errors: string[] = [] + const result = await sandbox.runCommand('echo out; echo err >&2', { + timeoutMs: 10_000, + onStdout: (chunk) => seen.push(chunk), + onStderr: (chunk) => errors.push(chunk), + }) + expect(seen.join('')).toBe('out\n') + expect(errors.join('')).toBe('err\n') + expect(result).toMatchObject({ stdout: 'out\n', stderr: 'err\n', exitCode: 0 }) + }) + + it('refuses an unsafe environment name before contacting the agent', async () => { + const sandbox = createAgentSandboxHandle(connection({ baseUrl: 'http://127.0.0.1:9' })) + await expect( + sandbox.runCommand('true', { timeoutMs: 1_000, envs: { 'BAD-NAME': '1' } }) + ).rejects.toThrow('Sandbox environment variable names must start with a letter') + }) + + it('stops the process group when the caller aborts', async () => { + const sandbox = createAgentSandboxHandle(connection()) + const pidFile = path.join(agent.home, `pid-${generateId()}`) + const controller = new AbortController() + const run = sandbox.runCommand(`echo $$ > ${pidFile}; exec sleep 30`, { + timeoutMs: 60_000, + signal: controller.signal, + }) + await vi.waitFor(() => expect(existsSync(pidFile)).toBe(true), { timeout: 10_000 }) + const pid = Number(readFileSync(pidFile, 'utf8')) + controller.abort(new DOMException('user', 'AbortError')) + await expect(run).rejects.toMatchObject({ name: 'AbortError', message: 'user' }) + await vi.waitFor(() => expect(isAlive(pid)).toBe(false), { timeout: 10_000 }) + }) + + it.skipIf(process.getuid?.() !== 0)( + `runs rootUser commands as root and others as the sandbox user${process.getuid?.() === 0 ? '' : ` [skipped: an unprivileged agent cannot switch users; this run is uid ${process.getuid?.()}]`}`, + async () => { + const sandbox = createAgentSandboxHandle(connection()) + const asRoot = await sandbox.runCommand('id -u', { timeoutMs: 10_000, rootUser: true }) + const asUser = await sandbox.runCommand('id -u', { timeoutMs: 10_000 }) + expect(asRoot.stdout.trim()).toBe('0') + expect(asUser.stdout.trim()).toBe('1000') + } + ) +}) + +describe('at-most-once commands over a failing network', () => { + it('reattaches after the stream drops mid-run and runs the command exactly once', async () => { + const proxy = await startDroppingProxy({ drops: 1, after: '"type":"started"' }) + try { + const marker = path.join(agent.home, `runs-${generateId()}`) + const sandbox = createAgentSandboxHandle(connection({ baseUrl: proxy.baseUrl })) + const result = await sandbox.runCommand( + `echo run >> ${marker}; sleep 0.5; echo first; sleep 0.5; echo second`, + { timeoutMs: 20_000, atMostOnce: true } + ) + expect(result).toMatchObject({ exitCode: 0, stdout: 'first\nsecond\n' }) + expect(readFileSync(marker, 'utf8')).toBe('run\n') + } finally { + await proxy.close() + } + }) + + it('fails indeterminate, never rerunning, when the outcome cannot be observed', async () => { + const proxy = await startDroppingProxy({ drops: 1_000, after: 'HTTP/1.1' }) + try { + const marker = path.join(agent.home, `runs-${generateId()}`) + const sandbox = createAgentSandboxHandle(connection({ baseUrl: proxy.baseUrl })) + const outcome = await sandbox + .runCommand(`echo run >> ${marker}; sleep 2`, { timeoutMs: 20_000, atMostOnce: true }) + .catch((error: unknown) => error) + expect(isSandboxLaunchIndeterminateError(outcome)).toBe(true) + await vi.waitFor(() => expect(existsSync(marker)).toBe(true)) + expect(readFileSync(marker, 'utf8')).toBe('run\n') + } finally { + await proxy.close() + } + }) + + it('treats an unrecognized error status on start as indeterminate, not as a refusal', async () => { + const server = createHttpServer((_, response) => { + response.writeHead(502, { 'Content-Type': 'text/html' }) + response.end('bad gateway') + }) + const port = await freePort() + await new Promise((resolve) => server.listen(port, '127.0.0.1', resolve)) + try { + const sandbox = createAgentSandboxHandle(connection({ baseUrl: `http://127.0.0.1:${port}` })) + const outcome = await sandbox + .runCommand('true', { timeoutMs: 1_000, atMostOnce: true }) + .catch((error: unknown) => error) + expect(isSandboxLaunchIndeterminateError(outcome)).toBe(true) + } finally { + await new Promise((resolve) => server.close(() => resolve())) + } + }) +}) + +describe('files over the agent', () => { + it('round-trips buffered and streamed files and lists them relative to the directory', async () => { + const sandbox = createAgentSandboxHandle(connection()) + const directory = path.join(agent.home, `out-${generateId()}`) + await sandbox.writeFile(path.join(directory, 'a.txt'), 'alpha') + await sandbox.writeFileStream( + path.join(directory, 'nested', 'b.bin'), + new Blob([new Uint8Array([0, 1, 2, 255])]).stream(), + { signal: AbortSignal.timeout(10_000) } + ) + + expect(await sandbox.readFile(path.join(directory, 'a.txt'))).toBe('alpha') + const binary = await sandbox.readFileWithLimit(path.join(directory, 'nested', 'b.bin'), { + maxBytes: 4, + encoding: 'base64', + }) + expect(binary).toEqual({ + content: Buffer.from([0, 1, 2, 255]).toString('base64'), + byteLength: 4, + }) + const stream = await sandbox.readFileStream(path.join(directory, 'a.txt'), { + signal: AbortSignal.timeout(10_000), + }) + expect(await new Response(stream).text()).toBe('alpha') + + const entries = await sandbox.listFiles(directory, { depth: 2 }) + expect(entries.map((entry) => [entry.relativePath, entry.kind]).sort()).toEqual([ + ['a.txt', 'file'], + ['nested', 'directory'], + ['nested/b.bin', 'file'], + ]) + }) + + it('normalizes an absolute path with parent segments, as E2B accepts it', async () => { + const sandbox = createAgentSandboxHandle(connection()) + const name = `dotted-${generateId()}` + await sandbox.writeFile(`${agent.home}/sub/../${name}`, 'normalized') + expect(readFileSync(path.join(agent.home, name), 'utf8')).toBe('normalized') + }) + + it('refuses a file over the read limit and a directory read as a file', async () => { + const sandbox = createAgentSandboxHandle(connection()) + const target = path.join(agent.home, `large-${generateId()}`) + await sandbox.writeFile(target, 'x'.repeat(100)) + await expect( + sandbox.readFileWithLimit(target, { maxBytes: 10, encoding: 'utf8' }) + ).rejects.toMatchObject({ code: 'sandbox_output_limit_exceeded' }) + await expect(sandbox.getFileSize(agent.home)).rejects.toMatchObject({ + code: 'sandbox_output_file_invalid', + }) + }) + + it('fails a read whose body ends short of the size the agent declared', async () => { + const proxy = await startProxy((chunk) => + chunk.replace(/(X-Sim-File-Size|x-sim-file-size): 5\r\n/, '$1: 9\r\n') + ) + try { + const target = path.join(agent.home, `short-${generateId()}`) + const sandbox = createAgentSandboxHandle(connection({ baseUrl: proxy.baseUrl })) + await sandbox.writeFile(target, 'hello') + const stream = await sandbox.readFileStream(target, { signal: AbortSignal.timeout(10_000) }) + await expect(new Response(stream).text()).rejects.toThrow('truncated') + } finally { + await proxy.close() + } + }) + + it('aborts a streamed upload without leaving a partial file', async () => { + const sandbox = createAgentSandboxHandle(connection()) + const target = path.join(agent.home, `aborted-${generateId()}`) + const controller = new AbortController() + let sent = 0 + const stalled = new ReadableStream({ + async pull(stream) { + sent += 1 + if (sent <= 3) { + stream.enqueue(new Uint8Array(64 * 1024)) + return + } + // The upload is mid-body when the caller gives up; the source never finishes. + controller.abort(new DOMException('user', 'AbortError')) + await new Promise(() => {}) + }, + }) + await expect( + sandbox.writeFileStream(target, stalled, { signal: controller.signal }) + ).rejects.toMatchObject({ name: 'AbortError' }) + expect(existsSync(target)).toBe(false) + await sandbox.writeFile(`${target}-after`, 'still serving') + }) + + it('cancels a streamed read without disturbing later requests', async () => { + const sandbox = createAgentSandboxHandle(connection()) + const target = path.join(agent.home, `cancelled-${generateId()}`) + await sandbox.writeFile(target, 'y'.repeat(4 * 1024 * 1024)) + const stream = await sandbox.readFileStream(target, { signal: AbortSignal.timeout(10_000) }) + const reader = stream.getReader() + await reader.read() + await reader.cancel() + expect(await sandbox.getFileSize(target)).toBe(4 * 1024 * 1024) + }) +}) + +describe('session semantics', () => { + it('extends the agent lifetime by duration and reports the window it covers', async () => { + const sandbox = createAgentSandboxHandle( + connection({ sessionKey: 'session-a', expiresAtMs: Date.now() }) + ) + expect(sandbox.verifiesCliAtLaunch).toBe(true) + expect(sandbox.outlives?.(60_000, Date.now())).toBe(false) + await sandbox.extendLifetime?.(3_600_000) + expect(sandbox.outlives?.(3_000_000, Date.now())).toBe(true) + }) + + it('refuses a command whose CLI is stale, running nothing', async () => { + const sandbox = createAgentSandboxHandle(connection({ sessionKey: 'session-a' })) + const cli = path.join(agent.home, `cli-${generateId()}`) + const marker = path.join(agent.home, `ran-${generateId()}`) + await sandbox.writeFile(cli, 'current') + await expect( + sandbox.runCommand(`touch ${marker}`, { + timeoutMs: 10_000, + verifyCli: { path: cli, artifacts: { [cli]: '0'.repeat(64) } }, + }) + ).rejects.toBeInstanceOf(SessionCliStaleError) + expect(existsSync(marker)).toBe(false) + }) + + it('reports a CLI check that cannot complete as a verification failure', async () => { + const sandbox = createAgentSandboxHandle(connection({ sessionKey: 'session-a' })) + const directory = path.join(agent.home, `locked-${generateId()}`) + const cli = path.join(directory, 'sim-9') + await sandbox.writeFile(cli, 'release') + chmodSync(directory, 0o555) + try { + const digest = createHash('sha256').update('release').digest('hex') + await expect( + sandbox.runCommand('true', { + timeoutMs: 10_000, + verifyCli: { path: cli, artifacts: { [cli]: digest } }, + }) + ).rejects.toBeInstanceOf(SessionCliVerificationError) + } finally { + chmodSync(directory, 0o755) + } + }) + + it("returns timedOut when a session caller's own deadline stops the command", async () => { + const sandbox = createAgentSandboxHandle(connection({ sessionKey: 'session-a' })) + const deadline = new AbortController() + const run = sandbox.runCommand('sleep 30', { timeoutMs: 60_000, signal: deadline.signal }) + // The execution-limits timeout reason, as a workflow's deadline aborts with it. + setTimeout(() => deadline.abort(new DOMException('timeout', 'AbortError')), 500) + const result = await run + expect(result).toMatchObject({ exitCode: 124, timedOut: true }) + }) + + it('claims each session command before launch and settles it after, as E2B does', async () => { + const sandbox = createAgentSandboxHandle(connection({ sessionKey: 'session-claims' })) + const claimProcess = vi.fn(async (_process: SessionProcessIdentity) => {}) + const settleProcess = vi.fn(async () => {}) + const unsettled = vi.fn() + await observeSandboxExecution({ hold: () => {}, unsettled, claimProcess, settleProcess }, () => + sandbox.runCommand('echo ok', { timeoutMs: 10_000 }) + ) + expect(claimProcess).toHaveBeenCalledWith({ + id: expect.any(String), + sandboxId: 'sbx-test', + sessionKey: 'session-claims', + }) + expect(settleProcess).toHaveBeenCalledWith(claimProcess.mock.calls[0][0].id) + expect(unsettled).not.toHaveBeenCalled() + }) + + it.skipIf(!existsSync('/proc'))( + `kills a session command's background and setsid descendants before returning${existsSync('/proc') ? '' : ' [skipped: needs /proc (Linux) to find escaped descendants]'}`, + async () => { + const sandbox = createAgentSandboxHandle(connection({ sessionKey: 'session-a' })) + const pidFile = path.join(agent.home, `descendants-${generateId()}`) + await sandbox.runCommand( + `sleep 600 & echo $! >> ${pidFile}; setsid sleep 600 & echo $! >> ${pidFile}; sleep 0.3`, + { timeoutMs: 10_000 } + ) + const pids = readFileSync(pidFile, 'utf8').trim().split('\n').map(Number) + expect(pids).toHaveLength(2) + await vi.waitFor(() => expect(pids.filter(isAlive)).toEqual([]), { timeout: 5_000 }) + } + ) +}) + +describe('sandbox lifetime', () => { + it('reports a command the lifetime ends as a provider limit, as E2B does', async () => { + const expiring = await startAgent({ + [SANDBOX_AGENT_EXPIRES_AT_ENV]: String(Date.now() + 3_000), + }) + try { + const sandbox = createAgentSandboxHandle({ + sandboxId: 'sbx-expiring', + baseUrl: `http://127.0.0.1:${expiring.port}`, + token, + language: CodeLanguage.Python, + expiresAtMs: Date.now() + 3_000, + userHome: expiring.home, + kill: async () => {}, + }) + const result = await sandbox.runCode('import time\ntime.sleep(60)', { timeoutMs: 60_000 }) + expect(result).toMatchObject({ + providerFailure: 'provider_limit', + error: { name: 'SandboxLifetimeLimitError' }, + }) + } finally { + await stopAgent(expiring) + } + }) +}) diff --git a/apps/sim/lib/execution/remote-sandbox/agent/handle.test.ts b/apps/sim/lib/execution/remote-sandbox/agent/handle.test.ts deleted file mode 100644 index 262223d0576..00000000000 --- a/apps/sim/lib/execution/remote-sandbox/agent/handle.test.ts +++ /dev/null @@ -1,289 +0,0 @@ -import { type ChildProcess, spawn } from 'node:child_process' -import { createHash } from 'node:crypto' -import { existsSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync } from 'node:fs' -import { createServer, type Server, Socket } from 'node:net' -import { tmpdir } from 'node:os' -import path from 'node:path' -import { fileURLToPath } from 'node:url' -import { - SANDBOX_AGENT_HOST_ENV, - SANDBOX_AGENT_PORT_ENV, - SANDBOX_AGENT_ROUTES, - SANDBOX_AGENT_TOKEN_SHA256_ENV, -} from '@sim/sandbox-agent-protocol' -import { generateId } from '@sim/utils/id' -import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' -import { CodeLanguage } from '@/lib/execution/languages' -import { isSandboxLaunchIndeterminateError } from '@/lib/execution/non-retryable-error' -import { - type AgentSandboxConnection, - createAgentSandboxHandle, -} from '@/lib/execution/remote-sandbox/agent/handle' -import { SessionCliStaleError } from '@/lib/execution/remote-sandbox/session-cli' - -/** - * Drives the handle against the real `sim-sandbox-agent`, started from source with `bun` on a - * loopback port. Every agent route, the NDJSON stream, and reattachment cross a real HTTP - * connection; a byte-counting TCP proxy stands in for a network that drops a stream mid-flight. - */ -const AGENT_ENTRY = path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - '../../../../../sandbox-agent/src/main.ts' -) - -let agent: ChildProcess -let agentPort: number -let home: string -const token = generateId() - -async function freePort(): Promise { - return new Promise((resolve, reject) => { - const server = createServer() - server.once('error', reject) - server.listen(0, '127.0.0.1', () => { - const address = server.address() - server.close(() => - typeof address === 'object' && address - ? resolve(address.port) - : reject(new Error('no port')) - ) - }) - }) -} - -function connection(overrides: Partial = {}): AgentSandboxConnection { - return { - sandboxId: 'sbx-test', - baseUrl: `http://127.0.0.1:${agentPort}`, - token, - expiresAtMs: Date.now() + 60_000, - userHome: home, - kill: async () => {}, - ...overrides, - } -} - -/** - * Forwards to the agent, but cuts a connection as soon as the bytes it relayed back to the client - * contain `after`, for the first `drops` connections that get that far. - */ -async function startDroppingProxy(options: { drops: number; after: string }) { - const port = await freePort() - let remaining = options.drops - const sockets = new Set() - const server: Server = createServer((client) => { - const upstream = new Socket() - sockets.add(client) - sockets.add(upstream) - let relayed = '' - upstream.connect(agentPort, '127.0.0.1') - client.on('data', (chunk) => upstream.write(chunk)) - upstream.on('data', (chunk: Buffer) => { - relayed += chunk.toString('latin1') - client.write(chunk) - if (remaining > 0 && relayed.includes(options.after)) { - remaining -= 1 - client.destroy() - upstream.destroy() - } - }) - client.on('error', () => upstream.destroy()) - upstream.on('error', () => client.destroy()) - client.on('close', () => upstream.destroy()) - upstream.on('close', () => client.destroy()) - }) - await new Promise((resolve) => server.listen(port, '127.0.0.1', resolve)) - return { - baseUrl: `http://127.0.0.1:${port}`, - close: () => - new Promise((resolve) => { - for (const socket of sockets) socket.destroy() - server.close(() => resolve()) - }), - } -} - -beforeAll(async () => { - home = realpathSync(mkdtempSync(path.join(tmpdir(), 'sim-agent-handle-'))) - agentPort = await freePort() - agent = spawn('bun', [AGENT_ENTRY], { - env: { - PATH: process.env.PATH ?? '/usr/bin:/bin', - HOME: home, - [SANDBOX_AGENT_TOKEN_SHA256_ENV]: createHash('sha256').update(token).digest('hex'), - [SANDBOX_AGENT_PORT_ENV]: String(agentPort), - [SANDBOX_AGENT_HOST_ENV]: '127.0.0.1', - }, - stdio: 'ignore', - }) - await vi.waitFor( - async () => { - const response = await fetch(`http://127.0.0.1:${agentPort}${SANDBOX_AGENT_ROUTES.healthz}`) - if (!response.ok) throw new Error('agent not ready') - }, - { timeout: 15_000, interval: 50 } - ) -}, 30_000) - -afterAll(() => { - agent.kill('SIGKILL') - rmSync(home, { recursive: true, force: true }) -}) - -describe('runCode over the agent', () => { - it('runs Python from a home-relative file and removes it afterwards', async () => { - const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.Python })) - const result = await sandbox.runCode( - 'import json, os\nprint("__SIM_RESULT__=" + json.dumps({"cwd": os.getcwd(), "v": os.environ["MINE"]}))', - { timeoutMs: 20_000, envs: { MINE: 'set' } } - ) - expect(result.error).toBeUndefined() - const marker = result.stdout.trim().split('\n').at(-1) ?? '' - expect(JSON.parse(marker.slice('__SIM_RESULT__='.length))).toEqual({ cwd: home, v: 'set' }) - expect(readdirSync(home).filter((name) => name.startsWith('.sim-function-'))).toEqual([]) - }) - - it('runs JavaScript through the CommonJS preload with require and runtime bindings', async () => { - const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.JavaScript })) - const result = await sandbox.runCode( - 'const os = require("node:os")\nconsole.log("__SIM_RESULT__=" + JSON.stringify({ binding: globalThis.__simBinding, eol: os.EOL }))', - { timeoutMs: 20_000, javascriptPreload: 'globalThis.__simBinding = 42' } - ) - expect(result.error).toBeUndefined() - expect(result.stdout).toContain('__SIM_RESULT__={"binding":42,"eol":"\\n"}') - }) - - it('reports a Python exception in the shared error shape', async () => { - const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.Python })) - const result = await sandbox.runCode('raise ValueError("boom")', { timeoutMs: 20_000 }) - expect(result.error).toMatchObject({ name: 'ValueError', value: 'boom' }) - expect(result.error?.traceback).toContain('Traceback') - }) - - it('reports a timeout as timedOut rather than an error', async () => { - const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.Python })) - const result = await sandbox.runCode('import time\ntime.sleep(60)', { timeoutMs: 1_000 }) - expect(result.timedOut).toBe(true) - expect(result.error).toBeUndefined() - }) - - it('fails with the process output limit when code prints past its budget', async () => { - const sandbox = createAgentSandboxHandle(connection({ language: CodeLanguage.Python })) - await expect( - sandbox.runCode('while True: print("x" * 1000)', { - timeoutMs: 20_000, - maxOutputBytes: 10_000, - }) - ).rejects.toMatchObject({ code: 'sandbox_output_limit_exceeded', outputKind: 'process' }) - }) -}) - -describe('at-most-once commands over a failing network', () => { - it('reattaches after the stream drops mid-run and runs the command exactly once', async () => { - const proxy = await startDroppingProxy({ drops: 1, after: '"type":"started"' }) - try { - const marker = path.join(home, `runs-${generateId()}`) - const sandbox = createAgentSandboxHandle(connection({ baseUrl: proxy.baseUrl })) - const result = await sandbox.runCommand( - `echo run >> ${marker}; sleep 0.5; echo first; sleep 0.5; echo second`, - { timeoutMs: 20_000, atMostOnce: true } - ) - expect(result).toMatchObject({ exitCode: 0, stdout: 'first\nsecond\n' }) - expect(readFileSync(marker, 'utf8')).toBe('run\n') - } finally { - await proxy.close() - } - }) - - it('fails indeterminate, never rerunning, when the outcome cannot be observed', async () => { - const proxy = await startDroppingProxy({ drops: 1_000, after: 'HTTP/1.1' }) - try { - const marker = path.join(home, `runs-${generateId()}`) - const sandbox = createAgentSandboxHandle(connection({ baseUrl: proxy.baseUrl })) - const outcome = await sandbox - .runCommand(`echo run >> ${marker}; sleep 2`, { timeoutMs: 20_000, atMostOnce: true }) - .catch((error: unknown) => error) - expect(isSandboxLaunchIndeterminateError(outcome)).toBe(true) - await vi.waitFor(() => expect(existsSync(marker)).toBe(true)) - expect(readFileSync(marker, 'utf8')).toBe('run\n') - } finally { - await proxy.close() - } - }) -}) - -describe('files over the agent', () => { - it('round-trips buffered and streamed files and lists them relative to the directory', async () => { - const sandbox = createAgentSandboxHandle(connection()) - const directory = path.join(home, `out-${generateId()}`) - await sandbox.writeFile(path.join(directory, 'a.txt'), 'alpha') - await sandbox.writeFileStream( - path.join(directory, 'nested', 'b.bin'), - new Blob([new Uint8Array([0, 1, 2, 255])]).stream(), - { signal: AbortSignal.timeout(10_000) } - ) - - expect(await sandbox.readFile(path.join(directory, 'a.txt'))).toBe('alpha') - const binary = await sandbox.readFileWithLimit(path.join(directory, 'nested', 'b.bin'), { - maxBytes: 4, - encoding: 'base64', - }) - expect(binary).toEqual({ - content: Buffer.from([0, 1, 2, 255]).toString('base64'), - byteLength: 4, - }) - const stream = await sandbox.readFileStream(path.join(directory, 'a.txt'), { - signal: AbortSignal.timeout(10_000), - }) - expect(await new Response(stream).text()).toBe('alpha') - - const entries = await sandbox.listFiles(directory, { depth: 2 }) - expect(entries.map((entry) => [entry.relativePath, entry.kind]).sort()).toEqual([ - ['a.txt', 'file'], - ['nested', 'directory'], - ['nested/b.bin', 'file'], - ]) - }) - - it('refuses a file over the read limit and a directory read as a file', async () => { - const sandbox = createAgentSandboxHandle(connection()) - const target = path.join(home, `large-${generateId()}`) - await sandbox.writeFile(target, 'x'.repeat(100)) - await expect( - sandbox.readFileWithLimit(target, { maxBytes: 10, encoding: 'utf8' }) - ).rejects.toMatchObject({ code: 'sandbox_output_limit_exceeded' }) - await expect(sandbox.getFileSize(home)).rejects.toMatchObject({ - code: 'sandbox_output_file_invalid', - }) - }) -}) - -describe('session semantics', () => { - it('extends the agent lifetime without shortening it and reports the window it covers', async () => { - const sandbox = createAgentSandboxHandle(connection({ session: true, expiresAtMs: Date.now() })) - expect(sandbox.verifiesCliAtLaunch).toBe(true) - expect(sandbox.outlives?.(60_000, Date.now())).toBe(false) - await sandbox.extendLifetime?.(3_600_000) - expect(sandbox.outlives?.(3_000_000, Date.now())).toBe(true) - }) - - it('omits lifetime control from a one-shot sandbox', () => { - const sandbox = createAgentSandboxHandle(connection()) - expect(sandbox.extendLifetime).toBeUndefined() - expect(sandbox.verifiesCliAtLaunch).toBe(false) - }) - - it('refuses a command whose CLI is stale, running nothing', async () => { - const sandbox = createAgentSandboxHandle(connection({ session: true })) - const cli = path.join(home, `cli-${generateId()}`) - const marker = path.join(home, `ran-${generateId()}`) - await sandbox.writeFile(cli, 'current') - await expect( - sandbox.runCommand(`touch ${marker}`, { - timeoutMs: 10_000, - verifyCli: { path: cli, artifacts: { [cli]: '0'.repeat(64) } }, - }) - ).rejects.toBeInstanceOf(SessionCliStaleError) - expect(existsSync(marker)).toBe(false) - }) -}) diff --git a/apps/sim/lib/execution/remote-sandbox/agent/handle.ts b/apps/sim/lib/execution/remote-sandbox/agent/handle.ts index d3058eb0f40..1a4eefc1082 100644 --- a/apps/sim/lib/execution/remote-sandbox/agent/handle.ts +++ b/apps/sim/lib/execution/remote-sandbox/agent/handle.ts @@ -4,20 +4,23 @@ import { fileStatResponseSchema, lifetimeResponseSchema, listFilesResponseSchema, + NdjsonDecodeError, NdjsonDecoder, type ProcessEvent, processEventSchema, SANDBOX_AGENT_FILE_SIZE_HEADER, + SANDBOX_AGENT_HEARTBEAT_MS, SANDBOX_AGENT_MAX_OUTPUT_BYTES, SANDBOX_AGENT_MAX_TIMEOUT_MS, SANDBOX_AGENT_ROUTES, SANDBOX_AGENT_USER, type StartProcessRequest, sandboxAgentProcessEventsPath, - sandboxAgentProcessSignalPath, } from '@sim/sandbox-agent-protocol' import { getErrorMessage } from '@sim/utils/errors' import { generateId } from '@sim/utils/id' +import { backoffWithJitter } from '@sim/utils/retry' +import { ZodError } from 'zod' import { isTimeoutAbortReason } from '@/lib/core/execution-limits' import { isPayloadSizeLimitError, @@ -26,10 +29,17 @@ import { import { CodeLanguage } from '@/lib/execution/languages' import { SandboxLaunchIndeterminateError } from '@/lib/execution/non-retryable-error' import { + abortableSleep, SandboxAgentClient, SandboxAgentRequestError, } from '@/lib/execution/remote-sandbox/agent/client' import { type CodeRunOptions, runCodeAsProcess } from '@/lib/execution/remote-sandbox/code-process' +import { preserveLoginShellPath } from '@/lib/execution/remote-sandbox/login-shell' +import { + recordSandboxProcess, + reportUnsettledSandboxProcess, + settleSandboxProcess, +} from '@/lib/execution/remote-sandbox/observer' import { appendStreamedSandboxOutput, MAX_SANDBOX_OUTPUT_BYTES, @@ -40,6 +50,7 @@ import { tailStreamedSandboxOutput, } from '@/lib/execution/remote-sandbox/output-limits' import { resolveSandboxDirectoryEntryPath } from '@/lib/execution/remote-sandbox/paths' +import { assertSafeProcessEnvironment } from '@/lib/execution/remote-sandbox/process-environment' import { SessionCliStaleError, SessionCliVerificationError, @@ -57,12 +68,24 @@ const logger = createLogger('AgentSandboxHandle') /** Name used in launch-indeterminate errors; the handle does not know which control plane made the sandbox. */ const PROVIDER_LABEL = 'The sandbox agent' -/** Reconnects a single command may make after its event stream drops. */ -const MAX_STREAM_RECONNECTS = 20 +/** Consecutive reattaches without new events before a command's outcome counts as lost. */ +const MAX_STREAM_REATTACHES = 5 +const REATTACH_BACKOFF = { baseMs: 250, maxMs: 5_000 } + +/** An event stream silent for three heartbeats is dead, even if its socket never closes. */ +const STREAM_IDLE_MS = 3 * SANDBOX_AGENT_HEARTBEAT_MS + +/** A file body stalled this long fails, as E2B's `streamIdleTimeoutMs` does. */ +const FILE_STREAM_IDLE_MS = 120_000 -/** How long a cancelled command may take to report its exit before the cancellation returns. */ +/** How long a cancelled command may take to confirm its exit. */ const CANCEL_SETTLE_MS = 5_000 +const PATH_ALIAS_PREFIX = '__SIM_COMMAND_PATH' + +const SANDBOX_LIFETIME_LIMIT_ERROR = + 'The sandbox reached the end of its lifetime before this command finished. The workflow timeout may be longer, but this Function call must finish within the sandbox lifetime.' + /** How to reach one sandbox's agent, supplied by the control plane that created the sandbox. */ export interface AgentSandboxConnection { sandboxId: string @@ -73,11 +96,14 @@ export interface AgentSandboxConnection { /** Bound at create, per {@link SandboxHandle.runCode}. Defaults to Python. */ language?: CodeLanguage /** - * Enables session semantics: {@link SandboxHandle.extendLifetime}, {@link SandboxHandle.outlives}, - * and {@link SandboxHandle.verifiesCliAtLaunch}. + * The session this sandbox serves. Present exactly for session sandboxes, and enables session + * semantics: {@link SandboxHandle.extendLifetime}, {@link SandboxHandle.outlives}, + * {@link SandboxHandle.verifiesCliAtLaunch}, and commands that are claimed, settled with their + * whole process tree, and stoppable by `stopSessionProcess` (see + * {@link SandboxAgentClient.stopProcess}), as on E2B. */ - session?: boolean - /** The agent's self-termination deadline when the handle was made. */ + sessionKey?: string + /** The agent's self-termination deadline when the handle was made, by the caller's clock. */ expiresAtMs: number /** * Home directory of the identity code runs as; relative file paths resolve against it, as on @@ -90,7 +116,7 @@ export interface AgentSandboxConnection { type TerminalEvent = Extract -/** The stream ended or broke before a terminal event; the process may still be running. */ +/** The stream ended, broke, or went silent before a terminal event; the process may still run. */ class StreamInterruptedError extends Error { constructor(cause?: unknown) { super('Sandbox agent event stream ended before the process finished', { cause }) @@ -98,29 +124,63 @@ class StreamInterruptedError extends Error { } } -/** Wraps a body so it errors unless exactly `expectedBytes` arrive. */ -function exactLength( +/** Reads the next chunk, failing with `onIdle()` (after cancelling) when none arrives in time. */ +async function readWithin( + reader: ReadableStreamDefaultReader, + idleMs: number, + onIdle: () => Error +): Promise> { + let timer: ReturnType | undefined + const idle = new Promise((_, reject) => { + timer = setTimeout(() => { + void reader.cancel().catch(() => {}) + reject(onIdle()) + }, idleMs) + }) + try { + return await Promise.race([reader.read(), idle]) + } finally { + clearTimeout(timer) + } +} + +/** + * Wraps a file body so it errors unless exactly `expectedBytes` arrive, and when no chunk arrives + * for {@link FILE_STREAM_IDLE_MS}. Cancelling the wrapper cancels the request. + */ +function checkedFileBody( body: ReadableStream, expectedBytes: number ): ReadableStream { + const reader = body.getReader() let received = 0 - return body.pipeThrough( - new TransformStream({ - transform(chunk, controller) { - received += chunk.byteLength - if (received > expectedBytes) { - controller.error(new Error('Sandbox agent sent more bytes than the file held')) - return - } - controller.enqueue(chunk) - }, - flush(controller) { + return new ReadableStream({ + async pull(controller) { + const { value, done } = await readWithin( + reader, + FILE_STREAM_IDLE_MS, + () => new Error('Sandbox agent file read stalled') + ) + if (done) { if (received !== expectedBytes) { controller.error(new Error('Sandbox agent file read was truncated')) + } else { + controller.close() } - }, - }) - ) + return + } + received += value.byteLength + if (received > expectedBytes) { + await reader.cancel() + controller.error(new Error('Sandbox agent sent more bytes than the file held')) + return + } + controller.enqueue(value) + }, + cancel(reason) { + return reader.cancel(reason) + }, + }) } class AgentSandboxHandle implements SandboxHandle { @@ -131,6 +191,7 @@ class AgentSandboxHandle implements SandboxHandle { private readonly client: SandboxAgentClient private readonly language: CodeLanguage private readonly home: string + private readonly sessionKey?: string private deadlineAtMs: number private killPromise: Promise | null = null private killed = false @@ -140,30 +201,39 @@ class AgentSandboxHandle implements SandboxHandle { this.client = new SandboxAgentClient(connection.baseUrl, connection.token) this.language = connection.language ?? CodeLanguage.Python this.home = connection.userHome ?? SANDBOX_AGENT_USER.home + this.sessionKey = connection.sessionKey this.deadlineAtMs = connection.expiresAtMs - this.verifiesCliAtLaunch = connection.session === true - if (connection.session) { + this.verifiesCliAtLaunch = connection.sessionKey !== undefined + if (connection.sessionKey !== undefined) { this.outlives = (lifetimeMs, fromMs) => this.deadlineAtMs >= fromMs + lifetimeMs this.extendLifetime = (lifetimeMs) => this.extendDeadline(lifetimeMs) } } + /** + * Asks for `lifetimeMs` more by duration, never by instant, so the pod's clock need not agree + * with this one. The deadline recorded here counts from before the request was sent, which can + * only underestimate it. + */ private async extendDeadline(lifetimeMs: number): Promise { - const now = Date.now() - if (this.deadlineAtMs >= now + lifetimeMs) return + const sentAtMs = Date.now() + if (this.deadlineAtMs >= sentAtMs + lifetimeMs) return const granted = lifetimeResponseSchema.parse( await this.client.requestJson(SANDBOX_AGENT_ROUTES.lifetime, { method: 'POST', - json: { expiresAtMs: now + lifetimeMs }, + json: { ttlMs: Math.max(1, Math.ceil(lifetimeMs)) }, retry: true, }) ) - this.deadlineAtMs = Math.max(this.deadlineAtMs, granted.expiresAtMs) + this.deadlineAtMs = Math.max(this.deadlineAtMs, sentAtMs + granted.remainingMs) } - /** Absolute paths pass through; relative ones resolve against the user's home, as on E2B. */ + /** + * Relative paths resolve against the user's home and absolute ones are normalized, as E2B + * accepts `..` in an absolute path; the agent refuses any `..` that still reaches it. + */ private resolve(path: string): string { - return path.startsWith('/') ? path : posix.join(this.home, path) + return path.startsWith('/') ? posix.normalize(path) : posix.join(this.home, path) } runCode(code: string, options: CodeRunOptions): Promise { @@ -175,42 +245,82 @@ class AgentSandboxHandle implements SandboxHandle { }, this.language, code, - options + options, + { + name: 'SandboxLifetimeLimitError', + value: SANDBOX_LIFETIME_LIMIT_ERROR, + traceback: SANDBOX_LIFETIME_LIMIT_ERROR, + } + ) + } + + /** What E2B reports when its lifetime cap ends a command: a provider failure, not an exit. */ + private providerLimitResult(): SandboxCommandResult { + return { + stdout: '', + stderr: SANDBOX_LIFETIME_LIMIT_ERROR, + exitCode: 1, + providerFailure: 'provider_limit', + } + } + + /** + * The command's outcome can no longer be observed. Past the sandbox deadline that is its + * lifetime ending; otherwise an at-most-once caller gets an indeterminate failure rather than + * a rerun, and anyone else a plain error. + */ + private outcomeLost( + error: unknown, + started: boolean, + options: RunCommandOptions + ): SandboxCommandResult { + if (Date.now() >= this.deadlineAtMs) return this.providerLimitResult() + if (options.atMostOnce) { + throw new SandboxLaunchIndeterminateError(PROVIDER_LABEL, { cause: error }) + } + throw new Error( + `Lost the sandbox command's ${started ? 'output' : 'start'}: ${getErrorMessage(error)}`, + { cause: error } ) } /** * Launches under a fresh processKey and follows its event stream, reattaching from the last - * sequence number whenever the stream drops. The key makes every start and reattach safe to - * repeat: the agent launches a key at most once, so `atMostOnce` holds through any transport - * failure. When the outcome can no longer be observed, an `atMostOnce` command fails with - * {@link SandboxLaunchIndeterminateError} rather than being run again. + * sequence number whenever the stream drops or goes silent. The key makes every start and + * reattach safe to repeat (the agent launches a key at most once), so `atMostOnce` holds + * through any transport failure. A session command is claimed before launch and settled (or + * reported unsettled) after, exactly as E2B's session commands are, and the agent kills its + * whole process tree before reporting its exit. */ async runCommand(command: string, options: RunCommandOptions): Promise { options.signal?.throwIfAborted() + assertSafeProcessEnvironment(options.envs) + const prepared = preserveLoginShellPath(command, options.envs, PATH_ALIAS_PREFIX) const processKey = generateId() - const maxOutputBytes = options.maxOutputBytes ?? MAX_SANDBOX_PROCESS_OUTPUT_BYTES - const timeoutMs = Math.max( - 1, - Math.min(Math.ceil(options.timeoutMs), SANDBOX_AGENT_MAX_TIMEOUT_MS) + const outputLimit = Math.min( + options.maxOutputBytes ?? MAX_SANDBOX_PROCESS_OUTPUT_BYTES, + SANDBOX_AGENT_MAX_OUTPUT_BYTES ) const request: StartProcessRequest = { processKey, - shell: command, - envs: options.envs ?? {}, + shell: prepared.command, + envs: prepared.envs ?? {}, user: options.rootUser ? 'root' : 'user', - timeoutMs, - maxOutputBytes: Math.min(maxOutputBytes, SANDBOX_AGENT_MAX_OUTPUT_BYTES), + timeoutMs: Math.max(1, Math.min(Math.ceil(options.timeoutMs), SANDBOX_AGENT_MAX_TIMEOUT_MS)), + maxOutputBytes: outputLimit, ...(options.verifyCli ? { verifyCli: options.verifyCli } : {}), + ...(this.sessionKey !== undefined ? { reapDescendants: true } : {}), } - const budget = new SandboxProcessOutputBudget(maxOutputBytes) + const budget = new SandboxProcessOutputBudget(outputLimit) const retainStdout = options.onStdout === undefined const retainStderr = options.onStderr === undefined let stdout = '' let stderr = '' let lastSeq = -1 let started = false + /** True once the agent has reported this command finished (or its stop confirmed it). */ + let settled = false const collected = () => ({ stdout: retainStdout ? stdout : tailStreamedSandboxOutput(stdout), @@ -260,26 +370,52 @@ class AgentSandboxHandle implements SandboxHandle { } } + /** Follows one response; protocol violations fail fast rather than being retried. */ const follow = async (response: Response): Promise => { if (!response.body) throw new StreamInterruptedError() + const reader = response.body.getReader() const decoder = new NdjsonDecoder() try { - for await (const chunk of response.body) { - for (const value of decoder.push(chunk)) { - const terminal = apply(processEventSchema.parse(value)) - if (terminal) return terminal + while (true) { + const { value, done } = await readWithin( + reader, + STREAM_IDLE_MS, + () => new StreamInterruptedError(new Error('No heartbeat from the sandbox agent')) + ) + if (done) break + for (const raw of decoder.push(value)) { + const terminal = apply(processEventSchema.parse(raw)) + if (terminal) { + await reader.cancel().catch(() => {}) + return terminal + } } } decoder.finish() } catch (error) { - if (error instanceof SandboxOutputLimitError) throw error + if ( + error instanceof SandboxOutputLimitError || + error instanceof StreamInterruptedError || + error instanceof ZodError || + error instanceof NdjsonDecodeError + ) { + throw error + } throw new StreamInterruptedError(error) } throw new StreamInterruptedError() } + const recorded = this.sessionKey !== undefined + if (this.sessionKey !== undefined) { + await recordSandboxProcess({ + id: processKey, + sandboxId: this.sandboxId, + sessionKey: this.sessionKey, + }) + } try { - let terminal: TerminalEvent | undefined + options.signal?.throwIfAborted() let response: Response try { response = await this.client.request(SANDBOX_AGENT_ROUTES.processes, { @@ -291,23 +427,38 @@ class AgentSandboxHandle implements SandboxHandle { }) } catch (error) { options.signal?.throwIfAborted() - if (error instanceof SandboxAgentRequestError) throw error - if (options.atMostOnce) - throw new SandboxLaunchIndeterminateError(PROVIDER_LABEL, { cause: error }) - throw error + // A protocol refusal ran nothing; an unrecognized error status says nothing either way. + if (error instanceof SandboxAgentRequestError && error.code !== 'unknown') { + settled = true + throw error + } + return this.outcomeLost(error, false, options) } - for (let reconnects = 0; terminal === undefined; reconnects++) { + let terminal: TerminalEvent | undefined + let fruitlessReattaches = 0 + while (terminal === undefined) { + const seqBefore = lastSeq try { terminal = await follow(response) } catch (error) { + if (error instanceof ZodError || error instanceof NdjsonDecodeError) { + return this.outcomeLost(error, started, options) + } if (!(error instanceof StreamInterruptedError) || options.signal?.aborted) throw error - if (reconnects >= MAX_STREAM_RECONNECTS) throw this.unobservable(error, started, options) + fruitlessReattaches = lastSeq > seqBefore ? 1 : fruitlessReattaches + 1 + if (fruitlessReattaches > MAX_STREAM_REATTACHES) { + return this.outcomeLost(error, started, options) + } logger.warn('Sandbox agent event stream dropped; reattaching to the same process', { sandboxId: this.sandboxId, processKey, lastSeq, }) + await abortableSleep( + backoffWithJitter(fruitlessReattaches, null, REATTACH_BACKOFF), + options.signal + ) try { response = await this.client.request(sandboxAgentProcessEventsPath(processKey), { query: { from: String(lastSeq + 1) }, @@ -317,10 +468,11 @@ class AgentSandboxHandle implements SandboxHandle { }) } catch (reattachError) { options.signal?.throwIfAborted() - throw this.unobservable(reattachError, started, options) + return this.outcomeLost(reattachError, started, options) } } } + settled = true if (terminal.type === 'rejected') { if (terminal.reason === 'cli_stale') throw new SessionCliStaleError() @@ -330,20 +482,25 @@ class AgentSandboxHandle implements SandboxHandle { `Sandbox command did not start (${terminal.reason})${terminal.message ? `: ${terminal.message}` : ''}` ) } + if (terminal.lifetimeExpired) return this.providerLimitResult() if (terminal.outputLimitExceeded) { - throw new SandboxOutputLimitError(maxOutputBytes + 1, maxOutputBytes, 'process') + throw new SandboxOutputLimitError(outputLimit + 1, outputLimit, 'process') } if (terminal.timedOut) return timedOutResult() return { ...collected(), exitCode: terminal.exitCode } } catch (error) { - if (budget.error || options.signal?.aborted) { - await this.stopProcess(processKey, lastSeq) + if (!settled && (budget.error || options.signal?.aborted)) { + settled = await this.client.stopProcess( + processKey, + lastSeq + 1, + AbortSignal.timeout(CANCEL_SETTLE_MS) + ) } if (budget.error) throw budget.error if (options.signal?.aborted) { // A session caller's own deadline can stop the command before the agent's timeout does, // as on E2B; a Stop stays a cancellation. - if (this.connection.session && isTimeoutAbortReason(options.signal.reason)) { + if (this.sessionKey !== undefined && isTimeoutAbortReason(options.signal.reason)) { return timedOutResult() } throw options.signal.reason @@ -351,42 +508,28 @@ class AgentSandboxHandle implements SandboxHandle { throw error } finally { options.signal?.removeEventListener('abort', onAbort) + if (recorded) await this.settleSessionCommand(processKey, settled, lastSeq + 1) } } - /** The process's outcome can no longer be observed; an at-most-once caller must not rerun it. */ - private unobservable(error: unknown, started: boolean, options: RunCommandOptions): Error { - if (options.atMostOnce) - return new SandboxLaunchIndeterminateError(PROVIDER_LABEL, { cause: error }) - return new Error( - `Lost the sandbox command's ${started ? 'output' : 'start'}: ${getErrorMessage(error)}`, - { cause: error } - ) - } - - /** Kills a command's process group (or cancels its pending launch) and waits briefly for its exit. */ - private async stopProcess(processKey: string, lastSeq: number): Promise { - const signal = AbortSignal.timeout(CANCEL_SETTLE_MS) - try { - await this.client.request(sandboxAgentProcessSignalPath(processKey), { - method: 'POST', - json: { signal: 'SIGKILL' }, - signal, - retry: true, - }) - const response = await this.client.request(sandboxAgentProcessEventsPath(processKey), { - query: { from: String(lastSeq + 1) }, - signal, - timeout: false, - }) - await response.body?.pipeTo(new WritableStream()) - } catch (error) { - logger.warn('Could not confirm a cancelled sandbox command stopped', { - sandboxId: this.sandboxId, - processKey, - error: getErrorMessage(error), - }) + /** + * Settles a claimed session command, as E2B's do: one the agent has not reported finished is + * stopped first, and one whose exit cannot be confirmed is reported unsettled and fails the + * call, since its process tree may still hold the workbench. + */ + private async settleSessionCommand( + processKey: string, + settled: boolean, + fromSeq: number + ): Promise { + const confirmed = + settled || + (await this.client.stopProcess(processKey, fromSeq, AbortSignal.timeout(CANCEL_SETTLE_MS))) + if (!confirmed) { + reportUnsettledSandboxProcess(processKey) + throw new Error('Sandbox command exit is unconfirmed') } + await settleSandboxProcess(processKey) } async getFileSize(path: string): Promise { @@ -434,9 +577,10 @@ class AgentSandboxHandle implements SandboxHandle { } const declared = Number(response.headers.get(SANDBOX_AGENT_FILE_SIZE_HEADER)) if (!response.body || !Number.isSafeInteger(declared) || declared < 0) { + await response.body?.cancel() throw new Error('Sandbox agent file read is missing its size') } - return exactLength(response.body, declared) + return checkedFileBody(response.body, declared) } async readFileStream( @@ -476,12 +620,13 @@ class AgentSandboxHandle implements SandboxHandle { } async writeFile(path: string, content: string | ArrayBuffer): Promise { - await this.client.request(SANDBOX_AGENT_ROUTES.files, { + const response = await this.client.request(SANDBOX_AGENT_ROUTES.files, { method: 'PUT', query: { path: this.resolve(path) }, body: content, retry: true, }) + await response.body?.cancel() } async writeFileStream( @@ -490,35 +635,37 @@ class AgentSandboxHandle implements SandboxHandle { options: { signal: AbortSignal } ): Promise { options.signal.throwIfAborted() - await this.client.request(SANDBOX_AGENT_ROUTES.files, { + const response = await this.client.request(SANDBOX_AGENT_ROUTES.files, { method: 'PUT', query: { path: this.resolve(path) }, body: content, signal: options.signal, timeout: false, }) + await response.body?.cancel() options.signal.throwIfAborted() } async removeFile(path: string): Promise { - await this.client.request(SANDBOX_AGENT_ROUTES.files, { + const response = await this.client.request(SANDBOX_AGENT_ROUTES.files, { method: 'DELETE', query: { path: this.resolve(path) }, retry: true, }) + await response.body?.cancel() } async listFiles(path: string, options?: { depth?: number }): Promise { + const directory = this.resolve(path) const listing = listFilesResponseSchema.parse( await this.client.requestJson(SANDBOX_AGENT_ROUTES.fileList, { query: { - path: this.resolve(path), + path: directory, ...(options?.depth !== undefined ? { depth: String(options.depth) } : {}), }, retry: true, }) ) - const directory = this.resolve(path) const entries: SandboxDirectoryEntry[] = [] for (const entry of listing.entries) { const resolved = resolveSandboxDirectoryEntryPath(directory, entry.path) @@ -545,10 +692,11 @@ class AgentSandboxHandle implements SandboxHandle { /** * A {@link SandboxHandle} over `sim-sandbox-agent`'s protocol, independent of the control plane * that created the sandbox. `runCode` runs exactly as the E2B adapter's does (the same files, - * preload, and failure parsing, via {@link runCodeAsProcess}); commands and file operations go to - * the agent over HTTP. File streaming is always available, as workbench uploads require. Every - * file operation uses the agent's default `user` identity, as E2B's files API acts as the sandbox - * user: the agent runs it in its unprivileged file worker, so the kernel's permission checks apply. + * preload, and failure parsing, via {@link runCodeAsProcess}); commands run in a login shell + * with E2B's PATH handling; file operations go to the agent over HTTP. File streaming is always + * available, as workbench uploads require. Every file operation uses the agent's default `user` + * identity, as E2B's files API acts as the sandbox user: the agent runs it in its unprivileged + * file worker, so the kernel's permission checks apply. */ export function createAgentSandboxHandle( connection: AgentSandboxConnection diff --git a/apps/sim/lib/execution/remote-sandbox/code-process.ts b/apps/sim/lib/execution/remote-sandbox/code-process.ts index 43634ff426c..41c346b581a 100644 --- a/apps/sim/lib/execution/remote-sandbox/code-process.ts +++ b/apps/sim/lib/execution/remote-sandbox/code-process.ts @@ -13,7 +13,7 @@ import type { export type CodeRunOptions = Parameters[1] /** The three sandbox operations a code run needs, supplied by the provider adapter. */ -export interface CodeProcessIo { +interface CodeProcessIo { /** Writes a file at a path relative to the sandbox user's home, the command's working directory. */ writeFile(path: string, content: string): Promise removeFile(path: string): Promise diff --git a/knip.jsonc b/knip.jsonc index 159b2dc5cb1..3eac2e454e4 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -40,10 +40,7 @@ // Compile-time fixture compatibility assertion, included by tsconfig. "lib/table/fixture-contract.ts", // scripts/generate-docs.ts imports this through pathToFileURL. - "app/(landing)/integrations/data/landing-content.ts", - // Sandbox-agent handle consumed only by the stacked Kubernetes sandbox provider. Remove - // this entry once that provider imports it. - "lib/execution/remote-sandbox/agent/handle.ts" + "app/(landing)/integrations/data/landing-content.ts" ], // Required/discoverable barrels whose children have direct live imports. // Ignore only the barrel file finding, so it cannot keep dead children alive. From 862e54f11c1df955b4b0827e6ce7545f685d1e85 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:13:45 -0600 Subject: [PATCH 22/78] feat(sandbox): add the Kubernetes sandbox provider SANDBOX_PROVIDER=kubernetes runs each sandbox as a pod in SANDBOX_K8S_NAMESPACE and reaches it over sim-sandbox-agent's HTTP API. Nothing loads or runs unless that provider is selected; E2B and Daytona are unchanged. - Pod spec: the configured RuntimeClass, no service-account token or Service env, no host namespaces, shareProcessNamespace, restartPolicy Never, activeDeadlineSeconds at the 24-hour cap, the agent injected by an init container into a volume the sandbox mounts read-only, all capabilities dropped but CHOWN/DAC_OVERRIDE/FOWNER/SETUID/SETGID/KILL, RuntimeDefault seccomp, limits with requests at half, and size-capped emptyDirs for /tmp, /home/user and /opt/sim-deps. - Isolation guard: the RuntimeClass is read once per provider instance; a missing class or a runc/crun/empty handler is refused unless SANDBOX_K8S_ALLOW_UNISOLATED=true. - Create: watch the pod to Running, then poll the agent's /healthz, bounded by a create deadline. Quota exhaustion and API throttling map to a capacity error; RBAC, Pod Security and image-pull failures map to configuration errors naming the env var and the docs page. A retried create reuses its pod name so a 409 adopts our own pod. - Tokens: HKDF-SHA256 of INTERNAL_API_SECRET salted with the pod name; the pod holds only the digest, so any replica can reconnect. - Sessions: lookup by session label, oldest live and unexpired pod first; lifetime extensions are capped at the pod deadline and written to sim.ai/expires-at before the agent is asked. Session commands stop through the agent's signal endpoint. - Reaper: SandboxProvider.reapExpiredSandboxes deletes finished pods and pods past sim.ai/expires-at plus a grace period. Registration: provider id, capability and kind table, env vars, setup wizard, operator-paid pricing, 24-hour Pi lifetime ceiling, Trigger env sync, and the ESM-only client kept external for Next and Trigger. Managed CLI recipes do not opt Kubernetes in yet. --- apps/sim/lib/billing/sandbox-pricing.ts | 1 + apps/sim/lib/core/config/env.ts | 18 +- .../remote-sandbox/kubernetes/cluster.ts | 278 ++++++++ .../remote-sandbox/kubernetes/errors.ts | 128 ++++ .../remote-sandbox/kubernetes/handle.ts | 132 ++++ .../kubernetes/images.generated.json | 2 +- .../remote-sandbox/kubernetes/isolation.ts | 91 +++ .../remote-sandbox/kubernetes/pod.test.ts | 237 +++++++ .../remote-sandbox/kubernetes/pod.ts | 213 ++++++ .../kubernetes/provider.test.ts | 617 ++++++++++++++++++ .../remote-sandbox/kubernetes/provider.ts | 487 ++++++++++++++ .../remote-sandbox/kubernetes/reaper.ts | 66 ++ .../remote-sandbox/kubernetes/settings.ts | 238 +++++++ .../remote-sandbox/kubernetes/token.ts | 29 + .../execution/remote-sandbox/pi-lifetime.ts | 2 + .../lib/execution/remote-sandbox/provider.ts | 2 + .../sim/lib/execution/remote-sandbox/types.ts | 14 + apps/sim/next.config.ts | 1 + apps/sim/package.json | 1 + apps/sim/trigger.config.ts | 15 + bun.lock | 53 ++ .../deployment-config/src/env-capabilities.ts | 47 +- packages/sim-setup/src/capability-config.ts | 100 +++ packages/utils/src/sandbox-references.ts | 2 +- 24 files changed, 2770 insertions(+), 4 deletions(-) create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/cluster.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/errors.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/handle.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/isolation.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/pod.test.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/provider.test.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/provider.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/reaper.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/settings.ts create mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/token.ts diff --git a/apps/sim/lib/billing/sandbox-pricing.ts b/apps/sim/lib/billing/sandbox-pricing.ts index bebea399724..9580e66a8eb 100644 --- a/apps/sim/lib/billing/sandbox-pricing.ts +++ b/apps/sim/lib/billing/sandbox-pricing.ts @@ -96,6 +96,7 @@ const PRICING_BY_PROVIDER: Record(operation: string, call: () => Promise, retry: boolean): Promise { + for (let attempt = 1; ; attempt++) { + try { + return await call() + } catch (error) { + const failure = describeKubernetesApiFailure(error) + if (!retry || attempt >= MAX_ATTEMPTS || !isRetryableKubernetesFailure(failure)) { + throw new KubernetesApiError(operation, failure, { cause: error }) + } + logger.warn('Kubernetes API request failed; retrying', { + operation, + attempt, + status: failure.status, + }) + await sleep( + backoffWithJitter(attempt, parseRetryAfter(failure.retryAfter ?? null), RETRY_BACKOFF) + ) + } + } +} + +/** + * The cluster operations the sandbox provider performs, scoped to one namespace. Every method + * maps to one API verb the sandbox Role grants: pods create/get/list/watch/delete/patch, plus + * runtimeclasses get. + */ +export interface SandboxCluster { + readonly namespace: string + /** The RuntimeClass's handler, or null when no such RuntimeClass exists. */ + readRuntimeClassHandler(name: string): Promise + /** Creates the pod once, without retrying; the caller decides what a failure means. */ + createPod(pod: V1Pod): Promise + /** Null when the pod does not exist. */ + readPod(name: string): Promise + /** Every pod matching the label selector, across pages. */ + listPods(labelSelector: string): Promise + /** + * Streams the pod's updates from `resourceVersion` until `onUpdate` returns true, the watch + * ends (resolving false), or `signal` aborts. + */ + watchPod( + name: string, + resourceVersion: string | undefined, + onUpdate: (pod: V1Pod) => boolean, + signal: AbortSignal + ): Promise + setExpiresAt(name: string, expiresAtMs: number): Promise + /** Resolves when the pod is gone or was never there. */ + deletePod(name: string): Promise +} + +class ClientSandboxCluster implements SandboxCluster { + constructor( + readonly namespace: string, + private readonly core: CoreV1Api, + private readonly node: NodeV1Api, + private readonly watcher: Watch, + private readonly mergePatch: Awaited> + ) {} + + async readRuntimeClassHandler(name: string): Promise { + try { + const runtimeClass = await callApi( + 'RuntimeClass read', + () => this.node.readRuntimeClass({ name }), + true + ) + return runtimeClass.handler + } catch (error) { + if (isKubernetesStatus(error, 404)) return null + throw error + } + } + + createPod(pod: V1Pod): Promise { + return callApi( + 'pod create', + () => this.core.createNamespacedPod({ namespace: this.namespace, body: pod }), + false + ) + } + + async readPod(name: string): Promise { + try { + return await callApi( + 'pod read', + () => this.core.readNamespacedPod({ name, namespace: this.namespace }), + true + ) + } catch (error) { + if (isKubernetesStatus(error, 404)) return null + throw error + } + } + + async listPods(labelSelector: string): Promise { + const pods: V1Pod[] = [] + let continueToken: string | undefined + do { + const page = await callApi( + 'pod list', + () => + this.core.listNamespacedPod({ + namespace: this.namespace, + labelSelector, + limit: LIST_PAGE_SIZE, + ...(continueToken ? { _continue: continueToken } : {}), + }), + true + ) + pods.push(...page.items) + continueToken = page.metadata?._continue || undefined + } while (continueToken) + return pods + } + + async watchPod( + name: string, + resourceVersion: string | undefined, + onUpdate: (pod: V1Pod) => boolean, + signal: AbortSignal + ): Promise { + signal.throwIfAborted() + let settled = false + let finish: (matched: boolean) => void = () => {} + let fail: (error: unknown) => void = () => {} + const outcome = new Promise((resolve, reject) => { + finish = (matched) => { + settled = true + resolve(matched) + } + fail = (error) => { + settled = true + reject(error) + } + }) + // Observed by the `await` below; this only keeps an abort during connect from reporting as + // an unhandled rejection before that. + outcome.catch(() => {}) + let controller: AbortController | undefined + const onAbort = () => { + controller?.abort() + fail(signal.reason) + } + signal.addEventListener('abort', onAbort, { once: true }) + try { + controller = await this.watcher.watch( + `/api/v1/namespaces/${encodeURIComponent(this.namespace)}/pods`, + { + fieldSelector: `metadata.name=${name}`, + timeoutSeconds: WATCH_TIMEOUT_SECONDS, + ...(resourceVersion ? { resourceVersion } : {}), + }, + (type: string, object: V1Pod) => { + if (settled || (type !== 'ADDED' && type !== 'MODIFIED')) return + if (onUpdate(object)) finish(true) + }, + (error: unknown) => { + if (settled) return + // A watch that times out, is closed by the server, or expired its resourceVersion (410) + // just ends; the caller re-reads the pod and watches again. + if (error) logger.debug('Sandbox pod watch ended', { name, error: String(error) }) + finish(false) + } + ) + return await outcome + } finally { + signal.removeEventListener('abort', onAbort) + controller?.abort() + } + } + + async setExpiresAt(name: string, expiresAtMs: number): Promise { + await callApi( + 'pod patch', + () => + this.core.patchNamespacedPod( + { + name, + namespace: this.namespace, + body: { metadata: { annotations: { [EXPIRES_AT_ANNOTATION]: String(expiresAtMs) } } }, + }, + this.mergePatch + ), + true + ) + } + + async deletePod(name: string): Promise { + try { + await callApi( + 'pod delete', + () => + this.core.deleteNamespacedPod({ + name, + namespace: this.namespace, + gracePeriodSeconds: 0, + }), + true + ) + } catch (error) { + if (isKubernetesStatus(error, 404)) return + throw error + } + } +} + +async function loadPatchOptions() { + const { PatchStrategy, setHeaderOptions } = await import('@kubernetes/client-node') + return setHeaderOptions('Content-Type', PatchStrategy.MergePatch) +} + +/** + * Loads cluster credentials the standard way: `KUBECONFIG` (or `~/.kube/config`) when present, + * otherwise the pod's in-cluster service account. + */ +export async function loadDefaultKubeConfig(): Promise { + const { KubeConfig } = await import('@kubernetes/client-node') + const config = new KubeConfig() + config.loadFromDefault() + return config +} + +/** Opens the cluster operations for one namespace. The client is ESM-only and loaded on demand. */ +export async function openSandboxCluster( + config: KubeConfig, + namespace: string +): Promise { + const { CoreV1Api, NodeV1Api, Watch } = await import('@kubernetes/client-node') + return new ClientSandboxCluster( + namespace, + config.makeApiClient(CoreV1Api), + config.makeApiClient(NodeV1Api), + new Watch(config), + await loadPatchOptions() + ) +} diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.ts new file mode 100644 index 00000000000..cd0431c3256 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/errors.ts @@ -0,0 +1,128 @@ +import { getErrorMessage } from '@sim/utils/errors' +import { isRecordLike, toRecord } from '@sim/utils/object' +import { NonRetryableExecutionError } from '@/lib/execution/non-retryable-error' + +/** Operator documentation for the Kubernetes sandbox provider, named in every configuration error. */ +const KUBERNETES_SANDBOX_DOCS_URL = + 'https://docs.sim.ai/platform/self-hosting/sandboxes#kubernetes-no-third-party' + +/** + * The deployment is configured in a way no retry can fix: an unset or non-isolating RuntimeClass, + * an unset image, missing RBAC, or a namespace that rejects the pod. The message names what to + * change and where it is documented. + */ +export class KubernetesSandboxConfigError extends NonRetryableExecutionError { + constructor(message: string, options?: ErrorOptions) { + super(`${message} See ${KUBERNETES_SANDBOX_DOCS_URL}`, options) + this.name = 'KubernetesSandboxConfigError' + } +} + +/** + * The cluster has no room for another sandbox right now: the namespace's ResourceQuota is spent, + * the API server is throttling, or no node could run the pod before the create deadline. Unlike a + * configuration error, a later attempt may succeed. + */ +export class KubernetesSandboxCapacityError extends Error { + constructor(message: string, options?: ErrorOptions) { + super(message, options) + this.name = 'KubernetesSandboxCapacityError' + } +} + +/** The fields Sim reads from a failed Kubernetes API call. */ +export interface KubernetesApiFailure { + /** HTTP status, or undefined when no response arrived. */ + status?: number + /** `Status.reason` from the response body, such as `AlreadyExists` or `Forbidden`. */ + reason?: string + /** `Status.message` from the response body. */ + message: string + /** `Retry-After` response header, when the API server sent one. */ + retryAfter?: string +} + +function parseStatusBody(body: unknown): { reason?: string; message?: string } { + let parsed: unknown = body + if (typeof body === 'string') { + try { + parsed = JSON.parse(body) + } catch { + return { message: body.slice(0, 500) } + } + } + if (!isRecordLike(parsed)) return {} + return { + ...(typeof parsed.reason === 'string' ? { reason: parsed.reason } : {}), + ...(typeof parsed.message === 'string' ? { message: parsed.message } : {}), + } +} + +/** + * Reads an `ApiException` from `@kubernetes/client-node` without its default message, which + * embeds the full response headers and body. + */ +export function describeKubernetesApiFailure(error: unknown): KubernetesApiFailure { + if (!isRecordLike(error) || typeof error.code !== 'number') { + return { message: getErrorMessage(error) } + } + const status = parseStatusBody(error.body) + const retryAfter = toRecord(error.headers)['retry-after'] + return { + status: error.code, + ...(status.reason ? { reason: status.reason } : {}), + message: status.message ?? `Kubernetes API request failed (${error.code})`, + ...(typeof retryAfter === 'string' ? { retryAfter } : {}), + } +} + +/** True for a failed API call that a short, bounded retry may get past. */ +export function isRetryableKubernetesFailure(failure: KubernetesApiFailure): boolean { + return ( + failure.status === undefined || + failure.status === 429 || + failure.status === 500 || + failure.status === 502 || + failure.status === 503 || + failure.status === 504 + ) +} + +/** + * Turns a failed pod create into the error the caller and the operator act on. Quota exhaustion + * and throttling are capacity, an admission or RBAC refusal is configuration, and anything else + * keeps the API server's own message. + */ +export function toPodCreateError(failure: KubernetesApiFailure, namespace: string): Error { + if (failure.status === 403 && /exceeded quota/i.test(failure.message)) { + return new KubernetesSandboxCapacityError( + `The Kubernetes sandbox namespace "${namespace}" has reached its ResourceQuota, so no new sandbox can start until running ones finish. Raise the quota or lower concurrent sandbox use. Cluster detail: ${failure.message}` + ) + } + if (failure.status === 429) { + return new KubernetesSandboxCapacityError( + 'The Kubernetes API server is throttling sandbox creation; retry shortly.' + ) + } + if (failure.status === 403 && /violates PodSecurity/i.test(failure.message)) { + return new KubernetesSandboxConfigError( + `The namespace "${namespace}" (SANDBOX_K8S_NAMESPACE) rejects sandbox pods under its Pod Security level. Sandbox pods run their agent as root inside the isolated runtime, so label the namespace pod-security.kubernetes.io/enforce=baseline. Cluster detail: ${failure.message}` + ) + } + if (failure.status === 403) { + return new KubernetesSandboxConfigError( + `Sim's service account may not create pods in namespace "${namespace}" (SANDBOX_K8S_NAMESPACE). Grant it the sandbox Role. Cluster detail: ${failure.message}` + ) + } + if (failure.status === 404) { + return new KubernetesSandboxConfigError( + `The sandbox namespace "${namespace}" does not exist. Create it or set SANDBOX_K8S_NAMESPACE.` + ) + } + if (failure.status === 400 || failure.status === 422) { + return new KubernetesSandboxConfigError( + `The cluster rejected the sandbox pod spec; check SANDBOX_K8S_NODE_SELECTOR, SANDBOX_K8S_TOLERATIONS, and the SANDBOX_K8S_* resource settings. Cluster detail: ${failure.message}` + ) + } + return new Error(`Kubernetes sandbox create failed: ${failure.message}`) +} diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/handle.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/handle.ts new file mode 100644 index 00000000000..78a01372de9 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/handle.ts @@ -0,0 +1,132 @@ +import type { createAgentSandboxHandle } from '@/lib/execution/remote-sandbox/agent/handle' +import type { SandboxCluster } from '@/lib/execution/remote-sandbox/kubernetes/cluster' +import type { + RunCommandOptions, + SandboxCodeResult, + SandboxCommandResult, + SandboxDirectoryEntry, + SandboxHandle, +} from '@/lib/execution/remote-sandbox/types' + +type AgentHandle = ReturnType + +/** The pod a handle runs in, as the control plane last recorded it. */ +interface SandboxPodLease { + name: string + /** The pod's `sim.ai/expires-at`. */ + expiresAtMs: number + /** When `activeDeadlineSeconds` ends the pod, whatever the agent's deadline says. */ + hardDeadlineMs: number +} + +/** + * The agent handle for one sandbox pod, with lifetime extension bound to the pod. An extension is + * capped at the pod's hard deadline (Kubernetes ends the pod there regardless), and recorded in + * the pod's `sim.ai/expires-at` before the agent is asked for it, so the reaper, which reads only + * the annotation, never deletes a pod whose agent was told to stay up. Both deadlines are measured + * on Sim's clock, so a skewed node clock cannot shorten one. + */ +class KubernetesSandboxHandle implements SandboxHandle { + readonly sandboxId: string + readonly verifiesCliAtLaunch?: boolean + readonly extendLifetime?: (lifetimeMs: number) => Promise + readonly outlives?: (lifetimeMs: number, fromMs: number) => boolean + private annotatedAtMs: number + + constructor( + private readonly agent: AgentHandle, + private readonly lease: SandboxPodLease, + private readonly cluster: SandboxCluster + ) { + this.sandboxId = agent.sandboxId + this.annotatedAtMs = lease.expiresAtMs + if (agent.verifiesCliAtLaunch !== undefined) + this.verifiesCliAtLaunch = agent.verifiesCliAtLaunch + const { outlives, extendLifetime } = agent + if (outlives && extendLifetime) { + this.outlives = (lifetimeMs, fromMs) => outlives.call(agent, lifetimeMs, fromMs) + this.extendLifetime = (lifetimeMs) => this.extend(lifetimeMs, extendLifetime.bind(agent)) + } + } + + private async extend( + lifetimeMs: number, + extendAgent: (lifetimeMs: number) => Promise + ): Promise { + const now = Date.now() + const grantedMs = Math.min(lifetimeMs, this.lease.hardDeadlineMs - now) + if (grantedMs <= 0) return + const expiresAtMs = now + grantedMs + if (expiresAtMs > this.annotatedAtMs) { + await this.cluster.setExpiresAt(this.lease.name, expiresAtMs) + this.annotatedAtMs = expiresAtMs + } + await extendAgent(grantedMs) + } + + runCode( + code: string, + options: Parameters[1] + ): Promise { + return this.agent.runCode(code, options) + } + + runCommand(command: string, options: RunCommandOptions): Promise { + return this.agent.runCommand(command, options) + } + + getFileSize(path: string): Promise { + return this.agent.getFileSize(path) + } + + readFile(path: string): Promise { + return this.agent.readFile(path) + } + + readFileStream( + path: string, + options: { signal: AbortSignal } + ): Promise> { + return this.agent.readFileStream(path, options) + } + + readFileWithLimit( + path: string, + options: { maxBytes: number; encoding: 'utf8' | 'base64'; signal?: AbortSignal } + ): Promise<{ content: string; byteLength: number }> { + return this.agent.readFileWithLimit(path, options) + } + + writeFile(path: string, content: string | ArrayBuffer): Promise { + return this.agent.writeFile(path, content) + } + + writeFileStream( + path: string, + content: ReadableStream, + options: { signal: AbortSignal } + ): Promise { + return this.agent.writeFileStream(path, content, options) + } + + removeFile(path: string): Promise { + return this.agent.removeFile(path) + } + + listFiles(path: string, options?: { depth?: number }): Promise { + return this.agent.listFiles(path, options) + } + + kill(): Promise { + return this.agent.kill() + } +} + +/** Binds an agent handle to the pod it runs in; see {@link KubernetesSandboxHandle}. */ +export function bindSandboxPod( + agent: AgentHandle, + lease: SandboxPodLease, + cluster: SandboxCluster +): SandboxHandle { + return new KubernetesSandboxHandle(agent, lease, cluster) +} diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json b/apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json index ee2cf830032..cdd551e7ddf 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json @@ -1,5 +1,5 @@ { "function": "ghcr.io/simstudioai/sandbox-function:6d7f249fa417b147", "pi": "ghcr.io/simstudioai/sandbox-pi:01cb06a1b2c01cad", - "agent": "ghcr.io/simstudioai/sandbox-agent:f78259477207d674" + "agent": "ghcr.io/simstudioai/sandbox-agent:2b732c77b0bdec04" } diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/isolation.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/isolation.ts new file mode 100644 index 00000000000..e9343d43817 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/isolation.ts @@ -0,0 +1,91 @@ +import { createLogger } from '@sim/logger' +import { + isKubernetesStatus, + type SandboxCluster, +} from '@/lib/execution/remote-sandbox/kubernetes/cluster' +import { KubernetesSandboxConfigError } from '@/lib/execution/remote-sandbox/kubernetes/errors' +import type { KubernetesSandboxSettings } from '@/lib/execution/remote-sandbox/kubernetes/settings' + +const logger = createLogger('KubernetesSandboxIsolation') + +/** OCI runtimes that run containers on the node's own kernel. */ +const SHARED_KERNEL_HANDLERS = new Set(['', 'runc', 'crun']) + +/** + * How long a refusal is remembered before the RuntimeClass is read again, so a burst of creates + * against a misconfigured cluster costs one read rather than one each, yet fixing the cluster + * takes effect without a restart. + */ +const REFUSAL_TTL_MS = 30_000 + +/** + * Decides once per provider instance whether sandboxes may run, from the configured RuntimeClass. + * Untrusted code runs as root in the sandbox, so the pod's runtime must be the isolation boundary: + * a RuntimeClass that is missing, or whose handler is a shared-kernel runtime, is refused unless + * the operator set `SANDBOX_K8S_ALLOW_UNISOLATED=true`. A passing verdict is kept for the life of + * the instance; a refusal is kept for {@link REFUSAL_TTL_MS}. + */ +export class IsolationGuard { + private verdict: Promise | null = null + private refusedAtMs = 0 + + constructor(private readonly cluster: SandboxCluster) {} + + assertIsolated(settings: KubernetesSandboxSettings): Promise { + if ( + this.verdict && + (this.refusedAtMs === 0 || Date.now() - this.refusedAtMs < REFUSAL_TTL_MS) + ) { + return this.verdict + } + this.refusedAtMs = 0 + const verdict = this.check(settings) + this.verdict = verdict + verdict.catch((error: unknown) => { + if (this.verdict !== verdict) return + // A refusal is the cluster's answer; a failed read is not, so the next create asks again. + if (error instanceof KubernetesSandboxConfigError) this.refusedAtMs = Date.now() + else this.verdict = null + }) + return verdict + } + + private async check(settings: KubernetesSandboxSettings): Promise { + const { runtimeClassName, allowUnisolated } = settings + if (allowUnisolated) { + logger.warn( + 'SANDBOX_K8S_ALLOW_UNISOLATED is set: sandbox pods share the node kernel with untrusted code', + { runtimeClassName: runtimeClassName ?? null } + ) + return + } + if (!runtimeClassName) { + throw new KubernetesSandboxConfigError( + 'Kubernetes sandboxes need an isolating RuntimeClass: set SANDBOX_K8S_RUNTIME_CLASS, or set SANDBOX_K8S_ALLOW_UNISOLATED=true to accept a shared kernel.' + ) + } + let handler: string | null + try { + handler = await this.cluster.readRuntimeClassHandler(runtimeClassName) + } catch (error) { + if (isKubernetesStatus(error, 403)) { + throw new KubernetesSandboxConfigError( + `Sim's service account may not read RuntimeClass "${runtimeClassName}". Grant it get on runtimeclasses (a ClusterRole), so the isolation of SANDBOX_K8S_RUNTIME_CLASS can be verified.`, + { cause: error } + ) + } + throw error + } + if (handler === null) { + throw new KubernetesSandboxConfigError( + `RuntimeClass "${runtimeClassName}" (SANDBOX_K8S_RUNTIME_CLASS) does not exist in the cluster. Install the sandbox runtime (gVisor, Kata, or a microVM runtime) and its RuntimeClass, or point SANDBOX_K8S_RUNTIME_CLASS at an existing one.` + ) + } + if (SHARED_KERNEL_HANDLERS.has(handler.trim().toLowerCase())) { + throw new KubernetesSandboxConfigError( + `RuntimeClass "${runtimeClassName}" (SANDBOX_K8S_RUNTIME_CLASS) uses the "${handler}" handler, which shares the node kernel with untrusted code. Use an isolating runtime such as gVisor (runsc) or Kata, or set SANDBOX_K8S_ALLOW_UNISOLATED=true to accept the risk.` + ) + } + logger.info('Sandbox pods run under an isolating RuntimeClass', { runtimeClassName, handler }) + } +} diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.test.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.test.ts new file mode 100644 index 00000000000..c3885365ae0 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.test.ts @@ -0,0 +1,237 @@ +/** + * @vitest-environment node + */ +import type { V1Container, V1Pod } from '@kubernetes/client-node' +import { + SANDBOX_AGENT_EXPIRES_AT_ENV, + SANDBOX_AGENT_TOKEN_SHA256_ENV, +} from '@sim/sandbox-agent-protocol' +import { describe, expect, it } from 'vitest' +import { KubernetesSandboxConfigError } from '@/lib/execution/remote-sandbox/kubernetes/errors' +import { buildSandboxPod } from '@/lib/execution/remote-sandbox/kubernetes/pod' +import { + imageFor, + type KubernetesSandboxSettings, + readKubernetesSandboxSettings, +} from '@/lib/execution/remote-sandbox/kubernetes/settings' +import { + deriveSandboxAgentToken, + sandboxAgentTokenDigest, +} from '@/lib/execution/remote-sandbox/kubernetes/token' + +const SECRET = 'internal-secret-internal-secret-0123456789' + +function settings(overrides: Partial = {}): KubernetesSandboxSettings { + return { + namespace: 'sim-sandboxes', + runtimeClassName: 'gvisor', + allowUnisolated: false, + images: { agent: 'registry/agent:1', function: 'registry/function:1', pi: 'registry/pi:1' }, + resources: { cpu: '1', memory: '2Gi', ephemeralStorage: '4Gi' }, + tokenSecret: SECRET, + ...overrides, + } +} + +function build(overrides: Partial[0]> = {}): V1Pod { + const name = 'sim-sbx-test' + return buildSandboxPod({ + name, + kind: 'code', + image: 'registry/function:1', + settings: settings(), + tokenDigest: sandboxAgentTokenDigest(deriveSandboxAgentToken(SECRET, name)), + expiresAtMs: 1_800_000_000_000, + ...overrides, + }) +} + +function sandboxContainer(pod: V1Pod): V1Container { + const container = pod.spec?.containers.find(({ name }) => name === 'sandbox') + if (!container) throw new Error('no sandbox container') + return container +} + +function allContainers(pod: V1Pod): V1Container[] { + return [...(pod.spec?.initContainers ?? []), ...(pod.spec?.containers ?? [])] +} + +describe('sandbox pod isolation', () => { + it('runs under the configured RuntimeClass', () => { + expect(build().spec?.runtimeClassName).toBe('gvisor') + }) + + it('names no RuntimeClass only when the operator opted into a shared kernel without one', () => { + const pod = build({ + settings: settings({ runtimeClassName: undefined, allowUnisolated: true }), + }) + expect(pod.spec).not.toHaveProperty('runtimeClassName') + }) + + it('gives sandbox code no service-account token and no Service environment', () => { + const spec = build().spec + expect(spec?.automountServiceAccountToken).toBe(false) + expect(spec?.enableServiceLinks).toBe(false) + }) + + it('shares no host namespace', () => { + const spec = build().spec + expect(spec?.hostNetwork).toBe(false) + expect(spec?.hostPID).toBe(false) + expect(spec?.hostIPC).toBe(false) + }) + + it('drops every capability and adds back only what the agent needs, in every container', () => { + const [installer, sandbox] = allContainers(build()) + expect(installer.securityContext?.capabilities).toEqual({ drop: ['ALL'] }) + expect(sandbox.securityContext?.capabilities?.drop).toEqual(['ALL']) + expect([...(sandbox.securityContext?.capabilities?.add ?? [])].sort()).toEqual([ + 'CHOWN', + 'DAC_OVERRIDE', + 'FOWNER', + 'KILL', + 'SETGID', + 'SETUID', + ]) + }) + + it('forbids privilege escalation and privileged mode, with the runtime default seccomp filter', () => { + for (const container of allContainers(build())) { + expect(container.securityContext?.allowPrivilegeEscalation).toBe(false) + expect(container.securityContext?.privileged).toBe(false) + expect(container.securityContext?.seccompProfile).toEqual({ type: 'RuntimeDefault' }) + } + }) + + it('mounts the agent binary read-only in the sandbox, so user code cannot replace it', () => { + const pod = build() + const agentMount = sandboxContainer(pod).volumeMounts?.find( + ({ mountPath }) => mountPath === '/opt/sim-agent' + ) + expect(agentMount?.readOnly).toBe(true) + expect(sandboxContainer(pod).command).toEqual(['/opt/sim-agent/sim-sandbox-agent']) + const installer = pod.spec?.initContainers?.[0] + expect(installer?.image).toBe('registry/agent:1') + expect(installer?.command).toEqual([ + '/sim-sandbox-agent', + 'install', + '/opt/sim-agent/sim-sandbox-agent', + ]) + }) + + it('shares the process namespace, so zombies the agent leaves are reaped', () => { + expect(build().spec?.shareProcessNamespace).toBe(true) + }) + + it('never restarts and is ended by Kubernetes at the 24-hour cap', () => { + const spec = build().spec + expect(spec?.restartPolicy).toBe('Never') + expect(spec?.activeDeadlineSeconds).toBe(24 * 60 * 60) + }) + + it('hands the agent only the token digest, never the token', () => { + const name = 'sim-sbx-test' + const token = deriveSandboxAgentToken(SECRET, name) + const pod = build({ name }) + const env = sandboxContainer(pod).env ?? [] + expect(env.find((entry) => entry.name === SANDBOX_AGENT_TOKEN_SHA256_ENV)?.value).toBe( + sandboxAgentTokenDigest(token) + ) + expect(env.find((entry) => entry.name === SANDBOX_AGENT_EXPIRES_AT_ENV)?.value).toBe( + '1800000000000' + ) + expect(JSON.stringify(pod)).not.toContain(token) + }) +}) + +describe('sandbox pod resources', () => { + it('limits the sandbox and requests half of each limit', () => { + expect(sandboxContainer(build()).resources).toEqual({ + limits: { cpu: '1', memory: '2Gi', 'ephemeral-storage': '4Gi' }, + requests: { cpu: '500m', memory: '1073741824', 'ephemeral-storage': '2147483648' }, + }) + }) + + it('gives the agent installer explicit requests and limits, so quota never sizes it by default', () => { + const installer = build().spec?.initContainers?.[0] + for (const bound of [installer?.resources?.requests, installer?.resources?.limits]) { + expect(Object.keys(bound ?? {}).sort()).toEqual(['cpu', 'ephemeral-storage', 'memory']) + } + }) + + it('caps every writable scratch volume at the ephemeral-storage limit', () => { + const volumes = build().spec?.volumes ?? [] + const mounts = sandboxContainer(build()).volumeMounts ?? [] + for (const path of ['/tmp', '/home/user', '/opt/sim-deps']) { + const mount = mounts.find(({ mountPath }) => mountPath === path) + expect(mount?.readOnly).toBeFalsy() + expect(volumes.find(({ name }) => name === mount?.name)?.emptyDir?.sizeLimit).toBe('4Gi') + } + }) +}) + +describe('sandbox pod labels', () => { + it('marks the pod Sim-managed with its kind and deadline, and labels a session by digest', () => { + const metadata = build({ kind: 'pi', sessionLabel: 'a'.repeat(40) }).metadata + expect(metadata?.labels).toEqual({ + 'app.kubernetes.io/managed-by': 'sim', + 'sim.ai/sandbox-kind': 'pi', + 'sim.ai/session': 'a'.repeat(40), + }) + expect(metadata?.annotations).toEqual({ 'sim.ai/expires-at': '1800000000000' }) + }) + + it('leaves a one-shot pod without a session label', () => { + expect(build().metadata?.labels).not.toHaveProperty('sim.ai/session') + }) +}) + +describe('Kubernetes sandbox settings', () => { + it('refuses to run without an isolating RuntimeClass unless the operator opts in', () => { + expect(() => readKubernetesSandboxSettings({ INTERNAL_API_SECRET: SECRET })).toThrow( + KubernetesSandboxConfigError + ) + expect(() => + readKubernetesSandboxSettings({ + INTERNAL_API_SECRET: SECRET, + SANDBOX_K8S_ALLOW_UNISOLATED: 'false', + }) + ).toThrow(/SANDBOX_K8S_RUNTIME_CLASS/) + expect( + readKubernetesSandboxSettings({ + INTERNAL_API_SECRET: SECRET, + SANDBOX_K8S_ALLOW_UNISOLATED: 'true', + }).allowUnisolated + ).toBe(true) + }) + + it('fails a Mothership or doc sandbox closed when its image is unset', () => { + const resolved = settings() + expect(() => imageFor('mothership', resolved)).toThrow(/SANDBOX_K8S_MOTHERSHIP_IMAGE/) + expect(() => imageFor('doc', resolved)).toThrow(/SANDBOX_K8S_DOC_IMAGE/) + }) + + it('never lets a caller image displace the Pi, Mothership, or doc image', () => { + const resolved = settings({ images: { ...settings().images, mothership: 'registry/shell:1' } }) + expect(imageFor('pi', resolved, 'user/image:1')).toBe('registry/pi:1') + expect(imageFor('mothership', resolved, 'user/image:1')).toBe('registry/shell:1') + expect(imageFor('code', resolved, 'user/image:1')).toBe('user/image:1') + }) + + it('rejects a malformed resource quantity or node selector by name', () => { + expect(() => + readKubernetesSandboxSettings({ + INTERNAL_API_SECRET: SECRET, + SANDBOX_K8S_RUNTIME_CLASS: 'gvisor', + SANDBOX_K8S_MEMORY: 'lots', + }) + ).toThrow(/SANDBOX_K8S_MEMORY/) + expect(() => + readKubernetesSandboxSettings({ + INTERNAL_API_SECRET: SECRET, + SANDBOX_K8S_RUNTIME_CLASS: 'gvisor', + SANDBOX_K8S_NODE_SELECTOR: '["not", "an", "object"]', + }) + ).toThrow(/SANDBOX_K8S_NODE_SELECTOR/) + }) +}) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts new file mode 100644 index 00000000000..ff3a8464061 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts @@ -0,0 +1,213 @@ +import type { V1Container, V1Pod, V1SecurityContext } from '@kubernetes/client-node' +import { + SANDBOX_AGENT_EXPIRES_AT_ENV, + SANDBOX_AGENT_PORT, + SANDBOX_AGENT_TOKEN_SHA256_ENV, +} from '@sim/sandbox-agent-protocol' +import { + halfQuantity, + type KubernetesSandboxSettings, +} from '@/lib/execution/remote-sandbox/kubernetes/settings' +import type { SandboxKind } from '@/lib/execution/remote-sandbox/types' + +/** Marks every pod this provider creates; the reaper and session lookup select on it. */ +const MANAGED_BY_LABEL = 'app.kubernetes.io/managed-by' +const MANAGED_BY_VALUE = 'sim' +const SANDBOX_KIND_LABEL = 'sim.ai/sandbox-kind' +/** Present only on session pods; its value is {@link sessionLabelValue} of the session key. */ +export const SESSION_LABEL = 'sim.ai/session' +/** Epoch milliseconds after which the reaper may delete the pod. */ +export const EXPIRES_AT_ANNOTATION = 'sim.ai/expires-at' + +/** Pod label selector for every sandbox pod Sim manages. */ +export const MANAGED_SELECTOR = `${MANAGED_BY_LABEL}=${MANAGED_BY_VALUE}` + +/** A pod never runs longer than this: E2B's continuous-runtime cap, applied as `activeDeadlineSeconds`. */ +export const SANDBOX_POD_MAX_LIFETIME_MS = 24 * 60 * 60 * 1000 + +export const SANDBOX_CONTAINER_NAME = 'sandbox' +const AGENT_INIT_CONTAINER_NAME = 'sim-agent' +const AGENT_VOLUME = 'sim-agent' +const AGENT_DIRECTORY = '/opt/sim-agent' +const AGENT_BINARY = `${AGENT_DIRECTORY}/sim-sandbox-agent` +const AGENT_PORT_NAME = 'agent' +/** The agent binary is ~100 MB per architecture; the volume holds only it. */ +const AGENT_VOLUME_SIZE = '256Mi' + +/** + * Writable scratch the sandbox user and dependency installs need. Each is an emptyDir capped at + * the pod's ephemeral-storage limit, so a runaway write is evicted rather than filling the node. + */ +const SCRATCH_MOUNTS = [ + { name: 'tmp', mountPath: '/tmp' }, + { name: 'home', mountPath: '/home/user' }, + { name: 'deps', mountPath: '/opt/sim-deps' }, +] as const + +/** + * The agent runs as root inside the sandbox runtime so it can run `root` commands and drop to + * uid 1000 for user code, but with only the capabilities that requires: changing file ownership + * and identity, reading and writing across users' files, and signalling process groups. + */ +const SANDBOX_CAPABILITIES = ['CHOWN', 'DAC_OVERRIDE', 'FOWNER', 'SETUID', 'SETGID', 'KILL'] + +/** Everything a sandbox pod is built from. */ +interface SandboxPodInput { + name: string + kind: SandboxKind + image: string + settings: KubernetesSandboxSettings + /** Hex SHA-256 of the agent's bearer token. */ + tokenDigest: string + expiresAtMs: number + /** {@link sessionLabelValue} of the session key, for a session pod. */ + sessionLabel?: string +} + +function agentInstallerContainer(input: SandboxPodInput, security: V1SecurityContext): V1Container { + return { + name: AGENT_INIT_CONTAINER_NAME, + image: input.settings.images.agent, + command: ['/sim-sandbox-agent', 'install', AGENT_BINARY], + volumeMounts: [{ name: AGENT_VOLUME, mountPath: AGENT_DIRECTORY }], + // Explicit, because the namespace's ResourceQuota counts limits and a LimitRange default + // would otherwise size it. Copying one binary needs little CPU; the limit leaves the Bun + // runtime its working set. + resources: { + requests: { cpu: '10m', memory: '32Mi', 'ephemeral-storage': '32Mi' }, + limits: { cpu: '100m', memory: '128Mi', 'ephemeral-storage': '32Mi' }, + }, + securityContext: { ...security, capabilities: { drop: ['ALL'] }, readOnlyRootFilesystem: true }, + } +} + +/** + * The pod for one sandbox. Pure, so its security properties are asserted directly: + * + * - It runs under the configured RuntimeClass (the isolation boundary) and never receives a + * service-account token, Service environment, host namespace, or privilege escalation. + * - The agent binary comes from an init container into a volume the sandbox mounts read-only, so + * any image can host the agent and user code cannot replace the binary the agent re-executes. + * - `shareProcessNamespace` puts the pause container at PID 1 to reap zombies the agent (a Bun + * process, which cannot reap) would otherwise leave behind. + * - `activeDeadlineSeconds` is the hard lifetime cap, set once and never raised; the agent's own + * deadline (`expiresAtMs`) ends the pod earlier, and `restartPolicy: Never` keeps it ended. + */ +export function buildSandboxPod(input: SandboxPodInput): V1Pod { + const { settings } = input + const { cpu, memory, ephemeralStorage } = settings.resources + const security: V1SecurityContext = { + allowPrivilegeEscalation: false, + privileged: false, + runAsUser: 0, + runAsGroup: 0, + // Kept under every runtime: admission never sees the runtime, and gVisor's runsc enforces + // the OCI seccomp filter inside its sandbox (its `oci-seccomp` flag defaults on) rather than + // refusing the container. Under runc it is the usual host-kernel filter. + seccompProfile: { type: 'RuntimeDefault' }, + } + return { + apiVersion: 'v1', + kind: 'Pod', + metadata: { + name: input.name, + namespace: settings.namespace, + labels: { + [MANAGED_BY_LABEL]: MANAGED_BY_VALUE, + [SANDBOX_KIND_LABEL]: input.kind, + ...(input.sessionLabel ? { [SESSION_LABEL]: input.sessionLabel } : {}), + }, + annotations: { [EXPIRES_AT_ANNOTATION]: String(input.expiresAtMs) }, + }, + spec: { + ...(settings.runtimeClassName ? { runtimeClassName: settings.runtimeClassName } : {}), + restartPolicy: 'Never', + automountServiceAccountToken: false, + enableServiceLinks: false, + shareProcessNamespace: true, + hostNetwork: false, + hostPID: false, + hostIPC: false, + activeDeadlineSeconds: SANDBOX_POD_MAX_LIFETIME_MS / 1000, + terminationGracePeriodSeconds: 5, + ...(settings.nodeSelector ? { nodeSelector: settings.nodeSelector } : {}), + ...(settings.tolerations ? { tolerations: settings.tolerations } : {}), + ...(settings.imagePullSecret + ? { imagePullSecrets: [{ name: settings.imagePullSecret }] } + : {}), + initContainers: [agentInstallerContainer(input, security)], + containers: [ + { + name: SANDBOX_CONTAINER_NAME, + image: input.image, + command: [AGENT_BINARY], + env: [ + { name: SANDBOX_AGENT_TOKEN_SHA256_ENV, value: input.tokenDigest }, + { name: SANDBOX_AGENT_EXPIRES_AT_ENV, value: String(input.expiresAtMs) }, + ], + ports: [{ name: AGENT_PORT_NAME, containerPort: SANDBOX_AGENT_PORT, protocol: 'TCP' }], + resources: { + limits: { cpu, memory, 'ephemeral-storage': ephemeralStorage }, + requests: { + cpu: halfQuantity(cpu), + memory: halfQuantity(memory), + 'ephemeral-storage': halfQuantity(ephemeralStorage), + }, + }, + securityContext: { + ...security, + capabilities: { drop: ['ALL'], add: SANDBOX_CAPABILITIES }, + }, + volumeMounts: [ + { name: AGENT_VOLUME, mountPath: AGENT_DIRECTORY, readOnly: true }, + ...SCRATCH_MOUNTS.map(({ name, mountPath }) => ({ name, mountPath })), + ], + }, + ], + volumes: [ + { name: AGENT_VOLUME, emptyDir: { sizeLimit: AGENT_VOLUME_SIZE } }, + ...SCRATCH_MOUNTS.map(({ name }) => ({ + name, + emptyDir: { sizeLimit: ephemeralStorage }, + })), + ], + }, + } +} + +/** + * The agent's base URL, read from the pod itself: its IP and the port its sandbox container + * declares. Null until the pod has an IP. + */ +export function agentBaseUrl(pod: V1Pod): string | null { + const ip = pod.status?.podIP + if (!ip) return null + const container = pod.spec?.containers.find(({ name }) => name === SANDBOX_CONTAINER_NAME) + const port = + container?.ports?.find(({ name }) => name === AGENT_PORT_NAME)?.containerPort ?? + SANDBOX_AGENT_PORT + return `http://${ip.includes(':') ? `[${ip}]` : ip}:${port}` +} + +/** The pod's `sim.ai/expires-at`, or null when it is missing or malformed. */ +export function podExpiresAtMs(pod: V1Pod): number | null { + const raw = pod.metadata?.annotations?.[EXPIRES_AT_ANNOTATION] + const value = raw === undefined ? Number.NaN : Number(raw) + return Number.isSafeInteger(value) && value > 0 ? value : null +} + +/** The token digest the pod's agent was started with. */ +export function podTokenDigest(pod: V1Pod): string | undefined { + return pod.spec?.containers + .find(({ name }) => name === SANDBOX_CONTAINER_NAME) + ?.env?.find(({ name }) => name === SANDBOX_AGENT_TOKEN_SHA256_ENV)?.value +} + +/** + * When `activeDeadlineSeconds` ends the pod: counted from its start, or from its creation while + * it has not started (a later start only moves it later). + */ +export function podHardDeadlineMs(pod: V1Pod): number | null { + const started = pod.status?.startTime ?? pod.metadata?.creationTimestamp + return started ? new Date(started).getTime() + SANDBOX_POD_MAX_LIFETIME_MS : null +} diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.test.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.test.ts new file mode 100644 index 00000000000..c5d8d4cd83c --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.test.ts @@ -0,0 +1,617 @@ +/** + * @vitest-environment node + */ +import { createHash } from 'node:crypto' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http' +import type { AddressInfo } from 'node:net' +import { tmpdir } from 'node:os' +import path from 'node:path' +import type { V1Pod } from '@kubernetes/client-node' +import { SANDBOX_AGENT_TOKEN_SHA256_ENV } from '@sim/sandbox-agent-protocol' +import { setEnv } from '@sim/testing/mocks/env.mock' +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { env } from '@/lib/core/config/env' +import { + KubernetesSandboxCapacityError, + KubernetesSandboxConfigError, +} from '@/lib/execution/remote-sandbox/kubernetes/errors' +import { kubernetesProvider } from '@/lib/execution/remote-sandbox/kubernetes/provider' +import { + deriveSandboxAgentToken, + sandboxAgentTokenDigest, + sessionLabelValue, +} from '@/lib/execution/remote-sandbox/kubernetes/token' + +/** + * Drives the production provider, configured through its env vars and a real `KUBECONFIG` file, + * through the real `@kubernetes/client-node` against an in-process API server speaking the REST + * shapes the client uses (pods create/get/list/watch/patch/delete, RuntimeClass get), plus a + * stand-in agent that checks bearer tokens against the pod's digest. The fake kubelet moves a pod + * to Running at the stand-in agent's loopback address and port. + * + * Each test gets its own namespace: the provider opens one cluster client, with its own + * RuntimeClass verdict, per namespace, so a test never sees another's cached verdict. + */ + +const HOUR_MS = 60 * 60 * 1000 +let namespace = '' +let namespaceCount = 0 +let kubeconfigDirectory = '' + +/** Every request either fake server saw, in arrival order. */ +const timeline: string[] = [] + +interface StoredEvent { + resourceVersion: number + type: 'ADDED' | 'MODIFIED' | 'DELETED' + pod: V1Pod +} + +interface Watcher { + name: string + response: ServerResponse +} + +function statusBody(code: number, reason: string, message: string) { + return { kind: 'Status', apiVersion: 'v1', status: 'Failure', reason, message, code } +} + +async function readBody(request: IncomingMessage): Promise { + const chunks: Buffer[] = [] + for await (const chunk of request) chunks.push(chunk as Buffer) + const text = Buffer.concat(chunks).toString('utf8') + return text ? JSON.parse(text) : undefined +} + +function matchesSelector(pod: V1Pod, selector: string | null): boolean { + if (!selector) return true + return selector.split(',').every((term) => { + const [key, value] = term.split('=') + return pod.metadata?.labels?.[key] === value + }) +} + +class FakeKubernetes { + readonly pods = new Map() + readonly runtimeClasses = new Map() + readonly log: string[] = [] + quotaExceeded = false + /** Runs after a pod is stored, standing in for the scheduler and kubelet. */ + onCreate: (name: string) => void = () => {} + private events: StoredEvent[] = [] + private watchers = new Set() + private resourceVersion = 1 + private server: Server + port = 0 + + constructor() { + this.server = createServer((request, response) => { + this.handle(request, response).catch((error: unknown) => { + response.writeHead(500).end(String(error)) + }) + }) + } + + async start(): Promise { + await new Promise((resolve) => this.server.listen(0, '127.0.0.1', resolve)) + this.port = (this.server.address() as AddressInfo).port + } + + async stop(): Promise { + for (const watcher of this.watchers) watcher.response.end() + this.server.closeAllConnections() + await new Promise((resolve) => this.server.close(() => resolve())) + } + + reset(): void { + this.pods.clear() + this.runtimeClasses.clear() + this.log.length = 0 + this.events = [] + this.quotaExceeded = false + this.onCreate = () => {} + } + + kubeconfig(): string { + return [ + 'apiVersion: v1', + 'kind: Config', + 'clusters:', + `- name: fake\n cluster:\n server: http://127.0.0.1:${this.port}\n insecure-skip-tls-verify: true`, + 'users:', + '- name: sim\n user:\n token: service-account-token', + 'contexts:', + '- name: fake\n context:\n cluster: fake\n user: sim', + 'current-context: fake', + '', + ].join('\n') + } + + /** Stores a pod as the API server would and publishes the change to watchers. */ + put(pod: V1Pod, type: StoredEvent['type'] = 'MODIFIED'): V1Pod { + const name = pod.metadata?.name ?? '' + this.resourceVersion++ + const stored: V1Pod = { + ...pod, + metadata: { ...pod.metadata, resourceVersion: String(this.resourceVersion) }, + } + if (type === 'DELETED') this.pods.delete(name) + else this.pods.set(name, stored) + const event = { resourceVersion: this.resourceVersion, type, pod: stored } + this.events.push(event) + for (const watcher of this.watchers) { + if (watcher.name === name) + watcher.response.write(`${JSON.stringify({ type, object: stored })}\n`) + } + return stored + } + + update(name: string, mutate: (pod: V1Pod) => V1Pod): void { + const pod = this.pods.get(name) + if (pod) this.put(mutate(pod)) + } + + private async handle(request: IncomingMessage, response: ServerResponse): Promise { + const url = new URL(request.url ?? '/', 'http://fake') + const method = request.method ?? 'GET' + this.log.push(`${method} ${url.pathname}`) + timeline.push(`api ${method} ${url.pathname}`) + const json = (code: number, body: unknown) => { + response.writeHead(code, { 'Content-Type': 'application/json' }).end(JSON.stringify(body)) + } + + const runtimeClass = /^\/apis\/node\.k8s\.io\/v1\/runtimeclasses\/([^/]+)$/.exec(url.pathname) + if (runtimeClass && method === 'GET') { + const handler = this.runtimeClasses.get(runtimeClass[1]) + if (handler === undefined) return json(404, statusBody(404, 'NotFound', 'not found')) + return json(200, { + apiVersion: 'node.k8s.io/v1', + kind: 'RuntimeClass', + metadata: { name: runtimeClass[1] }, + handler, + }) + } + + const collection = `/api/v1/namespaces/${namespace}/pods` + if (url.pathname === collection && method === 'POST') { + const pod = (await readBody(request)) as V1Pod + const name = pod.metadata?.name ?? '' + if (this.quotaExceeded) { + return json( + 403, + statusBody( + 403, + 'Forbidden', + `pods "${name}" is forbidden: exceeded quota: sandboxes, requested: pods=1, used: pods=20, limited: pods=20` + ) + ) + } + if (this.pods.has(name)) return json(409, statusBody(409, 'AlreadyExists', 'exists')) + const stored = this.put( + { + ...pod, + metadata: { + ...pod.metadata, + uid: `uid-${name}`, + creationTimestamp: new Date(), + }, + status: { phase: 'Pending' }, + }, + 'ADDED' + ) + json(201, stored) + this.onCreate(name) + return + } + if (url.pathname === collection && method === 'GET') { + if (url.searchParams.get('watch') === 'true') { + const name = (url.searchParams.get('fieldSelector') ?? '').replace('metadata.name=', '') + const from = Number(url.searchParams.get('resourceVersion') ?? '0') + response.writeHead(200, { 'Content-Type': 'application/json' }) + for (const event of this.events) { + if (event.resourceVersion > from && event.pod.metadata?.name === name) { + response.write(`${JSON.stringify({ type: event.type, object: event.pod })}\n`) + } + } + const watcher = { name, response } + this.watchers.add(watcher) + request.on('close', () => this.watchers.delete(watcher)) + return + } + const selector = url.searchParams.get('labelSelector') + return json(200, { + apiVersion: 'v1', + kind: 'PodList', + metadata: { resourceVersion: String(this.resourceVersion) }, + items: [...this.pods.values()].filter((pod) => matchesSelector(pod, selector)), + }) + } + + const item = new RegExp(`^${collection}/([^/]+)$`).exec(url.pathname) + if (item) { + const pod = this.pods.get(item[1]) + if (!pod) return json(404, statusBody(404, 'NotFound', `pods "${item[1]}" not found`)) + if (method === 'GET') return json(200, pod) + if (method === 'DELETE') { + this.put(pod, 'DELETED') + return json(200, pod) + } + if (method === 'PATCH') { + const patch = (await readBody(request)) as V1Pod + const patched = this.put({ + ...pod, + metadata: { + ...pod.metadata, + annotations: { ...pod.metadata?.annotations, ...patch.metadata?.annotations }, + }, + }) + return json(200, patched) + } + } + json(404, statusBody(404, 'NotFound', 'no route')) + } +} + +/** Stand-in agent: answers health checks and accepts lifetime extensions under the pod's token. */ +class FakeAgent { + readonly log: string[] = [] + /** Token digests the agent accepts, as the pod env would hand them over. */ + readonly accepted = new Set() + private server: Server + port = 0 + + constructor() { + this.server = createServer(async (request, response) => { + const url = new URL(request.url ?? '/', 'http://agent') + if (url.pathname === '/healthz') { + response.writeHead(200, { 'Content-Type': 'application/json' }) + response.end(JSON.stringify({ ok: true, protocol: 1, agentVersion: 'fake' })) + return + } + const token = /^Bearer (.+)$/.exec(request.headers.authorization ?? '')?.[1] ?? '' + if (!this.accepted.has(createHash('sha256').update(token).digest('hex'))) { + response.writeHead(401, { 'Content-Type': 'application/json' }) + response.end(JSON.stringify({ error: { code: 'unauthorized', message: 'no' } })) + return + } + const body = await readBody(request) + this.log.push(`${request.method} ${url.pathname}`) + timeline.push(`agent ${request.method} ${url.pathname}`) + if (url.pathname === '/v1/lifetime') { + response.writeHead(200, { 'Content-Type': 'application/json' }) + response.end(JSON.stringify(body)) + return + } + response.writeHead(200, { 'Content-Type': 'application/json' }).end('{}') + }) + } + + async start(): Promise { + await new Promise((resolve) => this.server.listen(0, '127.0.0.1', resolve)) + this.port = (this.server.address() as AddressInfo).port + } + + async stop(): Promise { + this.server.closeAllConnections() + await new Promise((resolve) => this.server.close(() => resolve())) + } +} + +const cluster = new FakeKubernetes() +const agent = new FakeAgent() + +/** Selects the provider's isolation settings for this test, as an operator would in env. */ +function configure(isolation: { runtimeClass?: string; allowUnisolated?: boolean } = {}) { + setEnv({ + SANDBOX_K8S_NAMESPACE: namespace, + SANDBOX_K8S_RUNTIME_CLASS: isolation.runtimeClass ?? 'gvisor', + SANDBOX_K8S_ALLOW_UNISOLATED: isolation.allowUnisolated ? 'true' : undefined, + }) + return kubernetesProvider +} + +/** The fake kubelet: starts the pod at the stand-in agent, accepting the digest the pod carries. */ +function runPod(pod: V1Pod): V1Pod { + const container = pod.spec?.containers[0] + const digest = container?.env?.find(({ name }) => name === SANDBOX_AGENT_TOKEN_SHA256_ENV)?.value + if (digest) agent.accepted.add(digest) + return { + ...pod, + spec: pod.spec && { + ...pod.spec, + containers: pod.spec.containers.map((entry) => ({ + ...entry, + ports: [{ name: 'agent', containerPort: agent.port }], + })), + }, + status: { + phase: 'Running', + podIP: '127.0.0.1', + startTime: new Date(), + containerStatuses: [ + { + name: 'sandbox', + image: container?.image ?? '', + imageID: '', + ready: true, + restartCount: 0, + state: { running: {} }, + }, + ], + }, + } +} + +/** A pod as another replica (or an earlier create) left it in the cluster. */ +function seedPod(options: { + name: string + phase?: string + createdAgoMs: number + expiresInMs?: number + sessionKey?: string + secret?: string + managed?: boolean +}): void { + const now = Date.now() + const created = new Date(now - options.createdAgoMs) + const digest = sandboxAgentTokenDigest( + deriveSandboxAgentToken(options.secret ?? env.INTERNAL_API_SECRET, options.name) + ) + cluster.put( + { + metadata: { + name: options.name, + namespace, + creationTimestamp: created, + labels: { + 'app.kubernetes.io/managed-by': options.managed === false ? 'someone-else' : 'sim', + 'sim.ai/sandbox-kind': 'code', + ...(options.sessionKey + ? { 'sim.ai/session': sessionLabelValue(options.sessionKey) } + : {}), + }, + annotations: + options.expiresInMs === undefined + ? {} + : { 'sim.ai/expires-at': String(now + options.expiresInMs) }, + }, + spec: { + containers: [ + { + name: 'sandbox', + image: 'registry/function:1', + env: [{ name: SANDBOX_AGENT_TOKEN_SHA256_ENV, value: digest }], + ports: [{ name: 'agent', containerPort: agent.port }], + }, + ], + }, + status: { + phase: options.phase ?? 'Running', + podIP: '127.0.0.1', + startTime: created, + }, + }, + 'ADDED' + ) + agent.accepted.add(digest) +} + +beforeAll(async () => { + await Promise.all([cluster.start(), agent.start()]) + kubeconfigDirectory = mkdtempSync(path.join(tmpdir(), 'sim-k8s-sandbox-')) + writeFileSync(path.join(kubeconfigDirectory, 'config'), cluster.kubeconfig()) +}) + +afterAll(async () => { + await Promise.all([cluster.stop(), agent.stop()]) + rmSync(kubeconfigDirectory, { recursive: true, force: true }) +}) + +beforeEach(() => { + vi.stubEnv('KUBECONFIG', path.join(kubeconfigDirectory, 'config')) + namespace = `sandboxes-${++namespaceCount}` + cluster.reset() + cluster.runtimeClasses.set('gvisor', 'runsc') + agent.log.length = 0 + agent.accepted.clear() + timeline.length = 0 +}) + +afterEach(() => { + cluster.onCreate = () => {} +}) + +describe('create', () => { + it('watches a new pod to Running, then hands back a handle its agent authenticates', async () => { + cluster.onCreate = (name) => { + setTimeout(() => cluster.update(name, runPod), 50) + } + const sandbox = await configure().create('code', { lifetimeMs: 60_000, sessionKey: 'chat-1' }) + + const pod = cluster.pods.get(sandbox.sandboxId) + expect(pod?.spec?.runtimeClassName).toBe('gvisor') + expect(pod?.metadata?.labels?.['sim.ai/session']).toBe(sessionLabelValue('chat-1')) + expect(cluster.log).toContain(`GET /api/v1/namespaces/${namespace}/pods`) + + await sandbox.extendLifetime?.(10 * 60_000) + expect(agent.log).toEqual(['POST /v1/lifetime']) + const annotated = Number( + cluster.pods.get(sandbox.sandboxId)?.metadata?.annotations?.['sim.ai/expires-at'] + ) + expect(annotated).toBeGreaterThan(Date.now() + 9 * 60_000) + // The pod's annotation is moved before the agent is asked, so the reaper never sees a pod + // whose agent outlives its recorded deadline. + const patched = timeline.indexOf( + `api PATCH /api/v1/namespaces/${namespace}/pods/${sandbox.sandboxId}` + ) + expect(patched).toBeGreaterThan(-1) + expect(patched).toBeLessThan(timeline.indexOf('agent POST /v1/lifetime')) + + await sandbox.kill() + expect(cluster.pods.has(sandbox.sandboxId)).toBe(false) + }) + + it('reports an exhausted ResourceQuota as a capacity limit and creates nothing', async () => { + cluster.quotaExceeded = true + const error = await configure() + .create('code', { lifetimeMs: 60_000 }) + .catch((caught: unknown) => caught) + expect(error).toBeInstanceOf(KubernetesSandboxCapacityError) + expect(String(error)).toMatch(/ResourceQuota/) + expect(cluster.pods.size).toBe(0) + }) + + it('fails fast on an image the cluster cannot pull, naming the variable, and deletes the pod', async () => { + cluster.onCreate = (name) => { + setTimeout( + () => + cluster.update(name, (pod) => ({ + ...pod, + status: { + phase: 'Pending', + containerStatuses: [ + { + name: 'sandbox', + image: 'registry/function:1', + imageID: '', + ready: false, + restartCount: 0, + state: { waiting: { reason: 'ImagePullBackOff', message: 'pull denied' } }, + }, + ], + }, + })), + 20 + ) + } + await expect(configure().create('code', { lifetimeMs: 60_000 })).rejects.toThrow( + /SANDBOX_K8S_FUNCTION_IMAGE/ + ) + expect(cluster.pods.size).toBe(0) + }) +}) + +describe('isolation guard', () => { + it('refuses a RuntimeClass that does not exist, before creating any pod', async () => { + cluster.runtimeClasses.clear() + await expect(configure().create('code', { lifetimeMs: 60_000 })).rejects.toThrow( + KubernetesSandboxConfigError + ) + expect(cluster.log.some((entry) => entry.startsWith('POST'))).toBe(false) + }) + + it('refuses a RuntimeClass whose handler shares the node kernel', async () => { + cluster.runtimeClasses.set('gvisor', 'runc') + await expect(configure().create('code', { lifetimeMs: 60_000 })).rejects.toThrow(/runc/) + expect(cluster.log.some((entry) => entry.startsWith('POST'))).toBe(false) + }) + + it('reads the RuntimeClass once per provider, not per create', async () => { + cluster.onCreate = (name) => cluster.update(name, runPod) + const sandboxes = configure() + await sandboxes.create('code', { lifetimeMs: 60_000 }) + await sandboxes.create('code', { lifetimeMs: 60_000 }) + expect(cluster.log.filter((entry) => entry.includes('runtimeclasses'))).toHaveLength(1) + }) + + it('runs without a RuntimeClass only when the operator opted into a shared kernel', async () => { + cluster.runtimeClasses.clear() + cluster.onCreate = (name) => cluster.update(name, runPod) + const sandbox = await configure({ runtimeClass: '', allowUnisolated: true }).create('code', { + lifetimeMs: 60_000, + }) + expect(cluster.pods.get(sandbox.sandboxId)?.spec).not.toHaveProperty('runtimeClassName') + expect(cluster.log.some((entry) => entry.includes('runtimeclasses'))).toBe(false) + }) +}) + +describe('findSessionSandbox', () => { + it('reconnects to the oldest live pod this deployment can authenticate to', async () => { + seedPod({ name: 'expired', createdAgoMs: 3 * HOUR_MS, expiresInMs: -1_000, sessionKey: 'chat' }) + seedPod({ + name: 'oldest-live', + createdAgoMs: 2 * HOUR_MS, + expiresInMs: HOUR_MS, + sessionKey: 'chat', + }) + seedPod({ name: 'newer-live', createdAgoMs: HOUR_MS, expiresInMs: HOUR_MS, sessionKey: 'chat' }) + seedPod({ + name: 'rotated-secret', + createdAgoMs: 4 * HOUR_MS, + expiresInMs: HOUR_MS, + sessionKey: 'chat', + secret: 'a-different-internal-secret-0123456789', + }) + seedPod({ + name: 'pending', + phase: 'Pending', + createdAgoMs: 5 * HOUR_MS, + expiresInMs: HOUR_MS, + sessionKey: 'chat', + }) + seedPod({ + name: 'other-chat', + createdAgoMs: 6 * HOUR_MS, + expiresInMs: HOUR_MS, + sessionKey: 'x', + }) + + const sandbox = await configure().findSessionSandbox?.('chat', { lifetimeMs: 60_000 }) + expect(sandbox?.sandboxId).toBe('oldest-live') + // The reconnected handle authenticates with the token derived for that pod. + await sandbox?.extendLifetime?.(2 * HOUR_MS) + expect(agent.log).toEqual(['POST /v1/lifetime']) + }) + + it('skips a pod whose 24-hour cap falls inside the requested lease', async () => { + seedPod({ + name: 'near-cap', + createdAgoMs: 23.9 * HOUR_MS, + expiresInMs: HOUR_MS, + sessionKey: 'chat', + }) + seedPod({ name: 'fresh', createdAgoMs: HOUR_MS, expiresInMs: HOUR_MS, sessionKey: 'chat' }) + const sandbox = await configure().findSessionSandbox?.('chat', { lifetimeMs: 30 * 60_000 }) + expect(sandbox?.sandboxId).toBe('fresh') + }) + + it('resolves null when the session has no live pod', async () => { + seedPod({ name: 'expired', createdAgoMs: HOUR_MS, expiresInMs: -1_000, sessionKey: 'chat' }) + await expect(configure().findSessionSandbox?.('chat', {})).resolves.toBeNull() + }) +}) + +describe('reapExpiredSandboxes', () => { + it('deletes finished pods and pods past their deadline plus grace, and nothing else', async () => { + seedPod({ name: 'succeeded', phase: 'Succeeded', createdAgoMs: HOUR_MS, expiresInMs: HOUR_MS }) + seedPod({ name: 'failed', phase: 'Failed', createdAgoMs: HOUR_MS, expiresInMs: HOUR_MS }) + seedPod({ + name: 'orphaned', + createdAgoMs: HOUR_MS, + // Past the five-minute grace. + expiresInMs: -6 * 60_000, + }) + seedPod({ name: 'in-grace', createdAgoMs: HOUR_MS, expiresInMs: -60_000 }) + seedPod({ name: 'live', createdAgoMs: HOUR_MS, expiresInMs: HOUR_MS }) + seedPod({ name: 'unannotated-past-cap', createdAgoMs: 25 * HOUR_MS }) + seedPod({ name: 'unannotated-young', createdAgoMs: HOUR_MS }) + seedPod({ + name: 'not-ours', + phase: 'Succeeded', + createdAgoMs: HOUR_MS, + expiresInMs: -HOUR_MS, + managed: false, + }) + + const result = await configure().reapExpiredSandboxes?.(AbortSignal.timeout(10_000)) + + expect(result).toEqual({ deleted: 4, deferred: 0, failed: 0 }) + expect([...cluster.pods.keys()].sort()).toEqual([ + 'in-grace', + 'live', + 'not-ours', + 'unannotated-young', + ]) + }) +}) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.ts new file mode 100644 index 00000000000..2c237b70e4b --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.ts @@ -0,0 +1,487 @@ +import type { KubeConfig, V1Pod } from '@kubernetes/client-node' +import { createLogger } from '@sim/logger' +import { + healthzResponseSchema, + SANDBOX_AGENT_ROUTES, + sandboxAgentProcessSignalPath, +} from '@sim/sandbox-agent-protocol' +import { getErrorMessage } from '@sim/utils/errors' +import { sleep } from '@sim/utils/helpers' +import { generateShortId } from '@sim/utils/id' +import { backoffWithJitter, parseRetryAfter } from '@sim/utils/retry' +import { compareStrings } from '@sim/utils/string' +import { env } from '@/lib/core/config/env' +import type { CodeLanguage } from '@/lib/execution/languages' +import { + SandboxAgentClient, + SandboxAgentRequestError, +} from '@/lib/execution/remote-sandbox/agent/client' +import { createAgentSandboxHandle } from '@/lib/execution/remote-sandbox/agent/handle' +import { + KubernetesApiError, + loadDefaultKubeConfig, + openSandboxCluster, + type SandboxCluster, +} from '@/lib/execution/remote-sandbox/kubernetes/cluster' +import { + isRetryableKubernetesFailure, + KubernetesSandboxCapacityError, + KubernetesSandboxConfigError, + toPodCreateError, +} from '@/lib/execution/remote-sandbox/kubernetes/errors' +import { bindSandboxPod } from '@/lib/execution/remote-sandbox/kubernetes/handle' +import { IsolationGuard } from '@/lib/execution/remote-sandbox/kubernetes/isolation' +import { + agentBaseUrl, + buildSandboxPod, + MANAGED_SELECTOR, + podExpiresAtMs, + podHardDeadlineMs, + podTokenDigest, + SANDBOX_CONTAINER_NAME, + SANDBOX_POD_MAX_LIFETIME_MS, + SESSION_LABEL, +} from '@/lib/execution/remote-sandbox/kubernetes/pod' +import { reapSandboxPods } from '@/lib/execution/remote-sandbox/kubernetes/reaper' +import { + imageFor, + imageVariableFor, + type KubernetesSandboxSettings, + readKubernetesSandboxSettings, +} from '@/lib/execution/remote-sandbox/kubernetes/settings' +import { + deriveSandboxAgentToken, + sandboxAgentTokenDigest, + sessionLabelValue, +} from '@/lib/execution/remote-sandbox/kubernetes/token' +import type { SessionProcessIdentity } from '@/lib/execution/remote-sandbox/session-process' +import type { + CreateSandboxOptions, + SandboxHandle, + SandboxKind, + SandboxProvider, +} from '@/lib/execution/remote-sandbox/types' + +const logger = createLogger('KubernetesSandboxProvider') + +/** Lifetime of a sandbox whose caller asked for none, matching E2B's default. */ +const DEFAULT_SANDBOX_LIFETIME_MS = 5 * 60_000 + +/** + * Longest a create waits for its pod to run and its agent to answer. Covers a cold image pull of + * the Function image on a fresh node; a pod that cannot start by then is deleted. + */ +const CREATE_TIMEOUT_MS = 3 * 60_000 + +const MAX_CREATE_ATTEMPTS = 3 +const CREATE_BACKOFF = { baseMs: 500, maxMs: 5_000 } +const HEALTH_BACKOFF = { baseMs: 100, maxMs: 1_000 } +const HEALTH_REQUEST_TIMEOUT_MS = 2_000 + +/** Pod names: a fixed prefix plus 20 random lowercase alphanumerics (~103 bits). */ +const POD_NAME_PREFIX = 'sim-sbx-' +const POD_NAME_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789' + +/** Container waiting reasons that will not clear without an operator: fail the create now. */ +const FATAL_WAITING_REASONS = new Set([ + 'ErrImagePull', + 'ImagePullBackOff', + 'InvalidImageName', + 'ErrImageNeverPull', + 'CreateContainerConfigError', +]) + +/** Rounds to whole seconds (the pod deadline's unit) and caps at the pod's hard lifetime. */ +function resolveKubernetesSandboxLifetimeMs(lifetimeMs: number): number { + return Math.min(Math.ceil(lifetimeMs / 1000) * 1000, SANDBOX_POD_MAX_LIFETIME_MS) +} + +function newPodName(): string { + return `${POD_NAME_PREFIX}${generateShortId(20, POD_NAME_ALPHABET)}` +} + +type PodProgress = + | { state: 'ready'; baseUrl: string } + | { state: 'pending'; detail?: string } + | { state: 'failed'; error: Error } + +/** + * Where a starting pod stands. `failed` when it can no longer become ready: it finished, is being + * deleted, or one of its containers is stuck on an image or configuration problem. Returned rather + * than thrown, because it is also evaluated inside the watch callback, whose errors the client + * discards. + */ +function podProgress(pod: V1Pod, kind: SandboxKind): PodProgress { + const name = pod.metadata?.name ?? 'sandbox pod' + if (pod.metadata?.deletionTimestamp) { + return { state: 'failed', error: new Error(`Sandbox pod ${name} was deleted while starting`) } + } + const phase = pod.status?.phase + if (phase === 'Succeeded' || phase === 'Failed') { + return { + state: 'failed', + error: new Error( + `Sandbox pod ${name} stopped before its agent started (${pod.status?.reason ?? phase}${pod.status?.message ? `: ${pod.status.message}` : ''})` + ), + } + } + const statuses = [ + ...(pod.status?.initContainerStatuses ?? []).map((status) => ({ status, init: true })), + ...(pod.status?.containerStatuses ?? []).map((status) => ({ status, init: false })), + ] + for (const { status, init } of statuses) { + const waiting = status.state?.waiting + if (!waiting?.reason || !FATAL_WAITING_REASONS.has(waiting.reason)) continue + const variable = init ? 'SANDBOX_K8S_AGENT_IMAGE' : imageVariableFor(kind) + return { + state: 'failed', + error: new KubernetesSandboxConfigError( + `Sandbox pod ${name} cannot start its ${init ? 'agent installer' : 'sandbox'} container (${waiting.reason}): ${waiting.message ?? status.image}. Check that ${variable} names an image the cluster can pull, and set SANDBOX_K8S_IMAGE_PULL_SECRET for a private registry.` + ), + } + } + const sandboxRunning = pod.status?.containerStatuses?.some( + (status) => status.name === SANDBOX_CONTAINER_NAME && status.state?.running + ) + const baseUrl = agentBaseUrl(pod) + if (phase === 'Running' && sandboxRunning && baseUrl) return { state: 'ready', baseUrl } + const unscheduled = pod.status?.conditions?.find( + (condition) => condition.type === 'PodScheduled' && condition.status === 'False' + ) + const detail = unscheduled?.message ?? pod.status?.message ?? phase + return { state: 'pending', ...(detail ? { detail } : {}) } +} + +/** Polls the agent's `/healthz` until it answers as a compatible agent or `signal` aborts. */ +async function waitForAgent(baseUrl: string, signal: AbortSignal): Promise { + for (let attempt = 1; ; attempt++) { + signal.throwIfAborted() + let response: Response | undefined + try { + // egress-direct: the sandbox agent is an operator-local pod endpoint, never a workspace egress target + response = await fetch(`${baseUrl}${SANDBOX_AGENT_ROUTES.healthz}`, { + signal: AbortSignal.any([signal, AbortSignal.timeout(HEALTH_REQUEST_TIMEOUT_MS)]), + }) + } catch { + signal.throwIfAborted() + } + if (response?.ok) { + const health = healthzResponseSchema.safeParse(await response.json().catch(() => null)) + if (health.success) return + throw new KubernetesSandboxConfigError( + "The sandbox agent does not speak this Sim release's protocol. Set SANDBOX_K8S_AGENT_IMAGE to the agent image of this release (or unset it to use the default)." + ) + } + await sleep(backoffWithJitter(attempt, null, HEALTH_BACKOFF)) + } +} + +function readSettings(): KubernetesSandboxSettings { + return readKubernetesSandboxSettings(env) +} + +/** + * The Kubernetes sandbox provider: one pod per sandbox, reached over its agent's HTTP API. It + * keeps no per-sandbox state in memory. A pod's labels, its `sim.ai/expires-at` annotation, and a + * token derived from its name are everything a replica needs, so any app replica can reconnect to + * a session, stop its commands, or reap it. + */ +function createKubernetesSandboxProvider(): SandboxProvider { + let opened: { + namespace: string + access: Promise<{ cluster: SandboxCluster; guard: IsolationGuard }> + } | null = null + + function open(settings: KubernetesSandboxSettings) { + if (opened?.namespace === settings.namespace) return opened.access + const access = (async () => { + let config: KubeConfig + try { + config = await loadDefaultKubeConfig() + } catch (error) { + throw new KubernetesSandboxConfigError( + `Could not load Kubernetes API credentials (${getErrorMessage(error)}). Run Sim in the cluster with a service account, or set KUBECONFIG.`, + { cause: error } + ) + } + const cluster = await openSandboxCluster(config, settings.namespace) + return { cluster, guard: new IsolationGuard(cluster) } + })() + const entry = { namespace: settings.namespace, access } + opened = entry + access.catch(() => { + if (opened === entry) opened = null + }) + return access + } + + /** + * Creates the pod, retrying throttling and unanswered requests. A retry after a request that may + * have reached the API server reuses the pod name, so a 409 then is our own pod, recognised by + * its token digest; a 409 on a fresh name is a collision and takes a new one. + */ + async function createPod( + cluster: SandboxCluster, + settings: KubernetesSandboxSettings, + build: (name: string, tokenDigest: string) => V1Pod + ): Promise<{ pod: V1Pod; token: string }> { + let name = newPodName() + let maybeCreated = false + for (let attempt = 1; ; attempt++) { + const token = deriveSandboxAgentToken(settings.tokenSecret, name) + const digest = sandboxAgentTokenDigest(token) + try { + return { pod: await cluster.createPod(build(name, digest)), token } + } catch (error) { + if (!(error instanceof KubernetesApiError)) throw error + const { failure } = error + if (failure.status === 409) { + if (maybeCreated) { + const existing = await cluster.readPod(name) + if (existing && podTokenDigest(existing) === digest) return { pod: existing, token } + } + if (attempt >= MAX_CREATE_ATTEMPTS) throw toPodCreateError(failure, settings.namespace) + name = newPodName() + maybeCreated = false + continue + } + if (attempt >= MAX_CREATE_ATTEMPTS || !isRetryableKubernetesFailure(failure)) { + throw toPodCreateError(failure, settings.namespace) + } + maybeCreated = maybeCreated || failure.status !== 429 + logger.warn('Sandbox pod create failed; retrying', { attempt, status: failure.status }) + await sleep( + backoffWithJitter(attempt, parseRetryAfter(failure.retryAfter ?? null), CREATE_BACKOFF) + ) + } + } + } + + /** Follows the pod with a watch until it runs, then waits for its agent; bounded by `signal`. */ + async function waitUntilReady( + cluster: SandboxCluster, + created: V1Pod, + kind: SandboxKind, + signal: AbortSignal + ): Promise<{ pod: V1Pod; baseUrl: string }> { + const name = created.metadata?.name ?? '' + let pod = created + let detail: string | undefined + try { + for (;;) { + const progress = podProgress(pod, kind) + if (progress.state === 'failed') throw progress.error + if (progress.state === 'ready') { + await waitForAgent(progress.baseUrl, signal) + return { pod, baseUrl: progress.baseUrl } + } + detail = progress.detail + const changed = await cluster.watchPod( + name, + pod.metadata?.resourceVersion, + (update) => { + pod = update + return podProgress(update, kind).state !== 'pending' + }, + signal + ) + if (!changed) { + const latest = await cluster.readPod(name) + if (!latest) throw new Error(`Sandbox pod ${name} was deleted while starting`) + pod = latest + } + } + } catch (error) { + if (!signal.aborted) throw error + const reached = agentBaseUrl(pod) + throw new KubernetesSandboxCapacityError( + reached + ? `Sandbox pod ${name} is running but Sim could not reach its agent at ${reached}. Check that a NetworkPolicy lets Sim's pods reach the sandbox namespace on the agent port.` + : `Sandbox pod ${name} did not start before its create deadline${detail ? ` (${detail})` : ''}. The cluster may be out of capacity for sandboxes.`, + { cause: error } + ) + } + } + + function connect( + cluster: SandboxCluster, + pod: V1Pod, + baseUrl: string, + token: string, + options: { language?: CodeLanguage; session: boolean; fallbackExpiresAtMs: number } + ): SandboxHandle { + const name = pod.metadata?.name ?? '' + const expiresAtMs = podExpiresAtMs(pod) ?? options.fallbackExpiresAtMs + const agent = createAgentSandboxHandle({ + sandboxId: name, + baseUrl, + token, + expiresAtMs, + session: options.session, + ...(options.language ? { language: options.language } : {}), + kill: () => cluster.deletePod(name), + }) + return bindSandboxPod( + agent, + { + name, + expiresAtMs, + hardDeadlineMs: podHardDeadlineMs(pod) ?? Date.now() + SANDBOX_POD_MAX_LIFETIME_MS, + }, + cluster + ) + } + + return { + id: 'kubernetes', + dependencyStrategy: 'runtime', + resolveLifetimeMs: resolveKubernetesSandboxLifetimeMs, + + async create(kind: SandboxKind, options?: CreateSandboxOptions): Promise { + const settings = readSettings() + const image = imageFor(kind, settings, options?.imageRef) + const { cluster, guard } = await open(settings) + await guard.assertIsolated(settings) + + const lifetimeMs = resolveKubernetesSandboxLifetimeMs( + options?.lifetimeMs ?? DEFAULT_SANDBOX_LIFETIME_MS + ) + const requestedAtMs = Date.now() + const expiresAtMs = requestedAtMs + lifetimeMs + const sessionLabel = options?.sessionKey ? sessionLabelValue(options.sessionKey) : undefined + logger.info('Creating Kubernetes sandbox pod', { kind, image, namespace: settings.namespace }) + options?.onProviderRequestStarted?.(requestedAtMs) + const { pod, token } = await createPod(cluster, settings, (name, tokenDigest) => + buildSandboxPod({ + name, + kind, + image, + settings, + tokenDigest, + expiresAtMs, + ...(sessionLabel ? { sessionLabel } : {}), + }) + ) + const name = pod.metadata?.name ?? '' + try { + const ready = await waitUntilReady( + cluster, + pod, + kind, + AbortSignal.timeout(Math.max(1, Math.min(CREATE_TIMEOUT_MS, expiresAtMs - Date.now()))) + ) + return connect(cluster, ready.pod, ready.baseUrl, token, { + ...(options?.language ? { language: options.language } : {}), + session: sessionLabel !== undefined, + fallbackExpiresAtMs: expiresAtMs, + }) + } catch (error) { + await cluster.deletePod(name).catch((deleteError: unknown) => { + logger.warn('Failed to delete a sandbox pod that did not start; the reaper retries', { + name, + error: getErrorMessage(deleteError), + }) + }) + throw error + } + }, + + async findSessionSandbox( + key: string, + options: { language?: CodeLanguage; lifetimeMs?: number } + ): Promise { + const settings = readSettings() + const { cluster } = await open(settings) + const pods = await cluster.listPods( + `${MANAGED_SELECTOR},${SESSION_LABEL}=${sessionLabelValue(key)}` + ) + const pod = selectSessionPod(pods, { + nowMs: Date.now(), + leaseMs: options.lifetimeMs ?? 0, + tokenDigest: (name) => + sandboxAgentTokenDigest(deriveSandboxAgentToken(settings.tokenSecret, name)), + }) + const baseUrl = pod ? agentBaseUrl(pod) : null + if (!pod?.metadata?.name || !baseUrl) return null + return connect( + cluster, + pod, + baseUrl, + deriveSandboxAgentToken(settings.tokenSecret, pod.metadata.name), + { + ...(options.language ? { language: options.language } : {}), + session: true, + fallbackExpiresAtMs: Date.now(), + } + ) + }, + + async stopSessionProcess(process: SessionProcessIdentity, signal: AbortSignal): Promise { + const settings = readSettings() + const { cluster } = await open(settings) + const pod = await cluster.readPod(process.sandboxId) + const baseUrl = pod ? agentBaseUrl(pod) : null + // Only the session's own running pod can still hold the process; anything else is gone. + if ( + !pod || + !baseUrl || + pod.status?.phase !== 'Running' || + pod.metadata?.labels?.[SESSION_LABEL] !== sessionLabelValue(process.sessionKey) + ) { + return + } + const client = new SandboxAgentClient( + baseUrl, + deriveSandboxAgentToken(settings.tokenSecret, process.sandboxId) + ) + try { + await client.request(sandboxAgentProcessSignalPath(process.id), { + method: 'POST', + json: { signal: 'SIGKILL' }, + signal, + retry: true, + }) + } catch (error) { + if (error instanceof SandboxAgentRequestError && error.code === 'not_found') return + throw error + } + }, + + async reapExpiredSandboxes(deadline: AbortSignal) { + const { cluster } = await open(readSettings()) + return reapSandboxPods(cluster, deadline) + }, + } +} + +/** + * The session pod to reconnect to: running, reachable, not past its `sim.ai/expires-at`, able to + * stay up for the requested lease before its hard deadline, and started with the token this + * deployment derives for it (a pod from before a secret rotation can never authenticate). The + * oldest wins, so concurrent creates that raced converge on one pod. + */ +function selectSessionPod( + pods: readonly V1Pod[], + options: { nowMs: number; leaseMs: number; tokenDigest: (podName: string) => string } +): V1Pod | null { + const usable = pods.filter((pod) => { + const name = pod.metadata?.name + if (!name || pod.metadata?.deletionTimestamp || pod.status?.phase !== 'Running') return false + if (!agentBaseUrl(pod)) return false + const expiresAtMs = podExpiresAtMs(pod) + const hardDeadlineMs = podHardDeadlineMs(pod) + if (expiresAtMs === null || expiresAtMs <= options.nowMs) return false + if (hardDeadlineMs === null || hardDeadlineMs < options.nowMs + options.leaseMs) return false + return podTokenDigest(pod) === options.tokenDigest(name) + }) + usable.sort( + (a, b) => + new Date(a.metadata?.creationTimestamp ?? 0).getTime() - + new Date(b.metadata?.creationTimestamp ?? 0).getTime() || + compareStrings(a.metadata?.name ?? '', b.metadata?.name ?? '') + ) + return usable[0] ?? null +} + +/** The provider selected by `SANDBOX_PROVIDER=kubernetes`. Inert until a sandbox is requested. */ +export const kubernetesProvider = createKubernetesSandboxProvider() diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/reaper.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/reaper.ts new file mode 100644 index 00000000000..52187a909c9 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/reaper.ts @@ -0,0 +1,66 @@ +import type { V1Pod } from '@kubernetes/client-node' +import { createLogger } from '@sim/logger' +import { mapSettledWithConcurrency } from '@sim/utils/concurrency' +import { getErrorMessage } from '@sim/utils/errors' +import type { SandboxCluster } from '@/lib/execution/remote-sandbox/kubernetes/cluster' +import { + MANAGED_SELECTOR, + podExpiresAtMs, + podHardDeadlineMs, +} from '@/lib/execution/remote-sandbox/kubernetes/pod' +import type { ExpiredSandboxSweep } from '@/lib/execution/remote-sandbox/types' + +const logger = createLogger('KubernetesSandboxReaper') + +/** + * How long past its recorded deadline a pod is left alone. The agent ends itself at its deadline, + * so a pod still present this long after is orphaned (the app died mid-run, or its kill failed); + * the margin also absorbs clock skew between app replicas. + */ +const SANDBOX_REAP_GRACE_MS = 5 * 60_000 + +const REAP_CONCURRENCY = 8 + +/** + * Sim-managed pods the reaper deletes: those that have finished (`Succeeded` or `Failed`, which + * `restartPolicy: Never` makes final) and those past `sim.ai/expires-at` plus the grace period. + * A pod whose annotation is missing or malformed falls back to its hard deadline, so nothing Sim + * labelled outlives the 24-hour cap by more than the grace period. + */ +function selectReapablePods(pods: readonly V1Pod[], nowMs: number): V1Pod[] { + return pods.filter((pod) => { + if (!pod.metadata?.name || pod.metadata.deletionTimestamp) return false + const phase = pod.status?.phase + if (phase === 'Succeeded' || phase === 'Failed') return true + const deadlineMs = podExpiresAtMs(pod) ?? podHardDeadlineMs(pod) + return deadlineMs !== null && nowMs > deadlineMs + SANDBOX_REAP_GRACE_MS + }) +} + +/** Deletes every reapable sandbox pod in the namespace, stopping new deletes at `deadline`. */ +export async function reapSandboxPods( + cluster: SandboxCluster, + deadline: AbortSignal +): Promise { + const names = selectReapablePods(await cluster.listPods(MANAGED_SELECTOR), Date.now()).flatMap( + (pod) => (pod.metadata?.name ? [pod.metadata.name] : []) + ) + const result: ExpiredSandboxSweep = { deleted: 0, deferred: 0, failed: 0 } + const outcomes = await mapSettledWithConcurrency(names, REAP_CONCURRENCY, async (name) => { + if (deadline.aborted) return 'deferred' as const + await cluster.deletePod(name) + return 'deleted' as const + }) + outcomes.forEach((outcome, index) => { + if (outcome.status === 'fulfilled') { + result[outcome.value]++ + return + } + result.failed++ + logger.warn('Failed to delete an expired sandbox pod; the next sweep retries', { + pod: names[index], + error: getErrorMessage(outcome.reason), + }) + }) + return result +} diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/settings.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/settings.ts new file mode 100644 index 00000000000..e9139e664a0 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/settings.ts @@ -0,0 +1,238 @@ +import type { V1Toleration } from '@kubernetes/client-node' +import { z } from 'zod' +import { type env, isTruthy } from '@/lib/core/config/env' +import { KubernetesSandboxConfigError } from '@/lib/execution/remote-sandbox/kubernetes/errors' +import publishedImages from '@/lib/execution/remote-sandbox/kubernetes/images.generated.json' +import type { SandboxKind } from '@/lib/execution/remote-sandbox/types' + +/** The environment the Kubernetes provider reads; a subset of the app's validated env. */ +type KubernetesSandboxEnv = Pick< + typeof env, + | 'INTERNAL_API_SECRET' + | 'SANDBOX_K8S_NAMESPACE' + | 'SANDBOX_K8S_RUNTIME_CLASS' + | 'SANDBOX_K8S_ALLOW_UNISOLATED' + | 'SANDBOX_K8S_AGENT_IMAGE' + | 'SANDBOX_K8S_FUNCTION_IMAGE' + | 'SANDBOX_K8S_PI_IMAGE' + | 'SANDBOX_K8S_MOTHERSHIP_IMAGE' + | 'SANDBOX_K8S_DOC_IMAGE' + | 'SANDBOX_K8S_CPU' + | 'SANDBOX_K8S_MEMORY' + | 'SANDBOX_K8S_EPHEMERAL_STORAGE' + | 'SANDBOX_K8S_NODE_SELECTOR' + | 'SANDBOX_K8S_TOLERATIONS' + | 'SANDBOX_K8S_IMAGE_PULL_SECRET' +> + +interface KubernetesSandboxResources { + cpu: string + memory: string + ephemeralStorage: string +} + +/** Everything the provider needs to place a sandbox pod, resolved from the environment. */ +export interface KubernetesSandboxSettings { + namespace: string + /** Unset only when {@link allowUnisolated} is true. */ + runtimeClassName?: string + allowUnisolated: boolean + images: { + agent: string + function: string + pi: string + mothership?: string + doc?: string + } + /** Limits; requests are half of each. */ + resources: KubernetesSandboxResources + nodeSelector?: Record + tolerations?: V1Toleration[] + imagePullSecret?: string + /** The app's shared internal secret; sandbox agent tokens are derived from it. */ + tokenSecret: string +} + +const DEFAULT_NAMESPACE = 'sim-sandboxes' +const DEFAULT_RESOURCES: KubernetesSandboxResources = { + cpu: '1', + memory: '2Gi', + ephemeralStorage: '4Gi', +} + +/** Kubernetes resource quantity: a decimal number with an optional SI or binary suffix. */ +const QUANTITY_PATTERN = /^(\d+(?:\.\d+)?)(m|k|M|G|T|P|E|Ki|Mi|Gi|Ti|Pi|Ei)?$/ + +const QUANTITY_MULTIPLIERS: Record = { + '': 1, + m: 1e-3, + k: 1e3, + M: 1e6, + G: 1e9, + T: 1e12, + P: 1e15, + E: 1e18, + Ki: 2 ** 10, + Mi: 2 ** 20, + Gi: 2 ** 30, + Ti: 2 ** 40, + Pi: 2 ** 50, + Ei: 2 ** 60, +} + +const tolerationsSchema = z.array( + z.object({ + key: z.string().optional(), + operator: z.enum(['Exists', 'Equal']).optional(), + value: z.string().optional(), + effect: z.enum(['NoSchedule', 'PreferNoSchedule', 'NoExecute']).optional(), + tolerationSeconds: z.number().int().optional(), + }) +) + +const nodeSelectorSchema = z.record(z.string(), z.string()) + +/** Value of a quantity in its base unit (cores or bytes), or null when it is not one. */ +function quantityValue(quantity: string): number | null { + const match = QUANTITY_PATTERN.exec(quantity) + if (!match) return null + return Number(match[1]) * QUANTITY_MULTIPLIERS[match[2] ?? ''] +} + +/** + * Half of a resource quantity, for the request that pairs with a limit. Whole base units stay + * whole (`2Gi` → `1073741824`); a fraction is expressed in milli-units (`1` → `500m`). + */ +export function halfQuantity(quantity: string): string { + const value = quantityValue(quantity) + if (value === null) throw new Error(`Invalid Kubernetes quantity: ${quantity}`) + const half = value / 2 + return Number.isInteger(half) ? String(half) : `${Math.ceil(half * 1000)}m` +} + +function readQuantity(name: string, value: string | undefined, fallback: string): string { + const quantity = value?.trim() || fallback + const parsed = quantityValue(quantity) + if (parsed === null || parsed <= 0) { + throw new KubernetesSandboxConfigError( + `${name} must be a positive Kubernetes quantity such as ${fallback}, not "${quantity}".` + ) + } + return quantity +} + +function readJson(name: string, value: string | undefined, schema: z.ZodType): T | undefined { + const raw = value?.trim() + if (!raw) return undefined + let parsed: unknown + try { + parsed = JSON.parse(raw) + } catch { + throw new KubernetesSandboxConfigError(`${name} is not valid JSON.`) + } + const result = schema.safeParse(parsed) + if (!result.success) { + throw new KubernetesSandboxConfigError( + `${name} has the wrong shape: ${result.error.issues[0]?.message ?? 'invalid value'}.` + ) + } + return result.data +} + +function optional(value: string | undefined): string | undefined { + return value?.trim() || undefined +} + +/** + * Resolves and validates the provider's settings. Throws {@link KubernetesSandboxConfigError} + * naming the variable to fix, including when no isolating RuntimeClass is set and the operator + * has not opted into shared-kernel sandboxes. + */ +export function readKubernetesSandboxSettings( + values: KubernetesSandboxEnv +): KubernetesSandboxSettings { + const runtimeClassName = optional(values.SANDBOX_K8S_RUNTIME_CLASS) + const allowUnisolated = isTruthy(values.SANDBOX_K8S_ALLOW_UNISOLATED) + if (!runtimeClassName && !allowUnisolated) { + throw new KubernetesSandboxConfigError( + 'Kubernetes sandboxes need an isolating RuntimeClass: set SANDBOX_K8S_RUNTIME_CLASS to a gVisor, Kata, or microVM class. To run untrusted code on the node kernel instead, set SANDBOX_K8S_ALLOW_UNISOLATED=true.' + ) + } + const mothership = optional(values.SANDBOX_K8S_MOTHERSHIP_IMAGE) + const doc = optional(values.SANDBOX_K8S_DOC_IMAGE) + const nodeSelector = readJson( + 'SANDBOX_K8S_NODE_SELECTOR', + values.SANDBOX_K8S_NODE_SELECTOR, + nodeSelectorSchema + ) + const tolerations = readJson( + 'SANDBOX_K8S_TOLERATIONS', + values.SANDBOX_K8S_TOLERATIONS, + tolerationsSchema + ) + const imagePullSecret = optional(values.SANDBOX_K8S_IMAGE_PULL_SECRET) + return { + namespace: optional(values.SANDBOX_K8S_NAMESPACE) ?? DEFAULT_NAMESPACE, + ...(runtimeClassName ? { runtimeClassName } : {}), + allowUnisolated, + images: { + agent: optional(values.SANDBOX_K8S_AGENT_IMAGE) ?? publishedImages.agent, + function: optional(values.SANDBOX_K8S_FUNCTION_IMAGE) ?? publishedImages.function, + pi: optional(values.SANDBOX_K8S_PI_IMAGE) ?? publishedImages.pi, + ...(mothership ? { mothership } : {}), + ...(doc ? { doc } : {}), + }, + resources: { + cpu: readQuantity('SANDBOX_K8S_CPU', values.SANDBOX_K8S_CPU, DEFAULT_RESOURCES.cpu), + memory: readQuantity( + 'SANDBOX_K8S_MEMORY', + values.SANDBOX_K8S_MEMORY, + DEFAULT_RESOURCES.memory + ), + ephemeralStorage: readQuantity( + 'SANDBOX_K8S_EPHEMERAL_STORAGE', + values.SANDBOX_K8S_EPHEMERAL_STORAGE, + DEFAULT_RESOURCES.ephemeralStorage + ), + }, + ...(nodeSelector ? { nodeSelector } : {}), + ...(tolerations ? { tolerations } : {}), + ...(imagePullSecret ? { imagePullSecret } : {}), + tokenSecret: values.INTERNAL_API_SECRET, + } +} + +/** The env var that sets each kind's image, for operator-facing errors. */ +const IMAGE_VARIABLE: Record = { + code: 'SANDBOX_K8S_FUNCTION_IMAGE', + shell: 'SANDBOX_K8S_FUNCTION_IMAGE', + pi: 'SANDBOX_K8S_PI_IMAGE', + mothership: 'SANDBOX_K8S_MOTHERSHIP_IMAGE', + doc: 'SANDBOX_K8S_DOC_IMAGE', +} + +/** Names the variable that sets `kind`'s image, so a failed pull can say what to fix. */ +export function imageVariableFor(kind: SandboxKind): string { + return IMAGE_VARIABLE[kind] +} + +/** + * The image a sandbox of `kind` runs. `code` and `shell` share the Function image, and only they + * accept a caller's `imageRef`: Mothership, doc, and Pi keep their vetted images unconditionally. + * Mothership and doc have no published default, so an unset image fails closed. + */ +export function imageFor( + kind: SandboxKind, + settings: KubernetesSandboxSettings, + imageRef?: string +): string { + if (kind === 'code' || kind === 'shell') return imageRef ?? settings.images.function + if (kind === 'pi') return settings.images.pi + const image = settings.images[kind] + if (!image) { + throw new KubernetesSandboxConfigError( + `The ${kind === 'doc' ? 'document compiler' : 'Mothership'} sandbox is not configured on Kubernetes (${IMAGE_VARIABLE[kind]} is unset).` + ) + } + return image +} diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/token.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/token.ts new file mode 100644 index 00000000000..f8f65ac59b1 --- /dev/null +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/token.ts @@ -0,0 +1,29 @@ +import { createHash, hkdfSync } from 'node:crypto' + +const TOKEN_INFO = 'sim/sandbox-agent/v1' +const TOKEN_BYTES = 32 + +/** + * The bearer token for the agent in pod `podName`: HKDF-SHA256 over the app's internal secret, + * salted with the pod name. Every app replica derives the same token for the same pod, so any of + * them can reconnect without the token being stored anywhere; the pod only ever holds its digest. + * The name is the salt (rather than the UID) because it is chosen before the pod exists. + */ +export function deriveSandboxAgentToken(secret: string, podName: string): string { + return Buffer.from(hkdfSync('sha256', secret, podName, TOKEN_INFO, TOKEN_BYTES)).toString( + 'base64url' + ) +} + +/** Hex SHA-256 of a token, the form the agent receives in its environment. */ +export function sandboxAgentTokenDigest(token: string): string { + return createHash('sha256').update(token, 'utf8').digest('hex') +} + +/** + * The value of a pod's `sim.ai/session` label: a fixed-length digest of the session key, so the + * key itself never appears in cluster metadata and always fits a label value. + */ +export function sessionLabelValue(sessionKey: string): string { + return createHash('sha256').update(sessionKey, 'utf8').digest('hex').slice(0, 40) +} diff --git a/apps/sim/lib/execution/remote-sandbox/pi-lifetime.ts b/apps/sim/lib/execution/remote-sandbox/pi-lifetime.ts index d56d627d696..3c08316e8ac 100644 --- a/apps/sim/lib/execution/remote-sandbox/pi-lifetime.ts +++ b/apps/sim/lib/execution/remote-sandbox/pi-lifetime.ts @@ -19,6 +19,8 @@ const logger = createLogger('PiSandboxLifetime') const PROVIDER_SANDBOX_LIFETIME_LIMIT_MS: Record = { e2b: 24 * 60 * 60 * 1000, daytona: null, + // The pod's `activeDeadlineSeconds`, set at create and never raised. + kubernetes: 24 * 60 * 60 * 1000, } /** diff --git a/apps/sim/lib/execution/remote-sandbox/provider.ts b/apps/sim/lib/execution/remote-sandbox/provider.ts index 8eebe70aa9d..27a348cd9e7 100644 --- a/apps/sim/lib/execution/remote-sandbox/provider.ts +++ b/apps/sim/lib/execution/remote-sandbox/provider.ts @@ -1,6 +1,7 @@ import { getSelectedSandboxProviderId } from '@/lib/core/config/env-capabilities.server' import { daytonaProvider } from '@/lib/execution/remote-sandbox/daytona' import { e2bProvider } from '@/lib/execution/remote-sandbox/e2b' +import { kubernetesProvider } from '@/lib/execution/remote-sandbox/kubernetes/provider' import type { SandboxProvider, SandboxProviderId } from '@/lib/execution/remote-sandbox/types' /** @@ -11,6 +12,7 @@ import type { SandboxProvider, SandboxProviderId } from '@/lib/execution/remote- const PROVIDERS: Record = { e2b: e2bProvider, daytona: daytonaProvider, + kubernetes: kubernetesProvider, } /** diff --git a/apps/sim/lib/execution/remote-sandbox/types.ts b/apps/sim/lib/execution/remote-sandbox/types.ts index 2e62e611551..169d3c2cc47 100644 --- a/apps/sim/lib/execution/remote-sandbox/types.ts +++ b/apps/sim/lib/execution/remote-sandbox/types.ts @@ -524,6 +524,20 @@ export interface SandboxProvider { * record session processes omit it. */ stopSessionProcess?(process: SessionProcessIdentity, signal: AbortSignal): Promise + /** + * Deletes sandboxes the provider itself would never end: finished ones it keeps around, and + * ones past their recorded deadline whose owner died before killing them. Starts no delete after + * `deadline` aborts. Providers that reap their own sandboxes omit it. + */ + reapExpiredSandboxes?(deadline: AbortSignal): Promise +} + +/** Outcome of one {@link SandboxProvider.reapExpiredSandboxes} sweep. */ +export interface ExpiredSandboxSweep { + deleted: number + /** Left for the next sweep because the deadline passed first. */ + deferred: number + failed: number } export interface PausedSessionSandbox { diff --git a/apps/sim/next.config.ts b/apps/sim/next.config.ts index 9abe44dad66..b1bec1f536e 100644 --- a/apps/sim/next.config.ts +++ b/apps/sim/next.config.ts @@ -82,6 +82,7 @@ const nextConfig: NextConfig = { '@e2b/code-interpreter', 'e2b', '@daytona/sdk', + '@kubernetes/client-node', '@earendil-works/pi-ai', '@earendil-works/pi-coding-agent', /** diff --git a/apps/sim/package.json b/apps/sim/package.json index f2d667339dc..ca9f9c31ce9 100644 --- a/apps/sim/package.json +++ b/apps/sim/package.json @@ -124,6 +124,7 @@ "@google-cloud/storage": "7.22.0", "@google/genai": "2.32.0", "@hookform/resolvers": "5.9.1", + "@kubernetes/client-node": "2.0.2", "@linear/sdk": "97.1.0", "@marsidev/react-turnstile": "1.6.3", "@modelcontextprotocol/sdk": "1.32.2", diff --git a/apps/sim/trigger.config.ts b/apps/sim/trigger.config.ts index 5e7a2aed5f8..3c402e7f37f 100644 --- a/apps/sim/trigger.config.ts +++ b/apps/sim/trigger.config.ts @@ -63,6 +63,18 @@ const FUNCTION_EXECUTION_ENV = [ { name: 'DAYTONA_API_KEY', secret: true }, { name: 'DAYTONA_FUNCTION_SNAPSHOT_ID', secret: false }, { name: 'DAYTONA_DOC_SNAPSHOT_ID', secret: false }, + { name: 'SANDBOX_K8S_NAMESPACE', secret: false }, + { name: 'SANDBOX_K8S_RUNTIME_CLASS', secret: false }, + { name: 'SANDBOX_K8S_ALLOW_UNISOLATED', secret: false }, + { name: 'SANDBOX_K8S_AGENT_IMAGE', secret: false }, + { name: 'SANDBOX_K8S_FUNCTION_IMAGE', secret: false }, + { name: 'SANDBOX_K8S_DOC_IMAGE', secret: false }, + { name: 'SANDBOX_K8S_CPU', secret: false }, + { name: 'SANDBOX_K8S_MEMORY', secret: false }, + { name: 'SANDBOX_K8S_EPHEMERAL_STORAGE', secret: false }, + { name: 'SANDBOX_K8S_NODE_SELECTOR', secret: false }, + { name: 'SANDBOX_K8S_TOLERATIONS', secret: false }, + { name: 'SANDBOX_K8S_IMAGE_PULL_SECRET', secret: false }, { name: 'S3_COPILOT_BUCKET_NAME', secret: false }, { name: 'AZURE_STORAGE_COPILOT_CONTAINER_NAME', secret: false }, { name: 'GCS_COPILOT_BUCKET_NAME', secret: false }, @@ -245,6 +257,8 @@ export default defineConfig({ 'e2b', '@e2b/code-interpreter', '@daytona/sdk', + // ESM-only; loaded lazily by the Kubernetes sandbox provider. + '@kubernetes/client-node', // pdf.js resolves its worker via a runtime-relative dynamic import that // breaks inside the worker bundle; it must load from node_modules. 'pdfjs-dist', @@ -282,6 +296,7 @@ export default defineConfig({ '@earendil-works/pi-coding-agent', '@e2b/code-interpreter', '@daytona/sdk', + '@kubernetes/client-node', 'pdfjs-dist', '@napi-rs/canvas', 'sharp', diff --git a/bun.lock b/bun.lock index 5f9c86c2bf0..0bb0bcf26e6 100644 --- a/bun.lock +++ b/bun.lock @@ -285,6 +285,7 @@ "@google-cloud/storage": "7.22.0", "@google/genai": "2.32.0", "@hookform/resolvers": "5.9.1", + "@kubernetes/client-node": "2.0.2", "@linear/sdk": "97.1.0", "@marsidev/react-turnstile": "1.6.3", "@modelcontextprotocol/sdk": "1.32.2", @@ -1630,8 +1631,14 @@ "@js-sdsl/ordered-map": ["@js-sdsl/ordered-map@4.4.2", "", {}, "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw=="], + "@jsep-plugin/assignment": ["@jsep-plugin/assignment@1.4.0", "", { "peerDependencies": { "jsep": "^0.4.0||^1.0.0" } }, "sha512-nw2Px23Eirx0PFTVoPrb3FEq9Wkmg6vxcDtt38MtBCf1G0tjLCB9cK+3seOXyiw+6+aalgYhvJabQbWwMVKlEQ=="], + + "@jsep-plugin/regex": ["@jsep-plugin/regex@1.1.0", "", { "peerDependencies": { "jsep": "^0.4.0||^1.0.0" } }, "sha512-2Vkbda+XRjK6VTI6Lrh0sNBuMT8mZ51EhqMvO+V2rSdmqjs7NAGssxPZfkL23EFzYfSrvxyd1ZjOdqPQMM50og=="], + "@jsonhero/path": ["@jsonhero/path@1.0.21", "", {}, "sha512-gVUDj/92acpVoJwsVJ/RuWOaHyG4oFzn898WNGQItLCTQ+hOaVlEaImhwE1WqOTf+l3dGOUkbSiVKlb3q1hd1Q=="], + "@kubernetes/client-node": ["@kubernetes/client-node@2.0.2", "", { "dependencies": { "@types/js-yaml": "^4.0.1", "@types/node": "^26.0.0", "@types/stream-buffers": "^3.0.3", "form-data": "^4.0.0", "hpagent": "^1.2.0", "isomorphic-ws": "^5.0.0", "js-yaml": "^5.1.0", "jsonpath-plus": "^10.3.0", "openid-client": "^6.1.3", "rfc4648": "^1.3.0", "socks": "^2.8.4", "socks-proxy-agent": "^10.0.0", "stream-buffers": "^3.0.2", "tar-fs": "^3.0.9", "undici": "^8.7.0", "ws": "^8.18.2" } }, "sha512-AvVq87luFXIoo95dkBsNnzU6pIwKGJM5CZD/iLfxMPXPzVa4w8isIMvXmYly+4TkodQFf3fQzX3KDysVy1OYng=="], + "@linear/sdk": ["@linear/sdk@97.1.0", "", { "dependencies": { "@graphql-typed-document-node/core": "^3.2.0" } }, "sha512-HPk0zY8+SAOEoUEPxZZgqTU7xpNJ5BYcN3grngaWsesecaGMUrn2bzhmWtsQ0jOtTvLImZKHxgiL3hqEjb6oig=="], "@lydell/node-pty": ["@lydell/node-pty@1.2.0-beta.12", "", { "optionalDependencies": { "@lydell/node-pty-darwin-arm64": "1.2.0-beta.12", "@lydell/node-pty-darwin-x64": "1.2.0-beta.12", "@lydell/node-pty-linux-arm64": "1.2.0-beta.12", "@lydell/node-pty-linux-x64": "1.2.0-beta.12", "@lydell/node-pty-win32-arm64": "1.2.0-beta.12", "@lydell/node-pty-win32-x64": "1.2.0-beta.12" } }, "sha512-qIK890UwPupoj07osVvgOIa++1mxeHbcGry4PKRHhNVNs81V2SCG34eJr46GybiOmBtc8Sj5PB1/GGM5PL549g=="], @@ -2532,6 +2539,8 @@ "@types/ssh2": ["@types/ssh2@1.15.6", "", { "dependencies": { "@types/node": "^18.11.18" } }, "sha512-oGdxhBqcRTwSTKFm+9EiKzkNVYRLEFkcW44lhguvBalGJbWfGnDt/ezwSUZc+SF9m9bMc3VyklNAtp7zICjS5w=="], + "@types/stream-buffers": ["@types/stream-buffers@3.0.8", "", { "dependencies": { "@types/node": "*" } }, "sha512-J+7VaHKNvlNPJPEJXX/fKa9DZtR/xPMwuIbe+yNOwp1YB+ApUOBv2aUpEoBJEi8nJgbgs1x8e73ttg0r1rSUdw=="], + "@types/tough-cookie": ["@types/tough-cookie@4.0.5", "", {}, "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA=="], "@types/trusted-types": ["@types/trusted-types@2.0.7", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="], @@ -3442,6 +3451,8 @@ "hosted-git-info": ["hosted-git-info@9.0.3", "", { "dependencies": { "lru-cache": "^11.1.0" } }, "sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg=="], + "hpagent": ["hpagent@1.2.0", "", {}, "sha512-A91dYTeIB6NoXG+PxTQpCCDDnfHsW9kc06Lvpu1TEe9gnd6ZFeiBoRO9JvzEv6xK7EX97/dUE8g/vBMTqTS3CA=="], + "html-encoding-sniffer": ["html-encoding-sniffer@4.0.0", "", { "dependencies": { "whatwg-encoding": "^3.1.1" } }, "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ=="], "html-entities": ["html-entities@2.6.0", "", {}, "sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ=="], @@ -3578,6 +3589,8 @@ "jsdom": ["jsdom@26.1.0", "", { "dependencies": { "cssstyle": "^4.2.1", "data-urls": "^5.0.0", "decimal.js": "^10.5.0", "html-encoding-sniffer": "^4.0.0", "http-proxy-agent": "^7.0.2", "https-proxy-agent": "^7.0.6", "is-potential-custom-element-name": "^1.0.1", "nwsapi": "^2.2.16", "parse5": "^7.2.1", "rrweb-cssom": "^0.8.0", "saxes": "^6.0.0", "symbol-tree": "^3.2.4", "tough-cookie": "^5.1.1", "w3c-xmlserializer": "^5.0.0", "webidl-conversions": "^7.0.0", "whatwg-encoding": "^3.1.1", "whatwg-mimetype": "^4.0.0", "whatwg-url": "^14.1.1", "ws": "^8.18.0", "xml-name-validator": "^5.0.0" }, "peerDependencies": { "canvas": "^3.0.0" }, "optionalPeers": ["canvas"] }, "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg=="], + "jsep": ["jsep@1.6.0", "", {}, "sha512-Y8Tr54CX7B5YGAwo7/n8eumidEX3Opx98RyyQVnlHqUaZcPA8uUzL2v1rshr9ypW9Q6hNjfJtg3sL+8kaNE7TA=="], + "jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="], "json-bigint": ["json-bigint@1.0.0", "", { "dependencies": { "bignumber.js": "^9.0.0" } }, "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ=="], @@ -3600,6 +3613,8 @@ "jsonfile": ["jsonfile@6.2.1", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="], + "jsonpath-plus": ["jsonpath-plus@10.4.0", "", { "dependencies": { "@jsep-plugin/assignment": "^1.3.0", "@jsep-plugin/regex": "^1.0.4", "jsep": "^1.4.0" }, "bin": { "jsonpath": "bin/jsonpath-cli.js", "jsonpath-plus": "bin/jsonpath-cli.js" } }, "sha512-T92WWatJXmhBbKsgH/0hl+jxjdXrifi5IKeMY02DWggRxX0UElcbVzPlmgLTbvsPeW1PasQ6xE2Q75stkhGbsA=="], + "jsonwebtoken": ["jsonwebtoken@9.0.3", "", { "dependencies": { "jws": "^4.0.1", "lodash.includes": "^4.3.0", "lodash.isboolean": "^3.0.3", "lodash.isinteger": "^4.0.4", "lodash.isnumber": "^3.0.3", "lodash.isplainobject": "^4.0.6", "lodash.isstring": "^4.0.1", "lodash.once": "^4.0.0", "ms": "^2.1.1", "semver": "^7.5.4" } }, "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g=="], "jszip": ["jszip@3.10.2", "", { "dependencies": { "lie": "~3.3.0", "pako": "~1.0.2", "readable-stream": "~2.3.6", "setimmediate": "^1.0.5" } }, "sha512-3l+rb15IOWtUhU0H5MFqES/T6Kh7abYwjosBey/vD6hDt8zoEffkSC5Ws5SGtgVw3gBx2NEbhTeSW1+kWkpyTQ=="], @@ -3978,6 +3993,8 @@ "nypm": ["nypm@0.6.6", "", { "dependencies": { "citty": "^0.2.2", "pathe": "^2.0.3", "tinyexec": "^1.1.1" }, "bin": { "nypm": "dist/cli.mjs" } }, "sha512-vRyr0r4cbBapw07Xw8xrj9Teq3o7MUD35rSaTcanDbW+aK2XHDgJFiU6ZTj2GBw7Q12ysdsyFss+Vdz4hQ0Y6Q=="], + "oauth4webapi": ["oauth4webapi@3.8.9", "", {}, "sha512-gyn4jpaxyYFm1epl3mwqc1sFShLjT9eq/63JW+Nvk286Lz6FC72pVv/SyhJHxo+sQiHEcjIHs4TtFKX/+Md07A=="], + "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], "object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="], @@ -4014,6 +4031,8 @@ "openapi-typescript-helpers": ["openapi-typescript-helpers@0.1.0", "", {}, "sha512-OKTGPthhivLw/fHz6c3OPtg72vi86qaMlqbJuVJ23qOvQ+53uw1n7HdmkJFibloF7QEjDrDkzJiOJuockM/ljw=="], + "openid-client": ["openid-client@6.9.1", "", { "dependencies": { "jose": "^6.2.18", "oauth4webapi": "^3.8.9" } }, "sha512-wysSRjtNRRpu1S/HCVaQ7LRPSNc42lhS1szB1SihVTcA2kAarpzKyvAd+sjFX41ky7iDblGerORC8ASwpt3zqA=="], + "opentype.js": ["opentype.js@1.3.4", "", { "dependencies": { "string.prototype.codepointat": "^0.2.1", "tiny-inflate": "^1.0.3" }, "bin": { "ot": "bin/ot" } }, "sha512-d2JE9RP/6uagpQAVtJoF0pJJA/fgai89Cc50Yp0EJHk+eLp6QQ7gBoblsnubRULNY132I0J1QKMJ+JTbMqz4sw=="], "option": ["option@0.2.4", "", {}, "sha512-pkEqbDyl8ou5cpq+VsnQbe/WlEy5qS7xPzMS1U55OCG9KPvwFD46zDbxQIj3egJSFc3D+XhYOPUzz49zQAVy7A=="], @@ -4334,6 +4353,8 @@ "retry-request": ["retry-request@7.0.2", "", { "dependencies": { "@types/request": "^2.48.8", "extend": "^3.0.2", "teeny-request": "^9.0.0" } }, "sha512-dUOvLMJ0/JJYEn8NrpOaGNE7X3vpI5XlZS/u0ANjqtcZVKnIxP7IgCFwrKTxENw29emmwug53awKtaMm4i9g5w=="], + "rfc4648": ["rfc4648@1.5.4", "", {}, "sha512-rRg/6Lb+IGfJqO05HZkN50UtY7K/JhxJag1kP23+zyMfrvoB0B7RWv06MbOzoc79RgCdNTiUaNsTT1AJZ7Z+cg=="], + "rfdc": ["rfdc@1.4.1", "", {}, "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA=="], "rimraf": ["rimraf@2.6.3", "", { "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "./bin.js" } }, "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA=="], @@ -4450,6 +4471,8 @@ "socks": ["socks@2.8.9", "", { "dependencies": { "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" } }, "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw=="], + "socks-proxy-agent": ["socks-proxy-agent@10.1.0", "", { "dependencies": { "agent-base": "9.0.0", "debug": "^4.3.4", "socks": "^2.8.3" } }, "sha512-WlMj/67cEJ6MDI1OcsnjuYKDNDoyPCCYZ249kuuXPiMDw9F8PXkVaQ7YWu3siTydfQ/4BEZcvGzu+aYvz7dDCQ=="], + "sonic-boom": ["sonic-boom@4.2.1", "", { "dependencies": { "atomic-sleep": "^1.0.0" } }, "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q=="], "source-map": ["source-map@0.7.6", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="], @@ -4482,6 +4505,8 @@ "stream-browserify": ["stream-browserify@3.0.0", "", { "dependencies": { "inherits": "~2.0.4", "readable-stream": "^3.5.0" } }, "sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA=="], + "stream-buffers": ["stream-buffers@3.0.3", "", {}, "sha512-pqMqwQCso0PBJt2PQmDO0cFj0lyqmiwOMiMSkVtRokl7e+ZTRYgDHKnuZNbqjiJXgsg4nuqtD/zxuo9KqTp0Yw=="], + "stream-events": ["stream-events@1.0.5", "", { "dependencies": { "stubs": "^3.0.0" } }, "sha512-E1GUzBSgvct8Jsb3v2X15pjzN1tYebtbLaMg+eBOUOAxgbLoSbT2NS91ckc5lJD1KfLjId+jXJRgo0qnV5Nerg=="], "stream-shift": ["stream-shift@1.0.3", "", {}, "sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ=="], @@ -4552,6 +4577,8 @@ "tar": ["tar@7.5.22", "", { "dependencies": { "@isaacs/fs-minipass": "^4.0.0", "chownr": "^3.0.0", "minipass": "^7.1.2", "minizlib": "^3.1.0", "yallist": "^5.0.0" } }, "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA=="], + "tar-fs": ["tar-fs@3.1.4", "", { "dependencies": { "pump": "^3.0.0", "tar-stream": "^3.3.0" }, "optionalDependencies": { "bare-fs": "^4.0.1", "bare-path": "^3.0.0" } }, "sha512-S0lrlrJkynj6otwBGsd+1YHWvbgac42+LeHavSzgokehNdiRg1D4eGFDi1cceiG1fQlSTnnss+agdRQl5Bb1DA=="], + "tar-stream": ["tar-stream@3.2.0", "", { "dependencies": { "b4a": "^1.6.4", "bare-fs": "^4.5.5", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, "sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg=="], "tarn": ["tarn@3.1.2", "", {}, "sha512-3RTvqKZcK/17jnJ8rMKFXbyNogywTs1z0gVPPwFsJGX46rkmUHOdIaSQ/aVO1rS7nH+soiXiWk7rvUXxndm8Dg=="], @@ -5088,6 +5115,12 @@ "@jridgewell/trace-mapping/@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="], + "@kubernetes/client-node/@types/node": ["@types/node@26.6.6", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="], + + "@kubernetes/client-node/js-yaml": ["js-yaml@5.5.0", "", { "dependencies": { "argparse": "^3.0.3" }, "bin": { "js-yaml": "bin/js-yaml.mjs" } }, "sha512-paNr4LFIFPjeeSmwNYdrb8FafLLG/Cr2Af3GjbsHJ5CxIjH4r0c2emlmRdAtpPAieP1gRVzk6buBbVP5gBMGAg=="], + + "@kubernetes/client-node/undici": ["undici@8.12.3", "", {}, "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw=="], + "@octokit/plugin-paginate-rest/@octokit/types": ["@octokit/types@16.0.0", "", { "dependencies": { "@octokit/openapi-types": "^27.0.0" } }, "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg=="], "@octokit/plugin-rest-endpoint-methods/@octokit/types": ["@octokit/types@16.0.0", "", { "dependencies": { "@octokit/openapi-types": "^27.0.0" } }, "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg=="], @@ -5236,6 +5269,8 @@ "@types/ssh2/@types/node": ["@types/node@18.19.130", "", { "dependencies": { "undici-types": "~5.26.4" } }, "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg=="], + "@types/stream-buffers/@types/node": ["@types/node@26.6.6", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="], + "@types/ws/@types/node": ["@types/node@25.9.3", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-603BddQMv3pUcr4U2dhujk83N2tTDVr/34wII2B6bJy6g+8WD6yUb11jszNs0gdi4PesVWl7ABt8nYMVpnLUcg=="], "@types/yauzl/@types/node": ["@types/node@25.9.3", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-603BddQMv3pUcr4U2dhujk83N2tTDVr/34wII2B6bJy6g+8WD6yUb11jszNs0gdi4PesVWl7ABt8nYMVpnLUcg=="], @@ -5452,6 +5487,8 @@ "nypm/tinyexec": ["tinyexec@1.2.4", "", {}, "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg=="], + "openid-client/jose": ["jose@6.2.18", "", {}, "sha512-doV4thUwgkrycJH4yLeqwTGIIZphHl+pk7CPReuMIhYhncmgzdko85MaCG4YQFTxqMFr1/oEH32tZuKKovcDEg=="], + "p-retry/retry": ["retry@0.13.1", "", {}, "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg=="], "parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="], @@ -5518,6 +5555,8 @@ "slice-ansi/is-fullwidth-code-point": ["is-fullwidth-code-point@5.1.0", "", { "dependencies": { "get-east-asian-width": "^1.3.1" } }, "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ=="], + "socks-proxy-agent/agent-base": ["agent-base@9.0.0", "", {}, "sha512-TQf59BsZnytt8GdJKLPfUZ54g/iaUL2OWDSFCCvMOhsHduDQxO8xC4PNeyIkVcA5KwL2phPSv0douC0fgWzmnA=="], + "source-map-support/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], "stream-browserify/readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], @@ -5528,6 +5567,8 @@ "sucrase/commander": ["commander@4.1.1", "", {}, "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA=="], + "tar-fs/tar-stream": ["tar-stream@3.3.0", "", { "dependencies": { "b4a": "^1.9.0", "bare-fs": "^4.8.2", "fast-fifo": "^1.3.2", "streamx": "^2.28.1" } }, "sha512-rQZZfW2Q4YDCFJyP8KFDG+gfMzcOHaMYq0gb9jzH2gsK0P5qXVpu+UoKE1qaZcs3/R6QVkJr2228nlZoM1V5PA=="], + "tedious/@types/node": ["@types/node@25.9.3", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-603BddQMv3pUcr4U2dhujk83N2tTDVr/34wII2B6bJy6g+8WD6yUb11jszNs0gdi4PesVWl7ABt8nYMVpnLUcg=="], "tedious/iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="], @@ -5692,6 +5733,10 @@ "@img/sharp-wasm32/@emnapi/runtime/tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + "@kubernetes/client-node/@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + + "@kubernetes/client-node/js-yaml/argparse": ["argparse@3.0.4", "", {}, "sha512-fwWK3Zq22l4XJJjx5mcBHGikIk+hJqO+32dPm0Jur7+rtG5x1scOjSfdT9ZKeWHPpsya/l0HHK4tDImBkTrtvA=="], + "@octokit/plugin-paginate-rest/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@27.0.0", "", {}, "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA=="], "@octokit/plugin-rest-endpoint-methods/@octokit/types/@octokit/openapi-types": ["@octokit/openapi-types@27.0.0", "", {}, "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA=="], @@ -5722,6 +5767,8 @@ "@types/ssh2/@types/node/undici-types": ["undici-types@5.26.5", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="], + "@types/stream-buffers/@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + "@useblacksmith/vitest/oxc-parser/@oxc-parser/binding-android-arm-eabi": ["@oxc-parser/binding-android-arm-eabi@0.159.0", "", { "os": "android", "cpu": "arm" }, "sha512-9/yHxYVeyVzS3CEilO17axbtudUEmySuCL5x4nRz63nld21u4sdxXNhAOLeLCw/c8puAu9RmMb1+FWpq6jJYeQ=="], "@useblacksmith/vitest/oxc-parser/@oxc-parser/binding-android-arm64": ["@oxc-parser/binding-android-arm64@0.159.0", "", { "os": "android", "cpu": "arm64" }, "sha512-w9/NlA/feGMweV8DD1yzNwRAgusdGawCxqK+p3bVhDhXDeg8ahIeJxK/iVTOSA8s4dcnRS8hZYumznAFiKMf5Q=="], @@ -5938,6 +5985,12 @@ "style-to-js/style-to-object/inline-style-parser": ["inline-style-parser@0.2.7", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="], + "tar-fs/tar-stream/b4a": ["b4a@1.9.0", "", { "peerDependencies": { "react-native-b4a": "*" }, "optionalPeers": ["react-native-b4a"] }, "sha512-dpfcF9fDNR6++cthXR67iyhgqWy9CBouAvIWhIntzBG6cvK/cnIPiZQjBwi/ZqjjBEDGfoNDtmB0kTjroOJ3pQ=="], + + "tar-fs/tar-stream/bare-fs": ["bare-fs@4.8.7", "", { "dependencies": { "bare-events": "^2.5.4", "bare-path": "^3.0.0", "bare-stream": "^2.6.4", "bare-url": "^2.2.2", "fast-fifo": "^1.3.2" }, "peerDependencies": { "bare-buffer": "*" }, "optionalPeers": ["bare-buffer"] }, "sha512-bNBjq+x9Wezp3risJs7TaPH3jjVnyFmmSSxfpES8tp9xjvL4t6Bk9v2nC+xm5lfxJeDzChK7NBryK+JciM/pfQ=="], + + "tar-fs/tar-stream/streamx": ["streamx@2.28.1", "", { "dependencies": { "events-universal": "^1.0.0", "fast-fifo": "^1.3.2", "text-decoder": "^1.1.0" } }, "sha512-zEzXb0s5Cds7tqMH6rhZ05lcJydCWiQPEwiNngVqzsxCc962vLY4Uw+mW7od8kDH258k2Uz/JrOkdIAAhSh9VA=="], + "teeny-request/http-proxy-agent/agent-base": ["agent-base@6.0.2", "", { "dependencies": { "debug": "4" } }, "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ=="], "teeny-request/https-proxy-agent/agent-base": ["agent-base@6.0.2", "", { "dependencies": { "debug": "4" } }, "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ=="], diff --git a/packages/deployment-config/src/env-capabilities.ts b/packages/deployment-config/src/env-capabilities.ts index d684121fccd..31b70e23c2f 100644 --- a/packages/deployment-config/src/env-capabilities.ts +++ b/packages/deployment-config/src/env-capabilities.ts @@ -1118,6 +1118,44 @@ export const SANDBOX_CAPABILITY = defineCapability({ }) ), }, + { + id: 'kubernetes', + label: 'Kubernetes', + activation: { + mode: 'any-present', + keys: ['SANDBOX_K8S_RUNTIME_CLASS', 'SANDBOX_K8S_ALLOW_UNISOLATED'], + }, + // Fails closed on isolation: a sandbox pod needs an isolating RuntimeClass (gVisor, Kata, + // a microVM) unless the operator explicitly accepts sharing the node kernel. Every image + // the Function and Pi kinds need defaults to the release's published refs. + requires: anyOf( + envField('SANDBOX_K8S_RUNTIME_CLASS'), + envField('SANDBOX_K8S_ALLOW_UNISOLATED', { + validation: { + kind: 'pattern', + pattern: /^(?:true|1)$/i, + message: 'must be true to run sandboxes without SANDBOX_K8S_RUNTIME_CLASS', + }, + }) + ), + optionalFields: [ + envField('SANDBOX_K8S_NAMESPACE'), + envField('SANDBOX_K8S_AGENT_IMAGE'), + envField('SANDBOX_K8S_FUNCTION_IMAGE'), + envField('SANDBOX_K8S_PI_IMAGE'), + envField('SANDBOX_K8S_CPU'), + envField('SANDBOX_K8S_MEMORY'), + envField('SANDBOX_K8S_EPHEMERAL_STORAGE'), + envField('SANDBOX_K8S_NODE_SELECTOR', { + validation: { + kind: 'json-object', + message: 'must be a JSON object of node label keys to values', + }, + }), + envField('SANDBOX_K8S_TOLERATIONS'), + envField('SANDBOX_K8S_IMAGE_PULL_SECRET'), + ], + }, ], } as const) @@ -1136,7 +1174,9 @@ type DedicatedSandboxImageKind = 'mothership' | 'doc' | 'pi' * * E2B's Pi entry is empty on purpose: Pi cloud has always shown whenever E2B is * enabled, and the adapter reports a missing `E2B_PI_TEMPLATE_ID` when the - * sandbox is created. + * sandbox is created. Kubernetes's is empty because its Pi image defaults to the + * release's published ref; Mothership and doc images are private, so they have + * no default. */ /** * `unknown` when `SANDBOX_PROVIDER_IDS` (which validates `SANDBOX_PROVIDER` and types the @@ -1162,6 +1202,11 @@ const SANDBOX_IMAGE_KIND_REQUIREMENTS = { doc: allOf(envField('DAYTONA_API_KEY'), envField('DAYTONA_DOC_SNAPSHOT_ID')), pi: allOf(envField('DAYTONA_API_KEY'), envField('DAYTONA_PI_SNAPSHOT_ID')), }, + kubernetes: { + mothership: envField('SANDBOX_K8S_MOTHERSHIP_IMAGE'), + doc: envField('SANDBOX_K8S_DOC_IMAGE'), + pi: allOf(), + }, } as const satisfies Record< DeclaredProviderId, Record diff --git a/packages/sim-setup/src/capability-config.ts b/packages/sim-setup/src/capability-config.ts index 720642f58cb..88c21929d71 100644 --- a/packages/sim-setup/src/capability-config.ts +++ b/packages/sim-setup/src/capability-config.ts @@ -605,6 +605,106 @@ export const SANDBOX_SETUP = defineCapabilitySetup(SANDBOX_CAPABILITY, { }, ], }, + kubernetes: { + hint: 'sandbox pods in your own cluster, isolated by a RuntimeClass', + prompts: [ + { + type: 'choice', + id: 'kubernetes-isolation', + message: 'How are sandbox pods isolated from the node?', + options: [ + { + id: 'runtime-class', + label: 'Isolating RuntimeClass', + hint: 'gVisor, Kata, or a microVM runtime installed in the cluster', + currentWhen: { kind: 'present', key: 'SANDBOX_K8S_RUNTIME_CLASS' }, + prompts: [ + { + type: 'field', + key: 'SANDBOX_K8S_RUNTIME_CLASS', + input: 'text', + required: true, + hint: 'RuntimeClass name, such as gvisor, kata, or isolated-sandbox', + }, + ], + }, + { + id: 'unisolated', + label: 'Shared node kernel (unsafe)', + hint: 'untrusted code runs on the node kernel; for trusted or test clusters only', + currentWhen: { kind: 'truthy', key: 'SANDBOX_K8S_ALLOW_UNISOLATED' }, + env: { SANDBOX_K8S_ALLOW_UNISOLATED: 'true' }, + }, + ], + }, + { + type: 'field', + key: 'SANDBOX_K8S_NAMESPACE', + input: 'text', + defaultValue: 'sim-sandboxes', + hint: 'namespace the sandbox pods run in', + }, + { + type: 'choice', + id: 'kubernetes-overrides', + message: 'Sandbox images, resources, and scheduling?', + options: [ + { + id: 'defaults', + label: 'Release defaults', + hint: "this release's published images, 1 CPU, 2Gi memory, 4Gi disk per sandbox", + }, + { + id: 'custom', + label: 'Customize', + hint: 'leave any prompt empty to keep its default', + prompts: [ + { type: 'field', key: 'SANDBOX_K8S_AGENT_IMAGE', input: 'text' }, + { type: 'field', key: 'SANDBOX_K8S_FUNCTION_IMAGE', input: 'text' }, + { type: 'field', key: 'SANDBOX_K8S_PI_IMAGE', input: 'text' }, + { + type: 'field', + key: 'SANDBOX_K8S_CPU', + input: 'text', + hint: 'CPU limit, default 1', + }, + { + type: 'field', + key: 'SANDBOX_K8S_MEMORY', + input: 'text', + hint: 'memory limit, default 2Gi', + }, + { + type: 'field', + key: 'SANDBOX_K8S_EPHEMERAL_STORAGE', + input: 'text', + hint: 'disk limit, default 4Gi', + }, + { + type: 'field', + key: 'SANDBOX_K8S_NODE_SELECTOR', + input: 'text', + validate: true, + hint: 'JSON object of node labels', + }, + { + type: 'field', + key: 'SANDBOX_K8S_TOLERATIONS', + input: 'text', + hint: 'JSON array of tolerations', + }, + { + type: 'field', + key: 'SANDBOX_K8S_IMAGE_PULL_SECRET', + input: 'text', + hint: 'pull secret in the sandbox namespace, for private images', + }, + ], + }, + ], + }, + ], + }, }, optionOrder: ['disabled', ...SANDBOX_CAPABILITY.providers.map((provider) => provider.id)], }) diff --git a/packages/utils/src/sandbox-references.ts b/packages/utils/src/sandbox-references.ts index f12ffeccdc6..2e246c4ffca 100644 --- a/packages/utils/src/sandbox-references.ts +++ b/packages/utils/src/sandbox-references.ts @@ -8,7 +8,7 @@ export const IMMUTABLE_DAYTONA_SNAPSHOT_REF_ERROR = export const SANDBOX_RELEASE_GENERATION_ERROR = 'must be a positive safe integer release generation' -export const SANDBOX_PROVIDER_IDS = ['e2b', 'daytona'] as const +export const SANDBOX_PROVIDER_IDS = ['e2b', 'daytona', 'kubernetes'] as const /** Leaves three decimal digits for a materializer revision in one safe integer. */ const MAX_SANDBOX_RELEASE_GENERATION = Math.floor((Number.MAX_SAFE_INTEGER - 999) / 1000) From 03dc438fc4a1828771aa7610b8c1df23938ce310 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:14:02 -0600 Subject: [PATCH 23/78] feat(sandbox): hash every input of the agent image build The agent image builds from `turbo prune @sim/sandbox-agent --docker`, which also carries bunfig.toml and patches/ into its `bun install` (zod, which the agent bundles, is patched) and turbo.json. Add them to the agent's content-hash inputs so a change to any of them publishes a new tag, and regenerate the image refs. --- .../remote-sandbox/kubernetes/images.generated.json | 2 +- apps/sim/scripts/generate-sandbox-dockerfiles.ts | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json b/apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json index cdd551e7ddf..7f8b879151c 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/images.generated.json @@ -1,5 +1,5 @@ { "function": "ghcr.io/simstudioai/sandbox-function:6d7f249fa417b147", "pi": "ghcr.io/simstudioai/sandbox-pi:01cb06a1b2c01cad", - "agent": "ghcr.io/simstudioai/sandbox-agent:2b732c77b0bdec04" + "agent": "ghcr.io/simstudioai/sandbox-agent:12affd66181a62b4" } diff --git a/apps/sim/scripts/generate-sandbox-dockerfiles.ts b/apps/sim/scripts/generate-sandbox-dockerfiles.ts index c0b3a9d9336..0d783580a14 100644 --- a/apps/sim/scripts/generate-sandbox-dockerfiles.ts +++ b/apps/sim/scripts/generate-sandbox-dockerfiles.ts @@ -91,8 +91,11 @@ const CONTENT_TAG_LENGTH = 16 /** * Every sandbox image and the repo paths (files or directories, as git pathspecs) * its build reads. Function and Pi COPY nothing, so their Dockerfile is the whole - * input. The agent image compiles `apps/sandbox-agent` with the workspace packages - * it imports; keep its list in step with `docker/sandbox-agent.Dockerfile`. + * input. The agent image is built from what `turbo prune @sim/sandbox-agent --docker` + * emits: the root manifest and lockfile, `bunfig.toml` and `patches/` (both read by + * its `bun install`; zod, which the agent bundles, is patched), `turbo.json`, and + * the workspaces in the agent's dependency closure. Keep the list in step with + * that prune and with `docker/sandbox-agent.Dockerfile`. */ const SANDBOX_IMAGES = [ { kind: 'function', inputs: ['docker/sandbox-function.Dockerfile'] }, @@ -104,6 +107,9 @@ const SANDBOX_IMAGES = [ '.dockerignore', 'package.json', 'bun.lock', + 'bunfig.toml', + 'patches', + 'turbo.json', 'apps/sandbox-agent', 'packages/sandbox-agent-protocol', 'packages/logger', From 1917ccb6208019c6c819cd1995b941a45867d542 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:14:03 -0600 Subject: [PATCH 24/78] feat(sandbox): sweep finished and orphaned sandboxes from the session cleanup cron cleanup-session-sandboxes now also calls the selected provider's reapExpiredSandboxes, a no-op for E2B and Daytona. On Kubernetes it deletes pods that finished or outlived sim.ai/expires-at plus grace, under the same 30-second deadline as the paused-workbench sweep. --- .../cron/cleanup-session-sandboxes/route.ts | 21 ++++++++++++------- .../lib/execution/remote-sandbox/session.ts | 11 ++++++++++ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/apps/sim/app/api/cron/cleanup-session-sandboxes/route.ts b/apps/sim/app/api/cron/cleanup-session-sandboxes/route.ts index fd91e2c08f6..dba501fef00 100644 --- a/apps/sim/app/api/cron/cleanup-session-sandboxes/route.ts +++ b/apps/sim/app/api/cron/cleanup-session-sandboxes/route.ts @@ -3,7 +3,10 @@ import { getErrorMessage } from '@sim/utils/errors' import { type NextRequest, NextResponse } from 'next/server' import { verifyCronAuth } from '@/lib/auth/internal' import { withRouteHandler } from '@/lib/core/utils/with-route-handler' -import { reapPausedSessionSandboxes } from '@/lib/execution/remote-sandbox/session' +import { + reapExpiredSandboxes, + reapPausedSessionSandboxes, +} from '@/lib/execution/remote-sandbox/session' export const dynamic = 'force-dynamic' export const maxDuration = 60 @@ -11,18 +14,22 @@ export const maxDuration = 60 const logger = createLogger('CleanupSessionSandboxesAPI') /** - * Retention sweep for paused chat workbenches. An idle workbench pauses instead of dying and the - * provider keeps it indefinitely, so this run is what bounds how long its files outlive the chat's - * last use. A no-op on providers without session sandboxes. + * Retention sweep for sandboxes the provider keeps past their use. An idle workbench pauses + * instead of dying and the provider keeps it indefinitely, so this run is what bounds how long its + * files outlive the chat's last use. Providers that leave finished or orphaned sandboxes behind + * (Kubernetes pods) are swept in the same run. Each half is a no-op where it does not apply. */ export const GET = withRouteHandler(async (request: NextRequest) => { const authError = verifyCronAuth(request, 'session sandbox cleanup') if (authError) return authError try { - const result = await reapPausedSessionSandboxes() - logger.info('Swept paused session sandboxes', result) - return NextResponse.json({ success: true, ...result }) + const [result, expired] = await Promise.all([ + reapPausedSessionSandboxes(), + reapExpiredSandboxes(), + ]) + logger.info('Swept session sandboxes', { ...result, expired }) + return NextResponse.json({ success: true, ...result, expired }) } catch (error) { logger.error('Failed to sweep paused session sandboxes', { error }) return NextResponse.json( diff --git a/apps/sim/lib/execution/remote-sandbox/session.ts b/apps/sim/lib/execution/remote-sandbox/session.ts index 3a402a8c2e0..4573c13418c 100644 --- a/apps/sim/lib/execution/remote-sandbox/session.ts +++ b/apps/sim/lib/execution/remote-sandbox/session.ts @@ -11,6 +11,7 @@ import { initializeSessionFileProvenance } from '@/lib/execution/remote-sandbox/ import { withSandboxSessionLock } from '@/lib/execution/remote-sandbox/session-lock' import type { CreateSandboxOptions, + ExpiredSandboxSweep, SandboxKind, SandboxProvider, SandboxSessionRequest, @@ -152,3 +153,13 @@ export async function reapPausedSessionSandboxes(): Promise<{ }) return result } + +/** + * Deletes sandboxes the selected provider leaves behind once they finish or outlive their recorded + * deadline (for Kubernetes, completed and orphaned pods). A no-op on providers that reap their own. + */ +export async function reapExpiredSandboxes(): Promise { + const provider = resolveProvider() + if (!provider.reapExpiredSandboxes) return { deleted: 0, deferred: 0, failed: 0 } + return provider.reapExpiredSandboxes(AbortSignal.timeout(REAP_DEADLINE_MS)) +} From 6bc2278453d35df2598d1dd6cc0cd1a3f0d4bd9d Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:45:22 -0600 Subject: [PATCH 25/78] fix(sandbox): recognise only isolating runtimes and tighten the sandbox pod - The isolation guard is now an allowlist: gVisor (runsc, runsc-*, gvisor), Kata (kata, kata-*), firecracker, and the EKS Nitro isolated-sandbox / confidential-sandbox handlers. Any other handler is refused unless listed in the new SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS or SANDBOX_K8S_ALLOW_UNISOLATED=true. The RuntimeClass read takes the create deadline. - /home/user is no longer an emptyDir: it was root-owned and hid the image's uid-1000 home, and the agent no longer re-owns an existing home. Writes there still count against the container's ephemeral-storage limit. - Requests are halved in whole milli-cores and whole bytes, so float noise cannot round a request up. - SANDBOX_K8S_TOLERATIONS is validated as a JSON array of objects in the capability registry and the setup wizard, which also offers the trusted-handlers override. - Pod-spec tests keep only properties that encode security or behavior. --- apps/sim/lib/core/config/env.ts | 1 + .../remote-sandbox/kubernetes/isolation.ts | 44 ++++++++++++++----- .../remote-sandbox/kubernetes/pod.test.ts | 27 +++++------- .../remote-sandbox/kubernetes/pod.ts | 13 ++++-- .../remote-sandbox/kubernetes/settings.ts | 23 +++++++--- .../deployment-config/src/env-capabilities.ts | 21 ++++++++- packages/sim-setup/src/capability-config.ts | 7 +++ 7 files changed, 99 insertions(+), 37 deletions(-) diff --git a/apps/sim/lib/core/config/env.ts b/apps/sim/lib/core/config/env.ts index b7c03c7d5b4..56c383e5a85 100644 --- a/apps/sim/lib/core/config/env.ts +++ b/apps/sim/lib/core/config/env.ts @@ -674,6 +674,7 @@ export const env = createEnv({ SANDBOX_K8S_NODE_SELECTOR: z.string().optional(), // JSON object of node labels sandbox pods are scheduled onto SANDBOX_K8S_TOLERATIONS: z.string().optional(), // JSON array of tolerations for sandbox pods SANDBOX_K8S_IMAGE_PULL_SECRET: z.string().optional(), // Image pull secret (in the sandbox namespace) for private sandbox images + SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS: z.string().optional(), // Comma-separated RuntimeClass handlers to treat as isolating, for custom runtimes Sim does not recognise // Access Control (Permission Groups) - for self-hosted deployments ACCESS_CONTROL_ENABLED: z.boolean().optional(), // Enable access control on self-hosted (bypasses plan requirements) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/isolation.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/isolation.ts index e9343d43817..e801599172b 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/isolation.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/isolation.ts @@ -8,8 +8,21 @@ import type { KubernetesSandboxSettings } from '@/lib/execution/remote-sandbox/k const logger = createLogger('KubernetesSandboxIsolation') -/** OCI runtimes that run containers on the node's own kernel. */ -const SHARED_KERNEL_HANDLERS = new Set(['', 'runc', 'crun']) +/** + * RuntimeClass handlers known to give each pod its own kernel: + * + * - gVisor: `runsc` and `runsc-*` variants, or `gvisor` as some managed clusters name it. + * - Kata Containers: `kata` and its per-hypervisor `kata-*` handlers (`kata-qemu`, `kata-fc`, ...). + * - Firecracker-based runtimes registered as `firecracker`. + * - AWS Nitro Sandboxes on EKS: the `isolated-sandbox` and `confidential-sandbox` classes + * (https://docs.aws.amazon.com/eks/latest/userguide/sandboxing-isolated-setup.html), whose + * handler carries the class name in AWS's published RuntimeClass. + * + * Anything else, `runc` and `crun` included, is treated as sharing the node kernel. An operator + * with another isolating runtime names its handler in `SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS`. + */ +const ISOLATING_HANDLER = + /^(?:runsc(?:-.+)?|gvisor|kata(?:-.+)?|firecracker|isolated-sandbox|confidential-sandbox)$/ /** * How long a refusal is remembered before the RuntimeClass is read again, so a burst of creates @@ -18,12 +31,21 @@ const SHARED_KERNEL_HANDLERS = new Set(['', 'runc', 'crun']) */ const REFUSAL_TTL_MS = 30_000 +/** True when `handler` runs pods on a kernel of their own. */ +function isIsolatingHandler(handler: string, settings: KubernetesSandboxSettings): boolean { + const normalized = handler.trim().toLowerCase() + return ( + ISOLATING_HANDLER.test(normalized) || + settings.trustedRuntimeHandlers.some((trusted) => trusted.toLowerCase() === normalized) + ) +} + /** * Decides once per provider instance whether sandboxes may run, from the configured RuntimeClass. * Untrusted code runs as root in the sandbox, so the pod's runtime must be the isolation boundary: - * a RuntimeClass that is missing, or whose handler is a shared-kernel runtime, is refused unless - * the operator set `SANDBOX_K8S_ALLOW_UNISOLATED=true`. A passing verdict is kept for the life of - * the instance; a refusal is kept for {@link REFUSAL_TTL_MS}. + * a RuntimeClass that is missing, or whose handler is not a known isolating runtime, is refused + * unless the operator set `SANDBOX_K8S_ALLOW_UNISOLATED=true`. A passing verdict is kept for the + * life of the instance; a refusal is kept for {@link REFUSAL_TTL_MS}. */ export class IsolationGuard { private verdict: Promise | null = null @@ -31,7 +53,7 @@ export class IsolationGuard { constructor(private readonly cluster: SandboxCluster) {} - assertIsolated(settings: KubernetesSandboxSettings): Promise { + assertIsolated(settings: KubernetesSandboxSettings, signal?: AbortSignal): Promise { if ( this.verdict && (this.refusedAtMs === 0 || Date.now() - this.refusedAtMs < REFUSAL_TTL_MS) @@ -39,7 +61,7 @@ export class IsolationGuard { return this.verdict } this.refusedAtMs = 0 - const verdict = this.check(settings) + const verdict = this.check(settings, signal) this.verdict = verdict verdict.catch((error: unknown) => { if (this.verdict !== verdict) return @@ -50,7 +72,7 @@ export class IsolationGuard { return verdict } - private async check(settings: KubernetesSandboxSettings): Promise { + private async check(settings: KubernetesSandboxSettings, signal?: AbortSignal): Promise { const { runtimeClassName, allowUnisolated } = settings if (allowUnisolated) { logger.warn( @@ -66,7 +88,7 @@ export class IsolationGuard { } let handler: string | null try { - handler = await this.cluster.readRuntimeClassHandler(runtimeClassName) + handler = await this.cluster.readRuntimeClassHandler(runtimeClassName, { signal }) } catch (error) { if (isKubernetesStatus(error, 403)) { throw new KubernetesSandboxConfigError( @@ -81,9 +103,9 @@ export class IsolationGuard { `RuntimeClass "${runtimeClassName}" (SANDBOX_K8S_RUNTIME_CLASS) does not exist in the cluster. Install the sandbox runtime (gVisor, Kata, or a microVM runtime) and its RuntimeClass, or point SANDBOX_K8S_RUNTIME_CLASS at an existing one.` ) } - if (SHARED_KERNEL_HANDLERS.has(handler.trim().toLowerCase())) { + if (!isIsolatingHandler(handler, settings)) { throw new KubernetesSandboxConfigError( - `RuntimeClass "${runtimeClassName}" (SANDBOX_K8S_RUNTIME_CLASS) uses the "${handler}" handler, which shares the node kernel with untrusted code. Use an isolating runtime such as gVisor (runsc) or Kata, or set SANDBOX_K8S_ALLOW_UNISOLATED=true to accept the risk.` + `RuntimeClass "${runtimeClassName}" (SANDBOX_K8S_RUNTIME_CLASS) uses the "${handler}" handler, which Sim does not recognise as isolating untrusted code from the node kernel. Use gVisor (runsc), Kata, or a microVM runtime; name a custom isolating handler in SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS; or set SANDBOX_K8S_ALLOW_UNISOLATED=true to accept a shared kernel.` ) } logger.info('Sandbox pods run under an isolating RuntimeClass', { runtimeClassName, handler }) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.test.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.test.ts index c3885365ae0..1ea3e70f50e 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.test.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.test.ts @@ -10,6 +10,7 @@ import { describe, expect, it } from 'vitest' import { KubernetesSandboxConfigError } from '@/lib/execution/remote-sandbox/kubernetes/errors' import { buildSandboxPod } from '@/lib/execution/remote-sandbox/kubernetes/pod' import { + halfQuantity, imageFor, type KubernetesSandboxSettings, readKubernetesSandboxSettings, @@ -26,6 +27,7 @@ function settings(overrides: Partial = {}): Kubernete namespace: 'sim-sandboxes', runtimeClassName: 'gvisor', allowUnisolated: false, + trustedRuntimeHandlers: [], images: { agent: 'registry/agent:1', function: 'registry/function:1', pi: 'registry/pi:1' }, resources: { cpu: '1', memory: '2Gi', ephemeralStorage: '4Gi' }, tokenSecret: SECRET, @@ -145,11 +147,15 @@ describe('sandbox pod isolation', () => { }) describe('sandbox pod resources', () => { - it('limits the sandbox and requests half of each limit', () => { + it('requests half of each limit as a valid whole quantity', () => { expect(sandboxContainer(build()).resources).toEqual({ limits: { cpu: '1', memory: '2Gi', 'ephemeral-storage': '4Gi' }, requests: { cpu: '500m', memory: '1073741824', 'ephemeral-storage': '2147483648' }, }) + expect(halfQuantity('250m', 'cpu')).toBe('125m') + expect(halfQuantity('4.014', 'cpu')).toBe('2007m') + expect(halfQuantity('1.5Gi', 'bytes')).toBe('805306368') + expect(halfQuantity('0.1Mi', 'bytes')).toBe('52429') }) it('gives the agent installer explicit requests and limits, so quota never sizes it by default', () => { @@ -162,27 +168,16 @@ describe('sandbox pod resources', () => { it('caps every writable scratch volume at the ephemeral-storage limit', () => { const volumes = build().spec?.volumes ?? [] const mounts = sandboxContainer(build()).volumeMounts ?? [] - for (const path of ['/tmp', '/home/user', '/opt/sim-deps']) { + for (const path of ['/tmp', '/opt/sim-deps']) { const mount = mounts.find(({ mountPath }) => mountPath === path) expect(mount?.readOnly).toBeFalsy() expect(volumes.find(({ name }) => name === mount?.name)?.emptyDir?.sizeLimit).toBe('4Gi') } }) -}) -describe('sandbox pod labels', () => { - it('marks the pod Sim-managed with its kind and deadline, and labels a session by digest', () => { - const metadata = build({ kind: 'pi', sessionLabel: 'a'.repeat(40) }).metadata - expect(metadata?.labels).toEqual({ - 'app.kubernetes.io/managed-by': 'sim', - 'sim.ai/sandbox-kind': 'pi', - 'sim.ai/session': 'a'.repeat(40), - }) - expect(metadata?.annotations).toEqual({ 'sim.ai/expires-at': '1800000000000' }) - }) - - it('leaves a one-shot pod without a session label', () => { - expect(build().metadata?.labels).not.toHaveProperty('sim.ai/session') + it("leaves the user's home on the image's filesystem, so it keeps uid 1000's ownership", () => { + const mounts = sandboxContainer(build()).volumeMounts ?? [] + expect(mounts.some(({ mountPath }) => mountPath.startsWith('/home'))).toBe(false) }) }) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts index ff3a8464061..4089772b4b5 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts @@ -37,10 +37,15 @@ const AGENT_VOLUME_SIZE = '256Mi' /** * Writable scratch the sandbox user and dependency installs need. Each is an emptyDir capped at * the pod's ephemeral-storage limit, so a runaway write is evicted rather than filling the node. + * + * `/home/user` is deliberately not one: an emptyDir there is root-owned and hides the home the + * image built for uid 1000 (its dotfiles and tool config), and the agent does not re-own an + * existing home. Left on the container's own filesystem, the home keeps the image's ownership, + * the agent creates it for an image without one, and its writes still count against the + * container's ephemeral-storage limit. */ const SCRATCH_MOUNTS = [ { name: 'tmp', mountPath: '/tmp' }, - { name: 'home', mountPath: '/home/user' }, { name: 'deps', mountPath: '/opt/sim-deps' }, ] as const @@ -149,9 +154,9 @@ export function buildSandboxPod(input: SandboxPodInput): V1Pod { resources: { limits: { cpu, memory, 'ephemeral-storage': ephemeralStorage }, requests: { - cpu: halfQuantity(cpu), - memory: halfQuantity(memory), - 'ephemeral-storage': halfQuantity(ephemeralStorage), + cpu: halfQuantity(cpu, 'cpu'), + memory: halfQuantity(memory, 'bytes'), + 'ephemeral-storage': halfQuantity(ephemeralStorage, 'bytes'), }, }, securityContext: { diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/settings.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/settings.ts index e9139e664a0..6056895580b 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/settings.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/settings.ts @@ -23,6 +23,7 @@ type KubernetesSandboxEnv = Pick< | 'SANDBOX_K8S_NODE_SELECTOR' | 'SANDBOX_K8S_TOLERATIONS' | 'SANDBOX_K8S_IMAGE_PULL_SECRET' + | 'SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS' > interface KubernetesSandboxResources { @@ -37,6 +38,11 @@ export interface KubernetesSandboxSettings { /** Unset only when {@link allowUnisolated} is true. */ runtimeClassName?: string allowUnisolated: boolean + /** + * RuntimeClass handlers the operator vouches for as isolating, beyond the ones Sim recognises + * (a custom microVM runtime, say). + */ + trustedRuntimeHandlers: string[] images: { agent: string function: string @@ -100,14 +106,16 @@ function quantityValue(quantity: string): number | null { } /** - * Half of a resource quantity, for the request that pairs with a limit. Whole base units stay - * whole (`2Gi` → `1073741824`); a fraction is expressed in milli-units (`1` → `500m`). + * Half of a resource limit, for the request that pairs with it: CPU in whole milli-cores, bytes + * rounded up to a whole byte, so the request is always a valid quantity and never rounds to zero. */ -export function halfQuantity(quantity: string): string { +export function halfQuantity(quantity: string, unit: 'cpu' | 'bytes'): string { const value = quantityValue(quantity) if (value === null) throw new Error(`Invalid Kubernetes quantity: ${quantity}`) - const half = value / 2 - return Number.isInteger(half) ? String(half) : `${Math.ceil(half * 1000)}m` + // Rounded to whole units before halving, so binary-fraction noise (0.3 * 1000) cannot add one. + return unit === 'cpu' + ? `${Math.ceil(Math.round(value * 1000) / 2)}m` + : String(Math.ceil(Math.round(value) / 2)) } function readQuantity(name: string, value: string | undefined, fallback: string): string { @@ -171,10 +179,15 @@ export function readKubernetesSandboxSettings( tolerationsSchema ) const imagePullSecret = optional(values.SANDBOX_K8S_IMAGE_PULL_SECRET) + const trustedRuntimeHandlers = (values.SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS ?? '') + .split(',') + .map((handler) => handler.trim()) + .filter(Boolean) return { namespace: optional(values.SANDBOX_K8S_NAMESPACE) ?? DEFAULT_NAMESPACE, ...(runtimeClassName ? { runtimeClassName } : {}), allowUnisolated, + trustedRuntimeHandlers, images: { agent: optional(values.SANDBOX_K8S_AGENT_IMAGE) ?? publishedImages.agent, function: optional(values.SANDBOX_K8S_FUNCTION_IMAGE) ?? publishedImages.function, diff --git a/packages/deployment-config/src/env-capabilities.ts b/packages/deployment-config/src/env-capabilities.ts index 31b70e23c2f..68c63978f84 100644 --- a/packages/deployment-config/src/env-capabilities.ts +++ b/packages/deployment-config/src/env-capabilities.ts @@ -4,6 +4,7 @@ * * @packageDocumentation */ +import { isRecordLike } from '@sim/utils/object' import { IMMUTABLE_DAYTONA_SNAPSHOT_REF_ERROR, IMMUTABLE_E2B_TEMPLATE_REF_ERROR, @@ -42,6 +43,10 @@ type EnvValueValidation = requiredStringFields?: readonly string[] message: string } + | { + kind: 'json-object-array' + message: string + } | { kind: 'pattern' pattern: RegExp @@ -387,6 +392,14 @@ function isValidEnvCapabilityFieldValue( return false } } + if (validation.kind === 'json-object-array') { + try { + const parsed: unknown = JSON.parse(serialized) + return Array.isArray(parsed) && parsed.every((entry) => isRecordLike(entry)) + } catch { + return false + } + } if (validation.kind === 'pattern') { validation.pattern.lastIndex = 0 return validation.pattern.test(serialized) @@ -1152,8 +1165,14 @@ export const SANDBOX_CAPABILITY = defineCapability({ message: 'must be a JSON object of node label keys to values', }, }), - envField('SANDBOX_K8S_TOLERATIONS'), + envField('SANDBOX_K8S_TOLERATIONS', { + validation: { + kind: 'json-object-array', + message: 'must be a JSON array of toleration objects', + }, + }), envField('SANDBOX_K8S_IMAGE_PULL_SECRET'), + envField('SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS'), ], }, ], diff --git a/packages/sim-setup/src/capability-config.ts b/packages/sim-setup/src/capability-config.ts index 88c21929d71..06b69a5ee30 100644 --- a/packages/sim-setup/src/capability-config.ts +++ b/packages/sim-setup/src/capability-config.ts @@ -626,6 +626,12 @@ export const SANDBOX_SETUP = defineCapabilitySetup(SANDBOX_CAPABILITY, { required: true, hint: 'RuntimeClass name, such as gvisor, kata, or isolated-sandbox', }, + { + type: 'field', + key: 'SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS', + input: 'text', + hint: 'only for a custom isolating runtime Sim does not recognise: its handler names, comma-separated', + }, ], }, { @@ -691,6 +697,7 @@ export const SANDBOX_SETUP = defineCapabilitySetup(SANDBOX_CAPABILITY, { type: 'field', key: 'SANDBOX_K8S_TOLERATIONS', input: 'text', + validate: true, hint: 'JSON array of tolerations', }, { From 47ee18511c3e337bc49a52b1069958817e07cafc Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:45:38 -0600 Subject: [PATCH 26/78] fix(sandbox): bound and harden Kubernetes sandbox creation, lookup, and stop Pod start-up: - A watch that ends early, errors, or returns 410/429/5xx is re-read and re-watched after a backoffWithJitter pause, never at once. A 403 on watch is a configuration error naming the missing verb. A DELETED event fails the create at once, and the watch connect is abortable by the create deadline. - ErrImagePull and ImagePullBackOff fail fast only when the kubelet message says the image is missing or the registry refused credentials (containerd "not found" / "code = NotFound", "pull access denied", "failed to authorize", "manifest unknown", 401/403), or for InvalidImageName/ErrImageNeverPull. Other pull errors are waited out; the deadline error carries the last pull message. - A FailedCreatePodSandBox event saying the node has no runtime for the RuntimeClass handler fails the create at once (needs events list; skipped without it). Requests and cleanup: - Every non-watch API call is bounded by a 10 s per-request timeout and by the create deadline, through a client-node request middleware that sets the RequestContext signal. - Deletes use the pod's own termination grace period instead of forcing. - A create that fails after an attempt that may have reached the API server deletes that pod, including when the 409 adoption read fails. - With no KUBECONFIG, ~/.kube/config, or in-cluster token, the provider fails with a configuration error instead of client-node's silent fallback to http://localhost:8080. - The provider refuses to run inside a Trigger.dev worker (by isInsideTriggerRun), which cannot reach sandbox pods; self-hosted executions run in the app on the database-backed queue. The trigger.config.ts env sync and package changes are reverted. Sessions and stop: - Reconnects skip pods whose runtimeClassName differs from the configured one (unless unisolated is allowed). A live pod too near its 24-hour cap for the requested lease is retired by moving its sim.ai/expires-at to now, so later lookups cannot split the session. - stopSessionProcess also requires managed-by=sim and the expected token digest. The forwarding handle wrapper is gone: AgentSandboxConnection gains maxExpiresAtMs and a beforeLifetimeExtended(expiresAtMs) hook, which the provider uses to patch sim.ai/expires-at before the agent is asked. Tests cover the cases above against a more faithful fake API server. --- .../execution/remote-sandbox/agent/handle.ts | 11 + .../remote-sandbox/kubernetes/cluster.ts | 338 ++++++--- .../remote-sandbox/kubernetes/handle.ts | 132 ---- .../remote-sandbox/kubernetes/pod.ts | 10 + .../kubernetes/provider.test.ts | 705 +++++++++++++----- .../remote-sandbox/kubernetes/provider.ts | 446 +++++++---- apps/sim/trigger.config.ts | 15 - 7 files changed, 1067 insertions(+), 590 deletions(-) delete mode 100644 apps/sim/lib/execution/remote-sandbox/kubernetes/handle.ts diff --git a/apps/sim/lib/execution/remote-sandbox/agent/handle.ts b/apps/sim/lib/execution/remote-sandbox/agent/handle.ts index 1a4eefc1082..83e4ed0b6c4 100644 --- a/apps/sim/lib/execution/remote-sandbox/agent/handle.ts +++ b/apps/sim/lib/execution/remote-sandbox/agent/handle.ts @@ -105,6 +105,17 @@ export interface AgentSandboxConnection { sessionKey?: string /** The agent's self-termination deadline when the handle was made, by the caller's clock. */ expiresAtMs: number + /** + * Latest deadline the control plane allows (for Kubernetes, the pod's `activeDeadlineSeconds`). + * {@link SandboxHandle.extendLifetime} never asks the agent for more. Unbounded when omitted. + */ + maxExpiresAtMs?: number + /** + * Runs before the agent is asked to live until `expiresAtMs`, so the control plane records the + * deadline first and a sweep that reads only the control plane never reaps a sandbox whose + * agent was told to stay up. A rejection fails the extension without contacting the agent. + */ + beforeLifetimeExtended?(expiresAtMs: number): Promise /** * Home directory of the identity code runs as; relative file paths resolve against it, as on * E2B. Only an unprivileged agent (a developer machine or CI) has one other than `/home/user`. diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/cluster.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/cluster.ts index e1e2f387d18..7dbfc29569b 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/cluster.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/cluster.ts @@ -1,11 +1,27 @@ -import type { CoreV1Api, KubeConfig, NodeV1Api, V1Pod, Watch } from '@kubernetes/client-node' +import { existsSync } from 'node:fs' +import { homedir } from 'node:os' +import path from 'node:path' +import type { + ConfigurationOptions, + CoreV1Api, + CoreV1Event, + KubeConfig, + NodeV1Api, + Observable, + ObservableMiddleware, + V1Pod, + Watch, +} from '@kubernetes/client-node' import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' import { sleep } from '@sim/utils/helpers' +import { isRecordLike } from '@sim/utils/object' import { backoffWithJitter, parseRetryAfter } from '@sim/utils/retry' import { describeKubernetesApiFailure, isRetryableKubernetesFailure, type KubernetesApiFailure, + KubernetesSandboxConfigError, } from '@/lib/execution/remote-sandbox/kubernetes/errors' import { EXPIRES_AT_ANNOTATION } from '@/lib/execution/remote-sandbox/kubernetes/pod' @@ -13,10 +29,15 @@ const logger = createLogger('KubernetesSandboxCluster') const MAX_ATTEMPTS = 3 const RETRY_BACKOFF = { baseMs: 250, maxMs: 4_000 } +/** Bound on one non-watch API request; a healthy API server answers well within it. */ +const REQUEST_TIMEOUT_MS = 10_000 /** One page of a pod listing; sessions and the reaper page through larger sets. */ const LIST_PAGE_SIZE = 500 /** Server-side bound on one watch request; the waiter re-reads and re-watches after it. */ const WATCH_TIMEOUT_SECONDS = 30 +const MERGE_PATCH = 'application/merge-patch+json' +/** Where Kubernetes mounts a pod's service-account token; its presence means in-cluster. */ +const SERVICE_ACCOUNT_TOKEN_PATH = '/var/run/secrets/kubernetes.io/serviceaccount/token' /** A failed Kubernetes API call, carrying the parsed status for callers to map. */ export class KubernetesApiError extends Error { @@ -36,58 +57,60 @@ export function isKubernetesStatus(error: unknown, status: number): boolean { } /** - * Runs one API call, retrying a throttled, unavailable, or unanswered request a bounded number of - * times. Only idempotent operations are passed in with retries on; a create handles its own. + * How a pod watch ended: + * - `matched`: the caller's predicate accepted an update. + * - `deleted`: the pod was deleted. + * - `ended`: the stream closed, failed, or reported an error (a 410 Gone for a resourceVersion too + * old included); the caller backs off, re-reads the pod, and watches again from there. */ -async function callApi(operation: string, call: () => Promise, retry: boolean): Promise { - for (let attempt = 1; ; attempt++) { - try { - return await call() - } catch (error) { - const failure = describeKubernetesApiFailure(error) - if (!retry || attempt >= MAX_ATTEMPTS || !isRetryableKubernetesFailure(failure)) { - throw new KubernetesApiError(operation, failure, { cause: error }) - } - logger.warn('Kubernetes API request failed; retrying', { - operation, - attempt, - status: failure.status, - }) - await sleep( - backoffWithJitter(attempt, parseRetryAfter(failure.retryAfter ?? null), RETRY_BACKOFF) - ) - } - } +type PodWatchEnd = 'matched' | 'deleted' | 'ended' + +/** Per-call options: aborts with the caller's deadline as well as the per-request timeout. */ +interface CallOptions { + signal?: AbortSignal } /** * The cluster operations the sandbox provider performs, scoped to one namespace. Every method - * maps to one API verb the sandbox Role grants: pods create/get/list/watch/delete/patch, plus - * runtimeclasses get. + * maps to one API verb the sandbox Role grants: pods create/get/list/watch/delete/patch, events + * list, and runtimeclasses get. Every request other than a watch is bounded by + * {@link REQUEST_TIMEOUT_MS} and by the caller's signal. */ export interface SandboxCluster { readonly namespace: string /** The RuntimeClass's handler, or null when no such RuntimeClass exists. */ - readRuntimeClassHandler(name: string): Promise + readRuntimeClassHandler(name: string, options?: CallOptions): Promise /** Creates the pod once, without retrying; the caller decides what a failure means. */ - createPod(pod: V1Pod): Promise + createPod(pod: V1Pod, options?: CallOptions): Promise /** Null when the pod does not exist. */ - readPod(name: string): Promise + readPod(name: string, options?: CallOptions): Promise /** Every pod matching the label selector, across pages. */ - listPods(labelSelector: string): Promise + listPods(labelSelector: string, options?: CallOptions): Promise + /** The pod's events, or null when the service account may not list events. */ + listPodEvents(name: string, options?: CallOptions): Promise /** - * Streams the pod's updates from `resourceVersion` until `onUpdate` returns true, the watch - * ends (resolving false), or `signal` aborts. + * Streams the pod's updates from `resourceVersion` until `onUpdate` returns true or the watch + * ends. Rejects when `signal` aborts, even while connecting. */ watchPod( name: string, resourceVersion: string | undefined, onUpdate: (pod: V1Pod) => boolean, signal: AbortSignal - ): Promise - setExpiresAt(name: string, expiresAtMs: number): Promise - /** Resolves when the pod is gone or was never there. */ - deletePod(name: string): Promise + ): Promise + setExpiresAt(name: string, expiresAtMs: number, options?: CallOptions): Promise + /** + * Deletes the pod with its own termination grace period. Resolves when the pod is gone or was + * never there. + */ + deletePod(name: string, options?: CallOptions): Promise +} + +type ObservableConstructor = new (promise: Promise) => Observable + +/** HTTP status the watch carried on a failed connect, from client-node's `statusCode`. */ +function watchStatus(error: unknown): number | undefined { + return isRecordLike(error) && typeof error.statusCode === 'number' ? error.statusCode : undefined } class ClientSandboxCluster implements SandboxCluster { @@ -96,15 +119,69 @@ class ClientSandboxCluster implements SandboxCluster { private readonly core: CoreV1Api, private readonly node: NodeV1Api, private readonly watcher: Watch, - private readonly mergePatch: Awaited> + private readonly ObservableClass: ObservableConstructor ) {} - async readRuntimeClassHandler(name: string): Promise { + /** + * Request options carrying an abort signal (and optionally a Content-Type) into client-node's + * fetch: a request middleware sets them on the `RequestContext`, which client-node passes to + * `fetch` as its `signal`. Appended, so the client's own middleware (its User-Agent) still runs. + */ + private requestOptions(signal: AbortSignal, contentType?: string): ConfigurationOptions { + const ObservableClass = this.ObservableClass + const middleware: ObservableMiddleware = { + pre: (context) => { + context.setSignal(signal) + if (contentType) context.setHeaderParam('Content-Type', contentType) + return new ObservableClass(Promise.resolve(context)) + }, + post: (response) => new ObservableClass(Promise.resolve(response)), + } + return { middleware: [middleware], middlewareMergeStrategy: 'append' } + } + + /** + * Runs one API call under a fresh per-request timeout, retrying a throttled, unavailable, or + * unanswered request a bounded number of times when `retry` is set. Only idempotent operations + * retry here; a create handles its own. + */ + private async call( + operation: string, + request: (options: ConfigurationOptions) => Promise, + settings: { retry: boolean; signal?: AbortSignal; contentType?: string } + ): Promise { + for (let attempt = 1; ; attempt++) { + settings.signal?.throwIfAborted() + const signal = AbortSignal.any([ + AbortSignal.timeout(REQUEST_TIMEOUT_MS), + ...(settings.signal ? [settings.signal] : []), + ]) + try { + return await request(this.requestOptions(signal, settings.contentType)) + } catch (error) { + settings.signal?.throwIfAborted() + const failure = describeKubernetesApiFailure(error) + if (!settings.retry || attempt >= MAX_ATTEMPTS || !isRetryableKubernetesFailure(failure)) { + throw new KubernetesApiError(operation, failure, { cause: error }) + } + logger.warn('Kubernetes API request failed; retrying', { + operation, + attempt, + status: failure.status, + }) + await sleep( + backoffWithJitter(attempt, parseRetryAfter(failure.retryAfter ?? null), RETRY_BACKOFF) + ) + } + } + } + + async readRuntimeClassHandler(name: string, options: CallOptions = {}): Promise { try { - const runtimeClass = await callApi( + const runtimeClass = await this.call( 'RuntimeClass read', - () => this.node.readRuntimeClass({ name }), - true + (request) => this.node.readRuntimeClass({ name }, request), + { retry: true, ...options } ) return runtimeClass.handler } catch (error) { @@ -113,20 +190,20 @@ class ClientSandboxCluster implements SandboxCluster { } } - createPod(pod: V1Pod): Promise { - return callApi( + createPod(pod: V1Pod, options: CallOptions = {}): Promise { + return this.call( 'pod create', - () => this.core.createNamespacedPod({ namespace: this.namespace, body: pod }), - false + (request) => this.core.createNamespacedPod({ namespace: this.namespace, body: pod }, request), + { retry: false, ...options } ) } - async readPod(name: string): Promise { + async readPod(name: string, options: CallOptions = {}): Promise { try { - return await callApi( + return await this.call( 'pod read', - () => this.core.readNamespacedPod({ name, namespace: this.namespace }), - true + (request) => this.core.readNamespacedPod({ name, namespace: this.namespace }, request), + { retry: true, ...options } ) } catch (error) { if (isKubernetesStatus(error, 404)) return null @@ -134,20 +211,23 @@ class ClientSandboxCluster implements SandboxCluster { } } - async listPods(labelSelector: string): Promise { + async listPods(labelSelector: string, options: CallOptions = {}): Promise { const pods: V1Pod[] = [] let continueToken: string | undefined do { - const page = await callApi( + const page = await this.call( 'pod list', - () => - this.core.listNamespacedPod({ - namespace: this.namespace, - labelSelector, - limit: LIST_PAGE_SIZE, - ...(continueToken ? { _continue: continueToken } : {}), - }), - true + (request) => + this.core.listNamespacedPod( + { + namespace: this.namespace, + labelSelector, + limit: LIST_PAGE_SIZE, + ...(continueToken ? { _continue: continueToken } : {}), + }, + request + ), + { retry: true, ...options } ) pods.push(...page.items) continueToken = page.metadata?._continue || undefined @@ -155,89 +235,113 @@ class ClientSandboxCluster implements SandboxCluster { return pods } + async listPodEvents(name: string, options: CallOptions = {}): Promise { + try { + const events = await this.call( + 'event list', + (request) => + this.core.listNamespacedEvent( + { namespace: this.namespace, fieldSelector: `involvedObject.name=${name}` }, + request + ), + { retry: true, ...options } + ) + return events.items + } catch (error) { + if (isKubernetesStatus(error, 403)) return null + throw error + } + } + async watchPod( name: string, resourceVersion: string | undefined, onUpdate: (pod: V1Pod) => boolean, signal: AbortSignal - ): Promise { + ): Promise { signal.throwIfAborted() let settled = false - let finish: (matched: boolean) => void = () => {} + let finish: (end: PodWatchEnd) => void = () => {} let fail: (error: unknown) => void = () => {} - const outcome = new Promise((resolve, reject) => { - finish = (matched) => { + const outcome = new Promise((resolve, reject) => { + finish = (end) => { + if (settled) return settled = true - resolve(matched) + resolve(end) } fail = (error) => { + if (settled) return settled = true reject(error) } }) - // Observed by the `await` below; this only keeps an abort during connect from reporting as - // an unhandled rejection before that. - outcome.catch(() => {}) - let controller: AbortController | undefined - const onAbort = () => { - controller?.abort() - fail(signal.reason) - } + const onAbort = () => fail(signal.reason) signal.addEventListener('abort', onAbort, { once: true }) - try { - controller = await this.watcher.watch( - `/api/v1/namespaces/${encodeURIComponent(this.namespace)}/pods`, - { - fieldSelector: `metadata.name=${name}`, - timeoutSeconds: WATCH_TIMEOUT_SECONDS, - ...(resourceVersion ? { resourceVersion } : {}), - }, - (type: string, object: V1Pod) => { - if (settled || (type !== 'ADDED' && type !== 'MODIFIED')) return - if (onUpdate(object)) finish(true) - }, - (error: unknown) => { - if (settled) return - // A watch that times out, is closed by the server, or expired its resourceVersion (410) - // just ends; the caller re-reads the pod and watches again. - if (error) logger.debug('Sandbox pod watch ended', { name, error: String(error) }) - finish(false) + // Not awaited: client-node resolves it only once the response headers arrive, and the + // deadline must be able to end a connect that hangs. + const connecting = this.watcher.watch( + `/api/v1/namespaces/${encodeURIComponent(this.namespace)}/pods`, + { + fieldSelector: `metadata.name=${name}`, + timeoutSeconds: WATCH_TIMEOUT_SECONDS, + allowWatchBookmarks: false, + ...(resourceVersion ? { resourceVersion } : {}), + }, + (type: string, object: unknown) => { + if (type === 'DELETED') return finish('deleted') + if (type === 'ERROR') return finish('ended') + if ((type === 'ADDED' || type === 'MODIFIED') && onUpdate(object as V1Pod)) { + finish('matched') } - ) + }, + (error: unknown) => { + if (!error) return finish('ended') + const status = watchStatus(error) + if (status === 403) { + return fail( + new KubernetesSandboxConfigError( + `Sim's service account may not watch pods in namespace "${this.namespace}" (SANDBOX_K8S_NAMESPACE). Grant it the watch verb on pods in the sandbox Role.` + ) + ) + } + logger.debug('Sandbox pod watch ended', { name, status, error: getErrorMessage(error) }) + finish('ended') + } + ) + connecting.catch(fail) + try { return await outcome } finally { signal.removeEventListener('abort', onAbort) - controller?.abort() + void connecting.then( + (controller) => controller.abort(), + () => {} + ) } } - async setExpiresAt(name: string, expiresAtMs: number): Promise { - await callApi( + async setExpiresAt(name: string, expiresAtMs: number, options: CallOptions = {}): Promise { + await this.call( 'pod patch', - () => + (request) => this.core.patchNamespacedPod( { name, namespace: this.namespace, body: { metadata: { annotations: { [EXPIRES_AT_ANNOTATION]: String(expiresAtMs) } } }, }, - this.mergePatch + request ), - true + { retry: true, contentType: MERGE_PATCH, ...options } ) } - async deletePod(name: string): Promise { + async deletePod(name: string, options: CallOptions = {}): Promise { try { - await callApi( + await this.call( 'pod delete', - () => - this.core.deleteNamespacedPod({ - name, - namespace: this.namespace, - gracePeriodSeconds: 0, - }), - true + (request) => this.core.deleteNamespacedPod({ name, namespace: this.namespace }, request), + { retry: true, ...options } ) } catch (error) { if (isKubernetesStatus(error, 404)) return @@ -246,16 +350,19 @@ class ClientSandboxCluster implements SandboxCluster { } } -async function loadPatchOptions() { - const { PatchStrategy, setHeaderOptions } = await import('@kubernetes/client-node') - return setHeaderOptions('Content-Type', PatchStrategy.MergePatch) -} - /** - * Loads cluster credentials the standard way: `KUBECONFIG` (or `~/.kube/config`) when present, - * otherwise the pod's in-cluster service account. + * Loads cluster credentials: the file `KUBECONFIG` names (or `~/.kube/config`) when out of the + * cluster, otherwise the pod's in-cluster service account. Throws when there is neither, instead + * of client-node's silent fallback to an unauthenticated `http://localhost:8080`. */ export async function loadDefaultKubeConfig(): Promise { + const kubeconfigFile = process.env.KUBECONFIG?.trim() + const homeConfig = path.join(process.env.HOME || homedir(), '.kube', 'config') + if (!kubeconfigFile && !existsSync(homeConfig) && !existsSync(SERVICE_ACCOUNT_TOKEN_PATH)) { + throw new KubernetesSandboxConfigError( + 'Sim found no Kubernetes credentials: no KUBECONFIG, no ~/.kube/config, and no in-cluster service-account token. Run Sim in the cluster with a service account bound to the sandbox Role (and its token mounted), or set KUBECONFIG.' + ) + } const { KubeConfig } = await import('@kubernetes/client-node') const config = new KubeConfig() config.loadFromDefault() @@ -267,12 +374,17 @@ export async function openSandboxCluster( config: KubeConfig, namespace: string ): Promise { - const { CoreV1Api, NodeV1Api, Watch } = await import('@kubernetes/client-node') + const { + CoreV1Api, + NodeV1Api, + Observable: ObservableClass, + Watch, + } = await import('@kubernetes/client-node') return new ClientSandboxCluster( namespace, config.makeApiClient(CoreV1Api), config.makeApiClient(NodeV1Api), new Watch(config), - await loadPatchOptions() + ObservableClass ) } diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/handle.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/handle.ts deleted file mode 100644 index 78a01372de9..00000000000 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/handle.ts +++ /dev/null @@ -1,132 +0,0 @@ -import type { createAgentSandboxHandle } from '@/lib/execution/remote-sandbox/agent/handle' -import type { SandboxCluster } from '@/lib/execution/remote-sandbox/kubernetes/cluster' -import type { - RunCommandOptions, - SandboxCodeResult, - SandboxCommandResult, - SandboxDirectoryEntry, - SandboxHandle, -} from '@/lib/execution/remote-sandbox/types' - -type AgentHandle = ReturnType - -/** The pod a handle runs in, as the control plane last recorded it. */ -interface SandboxPodLease { - name: string - /** The pod's `sim.ai/expires-at`. */ - expiresAtMs: number - /** When `activeDeadlineSeconds` ends the pod, whatever the agent's deadline says. */ - hardDeadlineMs: number -} - -/** - * The agent handle for one sandbox pod, with lifetime extension bound to the pod. An extension is - * capped at the pod's hard deadline (Kubernetes ends the pod there regardless), and recorded in - * the pod's `sim.ai/expires-at` before the agent is asked for it, so the reaper, which reads only - * the annotation, never deletes a pod whose agent was told to stay up. Both deadlines are measured - * on Sim's clock, so a skewed node clock cannot shorten one. - */ -class KubernetesSandboxHandle implements SandboxHandle { - readonly sandboxId: string - readonly verifiesCliAtLaunch?: boolean - readonly extendLifetime?: (lifetimeMs: number) => Promise - readonly outlives?: (lifetimeMs: number, fromMs: number) => boolean - private annotatedAtMs: number - - constructor( - private readonly agent: AgentHandle, - private readonly lease: SandboxPodLease, - private readonly cluster: SandboxCluster - ) { - this.sandboxId = agent.sandboxId - this.annotatedAtMs = lease.expiresAtMs - if (agent.verifiesCliAtLaunch !== undefined) - this.verifiesCliAtLaunch = agent.verifiesCliAtLaunch - const { outlives, extendLifetime } = agent - if (outlives && extendLifetime) { - this.outlives = (lifetimeMs, fromMs) => outlives.call(agent, lifetimeMs, fromMs) - this.extendLifetime = (lifetimeMs) => this.extend(lifetimeMs, extendLifetime.bind(agent)) - } - } - - private async extend( - lifetimeMs: number, - extendAgent: (lifetimeMs: number) => Promise - ): Promise { - const now = Date.now() - const grantedMs = Math.min(lifetimeMs, this.lease.hardDeadlineMs - now) - if (grantedMs <= 0) return - const expiresAtMs = now + grantedMs - if (expiresAtMs > this.annotatedAtMs) { - await this.cluster.setExpiresAt(this.lease.name, expiresAtMs) - this.annotatedAtMs = expiresAtMs - } - await extendAgent(grantedMs) - } - - runCode( - code: string, - options: Parameters[1] - ): Promise { - return this.agent.runCode(code, options) - } - - runCommand(command: string, options: RunCommandOptions): Promise { - return this.agent.runCommand(command, options) - } - - getFileSize(path: string): Promise { - return this.agent.getFileSize(path) - } - - readFile(path: string): Promise { - return this.agent.readFile(path) - } - - readFileStream( - path: string, - options: { signal: AbortSignal } - ): Promise> { - return this.agent.readFileStream(path, options) - } - - readFileWithLimit( - path: string, - options: { maxBytes: number; encoding: 'utf8' | 'base64'; signal?: AbortSignal } - ): Promise<{ content: string; byteLength: number }> { - return this.agent.readFileWithLimit(path, options) - } - - writeFile(path: string, content: string | ArrayBuffer): Promise { - return this.agent.writeFile(path, content) - } - - writeFileStream( - path: string, - content: ReadableStream, - options: { signal: AbortSignal } - ): Promise { - return this.agent.writeFileStream(path, content, options) - } - - removeFile(path: string): Promise { - return this.agent.removeFile(path) - } - - listFiles(path: string, options?: { depth?: number }): Promise { - return this.agent.listFiles(path, options) - } - - kill(): Promise { - return this.agent.kill() - } -} - -/** Binds an agent handle to the pod it runs in; see {@link KubernetesSandboxHandle}. */ -export function bindSandboxPod( - agent: AgentHandle, - lease: SandboxPodLease, - cluster: SandboxCluster -): SandboxHandle { - return new KubernetesSandboxHandle(agent, lease, cluster) -} diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts index 4089772b4b5..e2ab7969254 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/pod.ts @@ -180,9 +180,19 @@ export function buildSandboxPod(input: SandboxPodInput): V1Pod { } } +/** True for a pod this provider created, by its managed-by label. */ +export function isSimManagedPod(pod: V1Pod): boolean { + return pod.metadata?.labels?.[MANAGED_BY_LABEL] === MANAGED_BY_VALUE +} + /** * The agent's base URL, read from the pod itself: its IP and the port its sandbox container * declares. Null until the pod has an IP. + * + * The transport is plain HTTP on the pod network: the agent's bearer token and every command and + * file cross it unencrypted. That is why the sandbox namespace must admit only Sim's pods on the + * agent port (a NetworkPolicy), and why each token is derived per pod, so one pod's token cannot + * open another's agent. */ export function agentBaseUrl(pod: V1Pod): string | null { const ip = pod.status?.podIP diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.test.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.test.ts index c5d8d4cd83c..2a24b01ccb2 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.test.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.test.ts @@ -7,11 +7,15 @@ import { createServer, type IncomingMessage, type Server, type ServerResponse } import type { AddressInfo } from 'node:net' import { tmpdir } from 'node:os' import path from 'node:path' -import type { V1Pod } from '@kubernetes/client-node' -import { SANDBOX_AGENT_TOKEN_SHA256_ENV } from '@sim/sandbox-agent-protocol' +import type { CoreV1Event, V1Pod } from '@kubernetes/client-node' +import { SANDBOX_AGENT_PORT, SANDBOX_AGENT_TOKEN_SHA256_ENV } from '@sim/sandbox-agent-protocol' import { setEnv } from '@sim/testing/mocks/env.mock' import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import { env } from '@/lib/core/config/env' +import { + markInsideTriggerRun, + resetInsideTriggerRunForTests, +} from '@/lib/core/config/trigger-runtime' import { KubernetesSandboxCapacityError, KubernetesSandboxConfigError, @@ -25,16 +29,23 @@ import { /** * Drives the production provider, configured through its env vars and a real `KUBECONFIG` file, - * through the real `@kubernetes/client-node` against an in-process API server speaking the REST - * shapes the client uses (pods create/get/list/watch/patch/delete, RuntimeClass get), plus a - * stand-in agent that checks bearer tokens against the pod's digest. The fake kubelet moves a pod - * to Running at the stand-in agent's loopback address and port. + * through the real `@kubernetes/client-node` against an in-process API server, plus a stand-in + * agent on the agent port that checks bearer tokens against the pod's digest. + * + * The fake API server speaks the REST shapes the client uses: pods create/get/list (honouring + * `limit` and `continue`, and free to return short pages as the API allows), watch (replaying + * from a resourceVersion, and scriptable to fail or end early), merge-patch (refusing any other + * Content-Type), delete (marking `deletionTimestamp` before removal), events list, and + * RuntimeClass get. Its kubelet stand-in only ever writes pod status; its scheduler stand-in only + * binds `spec.nodeName`, as the real binding subresource does. * * Each test gets its own namespace: the provider opens one cluster client, with its own * RuntimeClass verdict, per namespace, so a test never sees another's cached verdict. */ const HOUR_MS = 60 * 60 * 1000 +const MERGE_PATCH = 'application/merge-patch+json' +const OTHER_SECRET = 'a-different-internal-secret-0123456789' let namespace = '' let namespaceCount = 0 let kubeconfigDirectory = '' @@ -48,6 +59,15 @@ interface StoredEvent { pod: V1Pod } +/** How the next watch request is answered; unscripted watches stream normally. */ +type WatchStep = + | { kind: 'status'; code: number } + | { kind: 'close' } + | { kind: 'error-event'; code: number } + +/** How the next pod create is answered; unscripted creates succeed. */ +type CreateStep = 'store-then-drop' | 'conflict' | 'quota' | 'forbidden' + interface Watcher { name: string response: ServerResponse @@ -75,11 +95,20 @@ function matchesSelector(pod: V1Pod, selector: string | null): boolean { class FakeKubernetes { readonly pods = new Map() readonly runtimeClasses = new Map() - readonly log: string[] = [] - quotaExceeded = false + readonly events: CoreV1Event[] = [] + readonly watchScript: WatchStep[] = [] + readonly createScript: CreateStep[] = [] + readonly watchStartedAt: number[] = [] + /** Query strings of every pod DELETE, to check how a delete was asked for. */ + readonly deleteQueries: string[] = [] + /** When set, RuntimeClass reads are accepted but never answered. */ + hangRuntimeClassReads = false + private hung: ServerResponse[] = [] + /** The API may return fewer items than `limit`; a small page exercises `continue`. */ + maxPageSize = Number.POSITIVE_INFINITY /** Runs after a pod is stored, standing in for the scheduler and kubelet. */ onCreate: (name: string) => void = () => {} - private events: StoredEvent[] = [] + private log: StoredEvent[] = [] private watchers = new Set() private resourceVersion = 1 private server: Server @@ -105,11 +134,20 @@ class FakeKubernetes { } reset(): void { + for (const watcher of this.watchers) watcher.response.end() + this.watchers.clear() this.pods.clear() this.runtimeClasses.clear() - this.log.length = 0 - this.events = [] - this.quotaExceeded = false + this.events.length = 0 + this.watchScript.length = 0 + this.createScript.length = 0 + this.watchStartedAt.length = 0 + this.deleteQueries.length = 0 + this.hangRuntimeClassReads = false + for (const response of this.hung) response.destroy() + this.hung = [] + this.log = [] + this.maxPageSize = Number.POSITIVE_INFINITY this.onCreate = () => {} } @@ -138,24 +176,48 @@ class FakeKubernetes { } if (type === 'DELETED') this.pods.delete(name) else this.pods.set(name, stored) - const event = { resourceVersion: this.resourceVersion, type, pod: stored } - this.events.push(event) + this.log.push({ resourceVersion: this.resourceVersion, type, pod: stored }) for (const watcher of this.watchers) { - if (watcher.name === name) + if (watcher.name === name) { watcher.response.write(`${JSON.stringify({ type, object: stored })}\n`) + } } return stored } - update(name: string, mutate: (pod: V1Pod) => V1Pod): void { + /** The kubelet stand-in: replaces a pod's status, never its spec. */ + setStatus(name: string, status: V1Pod['status']): void { + const pod = this.pods.get(name) + if (pod) this.put({ ...pod, status }) + } + + /** The scheduler stand-in: binds the pod to a node, as the binding subresource does. */ + bind(name: string, nodeName: string): void { + const pod = this.pods.get(name) + if (pod?.spec) this.put({ ...pod, spec: { ...pod.spec, nodeName } }) + } + + /** + * Deletes as the API server does: marked terminating first, removed once it has stopped. A force + * delete (grace period zero, as another actor may issue) skips straight to removal. + */ + remove(name: string, force = false): void { const pod = this.pods.get(name) - if (pod) this.put(mutate(pod)) + if (!pod) return + if (force) { + this.put(pod, 'DELETED') + return + } + this.put({ ...pod, metadata: { ...pod.metadata, deletionTimestamp: new Date() } }) + setTimeout(() => { + const terminating = this.pods.get(name) + if (terminating) this.put(terminating, 'DELETED') + }, 20) } private async handle(request: IncomingMessage, response: ServerResponse): Promise { const url = new URL(request.url ?? '/', 'http://fake') const method = request.method ?? 'GET' - this.log.push(`${method} ${url.pathname}`) timeline.push(`api ${method} ${url.pathname}`) const json = (code: number, body: unknown) => { response.writeHead(code, { 'Content-Type': 'application/json' }).end(JSON.stringify(body)) @@ -163,6 +225,10 @@ class FakeKubernetes { const runtimeClass = /^\/apis\/node\.k8s\.io\/v1\/runtimeclasses\/([^/]+)$/.exec(url.pathname) if (runtimeClass && method === 'GET') { + if (this.hangRuntimeClassReads) { + this.hung.push(response) + return + } const handler = this.runtimeClasses.get(runtimeClass[1]) if (handler === undefined) return json(404, statusBody(404, 'NotFound', 'not found')) return json(200, { @@ -173,11 +239,25 @@ class FakeKubernetes { }) } + if (url.pathname === `/api/v1/namespaces/${namespace}/events` && method === 'GET') { + const involved = (url.searchParams.get('fieldSelector') ?? '').replace( + 'involvedObject.name=', + '' + ) + return json(200, { + apiVersion: 'v1', + kind: 'EventList', + metadata: {}, + items: this.events.filter((event) => event.involvedObject.name === involved), + }) + } + const collection = `/api/v1/namespaces/${namespace}/pods` if (url.pathname === collection && method === 'POST') { const pod = (await readBody(request)) as V1Pod const name = pod.metadata?.name ?? '' - if (this.quotaExceeded) { + const step = this.createScript.shift() + if (step === 'quota') { return json( 403, statusBody( @@ -187,44 +267,51 @@ class FakeKubernetes { ) ) } - if (this.pods.has(name)) return json(409, statusBody(409, 'AlreadyExists', 'exists')) + if (step === 'forbidden') { + return json( + 403, + statusBody( + 403, + 'Forbidden', + 'pods is forbidden: User "sim" cannot create resource "pods"' + ) + ) + } + if (step === 'conflict' || this.pods.has(name)) { + return json(409, statusBody(409, 'AlreadyExists', `pods "${name}" already exists`)) + } const stored = this.put( { ...pod, - metadata: { - ...pod.metadata, - uid: `uid-${name}`, - creationTimestamp: new Date(), - }, + metadata: { ...pod.metadata, uid: `uid-${name}`, creationTimestamp: new Date() }, status: { phase: 'Pending' }, }, 'ADDED' ) - json(201, stored) this.onCreate(name) - return + // The pod exists, but the client never hears so: the create's outcome is ambiguous. + if (step === 'store-then-drop') return void request.socket.destroy() + return json(201, stored) } if (url.pathname === collection && method === 'GET') { - if (url.searchParams.get('watch') === 'true') { - const name = (url.searchParams.get('fieldSelector') ?? '').replace('metadata.name=', '') - const from = Number(url.searchParams.get('resourceVersion') ?? '0') - response.writeHead(200, { 'Content-Type': 'application/json' }) - for (const event of this.events) { - if (event.resourceVersion > from && event.pod.metadata?.name === name) { - response.write(`${JSON.stringify({ type: event.type, object: event.pod })}\n`) - } - } - const watcher = { name, response } - this.watchers.add(watcher) - request.on('close', () => this.watchers.delete(watcher)) - return - } + if (url.searchParams.get('watch') === 'true') return this.watch(url, request, response) const selector = url.searchParams.get('labelSelector') + const matching = [...this.pods.values()].filter((pod) => matchesSelector(pod, selector)) + const offset = Number(url.searchParams.get('continue') ?? '0') + const pageSize = Math.min( + Number(url.searchParams.get('limit') ?? Number.POSITIVE_INFINITY), + this.maxPageSize + ) + const items = matching.slice(offset, offset + pageSize) + const next = offset + items.length return json(200, { apiVersion: 'v1', kind: 'PodList', - metadata: { resourceVersion: String(this.resourceVersion) }, - items: [...this.pods.values()].filter((pod) => matchesSelector(pod, selector)), + metadata: { + resourceVersion: String(this.resourceVersion), + ...(next < matching.length ? { continue: String(next) } : {}), + }, + items, }) } @@ -234,62 +321,93 @@ class FakeKubernetes { if (!pod) return json(404, statusBody(404, 'NotFound', `pods "${item[1]}" not found`)) if (method === 'GET') return json(200, pod) if (method === 'DELETE') { - this.put(pod, 'DELETED') - return json(200, pod) + this.deleteQueries.push(url.search) + this.remove(item[1]) + return json(200, this.pods.get(item[1])) } if (method === 'PATCH') { + if (request.headers['content-type'] !== MERGE_PATCH) { + return json(415, statusBody(415, 'UnsupportedMediaType', 'unsupported patch type')) + } const patch = (await readBody(request)) as V1Pod - const patched = this.put({ - ...pod, - metadata: { - ...pod.metadata, - annotations: { ...pod.metadata?.annotations, ...patch.metadata?.annotations }, - }, - }) - return json(200, patched) + return json( + 200, + this.put({ + ...pod, + metadata: { + ...pod.metadata, + annotations: { ...pod.metadata?.annotations, ...patch.metadata?.annotations }, + }, + }) + ) } } json(404, statusBody(404, 'NotFound', 'no route')) } + + private watch(url: URL, request: IncomingMessage, response: ServerResponse): void { + this.watchStartedAt.push(Date.now()) + const step = this.watchScript.shift() + if (step?.kind === 'status') { + response.writeHead(step.code, { 'Content-Type': 'application/json' }) + response.end(JSON.stringify(statusBody(step.code, 'Scripted', 'scripted watch failure'))) + return + } + response.writeHead(200, { 'Content-Type': 'application/json' }) + if (step?.kind === 'close') return void response.end() + if (step?.kind === 'error-event') { + const status = statusBody(step.code, 'Expired', 'too old resource version') + return void response.end(`${JSON.stringify({ type: 'ERROR', object: status })}\n`) + } + const name = (url.searchParams.get('fieldSelector') ?? '').replace('metadata.name=', '') + const from = Number(url.searchParams.get('resourceVersion') ?? '0') + for (const event of this.log) { + if (event.resourceVersion > from && event.pod.metadata?.name === name) { + response.write(`${JSON.stringify({ type: event.type, object: event.pod })}\n`) + } + } + const watcher = { name, response } + this.watchers.add(watcher) + request.on('close', () => this.watchers.delete(watcher)) + } } -/** Stand-in agent: answers health checks and accepts lifetime extensions under the pod's token. */ +/** Stand-in agent on the agent port: health checks, lifetime extensions, and signals. */ class FakeAgent { readonly log: string[] = [] /** Token digests the agent accepts, as the pod env would hand them over. */ readonly accepted = new Set() private server: Server - port = 0 constructor() { this.server = createServer(async (request, response) => { const url = new URL(request.url ?? '/', 'http://agent') + const reply = (code: number, body: unknown) => { + response.writeHead(code, { 'Content-Type': 'application/json' }).end(JSON.stringify(body)) + } if (url.pathname === '/healthz') { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify({ ok: true, protocol: 1, agentVersion: 'fake' })) - return + return reply(200, { ok: true, protocol: 1, agentVersion: 'fake' }) } const token = /^Bearer (.+)$/.exec(request.headers.authorization ?? '')?.[1] ?? '' if (!this.accepted.has(createHash('sha256').update(token).digest('hex'))) { - response.writeHead(401, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify({ error: { code: 'unauthorized', message: 'no' } })) - return + return reply(401, { error: { code: 'unauthorized', message: 'no' } }) } const body = await readBody(request) this.log.push(`${request.method} ${url.pathname}`) timeline.push(`agent ${request.method} ${url.pathname}`) - if (url.pathname === '/v1/lifetime') { - response.writeHead(200, { 'Content-Type': 'application/json' }) - response.end(JSON.stringify(body)) - return - } - response.writeHead(200, { 'Content-Type': 'application/json' }).end('{}') + reply(200, url.pathname === '/v1/lifetime' ? body : {}) }) } + /** + * Binds the agent port on loopback, where the kubelet stand-in places every pod. The provider + * reads the port from the pod spec, which only the real scheduler and kubelet may change. + */ async start(): Promise { - await new Promise((resolve) => this.server.listen(0, '127.0.0.1', resolve)) - this.port = (this.server.address() as AddressInfo).port + await new Promise((resolve, reject) => { + this.server.once('error', reject) + this.server.listen(SANDBOX_AGENT_PORT, '127.0.0.1', resolve) + }) } async stop(): Promise { @@ -302,44 +420,64 @@ const cluster = new FakeKubernetes() const agent = new FakeAgent() /** Selects the provider's isolation settings for this test, as an operator would in env. */ -function configure(isolation: { runtimeClass?: string; allowUnisolated?: boolean } = {}) { +function configure( + isolation: { runtimeClass?: string; allowUnisolated?: boolean; trustedHandlers?: string } = {} +) { setEnv({ SANDBOX_K8S_NAMESPACE: namespace, SANDBOX_K8S_RUNTIME_CLASS: isolation.runtimeClass ?? 'gvisor', SANDBOX_K8S_ALLOW_UNISOLATED: isolation.allowUnisolated ? 'true' : undefined, + SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS: isolation.trustedHandlers, }) return kubernetesProvider } -/** The fake kubelet: starts the pod at the stand-in agent, accepting the digest the pod carries. */ -function runPod(pod: V1Pod): V1Pod { - const container = pod.spec?.containers[0] - const digest = container?.env?.find(({ name }) => name === SANDBOX_AGENT_TOKEN_SHA256_ENV)?.value +function digestFor(name: string, secret = env.INTERNAL_API_SECRET): string { + return sandboxAgentTokenDigest(deriveSandboxAgentToken(secret, name)) +} + +function runningStatus(startTime = new Date()): V1Pod['status'] { + return { + phase: 'Running', + podIP: '127.0.0.1', + startTime, + containerStatuses: [ + { + name: 'sandbox', + image: 'registry/function:1', + imageID: '', + ready: true, + restartCount: 0, + state: { running: {} }, + }, + ], + } +} + +/** The kubelet stand-in starting a pod: the agent accepts the digest the pod was created with. */ +function startPod(name: string): void { + const digest = cluster.pods + .get(name) + ?.spec?.containers[0]?.env?.find( + ({ name: variable }) => variable === SANDBOX_AGENT_TOKEN_SHA256_ENV + )?.value if (digest) agent.accepted.add(digest) + cluster.setStatus(name, runningStatus()) +} + +function waitingStatus(reason: string, message: string): V1Pod['status'] { return { - ...pod, - spec: pod.spec && { - ...pod.spec, - containers: pod.spec.containers.map((entry) => ({ - ...entry, - ports: [{ name: 'agent', containerPort: agent.port }], - })), - }, - status: { - phase: 'Running', - podIP: '127.0.0.1', - startTime: new Date(), - containerStatuses: [ - { - name: 'sandbox', - image: container?.image ?? '', - imageID: '', - ready: true, - restartCount: 0, - state: { running: {} }, - }, - ], - }, + phase: 'Pending', + containerStatuses: [ + { + name: 'sandbox', + image: 'registry/function:1', + imageID: '', + ready: false, + restartCount: 0, + state: { waiting: { reason, message } }, + }, + ], } } @@ -352,12 +490,12 @@ function seedPod(options: { sessionKey?: string secret?: string managed?: boolean + runtimeClassName?: string }): void { const now = Date.now() const created = new Date(now - options.createdAgoMs) - const digest = sandboxAgentTokenDigest( - deriveSandboxAgentToken(options.secret ?? env.INTERNAL_API_SECRET, options.name) - ) + const digest = digestFor(options.name, options.secret) + const phase = options.phase ?? 'Running' cluster.put( { metadata: { @@ -377,20 +515,17 @@ function seedPod(options: { : { 'sim.ai/expires-at': String(now + options.expiresInMs) }, }, spec: { + runtimeClassName: options.runtimeClassName ?? 'gvisor', containers: [ { name: 'sandbox', image: 'registry/function:1', env: [{ name: SANDBOX_AGENT_TOKEN_SHA256_ENV, value: digest }], - ports: [{ name: 'agent', containerPort: agent.port }], + ports: [{ name: 'agent', containerPort: SANDBOX_AGENT_PORT }], }, ], }, - status: { - phase: options.phase ?? 'Running', - podIP: '127.0.0.1', - startTime: created, - }, + status: phase === 'Running' ? runningStatus(created) : { phase }, }, 'ADDED' ) @@ -419,20 +554,17 @@ beforeEach(() => { }) afterEach(() => { - cluster.onCreate = () => {} + vi.useRealTimers() + resetInsideTriggerRunForTests() }) describe('create', () => { - it('watches a new pod to Running, then hands back a handle its agent authenticates', async () => { - cluster.onCreate = (name) => { - setTimeout(() => cluster.update(name, runPod), 50) - } + it('watches a new pod to Running and hands back a handle its agent authenticates', async () => { + cluster.onCreate = (name) => setTimeout(() => startPod(name), 50) const sandbox = await configure().create('code', { lifetimeMs: 60_000, sessionKey: 'chat-1' }) - const pod = cluster.pods.get(sandbox.sandboxId) - expect(pod?.spec?.runtimeClassName).toBe('gvisor') - expect(pod?.metadata?.labels?.['sim.ai/session']).toBe(sessionLabelValue('chat-1')) - expect(cluster.log).toContain(`GET /api/v1/namespaces/${namespace}/pods`) + expect(cluster.pods.get(sandbox.sandboxId)?.spec?.runtimeClassName).toBe('gvisor') + expect(cluster.watchStartedAt.length).toBeGreaterThan(0) await sandbox.extendLifetime?.(10 * 60_000) expect(agent.log).toEqual(['POST /v1/lifetime']) @@ -440,8 +572,8 @@ describe('create', () => { cluster.pods.get(sandbox.sandboxId)?.metadata?.annotations?.['sim.ai/expires-at'] ) expect(annotated).toBeGreaterThan(Date.now() + 9 * 60_000) - // The pod's annotation is moved before the agent is asked, so the reaper never sees a pod - // whose agent outlives its recorded deadline. + // The pod's annotation moves before the agent is asked, so the reaper never sees a pod whose + // agent outlives its recorded deadline. const patched = timeline.indexOf( `api PATCH /api/v1/namespaces/${namespace}/pods/${sandbox.sandboxId}` ) @@ -449,11 +581,13 @@ describe('create', () => { expect(patched).toBeLessThan(timeline.indexOf('agent POST /v1/lifetime')) await sandbox.kill() - expect(cluster.pods.has(sandbox.sandboxId)).toBe(false) + await vi.waitFor(() => expect(cluster.pods.has(sandbox.sandboxId)).toBe(false)) + // Deleted with the pod's own termination grace period, never forced. + expect(cluster.deleteQueries).toEqual(['']) }) - it('reports an exhausted ResourceQuota as a capacity limit and creates nothing', async () => { - cluster.quotaExceeded = true + it('reports an exhausted ResourceQuota as a capacity limit and leaves no pod', async () => { + cluster.createScript.push('quota') const error = await configure() .create('code', { lifetimeMs: 60_000 }) .catch((caught: unknown) => caught) @@ -462,33 +596,184 @@ describe('create', () => { expect(cluster.pods.size).toBe(0) }) - it('fails fast on an image the cluster cannot pull, naming the variable, and deletes the pod', async () => { + it('reports a create the service account may not make as configuration, naming the namespace', async () => { + cluster.createScript.push('forbidden') + const error = await configure() + .create('code', { lifetimeMs: 60_000 }) + .catch((caught: unknown) => caught) + expect(error).toBeInstanceOf(KubernetesSandboxConfigError) + expect(String(error)).toMatch(/SANDBOX_K8S_NAMESPACE/) + }) + + it('adopts its own pod when the create it retries had already succeeded', async () => { + cluster.createScript.push('store-then-drop') + cluster.onCreate = (name) => startPod(name) + const created = await configure().create('code', { lifetimeMs: 60_000 }) + expect([...cluster.pods.keys()]).toEqual([created.sandboxId]) + expect(timeline.filter((entry) => entry.startsWith('api POST'))).toHaveLength(2) + }) + + it('takes a fresh name when its first name collides with a pod it did not make', async () => { + cluster.createScript.push('conflict') + cluster.onCreate = (name) => startPod(name) + const created = await configure().create('code', { lifetimeMs: 60_000 }) + expect(timeline.filter((entry) => entry.startsWith('api POST'))).toHaveLength(2) + expect([...cluster.pods.keys()]).toEqual([created.sandboxId]) + }) + + it('deletes a pod an unanswered create may have made when the create then fails', async () => { + cluster.createScript.push('store-then-drop', 'quota') + await expect(configure().create('code', { lifetimeMs: 60_000 })).rejects.toThrow( + /ResourceQuota/ + ) + await vi.waitFor(() => expect(cluster.pods.size).toBe(0)) + }) + + it('fails at once on an image that does not exist, naming the variable, and deletes the pod', async () => { + cluster.onCreate = (name) => + setTimeout( + () => + cluster.setStatus( + name, + waitingStatus( + 'ErrImagePull', + 'Failed to pull image "registry/function:1": rpc error: code = NotFound desc = failed to pull and unpack image "registry/function:1": failed to resolve reference "registry/function:1": registry/function:1: not found' + ) + ), + 20 + ) + const startedAt = Date.now() + await expect(configure().create('code', { lifetimeMs: 60_000 })).rejects.toThrow( + /SANDBOX_K8S_FUNCTION_IMAGE/ + ) + expect(Date.now() - startedAt).toBeLessThan(10_000) + await vi.waitFor(() => expect(cluster.pods.size).toBe(0)) + }) + + it('waits out a transient pull failure instead of failing the create', async () => { cluster.onCreate = (name) => { setTimeout( () => - cluster.update(name, (pod) => ({ - ...pod, - status: { - phase: 'Pending', - containerStatuses: [ - { - name: 'sandbox', - image: 'registry/function:1', - imageID: '', - ready: false, - restartCount: 0, - state: { waiting: { reason: 'ImagePullBackOff', message: 'pull denied' } }, - }, - ], - }, - })), + cluster.setStatus( + name, + waitingStatus( + 'ImagePullBackOff', + 'Back-off pulling image "registry/function:1": failed to do request: dial tcp: i/o timeout' + ) + ), 20 ) + setTimeout(() => startPod(name), 200) + } + const created = await configure().create('code', { lifetimeMs: 60_000 }) + expect(cluster.pods.get(created.sandboxId)?.status?.phase).toBe('Running') + }) + + it('deletes a pod that does not start before its create deadline, reporting the pull error', async () => { + cluster.onCreate = (name) => + cluster.setStatus( + name, + waitingStatus( + 'ErrImagePull', + 'Failed to pull image "registry/function:1": unexpected status: 503 Service Unavailable' + ) + ) + const error = await configure() + .create('code', { lifetimeMs: 1_500 }) + .catch((caught: unknown) => caught) + expect(error).toBeInstanceOf(KubernetesSandboxCapacityError) + expect(String(error)).toMatch(/503 Service Unavailable/) + await vi.waitFor(() => expect(cluster.pods.size).toBe(0)) + }) + + it('fails at once when the node has no runtime for the RuntimeClass', async () => { + cluster.watchScript.push({ kind: 'close' }) + cluster.onCreate = (name) => { + cluster.bind(name, 'node-a') + cluster.events.push({ + metadata: { name: `${name}.1` }, + involvedObject: { name, kind: 'Pod' }, + reason: 'FailedCreatePodSandBox', + type: 'Warning', + message: + 'Failed to create pod sandbox: rpc error: code = Unknown desc = failed to get sandbox runtime: no runtime for "runsc" is configured', + }) } await expect(configure().create('code', { lifetimeMs: 60_000 })).rejects.toThrow( - /SANDBOX_K8S_FUNCTION_IMAGE/ + /node-a cannot run RuntimeClass/ ) - expect(cluster.pods.size).toBe(0) + }) + + it('refuses to run inside a Trigger.dev worker, which cannot reach sandbox pods', async () => { + markInsideTriggerRun() + await expect(configure().create('code', { lifetimeMs: 60_000 })).rejects.toThrow( + /TRIGGER_DEV_ENABLED/ + ) + expect(timeline).toEqual([]) + }) + + it('refuses to guess credentials when there is no kubeconfig and no service account', async () => { + vi.stubEnv('KUBECONFIG', '') + vi.stubEnv('HOME', kubeconfigDirectory) + const error = await configure() + .create('code', { lifetimeMs: 60_000 }) + .catch((caught: unknown) => caught) + expect(error).toBeInstanceOf(KubernetesSandboxConfigError) + expect(String(error)).toMatch(/KUBECONFIG/) + expect(timeline).toEqual([]) + }) +}) + +describe('waiting for a pod', () => { + it('backs off between watches that end early or fail, instead of reconnecting at once', async () => { + cluster.watchScript.push( + { kind: 'close' }, + { kind: 'status', code: 429 }, + { kind: 'status', code: 500 } + ) + // Starts only after every scripted watch has been made, so each failure is followed by one. + cluster.onCreate = (name) => setTimeout(() => startPod(name), 2_500) + await configure().create('code', { lifetimeMs: 60_000 }) + const starts = cluster.watchStartedAt + const gaps = starts.slice(1, 4).map((at, index) => at - starts[index]) + expect(gaps).toHaveLength(3) + expect(gaps.every((gap) => gap >= 150)).toBe(true) + }) + + it('re-reads and keeps watching after its resourceVersion expires', async () => { + cluster.watchScript.push({ kind: 'status', code: 410 }, { kind: 'error-event', code: 410 }) + cluster.onCreate = (name) => setTimeout(() => startPod(name), 1_500) + const created = await configure().create('code', { lifetimeMs: 60_000 }) + expect(cluster.pods.get(created.sandboxId)?.status?.phase).toBe('Running') + expect(cluster.watchStartedAt.length).toBeGreaterThanOrEqual(3) + }) + + it('reports a watch the service account may not make as configuration', async () => { + cluster.watchScript.push({ kind: 'status', code: 403 }) + await expect(configure().create('code', { lifetimeMs: 60_000 })).rejects.toThrow( + /watch verb on pods/ + ) + }) + + it('fails as soon as the pod is force-deleted while starting', async () => { + cluster.onCreate = (name) => setTimeout(() => cluster.remove(name, true), 50) + const startedAt = Date.now() + await expect(configure().create('code', { lifetimeMs: 60_000 })).rejects.toThrow(/deleted/) + expect(Date.now() - startedAt).toBeLessThan(5_000) + }) + + it('cannot be held past its create deadline by an API request that never answers', async () => { + cluster.hangRuntimeClassReads = true + const startedAt = Date.now() + await expect(configure().create('code', { lifetimeMs: 1_500 })).rejects.toThrow() + expect(Date.now() - startedAt).toBeLessThan(5_000) + }) + + it('fails as soon as the pod is deleted while starting', async () => { + cluster.onCreate = (name) => setTimeout(() => cluster.remove(name), 50) + const startedAt = Date.now() + await expect(configure().create('code', { lifetimeMs: 60_000 })).rejects.toThrow(/deleted/) + expect(Date.now() - startedAt).toBeLessThan(5_000) }) }) @@ -498,36 +783,62 @@ describe('isolation guard', () => { await expect(configure().create('code', { lifetimeMs: 60_000 })).rejects.toThrow( KubernetesSandboxConfigError ) - expect(cluster.log.some((entry) => entry.startsWith('POST'))).toBe(false) + expect(timeline.some((entry) => entry.startsWith('api POST'))).toBe(false) }) - it('refuses a RuntimeClass whose handler shares the node kernel', async () => { + it('refuses a handler it does not recognise as isolating', async () => { cluster.runtimeClasses.set('gvisor', 'runc') - await expect(configure().create('code', { lifetimeMs: 60_000 })).rejects.toThrow(/runc/) - expect(cluster.log.some((entry) => entry.startsWith('POST'))).toBe(false) + await expect(configure().create('code', { lifetimeMs: 60_000 })).rejects.toThrow(/"runc"/) + expect(timeline.some((entry) => entry.startsWith('api POST'))).toBe(false) + }) + + it('accepts a custom handler only when the operator lists it as trusted', async () => { + cluster.runtimeClasses.set('gvisor', 'acme-microvm') + cluster.onCreate = (name) => startPod(name) + await expect(configure().create('code', { lifetimeMs: 60_000 })).rejects.toThrow( + /SANDBOX_K8S_TRUSTED_RUNTIME_HANDLERS/ + ) + namespace = `sandboxes-${++namespaceCount}` + await expect( + configure({ trustedHandlers: 'acme-microvm' }).create('code', { lifetimeMs: 60_000 }) + ).resolves.toBeDefined() }) it('reads the RuntimeClass once per provider, not per create', async () => { - cluster.onCreate = (name) => cluster.update(name, runPod) + cluster.onCreate = (name) => startPod(name) const sandboxes = configure() await sandboxes.create('code', { lifetimeMs: 60_000 }) await sandboxes.create('code', { lifetimeMs: 60_000 }) - expect(cluster.log.filter((entry) => entry.includes('runtimeclasses'))).toHaveLength(1) + expect(timeline.filter((entry) => entry.includes('runtimeclasses'))).toHaveLength(1) + }) + + it('keeps a refusal for thirty seconds, then reads the RuntimeClass again', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + cluster.runtimeClasses.set('gvisor', 'runc') + cluster.onCreate = (name) => startPod(name) + const sandboxes = configure() + await expect(sandboxes.create('code', { lifetimeMs: 60_000 })).rejects.toThrow(/"runc"/) + + cluster.runtimeClasses.set('gvisor', 'runsc') + await expect(sandboxes.create('code', { lifetimeMs: 60_000 })).rejects.toThrow(/"runc"/) + vi.setSystemTime(Date.now() + 31_000) + await expect(sandboxes.create('code', { lifetimeMs: 60_000 })).resolves.toBeDefined() + expect(timeline.filter((entry) => entry.includes('runtimeclasses'))).toHaveLength(2) }) it('runs without a RuntimeClass only when the operator opted into a shared kernel', async () => { cluster.runtimeClasses.clear() - cluster.onCreate = (name) => cluster.update(name, runPod) + cluster.onCreate = (name) => startPod(name) const sandbox = await configure({ runtimeClass: '', allowUnisolated: true }).create('code', { lifetimeMs: 60_000, }) expect(cluster.pods.get(sandbox.sandboxId)?.spec).not.toHaveProperty('runtimeClassName') - expect(cluster.log.some((entry) => entry.includes('runtimeclasses'))).toBe(false) + expect(timeline.some((entry) => entry.includes('runtimeclasses'))).toBe(false) }) }) describe('findSessionSandbox', () => { - it('reconnects to the oldest live pod this deployment can authenticate to', async () => { + it('reconnects to the oldest live pod this deployment can authenticate to and trusts', async () => { seedPod({ name: 'expired', createdAgoMs: 3 * HOUR_MS, expiresInMs: -1_000, sessionKey: 'chat' }) seedPod({ name: 'oldest-live', @@ -541,30 +852,36 @@ describe('findSessionSandbox', () => { createdAgoMs: 4 * HOUR_MS, expiresInMs: HOUR_MS, sessionKey: 'chat', - secret: 'a-different-internal-secret-0123456789', + secret: OTHER_SECRET, + }) + seedPod({ + name: 'shared-kernel', + createdAgoMs: 5 * HOUR_MS, + expiresInMs: HOUR_MS, + sessionKey: 'chat', + runtimeClassName: 'runc-class', }) seedPod({ name: 'pending', phase: 'Pending', - createdAgoMs: 5 * HOUR_MS, + createdAgoMs: 6 * HOUR_MS, expiresInMs: HOUR_MS, sessionKey: 'chat', }) seedPod({ name: 'other-chat', - createdAgoMs: 6 * HOUR_MS, + createdAgoMs: 7 * HOUR_MS, expiresInMs: HOUR_MS, sessionKey: 'x', }) const sandbox = await configure().findSessionSandbox?.('chat', { lifetimeMs: 60_000 }) expect(sandbox?.sandboxId).toBe('oldest-live') - // The reconnected handle authenticates with the token derived for that pod. await sandbox?.extendLifetime?.(2 * HOUR_MS) expect(agent.log).toEqual(['POST /v1/lifetime']) }) - it('skips a pod whose 24-hour cap falls inside the requested lease', async () => { + it('retires a pod too close to its 24-hour cap, so later lookups cannot split the session', async () => { seedPod({ name: 'near-cap', createdAgoMs: 23.9 * HOUR_MS, @@ -572,8 +889,16 @@ describe('findSessionSandbox', () => { sessionKey: 'chat', }) seedPod({ name: 'fresh', createdAgoMs: HOUR_MS, expiresInMs: HOUR_MS, sessionKey: 'chat' }) - const sandbox = await configure().findSessionSandbox?.('chat', { lifetimeMs: 30 * 60_000 }) - expect(sandbox?.sandboxId).toBe('fresh') + const sandboxes = configure() + const long = await sandboxes.findSessionSandbox?.('chat', { lifetimeMs: 30 * 60_000 }) + expect(long?.sandboxId).toBe('fresh') + const retiredAt = Number( + cluster.pods.get('near-cap')?.metadata?.annotations?.['sim.ai/expires-at'] + ) + expect(retiredAt).toBeLessThanOrEqual(Date.now()) + // A shorter lease no longer brings the retired pod back. + const short = await sandboxes.findSessionSandbox?.('chat', { lifetimeMs: 60_000 }) + expect(short?.sandboxId).toBe('fresh') }) it('resolves null when the session has no live pod', async () => { @@ -582,16 +907,51 @@ describe('findSessionSandbox', () => { }) }) +describe('stopSessionProcess', () => { + it("signals the process on the session's own pod", async () => { + seedPod({ name: 'workbench', createdAgoMs: HOUR_MS, expiresInMs: HOUR_MS, sessionKey: 'chat' }) + await configure().stopSessionProcess?.( + { id: 'process-1', sandboxId: 'workbench', sessionKey: 'chat' }, + AbortSignal.timeout(5_000) + ) + expect(agent.log).toEqual(['POST /v1/processes/process-1/signal']) + }) + + it('never signals a pod of another session, not made by Sim, or started with another token', async () => { + seedPod({ name: 'other-session', createdAgoMs: HOUR_MS, expiresInMs: HOUR_MS, sessionKey: 'x' }) + seedPod({ + name: 'not-ours', + createdAgoMs: HOUR_MS, + expiresInMs: HOUR_MS, + sessionKey: 'chat', + managed: false, + }) + seedPod({ + name: 'foreign-token', + createdAgoMs: HOUR_MS, + expiresInMs: HOUR_MS, + sessionKey: 'chat', + secret: OTHER_SECRET, + }) + // The stand-in agent would accept every token here, so only the provider's checks stop a call. + agent.accepted.add(digestFor('foreign-token')) + const sandboxes = configure() + for (const sandboxId of ['other-session', 'not-ours', 'foreign-token', 'missing']) { + await sandboxes.stopSessionProcess?.( + { id: 'process-1', sandboxId, sessionKey: 'chat' }, + AbortSignal.timeout(5_000) + ) + } + expect(agent.log).toEqual([]) + }) +}) + describe('reapExpiredSandboxes', () => { it('deletes finished pods and pods past their deadline plus grace, and nothing else', async () => { seedPod({ name: 'succeeded', phase: 'Succeeded', createdAgoMs: HOUR_MS, expiresInMs: HOUR_MS }) seedPod({ name: 'failed', phase: 'Failed', createdAgoMs: HOUR_MS, expiresInMs: HOUR_MS }) - seedPod({ - name: 'orphaned', - createdAgoMs: HOUR_MS, - // Past the five-minute grace. - expiresInMs: -6 * 60_000, - }) + // Past the five-minute grace. + seedPod({ name: 'orphaned', createdAgoMs: HOUR_MS, expiresInMs: -6 * 60_000 }) seedPod({ name: 'in-grace', createdAgoMs: HOUR_MS, expiresInMs: -60_000 }) seedPod({ name: 'live', createdAgoMs: HOUR_MS, expiresInMs: HOUR_MS }) seedPod({ name: 'unannotated-past-cap', createdAgoMs: 25 * HOUR_MS }) @@ -607,11 +967,22 @@ describe('reapExpiredSandboxes', () => { const result = await configure().reapExpiredSandboxes?.(AbortSignal.timeout(10_000)) expect(result).toEqual({ deleted: 4, deferred: 0, failed: 0 }) - expect([...cluster.pods.keys()].sort()).toEqual([ - 'in-grace', - 'live', - 'not-ours', - 'unannotated-young', - ]) + await vi.waitFor(() => + expect([...cluster.pods.keys()].sort()).toEqual([ + 'in-grace', + 'live', + 'not-ours', + 'unannotated-young', + ]) + ) + }) + + it('pages through a namespace larger than one API page', async () => { + cluster.maxPageSize = 2 + for (const name of ['a', 'b', 'c', 'd', 'e']) { + seedPod({ name, phase: 'Succeeded', createdAgoMs: HOUR_MS, expiresInMs: HOUR_MS }) + } + const result = await configure().reapExpiredSandboxes?.(AbortSignal.timeout(10_000)) + expect(result?.deleted).toBe(5) }) }) diff --git a/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.ts b/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.ts index 2c237b70e4b..d08d9f07218 100644 --- a/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.ts +++ b/apps/sim/lib/execution/remote-sandbox/kubernetes/provider.ts @@ -1,4 +1,4 @@ -import type { KubeConfig, V1Pod } from '@kubernetes/client-node' +import type { CoreV1Event, V1Pod } from '@kubernetes/client-node' import { createLogger } from '@sim/logger' import { healthzResponseSchema, @@ -6,11 +6,12 @@ import { sandboxAgentProcessSignalPath, } from '@sim/sandbox-agent-protocol' import { getErrorMessage } from '@sim/utils/errors' -import { sleep } from '@sim/utils/helpers' +import { interruptibleSleep, sleep } from '@sim/utils/helpers' import { generateShortId } from '@sim/utils/id' import { backoffWithJitter, parseRetryAfter } from '@sim/utils/retry' import { compareStrings } from '@sim/utils/string' import { env } from '@/lib/core/config/env' +import { isInsideTriggerRun } from '@/lib/core/config/trigger-runtime' import type { CodeLanguage } from '@/lib/execution/languages' import { SandboxAgentClient, @@ -29,11 +30,11 @@ import { KubernetesSandboxConfigError, toPodCreateError, } from '@/lib/execution/remote-sandbox/kubernetes/errors' -import { bindSandboxPod } from '@/lib/execution/remote-sandbox/kubernetes/handle' import { IsolationGuard } from '@/lib/execution/remote-sandbox/kubernetes/isolation' import { agentBaseUrl, buildSandboxPod, + isSimManagedPod, MANAGED_SELECTOR, podExpiresAtMs, podHardDeadlineMs, @@ -75,6 +76,8 @@ const CREATE_TIMEOUT_MS = 3 * 60_000 const MAX_CREATE_ATTEMPTS = 3 const CREATE_BACKOFF = { baseMs: 500, maxMs: 5_000 } +/** Pause before re-watching a pod whose watch ended without news; an API outage must not spin. */ +const WATCH_BACKOFF = { baseMs: 250, maxMs: 5_000 } const HEALTH_BACKOFF = { baseMs: 100, maxMs: 1_000 } const HEALTH_REQUEST_TIMEOUT_MS = 2_000 @@ -82,15 +85,38 @@ const HEALTH_REQUEST_TIMEOUT_MS = 2_000 const POD_NAME_PREFIX = 'sim-sbx-' const POD_NAME_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789' -/** Container waiting reasons that will not clear without an operator: fail the create now. */ -const FATAL_WAITING_REASONS = new Set([ - 'ErrImagePull', - 'ImagePullBackOff', +/** Container waiting reasons the kubelet never retries past: the create fails at once. */ +const PERMANENT_WAITING_REASONS = new Set([ 'InvalidImageName', 'ErrImageNeverPull', 'CreateContainerConfigError', ]) +/** Waiting reasons for an image pull the kubelet keeps retrying with back-off. */ +const PULL_WAITING_REASONS = new Set(['ErrImagePull', 'ImagePullBackOff']) + +/** + * Pull errors that no retry fixes: the image or tag does not exist, or the registry refused the + * credentials. The kubelet reports `Failed to pull image "": ` for + * ErrImagePull and `Back-off pulling image "": ` for ImagePullBackOff + * (kubernetes `pkg/kubelet/images/image_manager.go`). containerd's resolver phrases a missing + * reference as `: not found` (gRPC `code = NotFound`) and a refused credential as + * `pull access denied, repository does not exist or may require authorization` or `failed to + * authorize` (containerd `core/remotes/docker/resolver.go`); the registry's own `manifest unknown`, + * `401 Unauthorized`, and `403 Forbidden` pass through. Anything else (timeouts, 5xx, rate limits) + * is treated as transient and waited out until the create deadline. + */ +const PERMANENT_PULL_ERROR = + /code = NotFound|: not found\b|manifest unknown|pull access denied|failed to authorize|authorization failed|401 Unauthorized|403 Forbidden/i + +/** + * The node has no runtime for the pod's RuntimeClass handler: containerd reports + * `no runtime for "" is configured`, and older runtimes `RuntimeHandler "" not + * supported`, in the kubelet's FailedCreatePodSandBox event. + */ +const MISSING_RUNTIME_HANDLER = + /no runtime for "[^"]*" is configured|RuntimeHandler "[^"]*" not supported/ + /** Rounds to whole seconds (the pod deadline's unit) and caps at the pod's hard lifetime. */ function resolveKubernetesSandboxLifetimeMs(lifetimeMs: number): number { return Math.min(Math.ceil(lifetimeMs / 1000) * 1000, SANDBOX_POD_MAX_LIFETIME_MS) @@ -102,14 +128,14 @@ function newPodName(): string { type PodProgress = | { state: 'ready'; baseUrl: string } - | { state: 'pending'; detail?: string } + | { state: 'pending'; detail?: string; pullError?: string } | { state: 'failed'; error: Error } /** * Where a starting pod stands. `failed` when it can no longer become ready: it finished, is being - * deleted, or one of its containers is stuck on an image or configuration problem. Returned rather - * than thrown, because it is also evaluated inside the watch callback, whose errors the client - * discards. + * deleted, or a container is stuck on a problem no retry fixes. A transient pull failure stays + * `pending`, carrying its message for the deadline error. Returned rather than thrown, because it + * is also evaluated inside the watch callback, whose errors the client discards. */ function podProgress(pod: V1Pod, kind: SandboxKind): PodProgress { const name = pod.metadata?.name ?? 'sandbox pod' @@ -129,15 +155,25 @@ function podProgress(pod: V1Pod, kind: SandboxKind): PodProgress { ...(pod.status?.initContainerStatuses ?? []).map((status) => ({ status, init: true })), ...(pod.status?.containerStatuses ?? []).map((status) => ({ status, init: false })), ] + let pullError: string | undefined for (const { status, init } of statuses) { const waiting = status.state?.waiting - if (!waiting?.reason || !FATAL_WAITING_REASONS.has(waiting.reason)) continue + if (!waiting?.reason) continue const variable = init ? 'SANDBOX_K8S_AGENT_IMAGE' : imageVariableFor(kind) - return { - state: 'failed', - error: new KubernetesSandboxConfigError( - `Sandbox pod ${name} cannot start its ${init ? 'agent installer' : 'sandbox'} container (${waiting.reason}): ${waiting.message ?? status.image}. Check that ${variable} names an image the cluster can pull, and set SANDBOX_K8S_IMAGE_PULL_SECRET for a private registry.` - ), + const message = waiting.message ?? status.image + const permanent = + PERMANENT_WAITING_REASONS.has(waiting.reason) || + (PULL_WAITING_REASONS.has(waiting.reason) && PERMANENT_PULL_ERROR.test(message)) + if (permanent) { + return { + state: 'failed', + error: new KubernetesSandboxConfigError( + `Sandbox pod ${name} cannot start its ${init ? 'agent installer' : 'sandbox'} container (${waiting.reason}): ${message}. Check that ${variable} names an image that exists, and set SANDBOX_K8S_IMAGE_PULL_SECRET for a private registry.` + ), + } + } + if (PULL_WAITING_REASONS.has(waiting.reason)) { + pullError = `${waiting.reason} for ${variable}: ${message}` } } const sandboxRunning = pod.status?.containerStatuses?.some( @@ -148,8 +184,16 @@ function podProgress(pod: V1Pod, kind: SandboxKind): PodProgress { const unscheduled = pod.status?.conditions?.find( (condition) => condition.type === 'PodScheduled' && condition.status === 'False' ) - const detail = unscheduled?.message ?? pod.status?.message ?? phase - return { state: 'pending', ...(detail ? { detail } : {}) } + const detail = pullError ?? unscheduled?.message ?? pod.status?.message ?? phase + return { state: 'pending', ...(detail ? { detail } : {}), ...(pullError ? { pullError } : {}) } +} + +/** A sandbox-creation failure the node will repeat forever: no runtime for the RuntimeClass. */ +function missingRuntimeHandler(events: readonly CoreV1Event[]): CoreV1Event | undefined { + return events.find( + (event) => + event.reason === 'FailedCreatePodSandBox' && MISSING_RUNTIME_HANDLER.test(event.message ?? '') + ) } /** Polls the agent's `/healthz` until it answers as a compatible agent or `signal` aborts. */ @@ -172,7 +216,7 @@ async function waitForAgent(baseUrl: string, signal: AbortSignal): Promise "The sandbox agent does not speak this Sim release's protocol. Set SANDBOX_K8S_AGENT_IMAGE to the agent image of this release (or unset it to use the default)." ) } - await sleep(backoffWithJitter(attempt, null, HEALTH_BACKOFF)) + await interruptibleSleep(backoffWithJitter(attempt, null, HEALTH_BACKOFF), signal) } } @@ -180,11 +224,69 @@ function readSettings(): KubernetesSandboxSettings { return readKubernetesSandboxSettings(env) } +/** The live, unexpired session pods a lookup may consider, before the lease is applied. */ +interface SessionCandidates { + /** Oldest pod that can serve the requested lease, if any. */ + pod: V1Pod | null + /** Live pods that cannot serve the lease before their hard deadline. */ + exhausted: V1Pod[] +} + /** - * The Kubernetes sandbox provider: one pod per sandbox, reached over its agent's HTTP API. It - * keeps no per-sandbox state in memory. A pod's labels, its `sim.ai/expires-at` annotation, and a - * token derived from its name are everything a replica needs, so any app replica can reconnect to - * a session, stop its commands, or reap it. + * Sorts a session's pods into the one to reconnect to and the ones near their 24-hour cap. A pod + * qualifies when it is running, reachable, before its `sim.ai/expires-at`, started with the + * token this deployment derives for it (a pod from before a secret rotation can never + * authenticate), and running under the configured RuntimeClass (unless the operator accepted a + * shared kernel), so a pod from an older, weaker configuration is never reused. Of the pods that + * can also serve the lease, the oldest wins, so concurrent creates that raced converge on one. + */ +function selectSessionPods( + pods: readonly V1Pod[], + options: { + nowMs: number + leaseMs: number + settings: KubernetesSandboxSettings + tokenDigest: (podName: string) => string + } +): SessionCandidates { + const live = pods.filter((pod) => { + const name = pod.metadata?.name + if (!name || pod.metadata?.deletionTimestamp || pod.status?.phase !== 'Running') return false + if (!agentBaseUrl(pod)) return false + const expiresAtMs = podExpiresAtMs(pod) + if (expiresAtMs === null || expiresAtMs <= options.nowMs) return false + if ( + !options.settings.allowUnisolated && + pod.spec?.runtimeClassName !== options.settings.runtimeClassName + ) { + return false + } + return podTokenDigest(pod) === options.tokenDigest(name) + }) + const servesLease = (pod: V1Pod) => { + const hardDeadlineMs = podHardDeadlineMs(pod) + return hardDeadlineMs !== null && hardDeadlineMs >= options.nowMs + options.leaseMs + } + const usable = live.filter(servesLease) + usable.sort( + (a, b) => + new Date(a.metadata?.creationTimestamp ?? 0).getTime() - + new Date(b.metadata?.creationTimestamp ?? 0).getTime() || + compareStrings(a.metadata?.name ?? '', b.metadata?.name ?? '') + ) + return { pod: usable[0] ?? null, exhausted: live.filter((pod) => !servesLease(pod)) } +} + +/** + * The Kubernetes sandbox provider: one pod per sandbox, reached over its agent's HTTP API on the + * pod network (see {@link agentBaseUrl} for that transport's trust model). It keeps no + * per-sandbox state in memory. A pod's labels, its `sim.ai/expires-at` annotation, and a token + * derived from its name are everything a replica needs, so any app replica can reconnect to a + * session, stop its commands, or reap it. + * + * It runs only in the Sim app process. Trigger.dev workers cannot reach pod IPs or the cluster + * API, and a self-hosted deployment without `TRIGGER_DEV_ENABLED` already runs executions in the + * app, on the database-backed job queue. */ function createKubernetesSandboxProvider(): SandboxProvider { let opened: { @@ -193,18 +295,14 @@ function createKubernetesSandboxProvider(): SandboxProvider { } | null = null function open(settings: KubernetesSandboxSettings) { + if (isInsideTriggerRun()) { + throw new KubernetesSandboxConfigError( + 'Kubernetes sandboxes run only from the Sim app, not from Trigger.dev workers, which cannot reach sandbox pods. Leave TRIGGER_DEV_ENABLED unset so executions run in the app on the database-backed job queue.' + ) + } if (opened?.namespace === settings.namespace) return opened.access const access = (async () => { - let config: KubeConfig - try { - config = await loadDefaultKubeConfig() - } catch (error) { - throw new KubernetesSandboxConfigError( - `Could not load Kubernetes API credentials (${getErrorMessage(error)}). Run Sim in the cluster with a service account, or set KUBECONFIG.`, - { cause: error } - ) - } - const cluster = await openSandboxCluster(config, settings.namespace) + const cluster = await openSandboxCluster(await loadDefaultKubeConfig(), settings.namespace) return { cluster, guard: new IsolationGuard(cluster) } })() const entry = { namespace: settings.namespace, access } @@ -215,80 +313,127 @@ function createKubernetesSandboxProvider(): SandboxProvider { return access } + /** Deletes pods a failed create may have left behind; the reaper catches any this misses. */ + async function discardPods(cluster: SandboxCluster, names: Iterable): Promise { + for (const name of names) { + await cluster.deletePod(name).catch((error: unknown) => { + logger.warn('Failed to delete a sandbox pod that did not start; the reaper retries', { + name, + error: getErrorMessage(error), + }) + }) + } + } + /** * Creates the pod, retrying throttling and unanswered requests. A retry after a request that may * have reached the API server reuses the pod name, so a 409 then is our own pod, recognised by - * its token digest; a 409 on a fresh name is a collision and takes a new one. + * its token digest; a 409 on a fresh name is a collision and takes a new one. When the create + * fails for good, any pod an unanswered attempt may have made is deleted. */ async function createPod( cluster: SandboxCluster, settings: KubernetesSandboxSettings, - build: (name: string, tokenDigest: string) => V1Pod + build: (name: string, tokenDigest: string) => V1Pod, + signal: AbortSignal ): Promise<{ pod: V1Pod; token: string }> { let name = newPodName() - let maybeCreated = false - for (let attempt = 1; ; attempt++) { - const token = deriveSandboxAgentToken(settings.tokenSecret, name) - const digest = sandboxAgentTokenDigest(token) - try { - return { pod: await cluster.createPod(build(name, digest)), token } - } catch (error) { - if (!(error instanceof KubernetesApiError)) throw error - const { failure } = error - if (failure.status === 409) { - if (maybeCreated) { - const existing = await cluster.readPod(name) - if (existing && podTokenDigest(existing) === digest) return { pod: existing, token } + const maybeCreated = new Set() + try { + for (let attempt = 1; ; attempt++) { + const token = deriveSandboxAgentToken(settings.tokenSecret, name) + const digest = sandboxAgentTokenDigest(token) + try { + return { pod: await cluster.createPod(build(name, digest), { signal }), token } + } catch (error) { + if (!(error instanceof KubernetesApiError)) throw error + const { failure } = error + if (failure.status === 409) { + if (maybeCreated.has(name)) { + const existing = await cluster.readPod(name, { signal }) + if (existing && podTokenDigest(existing) === digest) return { pod: existing, token } + maybeCreated.delete(name) + } + if (attempt >= MAX_CREATE_ATTEMPTS) throw toPodCreateError(failure, settings.namespace) + name = newPodName() + continue } - if (attempt >= MAX_CREATE_ATTEMPTS) throw toPodCreateError(failure, settings.namespace) - name = newPodName() - maybeCreated = false - continue - } - if (attempt >= MAX_CREATE_ATTEMPTS || !isRetryableKubernetesFailure(failure)) { - throw toPodCreateError(failure, settings.namespace) + if (attempt >= MAX_CREATE_ATTEMPTS || !isRetryableKubernetesFailure(failure)) { + throw toPodCreateError(failure, settings.namespace) + } + if (failure.status !== 429) maybeCreated.add(name) + logger.warn('Sandbox pod create failed; retrying', { attempt, status: failure.status }) + await sleep( + backoffWithJitter(attempt, parseRetryAfter(failure.retryAfter ?? null), CREATE_BACKOFF) + ) } - maybeCreated = maybeCreated || failure.status !== 429 - logger.warn('Sandbox pod create failed; retrying', { attempt, status: failure.status }) - await sleep( - backoffWithJitter(attempt, parseRetryAfter(failure.retryAfter ?? null), CREATE_BACKOFF) - ) } + } catch (error) { + await discardPods(cluster, maybeCreated) + throw error } } - /** Follows the pod with a watch until it runs, then waits for its agent; bounded by `signal`. */ + /** + * Follows the pod with a watch until it runs, then waits for its agent; bounded by `signal`. + * A watch that ends without news is re-read and re-watched after a back-off, so an API server + * that refuses or drops watches is never hammered. After each re-read of a scheduled pod, its + * events are checked for a node that has no runtime for the RuntimeClass, which never clears. + */ async function waitUntilReady( cluster: SandboxCluster, created: V1Pod, kind: SandboxKind, + settings: KubernetesSandboxSettings, signal: AbortSignal ): Promise<{ pod: V1Pod; baseUrl: string }> { const name = created.metadata?.name ?? '' let pod = created let detail: string | undefined + let pullError: string | undefined + const observe = (update: V1Pod): PodProgress => { + pod = update + const progress = podProgress(update, kind) + if (progress.state === 'pending') { + detail = progress.detail + pullError = progress.pullError ?? pullError + } + return progress + } try { - for (;;) { - const progress = podProgress(pod, kind) + for (let quietEnds = 0; ; ) { + const progress = observe(pod) if (progress.state === 'failed') throw progress.error if (progress.state === 'ready') { await waitForAgent(progress.baseUrl, signal) return { pod, baseUrl: progress.baseUrl } } - detail = progress.detail - const changed = await cluster.watchPod( + const end = await cluster.watchPod( name, pod.metadata?.resourceVersion, - (update) => { - pod = update - return podProgress(update, kind).state !== 'pending' - }, + (update) => observe(update).state !== 'pending', signal ) - if (!changed) { - const latest = await cluster.readPod(name) - if (!latest) throw new Error(`Sandbox pod ${name} was deleted while starting`) - pod = latest + if (end === 'deleted') throw new Error(`Sandbox pod ${name} was deleted while starting`) + if (end === 'matched') { + quietEnds = 0 + continue + } + quietEnds++ + await interruptibleSleep(backoffWithJitter(quietEnds, null, WATCH_BACKOFF), signal) + signal.throwIfAborted() + const latest = await cluster.readPod(name, { signal }) + if (!latest) throw new Error(`Sandbox pod ${name} was deleted while starting`) + pod = latest + if (latest.spec?.nodeName && latest.status?.phase === 'Pending') { + const failure = missingRuntimeHandler( + (await cluster.listPodEvents(name, { signal })) ?? [] + ) + if (failure) { + throw new KubernetesSandboxConfigError( + `Node ${latest.spec.nodeName} cannot run RuntimeClass "${settings.runtimeClassName ?? ''}" (SANDBOX_K8S_RUNTIME_CLASS): ${failure.message}. Install the runtime on every node the class schedules to, or give the RuntimeClass a nodeSelector for the nodes that have it.` + ) + } } } } catch (error) { @@ -297,7 +442,9 @@ function createKubernetesSandboxProvider(): SandboxProvider { throw new KubernetesSandboxCapacityError( reached ? `Sandbox pod ${name} is running but Sim could not reach its agent at ${reached}. Check that a NetworkPolicy lets Sim's pods reach the sandbox namespace on the agent port.` - : `Sandbox pod ${name} did not start before its create deadline${detail ? ` (${detail})` : ''}. The cluster may be out of capacity for sandboxes.`, + : pullError + ? `Sandbox pod ${name} could not pull its image before its create deadline (${pullError}). Check the registry is reachable from the nodes.` + : `Sandbox pod ${name} did not start before its create deadline${detail ? ` (${detail})` : ''}. The cluster may be out of capacity for sandboxes.`, { cause: error } ) } @@ -311,25 +458,19 @@ function createKubernetesSandboxProvider(): SandboxProvider { options: { language?: CodeLanguage; session: boolean; fallbackExpiresAtMs: number } ): SandboxHandle { const name = pod.metadata?.name ?? '' - const expiresAtMs = podExpiresAtMs(pod) ?? options.fallbackExpiresAtMs - const agent = createAgentSandboxHandle({ + return createAgentSandboxHandle({ sandboxId: name, baseUrl, token, - expiresAtMs, + expiresAtMs: podExpiresAtMs(pod) ?? options.fallbackExpiresAtMs, + maxExpiresAtMs: podHardDeadlineMs(pod) ?? Date.now() + SANDBOX_POD_MAX_LIFETIME_MS, + // Recorded on the pod before the agent hears of it, so the reaper, which reads only the + // annotation, never deletes a pod whose agent was told to stay up. + beforeLifetimeExtended: (expiresAtMs) => cluster.setExpiresAt(name, expiresAtMs), session: options.session, ...(options.language ? { language: options.language } : {}), kill: () => cluster.deletePod(name), }) - return bindSandboxPod( - agent, - { - name, - expiresAtMs, - hardDeadlineMs: podHardDeadlineMs(pod) ?? Date.now() + SANDBOX_POD_MAX_LIFETIME_MS, - }, - cluster - ) } return { @@ -340,48 +481,43 @@ function createKubernetesSandboxProvider(): SandboxProvider { async create(kind: SandboxKind, options?: CreateSandboxOptions): Promise { const settings = readSettings() const image = imageFor(kind, settings, options?.imageRef) - const { cluster, guard } = await open(settings) - await guard.assertIsolated(settings) - const lifetimeMs = resolveKubernetesSandboxLifetimeMs( options?.lifetimeMs ?? DEFAULT_SANDBOX_LIFETIME_MS ) const requestedAtMs = Date.now() const expiresAtMs = requestedAtMs + lifetimeMs + const deadline = AbortSignal.timeout(Math.max(1, Math.min(CREATE_TIMEOUT_MS, lifetimeMs))) + const { cluster, guard } = await open(settings) + await guard.assertIsolated(settings, deadline) + const sessionLabel = options?.sessionKey ? sessionLabelValue(options.sessionKey) : undefined logger.info('Creating Kubernetes sandbox pod', { kind, image, namespace: settings.namespace }) options?.onProviderRequestStarted?.(requestedAtMs) - const { pod, token } = await createPod(cluster, settings, (name, tokenDigest) => - buildSandboxPod({ - name, - kind, - image, - settings, - tokenDigest, - expiresAtMs, - ...(sessionLabel ? { sessionLabel } : {}), - }) + const { pod, token } = await createPod( + cluster, + settings, + (name, tokenDigest) => + buildSandboxPod({ + name, + kind, + image, + settings, + tokenDigest, + expiresAtMs, + ...(sessionLabel ? { sessionLabel } : {}), + }), + deadline ) const name = pod.metadata?.name ?? '' try { - const ready = await waitUntilReady( - cluster, - pod, - kind, - AbortSignal.timeout(Math.max(1, Math.min(CREATE_TIMEOUT_MS, expiresAtMs - Date.now()))) - ) + const ready = await waitUntilReady(cluster, pod, kind, settings, deadline) return connect(cluster, ready.pod, ready.baseUrl, token, { ...(options?.language ? { language: options.language } : {}), session: sessionLabel !== undefined, fallbackExpiresAtMs: expiresAtMs, }) } catch (error) { - await cluster.deletePod(name).catch((deleteError: unknown) => { - logger.warn('Failed to delete a sandbox pod that did not start; the reaper retries', { - name, - error: getErrorMessage(deleteError), - }) - }) + await discardPods(cluster, [name]) throw error } }, @@ -392,15 +528,30 @@ function createKubernetesSandboxProvider(): SandboxProvider { ): Promise { const settings = readSettings() const { cluster } = await open(settings) - const pods = await cluster.listPods( - `${MANAGED_SELECTOR},${SESSION_LABEL}=${sessionLabelValue(key)}` + const nowMs = Date.now() + const { pod, exhausted } = selectSessionPods( + await cluster.listPods(`${MANAGED_SELECTOR},${SESSION_LABEL}=${sessionLabelValue(key)}`), + { + nowMs, + leaseMs: options.lifetimeMs ?? 0, + settings, + tokenDigest: (name) => + sandboxAgentTokenDigest(deriveSandboxAgentToken(settings.tokenSecret, name)), + } ) - const pod = selectSessionPod(pods, { - nowMs: Date.now(), - leaseMs: options.lifetimeMs ?? 0, - tokenDigest: (name) => - sandboxAgentTokenDigest(deriveSandboxAgentToken(settings.tokenSecret, name)), - }) + // A pod too close to its cap for this lease is retired rather than left eligible for + // shorter leases, so the session's files never split across two pods. Its agent keeps + // running until its own deadline; the reaper deletes it after the grace period. + for (const retired of exhausted) { + const retiredName = retired.metadata?.name + if (!retiredName) continue + await cluster.setExpiresAt(retiredName, nowMs).catch((error: unknown) => { + logger.warn('Failed to retire a session pod near its lifetime cap', { + name: retiredName, + error: getErrorMessage(error), + }) + }) + } const baseUrl = pod ? agentBaseUrl(pod) : null if (!pod?.metadata?.name || !baseUrl) return null return connect( @@ -411,7 +562,7 @@ function createKubernetesSandboxProvider(): SandboxProvider { { ...(options.language ? { language: options.language } : {}), session: true, - fallbackExpiresAtMs: Date.now(), + fallbackExpiresAtMs: nowMs, } ) }, @@ -419,28 +570,26 @@ function createKubernetesSandboxProvider(): SandboxProvider { async stopSessionProcess(process: SessionProcessIdentity, signal: AbortSignal): Promise { const settings = readSettings() const { cluster } = await open(settings) - const pod = await cluster.readPod(process.sandboxId) + const pod = await cluster.readPod(process.sandboxId, { signal }) const baseUrl = pod ? agentBaseUrl(pod) : null - // Only the session's own running pod can still hold the process; anything else is gone. + const token = deriveSandboxAgentToken(settings.tokenSecret, process.sandboxId) + // Only the session's own running, Sim-made pod, started with this deployment's token, can + // still hold the process; anything else means the recorded sandbox is gone. if ( !pod || !baseUrl || pod.status?.phase !== 'Running' || - pod.metadata?.labels?.[SESSION_LABEL] !== sessionLabelValue(process.sessionKey) + !isSimManagedPod(pod) || + pod.metadata?.labels?.[SESSION_LABEL] !== sessionLabelValue(process.sessionKey) || + podTokenDigest(pod) !== sandboxAgentTokenDigest(token) ) { return } - const client = new SandboxAgentClient( - baseUrl, - deriveSandboxAgentToken(settings.tokenSecret, process.sandboxId) - ) try { - await client.request(sandboxAgentProcessSignalPath(process.id), { - method: 'POST', - json: { signal: 'SIGKILL' }, - signal, - retry: true, - }) + await new SandboxAgentClient(baseUrl, token).request( + sandboxAgentProcessSignalPath(process.id), + { method: 'POST', json: { signal: 'SIGKILL' }, signal, retry: true } + ) } catch (error) { if (error instanceof SandboxAgentRequestError && error.code === 'not_found') return throw error @@ -454,34 +603,5 @@ function createKubernetesSandboxProvider(): SandboxProvider { } } -/** - * The session pod to reconnect to: running, reachable, not past its `sim.ai/expires-at`, able to - * stay up for the requested lease before its hard deadline, and started with the token this - * deployment derives for it (a pod from before a secret rotation can never authenticate). The - * oldest wins, so concurrent creates that raced converge on one pod. - */ -function selectSessionPod( - pods: readonly V1Pod[], - options: { nowMs: number; leaseMs: number; tokenDigest: (podName: string) => string } -): V1Pod | null { - const usable = pods.filter((pod) => { - const name = pod.metadata?.name - if (!name || pod.metadata?.deletionTimestamp || pod.status?.phase !== 'Running') return false - if (!agentBaseUrl(pod)) return false - const expiresAtMs = podExpiresAtMs(pod) - const hardDeadlineMs = podHardDeadlineMs(pod) - if (expiresAtMs === null || expiresAtMs <= options.nowMs) return false - if (hardDeadlineMs === null || hardDeadlineMs < options.nowMs + options.leaseMs) return false - return podTokenDigest(pod) === options.tokenDigest(name) - }) - usable.sort( - (a, b) => - new Date(a.metadata?.creationTimestamp ?? 0).getTime() - - new Date(b.metadata?.creationTimestamp ?? 0).getTime() || - compareStrings(a.metadata?.name ?? '', b.metadata?.name ?? '') - ) - return usable[0] ?? null -} - /** The provider selected by `SANDBOX_PROVIDER=kubernetes`. Inert until a sandbox is requested. */ export const kubernetesProvider = createKubernetesSandboxProvider() diff --git a/apps/sim/trigger.config.ts b/apps/sim/trigger.config.ts index 3c402e7f37f..5e7a2aed5f8 100644 --- a/apps/sim/trigger.config.ts +++ b/apps/sim/trigger.config.ts @@ -63,18 +63,6 @@ const FUNCTION_EXECUTION_ENV = [ { name: 'DAYTONA_API_KEY', secret: true }, { name: 'DAYTONA_FUNCTION_SNAPSHOT_ID', secret: false }, { name: 'DAYTONA_DOC_SNAPSHOT_ID', secret: false }, - { name: 'SANDBOX_K8S_NAMESPACE', secret: false }, - { name: 'SANDBOX_K8S_RUNTIME_CLASS', secret: false }, - { name: 'SANDBOX_K8S_ALLOW_UNISOLATED', secret: false }, - { name: 'SANDBOX_K8S_AGENT_IMAGE', secret: false }, - { name: 'SANDBOX_K8S_FUNCTION_IMAGE', secret: false }, - { name: 'SANDBOX_K8S_DOC_IMAGE', secret: false }, - { name: 'SANDBOX_K8S_CPU', secret: false }, - { name: 'SANDBOX_K8S_MEMORY', secret: false }, - { name: 'SANDBOX_K8S_EPHEMERAL_STORAGE', secret: false }, - { name: 'SANDBOX_K8S_NODE_SELECTOR', secret: false }, - { name: 'SANDBOX_K8S_TOLERATIONS', secret: false }, - { name: 'SANDBOX_K8S_IMAGE_PULL_SECRET', secret: false }, { name: 'S3_COPILOT_BUCKET_NAME', secret: false }, { name: 'AZURE_STORAGE_COPILOT_CONTAINER_NAME', secret: false }, { name: 'GCS_COPILOT_BUCKET_NAME', secret: false }, @@ -257,8 +245,6 @@ export default defineConfig({ 'e2b', '@e2b/code-interpreter', '@daytona/sdk', - // ESM-only; loaded lazily by the Kubernetes sandbox provider. - '@kubernetes/client-node', // pdf.js resolves its worker via a runtime-relative dynamic import that // breaks inside the worker bundle; it must load from node_modules. 'pdfjs-dist', @@ -296,7 +282,6 @@ export default defineConfig({ '@earendil-works/pi-coding-agent', '@e2b/code-interpreter', '@daytona/sdk', - '@kubernetes/client-node', 'pdfjs-dist', '@napi-rs/canvas', 'sharp', From 58f98c0cf35863028f502a894281964f7f32db1e Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:45:39 -0600 Subject: [PATCH 27/78] fix(sandbox): settle the paused and expired sandbox sweeps independently The cleanup cron runs both sweeps with Promise.allSettled, so one failing neither stops nor hides the other: each failure is logged on its own and the response carries whichever results completed. --- .../cron/cleanup-session-sandboxes/route.ts | 35 +++++++++++++------ 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/apps/sim/app/api/cron/cleanup-session-sandboxes/route.ts b/apps/sim/app/api/cron/cleanup-session-sandboxes/route.ts index dba501fef00..4d7a7ad263f 100644 --- a/apps/sim/app/api/cron/cleanup-session-sandboxes/route.ts +++ b/apps/sim/app/api/cron/cleanup-session-sandboxes/route.ts @@ -17,24 +17,37 @@ const logger = createLogger('CleanupSessionSandboxesAPI') * Retention sweep for sandboxes the provider keeps past their use. An idle workbench pauses * instead of dying and the provider keeps it indefinitely, so this run is what bounds how long its * files outlive the chat's last use. Providers that leave finished or orphaned sandboxes behind - * (Kubernetes pods) are swept in the same run. Each half is a no-op where it does not apply. + * (Kubernetes pods) are swept in the same run. Each half is a no-op where it does not apply, and + * each settles on its own, so one failing neither stops nor hides the other. */ export const GET = withRouteHandler(async (request: NextRequest) => { const authError = verifyCronAuth(request, 'session sandbox cleanup') if (authError) return authError - try { - const [result, expired] = await Promise.all([ - reapPausedSessionSandboxes(), - reapExpiredSandboxes(), - ]) - logger.info('Swept session sandboxes', { ...result, expired }) - return NextResponse.json({ success: true, ...result, expired }) - } catch (error) { - logger.error('Failed to sweep paused session sandboxes', { error }) + const [paused, expired] = await Promise.allSettled([ + reapPausedSessionSandboxes(), + reapExpiredSandboxes(), + ]) + const summary = { + ...(paused.status === 'fulfilled' ? paused.value : {}), + ...(expired.status === 'fulfilled' ? { expired: expired.value } : {}), + } + const failures = [ + ...(paused.status === 'rejected' ? [paused.reason] : []), + ...(expired.status === 'rejected' ? [expired.reason] : []), + ] + if (paused.status === 'rejected') { + logger.error('Failed to sweep paused session sandboxes', { error: paused.reason }) + } + if (expired.status === 'rejected') { + logger.error('Failed to sweep expired sandboxes', { error: expired.reason }) + } + if (failures.length > 0) { return NextResponse.json( - { error: getErrorMessage(error, 'Failed to sweep paused session sandboxes') }, + { error: getErrorMessage(failures[0], 'Failed to sweep session sandboxes'), ...summary }, { status: 500 } ) } + logger.info('Swept paused and expired sandboxes', summary) + return NextResponse.json({ success: true, ...summary }) }) From bb0c3a7e0654916d0142c5d399163b313455158f Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:00:37 -0600 Subject: [PATCH 28/78] feat(helm): add the Kubernetes sandbox provider's namespace, RBAC, and isolation sandbox.kubernetes.* (off by default; default renders are unchanged) wires SANDBOX_PROVIDER=kubernetes into the app and renders what the provider runs against: the sandbox namespace with Pod Security baseline enforced, a Role limited to pods and pods/log (no exec, no Secrets), a ClusterRole that reads only the configured RuntimeClass, a default-deny NetworkPolicy admitting the app on the agent port with internet or restricted egress, a ResourceQuota and LimitRange, an optional RuntimeClass for self-managed gVisor or Kata (never runc or crun), and an optional pre-pull DaemonSet for the function image. The app pod mounts its projected token only when the provider is enabled, and the app NetworkPolicy gains egress to the sandbox agent port and the Kubernetes API. Rendering fails without an isolation runtime unless allowUnisolated is set. --- .github/workflows/helm.yml | 9 + helm/sim/Chart.yaml | 2 +- helm/sim/README.md | 1 + helm/sim/ci/sandbox-kubernetes-values.yaml | 39 ++ helm/sim/templates/_helpers.tpl | 138 +++++ .../templates/daemonset-sandbox-prepull.yaml | 55 ++ helm/sim/templates/deployment-app.yaml | 7 +- helm/sim/templates/networkpolicy.yaml | 30 + helm/sim/templates/sandbox-kubernetes.yaml | 244 ++++++++ helm/sim/tests/sandbox-kubernetes_test.yaml | 537 ++++++++++++++++++ helm/sim/values.schema.json | 289 ++++++++++ helm/sim/values.yaml | 150 +++++ 12 files changed, 1499 insertions(+), 2 deletions(-) create mode 100644 helm/sim/ci/sandbox-kubernetes-values.yaml create mode 100644 helm/sim/templates/daemonset-sandbox-prepull.yaml create mode 100644 helm/sim/templates/sandbox-kubernetes.yaml create mode 100644 helm/sim/tests/sandbox-kubernetes_test.yaml diff --git a/.github/workflows/helm.yml b/.github/workflows/helm.yml index 65580e12bb9..ff45efe639e 100644 --- a/.github/workflows/helm.yml +++ b/.github/workflows/helm.yml @@ -139,6 +139,15 @@ jobs: -schema-location default \ -schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' + - name: Render and validate manifests (Kubernetes sandbox provider) + run: | + helm template sim helm/sim --namespace sim \ + --values helm/sim/ci/sandbox-kubernetes-values.yaml \ + | /tmp/kubeconform -strict -summary \ + -kubernetes-version 1.29.0 \ + -schema-location default \ + -schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' + - name: Render every example values file run: | set -euo pipefail diff --git a/helm/sim/Chart.yaml b/helm/sim/Chart.yaml index 9d542241daa..a57fd63227e 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.16.1 +version: 1.17.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 c11e6c00f07..b55ecd76a19 100644 --- a/helm/sim/README.md +++ b/helm/sim/README.md @@ -58,6 +58,7 @@ Optional components (off by default): * **`telemetry`** — OpenTelemetry Collector wired to Jaeger / Prometheus / OTLP backends. * **`ingress`** — NGINX-style Ingress for the app and realtime services. * **`networkPolicy`** — east-west and egress isolation (blocks cloud metadata endpoints by default). +* **`sandbox.kubernetes`** — runs code sandboxes as pods in a dedicated namespace on this cluster instead of E2B or Daytona, with its RBAC, NetworkPolicies, quota, and Pod Security labels. Requires a VM or gVisor RuntimeClass. See [Sandboxes](https://docs.sim.ai/platform/self-hosting/sandboxes#kubernetes-no-third-party). * **`hpa`** — HorizontalPodAutoscaler for `app` and `realtime`. * **`podDisruptionBudget`** — auto-activates when `replicaCount > 1`. diff --git a/helm/sim/ci/sandbox-kubernetes-values.yaml b/helm/sim/ci/sandbox-kubernetes-values.yaml new file mode 100644 index 00000000000..5307f3b399c --- /dev/null +++ b/helm/sim/ci/sandbox-kubernetes-values.yaml @@ -0,0 +1,39 @@ +# CI-only values: the Kubernetes sandbox provider with every optional object it +# renders (created RuntimeClass, quota, LimitRange, pre-pull DaemonSet) plus the app +# NetworkPolicy, so lint and kubeconform cover them. Standalone, because ct lint +# renders each ci/*-values.yaml file on its own. Dummy values — never use in a +# deployment. +app: + env: + BETTER_AUTH_SECRET: "cicicicicicicicicicicicicicicicicicicicicicicicicicicicicicicici" + ENCRYPTION_KEY: "cicicicicicicicicicicicicicicicicicicicicicicicicicicicicicicici" + INTERNAL_API_SECRET: "cicicicicicicicicicicicicicicicicicicicicicicicicicicicicicicici" + CRON_SECRET: "cicicicicicicicicicicicicicicicicicicicicicicicicicicicicicicici" + +postgresql: + auth: + password: "ci-dummy-password" + +networkPolicy: + enabled: true + +sandbox: + kubernetes: + enabled: true + runtimeClass: + preset: gvisor + create: true + images: + function: + tag: ci-dummy-tag + nodeSelector: + sim.ai/sandbox: "true" + tolerations: + - key: sim.ai/sandbox + operator: Exists + effect: NoSchedule + egress: + clusterCidrs: + - "198.18.0.0/15" + prePull: + enabled: true diff --git a/helm/sim/templates/_helpers.tpl b/helm/sim/templates/_helpers.tpl index 3af537b9240..7ea417b8a65 100644 --- a/helm/sim/templates/_helpers.tpl +++ b/helm/sim/templates/_helpers.tpl @@ -865,3 +865,141 @@ values, then extraEnvVars. Shared with the migrations init container so both res {{ toYaml . }} {{- end }} {{- end }} + +{{/* +Kubernetes sandbox provider: the namespace that holds sandbox pods. +*/}} +{{- define "sim.sandbox.namespace" -}} +{{- .Values.sandbox.kubernetes.namespace.name -}} +{{- end }} + +{{/* +Kubernetes sandbox provider: the RuntimeClass sandbox pods run under. An explicit +runtimeClass.name wins over the preset's name; empty when neither is set (only +valid with allowUnisolated). +*/}} +{{- define "sim.sandbox.runtimeClassName" -}} +{{- $rc := .Values.sandbox.kubernetes.runtimeClass -}} +{{- $presetNames := dict "isolated-sandbox" "isolated-sandbox" "gvisor" "gvisor" "kata" "kata-vm-isolation" -}} +{{- default (get $presetNames (toString $rc.preset)) $rc.name -}} +{{- end }} + +{{/* +Kubernetes sandbox provider: the handler of a chart-created RuntimeClass. +*/}} +{{- define "sim.sandbox.runtimeClassHandler" -}} +{{- $rc := .Values.sandbox.kubernetes.runtimeClass -}} +{{- $presetHandlers := dict "gvisor" "runsc" -}} +{{- default (get $presetHandlers (toString $rc.preset)) $rc.handler -}} +{{- end }} + +{{/* +Kubernetes sandbox provider: one sandbox image reference, or empty when neither +tag nor digest is set (the app then uses the image built for its release). +Usage: {{ include "sim.sandbox.image" (dict "root" . "kind" "function") }} +*/}} +{{- define "sim.sandbox.image" -}} +{{- $image := index .root.Values.sandbox.kubernetes.images .kind -}} +{{- if or $image.tag $image.digest -}} +{{- include "sim.image" (dict "imageRoot" $image "global" .root.Values.global "chartAppVersion" "") -}} +{{- end -}} +{{- end }} + +{{/* +Kubernetes sandbox provider labels. +*/}} +{{- define "sim.sandbox.labels" -}} +{{ include "sim.labels" . }} +app.kubernetes.io/component: sandbox +{{- end }} + +{{/* +Kubernetes sandbox provider: fail at render time on a configuration the app would +refuse or that would weaken isolation. +*/}} +{{- define "sim.sandbox.validate" -}} +{{- $sbx := .Values.sandbox.kubernetes -}} +{{- if $sbx.enabled -}} +{{- $ns := include "sim.sandbox.namespace" . -}} +{{- if not $ns -}} +{{- fail "sandbox.kubernetes.namespace.name is required when sandbox.kubernetes.enabled=true" -}} +{{- end -}} +{{- if eq $ns .Release.Namespace -}} +{{- fail (printf "sandbox.kubernetes.namespace.name must differ from the release namespace %q: the sandbox namespace's Pod Security level, quota, and NetworkPolicies apply to every pod in it" .Release.Namespace) -}} +{{- end -}} +{{- $preset := toString $sbx.runtimeClass.preset -}} +{{- if and $preset (not (has $preset (list "isolated-sandbox" "gvisor" "kata" "custom"))) -}} +{{- fail (printf "sandbox.kubernetes.runtimeClass.preset %q is not one of isolated-sandbox, gvisor, kata, custom" $preset) -}} +{{- end -}} +{{- if and (eq $preset "custom") (not $sbx.runtimeClass.name) -}} +{{- fail "sandbox.kubernetes.runtimeClass.name is required when runtimeClass.preset=custom" -}} +{{- end -}} +{{- if and (not (include "sim.sandbox.runtimeClassName" .)) (not $sbx.allowUnisolated) -}} +{{- fail "sandbox.kubernetes.runtimeClass.preset (or runtimeClass.name) is required: sandboxes run untrusted code as root and need a VM or gVisor runtime. Set allowUnisolated=true only to accept running it on the shared node kernel. See https://docs.sim.ai/platform/self-hosting/sandboxes#kubernetes-no-third-party" -}} +{{- end -}} +{{- if $sbx.runtimeClass.create -}} +{{- if has $preset (list "isolated-sandbox" "kata") -}} +{{- fail (printf "sandbox.kubernetes.runtimeClass.create must be false for preset %q: the cloud provider manages that RuntimeClass" $preset) -}} +{{- end -}} +{{- $handler := include "sim.sandbox.runtimeClassHandler" . -}} +{{- if not $handler -}} +{{- fail "sandbox.kubernetes.runtimeClass.handler is required when runtimeClass.create=true" -}} +{{- end -}} +{{- if has $handler (list "runc" "crun") -}} +{{- fail (printf "sandbox.kubernetes.runtimeClass.handler %q shares the node kernel; the chart does not create a runc or crun RuntimeClass" $handler) -}} +{{- end -}} +{{- end -}} +{{- if not (has (toString $sbx.egress.profile) (list "internet" "restricted")) -}} +{{- fail (printf "sandbox.kubernetes.egress.profile %q is not one of internet, restricted" (toString $sbx.egress.profile)) -}} +{{- end -}} +{{- if eq (include "sim.serviceAccountName" .) "default" -}} +{{- fail "sandbox.kubernetes.enabled=true binds pod-management RBAC to the app ServiceAccount, which resolves to \"default\". Set serviceAccount.create=true or serviceAccount.name to a dedicated ServiceAccount" -}} +{{- end -}} +{{- if and $sbx.prePull.enabled (not (include "sim.sandbox.image" (dict "root" . "kind" "function"))) -}} +{{- fail "sandbox.kubernetes.prePull.enabled=true needs sandbox.kubernetes.images.function.tag or .digest, so the DaemonSet holds the exact image the app runs" -}} +{{- end -}} +{{- end -}} +{{- end }} + +{{/* +Kubernetes sandbox provider: env entries for the app container. +*/}} +{{- define "sim.sandbox.appEnv" -}} +{{- $sbx := .Values.sandbox.kubernetes -}} +- name: SANDBOX_PROVIDER + value: kubernetes +- name: SANDBOX_K8S_NAMESPACE + value: {{ include "sim.sandbox.namespace" . | quote }} +{{- with include "sim.sandbox.runtimeClassName" . }} +- name: SANDBOX_K8S_RUNTIME_CLASS + value: {{ . | quote }} +{{- end }} +{{- if $sbx.allowUnisolated }} +- name: SANDBOX_K8S_ALLOW_UNISOLATED + value: "true" +{{- end }} +{{- range $kind := list "agent" "function" "pi" "mothership" "doc" }} +{{- with include "sim.sandbox.image" (dict "root" $ "kind" $kind) }} +- name: SANDBOX_K8S_{{ upper $kind }}_IMAGE + value: {{ . | quote }} +{{- end }} +{{- end }} +- name: SANDBOX_K8S_CPU + value: {{ $sbx.resources.cpu | toString | quote }} +- name: SANDBOX_K8S_MEMORY + value: {{ $sbx.resources.memory | toString | quote }} +- name: SANDBOX_K8S_EPHEMERAL_STORAGE + value: {{ $sbx.resources.ephemeralStorage | toString | quote }} +{{- with $sbx.nodeSelector }} +- name: SANDBOX_K8S_NODE_SELECTOR + value: {{ toJson . | quote }} +{{- end }} +{{- with $sbx.tolerations }} +- name: SANDBOX_K8S_TOLERATIONS + value: {{ toJson . | quote }} +{{- end }} +{{- with $sbx.imagePullSecret }} +- name: SANDBOX_K8S_IMAGE_PULL_SECRET + value: {{ . | quote }} +{{- end }} +{{- end }} diff --git a/helm/sim/templates/daemonset-sandbox-prepull.yaml b/helm/sim/templates/daemonset-sandbox-prepull.yaml new file mode 100644 index 00000000000..a34e50bd6fe --- /dev/null +++ b/helm/sim/templates/daemonset-sandbox-prepull.yaml @@ -0,0 +1,55 @@ +{{- /* + Holds the sandbox function image on every node sandbox pods can land on, so a + sandbox start does not wait for the pull. The idle container keeps the image in + use, which also keeps kubelet image garbage collection from removing it. It runs + under the sandbox RuntimeClass to land on the same nodes and fill the same image + store. Lives in the release namespace so it never counts against the sandbox quota. +*/}} +{{- if and .Values.sandbox.kubernetes.enabled .Values.sandbox.kubernetes.prePull.enabled }} +{{- include "sim.sandbox.validate" . }} +{{- $sbx := .Values.sandbox.kubernetes }} +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: {{ include "sim.fullname" . }}-sandbox-prepull + namespace: {{ .Release.Namespace }} + labels: + {{- include "sim.labels" . | nindent 4 }} + app.kubernetes.io/component: sandbox-prepull +spec: + selector: + matchLabels: + {{- include "sim.selectorLabels" . | nindent 6 }} + app.kubernetes.io/component: sandbox-prepull + updateStrategy: + type: RollingUpdate + template: + metadata: + labels: + {{- include "sim.selectorLabels" . | nindent 8 }} + app.kubernetes.io/component: sandbox-prepull + spec: + {{- with .Values.global.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + automountServiceAccountToken: false + enableServiceLinks: false + {{- with include "sim.sandbox.runtimeClassName" . }} + runtimeClassName: {{ . }} + {{- end }} + {{- with $sbx.prePull.priorityClassName }} + priorityClassName: {{ . }} + {{- end }} + {{- include "sim.podSecurityContext" (dict) | nindent 6 }} + {{- include "sim.nodeSelector" $sbx | nindent 6 }} + {{- include "sim.tolerations" $sbx | nindent 6 }} + terminationGracePeriodSeconds: 0 + containers: + - name: hold-function-image + image: {{ include "sim.sandbox.image" (dict "root" . "kind" "function") }} + imagePullPolicy: IfNotPresent + command: ["sleep", "infinity"] + {{- include "sim.resources" $sbx.prePull | nindent 10 }} + {{- include "sim.containerSecurityContext" (dict) | nindent 10 }} +{{- end }} diff --git a/helm/sim/templates/deployment-app.yaml b/helm/sim/templates/deployment-app.yaml index b7eb748b3d8..2d46d8e38f0 100644 --- a/helm/sim/templates/deployment-app.yaml +++ b/helm/sim/templates/deployment-app.yaml @@ -1,5 +1,6 @@ {{- if .Values.app.enabled }} {{- include "sim.validateSecrets" . }} +{{- include "sim.sandbox.validate" . }} apiVersion: apps/v1 kind: Deployment metadata: @@ -41,7 +42,8 @@ spec: {{- toYaml . | nindent 8 }} {{- end }} serviceAccountName: {{ include "sim.serviceAccountName" . }} - automountServiceAccountToken: false + {{- /* The Kubernetes sandbox provider manages pods through the API, so only then does the app mount its projected token. */}} + automountServiceAccountToken: {{ if .Values.sandbox.kubernetes.enabled }}true{{ else }}false{{ end }} {{- include "sim.podSecurityContext" .Values.app | nindent 6 }} {{- include "sim.nodeSelector" .Values.app | nindent 6 }} {{- include "sim.tolerations" .Values | nindent 6 }} @@ -147,6 +149,9 @@ spec: name: {{ include "sim.copilot.envSecretName" . }} key: COPILOT_INBOUND_API_KEY {{- end }} + {{- if .Values.sandbox.kubernetes.enabled }} + {{- include "sim.sandbox.appEnv" . | nindent 12 }} + {{- end }} {{- /* Operator overrides last, so they win over the defaults above and over envFrom. */}} {{- include "sim.appEnvOverrides" . | trim | nindent 12 }} envFrom: diff --git a/helm/sim/templates/networkpolicy.yaml b/helm/sim/templates/networkpolicy.yaml index 9a63df017b1..e56c3903767 100644 --- a/helm/sim/templates/networkpolicy.yaml +++ b/helm/sim/templates/networkpolicy.yaml @@ -135,6 +135,36 @@ spec: - protocol: TCP port: 4318 {{- end }} + {{- if .Values.sandbox.kubernetes.enabled }} + # Allow egress to sandbox pods' agent port (Kubernetes sandbox provider) + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: {{ include "sim.sandbox.namespace" . }} + ports: + - protocol: TCP + port: 49983 + # Allow egress to the Kubernetes API, which the sandbox provider manages pods through + - to: + {{- with .Values.sandbox.kubernetes.apiServerEgress.cidrs }} + {{- range . }} + - ipBlock: + cidr: {{ . | quote }} + {{- end }} + {{- else }} + - ipBlock: + cidr: 0.0.0.0/0 + except: + {{- range (default (list "169.254.169.254/32" "169.254.170.2/32") .Values.networkPolicy.egressExceptCidrs) }} + - {{ . | quote }} + {{- end }} + {{- end }} + ports: + {{- range .Values.sandbox.kubernetes.apiServerEgress.ports }} + - protocol: TCP + port: {{ . }} + {{- end }} + {{- end }} # Allow DNS resolution - to: [] ports: diff --git a/helm/sim/templates/sandbox-kubernetes.yaml b/helm/sim/templates/sandbox-kubernetes.yaml new file mode 100644 index 00000000000..9f6f5d5be64 --- /dev/null +++ b/helm/sim/templates/sandbox-kubernetes.yaml @@ -0,0 +1,244 @@ +{{- /* + Kubernetes sandbox provider: the namespace sandbox pods run in, the app's rights + over it, and the boundaries every sandbox pod inherits from it (Pod Security, + NetworkPolicy, quota). The app creates the pods themselves at run time. +*/}} +{{- if .Values.sandbox.kubernetes.enabled }} +{{- include "sim.sandbox.validate" . }} +{{- $sbx := .Values.sandbox.kubernetes }} +{{- $ns := include "sim.sandbox.namespace" . }} +{{- $runtimeClassName := include "sim.sandbox.runtimeClassName" . }} +{{- if $sbx.namespace.create }} +--- +{{- /* + Pod Security "baseline", not "restricted": the in-sandbox agent runs as root and + adds CHOWN, DAC_OVERRIDE, FOWNER, SETUID, SETGID, and KILL so it can run user code + as uid 1000 and install dependencies. "restricted" forbids both. Baseline still + refuses privileged pods, host namespaces, and hostPath; the VM or gVisor runtime + is the boundary that contains root. +*/}} +apiVersion: v1 +kind: Namespace +metadata: + name: {{ $ns }} + labels: + {{- include "sim.sandbox.labels" . | nindent 4 }} + pod-security.kubernetes.io/enforce: baseline + pod-security.kubernetes.io/enforce-version: latest + pod-security.kubernetes.io/warn: baseline + pod-security.kubernetes.io/warn-version: latest + pod-security.kubernetes.io/audit: baseline + pod-security.kubernetes.io/audit-version: latest + {{- with $sbx.namespace.labels }} + {{- toYaml . | nindent 4 }} + {{- end }} + {{- with $sbx.namespace.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +{{- end }} +--- +{{- /* No pods/exec and no Secrets: the app talks to sandboxes only through the agent port. */}} +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ include "sim.fullname" . }}-sandbox-manager + namespace: {{ $ns }} + labels: + {{- include "sim.sandbox.labels" . | nindent 4 }} +rules: + - apiGroups: [""] + resources: ["pods"] + verbs: ["create", "get", "list", "watch", "delete", "patch"] + - apiGroups: [""] + resources: ["pods/log"] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ include "sim.fullname" . }}-sandbox-manager + namespace: {{ $ns }} + labels: + {{- include "sim.sandbox.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ include "sim.fullname" . }}-sandbox-manager +subjects: + - kind: ServiceAccount + name: {{ include "sim.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} +{{- if $runtimeClassName }} +--- +{{- /* The app reads its RuntimeClass to refuse one whose handler shares the node kernel. */}} +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: {{ printf "%s-%s-sandbox-runtimeclass" .Release.Namespace (include "sim.fullname" .) }} + labels: + {{- include "sim.sandbox.labels" . | nindent 4 }} +rules: + - apiGroups: ["node.k8s.io"] + resources: ["runtimeclasses"] + resourceNames: [{{ $runtimeClassName | quote }}] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: {{ printf "%s-%s-sandbox-runtimeclass" .Release.Namespace (include "sim.fullname" .) }} + labels: + {{- include "sim.sandbox.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: {{ printf "%s-%s-sandbox-runtimeclass" .Release.Namespace (include "sim.fullname" .) }} +subjects: + - kind: ServiceAccount + name: {{ include "sim.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} +{{- end }} +{{- if $sbx.runtimeClass.create }} +--- +apiVersion: node.k8s.io/v1 +kind: RuntimeClass +metadata: + name: {{ $runtimeClassName }} + labels: + {{- include "sim.sandbox.labels" . | nindent 4 }} +handler: {{ include "sim.sandbox.runtimeClassHandler" . }} +{{- with $sbx.runtimeClass.overhead }} +overhead: + {{- toYaml . | nindent 2 }} +{{- end }} +{{- with $sbx.runtimeClass.scheduling }} +scheduling: + {{- toYaml . | nindent 2 }} +{{- end }} +{{- end }} +--- +{{- /* + Selects every pod in the sandbox namespace: only the Sim app reaches the agent, + and egress follows the chosen profile. +*/}} +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ include "sim.fullname" . }}-sandbox + namespace: {{ $ns }} + labels: + {{- include "sim.sandbox.labels" . | nindent 4 }} +spec: + podSelector: {} + policyTypes: + - Ingress + - Egress + ingress: + - from: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: {{ .Release.Namespace }} + podSelector: + matchLabels: + {{- include "sim.app.selectorLabels" . | nindent 10 }} + ports: + - protocol: TCP + port: 49983 + egress: + # DNS resolution + - to: [] + ports: + - protocol: UDP + port: 53 + - protocol: TCP + port: 53 + {{- if eq $sbx.egress.profile "internet" }} + {{- $blocked := concat $sbx.egress.blockedCidrs $sbx.egress.clusterCidrs }} + {{- $blockedV4 := list }} + {{- $blockedV6 := list }} + {{- range $blocked }} + {{- if contains ":" . }} + {{- $blockedV6 = append $blockedV6 . }} + {{- else }} + {{- $blockedV4 = append $blockedV4 . }} + {{- end }} + {{- end }} + # Public internet, excluding private, cluster, link-local, and metadata ranges + - to: + - ipBlock: + cidr: 0.0.0.0/0 + {{- with $blockedV4 }} + except: + {{- range . }} + - {{ . | quote }} + {{- end }} + {{- end }} + - ipBlock: + cidr: ::/0 + {{- with $blockedV6 }} + except: + {{- range . }} + - {{ . | quote }} + {{- end }} + {{- end }} + {{- else }} + {{- with $sbx.egress.allowedCidrs }} + # Operator allowlist + - to: + {{- range . }} + - ipBlock: + cidr: {{ . | quote }} + {{- end }} + {{- end }} + {{- end }} + {{- with $sbx.egress.extraRules }} + {{- toYaml . | nindent 2 }} + {{- end }} +{{- if $sbx.quota.enabled }} +--- +apiVersion: v1 +kind: ResourceQuota +metadata: + name: {{ include "sim.fullname" . }}-sandbox + namespace: {{ $ns }} + labels: + {{- include "sim.sandbox.labels" . | nindent 4 }} +spec: + hard: + pods: {{ $sbx.quota.pods | toString | quote }} + limits.cpu: {{ $sbx.quota.cpu | toString | quote }} + limits.memory: {{ $sbx.quota.memory | toString | quote }} + limits.ephemeral-storage: {{ $sbx.quota.ephemeralStorage | toString | quote }} +{{- end }} +{{- if $sbx.limitRange.enabled }} +--- +{{- /* + The quota counts limits, so a container without them is refused: the defaults + size the ones the app leaves unsized (the agent init container) without raising + the pod's effective request. max caps any container at the sandbox size. +*/}} +apiVersion: v1 +kind: LimitRange +metadata: + name: {{ include "sim.fullname" . }}-sandbox + namespace: {{ $ns }} + labels: + {{- include "sim.sandbox.labels" . | nindent 4 }} +spec: + limits: + - type: Container + default: + cpu: {{ $sbx.resources.cpu | toString | quote }} + memory: {{ $sbx.resources.memory | toString | quote }} + ephemeral-storage: {{ $sbx.resources.ephemeralStorage | toString | quote }} + defaultRequest: + cpu: 50m + memory: 64Mi + ephemeral-storage: 64Mi + max: + cpu: {{ $sbx.resources.cpu | toString | quote }} + memory: {{ $sbx.resources.memory | toString | quote }} + ephemeral-storage: {{ $sbx.resources.ephemeralStorage | toString | quote }} +{{- end }} +{{- end }} diff --git a/helm/sim/tests/sandbox-kubernetes_test.yaml b/helm/sim/tests/sandbox-kubernetes_test.yaml new file mode 100644 index 00000000000..ccc88fdfc39 --- /dev/null +++ b/helm/sim/tests/sandbox-kubernetes_test.yaml @@ -0,0 +1,537 @@ +suite: Kubernetes sandbox provider — namespace, RBAC, isolation, network, quota +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 +enabled: &enabled + <<: *defaults + sandbox.kubernetes.enabled: true + sandbox.kubernetes.runtimeClass.preset: gvisor + +tests: + - it: renders nothing for the provider when disabled + template: sandbox-kubernetes.yaml + set: + <<: *defaults + asserts: + - hasDocuments: { count: 0 } + + - it: renders no pre-pull DaemonSet when disabled + template: daemonset-sandbox-prepull.yaml + set: + <<: *defaults + sandbox.kubernetes.prePull.enabled: true + asserts: + - hasDocuments: { count: 0 } + + - it: keeps the app token unmounted and sets no sandbox env when disabled + template: deployment-app.yaml + set: + <<: *defaults + asserts: + - equal: + path: spec.template.spec.automountServiceAccountToken + value: false + - notContains: + path: spec.template.spec.containers[0].env + content: + name: SANDBOX_PROVIDER + value: kubernetes + + - it: creates the sandbox namespace with Pod Security baseline enforced + template: sandbox-kubernetes.yaml + set: + <<: *enabled + documentSelector: + path: kind + value: Namespace + asserts: + - equal: + path: metadata.name + value: sim-sandboxes + - equal: + path: metadata.labels["pod-security.kubernetes.io/enforce"] + value: baseline + - equal: + path: metadata.labels["pod-security.kubernetes.io/warn"] + value: baseline + - equal: + path: metadata.labels["pod-security.kubernetes.io/audit"] + value: baseline + + - it: leaves an existing namespace alone when namespace.create=false + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.namespace.create: false + asserts: + - containsDocument: + kind: Namespace + apiVersion: v1 + name: sim-sandboxes + not: true + + - it: grants the app pod lifecycle and logs in the sandbox namespace, and nothing else + template: sandbox-kubernetes.yaml + set: + <<: *enabled + documentSelector: + path: kind + value: Role + asserts: + - equal: + path: metadata.namespace + value: sim-sandboxes + - equal: + path: rules + value: + - apiGroups: [""] + resources: ["pods"] + verbs: ["create", "get", "list", "watch", "delete", "patch"] + - apiGroups: [""] + resources: ["pods/log"] + verbs: ["get"] + - notContains: + path: rules + content: + apiGroups: [""] + resources: ["pods/exec"] + any: true + - notContains: + path: rules + content: + resources: ["secrets"] + any: true + + - it: binds the sandbox Role to the app ServiceAccount in the release namespace + template: sandbox-kubernetes.yaml + set: + <<: *enabled + documentSelector: + path: kind + value: RoleBinding + asserts: + - equal: + path: subjects + value: + - kind: ServiceAccount + name: t-sim + namespace: sim + + - it: lets the app read only its own RuntimeClass cluster-wide + template: sandbox-kubernetes.yaml + set: + <<: *enabled + documentSelector: + path: kind + value: ClusterRole + asserts: + - equal: + path: rules + value: + - apiGroups: ["node.k8s.io"] + resources: ["runtimeclasses"] + resourceNames: ["gvisor"] + verbs: ["get"] + + - it: maps the kata preset to the AKS RuntimeClass name + template: deployment-app.yaml + set: + <<: *enabled + sandbox.kubernetes.runtimeClass.preset: kata + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: SANDBOX_K8S_RUNTIME_CLASS + value: kata-vm-isolation + + - it: maps the isolated-sandbox preset to the EKS RuntimeClass name + template: deployment-app.yaml + set: + <<: *enabled + sandbox.kubernetes.runtimeClass.preset: isolated-sandbox + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: SANDBOX_K8S_RUNTIME_CLASS + value: isolated-sandbox + + - it: does not create a RuntimeClass unless asked + template: sandbox-kubernetes.yaml + set: + <<: *enabled + asserts: + - containsDocument: + kind: RuntimeClass + apiVersion: node.k8s.io/v1 + not: true + + - it: creates a gVisor RuntimeClass with the runsc handler for self-managed clusters + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.runtimeClass.create: true + documentSelector: + path: kind + value: RuntimeClass + asserts: + - equal: + path: metadata.name + value: gvisor + - equal: + path: handler + value: runsc + + - it: refuses to create a runc RuntimeClass + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.runtimeClass.preset: custom + sandbox.kubernetes.runtimeClass.name: shared-kernel + sandbox.kubernetes.runtimeClass.create: true + sandbox.kubernetes.runtimeClass.handler: runc + asserts: + - failedTemplate: + errorPattern: "shares the node kernel" + + - it: refuses to create the RuntimeClass a cloud provider manages + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.runtimeClass.preset: isolated-sandbox + sandbox.kubernetes.runtimeClass.create: true + asserts: + - failedTemplate: + errorPattern: "the cloud provider manages that RuntimeClass" + + - it: refuses to enable without an isolation runtime or the explicit opt-in + template: sandbox-kubernetes.yaml + set: + <<: *defaults + sandbox.kubernetes.enabled: true + asserts: + - failedTemplate: + errorPattern: "need a VM or gVisor runtime" + + - it: passes the unisolated opt-in through to the app without a RuntimeClass + template: deployment-app.yaml + set: + <<: *defaults + sandbox.kubernetes.enabled: true + sandbox.kubernetes.allowUnisolated: true + asserts: + - contains: + path: spec.template.spec.containers[0].env + content: + name: SANDBOX_K8S_ALLOW_UNISOLATED + value: "true" + - notContains: + path: spec.template.spec.containers[0].env + content: + name: SANDBOX_K8S_RUNTIME_CLASS + any: true + + - it: grants no RuntimeClass read when there is no RuntimeClass + template: sandbox-kubernetes.yaml + set: + <<: *defaults + sandbox.kubernetes.enabled: true + sandbox.kubernetes.allowUnisolated: true + asserts: + - containsDocument: + kind: ClusterRole + apiVersion: rbac.authorization.k8s.io/v1 + not: true + + - it: refuses the release namespace as the sandbox namespace + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.namespace.name: sim + asserts: + - failedTemplate: + errorPattern: "must differ from the release namespace" + + - it: refuses to bind pod-management RBAC to the default ServiceAccount + template: sandbox-kubernetes.yaml + set: + <<: *enabled + serviceAccount.create: false + asserts: + - failedTemplate: + errorPattern: "resolves to \"default\"" + + - it: mounts the app token and wires the provider env when enabled + template: deployment-app.yaml + set: + <<: *enabled + sandbox.kubernetes.images.function.digest: sha256:0000000000000000000000000000000000000000000000000000000000000000 + sandbox.kubernetes.imagePullSecret: sandbox-pull + sandbox.kubernetes.nodeSelector: + pool: sandboxes + sandbox.kubernetes.tolerations: + - key: pool + operator: Equal + value: sandboxes + effect: NoSchedule + asserts: + - equal: + path: spec.template.spec.automountServiceAccountToken + value: true + - contains: + path: spec.template.spec.containers[0].env + content: { name: SANDBOX_PROVIDER, value: kubernetes } + - contains: + path: spec.template.spec.containers[0].env + content: { name: SANDBOX_K8S_NAMESPACE, value: sim-sandboxes } + - contains: + path: spec.template.spec.containers[0].env + content: { name: SANDBOX_K8S_RUNTIME_CLASS, value: gvisor } + - contains: + path: spec.template.spec.containers[0].env + content: + name: SANDBOX_K8S_FUNCTION_IMAGE + value: ghcr.io/simstudioai/sandbox-function@sha256:0000000000000000000000000000000000000000000000000000000000000000 + - contains: + path: spec.template.spec.containers[0].env + content: { name: SANDBOX_K8S_CPU, value: "1" } + - contains: + path: spec.template.spec.containers[0].env + content: { name: SANDBOX_K8S_MEMORY, value: 2Gi } + - contains: + path: spec.template.spec.containers[0].env + content: { name: SANDBOX_K8S_EPHEMERAL_STORAGE, value: 4Gi } + - contains: + path: spec.template.spec.containers[0].env + content: { name: SANDBOX_K8S_NODE_SELECTOR, value: '{"pool":"sandboxes"}' } + - contains: + path: spec.template.spec.containers[0].env + content: + name: SANDBOX_K8S_TOLERATIONS + value: '[{"effect":"NoSchedule","key":"pool","operator":"Equal","value":"sandboxes"}]' + - contains: + path: spec.template.spec.containers[0].env + content: { name: SANDBOX_K8S_IMAGE_PULL_SECRET, value: sandbox-pull } + - notContains: + path: spec.template.spec.containers[0].env + content: { name: SANDBOX_K8S_PI_IMAGE } + any: true + + - it: lets operator extraEnvVars override the provider env + template: deployment-app.yaml + set: + <<: *enabled + extraEnvVars: + - name: SANDBOX_K8S_CPU + value: "2" + asserts: + - equal: + path: spec.template.spec.containers[0].env[-1] + value: { name: SANDBOX_K8S_CPU, value: "2" } + + - it: admits ingress to sandboxes only from the Sim app on the agent port + template: sandbox-kubernetes.yaml + set: + <<: *enabled + documentSelector: + path: kind + value: NetworkPolicy + asserts: + - equal: + path: spec.podSelector + value: {} + - equal: + path: spec.policyTypes + value: [Ingress, Egress] + - equal: + path: spec.ingress + value: + - from: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: sim + podSelector: + matchLabels: + app.kubernetes.io/name: sim + app.kubernetes.io/instance: t + app.kubernetes.io/component: app + ports: + - protocol: TCP + port: 49983 + + - it: internet egress profile excludes private, cluster, and metadata ranges + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.egress.clusterCidrs: ["198.18.0.0/15", "fd12::/64"] + documentSelector: + path: kind + value: NetworkPolicy + asserts: + - equal: + path: spec.egress[1].to + value: + - ipBlock: + cidr: 0.0.0.0/0 + except: + - 10.0.0.0/8 + - 172.16.0.0/12 + - 192.168.0.0/16 + - 100.64.0.0/10 + - 169.254.0.0/16 + - 169.254.169.254/32 + - 198.18.0.0/15 + - ipBlock: + cidr: ::/0 + except: + - fc00::/7 + - fe80::/10 + - fd00:ec2::254/128 + - fd12::/64 + - notExists: + path: spec.egress[1].ports + + - it: restricted egress profile allows only DNS and the allowlist + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.egress.profile: restricted + sandbox.kubernetes.egress.allowedCidrs: ["203.0.113.10/32"] + documentSelector: + path: kind + value: NetworkPolicy + asserts: + - lengthEqual: + path: spec.egress + count: 2 + - equal: + path: spec.egress[0].ports + value: + - protocol: UDP + port: 53 + - protocol: TCP + port: 53 + - equal: + path: spec.egress[1] + value: + to: + - ipBlock: + cidr: 203.0.113.10/32 + + - it: restricted egress profile with no allowlist leaves DNS only + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.egress.profile: restricted + documentSelector: + path: kind + value: NetworkPolicy + asserts: + - lengthEqual: + path: spec.egress + count: 1 + + - it: caps concurrent sandboxes and their resources with a quota + template: sandbox-kubernetes.yaml + set: + <<: *enabled + documentSelector: + path: kind + value: ResourceQuota + asserts: + - equal: + path: spec.hard + value: + pods: "20" + limits.cpu: "20" + limits.memory: 40Gi + limits.ephemeral-storage: 80Gi + + - it: caps any container at the configured sandbox size + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.resources.cpu: "2" + documentSelector: + path: kind + value: LimitRange + asserts: + - equal: + path: spec.limits[0].max + value: + cpu: "2" + memory: 2Gi + ephemeral-storage: 4Gi + + - it: lets the app reach the sandbox agent port and the API server under networkPolicy + template: networkpolicy.yaml + set: + <<: *enabled + networkPolicy.enabled: true + sandbox.kubernetes.apiServerEgress.cidrs: ["10.100.0.1/32"] + documentIndex: 0 + asserts: + - contains: + path: spec.egress + content: + to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: sim-sandboxes + ports: + - protocol: TCP + port: 49983 + - contains: + path: spec.egress + content: + to: + - ipBlock: + cidr: 10.100.0.1/32 + ports: + - protocol: TCP + port: 443 + - protocol: TCP + port: 6443 + + - it: refuses pre-pull without a pinned function image + template: sandbox-kubernetes.yaml + set: + <<: *enabled + sandbox.kubernetes.prePull.enabled: true + asserts: + - failedTemplate: + errorPattern: "needs sandbox.kubernetes.images.function.tag or .digest" + + - it: pre-pulls the pinned function image on sandbox nodes under the sandbox runtime + template: daemonset-sandbox-prepull.yaml + set: + <<: *enabled + sandbox.kubernetes.prePull.enabled: true + sandbox.kubernetes.images.function.tag: abc123 + sandbox.kubernetes.nodeSelector: + pool: sandboxes + asserts: + - isKind: + of: DaemonSet + - equal: + path: metadata.namespace + value: sim + - equal: + path: spec.template.spec.runtimeClassName + value: gvisor + - equal: + path: spec.template.spec.nodeSelector + value: { pool: sandboxes } + - equal: + path: spec.template.spec.containers[0].image + value: ghcr.io/simstudioai/sandbox-function:abc123 + - equal: + path: spec.template.spec.automountServiceAccountToken + value: false diff --git a/helm/sim/values.schema.json b/helm/sim/values.schema.json index 0e33283acfc..b3cbbada72c 100644 --- a/helm/sim/values.schema.json +++ b/helm/sim/values.schema.json @@ -1277,6 +1277,295 @@ "type": "object", "description": "NetworkPolicy toggles and custom ingress/egress rules" }, + "sandbox": { + "type": "object", + "description": "Sandbox providers that run on this cluster", + "additionalProperties": false, + "properties": { + "kubernetes": { + "type": "object", + "description": "Kubernetes sandbox provider: sandbox pods in a dedicated namespace under a VM or gVisor RuntimeClass", + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + }, + "namespace": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + "pattern": "^[a-z0-9]([-a-z0-9]*[a-z0-9])?$", + "maxLength": 63 + }, + "create": { + "type": "boolean" + }, + "labels": { + "type": "object" + }, + "annotations": { + "type": "object" + } + } + }, + "runtimeClass": { + "type": "object", + "additionalProperties": false, + "properties": { + "preset": { + "type": "string", + "enum": [ + "", + "isolated-sandbox", + "gvisor", + "kata", + "custom" + ] + }, + "name": { + "type": "string" + }, + "create": { + "type": "boolean" + }, + "handler": { + "type": "string" + }, + "scheduling": { + "type": "object" + }, + "overhead": { + "type": "object" + } + } + }, + "allowUnisolated": { + "type": "boolean", + "description": "Run sandboxes on the shared node kernel (runc/crun or no RuntimeClass)" + }, + "images": { + "type": "object", + "additionalProperties": false, + "properties": { + "agent": { + "type": "object", + "additionalProperties": false, + "properties": { + "repository": { + "type": "string" + }, + "tag": { + "type": "string" + }, + "digest": { + "type": "string" + } + } + }, + "function": { + "type": "object", + "additionalProperties": false, + "properties": { + "repository": { + "type": "string" + }, + "tag": { + "type": "string" + }, + "digest": { + "type": "string" + } + } + }, + "pi": { + "type": "object", + "additionalProperties": false, + "properties": { + "repository": { + "type": "string" + }, + "tag": { + "type": "string" + }, + "digest": { + "type": "string" + } + } + }, + "mothership": { + "type": "object", + "additionalProperties": false, + "properties": { + "repository": { + "type": "string" + }, + "tag": { + "type": "string" + }, + "digest": { + "type": "string" + } + } + }, + "doc": { + "type": "object", + "additionalProperties": false, + "properties": { + "repository": { + "type": "string" + }, + "tag": { + "type": "string" + }, + "digest": { + "type": "string" + } + } + } + } + }, + "imagePullSecret": { + "type": "string" + }, + "resources": { + "type": "object", + "additionalProperties": false, + "properties": { + "cpu": { + "type": "string", + "pattern": "^[0-9]+(\\.[0-9]+)?(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?$" + }, + "memory": { + "type": "string", + "pattern": "^[0-9]+(\\.[0-9]+)?(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?$" + }, + "ephemeralStorage": { + "type": "string", + "pattern": "^[0-9]+(\\.[0-9]+)?(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?$" + } + } + }, + "nodeSelector": { + "type": "object" + }, + "tolerations": { + "type": "array", + "items": { + "type": "object" + } + }, + "quota": { + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + }, + "pods": { + "type": "integer", + "minimum": 1 + }, + "cpu": { + "type": "string", + "pattern": "^[0-9]+(\\.[0-9]+)?(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?$" + }, + "memory": { + "type": "string", + "pattern": "^[0-9]+(\\.[0-9]+)?(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?$" + }, + "ephemeralStorage": { + "type": "string", + "pattern": "^[0-9]+(\\.[0-9]+)?(Ki|Mi|Gi|Ti|Pi|Ei|m|k|M|G|T|P|E)?$" + } + } + }, + "limitRange": { + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + } + } + }, + "egress": { + "type": "object", + "additionalProperties": false, + "properties": { + "profile": { + "type": "string", + "enum": [ + "internet", + "restricted" + ] + }, + "blockedCidrs": { + "type": "array", + "items": { + "type": "string" + } + }, + "clusterCidrs": { + "type": "array", + "items": { + "type": "string" + } + }, + "allowedCidrs": { + "type": "array", + "items": { + "type": "string" + } + }, + "extraRules": { + "type": "array", + "items": { + "type": "object" + } + } + } + }, + "apiServerEgress": { + "type": "object", + "additionalProperties": false, + "properties": { + "cidrs": { + "type": "array", + "items": { + "type": "string" + } + }, + "ports": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1, + "maximum": 65535 + } + } + } + }, + "prePull": { + "type": "object", + "additionalProperties": false, + "properties": { + "enabled": { + "type": "boolean" + }, + "priorityClassName": { + "type": "string" + }, + "resources": { + "type": "object" + } + } + } + } + } + } + }, "podAnnotations": { "type": "object", "description": "Annotations added to app and realtime pods" diff --git a/helm/sim/values.yaml b/helm/sim/values.yaml index 7ea708f9306..98790d7e8f4 100644 --- a/helm/sim/values.yaml +++ b/helm/sim/values.yaml @@ -1202,6 +1202,156 @@ networkPolicy: # selector and do not need it. allowExternalEgress: false +# Code sandboxes on this cluster: the app runs Python, Shell, imported JavaScript, +# Pi, and chat code tools in short-lived pods it creates in a dedicated namespace, +# instead of calling E2B or Daytona. See +# https://docs.sim.ai/platform/self-hosting/sandboxes#kubernetes-no-third-party +sandbox: + kubernetes: + # Off by default: existing installs render exactly as before. Enabling sets + # SANDBOX_PROVIDER=kubernetes on the app, so do not also set it in app.env. + enabled: false + + # Namespace that holds sandbox pods. It must differ from the release namespace: + # its Pod Security level, quota, and NetworkPolicies apply to every pod in it. + namespace: + name: sim-sandboxes + # Create it with the Pod Security labels the chart sets. With create=false, + # create it yourself and label it pod-security.kubernetes.io/enforce=baseline. + create: true + labels: {} + annotations: {} + + # Isolation runtime for sandbox pods. User code runs as root inside the + # sandbox, so it needs a VM or gVisor boundary; the app refuses a RuntimeClass + # whose handler is runc, crun, or empty. + # isolated-sandbox EKS Nitro Sandboxes (Kubernetes 1.36+, provided by EKS) + # gvisor GKE Sandbox, or a self-managed gVisor install (handler runsc) + # kata AKS Pod Sandboxing (RuntimeClass kata-vm-isolation, provided by AKS) + # custom any other VM or gVisor RuntimeClass; set name + runtimeClass: + preset: "" + # Overrides the preset's RuntimeClass name. Required for `custom`. + name: "" + # Create the RuntimeClass object. Only for self-managed runtimes: EKS, GKE, + # and AKS create theirs. The chart never creates a runc or crun RuntimeClass. + create: false + # Handler for a created RuntimeClass (gvisor defaults to runsc). + handler: "" + # Scheduling and overhead for a created RuntimeClass. + scheduling: {} + overhead: {} + + # Run sandboxes without a RuntimeClass, or on a runc/crun one. User code then + # shares the node kernel with your other workloads, so a kernel or runtime + # escape reaches the node. Only for trusted authors or a throwaway cluster. + allowUnisolated: false + + # Sandbox images. With tag and digest empty the app uses the images built for + # its release, so leave them empty unless you mirror or pin them. mothership + # (chat code tools) and doc (document generation) are private images with no + # default: set them to enable those kinds, along with imagePullSecret. + # global.imageRegistry rewrites these repositories as it does the app images. + images: + agent: + repository: simstudioai/sandbox-agent + tag: "" + digest: "" + function: + repository: simstudioai/sandbox-function + tag: "" + digest: "" + pi: + repository: simstudioai/sandbox-pi + tag: "" + digest: "" + mothership: + repository: simstudioai/copilot-sandbox-shell + tag: "" + digest: "" + doc: + repository: simstudioai/copilot-sandbox-doc + tag: "" + digest: "" + + # Name of a docker-registry Secret in the sandbox namespace, attached to every + # sandbox pod. Create it yourself: the chart does not copy Secrets across namespaces. + imagePullSecret: "" + + # Per-sandbox limits; requests are half. They also become the namespace + # LimitRange default and maximum, so no pod there can ask for more. + resources: + cpu: "1" + memory: 2Gi + ephemeralStorage: 4Gi + + # Scheduling for sandbox pods and the pre-pull DaemonSet, e.g. a dedicated + # node pool. A RuntimeClass's own scheduling rules apply on top. + nodeSelector: {} + tolerations: [] + + # Namespace-wide ceiling on concurrent sandboxes. Past it, new sandboxes fail + # with a quota error instead of queueing. Keep pods x resources within it. + quota: + enabled: true + pods: 20 + cpu: "20" + memory: 40Gi + ephemeralStorage: 80Gi + + limitRange: + enabled: true + + # Sandbox network access. These NetworkPolicies render whenever the provider is + # enabled, independent of networkPolicy.enabled. Ingress is always limited to + # the Sim app pods on the agent port (49983). + egress: + # internet: any public address on any port, as E2B sandboxes get. + # restricted: DNS plus allowedCidrs only. + profile: internet + # Excluded from the internet profile: RFC 1918, CGNAT, link-local (which holds + # the cloud metadata endpoints), and IPv6 unique-local and link-local. + blockedCidrs: + - "10.0.0.0/8" + - "172.16.0.0/12" + - "192.168.0.0/16" + - "100.64.0.0/10" + - "169.254.0.0/16" + - "169.254.169.254/32" + - "fc00::/7" + - "fe80::/10" + - "fd00:ec2::254/128" + # Pod and Service CIDRs outside the ranges above, also excluded. + clusterCidrs: [] + # Destinations the restricted profile allows (CIDRs, any port). + allowedCidrs: [] + # Extra NetworkPolicy egress rules appended in either profile. + extraRules: [] + + # Egress the app NetworkPolicy (networkPolicy.enabled=true) gains so the app + # can reach the Kubernetes API. Narrow cidrs to your API server endpoints; + # empty means any address except networkPolicy.egressExceptCidrs. + apiServerEgress: + cidrs: [] + ports: + - 443 + - 6443 + + # Keeps the function image on every sandbox node so a sandbox does not pull it + # on first use. Needs images.function.tag or digest, so it holds exactly the + # image the app runs. Each node runs one idle pod under the sandbox RuntimeClass. + prePull: + enabled: false + priorityClassName: "" + # VM runtimes size the pod VM from these, so keep room for a guest kernel. + resources: + limits: + cpu: 100m + memory: 256Mi + requests: + cpu: 10m + memory: 64Mi + # Additional volumes for custom configurations (advanced users) extraVolumes: [] extraVolumeMounts: [] From 96aa8f145f78ee113dd46048bd1db20a3eeea423 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 2 Dec 2026 14:03:12 -0600 Subject: [PATCH 29/78] docs(sandbox): document the Kubernetes sandbox provider Adds the Kubernetes option to the sandboxes guide: how pods, the agent, and sessions work; the isolation runtime each platform needs (EKS Nitro Sandboxes, GKE Sandbox, AKS Pod Sandboxing, self-managed gVisor or Kata) and the refusal of runc behind an explicit opt-in; Helm setup and what the chart renders; egress profiles; images; capacity and cost; pre-pull; and the limits (no pause, setsid escape, Compose unsupported). Adds the provider to the security comparison, the SANDBOX_K8S_* variables to the environment reference and .env.example, and a pointer from the Kubernetes install guide. --- .../self-hosting/environment-variables.mdx | 10 +- .../docs/platform/self-hosting/kubernetes.mdx | 5 + .../docs/platform/self-hosting/sandboxes.mdx | 134 +++++++++++++++++- .../docs/platform/self-hosting/security.mdx | 4 + apps/sim/.env.example | 14 ++ 5 files changed, 165 insertions(+), 2 deletions(-) diff --git a/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx b/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx index 3483be41e3e..b00c8edb238 100644 --- a/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx +++ b/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx @@ -182,12 +182,20 @@ Who may sign up and sign in — the allowlists, blocklists, `REGISTRATION_MODE`, | Variable | Description | |----------|-------------| -| `SANDBOX_PROVIDER` | Remote sandbox provider: `e2b` (default) or `daytona` | +| `SANDBOX_PROVIDER` | Remote sandbox provider: `e2b` (default), `daytona`, or `kubernetes` | | `E2B_ENABLED` / `E2B_API_KEY` | Enable E2B remote execution | | `DAYTONA_API_KEY` | Daytona API key (used when `SANDBOX_PROVIDER=daytona`) | | `E2B_FUNCTION_TEMPLATE_ID` | Immutable `