Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/apro-soffice.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
112 changes: 112 additions & 0 deletions api/src/api/v2-remote-mounts.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>(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<void>(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);
});
15 changes: 15 additions & 0 deletions api/src/api/v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -395,6 +409,7 @@ function getJob(
tool_call_socket_enabled: toolCallSocketEnabled,
is_synthetic: isSynthetic,
session,
...(remoteMounts ? { remote_mounts: remoteMounts } : {}),
});
}

Expand Down
73 changes: 73 additions & 0 deletions api/src/execution-manifest-request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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> = {}): 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');
});
});
14 changes: 12 additions & 2 deletions api/src/execution-manifest-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ interface ExecuteRequestBody {
session_id?: string;
output_session_id?: string;
files?: TFile[];
remote_mounts?: unknown;
}

interface PayloadFileRef {
Expand All @@ -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}`;
}
Expand All @@ -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',
Expand Down Expand Up @@ -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;
Expand Down
5 changes: 5 additions & 0 deletions api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -72,6 +73,10 @@ async function main(): Promise<void> {
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(':');
Expand Down
Loading
Loading