interplane.Get Omega
Read in your language

spark-rsi-mv

Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger

Brought by drakestapleton

branch main Branches Tags History

spark-rsi-mv / src / isolation / cargo_sandbox.rs

304 lines · 11585 bytes Raw Blame History
1//! The one sandbox the judge uses for anything that compiles or runs candidate source.
2use std::path::{Path, PathBuf};
3use std::process::Command;
4
5/// Where this host's Rust toolchain lives, resolved the way cargo and rustup resolve it:
6/// `RUSTUP_HOME` and `CARGO_HOME` when set, else `$HOME/.rustup` and `$HOME/.cargo`, plus the
7/// `PATH` directory that holds `cargo`. Every jail that runs cargo binds exactly these
8/// directories read-only and points the same variables at them, so a host whose toolchain is
9/// not under `$HOME` (the Spark judge sandbox keeps it in `/var/lib/aien-run/{cargo,rustup}`)
10/// still builds. A directory that is or holds the judge's home is never exposed.
11#[derive(Debug, Clone, Default, PartialEq, Eq)]
12pub struct Toolchain {
13 pub rustup_home: Option<PathBuf>,
14 pub cargo_home: Option<PathBuf>,
15 pub cargo_dir: Option<PathBuf>,
16}
17
18impl Toolchain {
19 /// Resolves the toolchain from this process's environment.
20 pub fn from_env() -> Self {
21 Self::resolve(
22 std::env::var_os("HOME").map(PathBuf::from),
23 std::env::var_os("RUSTUP_HOME").map(PathBuf::from),
24 std::env::var_os("CARGO_HOME").map(PathBuf::from),
25 &std::env::var("PATH").unwrap_or_else(|_| "/usr/bin:/bin".into()),
26 )
27 }
28
29 /// Resolves the toolchain from explicit values (only directories that exist count).
30 pub fn resolve(
31 home: Option<PathBuf>,
32 rustup_home: Option<PathBuf>,
33 cargo_home: Option<PathBuf>,
34 path: &str,
35 ) -> Self {
36 let safe = |d: &PathBuf| home.as_ref().is_none_or(|h| !h.starts_with(d));
37 let pick = |set: Option<PathBuf>, default: &str| {
38 set.or_else(|| home.as_ref().map(|h| h.join(default)))
39 .filter(|p| p.is_dir())
40 .filter(safe)
41 };
42 let rustup_home = pick(rustup_home, ".rustup");
43 let cargo_home = pick(cargo_home, ".cargo");
44 let cargo_dir = path
45 .split(':')
46 .map(PathBuf::from)
47 .find(|d| d.join("cargo").is_file())
48 .filter(safe);
49 Self {
50 rustup_home,
51 cargo_home,
52 cargo_dir,
53 }
54 }
55
56 /// The directories a jail binds read-only (each once).
57 pub fn bind_dirs(&self) -> Vec<&Path> {
58 let mut dirs: Vec<&Path> = Vec::new();
59 for d in [&self.rustup_home, &self.cargo_home, &self.cargo_dir]
60 .into_iter()
61 .flatten()
62 {
63 if !dirs.contains(&d.as_path()) {
64 dirs.push(d);
65 }
66 }
67 dirs
68 }
69
70 /// The `RUSTUP_HOME` / `CARGO_HOME` values a jail sets.
71 pub fn env(&self) -> Vec<(&'static str, &Path)> {
72 let mut env = Vec::new();
73 if let Some(d) = &self.rustup_home {
74 env.push(("RUSTUP_HOME", d.as_path()));
75 }
76 if let Some(d) = &self.cargo_home {
77 env.push(("CARGO_HOME", d.as_path()));
78 }
79 env
80 }
81
82 /// The jail's `PATH`: the toolchain's bin directories first, then `tail`.
83 pub fn jail_path(&self, tail: &[&str]) -> String {
84 let mut path: Vec<String> = Vec::new();
85 let bins = [
86 self.cargo_dir.clone(),
87 self.cargo_home.as_ref().map(|c| c.join("bin")),
88 ];
89 for d in bins.into_iter().flatten() {
90 let d = d.display().to_string();
91 if !path.contains(&d) {
92 path.push(d);
93 }
94 }
95 for t in tail {
96 if !path.iter().any(|p| p == t) {
97 path.push(t.to_string());
98 }
99 }
100 path.join(":")
101 }
102}
103
104/// `systemd-run --user --scope` with the launcher environment every bounded launch uses.
105fn user_scope() -> Command {
106 let mut cmd = Command::new("/usr/bin/systemd-run");
107 cmd.env_clear();
108 // This is launcher-only: bubblewrap clears it before starting candidate code.
109 cmd.env(
110 "XDG_RUNTIME_DIR",
111 std::env::var_os("XDG_RUNTIME_DIR")
112 .unwrap_or_else(|| format!("/run/user/{}", unsafe { libc::getuid() }).into()),
113 );
114 cmd.args(["--user", "--scope", "--quiet", "--collect"]);
115 cmd
116}
117
118/// Whether this host can start the transient user scope that every bounded launch needs, that is,
119/// whether a systemd user manager for this uid is reachable. It starts `/usr/bin/true` through
120/// the same launcher. Tests use it to report NOT_RUN (`crate::not_run`); the launchers never
121/// consult it and still fail closed when the scope cannot start.
122pub(crate) fn user_scope_available() -> bool {
123 user_scope()
124 .arg("/usr/bin/true")
125 .stdout(std::process::Stdio::null())
126 .stderr(std::process::Stdio::null())
127 .status()
128 .is_ok_and(|s| s.success())
129}
130
131/// The common fail-closed host launcher for untrusted code. The user scope charges
132/// the whole process tree, including tmpfs/memfd, rather than sampled process RSS.
133pub(crate) fn bounded_bwrap(
134 limits: &super::container::SandboxLimits,
135 timeout: Option<u64>,
136) -> Command {
137 let mut cmd = user_scope();
138 cmd.arg(format!("--property=MemoryMax={}M", limits.max_memory_mb));
139 cmd.arg("--property=MemorySwapMax=0");
140 cmd.arg(format!("--property=TasksMax={}", limits.max_pids));
141 cmd.arg(format!("--property=CPUQuota={}%", limits.max_cpu_percent));
142 if let Some(seconds) = timeout {
143 cmd.arg(format!("--property=RuntimeMaxSec={}s", seconds));
144 }
145 cmd.arg("/usr/bin/bwrap");
146 cmd
147}
148
149/// `cargo <args>` for `tree` inside bubblewrap: no network, cleared launcher and jail
150/// environments, no view of the judge's home (where its signing key lives), the tree read-only
151/// at `/src`, only `target` writable (at `/target`, which must exist), and the toolchain read-only.
152/// Cargo compilation is limited to two jobs. Build scripts, proc macros, `include_bytes!` and
153/// the candidate's own tests run or read here, so they cannot reach the key. There is no
154/// fallback: if the sandbox cannot start, the command fails.
155pub fn sandboxed_cargo(tree: &Path, target: &Path, args: &[&str]) -> Command {
156 let toolchain = Toolchain::from_env();
157 let limits = super::container::SandboxLimits::default();
158 let mut cmd = bounded_bwrap(&limits, Some(limits.timeout_seconds));
159 cmd.args([
160 "--unshare-user",
161 "--unshare-ipc",
162 "--unshare-pid",
163 "--unshare-net",
164 "--unshare-uts",
165 "--die-with-parent",
166 "--clearenv",
167 "--proc",
168 "/proc",
169 "--dev",
170 "/dev",
171 "--tmpfs",
172 "/tmp",
173 ]);
174 for sys in ["/usr", "/lib", "/lib64", "/bin", "/etc"] {
175 if Path::new(sys).exists() {
176 cmd.args(["--ro-bind", sys, sys]);
177 }
178 }
179 for d in toolchain.bind_dirs() {
180 cmd.arg("--ro-bind").arg(d).arg(d);
181 }
182 for (k, d) in toolchain.env() {
183 cmd.arg("--setenv").arg(k).arg(d);
184 }
185 cmd.arg("--ro-bind").arg(tree).arg("/src");
186 cmd.arg("--bind").arg(target).arg("/target");
187 let path_in = match &toolchain.cargo_dir {
188 Some(d) => format!("{}:/usr/bin:/bin", d.display()),
189 None => "/usr/bin:/bin".to_string(),
190 };
191 cmd.args(["--setenv", "PATH", &path_in]);
192 cmd.args([
193 "--setenv",
194 "HOME",
195 "/tmp",
196 "--setenv",
197 "CARGO_TARGET_DIR",
198 "/target",
199 "--setenv",
200 "CARGO_BUILD_JOBS",
201 "2",
202 ]);
203 cmd.args(["--chdir", "/src", "cargo"]);
204 cmd.args(args);
205 cmd
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211
212 #[test]
213 fn sandbox_cargo_clears_environment_and_uses_only_isolated_output() {
214 let cmd = sandboxed_cargo(
215 Path::new("/tmp/candidate-source"),
216 Path::new("/tmp/candidate-target"),
217 &["check", "--offline", "--locked"],
218 );
219 let args: Vec<_> = cmd
220 .get_args()
221 .map(|arg| arg.to_string_lossy().into_owned())
222 .collect();
223 let clear = args.iter().position(|arg| arg == "--clearenv").unwrap();
224 let set = args.iter().position(|arg| arg == "--setenv").unwrap();
225 assert!(clear < set);
226 assert!(args.windows(3).any(|w| w == ["--setenv", "HOME", "/tmp"]));
227 assert!(args
228 .windows(3)
229 .any(|w| w == ["--setenv", "CARGO_TARGET_DIR", "/target"]));
230 assert!(args
231 .windows(3)
232 .any(|w| w == ["--setenv", "CARGO_BUILD_JOBS", "2"]));
233 assert!(args
234 .windows(3)
235 .any(|w| w == ["--ro-bind", "/tmp/candidate-source", "/src"]));
236 assert!(args
237 .windows(3)
238 .any(|w| w == ["--bind", "/tmp/candidate-target", "/target"]));
239 assert!(args.ends_with(&["cargo", "check", "--offline", "--locked"].map(str::to_string)));
240 let toolchain = Toolchain::from_env();
241 for d in toolchain.bind_dirs() {
242 let d = d.display().to_string();
243 assert!(args
244 .windows(3)
245 .any(|w| w[0] == "--ro-bind" && w[1] == d && w[2] == d));
246 }
247 for (key, path) in toolchain.env() {
248 let path = path.display().to_string();
249 assert!(args
250 .windows(3)
251 .any(|w| w[0] == "--setenv" && w[1] == key && w[2] == path));
252 }
253 }
254
255 /// The Spark judge sandbox keeps the toolchain beside HOME, not under it: HOME is
256 /// `/var/lib/aien-run`, the toolchain `/var/lib/aien-run/{cargo,rustup}`. The jails must
257 /// find it through CARGO_HOME / RUSTUP_HOME and PATH, not by guessing `$HOME/.cargo`.
258 #[test]
259 fn toolchain_outside_home_dotdirs_is_found_through_its_variables() {
260 let root = tempfile::tempdir().unwrap();
261 let home = root.path().to_path_buf();
262 let cargo_home = home.join("cargo");
263 let rustup_home = home.join("rustup");
264 std::fs::create_dir_all(cargo_home.join("bin")).unwrap();
265 std::fs::create_dir_all(&rustup_home).unwrap();
266 std::fs::write(cargo_home.join("bin/cargo"), b"").unwrap();
267 let path = format!("{}:/usr/bin:/bin", cargo_home.join("bin").display());
268
269 let t = Toolchain::resolve(
270 Some(home.clone()),
271 Some(rustup_home.clone()),
272 Some(cargo_home.clone()),
273 &path,
274 );
275 assert_eq!(t.rustup_home.as_deref(), Some(rustup_home.as_path()));
276 assert_eq!(t.cargo_home.as_deref(), Some(cargo_home.as_path()));
277 assert_eq!(t.cargo_dir, Some(cargo_home.join("bin")));
278 assert!(t.bind_dirs().contains(&cargo_home.as_path()));
279 assert!(t.bind_dirs().contains(&rustup_home.as_path()));
280 assert!(t
281 .jail_path(&["/usr/bin", "/bin"])
282 .starts_with(&cargo_home.join("bin").display().to_string()));
283
284 // Without the variables the `$HOME/.cargo` guess finds nothing here: the old behaviour.
285 let guessed = Toolchain::resolve(Some(home), None, None, "/usr/bin:/bin");
286 assert!(guessed.cargo_home.is_none() && guessed.rustup_home.is_none());
287 }
288
289 #[test]
290 fn a_directory_holding_the_judge_home_is_never_exposed() {
291 let root = tempfile::tempdir().unwrap();
292 let home = root.path().join("judge");
293 std::fs::create_dir_all(&home).unwrap();
294 let t = Toolchain::resolve(
295 Some(home),
296 Some(root.path().to_path_buf()),
297 Some(root.path().to_path_buf()),
298 "/usr/bin:/bin",
299 );
300 assert!(t.rustup_home.is_none());
301 assert!(t.cargo_home.is_none());
302 assert!(t.bind_dirs().is_empty());
303 }
304}