| 1 | //! Shared test-only helpers. |
| 2 | |
| 3 | #[cfg(test)] |
| 4 | use std::ffi::OsString; |
| 5 | use std::path::Path; |
| 6 | #[cfg(any(unix, test))] |
| 7 | use std::path::PathBuf; |
| 8 | #[cfg(unix)] |
| 9 | use std::sync::OnceLock; |
| 10 | |
| 11 | pub use codewhale_runtime::test_support::*; |
| 12 | |
| 13 | pub use codewhale_skills::install_project_cordis_skill_fixture; |
| 14 | |
| 15 | /// `CODEWHALE_CONFORMANCE_UPDATE=1` rewrites goldens from the current source. |
| 16 | pub const UPDATE_ENV: &str = "CODEWHALE_CONFORMANCE_UPDATE"; |
| 17 | |
| 18 | pub fn update_mode() -> bool { |
| 19 | let requested = std::env::var(UPDATE_ENV).is_ok_and(|value| value == "1"); |
| 20 | if requested && std::env::var_os("CI").is_some_and(|value| !value.is_empty()) { |
| 21 | panic!("{UPDATE_ENV}=1 is refused under CI: goldens are reviewed source, not build output"); |
| 22 | } |
| 23 | requested |
| 24 | } |
| 25 | |
| 26 | /// Compare `actual` with the golden at `path`; in update mode write it |
| 27 | /// instead. Returns a failure description rather than panicking so a family |
| 28 | /// can report every drifted case in one run. |
| 29 | pub fn check_golden(path: &Path, actual: &str) -> Result<(), String> { |
| 30 | let update = update_mode(); |
| 31 | let expected = std::fs::read_to_string(path).ok(); |
| 32 | if expected.as_deref() == Some(actual) { |
| 33 | return Ok(()); |
| 34 | } |
| 35 | if update { |
| 36 | if let Some(parent) = path.parent() { |
| 37 | std::fs::create_dir_all(parent).expect("create golden dir"); |
| 38 | } |
| 39 | std::fs::write(path, actual).expect("write golden"); |
| 40 | eprintln!("conformance: rewrote {}", path.display()); |
| 41 | return Ok(()); |
| 42 | } |
| 43 | let Some(expected) = expected else { |
| 44 | return Err(format!( |
| 45 | "missing golden {}; review the output and record it with {UPDATE_ENV}=1", |
| 46 | path.display() |
| 47 | )); |
| 48 | }; |
| 49 | Err(format!( |
| 50 | "golden drift at {}\n{}\nIf this change is intended, re-record with {UPDATE_ENV}=1 and review the diff.", |
| 51 | path.display(), |
| 52 | first_difference(&expected, actual) |
| 53 | )) |
| 54 | } |
| 55 | |
| 56 | fn first_difference(expected: &str, actual: &str) -> String { |
| 57 | let expected_lines: Vec<&str> = expected.lines().collect(); |
| 58 | let actual_lines: Vec<&str> = actual.lines().collect(); |
| 59 | let index = expected_lines |
| 60 | .iter() |
| 61 | .zip(&actual_lines) |
| 62 | .position(|(left, right)| left != right) |
| 63 | .unwrap_or_else(|| expected_lines.len().min(actual_lines.len())); |
| 64 | let character = match (expected_lines.get(index), actual_lines.get(index)) { |
| 65 | (Some(left), Some(right)) => left |
| 66 | .chars() |
| 67 | .zip(right.chars()) |
| 68 | .take_while(|(left, right)| left == right) |
| 69 | .count(), |
| 70 | _ => 0, |
| 71 | }; |
| 72 | let start = character.saturating_sub(40); |
| 73 | let show = |lines: &[&str]| { |
| 74 | lines.get(index).map_or_else( |
| 75 | || "<end of file>".to_string(), |
| 76 | |line| { |
| 77 | let window: String = line.chars().skip(start).take(601).collect(); |
| 78 | format!( |
| 79 | "{}{}", |
| 80 | if start == 0 { "" } else { "…" }, |
| 81 | truncate(&window, 600) |
| 82 | ) |
| 83 | }, |
| 84 | ) |
| 85 | }; |
| 86 | format!( |
| 87 | "first difference at line {}, character {} (expected {} lines, got {}):\n expected: {}\n actual: {}", |
| 88 | index + 1, |
| 89 | character + 1, |
| 90 | expected_lines.len(), |
| 91 | actual_lines.len(), |
| 92 | show(&expected_lines), |
| 93 | show(&actual_lines) |
| 94 | ) |
| 95 | } |
| 96 | |
| 97 | fn truncate(line: &str, max: usize) -> String { |
| 98 | if line.chars().count() <= max { |
| 99 | return line.to_string(); |
| 100 | } |
| 101 | let head: String = line.chars().take(max).collect(); |
| 102 | format!("{head}…") |
| 103 | } |
| 104 | |
| 105 | /// A fixture workspace an OS sandbox can still see (#6305). |
| 106 | /// |
| 107 | /// The Linux bwrap wrapper mounts a fresh `--tmpfs /tmp` before it binds the |
| 108 | /// policy's writable roots (`sandbox/bwrap.rs`), and an enforced read-only |
| 109 | /// command has no writable roots at all — nothing re-exposes the host `/tmp`. |
| 110 | /// A fixture rooted there is shadowed inside the sandbox, so the trailing |
| 111 | /// `--chdir <workspace>` lands on a path that no longer exists and bwrap exits |
| 112 | /// with `Can't chdir to /tmp/.tmpXXXXXX`. The tmpfs is deliberate isolation and |
| 113 | /// a security boundary, so the fixture moves instead of the mount. |
| 114 | /// |
| 115 | /// Known limitations: this relocates only the directory the sandboxed command |
| 116 | /// chdirs into. It does not make anything else under the host `/tmp` reachable |
| 117 | /// from inside the sandbox, and it says nothing about `/dev` or `/proc`, which |
| 118 | /// bwrap also replaces. Use it for the sandbox probes; plain `tempfile::tempdir` |
| 119 | /// stays correct everywhere else. |
| 120 | // Every caller is `#[cfg(unix)]` (the bwrap probes); on Windows these would |
| 121 | // be dead code and CI builds tests with `-Dwarnings`. |
| 122 | #[cfg(unix)] |
| 123 | pub fn sandbox_visible_tempdir() -> tempfile::TempDir { |
| 124 | let root = sandbox_visible_fixture_root(); |
| 125 | tempfile::tempdir_in(root).unwrap_or_else(|error| { |
| 126 | panic!( |
| 127 | "failed to create a sandbox-visible fixture workspace in {}: {error}", |
| 128 | root.display() |
| 129 | ) |
| 130 | }) |
| 131 | } |
| 132 | |
| 133 | /// `OUT_DIR` is this crate's own build directory, so it follows the Cargo |
| 134 | /// target directory rather than `TMPDIR` — the one path every test binary |
| 135 | /// already owns and that is outside `/tmp` in every normal layout. A target |
| 136 | /// directory deliberately placed under `/tmp` would silently reintroduce |
| 137 | /// #6305, so say so instead of handing back a shadowed path. |
| 138 | #[cfg(unix)] |
| 139 | fn sandbox_visible_fixture_root() -> &'static Path { |
| 140 | static ROOT: OnceLock<PathBuf> = OnceLock::new(); |
| 141 | ROOT.get_or_init(|| { |
| 142 | let root = Path::new(env!("OUT_DIR")).join("sandbox-fixtures"); |
| 143 | assert!( |
| 144 | !root.starts_with("/tmp"), |
| 145 | "sandbox fixtures need a root outside /tmp, which bwrap replaces with a fresh \ |
| 146 | tmpfs: {} is under it. Point CARGO_TARGET_DIR somewhere else.", |
| 147 | root.display() |
| 148 | ); |
| 149 | std::fs::create_dir_all(&root).unwrap_or_else(|error| { |
| 150 | panic!( |
| 151 | "failed to create the sandbox fixture root {}: {error}", |
| 152 | root.display() |
| 153 | ) |
| 154 | }); |
| 155 | root |
| 156 | }) |
| 157 | } |
| 158 | |
| 159 | #[cfg(test)] |
| 160 | mod tests { |
| 161 | use super::*; |
| 162 | use std::sync::mpsc; |
| 163 | use std::time::Duration; |
| 164 | |
| 165 | fn env_snapshot(keys: &[&str]) -> Vec<Option<OsString>> { |
| 166 | let _lock = lock_test_env(); |
| 167 | keys.iter().map(std::env::var_os).collect() |
| 168 | } |
| 169 | |
| 170 | #[test] |
| 171 | fn sealed_home_pins_every_alias_and_restores_the_environment() { |
| 172 | const KEYS: [&str; 8] = [ |
| 173 | "HOME", |
| 174 | "USERPROFILE", |
| 175 | "HOMEDRIVE", |
| 176 | "HOMEPATH", |
| 177 | "CODEWHALE_HOME", |
| 178 | "CODEWHALE_CONFIG_PATH", |
| 179 | "DEEPSEEK_CONFIG_PATH", |
| 180 | "DEEPSEEK_HOME", |
| 181 | ]; |
| 182 | let before = env_snapshot(&KEYS); |
| 183 | { |
| 184 | let seal = SealedHome::new(); |
| 185 | let now = |key: &str| std::env::var_os(key); |
| 186 | assert_eq!(now("HOME").as_deref(), Some(seal.home().as_os_str())); |
| 187 | assert_eq!(now("USERPROFILE").as_deref(), Some(seal.home().as_os_str())); |
| 188 | assert_eq!( |
| 189 | now("CODEWHALE_HOME").as_deref(), |
| 190 | Some(seal.codewhale_home().as_os_str()) |
| 191 | ); |
| 192 | for alias in [ |
| 193 | "HOMEDRIVE", |
| 194 | "HOMEPATH", |
| 195 | "CODEWHALE_CONFIG_PATH", |
| 196 | "DEEPSEEK_CONFIG_PATH", |
| 197 | "DEEPSEEK_HOME", |
| 198 | ] { |
| 199 | assert_eq!(now(alias), None, "{alias} would route around the seal"); |
| 200 | } |
| 201 | assert!(guarded_environment_provides_state_paths()); |
| 202 | assert!(home_is_sealed()); |
| 203 | // A resolver that follows the environment lands inside the seal. |
| 204 | let sessions = crate::session_manager::default_sessions_dir().expect("sessions dir"); |
| 205 | assert_eq!(sessions, seal.codewhale_home().join("sessions")); |
| 206 | } |
| 207 | { |
| 208 | let owned = tempfile::tempdir().expect("owned home"); |
| 209 | let seal = SealedHome::at(owned.path()); |
| 210 | assert_eq!(seal.home(), owned.path()); |
| 211 | assert_eq!(seal.codewhale_home(), owned.path().join(".codewhale")); |
| 212 | } |
| 213 | assert_eq!(env_snapshot(&KEYS), before, "the seal must restore the env"); |
| 214 | } |
| 215 | |
| 216 | /// The fence on every resolver a test reaches without ever thinking about |
| 217 | /// the home: an unsealed test must land in the isolated root, whatever the |
| 218 | /// ambient `HOME` / `CODEWHALE_HOME` say. Add a resolver here when it grows |
| 219 | /// a `#[cfg(any(test, feature = "test-support"))]` fence — and fence the next one before a test finds it. |
| 220 | #[test] |
| 221 | fn unsealed_state_resolvers_stay_inside_the_isolated_root() { |
| 222 | // Hold the barrier to keep the fixture's environment stable. |
| 223 | let _lock = lock_test_env(); |
| 224 | assert!(!home_is_sealed()); |
| 225 | let root = isolated_test_state_root(); |
| 226 | let inside = |label: &str, path: &Path| { |
| 227 | assert!( |
| 228 | path.starts_with(root), |
| 229 | "{label} resolved outside the isolated test root: {}", |
| 230 | path.display() |
| 231 | ); |
| 232 | }; |
| 233 | |
| 234 | inside( |
| 235 | "sessions", |
| 236 | &crate::session_manager::default_sessions_dir().expect("sessions dir"), |
| 237 | ); |
| 238 | inside( |
| 239 | "snapshots", |
| 240 | &codewhale_snapshot::snapshot_dir_for(Path::new("/nonexistent/codewhale-fence-probe")) |
| 241 | .expect("snapshot dir"), |
| 242 | ); |
| 243 | inside( |
| 244 | "audit log", |
| 245 | &codewhale_runtime::audit::audit_log_path().expect("audit log path"), |
| 246 | ); |
| 247 | } |
| 248 | |
| 249 | #[test] |
| 250 | fn home_seal_is_available_only_to_its_owner_and_enrolled_workers() { |
| 251 | let seal = SealedHome::new(); |
| 252 | let sessions = seal.codewhale_home().join("sessions"); |
| 253 | let ticket = env_scope_ticket().expect("seal owns an environment scope"); |
| 254 | |
| 255 | std::thread::spawn(move || { |
| 256 | assert!(!home_is_sealed(), "a foreign worker cannot follow the seal"); |
| 257 | assert!( |
| 258 | crate::session_manager::default_sessions_dir() |
| 259 | .expect("isolated sessions dir") |
| 260 | .starts_with(isolated_test_state_root()) |
| 261 | ); |
| 262 | |
| 263 | let membership = join_env_scope(Some(ticket)).expect("enroll worker"); |
| 264 | assert!(home_is_sealed()); |
| 265 | assert_eq!( |
| 266 | crate::session_manager::default_sessions_dir().expect("sealed sessions dir"), |
| 267 | sessions |
| 268 | ); |
| 269 | drop(membership); |
| 270 | assert!(!home_is_sealed(), "leaving the scope withdraws the seal"); |
| 271 | }) |
| 272 | .join() |
| 273 | .expect("home seal worker"); |
| 274 | } |
| 275 | |
| 276 | #[test] |
| 277 | fn removing_home_variables_does_not_seal_a_missing_path() { |
| 278 | let _lock = lock_test_env(); |
| 279 | let _home = EnvVarGuard::remove("HOME"); |
| 280 | let _userprofile = EnvVarGuard::remove("USERPROFILE"); |
| 281 | |
| 282 | assert!( |
| 283 | !guarded_environment_provides_state_paths(), |
| 284 | "removing HOME variables must keep state in the isolated test root" |
| 285 | ); |
| 286 | assert_eq!( |
| 287 | codewhale_runtime::config_persistence::config_toml_path(None) |
| 288 | .expect("resolve isolated config path"), |
| 289 | unsealed_test_state_root().join(codewhale_config::CONFIG_FILE_NAME) |
| 290 | ); |
| 291 | } |
| 292 | |
| 293 | #[test] |
| 294 | fn lock_without_sealed_paths_does_not_use_developer_config() { |
| 295 | let _lock = lock_test_env(); |
| 296 | let path = codewhale_runtime::config_persistence::config_toml_path(None) |
| 297 | .expect("resolve isolated config path"); |
| 298 | let root = isolated_test_state_root(); |
| 299 | assert!( |
| 300 | path.starts_with(root), |
| 301 | "holding lock_test_env without an EnvVarGuard must not read ~/.codewhale ({})", |
| 302 | path.display() |
| 303 | ); |
| 304 | assert_eq!( |
| 305 | path, |
| 306 | unsealed_test_state_root().join(codewhale_config::CONFIG_FILE_NAME) |
| 307 | ); |
| 308 | } |
| 309 | |
| 310 | #[test] |
| 311 | fn unguarded_state_writes_use_isolated_test_root() { |
| 312 | const PROBE_ENV: &str = "CODEWHALE_TEST_STATE_ISOLATION_PROBE"; |
| 313 | const RECEIPT_ENV: &str = "CODEWHALE_TEST_STATE_ISOLATION_RECEIPT"; |
| 314 | |
| 315 | if std::env::var_os(PROBE_ENV).is_some() { |
| 316 | let config_path = codewhale_runtime::config_persistence::persist_root_bool_key( |
| 317 | None, |
| 318 | "allow_shell", |
| 319 | true, |
| 320 | ) |
| 321 | .expect("write isolated config"); |
| 322 | let direct_config_path = codewhale_runtime::config::save_workspace_trust(Path::new( |
| 323 | "/tmp/codewhale-test-workspace", |
| 324 | )) |
| 325 | .expect("write through direct default config path"); |
| 326 | codewhale_runtime::settings::Settings::default() |
| 327 | .save() |
| 328 | .expect("write isolated settings"); |
| 329 | let settings_path = |
| 330 | codewhale_runtime::settings::Settings::path().expect("resolve isolated settings"); |
| 331 | let root = isolated_test_state_root(); |
| 332 | assert!(config_path.starts_with(root), "{}", config_path.display()); |
| 333 | assert!( |
| 334 | settings_path.starts_with(root), |
| 335 | "{}", |
| 336 | settings_path.display() |
| 337 | ); |
| 338 | assert!( |
| 339 | direct_config_path.starts_with(root), |
| 340 | "{}", |
| 341 | direct_config_path.display() |
| 342 | ); |
| 343 | assert!(config_path.exists()); |
| 344 | assert!(settings_path.exists()); |
| 345 | let receipt = std::env::var_os(RECEIPT_ENV).expect("receipt path"); |
| 346 | std::fs::write( |
| 347 | receipt, |
| 348 | format!( |
| 349 | "{}\n{}\n{}\n{}\n", |
| 350 | root.display(), |
| 351 | config_path.display(), |
| 352 | settings_path.display(), |
| 353 | direct_config_path.display() |
| 354 | ), |
| 355 | ) |
| 356 | .expect("write isolation receipt"); |
| 357 | return; |
| 358 | } |
| 359 | |
| 360 | let sentinel = tempfile::tempdir().expect("sentinel home"); |
| 361 | let user_state = sentinel.path().join(".codewhale"); |
| 362 | std::fs::create_dir_all(&user_state).expect("create sentinel state"); |
| 363 | let config_path = user_state.join("config.toml"); |
| 364 | let settings_path = user_state.join("settings.toml"); |
| 365 | let config_sentinel = b"# developer config sentinel\n"; |
| 366 | let settings_sentinel = b"# developer settings sentinel\n"; |
| 367 | std::fs::write(&config_path, config_sentinel).expect("seed config"); |
| 368 | std::fs::write(&settings_path, settings_sentinel).expect("seed settings"); |
| 369 | let receipt_path = sentinel.path().join("receipt.txt"); |
| 370 | |
| 371 | let output = std::process::Command::new(std::env::current_exe().expect("test binary")) |
| 372 | .arg("--exact") |
| 373 | .arg("test_support::tests::unguarded_state_writes_use_isolated_test_root") |
| 374 | .arg("--test-threads=1") |
| 375 | .env(PROBE_ENV, "1") |
| 376 | .env(RECEIPT_ENV, &receipt_path) |
| 377 | .env("HOME", sentinel.path()) |
| 378 | .env("USERPROFILE", sentinel.path()) |
| 379 | .env_remove("CODEWHALE_HOME") |
| 380 | .env_remove("CODEWHALE_CONFIG_PATH") |
| 381 | .env_remove("DEEPSEEK_CONFIG_PATH") |
| 382 | .output() |
| 383 | .expect("run isolated-state probe"); |
| 384 | assert!( |
| 385 | output.status.success(), |
| 386 | "probe failed\nstdout:\n{}\nstderr:\n{}", |
| 387 | String::from_utf8_lossy(&output.stdout), |
| 388 | String::from_utf8_lossy(&output.stderr) |
| 389 | ); |
| 390 | |
| 391 | assert_eq!( |
| 392 | std::fs::read(&config_path).expect("read config sentinel"), |
| 393 | config_sentinel |
| 394 | ); |
| 395 | assert_eq!( |
| 396 | std::fs::read(&settings_path).expect("read settings sentinel"), |
| 397 | settings_sentinel |
| 398 | ); |
| 399 | |
| 400 | let receipt = std::fs::read_to_string(&receipt_path).expect("read isolation receipt"); |
| 401 | let mut paths = receipt.lines().map(PathBuf::from); |
| 402 | let isolated_root = paths.next().expect("root receipt"); |
| 403 | let written_config = paths.next().expect("config receipt"); |
| 404 | let written_settings = paths.next().expect("settings receipt"); |
| 405 | let direct_config = paths.next().expect("direct config receipt"); |
| 406 | assert!(!isolated_root.starts_with(sentinel.path())); |
| 407 | assert!(written_config.starts_with(&isolated_root)); |
| 408 | assert!(written_settings.starts_with(&isolated_root)); |
| 409 | assert!(direct_config.starts_with(&isolated_root)); |
| 410 | assert!( |
| 411 | !isolated_root.exists(), |
| 412 | "probe leaked {}", |
| 413 | isolated_root.display() |
| 414 | ); |
| 415 | } |
| 416 | |
| 417 | #[test] |
| 418 | fn config_path_read_waits_for_foreign_env_redirect_to_restore() { |
| 419 | let (started_tx, started_rx) = mpsc::channel(); |
| 420 | let (tx, rx) = mpsc::channel(); |
| 421 | let redirected = std::env::temp_dir().join(format!( |
| 422 | "codewhale-config-path-read-barrier-{}", |
| 423 | std::process::id() |
| 424 | )); |
| 425 | |
| 426 | let reader = { |
| 427 | let lock = lock_test_env(); |
| 428 | let redirect = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &redirected); |
| 429 | let reader = std::thread::spawn(move || { |
| 430 | started_tx.send(()).expect("signal config path read start"); |
| 431 | tx.send(codewhale_runtime::config_persistence::config_toml_path( |
| 432 | None, |
| 433 | )) |
| 434 | .expect("send resolved config path"); |
| 435 | }); |
| 436 | |
| 437 | started_rx |
| 438 | .recv_timeout(Duration::from_secs(2)) |
| 439 | .expect("reader reached config path resolution"); |
| 440 | assert!( |
| 441 | rx.recv_timeout(Duration::from_millis(50)).is_err(), |
| 442 | "a foreign reader observed the temporary config redirect" |
| 443 | ); |
| 444 | drop(redirect); |
| 445 | drop(lock); |
| 446 | reader |
| 447 | }; |
| 448 | |
| 449 | let resolved = rx |
| 450 | .recv_timeout(Duration::from_secs(2)) |
| 451 | .expect("reader resumed after the redirect was restored") |
| 452 | .expect("resolve config path"); |
| 453 | reader.join().expect("reader thread"); |
| 454 | assert_ne!(resolved, redirected); |
| 455 | } |
| 456 | |
| 457 | #[test] |
| 458 | fn settings_save_waits_for_foreign_state_io_transaction() { |
| 459 | let (holder_ready_tx, holder_ready_rx) = mpsc::channel(); |
| 460 | let (release_tx, release_rx) = mpsc::channel(); |
| 461 | let holder = std::thread::spawn(move || { |
| 462 | with_test_state_io_lock(|| { |
| 463 | holder_ready_tx.send(()).expect("signal state lock held"); |
| 464 | release_rx.recv().expect("release state lock"); |
| 465 | }); |
| 466 | }); |
| 467 | holder_ready_rx |
| 468 | .recv_timeout(Duration::from_secs(2)) |
| 469 | .expect("holder acquired state I/O lock"); |
| 470 | |
| 471 | let (started_tx, started_rx) = mpsc::channel(); |
| 472 | let (saved_tx, saved_rx) = mpsc::channel(); |
| 473 | let writer = std::thread::spawn(move || { |
| 474 | started_tx.send(()).expect("signal settings save start"); |
| 475 | saved_tx |
| 476 | .send(codewhale_runtime::settings::Settings::default().save()) |
| 477 | .expect("send settings save result"); |
| 478 | }); |
| 479 | started_rx |
| 480 | .recv_timeout(Duration::from_secs(2)) |
| 481 | .expect("writer reached settings save"); |
| 482 | assert!( |
| 483 | saved_rx.recv_timeout(Duration::from_millis(50)).is_err(), |
| 484 | "settings save did not wait for an in-flight state transaction" |
| 485 | ); |
| 486 | |
| 487 | release_tx.send(()).expect("release holder"); |
| 488 | holder.join().expect("holder thread"); |
| 489 | saved_rx |
| 490 | .recv_timeout(Duration::from_secs(2)) |
| 491 | .expect("settings save resumed") |
| 492 | .expect("settings save succeeded"); |
| 493 | writer.join().expect("writer thread"); |
| 494 | } |
| 495 | } |
| 496 |