From c62becb222cff134ad797d3a008cec4f0b949e4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?T=C3=B3mas=20P=C3=A1lsson?= <46539820+TomasPalsson@users.noreply.github.com> Date: Tue, 1 Dec 2026 09:37:03 +0000 Subject: [PATCH 1/2] feat: read-only remote mounts (SharePoint / Google Drive) for caller-supplied folders (port of #17 to v1.11.0) --- api/src/api/v2-remote-mounts.test.ts | 112 +++ api/src/api/v2.ts | 15 + api/src/execution-manifest-request.test.ts | 73 ++ api/src/execution-manifest-request.ts | 14 +- api/src/index.ts | 5 + api/src/job.ts | 159 +++- api/src/nsjail.ts | 29 +- api/src/remote-mounts-hook.test.ts | 202 ++++ api/src/remote-mounts-job.test.ts | 271 ++++++ api/src/remote-mounts.test.ts | 860 ++++++++++++++++++ api/src/remote-mounts.ts | 801 ++++++++++++++++ docs/remote-mounts/README.md | 113 +++ service/openapi.yml | 86 ++ service/src/egress-grant.test.ts | 48 + service/src/egress-grant.ts | 45 +- service/src/execution-manifest-claims.ts | 4 +- service/src/execution-manifest.test.ts | 43 + service/src/payload.test.ts | 81 ++ service/src/payload.ts | 13 +- .../runtime-session/input-delivery.test.ts | 42 + service/src/runtime-session/input-delivery.ts | 49 +- .../sandbox-backend/lambda-microvm.test.ts | 20 + service/src/sandbox-backend/lambda-microvm.ts | 3 +- service/src/service/programmatic-router.ts | 7 + service/src/service/remote-mounts.test.ts | 330 +++++++ service/src/service/remote-mounts.ts | 268 ++++++ service/src/service/router.ts | 28 +- service/src/types/service.ts | 20 + service/src/workers.ts | 7 +- 29 files changed, 3702 insertions(+), 46 deletions(-) create mode 100644 api/src/api/v2-remote-mounts.test.ts create mode 100644 api/src/remote-mounts-hook.test.ts create mode 100644 api/src/remote-mounts-job.test.ts create mode 100644 api/src/remote-mounts.test.ts create mode 100644 api/src/remote-mounts.ts create mode 100644 docs/remote-mounts/README.md create mode 100644 service/src/payload.test.ts create mode 100644 service/src/service/remote-mounts.test.ts create mode 100644 service/src/service/remote-mounts.ts diff --git a/api/src/api/v2-remote-mounts.test.ts b/api/src/api/v2-remote-mounts.test.ts new file mode 100644 index 00000000..ea9654d0 --- /dev/null +++ b/api/src/api/v2-remote-mounts.test.ts @@ -0,0 +1,112 @@ +import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import express from 'express'; +import * as fsp from 'fs/promises'; +import type { Server } from 'http'; +import * as os from 'os'; +import * as path from 'path'; +import { loadPackage } from '../runtime'; +import v2Router from './v2'; + +let server: Server; +let baseUrl: string; +let packageDir: string; +const language = 'remote-mounts-route'; + +beforeAll(async () => { + packageDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'rm-route-runtime-')); + await fsp.writeFile( + path.join(packageDir, 'pkg-info.json'), + JSON.stringify({ language, version: '1.0.0', aliases: [] }), + ); + loadPackage(packageDir); + const app = express(); + app.use('/api/v2', v2Router); + await new Promise(resolve => { + server = app.listen(0, '127.0.0.1', () => resolve()); + }); + const address = server.address(); + baseUrl = `http://127.0.0.1:${typeof address === 'object' && address ? address.port : 0}`; +}); + +afterAll(async () => { + await new Promise(resolve => server.close(() => resolve())); + await fsp.rm(packageDir, { recursive: true, force: true }); +}); + +const post = (remote_mounts: unknown) => + fetch(`${baseUrl}/api/v2/execute`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + language, + version: '1.0.0', + files: [{ name: 'main.txt', content: 'x' }], + remote_mounts, + }), + }); + +describe('POST /execute remote_mounts validation', () => { + test('rejects /mnt/data with 400 invalid_remote_mounts before enqueue', async () => { + const response = await post([{ path: '/mnt/data', entries: [] }]); + expect(response.status).toBe(400); + const body = (await response.json()) as { + error: string; + message: string; + }; + expect(body.error).toBe('invalid_remote_mounts'); + expect(body.message).toContain('/mnt/data'); + }); + + test('rejects a traversal entry path with 400', async () => { + const response = await post([ + { path: '/mnt/drive', entries: [{ path: '../x', type: 'file' }] }, + ]); + expect(response.status).toBe(400); + expect(((await response.json()) as { error: string }).error).toBe( + 'invalid_remote_mounts', + ); + }); +}); + +describe('POST /execute remote_mounts limits and null', () => { + const loaded = (n: number) => [{ + path: '/mnt/drive', + entries: Array.from({ length: n }, (_, i) => ({ + path: `f${i}.txt`, type: 'file', + file: { id: `m${i}`, storage_session_id: 's' }, + })), + }]; + const postFiles = (refs: number, remote_mounts: unknown) => + fetch(`${baseUrl}/api/v2/execute`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + language, version: '1.0.0', remote_mounts, + files: [ + { name: 'main.txt', content: 'x' }, + ...Array.from({ length: refs }, (_, i) => ({ id: `r${i}`, storage_session_id: 's', name: `r${i}.txt` })), + ], + }), + }); + + test('the injected source file does not count: 192 refs + 64 loaded = 256 is not rejected for remote_mounts', async () => { + const response = await postFiles(192, loaded(64)); + const body = (await response.json().catch(() => ({}))) as { error?: string }; + expect(body.error).not.toBe('invalid_remote_mounts'); + }, 20_000); + + test('193 refs + 64 loaded = 257 is rejected with invalid_remote_mounts', async () => { + const response = await postFiles(193, loaded(64)); + expect(response.status).toBe(400); + expect(((await response.json()) as { error: string }).error).toBe('invalid_remote_mounts'); + }); + + test('remote_mounts: null is treated as absent, [] stays a 400', async () => { + const nullResponse = await post(null); + const nullBody = (await nullResponse.json().catch(() => ({}))) as { error?: string }; + expect(nullBody.error).not.toBe('invalid_remote_mounts'); + const empty = await post([]); + expect(empty.status).toBe(400); + expect(((await empty.json()) as { error: string }).error).toBe('invalid_remote_mounts'); + }, 20_000); +}); diff --git a/api/src/api/v2.ts b/api/src/api/v2.ts index 4fc3a9c9..06cd6407 100644 --- a/api/src/api/v2.ts +++ b/api/src/api/v2.ts @@ -19,6 +19,7 @@ import { activeSandboxExecutions, recordSandboxExecution } from '../metrics'; import { classifySandboxSafeError } from '../safe-error'; import { withSpan } from '../telemetry'; import { checkSandboxWorkspaceHealth } from '../workspace-isolation'; +import { RemoteMountsError, validateRemoteMounts, type RemoteMount } from '../remote-mounts'; import type { SessionWorkspace } from '../session-workspace'; import { RUNTIME_SESSION_ID_HEADER, @@ -198,6 +199,7 @@ export interface ExecuteRequestBody { egress_grant?: string; execution_manifest?: string; tool_call_socket?: boolean; + remote_mounts?: unknown; } export const ENV_VAR_KEY_RE = /^[A-Z_][A-Z0-9_]*$/i; @@ -316,6 +318,18 @@ function getJob( validateExecuteArguments(args, stdin); files = deduplicateFilesByDestination(files); validateExecuteFiles(files); + let remoteMounts: RemoteMount[] | undefined; + if (body.remote_mounts != null) { + try { + remoteMounts = validateRemoteMounts(body.remote_mounts, { + /* refs only: the injected source file (inline content) is not an input. */ + inputFileCount: files.filter(file => file.id != null).length, + maxInputFiles: config.max_input_files, + }); + } catch (error) { + throw error instanceof RemoteMountsError ? { code: error.code, message: error.message } : error; + } + } const rt = getLatestRuntimeMatchingLanguageVersion(language, version); if (!rt) { @@ -395,6 +409,7 @@ function getJob( tool_call_socket_enabled: toolCallSocketEnabled, is_synthetic: isSynthetic, session, + ...(remoteMounts ? { remote_mounts: remoteMounts } : {}), }); } diff --git a/api/src/execution-manifest-request.test.ts b/api/src/execution-manifest-request.test.ts index 4e7c92b1..1d5b453b 100644 --- a/api/src/execution-manifest-request.test.ts +++ b/api/src/execution-manifest-request.test.ts @@ -366,3 +366,76 @@ describe('execute request manifest validation', () => { }), 'malformed'); }); }); + +describe('remote_mounts loaded refs in the manifest (cross-half: service collector vs runner check)', () => { + const mountRef = { id: 'drive_1', storage_session_id: 'sess_drive', name: 'a.csv' }; + const mountBody = { + language: 'python', + version: '3.12', + session_id: 'sess_output', + files: [{ name: 'main.py', content: 'x' }], + remote_mounts: [{ + path: '/mnt/google-drive', + entries: [ + { path: 'a.csv', type: 'file', file: mountRef }, + { path: 'stub.docx', type: 'file' }, + ], + }], + }; + + function serviceClaims(payload: typeof mountBody, extra: Partial = {}): ExecutionManifestClaims { + // Pinned from service/src/execution-manifest-claims.ts collectManifestInputFiles (mirrored in + // service/src/execution-manifest.test.ts): a loaded mount ref becomes { id, session_id, name }. + const input_files = payload.remote_mounts + ? [{ id: 'drive_1', session_id: 'sess_drive', name: 'a.csv' }] + : []; + return claims({ + input_files, + read_sessions: [...new Set(input_files.map(file => file.session_id))], + output_session_id: 'sess_output', + execute_body_sha256: executionManifestBodySha256(payload), + ...extra, + }); + } + + test('accepts a body whose loaded mount ref is in the service-built manifest', () => { + const token = signExecutionManifest(serviceClaims(mountBody), SECRET); + expect(() => verifyExecuteRequestManifest({ + headerValue: token, secret: SECRET, body: mountBody, nowSeconds: 150, + })).not.toThrow(); + }); + + test('rejects a mount ref that is not in the manifest', () => { + const { remote_mounts: _unused, ...withoutMounts } = mountBody; + const token = signExecutionManifest(serviceClaims(withoutMounts as typeof mountBody), SECRET); + expectManifestError(() => verifyExecuteRequestManifest({ + headerValue: token, secret: SECRET, body: mountBody, nowSeconds: 150, + }), 'scope_mismatch'); + }); + + test('rejects an extra manifest file when the body has no mount refs', () => { + const token = signExecutionManifest(serviceClaims(mountBody), SECRET); + const { remote_mounts: _unused, ...withoutMounts } = mountBody; + expectManifestError(() => verifyExecuteRequestManifest({ + headerValue: token, secret: SECRET, body: withoutMounts, nowSeconds: 150, + }), 'scope_mismatch'); + }); + + test('never admits a mount ref input_cache_key through the legacy no-body-hash grace', () => { + const cachedBody = { + ...mountBody, + remote_mounts: [{ + path: '/mnt/google-drive', + entries: [{ path: 'a.csv', type: 'file', file: { ...mountRef, input_cache_key: 'a'.repeat(64) } }], + }], + }; + const legacy = { ...serviceClaims(cachedBody as never), execute_body_sha256: undefined }; + expectManifestError(() => verifyExecuteRequestManifest({ + headerValue: signExecutionManifest(legacy, SECRET), + secret: SECRET, + body: cachedBody, + nowSeconds: 150, + bodyHashRequiredAfterSeconds: 200, + }), 'scope_mismatch'); + }); +}); diff --git a/api/src/execution-manifest-request.ts b/api/src/execution-manifest-request.ts index 08b65b03..4cb2e79c 100644 --- a/api/src/execution-manifest-request.ts +++ b/api/src/execution-manifest-request.ts @@ -12,6 +12,7 @@ interface ExecuteRequestBody { session_id?: string; output_session_id?: string; files?: TFile[]; + remote_mounts?: unknown; } interface PayloadFileRef { @@ -29,6 +30,15 @@ function isPayloadFileRef(file: unknown): file is PayloadFileRef { ); } +/* Loaded remote_mounts[].entries[].file refs, in the shape the service signs + * (service/src/service/remote-mounts.ts payloadRemoteMountFiles). */ +function bodyMountFiles(body: ExecuteRequestBody): unknown[] { + if (!Array.isArray(body.remote_mounts)) return []; + return body.remote_mounts.flatMap((mount: { entries?: Array<{ file?: unknown }> } | null) => ( + Array.isArray(mount?.entries) ? mount.entries.flatMap(entry => (entry?.file ? [entry.file] : [])) : [] + )); +} + function fileKey(file: ExecutionManifestInputFile): string { return `${file.session_id}\0${file.id}\0${file.name}`; } @@ -52,7 +62,7 @@ function assertManifestBodyHashMatches( * from the coarse input-file claim tuple. It is therefore safe only when * the whole execute body is signed; never admit it through the rolling * legacy no-body-hash grace. */ - const hasInputCacheSelector = Array.isArray(body.files) && body.files.some( + const hasInputCacheSelector = [...(Array.isArray(body.files) ? body.files : []), ...bodyMountFiles(body)].some( file => file != null && typeof file === 'object' && typeof (file as TFile).input_cache_key === 'string', @@ -81,7 +91,7 @@ function assertManifestBodyHashMatches( } export function collectExecuteRequestInputFiles(body: ExecuteRequestBody): ExecutionManifestInputFile[] { - const files = Array.isArray(body.files) ? body.files : []; + const files = [...(Array.isArray(body.files) ? body.files : []), ...bodyMountFiles(body)]; return files .map((file, index) => { if (!isPayloadFileRef(file)) return null; diff --git a/api/src/index.ts b/api/src/index.ts index cc6da827..9d7b3dc6 100644 --- a/api/src/index.ts +++ b/api/src/index.ts @@ -4,6 +4,7 @@ import { logger } from './logger'; import { config } from './config'; import { validateHardenedSandboxStartup } from './secure-startup'; import { initializeSandboxWorkspaceIsolation, startWorkspaceReaper } from './workspace-isolation'; +import { sweepRemoteMountTrees } from './remote-mounts'; import { httpMetricsMiddleware, metricsHandler } from './metrics'; import { positiveInt, shutdownTelemetry, traceHttpRequest } from './telemetry'; import { startWarmupCommand } from './warmup'; @@ -72,6 +73,10 @@ async function main(): Promise { validateHostedAppStartup(); validateHardenedSandboxStartup(); await initializeSandboxWorkspaceIsolation(); + /* Trees of a runner that died mid-job; a fresh runner has no job using them. */ + await sweepRemoteMountTrees() + .then(removed => { if (removed > 0) logger.info({ removed }, 'Removed leftover remote mount trees'); }) + .catch(err => logger.warn({ err }, 'Remote mount tree sweep failed')); await startWarmupCommand(); const [address, port] = config.bind_address.split(':'); diff --git a/api/src/job.ts b/api/src/job.ts index 88d3e5b4..2ce44d28 100644 --- a/api/src/job.ts +++ b/api/src/job.ts @@ -45,6 +45,19 @@ import { } from './validation'; import { fetchCachedHttpInput } from './http-input-cache'; import { cachedInputResponse, inputCacheKey, openCachedInput } from './session-inputs'; +import { + REMOTE_MOUNTS_ENV, + REMOTE_MOUNTS_HOOK_DST, + REMOTE_MOUNTS_NONCE_ENV, + extractRemoteMountsRequired, + findRemoteMountChanges, + materializeRemoteMounts, + removeRemoteMounts, + stubPaths, + type MaterializedRemoteMounts, + type RemoteMount, + type RemoteMountFile, +} from './remote-mounts'; export { DIRKEEP, @@ -596,6 +609,8 @@ interface FileRef { /** Per-file storage session id (where the bytes live). */ storage_session_id: string; modified_from?: { id: string; storage_session_id: string }; + /** Only on outputs copied out of a remote_mounts tree (copy-on-write). */ + remote_mount?: { path: string; change: 'modified' | 'created' }; /** * `true` when this ref is an unchanged passthrough of an input the caller * already owns (downloaded inputs, inherited `.dirkeep` markers). Surfaced @@ -616,6 +631,8 @@ interface GeneratedFile { id: string; name: string; path: string; + /** Remote-mount outputs only: the verified fd (openMountFile); read from it, never re-open `path`. */ + handle?: fsp.FileHandle; } interface InputFileInfo { @@ -663,6 +680,8 @@ interface ExecuteResult { deleted_files?: string[]; artifact_delivery?: ArtifactDeliveryFailure; artifact_truncation?: ArtifactTruncation; + /** Stubs of this request's remote_mounts that sandboxed Python tried to read. */ + remote_mounts_required?: { read: string[] }; } export type ArtifactTruncationReason = 'max_files' | 'depth' | 'size' | 'path' | 'unreadable'; @@ -732,6 +751,11 @@ export class Job { private inputDestinations = new Map(); private entryPointName: string | undefined; private chmoddedDirs = new Set(); + /* remote_mounts (opt-in): declared trees, the runner-owned dir they are built + * in (outside the workspace), and the per-job nonce of the stderr report. */ + private readonly remoteMounts: RemoteMount[] | undefined; + private readonly remoteMountsNonce: string; + private remoteMountsState: MaterializedRemoteMounts | undefined; /* Persistent session workspace (stateful mode). When set, the job reuses * one long-lived workspace + pinned UID across calls instead of a fresh * per-job workspace; undefined = legacy fresh-per-job path (unchanged). */ @@ -756,7 +780,11 @@ export class Job { is_synthetic?: boolean; /* Injected when this VM is bound to a stateful runtime session. */ session?: SessionWorkspace | null; + remote_mounts?: RemoteMount[]; }) { + this.remoteMounts = opts.remote_mounts; + /* Only requests with mounts pay for (or carry) a nonce. */ + this.remoteMountsNonce = opts.remote_mounts ? crypto.randomBytes(16).toString('hex') : ''; this.session = opts.session ?? undefined; this.uuid = opts.session_id ?? nanoid(); this.outputSessionId = opts.output_session_id ?? this.uuid; @@ -1029,6 +1057,28 @@ export class Job { fileOps.push(() => runFileOperation(() => this.writeFile(file, operationContext))); } } + /* Mount trees are built in the same batch: the prime abort signal reaches + * their fetches, and a failure elsewhere cancels them. */ + if (this.remoteMounts) { + const remoteMounts = this.remoteMounts; + fileOps.push(() => runFileOperation(async () => { + this.remoteMountsState = await materializeRemoteMounts( + remoteMounts, + (file, signal) => this.fetchMountObject(file, signal), + config.max_file_size, + controller.signal, + // ponytail: this op holds one prime slot, so the inner pool gets the rest + Math.max(1, config.prime_concurrency - 1), + (target, type) => + applySandboxPathPermissionsNoFollow( + target, + this.sandboxIdentity(), + type === 'file' ? SANDBOX_FILE_MODE : SANDBOX_DIR_MODE, + type, + ), + ); + })); + } let nextOperation = 0; const runPrimeWorker = async (): Promise => { while (!controller.signal.aborted) { @@ -1505,6 +1555,26 @@ export class Job { }); } + /** Fetches one remote-mount object through the same path as files[] refs. */ + private async fetchMountObject(file: RemoteMountFile, signal?: AbortSignal): Promise { + const ref: TFile = { + id: file.id, + storage_session_id: file.storage_session_id, + input_cache_key: file.input_cache_key, + name: file.name ?? file.id, + }; + for (let attempt = 1; ; attempt++) { + const response = await this.fetchInputObject(ref, signal); + if (response.ok) return response; + await response.body?.cancel().catch(() => {}); + if (response.status === 401 || (response.status === 403 && !this.isLegacyGatewayDenial(response))) { + throw new InputAuthorizationError(response.status); + } + if (attempt >= 5) throw new Error(`HTTP error: ${response.status}`); + await sleep(500 * 2 ** (attempt - 1), signal); + } + } + private inputIdentity(file: TFile): string { return file.input_cache_key ?? inputCacheKey(file.storage_session_id ?? '', file.id ?? ''); } @@ -1629,6 +1699,12 @@ export class Job { HOME: '/mnt/data', }; + if (this.remoteMountsState) { + envVars.PYTHONPATH = [envVars.PYTHONPATH, REMOTE_MOUNTS_HOOK_DST].filter(Boolean).join(':'); + envVars[REMOTE_MOUNTS_ENV] = JSON.stringify(this.remoteMountsState.mountPaths); + envVars[REMOTE_MOUNTS_NONCE_ENV] = this.remoteMountsNonce; + } + let extraPkgdirs: string[] | undefined; if (this.runtime.language === 'bash') { const linkTarget: { nodeModulesPath?: string } = {}; @@ -1649,9 +1725,24 @@ export class Job { identity: this.sandboxIdentity(), enableToolCallPipes: this.toolCallPipesEnabled && script === 'run', suppressSuccessLogs: this.isSynthetic, + ...(this.remoteMountsState ? { extraBinds: this.remoteMountsState.binds } : {}), }); } + /** Strips this job's report blocks from the results; returns the stubs hit. */ + private collectRemoteMountsRequired(results: Array): string[] { + if (!this.remoteMounts) return []; + const stubs = stubPaths(this.remoteMounts); + const read = new Set(); + for (const result of results) { + if (!result) continue; + const extracted = extractRemoteMountsRequired([result.stderr, result.output], this.remoteMountsNonce, stubs); + [result.stderr, result.output] = extracted.texts; + for (const p of extracted.read) read.add(p); + } + return [...read].slice(0, 64); + } + async execute(): Promise { if (!this.isSynthetic) { this.log.info({ runtime: this.runtime.language, version: this.runtime.version.raw }, 'Executing'); @@ -1700,6 +1791,8 @@ export class Job { await this.handleSessionFiles(); + const remoteMountsRead = this.collectRemoteMountsRequired([compile, run]); + return { compile, run, @@ -1711,6 +1804,7 @@ export class Job { ? { deleted_files: this.deletedFiles } : {}), ...(this.artifactTruncation ? { artifact_truncation: this.artifactTruncation } : {}), + ...(remoteMountsRead.length > 0 ? { remote_mounts_required: { read: remoteMountsRead } } : {}), }; } @@ -1755,6 +1849,8 @@ export class Job { } } + await this.collectRemoteMountOutputs(); + /* Generated files get priority in sessionFiles; fill remaining slots up * to max_output_files with inherited refs (unchanged downloaded inputs * and unchanged inherited .dirkeep markers). This bounds the response @@ -1769,6 +1865,55 @@ export class Job { } } + /** Copy-on-write: modified loaded files and new files under a remote mount become + * ordinary outputs (same per-file size limit and output cap) tagged `remote_mount`. */ + private async collectRemoteMountOutputs(): Promise { + const state = this.remoteMountsState; + if (!state) return; + let changes: Awaited>; + try { + changes = await findRemoteMountChanges( + state, + (mountPath, reason) => this.recordArtifactTruncation(reason, mountPath), + undefined, + config.max_output_files, + ); + } catch (err) { + this.log.error({ err }, 'Error scanning remote mount trees'); + this.recordArtifactTruncation('unreadable', '.'); + return; + } + for (const change of changes) { + if (change.size > this.runtime.max_file_size) { + this.recordArtifactTruncation('size', change.mountPath); + await change.handle?.close().catch(() => {}); + continue; + } + if (this.generatedFiles.length >= config.max_output_files) { + this.recordArtifactTruncation('max_files', change.mountPath); + await change.handle?.close().catch(() => {}); + continue; + } + if (!change.handle) { + this.recordArtifactTruncation('unreadable', change.mountPath); + continue; + } + const id = nanoid(); + this.sessionFiles.push({ + id, + name: change.name, + storage_session_id: this.outputSessionId, + remote_mount: { path: change.mountPath, change: change.change }, + }); + this.generatedFiles.push({ + id, + name: change.name, + path: change.hostPath, + handle: change.handle, + }); + } + } + private recordArtifactTruncation(reason: ArtifactTruncationReason, relativePath: string): void { this.artifactTruncation ??= { code: 'artifact_truncated', @@ -2630,7 +2775,8 @@ export class Job { let size: number; try { - const lstat = await fsp.lstat(file.path); + /* Remote-mount outputs carry a verified fd: never re-open by name. */ + const lstat = file.handle ? await file.handle.stat() : await fsp.lstat(file.path); if (lstat.isSymbolicLink()) { this.log.error({ file: file.name }, 'Refusing to upload a symlink'); return null; @@ -2669,7 +2815,8 @@ export class Job { 'Content-Length': String(size), }); /* See computeFileHash: numeric O_NOFOLLOW is only typed via fsp.open. */ - uploadHandle = await fsp.open(file.path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + uploadHandle = + file.handle ?? (await fsp.open(file.path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW)); stream = uploadHandle.createReadStream(); stream.on('error', (error) => { this.log.warn({ file: file.name, err: error }, 'Upload file stream error'); @@ -2721,6 +2868,14 @@ export class Job { } let outcome: 'removed' | 'preserved' | 'retained' | 'error' = 'error'; + for (const f of this.generatedFiles) await f.handle?.close().catch(() => {}); + const remoteMountsState = this.remoteMountsState; + this.remoteMountsState = undefined; + if (remoteMountsState) { + await removeRemoteMounts(remoteMountsState.root).catch(error => { + this.log.error({ err: error }, 'Failed to remove remote mount trees'); + }); + } try { /* Session mode: the workspace and pinned UID belong to the long-lived * session, not this job. Keep both so the next call sees prior files; diff --git a/api/src/nsjail.ts b/api/src/nsjail.ts index 23c048a6..f3a52f49 100644 --- a/api/src/nsjail.ts +++ b/api/src/nsjail.ts @@ -213,8 +213,27 @@ function readBaseConfig(): string { * embedded backslashes and double-quotes defensively in case future * callers pass arbitrary paths in. The cfg syntax is C-like so only those * two characters need escaping inside a string literal. */ -export function renderJobConfigOverlay(submissionDir: string): string { - const escaped = submissionDir.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); +export function renderJobConfigOverlay( + submissionDir: string, + extraBinds: ReadonlyArray<{ src: string; dst: string; rw?: boolean }> = [], +): string { + const escape = (value: string): string => value.replace(/\\/g, '\\\\').replace(/"/g, '\\"'); + const escaped = escape(submissionDir); + /* Remote-mount trees (rw: copy-on-write scratch) and the hook dir (read-only), + * same hardening flags as /mnt/data. Empty for requests without remote_mounts, + * so the overlay is unchanged for them. */ + const extraBlocks = extraBinds.flatMap(bind => [ + 'mount {', + ` src: "${escape(bind.src)}"`, + ` dst: "${escape(bind.dst)}"`, + ' is_bind: true', + ` rw: ${bind.rw === true}`, + ' noexec: true', + ' nosuid: true', + ' nodev: true', + '}', + '', + ]); return [ '', '# Per-job submission workspace bind. Dynamic because the source path', @@ -231,6 +250,7 @@ export function renderJobConfigOverlay(submissionDir: string): string { ' nodev: true', '}', '', + ...extraBlocks, ].join('\n'); } @@ -247,6 +267,8 @@ interface ExecuteOptions { identity: SandboxJobIdentity; enableToolCallPipes?: boolean; suppressSuccessLogs?: boolean; + /* Extra binds for remote_mounts (host src -> in-jail dst; rw only for mount trees). */ + extraBinds?: Array<{ src: string; dst: string; rw?: boolean }>; } export async function execute(opts: ExecuteOptions, setupGate: NsJailSetupGate = defaultNsJailSetupGate): Promise { @@ -263,12 +285,13 @@ export async function execute(opts: ExecuteOptions, setupGate: NsJailSetupGate = identity, enableToolCallPipes, suppressSuccessLogs, + extraBinds, } = opts; const logId = nanoid(); const logPath = `/tmp/nsjail-${logId}.log`; const cfgPath = `/tmp/nsjail-${logId}.cfg`; - fs.writeFileSync(cfgPath, readBaseConfig() + renderJobConfigOverlay(submissionDir), { mode: 0o600 }); + fs.writeFileSync(cfgPath, readBaseConfig() + renderJobConfigOverlay(submissionDir, extraBinds), { mode: 0o600 }); const nsjailArgs = buildArgs({ logPath, diff --git a/api/src/remote-mounts-hook.test.ts b/api/src/remote-mounts-hook.test.ts new file mode 100644 index 00000000..25aebf7c --- /dev/null +++ b/api/src/remote-mounts-hook.test.ts @@ -0,0 +1,202 @@ +import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'child_process'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { + PYTHON_HOOK_SOURCE, + REMOTE_MOUNTS_ENV, + REMOTE_MOUNTS_NONCE_ENV, + extractRemoteMountsRequired, +} from './remote-mounts'; + +const hasPython = spawnSync('python3', ['--version']).status === 0; +const NONCE = 'feedface'; + +let base: string; +let mount: string; +let hookDir: string; + +beforeAll(() => { + base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'rm-hook-'))); + mount = path.join(base, 'mnt-drive'); + hookDir = path.join(base, 'hook'); + fs.mkdirSync(path.join(mount, 'sub'), { recursive: true }); + fs.mkdirSync(hookDir); + fs.writeFileSync( + path.join(hookDir, 'sitecustomize.py'), + PYTHON_HOOK_SOURCE, + ); + fs.writeFileSync(path.join(mount, 'sub', 'loaded.csv'), 'a,b\n1,2\n', { + mode: 0o444, + }); + fs.writeFileSync(path.join(mount, 'sub', 'loaded.json'), '{"k": 3}', { + mode: 0o444, + }); + fs.writeFileSync(path.join(mount, 'sub', 'stub.docx'), '', { mode: 0o000 }); + fs.chmodSync(path.join(mount, 'sub', 'stub.docx'), 0o000); +}); + +afterAll(() => { + fs.chmodSync(path.join(mount, 'sub', 'stub.docx'), 0o600); + fs.rmSync(base, { recursive: true, force: true }); +}); + +function run( + code: string, + cwd = base, +): { stdout: string; stderr: string; status: number | null } { + const result = spawnSync('python3', ['-c', code], { + cwd, + encoding: 'utf8', + env: { + PATH: process.env.PATH ?? '', + PYTHONPATH: hookDir, + [REMOTE_MOUNTS_ENV]: JSON.stringify([mount]), + [REMOTE_MOUNTS_NONCE_ENV]: NONCE, + }, + }); + return { + stdout: result.stdout, + stderr: result.stderr, + status: result.status, + }; +} + +const STUB = () => path.join(mount, 'sub', 'stub.docx'); + +describe.skipIf(!hasPython)('python sitecustomize hook', () => { + test('loaded files read, listdir shows both, stub open raises the EACCES message', () => { + const r = run(` +import os +print(open(${JSON.stringify(path.join(mount, 'sub', 'loaded.csv'))}).read().strip().replace("\\n", "|")) +print(sorted(os.listdir(${JSON.stringify(path.join(mount, 'sub'))}))) +try: + open(${JSON.stringify(STUB())}) +except PermissionError as e: + print("ERR", e.errno, e) +`); + expect(r.status).toBe(0); + const lines = r.stdout.trim().split('\n'); + expect(lines[0]).toBe('a,b|1,2'); + expect(lines[1]).toBe("['loaded.csv', 'loaded.json', 'stub.docx']"); + expect(lines[2]).toBe( + `ERR 13 [Errno 13] ${STUB()} is not loaded yet; it is fetched for you and the code is run again`, + ); + }); + + test('opening a stub for write raises EACCES and is reported', () => { + const r = run(` +try: + open(${JSON.stringify(STUB())}, "w") +except PermissionError as e: + print("ERR", e.errno) +`); + expect(r.stdout.trim()).toBe('ERR 13'); + expect( + extractRemoteMountsRequired([r.stderr], NONCE, new Set([STUB()])) + .read, + ).toEqual([STUB()]); + }); + + test('the stderr sentinel block lists exactly the stub and round-trips through the parser', () => { + const r = run(` +try: + open(${JSON.stringify(STUB())}) +except PermissionError: + pass +`); + expect(r.stderr).toContain( + `__CODEAPI_REMOTE_MOUNTS_V1_START__${NONCE}\n{"read": ["${STUB()}"]}\n__CODEAPI_REMOTE_MOUNTS_V1_END__${NONCE}\n`, + ); + const parsed = extractRemoteMountsRequired( + [r.stderr], + NONCE, + new Set([STUB()]), + ); + expect(parsed.read).toEqual([STUB()]); + expect(parsed.texts[0]).toBe(''); + }); + + test('json, csv and pathlib reads of loaded files go through open and work; relative stub path is caught', () => { + const r = run( + ` +import csv, json, pathlib +print(list(csv.reader(open("sub/loaded.csv")))) +print(json.load(open("sub/loaded.json"))) +print(pathlib.Path("sub/loaded.csv").read_text().count("\\n")) +try: + pathlib.Path("sub/stub.docx").read_bytes() +except PermissionError as e: + print("ERR", e.filename if e.filename else "") +try: + json.load(open("sub/stub.docx")) +except PermissionError: + print("ERR2") +`, + mount, + ); + expect(r.status).toBe(0); + expect(r.stdout).toContain("[['a', 'b'], ['1', '2']]"); + expect(r.stdout).toContain("{'k': 3}"); + expect(r.stdout).toContain('ERR2'); + expect( + extractRemoteMountsRequired([r.stderr], NONCE, new Set([STUB()])) + .read, + ).toEqual([STUB()]); + }); + + test('no stub touched: no sentinel, and opens outside the mount and by fd are untouched', () => { + const r = run(` +import os +fd = os.open(${JSON.stringify(path.join(mount, 'sub', 'loaded.json'))}, os.O_RDONLY) +os.close(fd) +open("/dev/null").close() +print(open(${JSON.stringify(path.join(mount, 'sub', 'loaded.json'))}).read()) +`); + expect(r.status).toBe(0); + expect(r.stderr).toBe(''); + }); + + test('opens under read-only system prefixes skip realpath; other paths, incl. symlinks into the mount, still resolve', () => { + const link = path.join(base, 'link-to-mount'); + fs.symlinkSync(mount, link); + try { + const r = run(` +import os +calls = [] +real = os.path.realpath +def counting(*a, **k): + calls.append(a[0]) + return real(*a, **k) +os.path.realpath = counting +open("/etc/passwd").close() +print("system", len(calls)) +try: + open(${JSON.stringify(path.join(link, 'sub', 'stub.docx'))}) +except PermissionError: + print("symlink caught", len(calls)) +`); + expect(r.status).toBe(0); + expect(r.stdout).toContain('system 0'); + expect(r.stdout).toContain('symlink caught 1'); + } finally { + fs.unlinkSync(link); + } + }); + + test('without the env vars the hook is inert', () => { + const result = spawnSync( + 'python3', + ['-c', `print(open(${JSON.stringify(STUB())}).read() == "")`], + { + cwd: base, + encoding: 'utf8', + env: { PATH: process.env.PATH ?? '', PYTHONPATH: hookDir }, + }, + ); + // Mode 0000 still denies a non-root caller, but with the kernel message and no sentinel. + expect(result.stderr).not.toContain('__CODEAPI_REMOTE_MOUNTS'); + expect(result.stderr).not.toContain('is not loaded yet'); + }); +}); diff --git a/api/src/remote-mounts-job.test.ts b/api/src/remote-mounts-job.test.ts new file mode 100644 index 00000000..d3e57bee --- /dev/null +++ b/api/src/remote-mounts-job.test.ts @@ -0,0 +1,271 @@ +import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test'; +import * as fs from 'fs'; +import * as fsp from 'fs/promises'; +import * as os from 'os'; +import * as path from 'path'; +import * as semver from 'semver'; +import { Job } from './job'; +import * as nsjail from './nsjail'; +import type { NsJailResult } from './nsjail'; +import type { Runtime } from './runtime'; +import { materializeRemoteMounts, type RemoteMount } from './remote-mounts'; + +interface JobInternals { + submissionDir: string; + remoteMountsState: + | Awaited> + | undefined; + remoteMountsNonce: string; + collectRemoteMountsRequired: ( + results: Array, + ) => string[]; + walkDir: ( + dir: string, + depth: number, + input: Map, + ) => Promise; + generatedFiles: Array<{ id: string; name: string; path: string }>; + sessionFiles: Array>; + handleSessionFiles: () => Promise; + artifactTruncation: { reasons: Record } | undefined; +} + +const runtime: Runtime = { + language: 'python', + version: new semver.SemVer('3.11.0'), + aliases: [], + pkgdir: '/tmp', + compiled: false, + env_vars: {}, + timeouts: { compile: 5000, run: 5000 }, + cpu_times: { compile: 5000, run: 5000 }, + memory_limits: { compile: 100_000_000, run: 100_000_000 }, + max_process_count: 100, + max_open_files: 100, + max_file_size: 10_000_000, + output_max_size: 1_000_000, +}; + +const mounts: RemoteMount[] = [ + { + path: '/mnt/google-drive', + entries: [ + { + path: 'Testing/data.csv', + type: 'file', + file: { id: 'a', storage_session_id: 's' }, + }, + { path: 'Testing/stub.docx', type: 'file' }, + ], + }, +]; + +function makeJob(remote_mounts?: RemoteMount[]): Job { + return new Job({ + session_id: 'rm-test', + runtime, + files: [], + args: [], + stdin: '', + timeouts: { compile: 5000, run: 5000 }, + cpu_times: { compile: 5000, run: 5000 }, + memory_limits: { compile: 100_000_000, run: 100_000_000 }, + ...(remote_mounts ? { remote_mounts } : {}), + }); +} + +function result(stderr: string): NsJailResult { + return { + stdout: '', + stderr, + code: 0, + signal: null, + output: stderr, + memory: null, + message: null, + status: null, + cpu_time: null, + wall_time: 1, + }; +} + +let workspace: string; +beforeEach(async () => { + workspace = await fsp.mkdtemp(path.join(os.tmpdir(), 'rm-job-ws-')); +}); +afterEach(async () => { + await fsp.rm(workspace, { recursive: true, force: true }); +}); + +describe('Job remote mounts', () => { + it('keeps mount files out of output collection and out of the workspace', async () => { + const job = makeJob(mounts); + const internals = job as unknown as JobInternals; + const state = await materializeRemoteMounts( + mounts, + async () => new Response('x'), + 1000, + ); + internals.remoteMountsState = state; + internals.submissionDir = workspace; + await fsp.writeFile(path.join(workspace, 'out.txt'), 'generated'); + + expect(path.relative(workspace, state.root).startsWith('..')).toBe( + true, + ); + await internals.walkDir(workspace, 0, new Map()); + expect(internals.generatedFiles.map(f => f.name)).toEqual(['out.txt']); + + await job.cleanup(); + expect(fs.existsSync(state.root)).toBe(false); + }); + + it("strips this job's report and returns only declared stubs", () => { + const job = makeJob(mounts); + const internals = job as unknown as JobInternals; + const nonce = internals.remoteMountsNonce; + const stub = '/mnt/google-drive/Testing/stub.docx'; + const block = `\n__CODEAPI_REMOTE_MOUNTS_V1_START__${nonce}\n${JSON.stringify({ read: [stub, '/mnt/google-drive/Testing/data.csv'] })}\n__CODEAPI_REMOTE_MOUNTS_V1_END__${nonce}\n`; + const run = result(`oops${block}`); + expect(internals.collectRemoteMountsRequired([undefined, run])).toEqual( + [stub], + ); + expect(run.stderr).toBe('oops'); + expect(run.output).toBe('oops'); + }); + + it('without remote_mounts nothing is touched: no state, no report, stderr unchanged', () => { + const job = makeJob(); + const internals = job as unknown as JobInternals; + const forged = `\n__CODEAPI_REMOTE_MOUNTS_V1_START__\n{"read":["/mnt/x/y"]}\n__CODEAPI_REMOTE_MOUNTS_V1_END__\n`; + const run = result(forged); + expect(internals.collectRemoteMountsRequired([run])).toEqual([]); + expect(run.stderr).toBe(forged); + expect(internals.remoteMountsState).toBeUndefined(); + }); + + it('creates the crypto nonce only when the request has remote_mounts', () => { + expect((makeJob() as unknown as JobInternals).remoteMountsNonce).toBe(''); + expect((makeJob(mounts) as unknown as JobInternals).remoteMountsNonce).toMatch(/^[0-9a-f]{32}$/); + }); + + describe('safeCall env and nsjail options', () => { + const calls: Array> = []; + let spy: ReturnType; + beforeEach(() => { + calls.length = 0; + spy = spyOn(nsjail, 'execute').mockImplementation((async (opts: Record) => { + calls.push(opts); + return result(''); + }) as never); + }); + afterEach(() => spy.mockRestore()); + + const call = async (job: Job): Promise> => { + (job as unknown as JobInternals).submissionDir = workspace; + await job.safeCall('run', [], 1000, 1000, 100_000_000); + return calls[0]; + }; + + it('without remote_mounts: no CODEAPI_REMOTE_MOUNTS env, PYTHONPATH untouched, no read-only binds', async () => { + const job = new Job({ + session_id: 'rm-test', runtime: { ...runtime, env_vars: { PYTHONPATH: '/opt/x' } }, + files: [], args: [], stdin: '', + timeouts: runtime.timeouts, cpu_times: runtime.cpu_times, memory_limits: runtime.memory_limits, + }); + const opts = await call(job); + const env = opts.envVars as Record; + expect(Object.keys(env).filter(k => k.startsWith('CODEAPI_REMOTE_MOUNTS'))).toEqual([]); + expect(env.PYTHONPATH).toBe('/opt/x'); + expect(opts.extraBinds).toBeUndefined(); + }); + + it('with remote_mounts: env, hook path and read-only binds are set', async () => { + const job = makeJob(mounts); + const internals = job as unknown as JobInternals; + const state = await materializeRemoteMounts(mounts, async () => new Response('x'), 1000); + internals.remoteMountsState = state; + try { + const opts = await call(job); + const env = opts.envVars as Record; + expect(env.CODEAPI_REMOTE_MOUNTS).toBe(JSON.stringify(['/mnt/google-drive'])); + expect(env.CODEAPI_REMOTE_MOUNTS_NONCE).toBe(internals.remoteMountsNonce); + expect(env.PYTHONPATH).toBe('/mnt/.codeapi-hook'); + expect(opts.extraBinds).toEqual(state.binds); + } finally { + await job.cleanup(); + } + }); + }); + + describe('copy-on-write outputs', () => { + const build = async (job: Job): Promise => { + const internals = job as unknown as JobInternals; + const state = await materializeRemoteMounts(mounts, async () => new Response('x'), 1000); + internals.remoteMountsState = state; + internals.submissionDir = workspace; + return state.binds.find(b => b.dst === '/mnt/google-drive')!.src; + }; + + it('reports exactly the modified and the created file with remote_mount, basename and shared ids', async () => { + const job = makeJob(mounts); + const internals = job as unknown as JobInternals; + const src = await build(job); + fs.writeFileSync(path.join(src, 'Testing/data.csv'), 'changed'); + fs.writeFileSync(path.join(src, 'Testing/new.txt'), 'n'); + await fsp.writeFile(path.join(workspace, 'out.txt'), 'generated'); + await internals.handleSessionFiles(); + const withMount = internals.sessionFiles.filter(f => f.remote_mount); + expect(withMount.map(f => [f.name, f.remote_mount, f.storage_session_id]).sort()).toEqual([ + ['data.csv', { path: '/mnt/google-drive/Testing/data.csv', change: 'modified' }, 'rm-test'], + ['new.txt', { path: '/mnt/google-drive/Testing/new.txt', change: 'created' }, 'rm-test'], + ]); + expect(internals.sessionFiles.find(f => f.name === 'out.txt')!.remote_mount).toBeUndefined(); + expect(internals.generatedFiles.map(f => f.id).sort()).toEqual( + internals.sessionFiles.map(f => f.id as string).sort(), + ); + await job.cleanup(); + }); + + it('shares the max output files cap with /mnt/data outputs and records truncation', async () => { + const { config } = await import('./config'); + const job = makeJob(mounts); + const internals = job as unknown as JobInternals; + const src = await build(job); + const saved = config.max_output_files; + config.max_output_files = 2; + try { + await fsp.writeFile(path.join(workspace, 'out.txt'), 'generated'); + fs.writeFileSync(path.join(src, 'a.txt'), '1'); + fs.writeFileSync(path.join(src, 'b.txt'), '2'); + await internals.handleSessionFiles(); + expect(internals.generatedFiles).toHaveLength(2); + expect(internals.artifactTruncation?.reasons.max_files).toBeGreaterThan(0); + } finally { + config.max_output_files = saved; + await job.cleanup(); + } + }); + + it('rejects a mount file over the per-file size limit', async () => { + const job = makeJob(mounts); + const internals = job as unknown as JobInternals; + const src = await build(job); + fs.writeFileSync(path.join(src, 'big.txt'), Buffer.alloc(runtime.max_file_size + 1)); + await internals.handleSessionFiles(); + expect(internals.generatedFiles).toHaveLength(0); + expect(internals.artifactTruncation?.reasons.size).toBe(1); + await job.cleanup(); + }); + + it('without remote_mounts no entry carries remote_mount', async () => { + const job = makeJob(); + const internals = job as unknown as JobInternals; + internals.submissionDir = workspace; + await fsp.writeFile(path.join(workspace, 'out.txt'), 'generated'); + await internals.handleSessionFiles(); + expect(internals.sessionFiles).toHaveLength(1); + expect('remote_mount' in internals.sessionFiles[0]).toBe(false); + }); + }); +}); diff --git a/api/src/remote-mounts.test.ts b/api/src/remote-mounts.test.ts new file mode 100644 index 00000000..35ef829a --- /dev/null +++ b/api/src/remote-mounts.test.ts @@ -0,0 +1,860 @@ +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { + MAX_REMOTE_MOUNTS_REPORTED, + RemoteMountsError, + extractRemoteMountsRequired, + fdInsideRoot, + findRemoteMountChanges, + materializeRemoteMounts, + openMountFile, + removeRemoteMounts, + stubPaths, + sweepRemoteMountTrees, + validateRemoteMounts, + type RemoteMount, +} from './remote-mounts'; +import { renderJobConfigOverlay } from './nsjail'; + +const opts = { inputFileCount: 1, maxInputFiles: 50 }; +const file = { id: 'a', storage_session_id: 's' }; + +function mounts(entries: unknown[], mountPath = '/mnt/google-drive'): unknown { + return [{ path: mountPath, entries }]; +} + +function rejects(value: unknown, message: RegExp, o = opts): void { + try { + validateRemoteMounts(value, o); + } catch (error) { + expect(error).toBeInstanceOf(RemoteMountsError); + expect((error as RemoteMountsError).message).toMatch(message); + return; + } + throw new Error('expected validation to fail'); +} + +describe('validateRemoteMounts', () => { + test('accepts a loaded file, a stub, and implied parents', () => { + const out = validateRemoteMounts( + mounts([ + { path: 'Testing', type: 'dir' }, + { path: 'Testing/data.csv', type: 'file', size: 99, file }, + { path: 'Testing/Tilboð.docx', type: 'file', size: 5 }, + { path: 'deep/er/x.txt', type: 'file' }, + ]), + opts, + ); + expect(out[0].entries).toHaveLength(4); + expect([...stubPaths(out)].sort()).toEqual([ + '/mnt/google-drive/Testing/Tilboð.docx', + '/mnt/google-drive/deep/er/x.txt', + ]); + }); + + test.each([ + ['not an array', {}, /array/], + ['empty', [], /1 to 4/], + [ + 'five mounts', + [1, 2, 3, 4, 5].map(i => ({ path: `/mnt/m${i}`, entries: [] })), + /1 to 4/, + ], + ['/mnt/data', [{ path: '/mnt/data', entries: [] }], /\/mnt\/data/], + ['bad mount path', [{ path: '/mnt/Bad', entries: [] }], /must match/], + [ + 'nested mount path', + [{ path: '/mnt/a/b', entries: [] }], + /must match/, + ], + [ + 'duplicate mount', + [ + { path: '/mnt/a', entries: [] }, + { path: '/mnt/a', entries: [] }, + ], + /duplicated/, + ], + ])('rejects %s', (_name, value, re) => rejects(value, re as RegExp)); + + test.each([ + ['dotdot', '../x'], + ['dot segment', 'a/./b'], + ['empty segment', 'a//b'], + ['leading slash', '/a'], + ['trailing slash', 'a/'], + ['backslash', 'a\\b'], + ['NUL', 'a\u0000b'], + ['control char', 'a\u001fb'], + ['DEL', 'a\u007fb'], + ['segment over 255 bytes', 'a'.repeat(256)], + [ + 'path over 1024 bytes', + Array.from({ length: 6 }, () => 'a'.repeat(200)).join('/'), + ], + ['depth 17', Array.from({ length: 17 }, () => 'a').join('/')], + ])('rejects entry path: %s', (_name, p) => { + rejects(mounts([{ path: p, type: 'dir' }]), /path/); + }); + + test('accepts depth 16 and 255-byte segments', () => { + validateRemoteMounts( + mounts([ + { + path: Array.from({ length: 16 }, () => 'a').join('/'), + type: 'dir', + }, + ]), + opts, + ); + validateRemoteMounts( + mounts([{ path: 'é'.repeat(127), type: 'file' }]), + opts, + ); + }); + + test('rejects duplicates, bad type, bad size, file-as-parent, file on dir', () => { + rejects( + mounts([ + { path: 'a', type: 'dir' }, + { path: 'a', type: 'file' }, + ]), + /duplicated/, + ); + rejects(mounts([{ path: 'a', type: 'link' }]), /type/); + rejects(mounts([{ path: 'a', type: 'file', size: -1 }]), /size/); + rejects(mounts([{ path: 'a', type: 'file', size: 1.5 }]), /size/); + rejects(mounts([{ path: 'a', type: 'dir', size: 1 }]), /size/); + rejects( + mounts([ + { path: 'a', type: 'file' }, + { path: 'a/b', type: 'file' }, + ]), + /parent/, + ); + rejects(mounts([{ path: 'a', type: 'dir', file }]), /file/); + rejects( + mounts([{ path: 'a', type: 'file', file: { id: 'x' } }]), + /storage_session_id/, + ); + }); + + test('rejects too many entries and too many loaded files', () => { + const many = Array.from({ length: 5001 }, (_v, i) => ({ + path: `f${i}`, + type: 'file', + })); + rejects(mounts(many), /5000/); + const loaded = Array.from({ length: 65 }, (_v, i) => ({ + path: `f${i}`, + type: 'file', + file, + })); + rejects(mounts(loaded), /64/); + const some = Array.from({ length: 10 }, (_v, i) => ({ + path: `f${i}`, + type: 'file', + file, + })); + rejects(mounts(some), /exceed 10/, { + inputFileCount: 1, + maxInputFiles: 10, + }); + }); +}); + +describe('extractRemoteMountsRequired', () => { + const stubs = new Set(['/mnt/x/a.txt', '/mnt/x/b.txt']); + const nonce = 'abc123'; + const block = (n: string, payload: string): string => + `\n__CODEAPI_REMOTE_MOUNTS_V1_START__${n}\n${payload}\n__CODEAPI_REMOTE_MOUNTS_V1_END__${n}\n`; + + test('strips only this nonce, keeps foreign blocks untouched', () => { + const forged = block('other', '{"read":["/mnt/x/a.txt"]}'); + const { texts, read } = extractRemoteMountsRequired( + [ + `before${block(nonce, '{"read":["/mnt/x/a.txt"]}')}after${forged}`, + ], + nonce, + stubs, + ); + expect(texts[0]).toBe(`beforeafter${forged}`); + expect(read).toEqual(['/mnt/x/a.txt']); + }); + + test('drops paths that are not stubs of this request, dedupes', () => { + const { read } = extractRemoteMountsRequired( + [ + block( + nonce, + '{"read":["/etc/passwd","/mnt/x/a.txt","/mnt/x/a.txt","/mnt/x/loaded.txt",7]}', + ), + ], + nonce, + stubs, + ); + expect(read).toEqual(['/mnt/x/a.txt']); + }); + + test('ignores malformed JSON but still strips the block', () => { + const { texts, read } = extractRemoteMountsRequired( + [`x${block(nonce, '{not json')}y`], + nonce, + stubs, + ); + expect(texts[0]).toBe('xy'); + expect(read).toEqual([]); + }); + + test('merges blocks across texts and caps the result', () => { + const many = new Set( + Array.from({ length: 100 }, (_v, i) => `/mnt/x/f${i}`), + ); + const payload = JSON.stringify({ read: [...many] }); + const { read } = extractRemoteMountsRequired( + [block(nonce, payload), block(nonce, payload)], + nonce, + many, + ); + expect(read).toHaveLength(MAX_REMOTE_MOUNTS_REPORTED); + }); + + test('text without blocks is returned as is', () => { + expect(extractRemoteMountsRequired(['plain'], nonce, stubs)).toEqual({ + texts: ['plain'], + read: [], + }); + }); +}); + +describe('materializeRemoteMounts', () => { + const roots: string[] = []; + afterEach(async () => { + for (const r of roots.splice(0)) await removeRemoteMounts(r); + }); + + const tree: RemoteMount[] = [ + { + path: '/mnt/google-drive', + entries: [ + { path: 'Testing', type: 'dir' }, + { path: 'Testing/data.csv', type: 'file', file }, + { path: 'Testing/stub.docx', type: 'file' }, + { path: 'a/b/c.txt', type: 'file', file }, + ], + }, + ]; + const fetchBytes = async (): Promise => + new Response('a,b\n1,2\n'); + + test('builds writable dirs 0700, loaded 0600, stubs empty 0000, no symlinks', async () => { + const m = await materializeRemoteMounts(tree, fetchBytes, 1000); + roots.push(m.root); + const bind = m.binds.find(b => b.dst === '/mnt/google-drive')!; + const stat = (rel: string) => fs.lstatSync(path.join(bind.src, rel)); + expect(stat('Testing').mode & 0o777).toBe(0o700); + expect(stat('a/b').mode & 0o777).toBe(0o700); + expect(fs.lstatSync(bind.src).mode & 0o777).toBe(0o700); + expect(stat('Testing/data.csv').mode & 0o777).toBe(0o600); + expect( + fs.readFileSync(path.join(bind.src, 'Testing/data.csv'), 'utf8'), + ).toBe('a,b\n1,2\n'); + const stub = stat('Testing/stub.docx'); + expect(stub.mode & 0o777).toBe(0); + expect(stub.size).toBe(0); + for (const rel of [ + 'Testing', + 'Testing/data.csv', + 'Testing/stub.docx', + 'a/b/c.txt', + ]) { + expect(stat(rel).isSymbolicLink()).toBe(false); + } + expect(m.binds.find(b => b.dst === '/mnt/.codeapi-hook')).toBeDefined(); + }); + + test('removeRemoteMounts deletes the sealed tree', async () => { + const m = await materializeRemoteMounts(tree, fetchBytes, 1000); + await removeRemoteMounts(m.root); + expect(fs.existsSync(m.root)).toBe(false); + }); + + const leftovers = (): string[] => + fs + .readdirSync(os.tmpdir()) + .filter(n => n.startsWith('codeapi-remote-mounts-')); + + test('a file over the size limit fails and leaves nothing behind', async () => { + const before = leftovers(); + await expect( + materializeRemoteMounts( + tree, + async () => new Response('x'.repeat(50)), + 10, + ), + ).rejects.toThrow(/exceeds/); + expect(leftovers()).toEqual(before); + }); + + test('an abort during setup fetches nothing and leaves no tree', async () => { + const before = leftovers(); + let fetches = 0; + const many: RemoteMount[] = [ + { + path: '/mnt/google-drive', + entries: [ + { path: 'stub.docx', type: 'file' }, + ...[1, 2, 3, 4, 5].map(i => ({ + path: `f${i}.csv`, + type: 'file' as const, + file, + })), + ], + }, + ]; + const controller = new AbortController(); + const pending = materializeRemoteMounts( + many, + async () => { + fetches++; + return new Response('x'); + }, + 1000, + controller.signal, + ); + controller.abort(new Error('cancelled')); + await expect(pending).rejects.toThrow(/cancelled/); + expect(fetches).toBe(0); + expect(leftovers()).toEqual(before); + }); + + test('a failed fetch removes the partial tree', async () => { + const before = leftovers(); + await expect( + materializeRemoteMounts( + tree, + async () => { + throw new Error('boom'); + }, + 1000, + ), + ).rejects.toThrow('boom'); + expect(leftovers()).toEqual(before); + }); +}); + +describe('renderJobConfigOverlay with remote mounts', () => { + test('without binds the overlay is exactly the historical /mnt/data block', () => { + expect(renderJobConfigOverlay('/w/dir')).toBe( + [ + '', + '# Per-job submission workspace bind. Dynamic because the source path', + '# rotates every execution. noexec/nosuid/nodev block the audit pattern', + '# of `chmod +x /mnt/data/x.sh && /mnt/data/x.sh` — neither user code', + '# nor any helper can run a binary from the writable scratch dir.', + 'mount {', + ' src: "/w/dir"', + ' dst: "/mnt/data"', + ' is_bind: true', + ' rw: true', + ' noexec: true', + ' nosuid: true', + ' nodev: true', + '}', + '', + ].join('\n'), + ); + expect(renderJobConfigOverlay('/w/dir', [])).toBe( + renderJobConfigOverlay('/w/dir'), + ); + }); + + test('with binds: nodev/nosuid/noexec mounts, rw only where asked', () => { + const out = renderJobConfigOverlay('/w/dir', [ + { src: '/t/m0', dst: '/mnt/google-drive', rw: true }, + { src: '/t/hook', dst: '/mnt/.codeapi-hook' }, + ]); + expect(out).toContain( + ' dst: "/mnt/data"\n is_bind: true\n rw: true', + ); + expect(out).toContain( + 'mount {\n src: "/t/m0"\n dst: "/mnt/google-drive"\n is_bind: true\n rw: true\n noexec: true\n nosuid: true\n nodev: true\n}', + ); + expect(out).toContain( + ' src: "/t/hook"\n dst: "/mnt/.codeapi-hook"\n is_bind: true\n rw: false', + ); + }); +}); + +describe('materializeRemoteMounts abort, concurrency and body draining', () => { + const many = (n: number): RemoteMount[] => [ + { + path: '/mnt/google-drive', + entries: Array.from({ length: n }, (_, i) => ({ + path: `f${i}.txt`, + type: 'file' as const, + file: { id: `id${i}`, storage_session_id: 's' }, + })), + }, + ]; + let tmp: string; + let prevTmp: string | undefined; + beforeEach(() => { + prevTmp = process.env.TMPDIR; + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'rm-abort-')); + process.env.TMPDIR = tmp; + }); + afterEach(() => { + if (prevTmp === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = prevTmp; + fs.rmSync(tmp, { recursive: true, force: true }); + }); + + test('an already aborted signal stops before any fetch and leaves no tree', async () => { + const controller = new AbortController(); + controller.abort(new Error('job aborted')); + let fetched = 0; + await expect( + materializeRemoteMounts( + many(3), + async () => { + fetched++; + return new Response('x'); + }, + 100, + controller.signal, + ), + ).rejects.toThrow('job aborted'); + expect(fetched).toBe(0); + expect(fs.readdirSync(tmp)).toEqual([]); + }); + + test('aborting mid-flight stops in-flight fetches promptly and leaves no tree', async () => { + const controller = new AbortController(); + let started = 0; + const hang = (_f: unknown, signal?: AbortSignal): Promise => + new Promise((_resolve, reject) => { + started++; + signal?.addEventListener('abort', () => reject(signal.reason), { + once: true, + }); + }); + const run = materializeRemoteMounts( + many(6), + hang, + 100, + controller.signal, + 3, + ); + await new Promise(r => setTimeout(r, 20)); + const t0 = performance.now(); + controller.abort(new Error('job aborted')); + await expect(run).rejects.toThrow('job aborted'); + expect(performance.now() - t0).toBeLessThan(500); + expect(started).toBe(3); + expect(fs.readdirSync(tmp)).toEqual([]); + }); + + test('fetches at most `concurrency` files at once', async () => { + let inFlight = 0; + let peak = 0; + const fetchSlow = async (): Promise => { + inFlight++; + peak = Math.max(peak, inFlight); + await new Promise(r => setTimeout(r, 10)); + inFlight--; + return new Response('x'); + }; + const m = await materializeRemoteMounts( + many(8), + fetchSlow, + 100, + undefined, + 3, + ); + await removeRemoteMounts(m.root); + expect(peak).toBe(3); + }); + + test('a failing file aborts its siblings', async () => { + const seen: Array = []; + const fetchObject = async ( + f: { id: string }, + signal?: AbortSignal, + ): Promise => { + seen.push(signal); + if (f.id === 'id0') throw new Error('boom'); + await new Promise(r => setTimeout(r, 50)); + return new Response('x'); + }; + await expect( + materializeRemoteMounts(many(3), fetchObject, 100, undefined, 3), + ).rejects.toThrow('boom'); + expect(seen.every(sig => sig?.aborted)).toBe(true); + expect(fs.readdirSync(tmp)).toEqual([]); + }); + + test('a file that fails to write cancels its response body', async () => { + let cancelled = false; + const body = new ReadableStream({ + pull(c) { + c.enqueue(new Uint8Array(50)); + }, + cancel() { + cancelled = true; + }, + }); + await expect( + materializeRemoteMounts( + many(1), + async () => new Response(body), + 10, + ), + ).rejects.toThrow(/exceeds/); + expect(cancelled).toBe(true); + }); +}); + +describe('sweepRemoteMountTrees', () => { + test('removes sealed leftover trees by prefix and leaves other entries', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rm-sweep-')); + try { + const stale = path.join(dir, 'codeapi-remote-mounts-abc'); + fs.mkdirSync(path.join(stale, 'm0', 'sub'), { recursive: true }); + fs.writeFileSync(path.join(stale, 'm0', 'sub', 'f'), 'x', { + mode: 0o444, + }); + for (const d of [ + path.join(stale, 'm0', 'sub'), + path.join(stale, 'm0'), + stale, + ]) + fs.chmodSync(d, 0o555); + fs.mkdirSync(path.join(dir, 'unrelated')); + expect(await sweepRemoteMountTrees(dir)).toBe(1); + expect(fs.readdirSync(dir)).toEqual(['unrelated']); + expect(await sweepRemoteMountTrees(path.join(dir, 'missing'))).toBe( + 0, + ); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe('findRemoteMountChanges (copy-on-write outputs)', () => { + const roots: string[] = []; + afterEach(async () => { + for (const r of roots.splice(0)) await removeRemoteMounts(r); + }); + const cow: RemoteMount[] = [ + { + path: '/mnt/google-drive', + entries: [ + { path: 'T/a.csv', type: 'file', file }, + { path: 'T/b.csv', type: 'file', file }, + { path: 'T/stub.docx', type: 'file' }, + ], + }, + ]; + const build = async () => { + const m = await materializeRemoteMounts( + cow, + async () => new Response('one\n'), + 1000, + ); + roots.push(m.root); + return { + m, + dir: m.binds.find(b => b.dst === '/mnt/google-drive')!.src, + }; + }; + + test('reports exactly the modified loaded file and the new file', async () => { + const { m, dir } = await build(); + fs.writeFileSync(path.join(dir, 'T/a.csv'), 'two\n'); + fs.mkdirSync(path.join(dir, 'N/deep'), { recursive: true }); + fs.writeFileSync(path.join(dir, 'N/deep/new.txt'), 'x'); + const changes = await findRemoteMountChanges(m); + expect(changes.map(c => [c.mountPath, c.change]).sort()).toEqual([ + ['/mnt/google-drive/N/deep/new.txt', 'created'], + ['/mnt/google-drive/T/a.csv', 'modified'], + ]); + expect(changes.find(c => c.change === 'created')!.hostPath).toBe( + path.join(dir, 'N/deep/new.txt'), + ); + }); + + test('rewriting identical bytes, deleting, and stubs report nothing', async () => { + const { m, dir } = await build(); + fs.writeFileSync(path.join(dir, 'T/a.csv'), 'one\n'); + fs.rmSync(path.join(dir, 'T/b.csv')); + fs.chmodSync(path.join(dir, 'T/stub.docx'), 0o600); + fs.writeFileSync(path.join(dir, 'T/stub.docx'), 'planted'); + expect(await findRemoteMountChanges(m)).toEqual([]); + }); + + test('symlinks (file or dir) are ignored and never followed', async () => { + const { m, dir } = await build(); + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'rm-out-')); + try { + fs.writeFileSync(path.join(outside, 'secret.txt'), 's'); + fs.symlinkSync( + path.join(outside, 'secret.txt'), + path.join(dir, 'link.txt'), + ); + fs.symlinkSync(outside, path.join(dir, 'linkdir')); + fs.rmSync(path.join(dir, 'T/a.csv')); + fs.symlinkSync( + path.join(outside, 'secret.txt'), + path.join(dir, 'T/a.csv'), + ); + expect(await findRemoteMountChanges(m)).toEqual([]); + } finally { + fs.rmSync(outside, { recursive: true, force: true }); + } + }); + + test('names failing the path rules are ignored', async () => { + const { m, dir } = await build(); + fs.writeFileSync(path.join(dir, 'bad\nname.txt'), 'x'); + fs.writeFileSync(path.join(dir, 'ok.txt'), 'x'); + const changes = await findRemoteMountChanges(m); + expect(changes.map(c => c.mountPath)).toEqual([ + '/mnt/google-drive/ok.txt', + ]); + }); + + test('a modified loaded file is found even when the walk hits the cap, and the cap is recorded', async () => { + const { m, dir } = await build(); + fs.writeFileSync(path.join(dir, 'T/a.csv'), 'two\n'); + fs.mkdirSync(path.join(dir, 'Z')); + for (let i = 0; i <= 20000; i++) + fs.writeFileSync(path.join(dir, 'Z', `f${i}`), ''); + const truncated: string[] = []; + const changes = await findRemoteMountChanges(m, p => truncated.push(p)); + expect( + changes + .filter(c => c.mountPath.endsWith('T/a.csv')) + .map(c => c.change), + ).toEqual(['modified']); + expect(truncated).toEqual(['/mnt/google-drive']); + }); + + test('a flood of empty directories records the cap', async () => { + const { m, dir } = await build(); + for (let i = 0; i <= 20000; i++) fs.mkdirSync(path.join(dir, `d${i}`)); + const truncated: string[] = []; + await findRemoteMountChanges(m, p => truncated.push(p)); + expect(truncated).toEqual(['/mnt/google-drive']); + }); + + test('a loaded file that cannot be hashed after the run counts as modified', async () => { + const { m, dir } = await build(); + fs.chmodSync(path.join(dir, 'T/a.csv'), 0o000); + const changes = await findRemoteMountChanges(m); + expect(changes.map(c => [c.mountPath, c.change])).toEqual([ + ['/mnt/google-drive/T/a.csv', 'modified'], + ]); + }); + + test('a path is reported at most once', async () => { + const { m, dir } = await build(); + fs.writeFileSync(path.join(dir, 'T/a.csv'), 'two\n'); + fs.writeFileSync(path.join(dir, 'new.txt'), 'x'); + const paths = (await findRemoteMountChanges(m)).map(c => c.mountPath); + expect(new Set(paths).size).toBe(paths.length); + }); + + test('a loaded file under a directory swapped for a symlink is never read or reported', async () => { + const { m, dir } = await build(); + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'rm-out-')); + try { + fs.writeFileSync(path.join(outside, 'a.csv'), 'host secret\n'); + fs.writeFileSync(path.join(outside, 'planted.txt'), 'x'); + fs.rmSync(path.join(dir, 'T'), { recursive: true }); + fs.symlinkSync(outside, path.join(dir, 'T')); + const seen: Array<[string, string?]> = []; + expect( + await findRemoteMountChanges(m, (p, r) => seen.push([p, r])), + ).toEqual([]); + expect(seen.every(([, r]) => r === 'unreadable')).toBe(true); + expect(seen.length).toBeGreaterThan(0); + } finally { + fs.rmSync(outside, { recursive: true, force: true }); + } + }); + + test('the walk does not descend into a symlinked directory holding new files', async () => { + const { m, dir } = await build(); + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'rm-out-')); + try { + fs.writeFileSync(path.join(outside, 'leak.txt'), 'x'); + fs.symlinkSync(outside, path.join(dir, 'N')); + expect(await findRemoteMountChanges(m)).toEqual([]); + } finally { + fs.rmSync(outside, { recursive: true, force: true }); + } + }); + + test('a loaded path replaced by a symlink or special file is skipped and recorded unreadable', async () => { + const { m, dir } = await build(); + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'rm-out-')); + try { + fs.writeFileSync(path.join(outside, 'secret.txt'), 's'); + fs.rmSync(path.join(dir, 'T/a.csv')); + fs.symlinkSync( + path.join(outside, 'secret.txt'), + path.join(dir, 'T/a.csv'), + ); + fs.rmSync(path.join(dir, 'T/b.csv')); + require('child_process').execFileSync('mkfifo', [ + path.join(dir, 'T/b.csv'), + ]); + const seen: Array<[string, string?]> = []; + expect( + await findRemoteMountChanges(m, (p, r) => seen.push([p, r])), + ).toEqual([]); + expect(seen.sort()).toEqual([ + ['/mnt/google-drive/T/a.csv', 'unreadable'], + ['/mnt/google-drive/T/b.csv', 'unreadable'], + ]); + } finally { + fs.rmSync(outside, { recursive: true, force: true }); + } + }); + + test('hashing is not size-capped: an unchanged large file is not reported, a modified one is with its size', async () => { + const { m, dir } = await build(); + expect(await findRemoteMountChanges(m)).toEqual([]); + fs.writeFileSync(path.join(dir, 'T/a.csv'), 'x'.repeat(5000)); + const changes = await findRemoteMountChanges(m); + expect(changes.map(c => [c.mountPath, c.size])).toEqual([ + ['/mnt/google-drive/T/a.csv', 5000], + ]); + }); +}); + +describe('mount content reads go through one verified fd', () => { + const roots: string[] = []; + afterEach(async () => { + for (const r of roots.splice(0)) await removeRemoteMounts(r); + }); + const build = async ( + specs: RemoteMount[] = [ + { + path: '/mnt/google-drive', + entries: [{ path: 'T/a.csv', type: 'file', file }], + }, + ], + ) => { + const m = await materializeRemoteMounts( + specs, + async () => new Response('one\n'), + 1000, + ); + roots.push(m.root); + return m; + }; + + test('fdInsideRoot compares the resolved path with the root as a directory prefix', () => { + expect(fdInsideRoot(3, '/t/m0', () => '/t/m0/T/a.csv')).toBe(true); + expect(fdInsideRoot(3, '/t/m0', () => '/t/m0evil/a.csv')).toBe(false); + expect(fdInsideRoot(3, '/t/m0', () => '/etc/passwd')).toBe(false); + expect(fdInsideRoot(3, '/t/m0', () => undefined)).toBeUndefined(); + }); + + test('openMountFile rejects an fd that resolves outside the tree and accepts one inside', async () => { + const m = await build(); + const tree = m.trees[0]; + await expect( + openMountFile(tree, 'T/a.csv', () => '/somewhere/else/a.csv'), + ).rejects.toThrow(); + const h = await openMountFile( + tree, + 'T/a.csv', + () => `${tree.realSrc}/T/a.csv`, + ); + expect(await h.readFile('utf8')).toBe('one\n'); + await h.close(); + }); + + test('without /proc it falls back to the parents-are-real-dirs check', async () => { + const m = await build(); + const tree = m.trees[0]; + const h = await openMountFile(tree, 'T/a.csv', () => undefined); + await h.close(); + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'rm-out-')); + try { + fs.writeFileSync(path.join(outside, 'a.csv'), 'secret'); + fs.rmSync(path.join(tree.src, 'T'), { recursive: true }); + fs.symlinkSync(outside, path.join(tree.src, 'T')); + await expect( + openMountFile(tree, 'T/a.csv', () => undefined), + ).rejects.toThrow(); + } finally { + fs.rmSync(outside, { recursive: true, force: true }); + } + }); + + test('a FIFO at a loaded path does not hang the open and is rejected', async () => { + const m = await build(); + const tree = m.trees[0]; + fs.rmSync(path.join(tree.src, 'T/a.csv')); + require('child_process').execFileSync('mkfifo', [ + path.join(tree.src, 'T/a.csv'), + ]); + const started = Date.now(); + await expect( + openMountFile(tree, 'T/a.csv', () => `${tree.realSrc}/T/a.csv`), + ).rejects.toThrow(); + expect(Date.now() - started).toBeLessThan(2000); + }); + + test('findRemoteMountChanges never hashes or hands out a file whose fd resolves outside the tree', async () => { + const m = await build(); + const dir = m.trees[0].src; + fs.writeFileSync(path.join(dir, 'T/a.csv'), 'two\n'); + fs.writeFileSync(path.join(dir, 'new.txt'), 'x'); + const seen: Array<[string, string?]> = []; + const changes = await findRemoteMountChanges( + m, + (p, r) => seen.push([p, r]), + () => '/somewhere/else', + 4, + ); + expect(changes).toEqual([]); + expect(seen.sort()).toEqual([ + ['/mnt/google-drive/T/a.csv', 'unreadable'], + ['/mnt/google-drive/new.txt', 'unreadable'], + ]); + }); + + test('changes carry the verified handle the upload reads from', async () => { + const m = await build(); + fs.writeFileSync(path.join(m.trees[0].src, 'T/a.csv'), 'two\n'); + const changes = await findRemoteMountChanges( + m, + undefined, + undefined, + 4, + ); + expect(await changes[0].handle!.readFile('utf8')).toBe('two\n'); + await changes[0].handle!.close(); + }); + + test('the walk cap is one budget across all trees of the job', async () => { + const m = await build([ + { path: '/mnt/a', entries: [] }, + { path: '/mnt/b', entries: [] }, + ]); + for (const t of m.trees) + for (let i = 0; i < 12000; i++) + fs.mkdirSync(path.join(t.src, `d${i}`)); + const truncated: string[] = []; + await findRemoteMountChanges(m, p => truncated.push(p)); + expect(truncated).toEqual(['/mnt/b']); + }); +}); diff --git a/api/src/remote-mounts.ts b/api/src/remote-mounts.ts new file mode 100644 index 00000000..941415e7 --- /dev/null +++ b/api/src/remote-mounts.ts @@ -0,0 +1,801 @@ +/* Remote mounts: copy-on-write trees a caller describes in `remote_mounts` + * (docs/remote-mounts/README.md). This module is pure policy plus the on-disk + * tree builder; job.ts supplies the byte fetch and nsjail.ts binds the result. */ +import * as crypto from 'crypto'; +import * as fs from 'fs'; +import * as fsp from 'fs/promises'; +import * as os from 'os'; +import * as path from 'path'; + +export const REMOTE_MOUNTS_INVALID_CODE = 'invalid_remote_mounts'; +export const REMOTE_MOUNTS_ENV = 'CODEAPI_REMOTE_MOUNTS'; +export const REMOTE_MOUNTS_NONCE_ENV = 'CODEAPI_REMOTE_MOUNTS_NONCE'; +/* Where the hook directory appears inside the jail. Outside /mnt/data, so it is + * never collected as output. */ +export const REMOTE_MOUNTS_HOOK_DST = '/mnt/.codeapi-hook'; +export const MAX_REMOTE_MOUNTS = 4; +export const MAX_REMOTE_MOUNT_ENTRIES = 5000; +export const MAX_REMOTE_MOUNT_LOADED_FILES = 64; +export const MAX_REMOTE_MOUNTS_REPORTED = 64; + +const MOUNT_PATH_RE = /^\/mnt\/[a-z0-9][a-z0-9-]{0,30}$/; +const CONTROL_RE = /[\u0000-\u001f\u007f]/; +const CACHE_KEY_RE = /^[0-9a-f]{64}$/; + +export interface RemoteMountFile { + id: string; + storage_session_id: string; + input_cache_key?: string; + name?: string; +} +export interface RemoteMountEntry { + path: string; + type: 'file' | 'dir'; + size?: number; + file?: RemoteMountFile; +} +export interface RemoteMount { + path: string; + entries: RemoteMountEntry[]; +} + +export class RemoteMountsError extends Error { + readonly code = REMOTE_MOUNTS_INVALID_CODE; +} + +function fail(message: string): never { + throw new RemoteMountsError(message); +} + +function isObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function validateEntryPath(p: unknown, where: string): string { + if (typeof p !== 'string' || p === '') + fail(`${where}.path must be a non-empty string`); + if (Buffer.byteLength(p) > 1024) + fail(`${where}.path is longer than 1024 bytes`); + if (p.includes('\\') || CONTROL_RE.test(p)) + fail(`${where}.path contains a forbidden character`); + if (p.startsWith('/') || p.endsWith('/')) + fail(`${where}.path must not start or end with "/"`); + const segments = p.split('/'); + if (segments.length > 16) fail(`${where}.path is deeper than 16 levels`); + for (const segment of segments) { + if (segment === '' || segment === '.' || segment === '..') + fail(`${where}.path has an invalid segment`); + if (Buffer.byteLength(segment) > 255) + fail(`${where}.path has a segment longer than 255 bytes`); + } + return p; +} + +/** Validates the raw `remote_mounts` field; returns a normalized copy. + * `inputFileCount` is the length of the request's `files[]`. */ +export function validateRemoteMounts( + value: unknown, + opts: { inputFileCount: number; maxInputFiles: number }, +): RemoteMount[] { + if (!Array.isArray(value)) fail('remote_mounts must be an array'); + if (value.length < 1 || value.length > MAX_REMOTE_MOUNTS) { + fail(`remote_mounts must contain 1 to ${MAX_REMOTE_MOUNTS} mounts`); + } + const seenMounts = new Set(); + let totalEntries = 0; + let loaded = 0; + const out: RemoteMount[] = []; + for (const [mi, rawMount] of value.entries()) { + const where = `remote_mounts[${mi}]`; + if (!isObject(rawMount)) fail(`${where} must be an object`); + const mountPath = rawMount.path; + if ( + typeof mountPath !== 'string' || + !MOUNT_PATH_RE.test(mountPath) || + mountPath === '/mnt/data' + ) { + fail(`${where}.path must match /mnt/ and not be /mnt/data`); + } + if (seenMounts.has(mountPath)) fail(`${where}.path is duplicated`); + seenMounts.add(mountPath); + if (!Array.isArray(rawMount.entries)) + fail(`${where}.entries must be an array`); + totalEntries += rawMount.entries.length; + if (totalEntries > MAX_REMOTE_MOUNT_ENTRIES) { + fail( + `remote_mounts has more than ${MAX_REMOTE_MOUNT_ENTRIES} entries`, + ); + } + const entries: RemoteMountEntry[] = []; + const seenPaths = new Set(); + const fileEntries = new Set(); + const implied = new Set(); + for (const [ei, raw] of rawMount.entries.entries()) { + const ew = `${where}.entries[${ei}]`; + if (!isObject(raw)) fail(`${ew} must be an object`); + const p = validateEntryPath(raw.path, ew); + if (seenPaths.has(p)) fail(`${ew}.path is duplicated`); + seenPaths.add(p); + if (raw.type !== 'file' && raw.type !== 'dir') + fail(`${ew}.type must be "file" or "dir"`); + const entry: RemoteMountEntry = { path: p, type: raw.type }; + if (raw.size !== undefined) { + if (raw.type !== 'file') + fail(`${ew}.size is only allowed on files`); + if ( + typeof raw.size !== 'number' || + !Number.isSafeInteger(raw.size) || + raw.size < 0 + ) { + fail(`${ew}.size must be a non-negative safe integer`); + } + entry.size = raw.size; + } + if (raw.file !== undefined) { + if (raw.type !== 'file') + fail(`${ew}.file is only allowed on files`); + const f = raw.file; + if (!isObject(f)) fail(`${ew}.file must be an object`); + if (typeof f.id !== 'string' || f.id === '') + fail(`${ew}.file.id must be a non-empty string`); + if ( + typeof f.storage_session_id !== 'string' || + f.storage_session_id === '' + ) { + fail( + `${ew}.file.storage_session_id must be a non-empty string`, + ); + } + if ( + f.input_cache_key !== undefined && + (typeof f.input_cache_key !== 'string' || + !CACHE_KEY_RE.test(f.input_cache_key)) + ) { + fail( + `${ew}.file.input_cache_key must be a 64-character lowercase hex digest`, + ); + } + entry.file = { + id: f.id, + storage_session_id: f.storage_session_id, + ...(typeof f.input_cache_key === 'string' + ? { input_cache_key: f.input_cache_key } + : {}), + ...(typeof f.name === 'string' ? { name: f.name } : {}), + }; + loaded++; + } + if (raw.type === 'file') fileEntries.add(p); + const segments = p.split('/'); + for (let i = 1; i < segments.length; i++) + implied.add(segments.slice(0, i).join('/')); + entries.push(entry); + } + for (const dir of implied) { + if (fileEntries.has(dir)) + fail( + `${where} entry "${dir}" is a file and also a parent of another entry`, + ); + } + out.push({ path: mountPath, entries }); + } + if (loaded > MAX_REMOTE_MOUNT_LOADED_FILES) { + fail( + `remote_mounts loads more than ${MAX_REMOTE_MOUNT_LOADED_FILES} files`, + ); + } + if (loaded + opts.inputFileCount > opts.maxInputFiles) { + fail( + `remote_mounts loaded files plus files[] exceed ${opts.maxInputFiles}`, + ); + } + return out; +} + +/** Absolute in-jail paths of every stub (file entry without bytes) of the request. */ +export function stubPaths(mounts: RemoteMount[]): Set { + const out = new Set(); + for (const mount of mounts) { + for (const entry of mount.entries) { + if (entry.type === 'file' && !entry.file) + out.add(`${mount.path}/${entry.path}`); + } + } + return out; +} + +const startMarker = (nonce: string): string => + `__CODEAPI_REMOTE_MOUNTS_V1_START__${nonce}`; +const endMarker = (nonce: string): string => + `__CODEAPI_REMOTE_MOUNTS_V1_END__${nonce}`; + +/** Removes every sentinel block carrying `nonce` from `text` (blocks with any + * other nonce stay) and returns the cleaned text plus the raw JSON payloads. */ +function stripBlocks( + text: string, + nonce: string, +): { text: string; payloads: string[] } { + const payloads: string[] = []; + const re = new RegExp( + `\\n?${startMarker(nonce)}\\n([^\\n]*)\\n${endMarker(nonce)}(?:\\n|$)`, + 'g', + ); + const cleaned = text.replace(re, (_m, payload: string) => { + payloads.push(payload); + return ''; + }); + return { text: cleaned, payloads }; +} + +/** Strips this job's sentinel blocks from each text and returns the stub paths + * they name: only stubs declared in this request, deduped, capped. */ +export function extractRemoteMountsRequired( + texts: string[], + nonce: string, + stubs: Set, +): { texts: string[]; read: string[] } { + const read = new Set(); + const cleaned = texts.map(original => { + const { text, payloads } = stripBlocks(original, nonce); + for (const payload of payloads) { + try { + const parsed = JSON.parse(payload) as { read?: unknown }; + if (!Array.isArray(parsed.read)) continue; + for (const p of parsed.read) { + if (typeof p === 'string' && stubs.has(p)) read.add(p); + } + } catch { + /* malformed block: ignore */ + } + } + return text; + }); + return { + texts: cleaned, + read: [...read].slice(0, MAX_REMOTE_MOUNTS_REPORTED), + }; +} + +/* Audit hook injected as sitecustomize. Never raises except the EACCES for a + * stub, and swallows its own errors. */ +export const PYTHON_HOOK_SOURCE = `import atexit, errno, json, os, stat, sys + +_hits = [] +try: + _mounts = [m.rstrip("/") for m in json.loads(os.environ.get("${REMOTE_MOUNTS_ENV}", "[]")) if isinstance(m, str)] + _nonce = os.environ.get("${REMOTE_MOUNTS_NONCE_ENV}", "") +except Exception: + _mounts, _nonce = [], "" + + +# Read-only system trees (imports, libraries): the sandbox user cannot plant a +# symlink there, so a path under one cannot reach a mount and skips realpath. +# Everything else (/mnt/data, /tmp, relative paths, ...) is resolved, so a +# symlink into a mount is still caught. +_SYSTEM_PREFIXES = ("/usr/", "/lib/", "/lib64/", "/opt/", "/etc/") + + +def _stub_path(path): + try: + if isinstance(path, int) or not isinstance(path, (str, bytes, os.PathLike)): + return None + p = os.path.normpath(os.path.join(os.getcwd(), os.fsdecode(os.fspath(path)))) + if not p.startswith(_SYSTEM_PREFIXES): + p = os.path.realpath(p) + if not any(p == m or p.startswith(m + "/") for m in _mounts): + return None + st = os.stat(p) + if stat.S_ISREG(st.st_mode) and (st.st_mode & 0o777) == 0 and st.st_size == 0: + return p + except Exception: + pass + return None + + +def _audit(event, args): + if event != "open" or not args: + return + p = _stub_path(args[0]) + if p is None: + return + if p not in _hits: + _hits.append(p) + raise PermissionError(errno.EACCES, p + " is not loaded yet; it is fetched for you and the code is run again") + + +def _report(): + try: + if _hits and _nonce: + err = sys.__stderr__ + err.write("\\n__CODEAPI_REMOTE_MOUNTS_V1_START__" + _nonce + "\\n" + json.dumps({"read": _hits}) + "\\n__CODEAPI_REMOTE_MOUNTS_V1_END__" + _nonce + "\\n") + err.flush() + except Exception: + pass + + +if _mounts and _nonce: + sys.addaudithook(_audit) + atexit.register(_report) +`; + +export interface MaterializedRemoteMounts { + root: string; + /** Copy-on-write binds for the jail: host source -> in-jail destination. */ + binds: Array<{ src: string; dst: string; rw?: boolean }>; + mountPaths: string[]; + /** Per tree: declared entry paths and the sha256 of each loaded file at materialize time. */ + trees: Array<{ + src: string; + /** `src` after realpath, taken once at materialize time (what /proc/self/fd must resolve under). */ + realSrc: string; + dst: string; + declared: Set; + hashes: Map; + }>; +} + +/** Hands a mount dir or loaded file to the sandbox user (see Job.ownMountPath). */ +export type OwnMountPath = ( + target: string, + type: 'file' | 'directory', +) => Promise; + +export type FetchMountObject = ( + file: RemoteMountFile, + signal?: AbortSignal, +) => Promise; + +async function writeExclusive( + file: string, + mode: number, + fill?: (handle: fsp.FileHandle) => Promise, +): Promise { + /* O_EXCL|O_NOFOLLOW: never reuse or follow anything already on disk. */ + const handle = await fsp.open( + file, + fs.constants.O_WRONLY | + fs.constants.O_CREAT | + fs.constants.O_EXCL | + fs.constants.O_NOFOLLOW, + 0o600, + ); + try { + if (fill) await fill(handle); + await handle.chmod(mode); + } finally { + await handle.close(); + } +} + +const ROOT_PREFIX = 'codeapi-remote-mounts-'; + +/** Builds each mount tree under a fresh runner-owned dir outside any workspace. + * Dirs and stubs are made first; loaded files are then fetched with at most + * `concurrency` in flight. `signal` (and the first failure) abort every fetch. */ +export async function materializeRemoteMounts( + mounts: RemoteMount[], + fetchObject: FetchMountObject, + maxFileBytes: number, + signal?: AbortSignal, + concurrency = 1, + own?: OwnMountPath, +): Promise { + const abortReason = (s: AbortSignal): Error => + s.reason instanceof Error ? s.reason : new Error('aborted'); + if (signal?.aborted) throw abortReason(signal); + const root = await fsp.mkdtemp(path.join(os.tmpdir(), ROOT_PREFIX)); + try { + await fsp.chmod(root, 0o755); + const hookDir = path.join(root, 'hook'); + await fsp.mkdir(hookDir, { mode: 0o700 }); + await writeExclusive(path.join(hookDir, 'sitecustomize.py'), 0o444, h => + h.writeFile(PYTHON_HOOK_SOURCE), + ); + const mountDirs: string[] = []; + const trees: MaterializedRemoteMounts['trees'] = []; + const binds: MaterializedRemoteMounts['binds'] = [ + { src: hookDir, dst: REMOTE_MOUNTS_HOOK_DST }, + ]; + const downloads: Array<{ + file: RemoteMountFile; + dest: string; + rel: string; + hashes: Map; + }> = []; + + for (const [i, mount] of mounts.entries()) { + const tree = path.join(root, `m${i}`); + await fsp.mkdir(tree, { mode: 0o700 }); + mountDirs.push(tree); + binds.push({ src: tree, dst: mount.path, rw: true }); + const declared = new Set(); + const hashes = new Map(); + trees.push({ + src: tree, + realSrc: await fsp.realpath(tree), + dst: mount.path, + declared, + hashes, + }); + const made = new Set(); + const ensureDir = async (rel: string): Promise => { + if (made.has(rel)) return; + const parent = path.posix.dirname(rel); + if (parent !== '.') await ensureDir(parent); + await fsp.mkdir(inside(tree, rel), { mode: 0o700 }); + made.add(rel); + mountDirs.push(inside(tree, rel)); + }; + for (const entry of mount.entries) { + if (entry.type === 'file') declared.add(entry.path); + const parent = path.posix.dirname(entry.path); + if (parent !== '.') await ensureDir(parent); + if (entry.type === 'dir') { + await ensureDir(entry.path); + } else if (entry.file) { + downloads.push({ + file: entry.file, + dest: inside(tree, entry.path), + rel: entry.path, + hashes, + }); + } else { + await writeExclusive(inside(tree, entry.path), 0o000); + } + } + } + + const controller = new AbortController(); + const onAbort = (): void => controller.abort(signal!.reason); + signal?.addEventListener('abort', onAbort, { once: true }); + if (signal?.aborted) onAbort(); // aborted during setup, before the listener existed + let failure: { error: unknown } | undefined; + let next = 0; + const worker = async (): Promise => { + while (!controller.signal.aborted) { + const job = downloads[next++]; + if (!job) return; + try { + await download(job, controller.signal); + } catch (error) { + failure ??= { error }; + controller.abort(error); + } + } + }; + const download = async ( + job: (typeof downloads)[number], + s: AbortSignal, + ): Promise => { + const response = await fetchObject(job.file, s); + try { + const digest = crypto.createHash('sha256'); + await writeExclusive(job.dest, 0o600, async h => { + let total = 0; + for await (const chunk of response.body as unknown as AsyncIterable) { + total += chunk.byteLength; + if (total > maxFileBytes) + throw new Error( + `Remote mount file exceeds ${maxFileBytes} bytes`, + ); + digest.update(chunk); + await h.write(chunk); + } + }); + job.hashes.set(job.rel, digest.digest('hex')); + } catch (error) { + await response.body?.cancel().catch(() => {}); + throw error; + } + }; + try { + await Promise.all( + Array.from( + { + length: Math.max( + 1, + Math.min(concurrency, downloads.length), + ), + }, + worker, + ), + ); + } finally { + signal?.removeEventListener('abort', onAbort); + } + if (failure) throw failure.error; + if (signal?.aborted) throw abortReason(signal); + + /* Mount trees are copy-on-write scratch: dirs and loaded files go to the + * sandbox user (stubs stay 0000 and runner-owned). Only the hook dir is sealed. */ + if (own) { + for (const dir of mountDirs) await own(dir, 'directory'); + for (const d of downloads) await own(d.dest, 'file'); + } + await fsp.chmod(hookDir, 0o555); + return { root, binds, mountPaths: mounts.map(m => m.path), trees }; + } catch (error) { + await removeRemoteMounts(root); + throw error; + } +} + +/** Resolves `rel` under `tree` and refuses anything that leaves it. */ +function inside(tree: string, rel: string): string { + const resolved = path.resolve(tree, rel); + if (!resolved.startsWith(tree + path.sep)) + throw new Error('Remote mount path escapes its tree'); + return resolved; +} + +async function unseal(dir: string): Promise { + await fsp.chmod(dir, 0o700).catch(() => {}); + for (const dirent of await fsp + .readdir(dir, { withFileTypes: true }) + .catch(() => [])) { + if (dirent.isDirectory()) await unseal(path.join(dir, dirent.name)); + } +} + +/** Removes a tree built by materializeRemoteMounts (sealed 0555 dirs included). */ +export async function removeRemoteMounts(root: string): Promise { + await unseal(root); + await fsp.rm(root, { recursive: true, force: true }); +} + +/** Startup sweep: removes `codeapi-remote-mounts-*` trees a crashed runner left in `dir`. */ +export async function sweepRemoteMountTrees( + dir: string = os.tmpdir(), +): Promise { + const names = await fsp.readdir(dir).catch(() => [] as string[]); + let removed = 0; + for (const name of names) { + if (!name.startsWith(ROOT_PREFIX)) continue; + await removeRemoteMounts(path.join(dir, name)); + removed++; + } + return removed; +} + +export interface RemoteMountChange { + hostPath: string; + /** Absolute in-jail path, e.g. /mnt/google-drive/Testing/x.xlsx. */ + mountPath: string; + name: string; + change: 'modified' | 'created'; + size: number; + /** Verified fd (see openMountFile) the upload must read from; the caller closes it. + * Absent when the file was readable by no one (modified, unhashable) or past the handle budget. */ + handle?: fsp.FileHandle; +} + +/* Bounds the post-run walk across ALL trees of a job: 5000 declared entries plus room for new ones. */ +const MAX_CHANGE_WALK_ENTRIES = 20000; + +/** Resolves an open fd to the real path it points at, or undefined when unknown. */ +export type FdPathResolver = (fd: number) => string | undefined; + +const procFdPath: FdPathResolver = fd => { + try { + return fs.readlinkSync(`/proc/self/fd/${fd}`); + } catch { + return undefined; // no /proc/self/fd (non-Linux dev machines) + } +}; + +/** True/false when the fd resolves inside/outside `root`; undefined when it cannot be resolved. */ +export function fdInsideRoot( + fd: number, + root: string, + resolve: FdPathResolver = procFdPath, +): boolean | undefined { + const real = resolve(fd); + return real === undefined ? undefined : real.startsWith(`${root}/`); +} + +/** The ONE way a mount file's content is read. Opens without following a final symlink + * and without blocking on a FIFO, requires a regular file, and ties the fd to the tree + * (/proc/self/fd must resolve under `realSrc`; without /proc, the parents-are-real-dirs + * check). The caller hashes and uploads from the returned handle and closes it; the name + * is never trusted again. */ +export async function openMountFile( + tree: { src: string; realSrc: string }, + rel: string, + resolve: FdPathResolver = procFdPath, +): Promise { + const handle = await fsp.open( + path.join(tree.src, rel), + fs.constants.O_RDONLY | + fs.constants.O_NOFOLLOW | + fs.constants.O_NONBLOCK, + ); + try { + if (!(await handle.stat()).isFile()) + throw Object.assign(new Error('not a regular file'), { + code: 'ENOTREG', + }); + const inside = fdInsideRoot(handle.fd, tree.realSrc, resolve); + if ( + inside === false || + (inside === undefined && !(await parentsAreRealDirs(tree.src, rel))) + ) + throw Object.assign(new Error('file is outside the mount tree'), { + code: 'EOUTSIDE', + }); + return handle; + } catch (error) { + await handle.close().catch(() => {}); + throw error; + } +} + +async function sha256Handle(handle: fsp.FileHandle): Promise { + const digest = crypto.createHash('sha256'); + for await (const chunk of handle.createReadStream({ + start: 0, + autoClose: false, + })) + digest.update(chunk as Buffer); + return digest.digest('hex'); +} + +/** True when every directory between `src` and `rel`'s last component is a real + * directory: lstat/O_NOFOLLOW only guard the last component, and the sandbox user + * can swap a parent for a symlink to a host path. */ +async function parentsAreRealDirs(src: string, rel: string): Promise { + const parts = rel.split('/').slice(0, -1); + let dir = src; + for (const part of parts) { + dir = path.join(dir, part); + const st = await fsp.lstat(dir).catch(() => undefined); + if (!st?.isDirectory()) return false; + } + return true; +} + +/** Loaded files are checked first by their known path (so a modification is + * found whatever the walk does), then each tree is walked with lstat only + * (symlinks, special files and dirs are never followed or reported) for new + * regular files. Stubs, deleted files and names failing the entry-path rules + * are ignored. A loaded file whose path (or a parent) became a symlink or + * special file is skipped and `onTruncated(mountPath, 'unreadable')` is called. + * Content is only ever read through openMountFile's verified fd (never from a + * walked name); the walk yields names and lstat types only. A file that cannot + * be opened for permissions counts as modified without a handle (the caller + * cannot upload it); one whose hash read fails is unreadable. Up to + * `maxHandles` (default 0) changes carry their open handle (the caller closes them). + * Hashing is streamed and not size-capped; the caller rejects an oversized + * modified file. The walk cap is one budget across all trees; a walk cut + * short by it calls `onTruncated` with the mount path and 'max_files'. */ +export async function findRemoteMountChanges( + state: MaterializedRemoteMounts, + onTruncated?: ( + mountPath: string, + reason: 'max_files' | 'unreadable', + ) => void, + resolve?: FdPathResolver, + maxHandles = 0, +): Promise { + const out: RemoteMountChange[] = []; + let visited = 0; + let kept = 0; + try { + for (const tree of state.trees) { + const reported = new Set(); + const report = ( + rel: string, + size: number, + change: 'modified' | 'created', + handle?: fsp.FileHandle, + ): boolean => { + if (reported.has(rel)) return false; + reported.add(rel); + out.push({ + hostPath: path.join(tree.src, rel), + mountPath: `${tree.dst}/${rel}`, + name: path.basename(rel), + change, + size, + handle, + }); + return true; + }; + /* Opens through the verified fd, hashes from it when `original` is + * given, and keeps the handle on the change while budget remains. */ + const readOne = async ( + rel: string, + original?: string, + ): Promise => { + const mountPath = `${tree.dst}/${rel}`; + let handle: fsp.FileHandle; + try { + handle = await openMountFile(tree, rel, resolve); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === 'ENOENT') return; + if ( + original !== undefined && + (code === 'EACCES' || code === 'EPERM') + ) { + const st = await fsp + .lstat(path.join(tree.src, rel)) + .catch(() => undefined); + if (st?.isFile()) report(rel, st.size, 'modified'); + return; + } + onTruncated?.(mountPath, 'unreadable'); + return; + } + let keep = false; + try { + if ( + original !== undefined && + (await sha256Handle(handle)) === original + ) + return; + const size = (await handle.stat()).size; + keep = + report( + rel, + size, + original === undefined ? 'created' : 'modified', + kept < maxHandles ? handle : undefined, + ) && kept < maxHandles; + if (keep) kept++; + } catch { + onTruncated?.(mountPath, 'unreadable'); + } finally { + if (!keep) await handle.close().catch(() => {}); + } + }; + for (const [rel, original] of tree.hashes) + await readOne(rel, original); + if (visited > MAX_CHANGE_WALK_ENTRIES) { + onTruncated?.(tree.dst, 'max_files'); + continue; + } + const stack: string[] = ['']; + walk: while (stack.length > 0) { + const relDir = stack.pop()!; + const dir = await fsp + .opendir(path.join(tree.src, relDir)) + .catch(() => undefined); + if (!dir) continue; + try { + for await (const dirent of dir) { + if (++visited > MAX_CHANGE_WALK_ENTRIES) { + onTruncated?.(tree.dst, 'max_files'); + break walk; + } + const name = dirent.name; + const rel = relDir ? `${relDir}/${name}` : name; + try { + validateEntryPath(rel, 'entry'); + } catch { + continue; + } + const st = await fsp + .lstat(path.join(tree.src, rel)) + .catch(() => undefined); + if (!st) continue; + if (st.isDirectory()) { + stack.push(rel); + continue; + } + if (!st.isFile()) continue; + if (tree.hashes.has(rel) || tree.declared.has(rel)) + continue; + if (kept < maxHandles) await readOne(rel); + else report(rel, st.size, 'created'); + } + } finally { + await dir.close().catch(() => {}); + } + } + } + } catch (error) { + for (const c of out) await c.handle?.close().catch(() => {}); + throw error; + } + return out; +} diff --git a/docs/remote-mounts/README.md b/docs/remote-mounts/README.md new file mode 100644 index 00000000..9186ca36 --- /dev/null +++ b/docs/remote-mounts/README.md @@ -0,0 +1,113 @@ +# Remote mounts (copy-on-write folders from a caller's remote source) + +Status: feature, opt-in per request. Callers that never send `remote_mounts` (LibreChat today) see **no change at all**: +same payload to the runner, same nsjail arguments, same response keys. + +## Why + +A caller (vitinn-ui) links a chat project to a remote folder (SharePoint, Google Drive, the next source). Code the model +runs should see that folder at a fixed path, e.g. `/mnt/google-drive/Testing/report.xlsx`, so `ls`, `os.listdir`, +`glob`, `open` and pandas work with no path rewriting. The sandbox must never hold the remote source's credentials and +must never get network access for this: the **caller** reads the remote source as the signed-in viewer, applies its own +approvals, uploads the approved bytes through the normal `/upload` path, and references them here. + +## Shape + +`POST /v1/exec` accepts an optional top-level field: + +```json +"remote_mounts": [ + { + "path": "/mnt/google-drive", + "entries": [ + { "path": "Testing", "type": "dir" }, + { "path": "Testing/data.csv", "type": "file", "size": 99, + "file": { "id": "…", "resource_id": "…", "storage_session_id": "…", "name": "data.csv", "kind": "user" } }, + { "path": "Testing/Tilboð.docx", "type": "file", "size": 23817 } + ] + } +] +``` + +- `entries` describe the tree. Parent directories of any entry are implied. +- A `file` entry **with** `file` (a `RequestFile`, same schema, validation and authorization as top-level `files[]`) + is _loaded_: its bytes appear at the path. Mounts are **copy-on-write**: code may modify loaded files and create new + files and directories, but the remote source is never touched (see "Changes come back as outputs"). +- A `file` entry **without** `file` is a _stub_: it is listed (name visible to `ls`/`os.listdir`), but reading it fails + with `EACCES`. Python code gets a clear error, and the response reports the stub so the caller can load it and run again. + +Response (only when the request had `remote_mounts`, and only when non-empty): + +```json +"remote_mounts_required": { "read": ["/mnt/google-drive/Testing/Tilboð.docx"] } +``` + +Changes come back as outputs (only when the request had `remote_mounts`): after the run, on success or non-zero exit, the +runner compares the sha256 of each loaded file with its value at materialize time and walks the tree for new regular +files. Each changed or new file is uploaded as an ordinary output object (same upload path, same per-file size limit +and the same `max_output_files` cap, shared with `/mnt/data` outputs) and listed in `files[]` with the basename as +`name` plus: + +```json +"remote_mount": { "path": "/mnt/google-drive/Testing/x.xlsx", "change": "modified" } +``` + +`change` is `modified` or `created`. Deleted files, symlinks, special files and directories are ignored (lstat, never +followed); file content is never read by name: each file is opened once (`O_NOFOLLOW|O_NONBLOCK`, must be regular, +`/proc/self/fd` must resolve under the tree's real root, else the parent-directory check off Linux) and hashed and +uploaded from that same fd, so a jail process that outlives the run cannot redirect the read; unchanged loaded files and stubs are never uploaded; names failing the entry-path rules are ignored. Requests +without `remote_mounts` never get this key (the service strips it). Saving back to the remote source is the caller's job. + +## Rules (all enforced server-side; the runner re-checks) + +- Validation failure: HTTP 400 `{ "error": "invalid_remote_mounts", "message": "" }`, before enqueue. +- 1..4 mounts. Mount `path` matches `^/mnt/[a-z0-9][a-z0-9-]{0,30}$`, is not `/mnt/data`, and is unique. +- At most 5000 entries per request (all mounts). Entry `path`: relative, `/`-separated, no empty, `.` or `..` + segment, no leading or trailing `/`, no backslash, no NUL or control character (U+0000–U+001F, U+007F), each segment + 1..255 UTF-8 bytes, whole path ≤ 1024 UTF-8 bytes, depth ≤ 16. Duplicate paths are rejected. An entry cannot be a + `file` and also a parent of another entry. +- `type` is `file` or `dir`. `size` (optional, `file` only) is a non-negative safe integer. +- `remote_mounts: null` is treated exactly like an absent key; `[]` is a 400. +- Loaded files: at most 64 per request, and loaded + top-level `files[]` ≤ 256 (the runner's default `max_input_files`; the + service caps at `min(INPUT_MANIFEST_MAX_FILES, 256)`, the runner does not count the injected source file). Each goes + through the same `authorizeRequestedFiles` check as `files[]` (a caller can only mount objects it may read). +- `remote_mounts` is accepted on `/v1/exec` only. The `remote-bridge` backend rejects it with 400 + `remote_mounts_unsupported` (fail closed). `http` and `lambda-microvm` support it. + +## In the runner + +- Per execution, the runner builds each mount tree in a fresh runner-owned directory **outside** the session + workspace (so it is never collected as output, never checkpointed, and cleaned up after the job): + created with no-follow / exclusive semantics, no symlinks. Directories (`0700`) and loaded files (`0600`) are then + handed to the sandbox user exactly like `/mnt/data` entries (same chown helper, per-job uid); stubs stay empty, + mode `0000`, owned by the runner. Only the hook directory is sealed `0555`. +- Loaded bytes are fetched exactly like other input refs (file-server / egress gateway, or the pushed input cache on + `lambda-microvm`), with the same size limits. +- Each tree is bind-mounted **read-write** (`nodev`, `nosuid`, `noexec`) into the jail at its `path`. +- Disk bound: trees live under the runner's temp dir, which is the same size-limited tmpfs (`size=1g` on `/tmp`, + `entrypoint.sh`) that holds the per-job `/mnt/data` workspaces (`/tmp/sandbox`), so writes into a mount count against + the same filesystem limit as `/mnt/data`; `rlimit_fsize` bounds each file. The post-run walk is bounded (20000 + entries, one budget shared by all trees of the job) and only files up to `max_file_size` are uploaded; larger ones are reported in `artifact_truncation`. +- Mount fetches use the job's abort signal and the prime concurrency setting; a failed or aborted job leaves no tree. + On startup the runner removes leftover `codeapi-remote-mounts-*` trees in the temp dir. +- Python: when the request has `remote_mounts`, a runner-owned read-only `sitecustomize` directory is added to + `PYTHONPATH` (so `python3` started from bash gets it too). It installs an audit hook (`sys.addaudithook`, cannot be + removed by user code) that turns an `open` of a stub into `PermissionError(EACCES, " is not loaded yet; …")` + and, at interpreter exit, writes the stub paths it hit to stderr between execution-scoped sentinel lines. +- The runner strips those sentinel lines from stderr, keeps only paths that are stubs **of this request** (so a forged + sentinel can request nothing new), de-duplicates, caps at 64, and returns them as `remote_mounts_required`. +- Other languages: a stub read fails with `EACCES` (no report). Callers answer shell looks themselves. + +## Security notes + +- No credentials, tokens or network paths enter the sandbox. Bytes only come from objects the caller uploaded and + is authorized to read. +- Mounts are copy-on-write scratch; the remote source is never written by the sandbox. Stubs stay unreadable and + unwritable (opening one for write raises `EACCES` and is reported like a read). +- A forged or tampered report can only name stubs the caller itself declared; the caller re-checks its own approvals + before loading anything. + +## Rollout + +Deploy the runner and the egress gateway before the API/worker. An old gateway does not mask mount refs, so the runner +rejects the request with `scope_mismatch` (fails closed). diff --git a/service/openapi.yml b/service/openapi.yml index 929fab71..4f8646c3 100644 --- a/service/openapi.yml +++ b/service/openapi.yml @@ -112,6 +112,23 @@ components: type: string path: type: string + remote_mount: + type: object + description: >- + Present only when the request had `remote_mounts`. This output was + copied out of a mount (mounts are copy-on-write; the remote source is + never touched): `path` is the absolute sandbox path, `change` is + `modified` for a loaded file whose bytes changed and `created` for a + new regular file. The caller decides whether to save it back. + properties: + path: + type: string + change: + type: string + enum: [modified, created] + required: + - path + - change RequestFile: type: object @@ -170,6 +187,58 @@ components: type: array items: $ref: '#/components/schemas/FileRef' + remote_mounts_required: + type: object + description: >- + Present only when the request had `remote_mounts` and user code + tried to read stub entries. `read` lists the absolute sandbox paths + (at most 64) so the caller can load them and run again. + properties: + read: + type: array + items: + type: string + required: + - read + + RemoteMountEntry: + type: object + required: + - path + - type + properties: + path: + type: string + description: >- + Path relative to the mount, `/`-separated. No empty, `.` or `..` + segment, no leading or trailing `/`, no backslash, no NUL or + control character; each segment 1..255 UTF-8 bytes, whole path at + most 1024 bytes, depth at most 16. Unique within the mount. A file + entry cannot be the parent of another entry. + type: + type: string + enum: [file, dir] + size: + type: integer + minimum: 0 + description: Optional, `file` entries only. A non-negative safe integer. + file: + $ref: '#/components/schemas/RequestFile' + + RemoteMount: + type: object + required: + - path + - entries + properties: + path: + type: string + pattern: '^/mnt/[a-z0-9][a-z0-9-]{0,30}$' + description: Mount point in the sandbox. Not `/mnt/data`; unique per request. + entries: + type: array + items: + $ref: '#/components/schemas/RemoteMountEntry' RequestBody: type: object @@ -212,6 +281,23 @@ components: Stable opaque hint for stateful runtime reuse. The server binds it to the authenticated tenant and user. Required in strict runtime session mode and ignored by the default stateless profile. + remote_mounts: + type: array + minItems: 1 + maxItems: 4 + items: + $ref: '#/components/schemas/RemoteMount' + description: >- + Optional read-only folder trees mounted in the sandbox at each + mount `path`. A `file` entry with `file` is loaded (its bytes + appear read-only, authorized like `files[]`); one without is a stub + that is listed but fails with EACCES when read. At most 5000 + entries in total and 64 loaded files; loaded files count toward the + same input-file limit as `files[]` (combined cap 256 input files). A + `null` value is treated as absent. Failures return 400 + `invalid_remote_mounts` with a `message`. The `remote-bridge` + backend returns 400 `remote_mounts_unsupported`. Not accepted on + `/exec/programmatic`. Omitting the field changes nothing. FileObject: type: object diff --git a/service/src/egress-grant.test.ts b/service/src/egress-grant.test.ts index cd26fcd7..6abbec3c 100644 --- a/service/src/egress-grant.test.ts +++ b/service/src/egress-grant.test.ts @@ -249,6 +249,54 @@ describe('egress encrypted grants and handles', () => { }); }); + test('scopes and masks loaded remote-mount refs like files[] refs', () => { + const payload: t.PayloadBody = { + language: 'python', + version: '3.14.4', + session_id: 'sess_output', + files: [{ name: 'main.py', content: 'print(1)' }], + remote_mounts: [{ + path: '/mnt/google-drive', + entries: [ + { path: 'a.csv', type: 'file', file: { id: 'mount_file', storage_session_id: 'mount_sess', name: 'a.csv' } }, + { path: 'stub.docx', type: 'file', size: 3 }, + ], + }], + }; + const prepared = prepareSandboxEgress({ payload, grantId: GRANT_ID, claims: claims(), secret: SECRET }); + + expect(JSON.stringify(prepared.payload)).not.toContain('mount_file'); + expect(JSON.stringify(prepared.payload)).not.toContain('mount_sess'); + const masked = prepared.payload.remote_mounts![0].entries[0].file!; + expect(masked.name).toBe('a.csv'); + expect(openEgressHandle(masked.id, SECRET, 150)).toMatchObject({ + typ: 'object', + object_id: 'mount_file', + session_id: 'mount_sess', + }); + expect(openEgressHandle(masked.storage_session_id, SECRET, 150)).toMatchObject({ + typ: 'session', + dir: 'read', + session_id: 'mount_sess', + }); + expect(prepared.payload.remote_mounts![0].entries[1]).toEqual({ path: 'stub.docx', type: 'file', size: 3 }); + expect(prepared.executionManifestClaims.read_sessions).toContain( + (prepared.executionManifestClaims.input_files ?? []).find(f => f.name === 'a.csv')!.session_id, + ); + expect(prepared.executionManifestClaims.input_files).toHaveLength(1); + }); + + test('without remote_mounts the masked payload has no remote_mounts key', () => { + const payload: t.PayloadBody = { + language: 'python', + version: '3.14.4', + session_id: 'sess_output', + files: [{ id: 'file_123', storage_session_id: 'sess_input', name: 'inputs/data.csv' }], + }; + const prepared = prepareSandboxEgress({ payload, grantId: GRANT_ID, claims: claims(), secret: SECRET }); + expect('remote_mounts' in prepared.payload).toBe(false); + }); + test('uses a short per-dispatch sandbox session id for workspace isolation', () => { const longOutputSessionId = `sess_${'x'.repeat(180)}`; const longClaims = claims({ output_session_id: longOutputSessionId }); diff --git a/service/src/egress-grant.ts b/service/src/egress-grant.ts index 8148bec7..fad79185 100644 --- a/service/src/egress-grant.ts +++ b/service/src/egress-grant.ts @@ -1,6 +1,7 @@ import crypto from 'crypto'; import type { ExecutionManifestClaims, ExecutionManifestInputFile } from './execution-manifest'; import type * as t from './types'; +import { payloadRemoteMountFiles } from './service/remote-mounts'; export const EGRESS_GRANT_HEADER = 'X-CodeAPI-Egress-Grant'; export const EGRESS_ERROR_CODE_HEADER = 'X-CodeAPI-Error-Code'; @@ -364,8 +365,7 @@ function sandboxWorkspaceSessionId(): string { } function collectMaskedInputFiles(payload: t.PayloadBody): ExecutionManifestInputFile[] { - return payload.files - .filter(isPayloadFileRef) + return [...payload.files.filter(isPayloadFileRef), ...payloadRemoteMountFiles(payload)] .map(file => ({ id: file.id, session_id: file.storage_session_id, name: file.name })) .sort((a, b) => ( a.session_id.localeCompare(b.session_id) || @@ -401,27 +401,32 @@ export function prepareSandboxEgress(args: { return handle; }; + const maskRef = (file: t.PayloadFileRef): t.PayloadFileRef => ({ + id: sealEgressHandle({ + typ: 'object', + dir: 'read', + grant_id: args.grantId, + exec_id: claims.exec_id, + session_id: file.storage_session_id, + object_id: file.id, + name: file.name, + iat: now, + exp: claims.exp, + }, secret), + storage_session_id: readSessionHandle(file.storage_session_id), + name: file.name, + }); + const maskedPayload: t.PayloadBody = { ...args.payload, - files: args.payload.files.map(file => { - if (!isPayloadFileRef(file)) return { ...file }; - return { - id: sealEgressHandle({ - typ: 'object', - dir: 'read', - grant_id: args.grantId, - exec_id: claims.exec_id, - session_id: file.storage_session_id, - object_id: file.id, - name: file.name, - iat: now, - exp: claims.exp, - }, secret), - storage_session_id: readSessionHandle(file.storage_session_id), - name: file.name, - }; - }), + files: args.payload.files.map(file => (isPayloadFileRef(file) ? maskRef(file) : { ...file })), }; + if (args.payload.remote_mounts) { + maskedPayload.remote_mounts = args.payload.remote_mounts.map(mount => ({ + path: mount.path, + entries: mount.entries.map(entry => (entry.file ? { ...entry, file: maskRef(entry.file) } : { ...entry })), + })); + } const outputSessionHandle = sealEgressHandle({ typ: 'session', diff --git a/service/src/execution-manifest-claims.ts b/service/src/execution-manifest-claims.ts index bed6d97d..aecc381b 100644 --- a/service/src/execution-manifest-claims.ts +++ b/service/src/execution-manifest-claims.ts @@ -1,6 +1,7 @@ import { env } from './config'; import type * as t from './types'; import { buildExecutionIdentity } from './execution-identity'; +import { payloadRemoteMountFiles } from './service/remote-mounts'; import { EXECUTION_MANIFEST_VERSION, type ExecutionManifestClaims, @@ -30,8 +31,7 @@ function isPayloadFileRef(file: t.PayloadBody['files'][number]): file is Payload } export function collectManifestInputFiles(payload: t.PayloadBody): ExecutionManifestInputFile[] { - return payload.files - .filter(isPayloadFileRef) + return [...payload.files.filter(isPayloadFileRef), ...payloadRemoteMountFiles(payload)] .map(file => ({ id: file.id, session_id: file.storage_session_id, name: file.name })) .sort((a, b) => ( a.session_id.localeCompare(b.session_id) || diff --git a/service/src/execution-manifest.test.ts b/service/src/execution-manifest.test.ts index 80f382fc..334c7015 100644 --- a/service/src/execution-manifest.test.ts +++ b/service/src/execution-manifest.test.ts @@ -194,6 +194,49 @@ describe('execution manifest claim construction', () => { expect(built.exp).toBeGreaterThan(100); }); + test('scopes loaded remote-mount refs like files[] refs', () => { + const payload: t.PayloadBody = { + language: 'python', + version: '3.12.0', + files: [ + { name: 'main.py', content: 'print(1)' }, + { id: 'file_b', storage_session_id: 'sess_b', name: 'b.csv' }, + ], + remote_mounts: [{ + path: '/mnt/google-drive', + entries: [ + { path: 'a.csv', type: 'file', file: { id: 'file_a', storage_session_id: 'sess_a', name: 'a.csv' } }, + { path: 'stub.docx', type: 'file', size: 1 }, + ], + }], + }; + expect(collectManifestInputFiles(payload)).toEqual([ + { id: 'file_a', session_id: 'sess_a', name: 'a.csv' }, + { id: 'file_b', session_id: 'sess_b', name: 'b.csv' }, + ]); + const { remote_mounts: _omitted, ...without } = payload; + expect(collectManifestInputFiles(without)).toEqual([ + { id: 'file_b', session_id: 'sess_b', name: 'b.csv' }, + ]); + }); + + test('pins the input_files shape the API manifest test uses for a loaded mount ref', () => { + // Literal mirror of api/src/execution-manifest-request.test.ts serviceClaims(). + expect(collectManifestInputFiles({ + language: 'python', + version: '3.12', + session_id: 'sess_output', + files: [{ name: 'main.py', content: 'x' }], + remote_mounts: [{ + path: '/mnt/google-drive', + entries: [ + { path: 'a.csv', type: 'file', file: { id: 'drive_1', storage_session_id: 'sess_drive', name: 'a.csv' } }, + { path: 'stub.docx', type: 'file' }, + ], + }], + })).toEqual([{ id: 'drive_1', session_id: 'sess_drive', name: 'a.csv' }]); + }); + test('marks tool-call socket access as an explicit signed claim', () => { const payload: t.PayloadBody = { language: 'python', diff --git a/service/src/payload.test.ts b/service/src/payload.test.ts new file mode 100644 index 00000000..9fa5f0bb --- /dev/null +++ b/service/src/payload.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, test } from 'bun:test'; +import type * as t from './types'; +import { createPayload } from './payload'; + +function build(body: Partial): t.PayloadBody { + const req = { + body: { lang: 'py', code: 'print(1)', ...body }, + } as unknown as t.AuthenticatedRequest; + return createPayload({ req, isPyPlot: false, session_id: 'sess_1' }); +} + +const file = (id: string, name: string): t.RequestFile => ({ + id, + resource_id: 'res', + storage_session_id: `s_${id}`, + name, + kind: 'user', +}); + +describe('createPayload remote_mounts', () => { + test("a request without remote_mounts yields exactly today's payload keys", () => { + const payload = build({ files: [file('f1', 'a.csv')] }); + expect(Object.keys(payload).sort()).toEqual( + [ + 'files', + 'language', + 'run_memory_limit', + 'session_id', + 'version', + ].sort(), + ); + expect('remote_mounts' in payload).toBe(false); + }); + + test('remote_mounts: null yields no remote_mounts key', () => { + const payload = build({ remote_mounts: null as unknown as undefined }); + expect('remote_mounts' in payload).toBe(false); + }); + + test('maps loaded refs to runner refs and keeps stubs and dirs', () => { + const payload = build({ + remote_mounts: [ + { + path: '/mnt/google-drive', + entries: [ + { path: 'T', type: 'dir' }, + { + path: 'T/a.csv', + type: 'file', + size: 9, + file: file('f2', 'a.csv'), + }, + { path: 'T/b.docx', type: 'file', size: 4 }, + ], + }, + ], + }); + expect(payload.remote_mounts).toEqual([ + { + path: '/mnt/google-drive', + entries: [ + { path: 'T', type: 'dir' }, + { + path: 'T/a.csv', + type: 'file', + size: 9, + file: { + id: 'f2', + storage_session_id: 's_f2', + name: 'a.csv', + }, + }, + { path: 'T/b.docx', type: 'file', size: 4 }, + ], + }, + ]); + expect(JSON.stringify(payload.remote_mounts)).not.toContain( + 'resource_id', + ); + }); +}); diff --git a/service/src/payload.ts b/service/src/payload.ts index 8a849e4a..c12d6ad6 100644 --- a/service/src/payload.ts +++ b/service/src/payload.ts @@ -10,7 +10,7 @@ export function createPayload({ isPyPlot, session_id, }: t.CreatePayload): t.PayloadBody { - const { lang: rawLang, code: userCode, args, files } = req.body as t.RequestBody; + const { lang: rawLang, code: userCode, args, files, remote_mounts } = req.body as t.RequestBody; const language = resolveLanguage(rawLang); if (language === undefined) { throw new Error(`Unsupported language: ${rawLang}`); @@ -65,5 +65,16 @@ export function createPayload({ }); } + if (remote_mounts) { + /* Only when the request carried `remote_mounts`: no key otherwise, so + * callers that never send it get a byte-identical runner payload. */ + payload.remote_mounts = remote_mounts.map(mount => ({ + path: mount.path, + entries: mount.entries.map(({ file, ...entry }) => (file + ? { ...entry, file: { id: file.id, storage_session_id: file.storage_session_id, name: file.name } } + : entry)), + })); + } + return payload; } \ No newline at end of file diff --git a/service/src/runtime-session/input-delivery.test.ts b/service/src/runtime-session/input-delivery.test.ts index 52e3f197..b9fb033e 100644 --- a/service/src/runtime-session/input-delivery.test.ts +++ b/service/src/runtime-session/input-delivery.test.ts @@ -74,6 +74,48 @@ describe('prepareInputDelivery', () => { expect(JSON.stringify(first.payload)).not.toContain('raw-session'); }); + test('delivers loaded remote-mount refs like files[] refs, masked and cache-keyed', () => { + const authorized: t.PayloadBody = { + ...payload(), + remote_mounts: [{ + path: '/mnt/google-drive', + entries: [ + { path: 'd', type: 'dir' }, + { path: 'd/a.csv', type: 'file', file: { id: 'mount-file', storage_session_id: 'mount-session', name: 'a.csv' } }, + { path: 'd/stub.docx', type: 'file', size: 3 }, + // same object as files[0]: one delivery, not two + { path: 'd/dup.csv', type: 'file', file: { id: 'raw-file', storage_session_id: 'raw-session', name: 'data.csv' } }, + ], + }], + }; + const masked = prepareSandboxEgress({ + payload: authorized, + claims: claims(), + grantId: 'grant_1', + secret: SECRET, + }).payload; + + const out = prepareInputDelivery(authorized, masked); + const mountRef = out.payload.remote_mounts![0].entries[1].file!; + expect(mountRef.input_cache_key).toBe(inputCacheKey('mount-session', 'mount-file')); + expect(out.payload.remote_mounts![0].entries[2].file).toBeUndefined(); + expect(out.refs.map(r => r.id)).toEqual(['raw-file', 'mount-file']); + expect(JSON.stringify(out.payload)).not.toContain('mount-file'); + expect(JSON.stringify(out.payload)).not.toContain('mount-session'); + }); + + test('without remote_mounts the delivered payload has no remote_mounts key', () => { + const authorized = payload(); + const masked = prepareSandboxEgress({ + payload: authorized, + claims: claims(), + grantId: 'grant_1', + secret: SECRET, + }).payload; + expect('remote_mounts' in masked).toBe(false); + expect('remote_mounts' in prepareInputDelivery(authorized, masked).payload).toBe(false); + }); + test('rejects a gateway response that changes file ordering or shape', () => { const authorized = payload(); expect(() => prepareInputDelivery(authorized, { diff --git a/service/src/runtime-session/input-delivery.ts b/service/src/runtime-session/input-delivery.ts index 6d4432ad..9de514bb 100644 --- a/service/src/runtime-session/input-delivery.ts +++ b/service/src/runtime-session/input-delivery.ts @@ -1,6 +1,7 @@ import type * as t from '../types'; import type { SandboxInputDeliveryRef } from '../sandbox-backend/types'; import { inputCacheKey } from './files'; +import { payloadRemoteMountFiles } from '../service/remote-mounts'; function isFileRef(file: t.PayloadBody['files'][number]): file is t.PayloadFileRef { return 'id' in file && typeof file.id === 'string'; @@ -20,17 +21,14 @@ export function prepareInputDelivery( throw new Error('Sandbox egress changed the input file count'); } + const mountFiles = payloadRemoteMountFiles(authorized); + if (mountFiles.length !== payloadRemoteMountFiles(sandboxVisible).length) { + throw new Error('Sandbox egress changed the remote mount file count'); + } + const refs: SandboxInputDeliveryRef[] = []; const seen = new Set(); - const files = sandboxVisible.files.map((sandboxFile, index) => { - const authorizedFile = authorized.files[index]; - const authorizedIsRef = isFileRef(authorizedFile); - const sandboxIsRef = isFileRef(sandboxFile); - if (authorizedIsRef !== sandboxIsRef || authorizedFile.name !== sandboxFile.name) { - throw new Error(`Sandbox egress changed files[${index}] shape or destination`); - } - if (!authorizedIsRef || !sandboxIsRef) return { ...sandboxFile }; - + const cacheKeyFor = (authorizedFile: t.PayloadFileRef): string => { const cacheKey = inputCacheKey( authorizedFile.storage_session_id, authorizedFile.id, @@ -44,8 +42,37 @@ export function prepareInputDelivery( cache_key: cacheKey, }); } - return { ...sandboxFile, input_cache_key: cacheKey }; + return cacheKey; + }; + const files = sandboxVisible.files.map((sandboxFile, index) => { + const authorizedFile = authorized.files[index]; + const authorizedIsRef = isFileRef(authorizedFile); + const sandboxIsRef = isFileRef(sandboxFile); + if (authorizedIsRef !== sandboxIsRef || authorizedFile.name !== sandboxFile.name) { + throw new Error(`Sandbox egress changed files[${index}] shape or destination`); + } + if (!authorizedIsRef || !sandboxIsRef) return { ...sandboxFile }; + + return { ...sandboxFile, input_cache_key: cacheKeyFor(authorizedFile) }; }); - return { payload: { ...sandboxVisible, files }, refs }; + /* Loaded remote-mount refs ride the same cache: same key, same single + * delivery per object, matched to the egress-masked copy by position. */ + let mountIndex = 0; + const remoteMounts = sandboxVisible.remote_mounts?.map(mount => ({ + ...mount, + entries: mount.entries.map(entry => { + if (!entry.file) return { ...entry }; + const authorizedFile = mountFiles[mountIndex++]; + if (authorizedFile.name !== entry.file.name) { + throw new Error(`Sandbox egress changed remote mount ${mount.path} destination`); + } + return { ...entry, file: { ...entry.file, input_cache_key: cacheKeyFor(authorizedFile) } }; + }), + })); + + return { + payload: { ...sandboxVisible, files, ...(remoteMounts ? { remote_mounts: remoteMounts } : {}) }, + refs, + }; } diff --git a/service/src/sandbox-backend/lambda-microvm.test.ts b/service/src/sandbox-backend/lambda-microvm.test.ts index 015b3a92..f1f69652 100644 --- a/service/src/sandbox-backend/lambda-microvm.test.ts +++ b/service/src/sandbox-backend/lambda-microvm.test.ts @@ -18,6 +18,7 @@ import { setRedisForTests as setRegistryRedis, writeRuntimeSessionRecord, } from '../runtime-session/registry'; +import { inputCacheKey } from '../runtime-session/files'; import { MemoryCheckpointStore, checkpointObjectKey, checkpointPrefixFor } from '../runtime-session/checkpoint-store'; import { LambdaMicrovmSandboxBackend, @@ -1200,6 +1201,25 @@ describe('LambdaMicrovmSandboxBackend session execution', () => { expect(untarred).not.toContain('inputs/data.csv'); }); + test('probes loaded remote-mount refs exactly like files[] refs (stubs are not delivered)', async () => { + const fake = fakeClient(); + const backend = makeBackend(fake); + const req = request(); + req.body.remote_mounts = [{ + path: '/mnt/google-drive', + entries: [ + { path: 'a.csv', type: 'file', file: { id: 'file_2', storage_session_id: 'sess_store_2', name: 'a.csv' } }, + { path: 'stub.docx', type: 'file', size: 5 }, + ], + }]; + await backend.execute(req, sessionContext()); + + expect(lastProbedRefs.map((r) => r.cache_key)).toEqual([ + inputCacheKey('sess_store_1', 'file_1'), + inputCacheKey('sess_store_2', 'file_2'), + ]); + }); + test('a second execution pushes nothing when the VM already holds the object', async () => { const fake = fakeClient(); const backend = makeBackend(fake); diff --git a/service/src/sandbox-backend/lambda-microvm.ts b/service/src/sandbox-backend/lambda-microvm.ts index 6e59d773..d32472d3 100644 --- a/service/src/sandbox-backend/lambda-microvm.ts +++ b/service/src/sandbox-backend/lambda-microvm.ts @@ -38,6 +38,7 @@ import { import { injectTraceHeaders, withSpan } from '../telemetry'; import { SandboxBackendError } from './types'; import { Jobs } from '../enum'; +import { payloadRemoteMountFiles } from '../service/remote-mounts'; import { checkpointPipelineBudgetMs } from '../config'; import logger from '../logger'; @@ -1233,7 +1234,7 @@ export class LambdaMicrovmSandboxBackend implements SandboxBackend { ctx: SandboxExecuteContext, onUnhealthy?: () => Promise, ): Promise { - const refs = req.inputDelivery ?? sessionFileRefs(req.body.files); + const refs = req.inputDelivery ?? sessionFileRefs([...req.body.files, ...payloadRemoteMountFiles(req.body)]); if (refs.length === 0) return; if (refs.length > SESSION_INPUTS_MAX_COUNT) { throw new SessionFilesError( diff --git a/service/src/service/programmatic-router.ts b/service/src/service/programmatic-router.ts index 86b1cdbb..d1ba4170 100644 --- a/service/src/service/programmatic-router.ts +++ b/service/src/service/programmatic-router.ts @@ -98,6 +98,7 @@ import { BRIDGE_WORKSPACE_PROGRAMMATIC_MAX_INPUT_FILES, } from '../../../packages/code/src/protocol'; import logger from '../logger'; +import { remoteMountsPresent } from './remote-mounts'; import { type ExecutionState, type HistoryEntry, @@ -1294,6 +1295,12 @@ router.post( if (rawRequestId != null && requestId == null) { return res.status(400).json({ error: 'Invalid programmatic request ID' }); } + if (remoteMountsPresent(rawBody.remote_mounts)) { + return res.status(400).json({ + error: 'invalid_remote_mounts', + message: 'remote_mounts is not supported on programmatic', + }); + } const requestedLanguage: unknown = rawBody.language ?? rawBody.lang; let bridgeWorkerId: string | undefined; let workspaceId: string | undefined; diff --git a/service/src/service/remote-mounts.test.ts b/service/src/service/remote-mounts.test.ts new file mode 100644 index 00000000..45bb36aa --- /dev/null +++ b/service/src/service/remote-mounts.test.ts @@ -0,0 +1,330 @@ +import { describe, expect, test } from 'bun:test'; +import { + gateRemoteMounts, + RUNNER_MAX_INPUT_FILES, + loadedRemoteMountFiles, + relabelMountFileError, + remoteMountsPresent, + remoteMountsRequiredField, + gateRemoteMountFiles, + validateRemoteMounts, + withAuthorizedMountFiles, +} from './remote-mounts'; +import { FileRefAuthorizationError } from './file-authorization'; + +const file = { + id: 'f1', + resource_id: 'r1', + storage_session_id: 's1', + name: 'data.csv', + kind: 'user' as const, +}; +const mount = (entries: unknown[], path: unknown = '/mnt/google-drive') => ({ + path, + entries, +}); +const one = (entries: unknown[], path?: string) => + validateRemoteMounts([mount(entries, path)]); + +function reject(value: unknown, reason: RegExp) { + const r = validateRemoteMounts(value); + expect(r.ok).toBe(false); + if (!r.ok) expect(r.reason).toMatch(reason); +} + +describe('validateRemoteMounts accepts', () => { + test('dirs, loaded files and stubs', () => { + const r = one([ + { path: 'Testing', type: 'dir' }, + { path: 'Testing/data.csv', type: 'file', size: 99, file }, + { path: 'Testing/Tilboð.docx', type: 'file', size: 0 }, + { path: 'deep/implied/parent.txt', type: 'file' }, + ]); + expect(r.ok).toBe(true); + if (r.ok) { + expect(r.mounts).toHaveLength(1); + expect(r.mounts[0].entries).toHaveLength(4); + expect(loadedRemoteMountFiles(r.mounts)).toEqual([file]); + } + }); + test('up to 4 mounts, mount with no entries', () => { + const paths = ['/mnt/a', '/mnt/b', '/mnt/c', '/mnt/d']; + expect(validateRemoteMounts(paths.map(p => mount([], p))).ok).toBe( + true, + ); + }); + test('boundary lengths: 255-byte segment, 1024-byte path, depth 16', () => { + expect(one([{ path: 'a'.repeat(255), type: 'file' }]).ok).toBe(true); + const p1024 = [ + ...Array(3).fill('a'.repeat(255)), + 'a'.repeat(254), + 'b', + ].join('/'); + expect(Buffer.byteLength(p1024)).toBe(1024); + expect(one([{ path: p1024, type: 'file' }]).ok).toBe(true); + expect( + one([{ path: Array(16).fill('d').join('/'), type: 'dir' }]).ok, + ).toBe(true); + }); + test('5000 entries and 64 loaded files', () => { + const many = Array.from({ length: 5000 }, (_, i) => ({ + path: `f${i}`, + type: 'file', + })); + expect(one(many).ok).toBe(true); + const loaded = Array.from({ length: 64 }, (_, i) => ({ + path: `f${i}`, + type: 'file', + file, + })); + expect(one(loaded).ok).toBe(true); + }); +}); + +describe('validateRemoteMounts rejects', () => { + test('non-array, empty, >4 mounts, non-object mount', () => { + reject(null, /array/); + reject({}, /array/); + reject([], /1\.\.4/); + reject( + ['/mnt/a', '/mnt/b', '/mnt/c', '/mnt/d', '/mnt/e'].map(p => + mount([], p), + ), + /1\.\.4/, + ); + reject(['x'], /object/); + reject([{ path: '/mnt/a' }], /entries/); + }); + test('mount path regex, /mnt/data, duplicates', () => { + for (const p of [ + '/mnt/', + '/mnt/A', + '/mnt/-a', + '/mnt/a/b', + 'mnt/a', + '/mnt/' + 'a'.repeat(32), + '/tmp/a', + 5, + ]) { + reject([mount([], p)], /mount path/); + } + expect( + validateRemoteMounts([mount([], '/mnt/' + 'a'.repeat(31))]).ok, + ).toBe(true); + reject([mount([], '/mnt/data')], /\/mnt\/data/); + reject([mount([], '/mnt/a'), mount([], '/mnt/a')], /duplicate mount/); + }); + test('entry path traversal and shape', () => { + const bad = [ + '..', + 'a/../b', + '.', + 'a/./b', + '/abs', + 'a/', + 'a//b', + '', + 'a\\b', + 'a\0b', + 'a\nb', + 'a\x7fb', + 'a\x1fb', + ]; + for (const p of bad) + reject([mount([{ path: p, type: 'file' }])], /entry path/); + reject([mount([{ path: 5, type: 'file' }])], /entry path/); + }); + test('segment, path and depth limits', () => { + reject([mount([{ path: 'a'.repeat(256), type: 'file' }])], /segment/); + reject([mount([{ path: 'é'.repeat(128), type: 'file' }])], /segment/); + const p1025 = [...Array(4).fill('a'.repeat(255)), 'b'].join('/'); + reject([mount([{ path: p1025, type: 'file' }])], /1024/); + reject( + [mount([{ path: Array(17).fill('d').join('/'), type: 'dir' }])], + /depth/, + ); + }); + test('duplicates and file-as-parent', () => { + reject( + [ + mount([ + { path: 'a', type: 'dir' }, + { path: 'a', type: 'dir' }, + ]), + ], + /duplicate entry/, + ); + reject( + [ + mount([ + { path: 'a', type: 'file' }, + { path: 'a/b', type: 'file' }, + ]), + ], + /parent/, + ); + reject( + [ + mount([ + { path: 'a/b', type: 'file' }, + { path: 'a', type: 'file' }, + ]), + ], + /parent/, + ); + reject( + [ + mount([ + { path: 'a/b/c', type: 'file' }, + { path: 'a/b', type: 'dir' }, + { path: 'a', type: 'file' }, + ]), + ], + /parent/, + ); + }); + test('entry limit across mounts', () => { + const many = Array.from({ length: 2501 }, (_, i) => ({ + path: `f${i}`, + type: 'file', + })); + reject([mount(many, '/mnt/a'), mount(many, '/mnt/b')], /5000/); + }); + test('loaded file limit', () => { + const loaded = Array.from({ length: 65 }, (_, i) => ({ + path: `f${i}`, + type: 'file', + file, + })); + reject([mount(loaded)], /64/); + }); + test('size must be a safe non-negative integer on files only', () => { + for (const size of [ + -1, + 1.5, + NaN, + Infinity, + '5', + Number.MAX_SAFE_INTEGER + 1, + null, + ]) { + reject([mount([{ path: 'a', type: 'file', size }])], /size/); + } + expect( + one([{ path: 'a', type: 'file', size: Number.MAX_SAFE_INTEGER }]) + .ok, + ).toBe(true); + reject([mount([{ path: 'a', type: 'dir', size: 1 }])], /size/); + }); + test('type and file field', () => { + reject([mount([{ path: 'a', type: 'symlink' }])], /type/); + reject([mount([{ path: 'a' }])], /type/); + reject([mount([{ path: 'a', type: 'dir', file }])], /file/); + reject([mount([{ path: 'a', type: 'file', file: 'x' }])], /file/); + reject([mount([{ path: 'a', type: 'file', file: null }])], /file/); + reject([mount(['x'])], /entry/); + }); +}); + +describe('helpers', () => { + test('withAuthorizedMountFiles swaps in the authorized refs in order', () => { + const r = one([ + { path: 'a', type: 'file', file }, + { path: 'b', type: 'file' }, + { path: 'c', type: 'file', file }, + ]); + if (!r.ok) throw new Error('setup'); + const auth = [ + { ...file, id: 'A' }, + { ...file, id: 'C' }, + ] as never; + const out = withAuthorizedMountFiles(r.mounts, auth); + expect(loadedRemoteMountFiles(out).map(f => f.id)).toEqual(['A', 'C']); + expect(out[0].entries[1].file).toBeUndefined(); + }); + test('remoteMountsRequiredField passes through only when requested and non-empty', () => { + const req = { read: ['/mnt/x/a'] }; + expect(remoteMountsRequiredField(true, req)).toEqual({ + remote_mounts_required: req, + }); + expect(remoteMountsRequiredField(false, req)).toEqual({}); + expect(remoteMountsRequiredField(true, { read: [] })).toEqual({}); + expect(remoteMountsRequiredField(true, undefined)).toEqual({}); + expect(remoteMountsRequiredField(true, { read: 'x' })).toEqual({}); + }); + test('gateRemoteMountFiles keeps a well-formed remote_mount only when requested', () => { + const rm = { path: '/mnt/g/a.txt', change: 'created' }; + const files = [ + { id: '1', name: 'a.txt', remote_mount: rm }, + { id: '2', name: 'b.txt', remote_mount: { path: 5, change: 'created' } }, + { id: '3', name: 'c.txt', remote_mount: { path: '/mnt/g/c', change: 'deleted' } }, + { id: '4', name: 'd.txt' }, + ] as never; + const on = gateRemoteMountFiles(true, files) as Array>; + expect(on.map(f => f.remote_mount)).toEqual([rm, undefined, undefined, undefined]); + expect(on.every((f, i) => i === 0 || !('remote_mount' in f))).toBe(true); + const off = gateRemoteMountFiles(false, files) as Array>; + expect(off.some(f => 'remote_mount' in f)).toBe(false); + expect(off.map(f => f.id)).toEqual(['1', '2', '3', '4']); + }); +}); + +describe('gateRemoteMounts', () => { + const value = [mount([{ path: 'a', type: 'file', file }])]; + const base = { value, backend: 'http', topLevelFiles: 0, maxInputFiles: 512 }; + + test('accepts on http and lambda-microvm', () => { + expect(gateRemoteMounts(base).ok).toBe(true); + expect(gateRemoteMounts({ ...base, backend: 'lambda-microvm' }).ok).toBe(true); + }); + test('remote-bridge fails closed, before validating', () => { + expect(gateRemoteMounts({ ...base, backend: 'remote-bridge', value: 'junk' })).toEqual({ + ok: false, + body: { error: 'remote_mounts_unsupported' }, + }); + }); + test('a validation failure is invalid_remote_mounts with the reason', () => { + const r = gateRemoteMounts({ ...base, value: [] }); + expect(r).toMatchObject({ ok: false, body: { error: 'invalid_remote_mounts' } }); + if (!r.ok) expect(r.body.message).toMatch(/1\.\.4/); + }); + test('loaded + top-level files share the input-file limit', () => { + expect(gateRemoteMounts({ ...base, maxInputFiles: 100, topLevelFiles: 99 }).ok).toBe(true); + const r = gateRemoteMounts({ ...base, maxInputFiles: 100, topLevelFiles: 100 }); + expect(r).toMatchObject({ ok: false, body: { error: 'invalid_remote_mounts' } }); + }); + test("never exceeds the runner's default max_input_files, even when the service limit is higher", () => { + expect(RUNNER_MAX_INPUT_FILES).toBe(256); + // base has 1 loaded file: 255 + 1 = 256 accepted, 256 + 1 = 257 rejected. + expect(gateRemoteMounts({ ...base, topLevelFiles: 255 }).ok).toBe(true); + const r = gateRemoteMounts({ ...base, topLevelFiles: 256 }); + expect(r).toMatchObject({ ok: false, body: { error: 'invalid_remote_mounts' } }); + }); + test('null is treated exactly like absent, [] stays a 400', () => { + expect(remoteMountsPresent(null)).toBe(false); + expect(remoteMountsPresent(undefined)).toBe(false); + expect(remoteMountsPresent([])).toBe(true); + expect(gateRemoteMounts({ ...base, value: null })).toEqual({ ok: true, mounts: undefined }); + expect(gateRemoteMounts({ ...base, value: null, backend: 'remote-bridge' })).toEqual({ ok: true, mounts: undefined }); + expect(gateRemoteMounts({ ...base, value: [] }).ok).toBe(false); + }); +}); + +describe('relabelMountFileError', () => { + const mounts = [ + mount([{ path: 'x', type: 'file' }, { path: 'a', type: 'file', file }]), + mount([{ path: 'b', type: 'file', file }], '/mnt/other'), + ] as never; + const err = (index: number) => new FileRefAuthorizationError(400, `files[${index}].id is invalid`, 'invalid_input', { index }); + + test('names the mount entry for indexes past the top-level files', () => { + expect((relabelMountFileError(err(2), mounts, 2) as Error).message).toBe('remote_mounts[0].entries[1].file.id is invalid'); + expect((relabelMountFileError(err(3), mounts, 2) as Error).message).toBe('remote_mounts[1].entries[0].file.id is invalid'); + }); + test('leaves top-level indexes and other errors alone', () => { + const top = err(1); + expect(relabelMountFileError(top, mounts, 2)).toBe(top); + const other = new Error('boom'); + expect(relabelMountFileError(other, mounts, 2)).toBe(other); + }); +}); diff --git a/service/src/service/remote-mounts.ts b/service/src/service/remote-mounts.ts new file mode 100644 index 00000000..21d39648 --- /dev/null +++ b/service/src/service/remote-mounts.ts @@ -0,0 +1,268 @@ +import type * as t from '../types'; +import { FileRefAuthorizationError } from './file-authorization'; + +/* Pure validation of POST /exec `remote_mounts` (docs/remote-mounts/README.md, + * "Rules"). Loaded-file refs are only shape-checked as plain objects here; the + * caller runs them through `authorizeRequestedFiles` with the top-level files. */ + +export const MAX_REMOTE_MOUNTS = 4; +export const MAX_REMOTE_MOUNT_ENTRIES = 5000; +export const MAX_REMOTE_MOUNT_LOADED_FILES = 64; +const MAX_SEGMENT_BYTES = 255; +const MAX_PATH_BYTES = 1024; +const MAX_DEPTH = 16; +const MOUNT_PATH_RE = /^\/mnt\/[a-z0-9][a-z0-9-]{0,30}$/; +// eslint-disable-next-line no-control-regex +const CONTROL_RE = /[\u0000-\u001f\u007f]/; + +export type RemoteMountsValidation = + | { ok: true; mounts: t.RemoteMount[] } + | { ok: false; reason: string }; + +const fail = (reason: string): { ok: false; reason: string } => ({ + ok: false, + reason, +}); + +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function entryPathError(path: unknown): string | undefined { + if (typeof path !== 'string' || path === '') + return 'entry path must be a non-empty string'; + if (CONTROL_RE.test(path)) + return 'entry path must not contain NUL or control characters'; + if (path.includes('\\')) return 'entry path must not contain a backslash'; + if (path.startsWith('/') || path.endsWith('/')) { + return 'entry path must be relative with no leading or trailing "/"'; + } + if (Buffer.byteLength(path) > MAX_PATH_BYTES) { + return `entry path must not exceed ${MAX_PATH_BYTES} bytes`; + } + const segments = path.split('/'); + if (segments.some(s => s === '' || s === '.' || s === '..')) { + return 'entry path must not contain empty, "." or ".." segments'; + } + if (segments.some(s => Buffer.byteLength(s) > MAX_SEGMENT_BYTES)) { + return `entry path segment must not exceed ${MAX_SEGMENT_BYTES} bytes`; + } + if (segments.length > MAX_DEPTH) + return `entry path depth must not exceed ${MAX_DEPTH}`; + return undefined; +} + +function validateEntry(e: unknown): t.RemoteMountEntry | string { + if (!isPlainObject(e)) return 'each entry must be an object'; + const pathError = entryPathError(e.path); + if (pathError) return pathError; + const path = e.path as string; + if (e.type !== 'file' && e.type !== 'dir') + return `entry type of ${path} must be "file" or "dir"`; + const entry: t.RemoteMountEntry = { path, type: e.type }; + if (e.size !== undefined) { + if (e.type !== 'file') return `entry size is only valid on files (${path})`; + if ( + typeof e.size !== 'number' || + !Number.isSafeInteger(e.size) || + e.size < 0 + ) { + return `entry size of ${path} must be a non-negative safe integer`; + } + entry.size = e.size; + } + if (e.file !== undefined) { + if (e.type !== 'file') return `entry file is only valid on files (${path})`; + if (!isPlainObject(e.file)) return `entry file of ${path} must be an object`; + entry.file = e.file as unknown as t.RequestFile; + } + return entry; +} + +/** Entries of one mount: unique paths, no file used as a parent. */ +function validateEntries(entries: unknown[]): t.RemoteMountEntry[] | string { + const seen = new Set(); + const out: t.RemoteMountEntry[] = []; + for (const e of entries) { + const entry = validateEntry(e); + if (typeof entry === 'string') return entry; + if (seen.has(entry.path)) return `duplicate entry path ${entry.path}`; + seen.add(entry.path); + out.push(entry); + } + const filePaths = new Set(out.filter(e => e.type === 'file').map(e => e.path)); + for (const { path } of out) { + const parts = path.split('/'); + for (let i = 1; i < parts.length; i++) { + if (filePaths.has(parts.slice(0, i).join('/'))) { + return `entry ${path} has a file as its parent`; + } + } + } + return out; +} + +export function validateRemoteMounts(value: unknown): RemoteMountsValidation { + if (!Array.isArray(value)) return fail('remote_mounts must be an array'); + if (value.length < 1 || value.length > MAX_REMOTE_MOUNTS) { + return fail(`remote_mounts must contain 1..${MAX_REMOTE_MOUNTS} mounts`); + } + let totalEntries = 0; + for (const m of value) { + if (isPlainObject(m) && Array.isArray(m.entries)) + totalEntries += m.entries.length; + } + if (totalEntries > MAX_REMOTE_MOUNT_ENTRIES) { + return fail( + `remote_mounts allows at most ${MAX_REMOTE_MOUNT_ENTRIES} entries in total`, + ); + } + + const mounts: t.RemoteMount[] = []; + const mountPaths = new Set(); + for (const m of value) { + if (!isPlainObject(m)) return fail('each mount must be an object'); + const { path: mountPath, entries } = m; + if (typeof mountPath !== 'string' || !MOUNT_PATH_RE.test(mountPath)) { + return fail(`mount path must match ${MOUNT_PATH_RE.source}`); + } + if (mountPath === '/mnt/data') + return fail('mount path must not be /mnt/data'); + if (mountPaths.has(mountPath)) + return fail(`duplicate mount path ${mountPath}`); + mountPaths.add(mountPath); + if (!Array.isArray(entries)) + return fail(`entries of ${mountPath} must be an array`); + const out = validateEntries(entries); + if (typeof out === 'string') return fail(out); + mounts.push({ path: mountPath, entries: out }); + } + if (loadedRemoteMountFiles(mounts).length > MAX_REMOTE_MOUNT_LOADED_FILES) { + return fail( + `remote_mounts allows at most ${MAX_REMOTE_MOUNT_LOADED_FILES} loaded files`, + ); + } + return { ok: true, mounts }; +} + +/** Loaded-file refs in mount/entry order (the order `withAuthorizedMountFiles` expects). */ +export function loadedRemoteMountFiles( + mounts: t.RemoteMount[], +): t.RequestFile[] { + return mounts.flatMap(m => + m.entries.flatMap(e => (e.file ? [e.file] : [])), + ); +} + +/** Replaces each loaded ref, in order, with its authorized/normalized counterpart. */ +export function withAuthorizedMountFiles( + mounts: t.RemoteMount[], + authorized: t.RequestFile[], +): t.RemoteMount[] { + let i = 0; + return mounts.map(m => ({ + path: m.path, + entries: m.entries.map(e => + e.file ? { ...e, file: authorized[i++] } : { ...e }, + ), + })); +} + +/** Loaded refs of a runner payload, in the same order as the payload entries. */ +export function payloadRemoteMountFiles( + payload: t.PayloadBody, +): t.PayloadFileRef[] { + return (payload.remote_mounts ?? []).flatMap(m => + m.entries.flatMap(e => (e.file ? [e.file] : [])), + ); +} + +/** Response passthrough: only when the request had mounts and the runner reported stubs. */ +export function remoteMountsRequiredField( + requested: boolean, + raw: unknown, +): { remote_mounts_required?: { read: string[] } } { + if (!requested || !isPlainObject(raw) || !Array.isArray(raw.read)) + return {}; + const read = raw.read.filter((p): p is string => typeof p === 'string'); + return read.length > 0 ? { remote_mounts_required: { read } } : {}; +} + +/** Response passthrough for copy-on-write outputs: `remote_mount` survives only + * when the request had mounts and the value is well formed; otherwise it is dropped. */ +export function gateRemoteMountFiles( + requested: boolean, + files: T[], +): T[] { + return files.map(file => { + const { remote_mount: raw, ...rest } = file as T & { remote_mount?: unknown }; + if ( + requested && + isPlainObject(raw) && + typeof raw.path === 'string' && + (raw.change === 'modified' || raw.change === 'created') + ) { + return { ...rest, remote_mount: { path: raw.path, change: raw.change } } as T; + } + return rest as T; + }); +} + +/* The runner's default SANDBOX_MAX_INPUT_FILES. The service cannot read the + * runner's setting, so a request must fit this to never be rejected after enqueue. */ +export const RUNNER_MAX_INPUT_FILES = 256; + +/** `null` means absent, exactly like an omitted key; `[]` is present (and invalid). */ +export function remoteMountsPresent(value: unknown): boolean { + return value != null; +} + +/** Rewrites `files[N]` in an authorization error whose N points past the + * top-level files into the `remote_mounts[i].entries[j].file` it came from. */ +export function relabelMountFileError( + error: unknown, + mounts: t.RemoteMount[], + topLevelFiles: number, +): unknown { + if (!(error instanceof FileRefAuthorizationError)) return error; + const index = error.context.index; + if (typeof index !== 'number' || index < topLevelFiles) return error; + const where = mounts.flatMap((m, mi) => + m.entries.flatMap((e, ei) => (e.file ? [`remote_mounts[${mi}].entries[${ei}].file`] : [])), + )[index - topLevelFiles]; + if (!where) return error; + return new FileRefAuthorizationError( + error.status, + error.message.replace(`files[${index}]`, where), + error.reason, + error.context, + ); +} + +export type RemoteMountsGate = + | { ok: true; mounts: t.RemoteMount[] | undefined } + | { ok: false; body: { error: string; message?: string } }; + +/** Everything POST /exec checks about `remote_mounts` before authorizing files. */ +export function gateRemoteMounts(args: { + value: unknown; + backend: string; + topLevelFiles: number; + maxInputFiles: number; +}): RemoteMountsGate { + if (!remoteMountsPresent(args.value)) return { ok: true, mounts: undefined }; + if (args.backend === 'remote-bridge') { + return { ok: false, body: { error: 'remote_mounts_unsupported' } }; + } + const result = validateRemoteMounts(args.value); + const invalid = (message: string): RemoteMountsGate => ({ + ok: false, + body: { error: 'invalid_remote_mounts', message }, + }); + if (!result.ok) return invalid(result.reason); + const cap = Math.min(args.maxInputFiles, RUNNER_MAX_INPUT_FILES); + if (args.topLevelFiles + loadedRemoteMountFiles(result.mounts).length > cap) { + return invalid(`files and loaded remote_mounts files together allow at most ${cap}`); + } + return { ok: true, mounts: result.mounts }; +} diff --git a/service/src/service/router.ts b/service/src/service/router.ts index a977182e..a0debd5d 100644 --- a/service/src/service/router.ts +++ b/service/src/service/router.ts @@ -29,6 +29,7 @@ import { jobsSubmitted } from '../metrics'; import { captureTraceCarrier, withSpan } from '../telemetry'; import { Jobs, Languages } from '../enum'; import { FileRefAuthorizationError, authorizeRequestedFiles } from './file-authorization'; +import { gateRemoteMounts, loadedRemoteMountFiles, relabelMountFileError, withAuthorizedMountFiles } from './remote-mounts'; import { createUploadSessionRegistrar } from './upload-session'; import { recordSessionOwnership } from '../session-ownership'; import { normalizeProgrammaticTimeoutMs, prepareSandboxJobSecurity } from '../sandbox-egress'; @@ -199,6 +200,16 @@ router.post('/exec', executionLimiter, async (req: t.AuthenticatedRequest, res) return res.status(400).json({ error: (error as Error).message }); } + /* Opt-in: absent or null `remote_mounts` makes the gate a no-op. */ + const gate = gateRemoteMounts({ + value: body.remote_mounts, + backend: env.SANDBOX_BACKEND, + topLevelFiles: Array.isArray(files) ? files.length : 0, + maxInputFiles: env.INPUT_MANIFEST_MAX_FILES, + }); + if (!gate.ok) return res.status(400).json(gate.body); + const remoteMounts = gate.mounts; + let bridgeWorkerId: string | undefined; try { const bridgeSelection = resolveBridgeWorkerSelection({ @@ -239,14 +250,25 @@ router.post('/exec', executionLimiter, async (req: t.AuthenticatedRequest, res) let authorizedFiles: t.RequestFile[]; try { - authorizedFiles = await authorizeRequestedFiles({ + /* Loaded remote-mount refs take the same authorization as files[]: one + * call, then split back (top-level first, mount refs in entry order). */ + const mountFiles = remoteMounts ? loadedRemoteMountFiles(remoteMounts) : []; + const topLevel = Array.isArray(files) ? files.length : 0; + const authorizedAll = await authorizeRequestedFiles({ req, - files, + files: mountFiles.length > 0 && (files == null || Array.isArray(files)) + ? [...(files ?? []), ...mountFiles] + : files, store: connection, }); + authorizedFiles = mountFiles.length > 0 ? authorizedAll.slice(0, topLevel) : authorizedAll; body.files = authorizedFiles.length > 0 ? authorizedFiles : undefined; + if (remoteMounts) { + body.remote_mounts = withAuthorizedMountFiles(remoteMounts, authorizedAll.slice(topLevel)); + } } catch (error) { - if (sendFileRefAuthorizationError(error, res, req)) return; + const relabelled = remoteMounts ? relabelMountFileError(error, remoteMounts, Array.isArray(files) ? files.length : 0) : error; + if (sendFileRefAuthorizationError(relabelled, res, req)) return; logger.error(`[${INSTANCE_ID}] Error authorizing file refs:`, error); return res.status(500).json({ error: 'Internal server error' }); } diff --git a/service/src/types/service.ts b/service/src/types/service.ts index b0375b38..58e12048 100644 --- a/service/src/types/service.ts +++ b/service/src/types/service.ts @@ -46,6 +46,8 @@ export type FileRef = { * inputs distinctly from generated outputs and skip post-processing. */ inherited?: true; + /** Only when the request had `remote_mounts`: output copied out of a mount (copy-on-write). */ + remote_mount?: { path: string; change: 'modified' | 'created' }; }; /** @@ -144,6 +146,7 @@ export type ExecuteResponse = { deleted_files?: string[]; artifact_delivery?: ArtifactDeliveryFailure; artifact_truncation?: ArtifactTruncation; + remote_mounts_required?: RemoteMountsRequired; }; export interface RequestBody { @@ -154,6 +157,7 @@ export interface RequestBody { args?: string[]; user_id?: string; files?: RequestFile[]; + remote_mounts?: RemoteMount[]; /** * Optional stable identity hint (e.g. conversation id) for stateful * runtime sessions. Never a security boundary: the server derives the @@ -188,6 +192,16 @@ export interface FileObject { contentType?: string; } +export type RemoteMountEntry = { + path: string; + type: 'file' | 'dir'; + size?: number; + /** Loaded file: authorized like top-level `files[]`. Absent = stub. */ + file?: RequestFile; +}; +export type RemoteMount = { path: string; entries: RemoteMountEntry[] }; +export type RemoteMountsRequired = { read: string[] }; + export type PayloadFile = { name: string; content: string }; export type PayloadFileRef = { id: string; @@ -201,6 +215,9 @@ export type PayloadFileRef = { input_cache_key?: string; }; +export type PayloadRemoteMountEntry = Omit & { file?: PayloadFileRef }; +export type PayloadRemoteMount = { path: string; entries: PayloadRemoteMountEntry[] }; + export interface PayloadBody { language: string; version: string; @@ -226,6 +243,8 @@ export interface PayloadBody { * consumed by the sandbox, so they're intentionally not on this * shape. */ files: Array; + /** Read-only remote trees; the key is absent unless the request had `remote_mounts`. */ + remote_mounts?: PayloadRemoteMount[]; /** Top-level execution session id (passed to sandbox to seed Job.uuid). */ session_id?: string; /** Output storage session id/handle used for generated file uploads. */ @@ -272,6 +291,7 @@ export type ExecuteResult = { message?: string | null; status?: string | null; wall_time?: number | null; + remote_mounts_required?: RemoteMountsRequired; /** Trusted worker control channel; avoids losing replay calls to stdout truncation. */ pending_tool_calls_payload?: string; }; diff --git a/service/src/workers.ts b/service/src/workers.ts index b0f0dc4d..0ed80242 100644 --- a/service/src/workers.ts +++ b/service/src/workers.ts @@ -26,6 +26,7 @@ import { import { refreshEgressGrantClaims } from './sandbox-egress'; import { buildSandboxExecuteRequest } from './sandbox-dispatch'; import { prepareInputDelivery } from './runtime-session/input-delivery'; +import { gateRemoteMountFiles, remoteMountsRequiredField } from './service/remote-mounts'; import { SessionFilesError } from './runtime-session/files'; import { resolveRuntimeSessionForJob } from './runtime-session/job-policy'; import { @@ -305,7 +306,7 @@ async function processJobInner(job: t.ExecuteJob): Promise { * required and downstream callers always iterate it. Default to * `[]` so the strictened response type from Phase B doesn't * surface a regression that wasn't there before. */ - files: files ?? [], + files: gateRemoteMountFiles(payload.remote_mounts != null, files ?? []), ...(responseData.deleted_files != null ? { deleted_files: responseData.deleted_files } : {}), @@ -315,6 +316,10 @@ async function processJobInner(job: t.ExecuteJob): Promise { ...(responseData.artifact_truncation != null ? { artifact_truncation: responseData.artifact_truncation } : {}), + ...remoteMountsRequiredField( + payload.remote_mounts != null, + responseData.remote_mounts_required, + ), stdout, stderr, ...(responseData.pending_tool_calls_payload != null From ebcbab308bb6f0f362d8d9b23d37f341129f250a Mon Sep 17 00:00:00 2001 From: TomasPalsson Date: Wed, 2 Dec 2026 12:43:51 +0000 Subject: [PATCH 2/2] ci: move the jail-policy baseline past remote_mounts (binds only, seccomp unchanged) --- .github/workflows/apro-soffice.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/apro-soffice.yml b/.github/workflows/apro-soffice.yml index 951a4f54..1e1a6511 100644 --- a/.github/workflows/apro-soffice.yml +++ b/.github/workflows/apro-soffice.yml @@ -52,4 +52,4 @@ jobs: with: bun-version: 1.4.4 - name: Compare the rendered seccomp policy with upstream - run: scripts/apro-policy-unchanged.sh c7bf37d69 c4ba504cc + run: scripts/apro-policy-unchanged.sh c7bf37d69 c62becb