From 9cd4caf175d13364179812e4e99f365c1f5cc54e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 01:46:31 +0100 Subject: [PATCH] sandbox: the one bwrap profile moves to sandbox.rs with extra_rw, and her box's side of a shell command (run_box, serve_box) ClaudeSpawner's sandboxed spawn was reached only from its own test since the Persona organ went live (the Self runs unsandboxed through ClaudeSpawner::new), so that use is deleted rather than kept: the profile now has one caller, the box. run_box reads one {command, timeout_s} request, runs /bin/sh -c under the profile with the commons data dirs bound writable, stops it at its timeout, and answers {tool: shell, status, exit, duration_ms, stdout_tail, stderr_tail, wrote}. Cut persona-agent-tools (A2). Co-Authored-By: Claude Opus 5.5 --- crates/mind-body/src/lib.rs | 1 + crates/mind-body/src/sandbox.rs | 196 +++++++++++++++++++++++++ crates/mind-body/src/sandbox/tests.rs | 126 ++++++++++++++++ crates/mind-body/src/self_run.rs | 64 +------- crates/mind-body/src/self_run/tests.rs | 51 ------- 5 files changed, 331 insertions(+), 107 deletions(-) create mode 100644 crates/mind-body/src/sandbox.rs create mode 100644 crates/mind-body/src/sandbox/tests.rs diff --git a/crates/mind-body/src/lib.rs b/crates/mind-body/src/lib.rs index f922800..dfad1c0 100644 --- a/crates/mind-body/src/lib.rs +++ b/crates/mind-body/src/lib.rs @@ -47,6 +47,7 @@ pub mod lease_client; pub mod persona; pub mod projection; pub mod queue; +pub mod sandbox; pub mod self_run; pub mod tempo; diff --git a/crates/mind-body/src/sandbox.rs b/crates/mind-body/src/sandbox.rs new file mode 100644 index 0000000..8dfc91d --- /dev/null +++ b/crates/mind-body/src/sandbox.rs @@ -0,0 +1,196 @@ +//! Her box (map 16.38.5, 16.38.17; ruling `eureka-body:ruling:sandbox-network`): the one bubblewrap profile, and the box's side +//! of a shell command. +//! +//! `sandbox_args` is the profile her leased Persona session ran under, with the commons data dirs she may write bound back +//! read-write. `run_box` is what `mind-persona box-exec` does for one connection to `mind-box-.socket`: read one request, +//! run its command under the profile with a timeout, answer one receipt. It runs as `mind--box`, whose fence chain admits the +//! public internet and nothing on this host, so the boundary is the operating system's: nothing here filters a command. + +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant, SystemTime}; + +use serde::Deserialize; +use serde_json::{Value, json}; + +use crate::self_run::CONFIG_DIR_NAME; + +/// The commons data dirs her box writes: shared hand-offs and the cast's art. The rest of `/opt/commons` is read-only to her. +pub const COMMONS_RW: [&str; 2] = ["/opt/commons/handoff", "/opt/commons/cast-art"]; +/// The longest a command may run. +pub const TIMEOUT_MAX_S: u64 = 120; +/// How much of each output stream the receipt keeps: its tail. +const TAIL_BYTES: usize = 4096; +/// The most paths the receipt lists as written, and the most entries a walk for them visits. +const WROTE_MAX: usize = 64; +const WALK_MAX: usize = 20_000; + +/// The bubblewrap arguments up to the program: the whole filesystem read-only, a private `/tmp` and `/run`, the scratch +/// directory read-only with only its `claude-config` writable (nothing can create, replace or link a file where the organ +/// writes), her sandbox writable, each of `extra_rw` writable, her unit's credentials (`/etc/gamecult`, the other `/var/lib` +/// directories, everything under `/run`) hidden, a private process table, and the child dead when its parent is. The network +/// is shared: what it reaches is the uid fence's (gamecult-ops `mind-fence.service`). The boundary is the operating system's, +/// not a pattern list (ruling `eureka-body:ruling:persona-git-personal-sandbox`). +pub(crate) fn sandbox_args(sandbox: &Path, scratch: &Path, extra_rw: &[&Path]) -> Vec { + let (sandbox, scratch) = (sandbox.to_string_lossy(), scratch.to_string_lossy()); + let config = scratch.to_string() + "/" + CONFIG_DIR_NAME; + let mut args: Vec = [ + "--ro-bind", "/", "/", + "--dev", "/dev", + "--proc", "/proc", + "--tmpfs", "/tmp", + "--tmpfs", "/run", + "--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve", + "--ro-bind", &scratch, &scratch, + "--bind", &config, &config, + "--tmpfs", "/etc/gamecult", + "--tmpfs", "/var/lib", + "--bind", &sandbox, &sandbox, + ] + .map(String::from) + .to_vec(); + for path in extra_rw { + let path = path.to_string_lossy().into_owned(); + args.extend(["--bind".to_owned(), path.clone(), path]); + } + args.extend(["--unshare-pid", "--die-with-parent", "--new-session", "--chdir", &sandbox, "--"].map(String::from)); + args +} + +/// Where a box command runs: her box's home (writable, the working directory), its scratch (read-only, the unit's runtime +/// directory) and the other directories it may write. +pub struct BoxPaths<'a> { + pub home: &'a Path, + pub scratch: &'a Path, + pub extra_rw: &'a [&'a Path], +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct BoxRequest { + command: String, + #[serde(default)] + timeout_s: Option, +} + +/// The whole argv `run_box` executes for `command`: bwrap, the profile, then `/bin/sh -c command`. +pub(crate) fn box_argv(paths: &BoxPaths<'_>, command: &str) -> Vec { + let mut argv = vec!["bwrap".to_owned()]; + argv.extend(sandbox_args(paths.home, paths.scratch, paths.extra_rw)); + argv.extend(["/bin/sh".to_owned(), "-c".to_owned(), command.to_owned()]); + argv +} + +/// One shell command in her box: `request` is the bytes the connection sent (one JSON object, `{command, timeout_s}`), and the +/// answer is the receipt the connection gets back: `{tool: shell, status: ok|error, exit, duration_ms, stdout_tail, +/// stderr_tail, wrote}`. `ok` is a command that ran and exited 0; anything else is `error` with why. `wrote` lists the files +/// under the writable binds modified while it ran. +pub fn run_box(request: &[u8], paths: &BoxPaths<'_>) -> Value { + let error = |why: String| json!({ "tool": "shell", "status": "error", "why": why }); + let request: BoxRequest = match serde_json::from_slice(request) { + Ok(request) => request, + Err(_) => return error("the box could not read the request".to_owned()), + }; + let timeout = Duration::from_secs(request.timeout_s.unwrap_or(30).clamp(1, TIMEOUT_MAX_S)); + if let Err(fault) = std::fs::create_dir_all(paths.scratch.join(CONFIG_DIR_NAME)) { + return error(format!("the box's scratch could not be prepared: {fault}")); + } + // The marker: a file in the read-only scratch whose time is the filesystem's own, so what a command wrote compares + // against the same clock. + let marker = paths.scratch.join(".shell-marker"); + let since = std::fs::File::create(&marker).and_then(|file| file.metadata()).and_then(|meta| meta.modified()).unwrap_or_else(|_| SystemTime::now()); + let argv = box_argv(paths, &request.command); + let began = Instant::now(); + let mut child = match Command::new(&argv[0]).args(&argv[1..]).env("PATH", "/opt/commons/bin:/usr/bin:/bin").env("HOME", paths.home).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() { + Ok(child) => child, + Err(fault) => return error(format!("the box could not start: {fault}")), + }; + let tail_of = |stream: Option>| std::thread::spawn(move || stream.map(tail).unwrap_or_default()); + let stdout = tail_of(child.stdout.take().map(|out| Box::new(out) as Box)); + let stderr = tail_of(child.stderr.take().map(|err| Box::new(err) as Box)); + let mut timed_out = false; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break Some(status), + Ok(None) if began.elapsed() >= timeout => { + // bwrap is the sandbox's parent: killed, its child dies with it (`--die-with-parent`), and with that child, the + // pid namespace's init, every process the command left. + timed_out = true; + let _ = child.kill(); + break child.wait().ok(); + } + Ok(None) => std::thread::sleep(Duration::from_millis(20)), + Err(_) => break None, + } + }; + let duration_ms = u64::try_from(began.elapsed().as_millis()).unwrap_or(u64::MAX); + let (stdout_tail, stderr_tail) = (stdout.join().unwrap_or_default(), stderr.join().unwrap_or_default()); + let mut roots: Vec<&Path> = vec![paths.home]; + roots.extend(paths.extra_rw.iter().copied()); + let wrote = written(&roots, since); + let _ = std::fs::remove_file(&marker); + let exit = status.and_then(|status| status.code()); + let ok = !timed_out && exit == Some(0); + let mut receipt = json!({ "tool": "shell", "status": if ok { "ok" } else { "error" }, "exit": exit, "duration_ms": duration_ms, "stdout_tail": stdout_tail, "stderr_tail": stderr_tail, "wrote": wrote }); + if timed_out { + receipt["why"] = json!(format!("it ran past {} s and was stopped", timeout.as_secs())); + } else if !ok { + receipt["why"] = json!(exit.map_or_else(|| "it was ended by a signal".to_owned(), |code| format!("it exited {code}"))); + } + receipt +} + +/// The last `TAIL_BYTES` of a stream, read to its end, as text. +fn tail(mut stream: Box) -> String { + let mut kept: Vec = Vec::new(); + let mut chunk = [0u8; 8192]; + while let Ok(read) = stream.read(&mut chunk) { + if read == 0 { + break; + } + kept.extend_from_slice(&chunk[..read]); + if kept.len() > 2 * TAIL_BYTES { + kept.drain(..kept.len() - TAIL_BYTES); + } + } + let start = kept.len().saturating_sub(TAIL_BYTES); + String::from_utf8_lossy(&kept[start..]).into_owned() +} + +/// The files under `roots` modified at or after `since`, links not followed, at most `WROTE_MAX`, visiting at most `WALK_MAX` entries. +fn written(roots: &[&Path], since: SystemTime) -> Vec { + let mut found = Vec::new(); + let mut stack: Vec = roots.iter().map(|root| root.to_path_buf()).collect(); + let mut visited = 0usize; + 'walk: while let Some(dir) = stack.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { continue }; + for entry in entries.flatten() { + visited += 1; + if visited > WALK_MAX || found.len() >= WROTE_MAX { + break 'walk; + } + let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue }; + if meta.is_dir() { + stack.push(entry.path()); + } else if meta.is_file() && meta.modified().is_ok_and(|at| at >= since) { + found.push(entry.path().to_string_lossy().into_owned()); + } + } + } + found.sort(); + found +} + +/// `mind-persona box-exec`'s whole work over one connection: the request read from `input` to its end, the receipt written to +/// `output`. The connection is the socket systemd hands the unit as stdin and stdout. +pub fn serve_box(mut input: impl Read, mut output: impl Write, paths: &BoxPaths<'_>) -> std::io::Result<()> { + let mut request = Vec::new(); + input.by_ref().take(64 * 1024).read_to_end(&mut request)?; + let receipt = run_box(&request, paths); + output.write_all(receipt.to_string().as_bytes())?; + output.flush() +} + +#[cfg(test)] +mod tests; diff --git a/crates/mind-body/src/sandbox/tests.rs b/crates/mind-body/src/sandbox/tests.rs new file mode 100644 index 0000000..bd89951 --- /dev/null +++ b/crates/mind-body/src/sandbox/tests.rs @@ -0,0 +1,126 @@ +//! The one profile, and the box's side of a command. The tests that run `bwrap` run it as whoever runs the tests: on +//! Yggdrasil an unprivileged user, as `mind--box` is. + +use super::*; + +/// The profile, pinned: the whole tree read-only, a private `/tmp` and `/run`, the credentials hidden before her sandbox, the +/// scratch and each extra directory are bound back, the extra directories writable and bound before `--`, the network shared. +#[test] +fn the_profile_is_pinned() { + let args = sandbox_args(Path::new("/var/lib/mind-x-box"), Path::new("/run/mind-x-box"), &[Path::new("/opt/commons/handoff")]); + let expected: Vec = "--ro-bind / / --dev /dev --proc /proc --tmpfs /tmp --tmpfs /run --ro-bind-try /run/systemd/resolve /run/systemd/resolve --ro-bind /run/mind-x-box /run/mind-x-box --bind /run/mind-x-box/claude-config /run/mind-x-box/claude-config --tmpfs /etc/gamecult --tmpfs /var/lib --bind /var/lib/mind-x-box /var/lib/mind-x-box --bind /opt/commons/handoff /opt/commons/handoff --unshare-pid --die-with-parent --new-session --chdir /var/lib/mind-x-box --" + .split(' ') + .map(String::from) + .collect(); + assert_eq!(args, expected); + let at = |needle: &str| args.iter().position(|arg| arg == needle).unwrap(); + assert!(at("/run") < at("/run/mind-x-box") && at("/var/lib") < at("/var/lib/mind-x-box"), "hidden first, bound back after"); + assert!(!args.windows(3).any(|w| w[0] == "--bind" && w[1] == "/run/mind-x-box"), "the scratch is read-only: {args:?}"); + assert!(!args.iter().any(|arg| arg == "--unshare-net" || arg == "--unshare-all"), "the network is the fence's"); +} + +#[test] +fn t_a2_box_profile_is_sandbox_args() { + let (home, scratch, handoff, art) = (Path::new("/var/lib/mind-x-box"), Path::new("/run/mind-x-box"), Path::new("/opt/commons/handoff"), Path::new("/opt/commons/cast-art")); + let paths = BoxPaths { home, scratch, extra_rw: &[handoff, art] }; + let argv = box_argv(&paths, "ls -la"); + let mut expected = vec!["bwrap".to_owned()]; + expected.extend(sandbox_args(home, scratch, &[handoff, art])); + expected.extend(["/bin/sh", "-c", "ls -la"].map(String::from)); + assert_eq!(argv, expected, "bwrap, the one profile with the two commons data dirs, then /bin/sh -c"); + let dashes = argv.iter().position(|arg| arg == "--").unwrap(); + for dir in COMMONS_RW { + let bound = argv.windows(3).position(|w| w[0] == "--bind" && w[1] == dir && w[2] == dir).unwrap_or_else(|| panic!("{dir} is bound writable: {argv:?}")); + assert!(bound < dashes); + } +} + +struct Box3 { + _dir: tempfile::TempDir, + home: PathBuf, + scratch: PathBuf, + handoff: PathBuf, +} + +fn box3() -> Box3 { + let dir = tempfile::tempdir().unwrap(); + let (home, scratch, handoff) = (dir.path().join("home"), dir.path().join("scratch"), dir.path().join("handoff")); + for made in [&home, &scratch, &handoff] { + std::fs::create_dir(made).unwrap(); + } + Box3 { _dir: dir, home, scratch, handoff } +} + +fn run(rig: &Box3, command: &str, timeout_s: u64) -> Value { + let extra = [rig.handoff.as_path()]; + let mut answer = Vec::new(); + serve_box(json!({ "command": command, "timeout_s": timeout_s }).to_string().as_bytes(), &mut answer, &BoxPaths { home: &rig.home, scratch: &rig.scratch, extra_rw: &extra }).unwrap(); + serde_json::from_slice(&answer).unwrap() +} + +fn has_bwrap() -> bool { + let program = box_argv(&BoxPaths { home: Path::new("/"), scratch: Path::new("/"), extra_rw: &[] }, "true").swap_remove(0); + Command::new(program).arg("--version").output().is_ok_and(|out| out.status.success()) +} + +/// Inside the box, the drain's files are not there: the unit's configuration, its credentials and her Persona's state. +#[test] +fn t_a2_box_hides_drain_files() { + if !has_bwrap() { + return eprintln!("no bwrap on this host: skipped"); + } + let rig = box3(); + let receipt = run(&rig, "[ -z \"$(ls -A /etc/gamecult)\" ] && [ ! -e /run/credentials ] && [ ! -e /var/lib/mind-eureka ] && [ ! -e /var/lib/mind-heartbeat ] && [ -d \"$HOME\" ] && pwd", 20); + assert_eq!(receipt["status"], "ok", "{receipt}"); + assert_eq!(receipt["stdout_tail"].as_str().map(str::trim), rig.home.to_str(), "the command runs in her box's home"); + // On a host where they exist outside, the box hides them; where they do not, the check above still holds. + for outside in ["/etc/gamecult", "/var/lib/mind-eureka"] { + eprintln!("{outside} outside the box: {}", if Path::new(outside).exists() { "present" } else { "absent" }); + } +} + +/// A command that writes to a commons data dir lists the path it wrote in `wrote`, and only what it wrote. +#[test] +fn t_a2_box_commons_receipt() { + if !has_bwrap() { + return eprintln!("no bwrap on this host: skipped"); + } + let rig = box3(); + std::fs::write(rig.handoff.join("old"), "before").unwrap(); + std::thread::sleep(Duration::from_millis(20)); + let target = rig.handoff.join("x"); + let receipt = run(&rig, &format!("echo made > {} && echo note > notes.txt", target.display()), 20); + assert_eq!(receipt["status"], "ok", "{receipt}"); + let wrote: Vec<&str> = receipt["wrote"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(wrote.contains(&target.to_str().unwrap()), "{receipt}"); + assert!(wrote.contains(&rig.home.join("notes.txt").to_str().unwrap()), "her home is a writable bind too: {receipt}"); + assert!(!wrote.iter().any(|path| path.ends_with("/old")), "a file it did not write is not listed: {receipt}"); + assert_eq!(std::fs::read_to_string(&target).unwrap(), "made\n"); +} + +/// A command that fails is `error` with its exit; one that runs past its timeout is stopped and says so; a request that is no +/// request is refused before anything runs. +#[test] +fn the_box_says_what_went_wrong() { + if !has_bwrap() { + return eprintln!("no bwrap on this host: skipped"); + } + let rig = box3(); + let failed = run(&rig, "echo oops >&2; exit 3", 20); + assert_eq!((failed["status"].as_str(), failed["exit"].as_i64(), failed["stderr_tail"].as_str()), (Some("error"), Some(3), Some("oops\n")), "{failed}"); + let slow = run(&rig, "sleep 30", 1); + assert_eq!(slow["status"], "error", "{slow}"); + assert!(slow["why"].as_str().unwrap().contains("ran past 1 s"), "{slow}"); + assert!(slow["duration_ms"].as_u64().unwrap() < 10_000, "stopped at its timeout: {slow}"); + let mut answer = Vec::new(); + serve_box(&b"not json"[..], &mut answer, &BoxPaths { home: &rig.home, scratch: &rig.scratch, extra_rw: &[] }).unwrap(); + assert_eq!(serde_json::from_slice::(&answer).unwrap()["status"], "error"); +} + +/// The tail keeps the end of a long stream. +#[test] +fn a_tail_is_the_end() { + let long: Vec = (0..20_000u32).map(|at| b'a' + (at % 26) as u8).collect(); + let kept = tail(Box::new(std::io::Cursor::new(long.clone()))); + assert_eq!(kept.as_bytes(), &long[long.len() - TAIL_BYTES..]); +} diff --git a/crates/mind-body/src/self_run.rs b/crates/mind-body/src/self_run.rs index 44142ef..4608ee6 100644 --- a/crates/mind-body/src/self_run.rs +++ b/crates/mind-body/src/self_run.rs @@ -1012,8 +1012,6 @@ pub struct ClaudeSpawner { unit_environment: Vec<(OsString, OsString)>, scratch: PathBuf, seed: Option, - /// Her sandbox: with it the child runs under bubblewrap (`sandbox_args`), the Persona's; the Self passes none. - sandbox: Option, /// Where her one kept conversation lives (the second of the unit's `STATE_DIRECTORY` entries, outside her working directory, the first); none keeps nothing, and every start is fresh. keep: Option, /// The digest of the seed tree this process copies from (empty without a seed); none when the seed cannot be read, which no kept conversation matches. @@ -1031,23 +1029,15 @@ impl ClaudeSpawner { .iter() .find(|(name, _)| name == STATE_DIRECTORY_VARIABLE) .and_then(|(_, value)| value.to_string_lossy().split(':').nth(1).filter(|second| !second.is_empty()).map(PathBuf::from)); - let mut spawner = Self::in_sandbox(unit_environment, SEED_VARIABLE, None)?; - spawner.seed_digest = match &spawner.seed { - Some(seed) => seed_digest(seed).ok(), - None => Some(String::new()), - }; - spawner.keep = keep; - Ok(spawner) - } - - /// The same, with the seed named by `seed_variable` and, if `sandbox` is given, the child run under bubblewrap with that directory as its writable home. - pub fn in_sandbox(unit_environment: impl IntoIterator, seed_variable: &str, sandbox: Option) -> Result { - let unit_environment: Vec<(OsString, OsString)> = unit_environment.into_iter().collect(); let named = |variable: &str| unit_environment.iter().find(|(name, _)| name == variable).map(|(_, value)| PathBuf::from(value)); // systemd lists several runtime directories colon-separated; the unit names one. let scratch = named(SCRATCH_VARIABLE).filter(|path| !path.as_os_str().is_empty()).ok_or_else(|| anyhow!("{SCRATCH_VARIABLE} is not set: the unit needs RuntimeDirectory="))?; - let seed = named(seed_variable).filter(|path| !path.as_os_str().is_empty()); - Ok(Self { unit_environment, scratch, seed, sandbox, keep: None, seed_digest: None }) + let seed = named(SEED_VARIABLE).filter(|path| !path.as_os_str().is_empty()); + let seed_digest = match &seed { + Some(seed) => seed_digest(seed).ok(), + None => Some(String::new()), + }; + Ok(Self { unit_environment, scratch, seed, keep, seed_digest }) } } @@ -1146,50 +1136,12 @@ impl Spawner for ClaudeSpawner { fn spawn(&self, args: &[String], token: &TokenFd, session: Option<&str>) -> Result> { let config = FreshConfig::create(&self.scratch, self.seed.as_deref(), self.keep.clone())?; - let Some(sandbox) = &self.sandbox else { return spawn_program(Path::new("claude"), args, token, (&self.unit_environment, session), config) }; - let mut wrapped = sandbox_args(sandbox, &self.scratch); - wrapped.push("claude".into()); - wrapped.extend(args.iter().cloned()); - spawn_program(Path::new("bwrap"), &wrapped, token, (&self.unit_environment, session), config) + spawn_program(Path::new("claude"), args, token, (&self.unit_environment, session), config) } } -/// The bubblewrap arguments up to the program: the whole filesystem read-only, a private `/tmp` -/// and `/run`, the unit's scratch directory read-only with only its `claude-config` writable (she -/// cannot create, replace or link a file where the organ writes, such as the instructions file), -/// her sandbox writable, her unit's credentials (`/etc/gamecult`, the other `/var/lib` -/// directories, the lease socket under `/run`) hidden, a private process table, and the child dead -/// when the unit's process is. The network is shared: the web, `huginn` and the API are reachable, -/// and what she reaches on the host is the uid fence's (gamecult-ops `mind-fence.service`), which -/// binds the organ and this sandbox alike. The boundary is the operating system's, not a pattern -/// list (ruling `eureka-body:ruling:persona-git-personal-sandbox`). -pub(crate) fn sandbox_args(sandbox: &Path, scratch: &Path) -> Vec { - let (sandbox, scratch) = (sandbox.to_string_lossy(), scratch.to_string_lossy()); - let config = scratch.to_string() + "/" + CONFIG_DIR_NAME; - [ - "--ro-bind", "/", "/", - "--dev", "/dev", - "--proc", "/proc", - "--tmpfs", "/tmp", - "--tmpfs", "/run", - "--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve", - "--ro-bind", &scratch, &scratch, - "--bind", &config, &config, - "--tmpfs", "/etc/gamecult", - "--tmpfs", "/var/lib", - "--bind", &sandbox, &sandbox, - "--unshare-pid", - "--die-with-parent", - "--new-session", - "--chdir", &sandbox, - "--", - ] - .map(String::from) - .to_vec() -} - /// The directory name of a child's configuration inside the scratch directory. -const CONFIG_DIR_NAME: &str = "claude-config"; +pub(crate) const CONFIG_DIR_NAME: &str = "claude-config"; /// One child's configuration directory: made empty (or as the seed) for it, /// owner-only, and removed when the child's handle goes. Whatever the run writes diff --git a/crates/mind-body/src/self_run/tests.rs b/crates/mind-body/src/self_run/tests.rs index 40f0297..ef95fd9 100644 --- a/crates/mind-body/src/self_run/tests.rs +++ b/crates/mind-body/src/self_run/tests.rs @@ -2026,57 +2026,6 @@ fn a_brief_the_run_claims_is_in_the_task_once_and_not_again_under_also_open() { assert!(start.contains("Do the claimed thing.") && !start.contains("Also open for you"), "{start}"); } -/// The Persona's boundary: the bubblewrap wrapper `ClaudeSpawner` runs when it has a sandbox. -#[cfg(unix)] -mod sandbox { - use std::os::unix::fs::PermissionsExt; - - use super::*; - - #[test] - fn the_sandbox_arguments_are_pinned() { - let args = sandbox_args(Path::new("/var/lib/mind-x/sandbox"), Path::new("/run/mind-x")); - let expected: Vec = [ - "--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--tmpfs", "/tmp", "--tmpfs", "/run", "--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve", "--ro-bind", "/run/mind-x", "/run/mind-x", "--bind", - "/run/mind-x/claude-config", "/run/mind-x/claude-config", "--tmpfs", "/etc/gamecult", "--tmpfs", "/var/lib", "--bind", "/var/lib/mind-x/sandbox", "/var/lib/mind-x/sandbox", "--unshare-pid", "--die-with-parent", "--new-session", "--chdir", "/var/lib/mind-x/sandbox", "--", - ] - .map(String::from) - .to_vec(); - assert_eq!(args, expected); - // The credentials are hidden before the sandbox and the scratch are bound back, and the network is not unshared. - let at = |needle: &str| args.iter().position(|arg| arg == needle).unwrap(); - assert!(at("/run") < at("/run/mind-x") && at("/var/lib") < at("/var/lib/mind-x/sandbox")); - // The scratch is read-only to her: no plain bind of it, so she cannot plant a link where the organ writes. - assert!(!args.windows(3).any(|w| w[0] == "--bind" && w[1] == "/run/mind-x"), "{args:?}"); - assert!(!args.iter().any(|arg| arg == "--unshare-net" || arg == "--unshare-all")); - } - - #[test] - fn a_sandboxed_spawner_runs_bwrap_with_its_arguments_then_claude_and_the_child_sees_no_credential() { - let dir = tempfile::tempdir().unwrap(); - let (bin, scratch, sandbox) = (dir.path().join("bin"), dir.path().join("scratch"), dir.path().join("sandbox")); - for made in [&bin, &scratch, &sandbox] { - std::fs::create_dir(made).unwrap(); - } - let (argv, environment) = (dir.path().join("argv"), dir.path().join("environment")); - let fake = bin.join("bwrap"); - std::fs::write(&fake, format!("#!/bin/sh\nprintf '%s\n' \"$@\" > {}\nenv > {}\n", argv.display(), environment.display())).unwrap(); - std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); - let mut unit: Vec<(std::ffi::OsString, std::ffi::OsString)> = ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "UNLISTED_VARIABLE"].iter().map(|name| ((*name).into(), format!("canary-{name}").into())).collect(); - unit.push(("PATH".into(), format!("{}:/usr/bin:/bin", bin.display()).into())); - unit.push((SCRATCH_VARIABLE.into(), scratch.clone().into_os_string())); - let spawner = ClaudeSpawner::in_sandbox(unit, "MIND_PERSONA_CONFIG_SEED", Some(sandbox.clone())).unwrap(); - let mut child = spawner.spawn(&["--flag".to_string(), "value".to_string()], &token_holding("tok-canary"), None).unwrap(); - while !matches!(child.next(StdDuration::from_secs(20)), Read::Exited(_) | Read::Timeout) {} - let recorded: Vec = std::fs::read_to_string(&argv).unwrap().lines().map(String::from).collect(); - let mut expected = sandbox_args(&sandbox, &scratch); - expected.extend(["claude", "--flag", "value"].map(String::from)); - assert_eq!(recorded, expected, "bwrap, its arguments, then claude and its own"); - let seen = std::fs::read_to_string(&environment).unwrap(); - assert!(!seen.contains("canary") && !seen.contains("UNLISTED"), "the child's environment is the allow-list: {seen}"); - } -} - #[test] fn a_user_line_with_images_is_a_text_block_then_one_base64_image_block_each_and_without_them_is_the_bare_text() { use super::session::user_line;