From b55f6a42db9f0a4c45d29b92e88355b9f5c1b034 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 17 Nov 2026 19:32:45 +0000 Subject: [PATCH] Fetch exe.dev launch payloads using the VM run identity --- docs/execution-boundaries.md | 22 +++- packages/api-client/src/schema.d.ts | 80 ++++++++++++ .../migrations/0053_run_launch_payload.sql | 3 + packages/api/src/api-contract.ts | 15 ++- packages/api/src/exe-vm-backend.ts | 8 +- packages/api/src/execution.ts | 2 + packages/api/src/factorize-job-launcher.ts | 42 ++++++- packages/api/src/flow-service.ts | 11 ++ packages/api/src/launch-payload.ts | 26 ++++ packages/api/src/postgres/run-repository.ts | 14 +++ packages/api/src/postgres/run-scheduler.ts | 17 ++- packages/api/src/postgres/schema.ts | 1 + packages/api/src/protected-api.ts | 1 + packages/api/test/api-boundary.test.ts | 12 ++ packages/api/test/execution-backend.test.ts | 11 +- packages/api/test/launcher-fetch.test.ts | 85 +++++++++++++ packages/api/test/run-vendor-launch.test.ts | 7 +- .../api/test/vendor-run-auth.postgres.test.ts | 55 +++++++++ packages/docs/openapi.yaml | 114 ++++++++++++++++++ 19 files changed, 505 insertions(+), 21 deletions(-) create mode 100644 packages/api/migrations/0053_run_launch_payload.sql create mode 100644 packages/api/src/launch-payload.ts create mode 100644 packages/api/test/launcher-fetch.test.ts diff --git a/docs/execution-boundaries.md b/docs/execution-boundaries.md index 16778dca..9fc3af4f 100644 --- a/docs/execution-boundaries.md +++ b/docs/execution-boundaries.md @@ -28,8 +28,26 @@ Amp thread URL. Amp does not declare output retrieval, so Factorize does not ingest thread contents. Amp credentials are dashboard-only; REST and MCP expose only non-secret target metadata and capabilities. -The prompt is delivered as part of direct process launch. The launch receipt is -persisted before polling begins so restarts can resume observation and cleanup. +For exe.dev runs, the scheduler encrypts and stores the exact launch payload +(rendered prompt, appended runtime instructions, harness and trace configuration, +or code script and input context) before VM provisioning. The first snapshot is +retained across launch retries. Provisioning transfers only the guest launcher +and identity helper, keeping prompts and scripts out of exe.dev's 64 KB command +request limit. Apply migration `0053_run_launch_payload` before deploying this +startup path. + +The launcher fetches `GET /api/v1/runtime-launch` through its local identity +helper before starting the harness. The endpoint requires the same vendor-signed +VM/run binding as other runtime operations, returns only the calling active +run's snapshot, requires no application scopes, rejects non-run identities and +stopping or terminal runs, and disables response caching. Downloads are limited +to 32 MiB, refuse redirects and mismatched run IDs, and retry transient failures +up to three times with a ten-second socket timeout. Exhausted or invalid fetches +record a launcher failure without starting the job. The harness receives the +prompt through stdin as before. + +The launch receipt is persisted before polling begins so restarts can resume +observation and cleanup. ## Job invocation boundary diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 999b7835..88813973 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1632,6 +1632,28 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/runtime-launch": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Fetch this VM's immutable launch payload + * @description Requires the vendor-verified identity of an active run. Returns only that run's encrypted-at-rest scheduler snapshot, including the rendered prompt and harness or code context. No application scope is required. Sessions, API keys, OAuth clients, other runs and terminal runs cannot retrieve it. Responses are never cached. + * + * Requires vendor-verified run identity; sessions and other bearer tokens cannot call this operation. + */ + get: operations["get_api_v1_runtime_launch"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/runtime-context": { parameters: { query?: never; @@ -6994,6 +7016,64 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; + get_api_v1_runtime_launch: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Launch payload for the calling run */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** @constant */ + version: 1; + /** Format: uuid */ + runId: string; + traceSources?: { + [key: string]: unknown; + }; + prompt: string; + harness: { + executable: string; + args: string[]; + env: { + [key: string]: string; + }; + }; + } | { + /** @constant */ + version: 1; + /** Format: uuid */ + runId: string; + traceSources?: { + [key: string]: unknown; + }; + code: { + script: string; + context: { + [key: string]: unknown; + }; + }; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; get_api_v1_runtime_context: { parameters: { query?: never; diff --git a/packages/api/migrations/0053_run_launch_payload.sql b/packages/api/migrations/0053_run_launch_payload.sql new file mode 100644 index 00000000..ee7cd2bf --- /dev/null +++ b/packages/api/migrations/0053_run_launch_payload.sql @@ -0,0 +1,3 @@ +-- Exact scheduler launch snapshots; plaintext prompts and scripts remain encrypted. +ALTER TABLE app.runs ADD COLUMN encrypted_launch_payload text; +INSERT INTO app.schema_migrations(version) VALUES ('0053_run_launch_payload') ON CONFLICT DO NOTHING; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 328cf09b..32e21172 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -1,4 +1,5 @@ import { queryOf } from "./query-params"; +import { launchPayloadResponse } from "./launch-payload"; import { searchResponse } from "./search-contracts"; import { consentPreviewInput, consentPreviewResponse, consentDecisionInput, consentDecisionResponse } from "./consent-api"; import { exeConnection, integrationStatus, authorizedClient, accessToken, createdAccessToken, savedExe, testedExe, savedAmp, savedTail, okResult } from "./settings-contracts"; @@ -37,6 +38,7 @@ export interface RouteContract { path: string; scope: string | string[]; ownerSession: boolean; + vendorIdentityOnly?: boolean; authOperation?: AuthAction; body?: z.ZodType; maxBodyBytes?: number; @@ -150,7 +152,7 @@ function route( documentation: RouteContract["documentation"], execute: RouteContract["execute"], options: Partial< - Pick + Pick > = {}, ): RouteContract { const keys = [...path.matchAll(/\{([^}]+)\}/g)].map((match) => match[1]); @@ -185,7 +187,7 @@ function route( // Legacy route labels are translated by resource and effect; they are never // accepted as newly issued scopes. function scopeForRoute(path: string, legacy: string): string | string[] { - if (path === "/api/v1/runtime-context" || path === "/api/v1/runtime-integrations") return []; + if (path === "/api/v1/runtime-context" || path === "/api/v1/runtime-integrations" || path === "/api/v1/runtime-launch") return []; if (legacy === "runs:write" && path.endsWith("/report-error")) return "runs:write"; if (legacy === "runs:write" && path === "/api/v1/runs/{runId}" ) return "runs:write"; if (legacy === "runs:read" && path === "/api/v1/search") return "jobs:read+runs:read"; @@ -846,6 +848,11 @@ export const API_ROUTES: RouteContract[] = [ (service, { params, body }) => service.invokeJob(params.jobId, body), { body: manualInvocationSchema }, ), + route("GET", "/api/v1/runtime-launch", "runs:read", { + summary: "Fetch this VM's immutable launch payload", + description: "Requires the vendor-verified identity of an active run. Returns only that run's encrypted-at-rest scheduler snapshot, including the rendered prompt and harness or code context. No application scope is required. Sessions, API keys, OAuth clients, other runs and terminal runs cannot retrieve it. Responses are never cached.", + responses: { "200": { description: "Launch payload for the calling run", content: { "application/json": { schema: jsonSchema(launchPayloadResponse, "output") } } } } }, + service => service.getRuntimeLaunchPayload(), { vendorIdentityOnly: true }), route("GET", "/api/v1/runtime-context", "runs:read", { summary: "Inspect the current runtime identity and scopes", description: "Returns the verified calling identity and effective scopes without credentials. Requires a verified active identity but no application-resource scope; callers with zero scopes can inspect only their own identity. Execution provisioning uses this operation to verify the dedicated run proxy. Execution VMs must not have additional shared Factorize proxy attachments.", @@ -1279,7 +1286,7 @@ export function generateOpenApi() { description: [ route.documentation.description, route.authOperation || (Array.isArray(route.scope) && route.scope.length === 0) ? undefined : `Requires the ${Array.isArray(route.scope) ? route.scope.join(" and ") : route.scope.replaceAll("+", " and ")} scope${Array.isArray(route.scope) || route.scope.includes("+") ? "s" : ""}.`, - route.authOperation ? undefined : route.ownerSession + route.vendorIdentityOnly ? "Requires vendor-verified run identity; sessions and other bearer tokens cannot call this operation." : route.authOperation ? undefined : route.ownerSession ? "An interactive owner session is required; bearer tokens cannot call this operation." : "Accepts a scoped bearer token, vendor-verified run identity, or interactive owner session.", ] @@ -1287,7 +1294,7 @@ export function generateOpenApi() { .join("\n\n"), operationId: `${route.method.toLowerCase()}_${route.path.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_|_$/g, "")}`, tags: [route.path.split("/")[3]], - security: route.authOperation ? (route.ownerSession ? [{ cookieAuth: [] }] : []) : route.ownerSession ? [{ cookieAuth: [] }] : [{ bearerAuth: [] }, { vendorRunIdentity: [], runIdentityHeader: [] }, { cookieAuth: [] }], + security: route.vendorIdentityOnly ? [{ vendorRunIdentity: [], runIdentityHeader: [] }] : route.authOperation ? (route.ownerSession ? [{ cookieAuth: [] }] : []) : route.ownerSession ? [{ cookieAuth: [] }] : [{ bearerAuth: [] }, { vendorRunIdentity: [], runIdentityHeader: [] }, { cookieAuth: [] }], ...(route.authOperation ? { "x-browser-auth-operation": route.authOperation } : { "x-required-scope": route.scope }), "x-owner-session-required": route.ownerSession, ...(parameters.length ? { parameters } : {}), diff --git a/packages/api/src/exe-vm-backend.ts b/packages/api/src/exe-vm-backend.ts index c56b7767..7bd03544 100644 --- a/packages/api/src/exe-vm-backend.ts +++ b/packages/api/src/exe-vm-backend.ts @@ -10,6 +10,7 @@ import { runArtifactTarget } from "./run-artifact-target"; import { assertExeVmIsolation } from "./exe-vm-isolation"; import { RUN_IDENTITY_GUEST_HELPER } from "./run-identity-guest-helper"; import { FACTORIZE_JOB_LAUNCHER } from "./factorize-job-launcher"; +import { serializeLaunchPayload } from "./launch-payload"; const API = "https://exe.dev/exec"; const capabilities = ["output", "recovery", "stop"] as const; @@ -210,6 +211,7 @@ export class ExeVmBackend implements ExecutionBackend { async launch(request: LaunchRequest): Promise { const connection = this.connection as ExeRunConnection; + if (request.fetchLaunchPayload && !request.runIdentity) throw new Error("Run identity is required to fetch the launch payload"); if (!request.code && (!connection.agentKind || !request.harness)) throw new Error("The job is missing its agent harness launch plan"); if (request.traceSources) validateTraceSources(request.traceSources); const handle: RunHandle = request.reservation ?? { backendKind: this.kind, id: vmNameFor(request.runId) }; @@ -244,7 +246,7 @@ export class ExeVmBackend implements ExecutionBackend { } const code = request.code, output = request.traceSources?.primary.formatVersion === "codex-exec-jsonl" ? request.traceSources.primary.path : "/tmp/factorize.log", unit = vm; - const launchPayload = JSON.stringify({ version: 1, runId: request.runId, ...(code ? { code } : { prompt: request.prompt, harness: request.harness }), ...(request.traceSources ? { traceSources: request.traceSources } : {}) }); + const launchPayload = request.fetchLaunchPayload ? null : serializeLaunchPayload(request); const launchPayloadPath = "/home/exedev/.factorize-job/launch.json"; const identitySetup = request.runIdentity ? [ "command -v node >/dev/null && command -v curl >/dev/null", @@ -262,8 +264,8 @@ export class ExeVmBackend implements ExecutionBackend { ...(request.traceSources?.primary.kind === "execution_stream" ? [`mkdir -p -- ${shellAtom(request.traceSources.primary.path.slice(0, request.traceSources.primary.path.lastIndexOf("/")) || "/")}`, `touch -- ${shellAtom(request.traceSources.primary.path)}`] : []), "sudo install -d -o exedev -g exedev -m 0700 /home/exedev/.factorize-job", `printf '%s' ${shellAtom(base64(FACTORIZE_JOB_LAUNCHER))} | sudo sh -c ${shellAtom("base64 -d > /usr/local/bin/factorize-job && chmod 0755 /usr/local/bin/factorize-job")}`, - `printf '%s' ${shellAtom(base64(launchPayload))} | base64 -d > ${shellAtom(launchPayloadPath)} && sudo chown exedev:exedev ${shellAtom(launchPayloadPath)}`, - `if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=null --property=StandardOutput=${output === "/tmp/factorize.log" ? `append:${output}` : shellAtom(`append:${output}`)} --property=StandardError=append:/tmp/factorize.stderr /bin/sh -c ${shellAtom(`exec ${request.runIdentity ? "/usr/bin/env FACTORIZE_PROXY_URL=http://127.0.0.1:18180 " : ""}/usr/local/bin/factorize-job launch --foreground < ${launchPayloadPath}`)}; fi`, + ...(launchPayload === null ? [] : [`printf '%s' ${shellAtom(base64(launchPayload))} | base64 -d > ${shellAtom(launchPayloadPath)} && sudo chown exedev:exedev ${shellAtom(launchPayloadPath)}`]), + `if [ "$(sudo systemctl show ${shellAtom(unit)} --property=LoadState --value 2>/dev/null || true)" != loaded ]; then sudo systemd-run --quiet --uid=exedev --gid=exedev --unit=${shellAtom(unit)} --property=Type=exec --property=RemainAfterExit=yes --property=WorkingDirectory=/home/exedev/workspace --property=StandardInput=null --property=StandardOutput=${output === "/tmp/factorize.log" ? `append:${output}` : shellAtom(`append:${output}`)} --property=StandardError=append:/tmp/factorize.stderr /bin/sh -c ${shellAtom(`exec ${request.runIdentity ? "/usr/bin/env FACTORIZE_PROXY_URL=http://127.0.0.1:18180 " : ""}/usr/local/bin/factorize-job launch --foreground ${request.fetchLaunchPayload ? `--fetch-payload ${shellAtom(request.runId)}` : `< ${launchPayloadPath}`}`)}; fi`, "echo started", ].join("; "); if (request.traceSources?.primary.formatVersion === "codex-exec-jsonl") { diff --git a/packages/api/src/execution.ts b/packages/api/src/execution.ts index f721e810..9c8490f1 100644 --- a/packages/api/src/execution.ts +++ b/packages/api/src/execution.ts @@ -18,6 +18,8 @@ export interface LaunchRequest { prompt: string; /** Public backend configuration only; requests must use fresh vendor identity. */ runIdentity?: { backendOrigin: string }; + /** The exact payload has been persisted for the VM to fetch with its vendor identity. */ + fetchLaunchPayload?: boolean; traceSources?: TraceSources; harness?: { executable: string; args: string[]; env: Record }; code?: { script: string; context: Record }; diff --git a/packages/api/src/factorize-job-launcher.ts b/packages/api/src/factorize-job-launcher.ts index 4f2eed88..bdaea462 100644 --- a/packages/api/src/factorize-job-launcher.ts +++ b/packages/api/src/factorize-job-launcher.ts @@ -7,6 +7,9 @@ import re import subprocess import sys import tempfile +import time +import urllib.error +import urllib.request ROOT = pathlib.Path('/home/exedev/.factorize-job') PAYLOAD = ROOT / 'launch.json' @@ -27,8 +30,31 @@ def save(path, value): try: os.unlink(temp) except FileNotFoundError: pass -def load_payload(): - raw = sys.stdin.buffer.read(32 * 1024 * 1024 + 1) +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + +def fetch_payload(run_id): + proxy = os.environ.get('FACTORIZE_PROXY_URL', '') + if not re.fullmatch(r'http://127\.0\.0\.1:[0-9]+', proxy): + raise ValueError('launch payload requires the local identity helper') + # Never route the local helper through the image's native HTTP proxy. + opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) + for attempt in range(3): + try: + with opener.open(proxy + '/api/v1/runtime-launch', timeout=10) as response: + return response.read(32 * 1024 * 1024 + 1) + except urllib.error.HTTPError as error: + if error.code not in (408, 429, 500, 502, 503, 504): + raise RuntimeError('launch payload fetch rejected (HTTP %s)' % error.code) from None + except (urllib.error.URLError, TimeoutError, OSError): + pass + if attempt < 2: + time.sleep(attempt + 1) + raise RuntimeError('launch payload fetch failed after 3 attempts') + +def load_payload(run_id=None): + raw = fetch_payload(run_id) if run_id else sys.stdin.buffer.read(32 * 1024 * 1024 + 1) if len(raw) > 32 * 1024 * 1024: raise ValueError('launch payload exceeds 32 MiB') value = json.loads(raw) @@ -36,6 +62,8 @@ def load_payload(): raise ValueError('unsupported launch payload') if ('code' in value) == ('harness' in value): raise ValueError('launch payload must contain code or harness') + if run_id and value.get('runId') != run_id: + raise ValueError('launch payload run binding mismatch') return value def child_command(payload): @@ -69,7 +97,7 @@ def child_command(payload): env['FACTORIZE_RESULT_PATH'] = str(RESULT) return [harness['executable'], *harness['args']], str(payload.get('prompt', '')).encode(), env -def launch(foreground=False): +def launch(foreground=False, run_id=None): ROOT.mkdir(mode=0o700, parents=True, exist_ok=True) if STATE.exists(): current = json.loads(STATE.read_text()) @@ -78,7 +106,8 @@ def launch(foreground=False): try: os.kill(pid, 0) except ProcessLookupError: pass else: raise RuntimeError('a Factorize job is already active') - payload = load_payload() + save(STATE, {'state': 'starting'}) + payload = load_payload(run_id) source = payload.get('traceSources', {}).get('primary', {}) trace_path = source.get('path') if source.get('kind') == 'execution_stream' else None if trace_path: @@ -141,10 +170,13 @@ if __name__ == '__main__': try: if sys.argv[1:] == ['launch']: launch() elif sys.argv[1:] == ['launch', '--foreground']: launch(foreground=True) + elif len(sys.argv) == 5 and sys.argv[1:4] == ['launch', '--foreground', '--fetch-payload']: launch(foreground=True, run_id=sys.argv[4]) elif len(sys.argv) == 4 and sys.argv[1] == '_run': run(json.loads(sys.argv[2]), sys.argv[3]) elif sys.argv[1:] == ['status']: raise SystemExit(status()) - else: raise ValueError('usage: factorize-job launch [--foreground]|status') + else: raise ValueError('usage: factorize-job launch [--foreground [--fetch-payload RUN_ID]]|status') except Exception as error: + if sys.argv[1:2] == ['launch'] and STATE.exists() and json.loads(STATE.read_text()).get('state') == 'starting': + save(STATE, {'state': 'exited', 'exitCode': 1, 'error': str(error)[:500]}) print('factorize-job: ' + str(error)[:500], file=sys.stderr) raise SystemExit(1) `; diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 526246fd..3e53c44a 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -1,4 +1,5 @@ import { DEFAULT_RUN_SCOPES } from "./run-scopes"; +import { launchPayloadResponse } from "./launch-payload"; import { searchResponse } from "./search-contracts"; import { integrationStatus, exeConnection, accessToken, createdAccessToken, authorizedClient } from "./settings-contracts"; import { namedOption, providerOptions, githubRepository, githubInstallation, tailIntegration } from "./editor-contracts"; @@ -239,6 +240,16 @@ export class ApiService { return publicValue(runtimeContextResponse, { kind: "factorize-runtime-context-v1", authMethod: this.auth.authMethod ?? "oauth", runId: this.auth.runId ?? null, jobId: this.auth.runJobId ?? null, scopes: normalizeScopes(this.auth.scopes) }); } + async getRuntimeLaunchPayload() { + await this.authorizeIdentity(); + if (this.auth.authMethod !== "vendor_identity" || !this.auth.runId) throw new ServiceError(403, "forbidden", "A vendor-verified run identity is required."); + const encrypted = await new RunRepository(databaseFor(this.env)).activeLaunchPayload(this.auth.tenantId, this.auth.runId); + if (!encrypted) throw new ServiceError(404, "not_found", "Active launch payload unavailable."); + const payload = publicValue(launchPayloadResponse, JSON.parse(await decrypt(encrypted, this.env.CREDENTIAL_ENCRYPTION_KEY))); + if (payload.runId !== this.auth.runId) throw new ServiceError(500, "internal_error", "Invalid launch payload binding."); + return payload; + } + async listExeConnections() { await this.authorize("integrations:read"); return publicValue(z.array(exeConnection), (await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).status()).exeConnections); } async getFlyConnection() { await this.authorizeOwnerSession("integrations:read"); return { connection: await this.flyConnections().get() }; } diff --git a/packages/api/src/launch-payload.ts b/packages/api/src/launch-payload.ts new file mode 100644 index 00000000..83b3d6aa --- /dev/null +++ b/packages/api/src/launch-payload.ts @@ -0,0 +1,26 @@ +import { z } from "zod"; +import type { LaunchRequest } from "./execution"; + +export const LAUNCH_PAYLOAD_LIMIT = 32 * 1024 * 1024; +const fields = { + version: z.literal(1), + runId: z.guid(), + // The launcher validates trace paths before writing to them. + traceSources: z.record(z.string(), z.unknown()).optional(), +}; +export const launchPayloadResponse = z.union([ + z.object({ ...fields, prompt: z.string(), harness: z.object({ + executable: z.string().min(1), args: z.array(z.string()), env: z.record(z.string(), z.string()), + }).strict() }).strict(), + z.object({ ...fields, code: z.object({ script: z.string(), context: z.record(z.string(), z.unknown()) }).strict() }).strict(), +]); + +/** Snapshot exactly what the scheduler would otherwise transfer inline. */ +export function serializeLaunchPayload(request: LaunchRequest): string { + const value = JSON.stringify({ version: 1, runId: request.runId, + ...(request.code ? { code: request.code } : { prompt: request.prompt, harness: request.harness }), + ...(request.traceSources ? { traceSources: request.traceSources } : {}), + }); + if (new TextEncoder().encode(value).byteLength > LAUNCH_PAYLOAD_LIMIT) throw new Error("Launch payload exceeds 32 MiB"); + return value; +} diff --git a/packages/api/src/postgres/run-repository.ts b/packages/api/src/postgres/run-repository.ts index 541b0922..b6b2b71a 100644 --- a/packages/api/src/postgres/run-repository.ts +++ b/packages/api/src/postgres/run-repository.ts @@ -26,6 +26,20 @@ const mapped = (row: RunRow): PersistedRun => ({ tenantId: row.tenant_id, id: ro export class RunRepository { constructor(private database: Database) {} + /** The first launch owns the snapshot, including across scheduler retries. */ + async snapshotLaunchPayload(run: Pick, encrypted: string): Promise { + const result = await this.database.pool.query(`UPDATE app.runs SET encrypted_launch_payload=coalesce(encrypted_launch_payload,$3) + WHERE tenant_id=$1 AND id=$2 AND state='starting' RETURNING id`, [run.tenantId, run.id, encrypted]); + if (!result.rowCount) throw new Error("Run is no longer starting"); + } + + async activeLaunchPayload(tenantId: string, runId: string): Promise { + const result = await this.database.pool.query<{encrypted_launch_payload: string | null}>(`SELECT r.encrypted_launch_payload + FROM app.runs r JOIN app.job_runs j ON j.tenant_id=r.tenant_id AND j.id=r.id + WHERE r.tenant_id=$1 AND r.id=$2 AND r.state IN ('starting','running','blocked') AND j.state IN ('starting','running','blocked')`, [tenantId, runId]); + return result.rows[0]?.encrypted_launch_payload ?? null; + } + async claimNext(): Promise { return this.database.transaction(async client => { // Retry expired launches in their existing active slot. Requeuing them diff --git a/packages/api/src/postgres/run-scheduler.ts b/packages/api/src/postgres/run-scheduler.ts index e1f90d3f..655ce287 100644 --- a/packages/api/src/postgres/run-scheduler.ts +++ b/packages/api/src/postgres/run-scheduler.ts @@ -4,9 +4,10 @@ import { issueArtifactUploadGrant } from "../artifact-upload"; import { artifactKey } from "../artifacts"; import { ArtifactRepository } from "./artifact-repository"; import { safeDiagnosticText } from "../harness-diagnostics"; -import { decrypt } from "../crypto"; +import { decrypt, encrypt } from "../crypto"; +import { serializeLaunchPayload } from "../launch-payload"; import { ExeVmBackend } from "../exe-vm-backend"; -import type { ArtifactCollector, ExecutionBackend, ExecutionTerminator, HarnessLogReader, JobFileCollector, JobResultReader, TraceChunkCollector } from "../execution"; +import type { ArtifactCollector, ExecutionBackend, ExecutionTerminator, HarnessLogReader, JobFileCollector, JobResultReader, TraceChunkCollector, LaunchRequest } from "../execution"; import type { ExeRunConnection } from "../exe"; import type { Env } from "../types"; import { ConnectionRepository } from "./connection-repository"; @@ -182,7 +183,7 @@ export class RunScheduler { if (!context || typeof context !== "object" || Array.isArray(context)) throw new Error("The code job input context snapshot is missing"); const reservation = backend.reserve?.(run.id) ?? null; if (reservation) await this.runs.recordLaunchHandle(run, reservation); - const launched = await backend.launch({ runId: run.id, reservation: reservation ?? undefined, prompt: "", runIdentity: { backendOrigin: this.env.APP_ORIGIN }, code: { script: run.executionConfig.script, context }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); + const launched = await this.launchBackend(run, backend, { runId: run.id, reservation: reservation ?? undefined, prompt: "", runIdentity: { backendOrigin: this.env.APP_ORIGIN }, code: { script: run.executionConfig.script, context }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities); if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation); return; @@ -198,11 +199,19 @@ export class RunScheduler { const prompt = await decrypt(run.encryptedPrompt, this.env.CREDENTIAL_ENCRYPTION_KEY); const reservation = backend.reserve?.(run.id) ?? null; if (reservation) await this.runs.recordLaunchHandle(run, reservation); - const launched = await backend.launch({ runId: run.id, reservation: reservation ?? undefined, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}${runAccessInstructions({ githubInstallationIds: run.executionConfig.githubInstallationIds ?? [], linear: run.executionConfig.linearConnectionId === "linear", model: run.executionConfig.modelAccess === "portable" && Boolean(run.executionConfig.modelAccountId) })}`, runIdentity: { backendOrigin: this.env.APP_ORIGIN }, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); + const launched = await this.launchBackend(run, backend, { runId: run.id, reservation: reservation ?? undefined, prompt: `${prompt}${JOB_RESULT_INSTRUCTIONS}${runAccessInstructions({ githubInstallationIds: run.executionConfig.githubInstallationIds ?? [], linear: run.executionConfig.linearConnectionId === "linear", model: run.executionConfig.modelAccess === "portable" && Boolean(run.executionConfig.modelAccountId) })}`, runIdentity: { backendOrigin: this.env.APP_ORIGIN }, traceSources: sources, harness: { executable: harness.executable, args: harness.args, env: harness.env }, verifyVendorIdentity: this.vendorIdentityVerifier(run) }); await this.runs.markLaunched(run, launched.handle, launched.destinationUrl, launched.capabilities, sources); if (launched.observation.state === "failed") await this.runs.recordObservation(run, launched.observation); } + private async launchBackend(run: PersistedRun, backend: ExecutionBackend, request: LaunchRequest) { + if (backend.kind === "exe-vm") { + await this.runs.snapshotLaunchPayload(run, await encrypt(serializeLaunchPayload(request), this.env.CREDENTIAL_ENCRYPTION_KEY)); + request.fetchLaunchPayload = true; + } + return backend.launch(request); + } + private async poll(run: PersistedRun) { if (!run.executionHandle && run.state === "stopping") return this.runs.schedulePoll(run, "stopping"); const backend = await this.backend(run); if (!run.executionHandle) throw new Error("Execution handle is missing"); diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 62748b2e..a66e0a6c 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -82,6 +82,7 @@ export const jobRuns = app.table("job_runs", { }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.invocationId), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.invocationId], foreignColumns: [invocations.tenantId, invocations.id] }).onDelete("cascade"), index("job_runs_queue").on(t.state, t.createdAt).where(sql`${t.state}='queued'`), index("job_runs_poll_due").on(t.nextPollAt).where(sql`${t.state} in ('running','blocked','stopping')`), index("job_runs_launch_lease").on(t.launchLeaseExpiresAt).where(sql`${t.state}='starting'`), index("job_runs_by_job_history").on(t.tenantId, t.jobId, t.createdAt.desc(), t.id.desc(), t.state), index("job_runs_active_by_job").on(t.tenantId, t.jobId).where(sql`${t.state} in ('reserved','starting','running','blocked','stopping')`)]); export const runs = app.table("runs", { + encryptedLaunchPayload: text("encrypted_launch_payload"), executionConfig: jsonb("execution_config").$type().notNull(), tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), invocationId: uuid("invocation_id").notNull(), provider: text("provider").notNull(), issueId: text("issue_id").notNull(), issueUrl: text("issue_url"), issueTitle: text("issue_title").notNull().default(""), runName: text("run_name").notNull().default(""), agentName: text("agent_name").notNull(), workspaceName: text("workspace_name").notNull().default(""), agentKind: text("agent_kind").notNull().default(""), state: text("state").notNull(), executionBackendKind: text("execution_backend_kind").notNull().default(""), executionHandle: jsonb("execution_handle").$type>(), executionCapabilities: jsonb("execution_capabilities").$type().notNull().default([]), destinationUrl: text("destination_url"), artifactState: text("artifact_state").$type().notNull().default("pending"), artifactError: text("artifact_error"), failureCode: text("failure_code"), failureReason: text("failure_reason"), resultProtocolVersion: integer("result_protocol_version").notNull().default(0), jobResult: jsonb("job_result").$type(), failureSource: text("failure_source").$type<"system" | "agent">(), agentErrorReason: text("agent_error_reason"), agentErrorReportedAt: timestamp("agent_error_reported_at", { withTimezone: true }), agentErrorReporterUserId: uuid("agent_error_reporter_user_id"), agentErrorReporterKind: text("agent_error_reporter_kind"), agentErrorReporterId: text("agent_error_reporter_id"), traceSources: jsonb("trace_sources").$type(), executionDiagnostics: jsonb("execution_diagnostics").$type(), claimReleased: boolean("claim_released").notNull().default(false), vmCleanupAttempt: integer("vm_cleanup_attempt").notNull().default(0), cleanupNextAt: timestamp("cleanup_next_at", { withTimezone: true }), vmCleanupComplete: boolean("vm_cleanup_complete").notNull().default(false), providerCleanupAttempt: integer("provider_cleanup_attempt").notNull().default(0), providerCleanupNextAt: timestamp("provider_cleanup_next_at", { withTimezone: true }), providerCleanupError: text("provider_cleanup_error"), createdAt: createdAt(), updatedAt: updatedAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.invocationId), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.invocationId], foreignColumns: [invocations.tenantId, invocations.id] }).onDelete("cascade"), index("runs_order").on(t.tenantId, t.createdAt.desc(), t.id.desc()), index("runs_state_order").on(t.tenantId, t.state, t.createdAt.desc(), t.id.desc()), index("runs_priority_order").on(t.tenantId, sql`CASE WHEN ${t.state} IN ('queued','reserved','starting') THEN 0 WHEN ${t.state}='running' THEN 1 ELSE 2 END`, t.createdAt.desc(), t.id.desc()), index("runs_priority_job_order").on(t.tenantId, t.jobId, sql`CASE WHEN ${t.state} IN ('queued','reserved','starting') THEN 0 WHEN ${t.state}='running' THEN 1 ELSE 2 END`, t.createdAt.desc(), t.id.desc()), index("runs_cleanup_due").on(t.cleanupNextAt).where(sql`not ${t.vmCleanupComplete}`), index("runs_issue_trgm").using("gin", sql`${t.issueId} gin_trgm_ops`), index("runs_name_trgm").using("gin", sql`${t.runName} gin_trgm_ops`)]); diff --git a/packages/api/src/protected-api.ts b/packages/api/src/protected-api.ts index d23798ef..bd949042 100644 --- a/packages/api/src/protected-api.ts +++ b/packages/api/src/protected-api.ts @@ -66,6 +66,7 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP const { route, params } = matched; if (!["GET", "HEAD", "OPTIONS"].includes(request.method) && (route.authOperation || auth?.authMethod === "session") && !validBrowserOrigin(request, env)) throw new ServiceError(403, "invalid_origin", "Invalid request origin."); if (!route.authOperation && !auth) throw new ServiceError(401, "invalid_token", "Unauthorized"); + if (route.vendorIdentityOnly && (auth?.authMethod !== "vendor_identity" || !auth.runId)) throw new ServiceError(403, "forbidden", "A vendor-verified run identity is required."); const requiredScopes = Array.isArray(route.scope) ? route.scope : route.scope.split("+"); if (!route.authOperation && !requiredScopes.every(scope => auth!.scopes.includes(scope))) throw new ServiceError(403, "insufficient_scope", `The ${requiredScopes.join(" and ")} scope is required.`); if (!route.authOperation && route.ownerSession && auth!.authMethod !== "session") throw new ServiceError(403, "session_required", "An interactive owner session is required."); diff --git a/packages/api/test/api-boundary.test.ts b/packages/api/test/api-boundary.test.ts index be466e0e..f77019fd 100644 --- a/packages/api/test/api-boundary.test.ts +++ b/packages/api/test/api-boundary.test.ts @@ -94,6 +94,18 @@ const jobInput = { }; describe("Worker OpenAPI request/response boundaries", () => { + it("documents the run launch payload and requires vendor identity without an application scope", async () => { + const runId = "00000000-0000-4000-8000-000000000001"; + const payload = {version: 1 as const, runId, prompt: "stored prompt", harness: {executable: "codex", args: ["exec"], env: {}}}; + const get = vi.spyOn(ApiService.prototype, "getRuntimeLaunchPayload").mockResolvedValue(payload); + await assertResponse(await request("GET", "/api/v1/runtime-launch"), "GET", "/api/v1/runtime-launch", 403); + expect(get).not.toHaveBeenCalled(); + const response = await request("GET", "/api/v1/runtime-launch", undefined, {auth: {...auth, authMethod: "vendor_identity", runId, scopes: []}}); + expect(response.headers.get("Cache-Control")).toBe("no-store"); + expect(await assertResponse(response, "GET", "/api/v1/runtime-launch", 200)).toEqual(payload); + expect(openapi.paths["/api/v1/runtime-launch"].get.security).toEqual([{vendorRunIdentity: [], runIdentityHeader: []}]); + }); + it("returns a documented JSON array for a read", async () => { vi.spyOn(ApiService.prototype, "listJobs").mockResolvedValue([]); expect( diff --git a/packages/api/test/execution-backend.test.ts b/packages/api/test/execution-backend.test.ts index 45dea86a..fb197638 100644 --- a/packages/api/test/execution-backend.test.ts +++ b/packages/api/test/execution-backend.test.ts @@ -109,7 +109,7 @@ describe("ExeVmBackend", () => { expect(requests[1]).toContain("systemctl show"); }); - it("acquires a per-VM exe.dev WIF identity and verifies it before starting the job", async () => { + it.each(["codex", "claude", "pi", "code"] as const)("keeps %s startup below the exe.dev limit by fetching its large payload after identity verification", async kind => { const requests: string[] = [], token = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL2V4ZS5kZXYvaXNzdWVyL3Rlc3QifQ.c2ln"; vi.stubGlobal("fetch", vi.fn(async (_url: string, init: RequestInit) => { const command = String(init.body); requests.push(command); @@ -121,7 +121,10 @@ describe("ExeVmBackend", () => { })); const verify = vi.fn(async () => undefined); const runId = "00000000-0000-4000-8000-000000000001"; - const launched = await new ExeVmBackend(connection).launch({ runId, prompt: "work", harness: agentDriver("codex").launch(runId, {}), verifyVendorIdentity: verify, runIdentity: {backendOrigin: "https://factorize.example.com"} }); + const large = "large-payload-".repeat(100_000); + const launched = await new ExeVmBackend(connection).launch({ runId, prompt: large, + ...(kind === "code" ? {code: {script: large, context: {large}}} : {harness: agentDriver(kind).launch(runId, {})}), + fetchLaunchPayload: true, verifyVendorIdentity: verify, runIdentity: {backendOrigin: "https://factorize.example.com"} }); expect(launched.observation.state).toBe("running"); expect(requests[0]).toBe("integrations list --json"); const wif = requests.find(value => value.startsWith("integrations add wif"))!; @@ -130,6 +133,10 @@ describe("ExeVmBackend", () => { const work = requests.find(value => value.includes("sudo systemd-run"))!; expect(work).toContain("/run/factorize-identity/proxy.mjs"); expect(work).toContain("FACTORIZE_PROXY_URL=http://127.0.0.1:18180"); + expect(work).toContain("--fetch-payload"); + expect(work).not.toContain("base64 -d > '/home/exedev/.factorize-job/launch.json'"); + expect(requests.every(command => Buffer.byteLength(command) < 65_536)).toBe(true); + expect(requests.some(command => command.includes(large) || command.includes(Buffer.from(large).toString("base64")))).toBe(false); expect(launched.handle).not.toHaveProperty("runProxyName"); expect(verify).toHaveBeenCalledWith({ provider: "exe.dev", vmId: "factorize-00000000-0000-4000-8000-000000000001", token, integrationName: "fzrun-00000000000040008000000000000001", expectedIssuer: "https://exe.dev/issuer/test", expectedSubject: "sub-test" }); expect(requests.indexOf(requests.find(value => value.includes("sudo systemd-run"))!)).toBeGreaterThan(requests.indexOf(requests.find(value => value.includes("/token"))!)); diff --git a/packages/api/test/launcher-fetch.test.ts b/packages/api/test/launcher-fetch.test.ts new file mode 100644 index 00000000..3e4ca2a3 --- /dev/null +++ b/packages/api/test/launcher-fetch.test.ts @@ -0,0 +1,85 @@ +import { execFile } from "node:child_process"; +import { createServer, type Server } from "node:http"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { FACTORIZE_JOB_LAUNCHER } from "../src/factorize-job-launcher"; +import { RUN_IDENTITY_GUEST_HELPER } from "../src/run-identity-guest-helper"; + +const runId = "11111111-1111-4111-8111-111111111111"; +async function fixture(server: Server) { + const directory = await mkdtemp(join(tmpdir(), "factorize-fetch-")); + const root = join(directory, "job"), launcher = join(directory, "launcher.py"); + await mkdir(root, {mode: 0o700}); + await writeFile(launcher, FACTORIZE_JOB_LAUNCHER.replace("/home/exedev/.factorize-job", root)); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + const proxy = `http://127.0.0.1:${(server.address() as {port: number}).port}`; + return { + root, + run: () => new Promise<{error: Error | null; stdout: string; stderr: string}>(resolve => { + const child = execFile("python3", [launcher, "launch", "--foreground", "--fetch-payload", runId], { + timeout: 8_000, env: {...process.env, FACTORIZE_PROXY_URL: proxy, HTTP_PROXY: "http://invalid-proxy:1", http_proxy: "http://invalid-proxy:1", NO_PROXY: "", no_proxy: ""}, + }, (error, stdout, stderr) => resolve({error, stdout, stderr})); + child.stdin!.end(); + }), + close: async () => { + server.closeAllConnections(); + await new Promise(resolve => server.close(() => resolve())); + await rm(directory, {recursive: true, force: true}); + }, + }; +} + +describe("VM launch payload retrieval", () => { + it.each(["agent", "code"] as const)("fetches a large %s payload through the vendor identity helper and retries temporary failures", async kind => { + const helper = await import(/* @vite-ignore */ `data:text/javascript;base64,${Buffer.from(RUN_IDENTITY_GUEST_HELPER).toString("base64")}`); + const prompt = "Fetched UTF-8 prompt: 🦊\n".repeat(10_000); + const payload = {version: 1, runId, ...(kind === "agent" + ? {prompt, harness: {executable: "python3", args: ["-c", "import sys; print(len(sys.stdin.buffer.read()))"], env: {}}} + : {code: {script: "python3 -c 'import os,json; print(len(json.load(open(os.environ[\"FACTORIZE_INPUT_PATH\"]))[\"prompt\"].encode()))'", context: {prompt}}})}; + let tokens = 0, attempts = 0; + const server = helper.createRunIdentityProxy({runId, backendOrigin: "https://factorize.test", provider: "exe.dev", integrationName: "fixture"}, { + getToken: async () => `header.claims.signature${++tokens}`, + fetcher: async (url: string, init: RequestInit) => { + expect(url).toBe("https://factorize.test/api/v1/runtime-launch"); + expect((init.headers as Headers).get("X-Factorize-Run-Id")).toBe(runId); + expect((init.headers as Headers).get("Authorization")).toBe(`Bearer header.claims.signature${tokens}`); + return ++attempts === 1 ? new Response("temporary", {status: 503}) : Response.json(payload); + }, + }); + const f = await fixture(server); + try { + const result = await f.run(); + expect(result.stderr).toBe(""); + expect(result.error).toBeNull(); + expect(result.stdout.trim()).toBe(String(Buffer.byteLength(prompt))); + expect(tokens).toBe(2); + expect(JSON.parse(await readFile(join(f.root, "process.json"), "utf8"))).toEqual({state: "exited", exitCode: 0}); + if (kind === "agent") expect(await readFile(join(f.root, "prompt.txt"), "utf8")).toBe(prompt); + } finally { await f.close(); } + }); + + it.each(["denied", "redirect", "wrong-run", "malformed", "oversize", "unavailable"])("does not launch the harness for a %s response", async mode => { + let requests = 0; + const server = createServer((_request, response) => { + requests++; + if (mode === "denied") response.writeHead(403).end("private-backend-error"); + else if (mode === "redirect") response.writeHead(302, {Location: "/unexpected"}).end(); + else if (mode === "unavailable") response.writeHead(503).end("private-backend-error"); + else if (mode === "oversize") response.end(" ".repeat(32 * 1024 * 1024 + 1)); + else if (mode === "malformed") response.end("{}"); + else response.end(JSON.stringify({version: 1, runId: "other-run", prompt: "secret prompt", harness: {executable: "touch", args: ["should-not-run"], env: {}}})); + }); + const f = await fixture(server); + try { + const result = await f.run(); + expect(result.error).not.toBeNull(); + expect(result.stderr).toContain("factorize-job:"); + expect(result.stderr).not.toMatch(/private-backend-error|secret prompt/); + expect(requests).toBe(mode === "unavailable" ? 3 : 1); + expect(JSON.parse(await readFile(join(f.root, "process.json"), "utf8"))).toMatchObject({state: "exited", exitCode: 1}); + await expect(readFile(join(f.root, "prompt.txt"))).rejects.toThrow(); + } finally { await f.close(); } + }); +}); diff --git a/packages/api/test/run-vendor-launch.test.ts b/packages/api/test/run-vendor-launch.test.ts index ec60def6..bd538d73 100644 --- a/packages/api/test/run-vendor-launch.test.ts +++ b/packages/api/test/run-vendor-launch.test.ts @@ -2,7 +2,8 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { RunScheduler } from "../src/postgres/run-scheduler"; import { RunRepository } from "../src/postgres/run-repository"; import { ExeVmBackend } from "../src/exe-vm-backend"; -import { encrypt } from "../src/crypto"; +import { decrypt, encrypt } from "../src/crypto"; +import { serializeLaunchPayload } from "../src/launch-payload"; import { RunCredentialRepairRequired } from "../src/run-credential-launch"; @@ -38,9 +39,13 @@ describe("vendor-authenticated run launch", () => { vi.spyOn(scheduler, "backend").mockResolvedValue(backend); const launch = vi.spyOn(backend, "launch").mockResolvedValue({ handle: { backendKind: "exe-vm", id: "factorize-run" }, observation: { state: "running" }, capabilities: [], destinationUrl: "https://vm.test" }); vi.spyOn(RunRepository.prototype, "markLaunched").mockResolvedValue(); + const snapshot = vi.spyOn(RunRepository.prototype, "snapshotLaunchPayload").mockResolvedValue(); const recordHandle = vi.spyOn(RunRepository.prototype, "recordLaunchHandle").mockResolvedValue(); await scheduler.launch({ id: runId, tenantId: "tenant", executionConfig: { agentKind, runScopes: ["jobs:read", "jobs:write"], ...(agentKind === "code" ? { executionType: "code", script: "echo test", inputContext: {} } : {}) }, encryptedPrompt: await encrypt("Complete the task", key) }); const request = launch.mock.calls[0][0]; + expect(snapshot.mock.invocationCallOrder[0]).toBeLessThan(launch.mock.invocationCallOrder[0]); + expect(await decrypt(snapshot.mock.calls[0][1], key)).toBe(serializeLaunchPayload(request)); + expect(request.fetchLaunchPayload).toBe(true); expect(recordHandle.mock.invocationCallOrder[0]).toBeLessThan(launch.mock.invocationCallOrder[0]); expect(request).not.toHaveProperty("runProxy"); expect(request.runIdentity).toEqual({backendOrigin: env.APP_ORIGIN}); diff --git a/packages/api/test/vendor-run-auth.postgres.test.ts b/packages/api/test/vendor-run-auth.postgres.test.ts index 995307cb..589bf141 100644 --- a/packages/api/test/vendor-run-auth.postgres.test.ts +++ b/packages/api/test/vendor-run-auth.postgres.test.ts @@ -10,6 +10,9 @@ import { CredentialRepository } from "../src/postgres/credential-repository"; import { GitHubRepository } from "../src/postgres/github-repository"; import { ConnectionRepository } from "../src/postgres/connection-repository"; import worker from "../src/worker"; +import { RunRepository } from "../src/postgres/run-repository"; +import { decrypt, encrypt } from "../src/crypto"; +import { protectedApiFetch } from "../src/protected-api"; vi.mock("cloudflare:workers", () => ({ WorkerEntrypoint: class {}, DurableObject: class {} })); vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); @@ -38,6 +41,7 @@ describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker beforeEach(async () => { const now = Math.floor(Date.now() / 1000); await f.db.pool.query("UPDATE app.job_runs SET state='running' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); + await f.db.pool.query("UPDATE app.runs SET encrypted_launch_payload=NULL WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); await f.db.pool.query("UPDATE app.runs SET state='running',execution_handle=$3,execution_config=$4 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, {backendKind: "fly", id: `run-app/${machineId}`}, {executionProvider: "fly", connectionId: "config", runScopes: ["runs:read"]}]); await new FlyConnectionRepository(f.db, f.tenantId, f.env.CREDENTIAL_ENCRYPTION_KEY).save({organizationSlug: "connected-org", organizationName: "A different display name"}, "fixture-token"); await f.db.pool.query("DELETE FROM app.vendor_run_identity_bindings WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); @@ -80,6 +84,57 @@ describe.skipIf(!url)("vendor identity request admission (PostgreSQL and Worker expect((await worker.fetch(request("invalid", f.runId, undefined, {Cookie: f.cookie}), f.env, {waitUntil() {}} as any)).status).toBe(401); }); + it.each(["agent", "code"] as const)("serves an encrypted immutable %s launch snapshot only to its own active VM, even with zero API scopes", async kind => { + const repository = new RunRepository(f.db); + const run = {tenantId: f.tenantId, id: f.runId}; + const prompt = "Exact snapshot 🦊\n".repeat(10_000); + const payload = {version: 1, runId: f.runId, ...(kind === "agent" + ? {prompt, harness: {executable: "codex", args: ["exec", "--json"], env: {}}} + : {code: {script: "echo snapshot", context: {prompt}}})}; + await f.db.pool.query("UPDATE app.runs SET state='starting' WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId]); + await repository.snapshotLaunchPayload(run, await encrypt(JSON.stringify(payload), f.env.CREDENTIAL_ENCRYPTION_KEY)); + await repository.snapshotLaunchPayload(run, await encrypt(JSON.stringify({...payload, runId: "replacement"}), f.env.CREDENTIAL_ENCRYPTION_KEY)); + const stored = (await f.db.pool.query("SELECT encrypted_launch_payload FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId])).rows[0].encrypted_launch_payload; + expect(stored).not.toContain("Exact snapshot"); + expect(JSON.parse(await decrypt(stored, f.env.CREDENTIAL_ENCRYPTION_KEY))).toEqual(payload); + expect(await repository.activeLaunchPayload(f.otherTenant, f.runId)).toBeNull(); + // Subsequent job/prompt edits cannot change the launch snapshot. + await f.db.pool.query("UPDATE app.job_runs SET encrypted_prompt=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, await encrypt("changed prompt", f.env.CREDENTIAL_ENCRYPTION_KEY)]); + await f.db.pool.query("UPDATE app.run_authorizations SET scopes='[]' WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); + const ctx = {waitUntil() {}} as any; + const call = (token = jwt, id = f.runId) => worker.fetch(request(token, id, "/api/v1/runtime-launch"), f.env, ctx); + for (const state of ["starting", "running", "blocked"]) { + await f.db.pool.query("UPDATE app.job_runs SET state=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, state]); + await f.db.pool.query("UPDATE app.runs SET state=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, state]); + const response = await call(); + expect(response.status).toBe(200); + expect(response.headers.get("Cache-Control")).toBe("no-store"); + expect(await response.json()).toEqual(payload); + } + expect((await f.request("/api/v1/runtime-launch")).status).toBe(403); + for (const authMethod of ["session", "access_token", "oauth"] as const) { + const response = await protectedApiFetch(new Request(f.env.APP_ORIGIN + "/api/v1/runtime-launch"), f.env, {...f.auth, authMethod}, ctx); + expect(response.status).toBe(403); + } + for (const token of [await sign({aud: "other-run"}), await sign({machine_id: "foreign-vm"})]) expect((await call(token)).status).toBe(401); + expect((await call(jwt, crypto.randomUUID())).status).toBe(401); + for (const state of ["stopping", "stopped", "failed", "succeeded"]) { + await f.db.pool.query("UPDATE app.job_runs SET state=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, state]); + expect((await call()).status).toBe(401); + } + }); + + it("does not fall back to an inline or different-run payload when the snapshot is unavailable or misbound", async () => { + const ctx = {waitUntil() {}} as any; + const call = () => worker.fetch(request(jwt, f.runId, "/api/v1/runtime-launch"), f.env, ctx); + expect((await call()).status).toBe(404); + await f.db.pool.query("UPDATE app.runs SET encrypted_launch_payload=$3 WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId, + await encrypt(JSON.stringify({version: 1, runId: crypto.randomUUID(), prompt: "other-run-prompt", harness: {executable: "codex", args: [], env: {}}}), f.env.CREDENTIAL_ENCRYPTION_KEY)]); + const response = await call(); + expect(response.status).toBe(500); + expect(await response.text()).not.toContain("other-run-prompt"); + }); + it("requires explicit destination permission and prevents a run from granting itself permission", async () => { await f.db.pool.query("UPDATE app.run_authorizations SET scopes='[\"runs:invoke\",\"jobs:write\"]' WHERE tenant_id=$1 AND run_id=$2", [f.tenantId, f.runId]); const invoke = () => worker.fetch(new Request(request(jwt, f.runId, `/api/v1/jobs/${f.jobIds[1]}/invocations`), { diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 0d2ed1b3..7fb18306 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -10467,6 +10467,120 @@ paths: application/json: schema: $ref: "#/components/schemas/ManualInvocation" + /api/v1/runtime-launch: + get: + summary: Fetch this VM's immutable launch payload + description: |- + Requires the vendor-verified identity of an active run. Returns only that run's encrypted-at-rest scheduler snapshot, including the rendered prompt and harness or code context. No application scope is required. Sessions, API keys, OAuth clients, other runs and terminal runs cannot retrieve it. Responses are never cached. + + Requires vendor-verified run identity; sessions and other bearer tokens cannot call this operation. + responses: + "200": + description: Launch payload for the calling run + content: + application/json: + schema: + anyOf: + - type: object + properties: + version: + type: number + const: 1 + runId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + traceSources: + type: object + propertyNames: + type: string + additionalProperties: {} + prompt: + type: string + harness: + type: object + properties: + executable: + type: string + minLength: 1 + args: + type: array + items: + type: string + env: + type: object + propertyNames: + type: string + additionalProperties: + type: string + required: + - executable + - args + - env + additionalProperties: false + required: + - version + - runId + - prompt + - harness + additionalProperties: false + - type: object + properties: + version: + type: number + const: 1 + runId: + type: string + format: uuid + pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + traceSources: + type: object + propertyNames: + type: string + additionalProperties: {} + code: + type: object + properties: + script: + type: string + context: + type: object + propertyNames: + type: string + additionalProperties: {} + required: + - script + - context + additionalProperties: false + required: + - version + - runId + - code + additionalProperties: false + "400": + $ref: "#/components/responses/Error400" + "401": + $ref: "#/components/responses/Error401" + "403": + $ref: "#/components/responses/Error403" + "404": + $ref: "#/components/responses/Error404" + "409": + $ref: "#/components/responses/Error409" + "429": + $ref: "#/components/responses/Error429" + "500": + $ref: "#/components/responses/Error500" + "503": + $ref: "#/components/responses/Error503" + operationId: get_api_v1_runtime_launch + tags: + - runtime-launch + security: + - vendorRunIdentity: [] + runIdentityHeader: [] + x-required-scope: [] + x-owner-session-required: false /api/v1/runtime-context: get: summary: Inspect the current runtime identity and scopes