spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / tests / test_security_isolation.rs
| 1 | //! Offline security boundary regressions. All host effects stay inside private tempdirs. |
| 2 | use spark_rsi::isolation::BuildJail; |
| 3 | use spark_rsi::observe::observe_codebase; |
| 4 | use spark_rsi::supervisor::HostSupervisor; |
| 5 | use spark_rsi::verifier::InvariantVerifier; |
| 6 | use std::fs; |
| 7 | use std::os::unix::fs::PermissionsExt; |
| 8 | use std::os::unix::net::UnixListener; |
| 9 | use std::path::Path; |
| 10 | |
| 11 | fn crate_at(root: &Path, source: &str, build: Option<&str>) { |
| 12 | fs::create_dir_all(root.join("src")).unwrap(); |
| 13 | fs::write( |
| 14 | root.join("Cargo.toml"), |
| 15 | "[package]\nname='boundary-probe'\nversion='0.1.0'\nedition='2021'\n", |
| 16 | ) |
| 17 | .unwrap(); |
| 18 | fs::write( |
| 19 | root.join("Cargo.lock"), |
| 20 | "version = 4\n\n[[package]]\nname = \"boundary-probe\"\nversion = \"0.1.0\"\n", |
| 21 | ) |
| 22 | .unwrap(); |
| 23 | fs::write(root.join("src/lib.rs"), source).unwrap(); |
| 24 | if let Some(build) = build { |
| 25 | fs::write(root.join("build.rs"), build).unwrap(); |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | #[test] |
| 30 | fn invariant_tests_cannot_write_host_files() { |
| 31 | if !spark_rsi::not_run::user_scope_or_not_run("invariant_tests_cannot_write_host_files") { |
| 32 | return; |
| 33 | } |
| 34 | let tmp = tempfile::tempdir().unwrap(); |
| 35 | let marker = tmp.path().join("host-only-marker"); |
| 36 | let tree = tmp.path().join("candidate"); |
| 37 | crate_at( |
| 38 | &tree, |
| 39 | &format!( |
| 40 | "#[test] fn confined() {{ assert!(std::fs::write({:?}, b\"escaped\").is_err()); }}", |
| 41 | marker |
| 42 | ), |
| 43 | None, |
| 44 | ); |
| 45 | let (compiled, error, passed, summary) = InvariantVerifier::verify_compilation_and_tests(&tree); |
| 46 | assert!(!marker.exists(), "candidate test wrote a host-only file"); |
| 47 | assert!( |
| 48 | compiled && passed, |
| 49 | "isolated test did not run successfully: {error:?} {summary:?}" |
| 50 | ); |
| 51 | assert!( |
| 52 | !tree.join("target").exists(), |
| 53 | "candidate source became writable build output" |
| 54 | ); |
| 55 | } |
| 56 | |
| 57 | #[test] |
| 58 | fn observation_build_scripts_cannot_write_host_files() { |
| 59 | if !spark_rsi::not_run::user_scope_or_not_run( |
| 60 | "observation_build_scripts_cannot_write_host_files", |
| 61 | ) { |
| 62 | return; |
| 63 | } |
| 64 | let tmp = tempfile::tempdir().unwrap(); |
| 65 | let marker = tmp.path().join("observer-host-marker"); |
| 66 | let tree = tmp.path().join("candidate"); |
| 67 | crate_at( |
| 68 | &tree, |
| 69 | "pub fn answer() -> u8 { 7 }", |
| 70 | Some(&format!( |
| 71 | "fn main() {{ assert!(std::fs::write({:?}, b\"escaped\").is_err()); }}", |
| 72 | marker |
| 73 | )), |
| 74 | ); |
| 75 | let observed = observe_codebase(&tree).unwrap(); |
| 76 | assert!( |
| 77 | !marker.exists(), |
| 78 | "observation ran a build script on the host" |
| 79 | ); |
| 80 | assert!( |
| 81 | observed.tests_passing, |
| 82 | "isolated compilation did not succeed" |
| 83 | ); |
| 84 | assert!(!tree.join("target").exists()); |
| 85 | } |
| 86 | |
| 87 | #[test] |
| 88 | fn failing_candidate_tests_are_not_accepted() { |
| 89 | if !spark_rsi::not_run::user_scope_or_not_run("failing_candidate_tests_are_not_accepted") { |
| 90 | return; |
| 91 | } |
| 92 | let tmp = tempfile::tempdir().unwrap(); |
| 93 | crate_at( |
| 94 | tmp.path(), |
| 95 | "#[test] fn negative_control() { panic!(\"intentional refusal\"); }", |
| 96 | None, |
| 97 | ); |
| 98 | let (compiled, _, passed, summary) = |
| 99 | InvariantVerifier::verify_compilation_and_tests(tmp.path()); |
| 100 | assert!(compiled, "negative control must compile"); |
| 101 | assert!( |
| 102 | !passed, |
| 103 | "intentionally failing candidate was accepted: {summary:?}" |
| 104 | ); |
| 105 | } |
| 106 | |
| 107 | #[test] |
| 108 | fn build_jail_does_not_inherit_service_environment() { |
| 109 | if !spark_rsi::not_run::user_scope_or_not_run("build_jail_does_not_inherit_service_environment") |
| 110 | { |
| 111 | return; |
| 112 | } |
| 113 | let tmp = tempfile::tempdir().unwrap(); |
| 114 | let source = tmp.path().join("source"); |
| 115 | let output = tmp.path().join("output"); |
| 116 | fs::create_dir_all(&source).unwrap(); |
| 117 | fs::create_dir_all(&output).unwrap(); |
| 118 | std::env::set_var("RSI_BUILD_SECRET_SENTINEL", "harmless-service-secret"); |
| 119 | let result = BuildJail::new("unused", &source, &output).execute_bwrap(&[ |
| 120 | "/bin/sh", |
| 121 | "-c", |
| 122 | "test -z \"$RSI_BUILD_SECRET_SENTINEL\" && printf scrubbed", |
| 123 | ]); |
| 124 | std::env::remove_var("RSI_BUILD_SECRET_SENTINEL"); |
| 125 | let (passed, stdout, stderr) = result.unwrap(); |
| 126 | assert!( |
| 127 | passed && stdout == "scrubbed", |
| 128 | "environment crossed build boundary: {stdout:?} {stderr:?}" |
| 129 | ); |
| 130 | } |
| 131 | |
| 132 | #[test] |
| 133 | fn canary_cannot_read_or_write_supervisor_files() { |
| 134 | if !spark_rsi::not_run::user_scope_or_not_run("canary_cannot_read_or_write_supervisor_files") { |
| 135 | return; |
| 136 | } |
| 137 | let tmp = tempfile::tempdir().unwrap(); |
| 138 | let secret = tmp.path().join("operator-secret"); |
| 139 | let marker = tmp.path().join("canary-host-marker"); |
| 140 | fs::write(&secret, b"harmless-private-sentinel").unwrap(); |
| 141 | let network = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); |
| 142 | let port = network.local_addr().unwrap().port(); |
| 143 | let script = tmp.path().join("worker"); |
| 144 | fs::write(&script, format!("#!/bin/bash\nif cat {:?} > {:?} 2>/dev/null; then exit 41; fi\nif echo escaped > {:?} 2>/dev/null; then exit 42; fi\nprintf scratch-ok > /scratch/ok || exit 43\ntest \"$HOME\" = /tmp || exit 44\nif (echo escaped > /dev/tcp/127.0.0.1/{port}) 2>/dev/null; then exit 45; fi\nexit 0\n", secret, marker, marker)).unwrap(); |
| 145 | fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); |
| 146 | let socket = tmp.path().join("worker.sock"); |
| 147 | let _listener = UnixListener::bind(&socket).unwrap(); |
| 148 | let supervisor = HostSupervisor::new(&tmp.path().join("state"), 1024); |
| 149 | let artifacts = tmp.path().join("artifacts"); |
| 150 | fs::create_dir_all(&artifacts).unwrap(); |
| 151 | let mut generation = supervisor |
| 152 | .stage_generation("confined", &artifacts, "test") |
| 153 | .unwrap(); |
| 154 | let mut child = supervisor |
| 155 | .spawn_worker_process(&mut generation, &script, &[], &socket, &[]) |
| 156 | .unwrap(); |
| 157 | let status = child.wait().unwrap(); |
| 158 | assert!( |
| 159 | !marker.exists(), |
| 160 | "canary read or overwrote supervisor-owned files" |
| 161 | ); |
| 162 | assert!( |
| 163 | status.success(), |
| 164 | "canary confinement probe did not execute: {status}" |
| 165 | ); |
| 166 | assert_eq!(fs::read(&secret).unwrap(), b"harmless-private-sentinel"); |
| 167 | } |
| 168 | |
| 169 | fn descendants(pid: u32) -> Vec<u32> { |
| 170 | let mut result = Vec::new(); |
| 171 | let Ok(children) = fs::read_to_string(format!("/proc/{pid}/task/{pid}/children")) else { |
| 172 | return result; |
| 173 | }; |
| 174 | for child in children.split_whitespace() { |
| 175 | let child = child.parse::<u32>().unwrap(); |
| 176 | result.push(child); |
| 177 | result.extend(descendants(child)); |
| 178 | } |
| 179 | result |
| 180 | } |
| 181 | |
| 182 | #[test] |
| 183 | fn stopping_canary_reaps_forked_descendants() { |
| 184 | if !spark_rsi::not_run::user_scope_or_not_run("stopping_canary_reaps_forked_descendants") { |
| 185 | return; |
| 186 | } |
| 187 | let tmp = tempfile::tempdir().unwrap(); |
| 188 | let script = tmp.path().join("worker"); |
| 189 | fs::write(&script, "#!/bin/sh\nsleep 60 &\nwait\n").unwrap(); |
| 190 | fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); |
| 191 | let socket = tmp.path().join("worker.sock"); |
| 192 | let _listener = UnixListener::bind(&socket).unwrap(); |
| 193 | let supervisor = HostSupervisor::new(&tmp.path().join("state"), 1024); |
| 194 | let artifacts = tmp.path().join("artifacts"); |
| 195 | fs::create_dir_all(&artifacts).unwrap(); |
| 196 | let mut generation = supervisor |
| 197 | .stage_generation("forking", &artifacts, "test") |
| 198 | .unwrap(); |
| 199 | let mut child = supervisor |
| 200 | .spawn_worker_process(&mut generation, &script, &[], &socket, &[]) |
| 201 | .unwrap(); |
| 202 | let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3); |
| 203 | let children = loop { |
| 204 | let children = descendants(child.id()); |
| 205 | if children.len() >= 3 || std::time::Instant::now() >= deadline { |
| 206 | break children; |
| 207 | } |
| 208 | std::thread::sleep(std::time::Duration::from_millis(10)); |
| 209 | }; |
| 210 | child.kill().unwrap(); |
| 211 | child.wait().unwrap(); |
| 212 | let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3); |
| 213 | let survivors = loop { |
| 214 | let survivors: Vec<u32> = children |
| 215 | .iter() |
| 216 | .copied() |
| 217 | .filter(|pid| { |
| 218 | fs::read_to_string(format!("/proc/{pid}/stat")) |
| 219 | .map(|stat| { |
| 220 | !stat |
| 221 | .rsplit_once(')') |
| 222 | .unwrap() |
| 223 | .1 |
| 224 | .trim_start() |
| 225 | .starts_with('Z') |
| 226 | }) |
| 227 | .unwrap_or(false) |
| 228 | }) |
| 229 | .collect(); |
| 230 | if survivors.is_empty() || std::time::Instant::now() >= deadline { |
| 231 | break survivors; |
| 232 | } |
| 233 | std::thread::sleep(std::time::Duration::from_millis(10)); |
| 234 | }; |
| 235 | // Cleanup is bounded to this test's recorded children even on a regressed host launch. |
| 236 | for pid in &survivors { |
| 237 | unsafe { |
| 238 | libc::kill(*pid as i32, libc::SIGKILL); |
| 239 | } |
| 240 | } |
| 241 | assert!( |
| 242 | children.len() >= 3, |
| 243 | "worker namespace and forked child did not start" |
| 244 | ); |
| 245 | assert!( |
| 246 | survivors.is_empty(), |
| 247 | "canary descendants outlived monitor: {survivors:?}" |
| 248 | ); |
| 249 | } |
| 250 | |
| 251 | #[test] |
| 252 | fn canary_tmpfs_is_charged_to_a_hard_memory_limit() { |
| 253 | if !spark_rsi::not_run::user_scope_or_not_run("canary_tmpfs_is_charged_to_a_hard_memory_limit") |
| 254 | { |
| 255 | return; |
| 256 | } |
| 257 | let tmp = tempfile::tempdir().unwrap(); |
| 258 | let script = tmp.path().join("worker"); |
| 259 | fs::write(&script, "#!/bin/sh\nprintf ok > /scratch/small || exit 40\nexec dd if=/dev/zero of=/scratch/fill bs=1M count=64 status=none\n").unwrap(); |
| 260 | fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); |
| 261 | let socket = tmp.path().join("worker.sock"); |
| 262 | let _listener = UnixListener::bind(&socket).unwrap(); |
| 263 | let supervisor = HostSupervisor::new(&tmp.path().join("state"), 32); |
| 264 | let artifacts = tmp.path().join("artifacts"); |
| 265 | fs::create_dir_all(&artifacts).unwrap(); |
| 266 | let mut generation = supervisor |
| 267 | .stage_generation("bounded", &artifacts, "test") |
| 268 | .unwrap(); |
| 269 | let mut child = supervisor |
| 270 | .spawn_worker_process(&mut generation, &script, &[], &socket, &[]) |
| 271 | .unwrap(); |
| 272 | let status = child.wait().unwrap(); |
| 273 | println!("tmpfs pressure canary status: {status}"); |
| 274 | assert_ne!( |
| 275 | status.code(), |
| 276 | Some(40), |
| 277 | "scratch setup failed before memory pressure" |
| 278 | ); |
| 279 | assert!( |
| 280 | !status.success(), |
| 281 | "worker filled tmpfs beyond its hard budget" |
| 282 | ); |
| 283 | } |
| 284 | |
| 285 | #[test] |
| 286 | fn build_jail_tmpfs_is_charged_to_a_hard_memory_limit() { |
| 287 | if !spark_rsi::not_run::user_scope_or_not_run( |
| 288 | "build_jail_tmpfs_is_charged_to_a_hard_memory_limit", |
| 289 | ) { |
| 290 | return; |
| 291 | } |
| 292 | let tmp = tempfile::tempdir().unwrap(); |
| 293 | let source = tmp.path().join("source"); |
| 294 | let output = tmp.path().join("output"); |
| 295 | fs::create_dir_all(&source).unwrap(); |
| 296 | fs::create_dir_all(&output).unwrap(); |
| 297 | let mut jail = BuildJail::new("unused", &source, &output); |
| 298 | jail.limits.max_memory_mb = 32; |
| 299 | let (passed, _, stderr) = jail.execute_bwrap(&[ |
| 300 | "/bin/sh", "-c", |
| 301 | "printf scratch-ok > /tmp/small && exec dd if=/dev/zero of=/tmp/fill bs=1M count=64 status=none", |
| 302 | ]).unwrap(); |
| 303 | assert!( |
| 304 | !passed, |
| 305 | "build process exceeded its hard memory limit: {stderr}" |
| 306 | ); |
| 307 | } |