SPB Git

Repository Public

sandbox.test.ts 11.9 KB 170 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SP Wallet8 * File             : services/research-runner/test/sandbox.test.ts9 * Module           : services10 * Repository       : https://git.spboucher.ai/sp-wallet11 * Project Website  : https://wallet.spboucher.ai12 * Created          : 2026-11-1113 * Last Modified    : 2026-11-1714 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// Proof of the OS-level isolation of a research job (macOS sandbox-exec). A job is run through the REAL runner with an agent44// whose only work is to attempt every forbidden access from inside the sandboxed process (node, python and system binaries)45// and to write down what happened. Each denial below was attempted for real; positive controls show the sandbox is not46// simply denying everything. Stand-ins: two local TCP servers play the wallet API and the signer, a Unix socket plays a47// local service, a canary file outside the job directory plays a secret. Skipped where sandbox-exec does not exist.48import { spawn, type ChildProcess } from 'node:child_process';49import { mkdtempSync, readFileSync, realpathSync, writeFileSync, existsSync } from 'node:fs';50import { createServer, type Server } from 'node:net';51import { homedir, tmpdir } from 'node:os';52import path from 'node:path';53import { afterAll, beforeAll, describe, expect, it } from 'vitest';54import { sandboxProfile } from '@spw/core/research-sandbox';55import { jobPaths, runJob, sandboxAvailable } from '../src/job.ts';56import { hooks, labReady, makeJob, REPO, testConfig } from './helpers.ts';5758type Probe = Record<string, { ok: boolean; error?: string; value?: string }> & { python: Record<string, { ok: boolean; error?: string }> };59const ENV_CANARY = 'CANARY-ENV-7f3a91c2d5e8';60let envHolder: ChildProcess | undefined;61let probe: Probe, profile = '', connections = { api: 0, signer: 0, unix: 0 }, servers: Server[] = [], outside = '', log = '';6263describe.skipIf(!sandboxAvailable() || !labReady())('sandbox: every forbidden access, attempted from inside the job', () => {64  beforeAll(async () => {65    const scratch = realpathSync(mkdtempSync(path.join(tmpdir(), 'spw-canary-')));66    const canary = path.join(scratch, 'secret.txt'); writeFileSync(canary, 'CANARY-SECRET-0123456789');67    outside = path.join(scratch, 'written-by-the-job.txt');68    const listen = (key: 'api' | 'signer' | 'unix', where: number | string) => new Promise<Server>((resolve) => { const s = createServer((c) => { connections[key] += 1; c.destroy(); });69      if (typeof where === 'string') s.listen(where, () => resolve(s)); else s.listen(where, '127.0.0.1', () => resolve(s)); });70    const api = await listen('api', 0), signer = await listen('signer', 0), unixPath = path.join(scratch, 'svc.sock'), unix = await listen('unix', unixPath);71    servers = [api, signer, unix];72    // a process of the same user, outside the sandbox, with a secret in its environment: stands for the runner itself (the73    // kernel serves the environment a process was STARTED with, so the canary must be there at exec time)74    envHolder = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 120000)'], { env: { PATH: process.env.PATH ?? '', SPW_TEST_ENV_CANARY: ENV_CANARY }, stdio: 'ignore' });75    await new Promise((r) => setTimeout(r, 300));76    const cfg = testConfig('probe', { home: homedir(), appDir: REPO, canary, outside, envCanary: ENV_CANARY, envPid: envHolder.pid, apiPort: (api.address() as { port: number }).port, signerPort: (signer.address() as { port: number }).port,77      unixSocket: unixPath, runnerPid: process.pid, stateDir: '' }, { keepJobs: true });78    const job = makeJob({ bars: 400 }), p = jobPaths(cfg, job.id);79    cfg.agent.argv[3] = JSON.stringify({ ...(JSON.parse(cfg.agent.argv[3]!) as object), stateDir: p.state });80    const h = hooks();81    const result = await runJob(job, cfg, h.hooks);82    log = h.captured.lines.map((l) => `${l.s}: ${l.t}`).join('\n');83    expect(result.usage.sandbox, log).toBe('sandbox-exec');84    expect(existsSync(path.join(p.work, 'probe.json')), `the probe wrote no result — outcome ${result.outcome}${'reason' in result ? ` (${result.reason})` : ''}\n${log}`).toBe(true);   // say WHY, not only ENOENT85    probe = JSON.parse(readFileSync(path.join(p.work, 'probe.json'), 'utf8')) as Probe;86    profile = readFileSync(p.profile, 'utf8');87  }, 120_000);88  afterAll(() => { for (const s of servers) s.close(); envHolder?.kill('SIGKILL'); });8990  const denied = (k: string, re = /EPERM|EACCES|not permitted|Permission denied/i) => { const r = probe[k]!; expect(r, k).toBeDefined(); expect(r.ok, `${k} must be denied, got ${JSON.stringify(r)}`).toBe(false); expect(r.error ?? '', k).toMatch(re); };9192  it('files: the owner\'s home, ~/.ssh, ~/.config, the keychain files, the application checkout and its .env cannot be read', () => {93    for (const k of ['read_ssh', 'read_config', 'read_home', 'read_keychains', 'read_app', 'read_app_src']) denied(k);94    // a path that does not exist answers ENOENT, one that exists answers EPERM: existence can be inferred, content never95    denied('read_app_env', /EPERM|ENOENT/);96  });97  it('files: a secret elsewhere on the machine cannot be read, stat-ed, reached through a symlink or hard-linked into the job', () => {98    for (const k of ['read_canary', 'stat_canary', 'symlink_read', 'hardlink_outside']) denied(k);99  });100  it('files: nothing can be written outside the job directory; the laboratory code and the data are read-only', () => {101    for (const k of ['write_outside', 'write_ro', 'write_ro_new']) denied(k);102    expect(existsSync(outside)).toBe(false);103  });104  it('files: the runner\'s own state (its ledger copy, the sandbox profile) can be neither read nor written', () => {105    for (const k of ['read_runner_state', 'write_runner_ledger', 'read_profile']) denied(k);106  });107  it('network: the wallet API port, the signer port, PostgreSQL and every other loopback port are refused — and nothing reached the listeners', () => {108    for (const k of ['tcp_api', 'tcp_signer', 'tcp_8650', 'tcp_8651', 'tcp_5432', 'tcp_v6_api']) denied(k);109    expect(connections).toEqual({ api: 0, signer: 0, unix: 0 });110  });111  it('network: no arbitrary host (internet, LAN), no DNS, no UDP, no Unix socket (local services, PostgreSQL), no listening socket', () => {112    for (const k of ['tcp_internet', 'tcp_internet_80', 'tcp_lan', 'unix_socket', 'pg_socket', 'listen', 'udp']) denied(k);113    denied('dns', /ENOTFOUND|EAI_|EPERM|not permitted/);114  });115  it('system: no keychain, no signal to processes outside the sandbox; curl and ssh started from inside get nowhere', () => {116    expect(probe.keychain!.ok, JSON.stringify(probe.keychain)).toBe(false);117    expect(probe.keychain_find!.ok).toBe(false);118    denied('kill_runner');119    expect(probe.curl!.ok, JSON.stringify(probe.curl)).toBe(false);120    expect(probe.ssh!.ok, JSON.stringify(probe.ssh)).toBe(false);121  });122  it('v8: the environment of a process outside the sandbox (the runner\'s secrets) cannot be read — ps -E, the process list, sysctl kern.procargs2', () => {123    // before v8 the profile had a blanket `(allow sysctl-read)` and no process-info rule: all three answered124    for (const k of ['ps_env', 'ps_list', 'sysctl_env']) denied(k, /EPERM|not permitted|hidden/i);125    // v10: the sysctl probe really ran (a probe that crashed, or that was given no process to read, is not a denial) and the126    // kernel refused the read itself127    expect(probe.sysctl_env!.error).not.toMatch(/PROBE-/); expect(probe.sysctl_env!.error).toMatch(/^EPERM .*(not permitted|Errno 1)/i);128    expect(profile).toContain('(deny sysctl-read (sysctl-name-prefix "kern.proc"))');129    expect(profile).toContain('(deny process-info*)');130  });131  it('the same holds for the laboratory\'s Python (the process that runs strategy code)', () => {132    for (const k of ['py_read_home', 'py_read_canary', 'py_tcp_api', 'py_tcp_internet', 'py_dns', 'py_write_outside']) { const r = probe.python[k]!; expect(r, k).toBeDefined(); expect(r.ok, `${k}: ${JSON.stringify(r)}`).toBe(false); }133    expect(probe.python.py_import!.ok).toBe(true);134  });135  it('positive controls: the job reads its brief, writes its working directory, reaches its model gateway and nothing else', () => {136    expect(probe.ok_read_ro!.ok).toBe(true);137    expect(probe.ok_write_work).toEqual({ ok: true, value: 'x' });138    expect(probe.ok_gateway!.ok, JSON.stringify(probe.ok_gateway)).toBe(true);139  });140  it('the environment of the agent contains no secret and nothing of the runner\'s own environment', () => {141    const keys = probe.ok_env!.value!.split(',');142    // (the probe truncates the list; what matters is that every name is one the runner set on purpose)143    for (const k of keys) expect(k).toMatch(/^(ANTHROPIC_API_KEY|ANTHROPIC_BASE_URL|CLAUDE_[A-Z_]+|DISABLE_[A-Z_]+|HOME|JOBLIB_MULTIPROCESSING|LANG|MPLCONFIGDIR|NO_COLOR|PATH|PYTHON[A-Z]+|SHELL|SPQ_[A-Z_]+|SPW_JOB_[A-Z_]+|TMPDIR|TMPPREFIX|UV_OFFLINE|__CF_USER_TEXT_ENCODING)$/);144  });145  it('the profile itself: deny by default, one loopback port, no home directory, no application path', () => {146    expect(profile).toMatch(/^\(version 1\)\n\(deny default\)/);147    expect(profile.match(/network-outbound/g)).toHaveLength(1);148    expect(profile).toMatch(/\(allow network-outbound \(remote ip "localhost:\d+"\)\)/);149    expect(profile).not.toMatch(/network-inbound|network\*|mach-lookup|\(allow default\)|file-write\* \(subpath "\/"\)/);150    expect(profile).not.toContain(`(subpath "${homedir()}")`);151    // in this test the laboratory's virtualenv lives inside the repository: it is the ONLY readable path under it152    // (on a research node the checkout is sparse — research/ only — and the application code is not on the machine at all)153    const subpaths = [...profile.matchAll(/\(subpath "([^"]+)"\)/g)].map((m) => m[1]!);154    for (const sp of subpaths.filter((x) => x.startsWith(REPO))) expect(sp.startsWith(path.join(REPO, 'research/.venv'))).toBe(true);155    expect(subpaths.some((x) => x === REPO || x === path.join(REPO, 'services') || x === path.join(REPO, 'research'))).toBe(false);156  });157});158159describe('sandbox profile builder', () => {160  it('refuses paths that could break out of the profile text, and relative paths', () => {161    for (const bad of ['relative/path', '/tmp/a"b', '/tmp/a\\b', '/tmp/a\nb', '/tmp/../etc'])162      expect(() => sandboxProfile({ writable: [bad], readable: [], localPorts: [] }), bad).toThrow(/not a plain absolute path/);163    expect(() => sandboxProfile({ writable: ['/tmp/x'], readable: [], localPorts: [70000] })).toThrow(/bad port/);164    expect(() => sandboxProfile({ writable: [], readable: [], localPorts: [] })).toThrow(/job directory/);165  });166  it('with no port there is no network rule at all', () => {167    expect(sandboxProfile({ writable: ['/private/tmp/job'], readable: ['/opt/venv'], localPorts: [] })).not.toMatch(/network/);168  });169});170
Files main
Menu

Theme