SPB Git

Repository Public MIT

sandbox.ts 21.2 KB 494 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : VQuant8 * File             : server/services/research/sandbox.ts9 * Module           : server10 * Repository       : https://git.spboucher.ai/vquant11 * Project Website  : https://vquant.spboucher.ai12 * Created          : 2026-11-2013 * Last Modified    : 2026-11-2014 *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: contact@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 * SPDX Identifier  : MIT34 * License          : MIT License35 * License File     : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Sandbox for code the agent writes (contract: docs/next/CONTRACT.md §9.2; residual risks: docs/next/RESEARCH_AGENT.md).47 *48 * Every Python process that runs model-written code — the notebook kernel, a script run, a package installation,49 * a dataset inspection — is started here, never with the server's environment:50 *51 *  1. Scrubbed environment. The child gets a fixed, minimal set of variables. No provider key, no ACCESS_KEY, no52 *     DATABASE_URL: the only credential it holds is a random token for the loopback egress broker (broker.ts),53 *     valid for this process only.54 *  2. Filesystem. macOS `sandbox-exec` with a profile that denies every write outside the workspace and every read55 *     under /Users, /Volumes, /tmp and the per-user temp dirs, except: the workspace (read-write), the base56 *     virtualenv, the Python helper modules of the app and the person's code library (read-only).57 *  3. Network. All sockets denied except TCP to the broker's loopback port. No DNS. Market data and the package58 *     index are reached through the broker, which holds the keys and an allow-list of hosts.59 *  4. Other processes. No signals to, and no information about, processes outside the sandbox; no AppleEvents, no60 *     LaunchServices, no launchd jobs, no Mach services beyond the few libc needs; setuid programs do not start.61 *  5. Resources. CPU seconds, file size, open files and process count by rlimit (vq_sandbox_boot.py); resident62 *     memory, number of processes, wall-clock time and workspace size by the watchdog below, which kills the whole63 *     process tree.64 *65 * On a platform without sandbox-exec (Linux development, CI) points 2–4 cannot be enforced: the child still gets66 * the scrubbed environment and the limits, `sandboxStatus()` says so, and VQ_SANDBOX_REQUIRED=1 refuses to run.67 */68import { spawn, execFile, type ChildProcess, type StdioOptions } from "node:child_process";69import fs from "node:fs";70import os from "node:os";71import path from "node:path";72import { fileURLToPath } from "node:url";73import { pythonPath } from "../python/lab";7475const __dirname = path.dirname(fileURLToPath(import.meta.url));76const SANDBOX_EXEC = "/usr/bin/sandbox-exec";7778export interface SandboxLimits {79  /** CPU seconds per process (rlimit) */80  cpuSeconds: number;81  /** resident memory of the whole process tree, MB (watchdog) */82  memoryMb: number;83  /** wall-clock, ms (watchdog); 0 = none (the kernel has its own per-execution limit) */84  wallMs: number;85  /** live processes in the tree (watchdog) */86  maxProcesses: number;87  /** largest single file a process may write, MB (rlimit) */88  fileMb: number;89  /** size of the workspace, MB (watchdog) */90  diskMb: number;91}9293const envInt = (name: string, fallback: number): number => {94  const n = Number(process.env[name]);95  return Number.isFinite(n) && n > 0 ? n : fallback;96};9798export function defaultLimits(): SandboxLimits {99  return {100    cpuSeconds: envInt("VQ_RESEARCH_CPU_SECONDS", 4 * 3600),101    memoryMb: envInt("VQ_RESEARCH_MEMORY_MB", 8192),102    wallMs: 0,103    maxProcesses: envInt("VQ_RESEARCH_MAX_PROCESSES", 64),104    fileMb: envInt("VQ_RESEARCH_FILE_MB", 2048),105    diskMb: envInt("VQ_RESEARCH_DISK_MB", 5120),106  };107}108109/** Where the Python helper modules live: next to the bundle in production, in server/services/python in development. */110export function pythonScriptsDir(): string {111  const candidates = [path.join(__dirname, "..", "python"), __dirname, path.join(process.cwd(), "dist"), path.join(process.cwd(), "server", "services", "python")];112  for (const c of candidates) if (fs.existsSync(path.join(c, "vq_sandbox_boot.py"))) return fs.realpathSync(c);113  throw new Error("vq_sandbox_boot.py not found: the Python helpers are missing from this build.");114}115116let statusCache: { enforced: boolean; mechanism: string; note: string } | null = null;117/** Whether filesystem and network isolation are really enforced on this host. */118export function sandboxStatus(): { enforced: boolean; mechanism: string; note: string } {119  if (statusCache) return statusCache;120  const off = process.env.VQ_SANDBOX === "off";121  if (process.platform === "darwin" && fs.existsSync(SANDBOX_EXEC) && !off) statusCache = { enforced: true, mechanism: "sandbox-exec", note: "macOS Seatbelt profile: workspace-only writes, no reads of user data, loopback broker as the only network." };122  else statusCache = { enforced: false, mechanism: "environment+rlimits", note: off ? "Disabled by VQ_SANDBOX=off: only the scrubbed environment and resource limits apply." : "sandbox-exec is not available on this platform: only the scrubbed environment and resource limits apply." };123  return statusCache;124}125export function __resetSandboxStatus(): void {126  statusCache = null;127}128129const q = (p: string) => `"${p.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;130const real = (p: string) => {131  try {132    return fs.realpathSync(p);133  } catch {134    return path.resolve(p);135  }136};137function ancestors(p: string): string[] {138  const out: string[] = [];139  let cur = path.dirname(p);140  while (cur !== path.dirname(cur)) {141    out.push(cur);142    cur = path.dirname(cur);143  }144  return out;145}146147export interface SandboxPaths {148  /** read-write */149  workspace: string;150  /** read-only directories (base venv, the person's code library…) */151  readOnly: string[];152  /** read-only single files (the uv binary) */153  readOnlyFiles?: string[];154  /** directory whose *.py files, fonts/ and vqlab/ are readable (the app's Python helpers; nothing else of the app is) */155  scriptsDir: string;156}157158/** The Seatbelt profile. Later rules win, so the order is: allow by default, deny broadly, re-allow narrowly. */159export function sandboxProfile(paths: SandboxPaths, brokerPort: number | null): string {160  const ws = real(paths.workspace);161  const ro = paths.readOnly.map(real);162  const files = (paths.readOnlyFiles ?? []).map(real);163  const scripts = real(paths.scriptsDir);164  const meta = new Set<string>();165  for (const p of [ws, scripts, ...ro, ...files]) for (const a of ancestors(p)) meta.add(a);166  const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");167  return [168    "(version 1)",169    "(allow default)",170    // Filesystem: nothing is written anywhere, nothing of the users' data is read…171    "(deny file-write*)",172    `(deny file-read* (subpath "/Users") (subpath "/Volumes") (subpath "/private/tmp") (subpath "/private/var/folders") (subpath "/private/var/root") (subpath "/private/var/db/sudo") (subpath "/Library/Keychains") (subpath "/private/etc/ssh") (subpath "/Network"))`,173    // …except what the run needs.174    `(allow file-read-metadata ${[...meta].map((m) => `(literal ${q(m)})`).join(" ")})`,175    `(allow file-read* ${[...ro, ws].map((p) => `(subpath ${q(p)})`).join(" ")} (subpath ${q(path.join(scripts, "fonts"))}) (subpath ${q(path.join(scripts, "vqlab"))}) (regex #"^${esc(scripts)}/[^/]+\\.py$") (literal ${q(scripts)})${files.map((f) => ` (literal ${q(f)})`).join("")})`,176    `(allow file-write* (subpath ${q(ws)}) (literal "/dev/null") (literal "/dev/dtracehelper") (literal "/dev/tty"))`,177    // Network: nothing but the broker on loopback (no DNS either).178    "(deny network*)",179    ...(brokerPort ? [`(allow network-outbound (remote ip "localhost:${brokerPort}"))`] : []),180    "(deny system-socket)",181    // Other processes and the rest of the system.182    "(deny signal (target others))",183    "(deny process-info* (target others))",184    "(deny mach-lookup)",185    '(allow mach-lookup (global-name "com.apple.system.notification_center") (global-name "com.apple.system.opendirectoryd.libinfo") (global-name "com.apple.logd") (global-name "com.apple.system.logger") (global-name "com.apple.diagnosticd"))',186    "(deny appleevent-send)",187    "(deny lsopen)",188    "(deny iokit-open)",189    "(deny job-creation)",190    "",191  ].join("\n");192}193194export interface SandboxEnvInput {195  workspace: string;196  scriptsDir: string;197  /** extra import roots, after the workspace overlay (the person's code library) */198  pythonPath?: string[];199  brokerUrl?: string | null;200  brokerToken?: string | null;201  extra?: Record<string, string>;202}203204/** The complete environment of a sandboxed process. Nothing is inherited from the server. */205export function sandboxEnv(i: SandboxEnvInput): Record<string, string> {206  const ws = real(i.workspace);207  const py = sandboxPython();208  const venvBin = path.isAbsolute(py) ? path.dirname(py) : "";209  const env: Record<string, string> = {210    PATH: [venvBin, "/usr/bin", "/bin"].filter(Boolean).join(":"),211    HOME: path.join(ws, ".home"),212    TMPDIR: path.join(ws, ".tmp"),213    LANG: "en_US.UTF-8",214    LC_ALL: "en_US.UTF-8",215    TZ: process.env.TZ ?? "UTC",216    PYTHONUNBUFFERED: "1",217    PYTHONNOUSERSITE: "1",218    PYTHONPYCACHEPREFIX: path.join(ws, ".cache", "pycache"),219    PYTHONPATH: [path.join(ws, ".site"), path.join(ws, "code"), ...(i.pythonPath ?? []), real(i.scriptsDir)].join(":"),220    MPLBACKEND: "Agg",221    MPLCONFIGDIR: path.join(ws, ".cache", "matplotlib"),222    XDG_CACHE_HOME: path.join(ws, ".cache"),223    PIP_CACHE_DIR: path.join(ws, ".cache", "pip"),224    UV_CACHE_DIR: path.join(ws, ".cache", "uv"),225    PIP_DISABLE_PIP_VERSION_CHECK: "1",226    PIP_NO_INPUT: "1",227    // A plain `pip install` typed by the agent behaves like install_package: packages go to the overlay of the228    // workspace (the base environment is read-only), and certificates come from certifi (the system trust store229    // is a macOS service the sandbox does not let the process talk to).230    PIP_TARGET: path.join(ws, ".site"),231    PIP_USE_DEPRECATED: "legacy-certs",232    OMP_NUM_THREADS: String(envInt("VQ_RESEARCH_THREADS", 4)),233    OPENBLAS_NUM_THREADS: String(envInt("VQ_RESEARCH_THREADS", 4)),234    VECLIB_MAXIMUM_THREADS: String(envInt("VQ_RESEARCH_THREADS", 4)),235    VQ_WORKSPACE: ws,236    VQ_SITE_DIR: path.join(ws, ".site"),237    VQ_SANDBOX: "1",238  };239  if (i.brokerUrl && i.brokerToken) {240    const proxy = i.brokerUrl.replace("http://", `http://vq:${i.brokerToken}@`);241    Object.assign(env, {242      VQ_BROKER_URL: i.brokerUrl,243      VQ_BROKER_TOKEN: i.brokerToken,244      // The data clients of the notebook keep their shape: the "key" they hold is the broker token, which only245      // works on loopback, for this process, and is swapped for the real key on the server side.246      FMP_BASE_URL: `${i.brokerUrl}/fmp`,247      FMP_API_KEY: i.brokerToken,248      FINDATA_URL: `${i.brokerUrl}/findata`,249      FINDATA_API_KEY: i.brokerToken,250      HTTPS_PROXY: proxy,251      HTTP_PROXY: proxy,252      https_proxy: proxy,253      http_proxy: proxy,254      ALL_PROXY: proxy,255      NO_PROXY: "127.0.0.1,localhost",256      no_proxy: "127.0.0.1,localhost",257    });258  }259  return { ...env, ...(i.extra ?? {}) };260}261262/**263 * The interpreter as the sandbox must name it: the venv's own bin/python (so the venv is recognised), reached264 * through the real path of the venv directory (a linked venv directory would otherwise sit under a denied path).265 */266export function sandboxPython(): string {267  const py = pythonPath();268  if (!path.isAbsolute(py)) return py;269  return path.join(real(path.dirname(path.dirname(py))), "bin", path.basename(py));270}271272function findUv(): string | null {273  for (const c of [process.env.VQ_UV_PATH, path.join(os.homedir(), ".local", "bin", "uv"), "/opt/homebrew/bin/uv", "/usr/local/bin/uv"]) if (c && fs.existsSync(c)) return real(c);274  return null;275}276277export interface SandboxSpawn {278  /** program and arguments run after the limits are applied (argv[0] is usually the Python interpreter) */279  argv: string[];280  workspace: string;281  cwd?: string;282  /** read-only import roots besides the workspace (the person's library) */283  libraryDirs?: string[];284  brokerUrl?: string | null;285  brokerPort?: number | null;286  brokerToken?: string | null;287  limits?: Partial<SandboxLimits>;288  /** "supervise": output to <runDir>/*.log and status.json, the server may go away; "exec": pipes */289  mode?: "exec" | "supervise";290  runDir?: string;291  stdio?: StdioOptions;292  env?: Record<string, string>;293  /** called once when the watchdog kills the tree */294  onKilled?: (reason: string) => void;295}296297export interface Sandboxed {298  child: ChildProcess;299  limits: SandboxLimits;300  /** why the watchdog killed it, when it did */301  killedFor(): string | null;302  /** kills the whole tree */303  kill(reason?: string): void;304}305306/** Processes of this user, to place the per-user process rlimit just above what is already running. */307function userProcessCount(): Promise<number> {308  return new Promise((resolve) => {309    execFile("/bin/ps", ["-U", String(process.getuid?.() ?? 0), "-o", "pid="], { timeout: 4000 }, (err, out) => resolve(err ? 600 : out.split("\n").filter((l) => l.trim()).length));310  });311}312313/** Starts a program in the sandbox. The caller owns the child's lifetime; `kill()` takes the whole tree down. */314export async function spawnSandboxed(o: SandboxSpawn): Promise<Sandboxed> {315  const status = sandboxStatus();316  if (!status.enforced && process.env.VQ_SANDBOX_REQUIRED === "1") throw new Error("Code execution is disabled: this server requires the sandbox and it is not available here.");317  const limits: SandboxLimits = { ...defaultLimits(), ...(o.limits ?? {}) };318  const ws = real(o.workspace);319  for (const d of [".home", ".tmp", ".site", ".cache", "code"]) fs.mkdirSync(path.join(ws, d), { recursive: true });320  const scripts = pythonScriptsDir();321  const py = sandboxPython();322  const pyReal = path.isAbsolute(py) ? real(py) : py;323  const venvRoot = path.isAbsolute(py) ? path.dirname(path.dirname(py)) : null;324  // Callers name the interpreter as the server knows it; inside the sandbox it is the resolved one.325  const argv = o.argv.map((a) => (a === pythonPath() ? py : a));326  const uv = findUv();327328  const boot = {329    mode: o.mode ?? "exec",330    runDir: o.runDir,331    cwd: o.cwd ?? ws,332    cpuSeconds: limits.cpuSeconds,333    fileMb: limits.fileMb,334    memoryMb: limits.memoryMb,335    openFiles: 4096,336    // The limit is per user on macOS: leave room for what already runs, plus this sandbox's own allowance.337    maxUserProcesses: (await userProcessCount()) + limits.maxProcesses * 2 + 64,338  };339  const inner = [py, "-s", path.join(scripts, "vq_sandbox_boot.py"), JSON.stringify(boot), "--", ...argv];340  const env = sandboxEnv({ workspace: ws, scriptsDir: scripts, pythonPath: o.libraryDirs, brokerUrl: o.brokerUrl, brokerToken: o.brokerToken, extra: { ...(uv ? { VQ_UV: uv } : {}), ...(o.env ?? {}) } });341342  let command = inner[0];343  let args = inner.slice(1);344  if (status.enforced) {345    const profile = sandboxProfile({ workspace: ws, readOnly: [...(venvRoot ? [venvRoot] : []), ...(o.libraryDirs ?? [])], readOnlyFiles: [...(uv ? [uv] : []), ...(pyReal !== py ? [pyReal] : [])], scriptsDir: scripts }, o.brokerPort ?? null);346    command = SANDBOX_EXEC;347    args = ["-p", profile, ...inner];348  }349  const child = spawn(command, args, { cwd: ws, env, stdio: o.stdio ?? ["pipe", "pipe", "pipe"], detached: true });350  let reason: string | null = null;351  const sandboxed: Sandboxed = {352    child,353    limits,354    killedFor: () => reason,355    kill(why) {356      if (why && !reason) reason = why;357      killTree(child.pid);358    },359  };360  if (child.pid) watch({ pid: child.pid, workspace: ws, limits, startedAt: Date.now(), known: new Set([child.pid]), kill: (why) => {361    if (!reason) {362      reason = why;363      try {364        o.onKilled?.(why);365      } catch {366        /* a listener must not stop the kill */367      }368    }369    killTree(child.pid);370  } });371  child.once("exit", () => unwatch(child.pid));372  child.once("error", () => unwatch(child.pid));373  return sandboxed;374}375376// ─── Watchdog ────────────────────────────────────────────────────────────────377interface Watched {378  pid: number;379  workspace: string;380  limits: SandboxLimits;381  startedAt: number;382  /** every pid ever seen in the tree: a process that detaches from its parent or its group stays known */383  known: Set<number>;384  kill: (reason: string) => void;385  lastDisk?: number;386}387const watched = new Map<number, Watched>();388let timer: NodeJS.Timeout | null = null;389390function killTree(pid: number | undefined): void {391  if (!pid) return;392  const w = watched.get(pid);393  for (const target of [-pid, ...(w ? [...w.known] : [pid])]) {394    try {395      process.kill(target, "SIGKILL");396    } catch {397      /* already gone */398    }399  }400}401402/** Puts a process the server did not just spawn (a background run found again after a restart) under the watchdog. */403export function adoptProcess(pid: number, workspace: string, limits: SandboxLimits, startedAt: number, onKilled: (reason: string) => void): { kill(reason?: string): void } {404  watch({ pid, workspace: real(workspace), limits, startedAt, known: new Set([pid]), kill: (why) => {405    onKilled(why);406    killTree(pid);407  } });408  return { kill: (why) => {409    if (why) onKilled(why);410    killTree(pid);411    unwatch(pid);412  } };413}414export function releaseProcess(pid: number): void {415  unwatch(pid);416}417418function watch(w: Watched): void {419  watched.set(w.pid, w);420  if (!timer) {421    timer = setInterval(sweep, 1500);422    timer.unref();423  }424}425function unwatch(pid: number | undefined): void {426  if (pid) watched.delete(pid);427  if (watched.size === 0 && timer) {428    clearInterval(timer);429    timer = null;430  }431}432433function ps(): Promise<Array<{ pid: number; ppid: number; pgid: number; rssKb: number }>> {434  return new Promise((resolve) => {435    execFile("/bin/ps", ["-axo", "pid=,ppid=,pgid=,rss="], { timeout: 5000, maxBuffer: 8 * 1024 * 1024 }, (err, out) => {436      if (err) return resolve([]);437      const rows = [];438      for (const line of out.split("\n")) {439        const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/.exec(line);440        if (m) rows.push({ pid: +m[1], ppid: +m[2], pgid: +m[3], rssKb: +m[4] });441      }442      resolve(rows);443    });444  });445}446function du(dir: string): Promise<number> {447  return new Promise((resolve) => execFile("/usr/bin/du", ["-sk", dir], { timeout: 20_000 }, (err, out) => resolve(err ? 0 : (Number(out.split(/\s+/)[0]) || 0) / 1024)));448}449450let sweeping = false;451async function sweep(): Promise<void> {452  if (sweeping || watched.size === 0) return;453  sweeping = true;454  try {455    const rows = await ps();456    if (rows.length === 0) return;457    const byPid = new Map(rows.map((r) => [r.pid, r]));458    for (const w of [...watched.values()]) {459      // Tree = the group of the root, plus descendants of anything already known (covers setsid/setpgid escapes).460      let grew = true;461      while (grew) {462        grew = false;463        for (const r of rows) {464          if (w.known.has(r.pid)) continue;465          if (r.pgid === w.pid || w.known.has(r.ppid)) {466            w.known.add(r.pid);467            grew = true;468          }469        }470      }471      const alive = [...w.known].filter((p) => byPid.has(p));472      if (!byPid.has(w.pid) && alive.length === 0) {473        unwatch(w.pid);474        continue;475      }476      const rssMb = alive.reduce((s, p) => s + (byPid.get(p)?.rssKb ?? 0), 0) / 1024;477      if (rssMb > w.limits.memoryMb) w.kill(`memory limit: ${Math.round(rssMb)} MB resident for a limit of ${w.limits.memoryMb} MB`);478      else if (alive.length > w.limits.maxProcesses) w.kill(`process limit: ${alive.length} processes for a limit of ${w.limits.maxProcesses}`);479      else if (w.limits.wallMs > 0 && Date.now() - w.startedAt > w.limits.wallMs) w.kill(`time limit: ${Math.round(w.limits.wallMs / 1000)} s of wall-clock time`);480      else if (!w.lastDisk || Date.now() - w.lastDisk > 10_000) {481        w.lastDisk = Date.now();482        const mb = await du(w.workspace);483        if (mb > w.limits.diskMb) w.kill(`disk limit: the workspace holds ${Math.round(mb)} MB for a limit of ${w.limits.diskMb} MB`);484      }485    }486  } finally {487    sweeping = false;488  }489}490491process.once("exit", () => {492  // Kernels and foreground runs die with the server; supervised background runs are meant to outlive it.493});494
Files main
Menu

Theme