diff --git a/src/drivers.rs b/src/drivers.rs index 8d331dd..2469028 100644 --- a/src/drivers.rs +++ b/src/drivers.rs @@ -8436,6 +8436,144 @@ mod tests { Ok(()) } + /// F6/N1 (Soul, second Cut 1 fix batch): `--read-only` is present on a + /// Named network runner even when a cache root is also mounted. Neither + /// branch alone exercised this combination before. + #[cfg(unix)] + #[test] + fn docker_run_args_keeps_read_only_with_a_named_network_and_a_cache_root() -> Result<()> { + use std::os::unix::fs::PermissionsExt; + let temp = tempfile::tempdir()?; + fs::set_permissions(temp.path(), fs::Permissions::from_mode(0o755))?; + let cache = temp.path().join("cache"); + let mut runner = fixture_docker_runner_binding(); + runner.network_profile = Some("build-net".to_owned()); + runner.cache_root = Some(cache); + let spec = ContainerSpec::for_step( + &runner, + &std::collections::BTreeSet::new(), + ("IDUNN_SOURCE_REVISION", "abc123"), + )?; + let workspace = PathBuf::from("/var/lib/gamecult/idunn/staging/txn-n1/.runner-rust"); + let args = docker_run_args(&spec, &workspace, Path::new("."), &vec!["cargo".to_owned(), "test".to_owned()])?; + assert!( + args.iter().any(|a| a == OsStr::new("--read-only")), + "a Named network plus a cache root must not drop --read-only: {args:?}" + ); + Ok(()) + } + + /// F6/N2 (Soul, second Cut 1 fix batch): a secret mount stays read-only + /// even when the runner also carries a plain environment entry. + #[cfg(unix)] + #[test] + fn docker_run_args_keeps_secret_mounts_read_only_alongside_plain_environment() -> Result<()> { + use std::os::unix::fs::PermissionsExt; + let temp = tempfile::tempdir()?; + fs::set_permissions(temp.path(), fs::Permissions::from_mode(0o755))?; + let secret = temp.path().join("secret.cc"); + fs::write(&secret, b"s").unwrap(); + ensure!( + Command::new("/bin/chown").arg("0:65532").arg(&secret).status()?.success(), + "chowning fixture secret" + ); + fs::set_permissions(&secret, fs::Permissions::from_mode(0o440))?; + + let mut runner = fixture_docker_runner_binding(); + runner.secret_files = BTreeMap::from([("A_SECRET".to_owned(), secret.clone())]); + runner.environment = BTreeMap::from([("PLAIN_ONE".to_owned(), "x".to_owned())]); + let required = std::collections::BTreeSet::from(["A_SECRET".to_owned(), "PLAIN_ONE".to_owned()]); + let spec = ContainerSpec::for_step(&runner, &required, ("IDUNN_SOURCE_REVISION", "abc123"))?; + let workspace = PathBuf::from("/var/lib/gamecult/idunn/staging/txn-n2/.runner-rust"); + let args = docker_run_args(&spec, &workspace, Path::new("."), &vec!["cargo".to_owned(), "test".to_owned()])?; + let secret_text = secret.display().to_string(); + let mount = args + .iter() + .map(|a| a.to_string_lossy().into_owned()) + .find(|a| a.starts_with("type=bind") && a.contains(&secret_text)) + .expect("secret mount present"); + assert!( + mount.ends_with(",readonly"), + "a plain environment entry must not make a secret mount writable: {mount}" + ); + Ok(()) + } + + /// F6/N3 (Soul, second Cut 1 fix batch): the Idunn source stamp survives + /// as the container's environment even when the runner carries both a + /// secret and a plain environment entry. + #[cfg(unix)] + #[test] + fn container_spec_for_step_keeps_the_source_stamp_with_a_secret_and_plain_environment() -> Result<()> { + use std::os::unix::fs::PermissionsExt; + let temp = tempfile::tempdir()?; + fs::set_permissions(temp.path(), fs::Permissions::from_mode(0o755))?; + let secret = temp.path().join("secret.cc"); + fs::write(&secret, b"s").unwrap(); + ensure!( + Command::new("/bin/chown").arg("0:65532").arg(&secret).status()?.success(), + "chowning fixture secret" + ); + fs::set_permissions(&secret, fs::Permissions::from_mode(0o440))?; + + let mut runner = fixture_docker_runner_binding(); + runner.secret_files = BTreeMap::from([("A_SECRET".to_owned(), secret)]); + runner.environment = BTreeMap::from([("PLAIN_ONE".to_owned(), "x".to_owned())]); + let required = std::collections::BTreeSet::from(["A_SECRET".to_owned(), "PLAIN_ONE".to_owned()]); + let spec = ContainerSpec::for_step(&runner, &required, ("IDUNN_SOURCE_REVISION", "abc123"))?; + assert_eq!( + spec.environment.first(), + Some(&("IDUNN_SOURCE_REVISION".to_owned(), "abc123".to_owned())), + "the source stamp must survive alongside a secret and a plain environment entry" + ); + Ok(()) + } + + /// F6/N5 (Soul, second Cut 1 fix batch): `freeze_exact` records that the + /// frozen tree contains a Git LFS pointer, and the pointer bytes + /// themselves -- never the real LFS content, which is never fetched -- + /// are what land on disk. + #[cfg(unix)] + #[test] + fn freeze_exact_sets_the_lfs_pointer_flag_for_a_pointer_file() -> Result<()> { + use std::os::unix::fs::PermissionsExt; + let temp = tempfile::tempdir()?; + fs::set_permissions(temp.path(), fs::Permissions::from_mode(0o755))?; + let origin_repo = temp.path().join("origin"); + fs::create_dir(&origin_repo)?; + git_at(&origin_repo, &["init", "--initial-branch=main"])?; + git_at(&origin_repo, &["config", "user.name", "Idunn Test"])?; + git_at(&origin_repo, &["config", "user.email", "idunn-test@example.invalid"])?; + fs::write(origin_repo.join("deployment.toml"), b"target = 'test'\n")?; + let pointer = b"version https://git-lfs.github.com/spec/v1\noid sha256:0000000000000000000000000000000000000000000000000000000000000000\nsize 3\n"; + fs::write(origin_repo.join("lfs.bin"), pointer)?; + git_at(&origin_repo, &["add", "--all"])?; + git_at(&origin_repo, &["commit", "-m", "fixture"])?; + let revision = git_at(&origin_repo, &["rev-parse", "HEAD"])?; + ensure!( + Command::new("/bin/chown").args(["-R", "1000:1000"]).arg(&origin_repo).status()?.success(), + "chowning the fixture origin repository" + ); + + let source_cache_root = temp.path().join("source-cache"); + let frozen_source_root = temp.path().join("frozen-source"); + fs::create_dir(&frozen_source_root)?; + fs::set_permissions(&frozen_source_root, fs::Permissions::from_mode(0o700))?; + let identity = ProcessIdentity { uid: 1000, gid: 1000 }; + let driver = GitSourceDriver::new(source_cache_root.clone(), frozen_source_root.clone(), Some(identity)); + let source = ExactSource { + origin: origin_repo.to_string_lossy().into_owned(), + checkout: source_cache_root.join("checkout"), + gitlinks: BTreeMap::new(), + recipe_path: PathBuf::from("deployment.toml"), + }; + let (tree_root, _snapshot_sha256, _recipe_bytes, contains_lfs_pointers) = + driver.freeze_exact(&source, &revision, "txn-lfs", &frozen_source_root)?; + assert!(contains_lfs_pointers, "an LFS pointer file must set the flag"); + assert_eq!(fs::read(tree_root.join("lfs.bin"))?, pointer); + Ok(()) + } + /// Cut 1 fix batch, F1, S9: `ContainerSpec::for_step` must call /// `validate_runner_secret`, not merely mount whatever path the binding /// names. This fixture's secret file has the wrong mode (`0644` instead @@ -8736,6 +8874,358 @@ mod tests { Ok(()) } + /// F1 (Self's ruling, second Cut 1 fix batch): every blob a frozen tree + /// needs is fetched in one bulk round trip, not lazily one object at a + /// time as `cat-file --batch` reads them. A spy standing in for + /// `/usr/bin/git` records every invocation; exactly one of them is the + /// bulk `fetch --stdin` call. + #[cfg(unix)] + #[test] + fn freeze_exact_bulk_fetches_every_blob_in_one_round_trip() -> Result<()> { + use std::os::unix::fs::PermissionsExt; + + let temp = tempfile::tempdir()?; + fs::set_permissions(temp.path(), fs::Permissions::from_mode(0o755))?; + + let origin_repo = temp.path().join("origin"); + fs::create_dir(&origin_repo)?; + git_at(&origin_repo, &["init", "--initial-branch=main"])?; + git_at(&origin_repo, &["config", "user.name", "Idunn Test"])?; + git_at( + &origin_repo, + &["config", "user.email", "idunn-test@example.invalid"], + )?; + fs::write(origin_repo.join("deployment.toml"), b"target = 'test'\n")?; + for i in 0..8 { + fs::write(origin_repo.join(format!("f{i}.txt")), format!("file {i}\n"))?; + } + git_at(&origin_repo, &["add", "--all"])?; + git_at(&origin_repo, &["commit", "-m", "fixture"])?; + let revision = git_at(&origin_repo, &["rev-parse", "HEAD"])?; + ensure!( + Command::new("/bin/chown") + .args(["-R", "1000:1000"]) + .arg(&origin_repo) + .status()? + .success(), + "chowning the fixture origin repository" + ); + + let source_cache_root = temp.path().join("source-cache"); + let frozen_source_root = temp.path().join("frozen-source"); + fs::create_dir(&frozen_source_root)?; + fs::set_permissions(&frozen_source_root, fs::Permissions::from_mode(0o700))?; + + let log = temp.path().join("git-invocations.log"); + let spy = temp.path().join("git-spy.sh"); + fs::write( + &spy, + format!( + "#!/bin/sh\necho \"$@\" >> {}\nexec /usr/bin/git \"$@\"\n", + log.display() + ), + )?; + fs::set_permissions(&spy, fs::Permissions::from_mode(0o755))?; + + let identity = ProcessIdentity { + uid: 1000, + gid: 1000, + }; + let mut driver = GitSourceDriver::new( + source_cache_root.clone(), + frozen_source_root.clone(), + Some(identity), + ); + driver.git_program = spy; + let source = ExactSource { + origin: origin_repo.to_string_lossy().into_owned(), + checkout: source_cache_root.join("checkout"), + gitlinks: BTreeMap::new(), + recipe_path: PathBuf::from("deployment.toml"), + }; + + driver.freeze_exact(&source, &revision, "txn-bulk", &frozen_source_root)?; + let log_text = fs::read_to_string(&log).unwrap_or_default(); + let bulk_fetches = log_text + .lines() + .filter(|line| line.contains("fetch") && line.contains("--stdin")) + .count(); + assert_eq!( + bulk_fetches, 1, + "expected exactly one bulk --stdin fetch; invocations:\n{log_text}" + ); + Ok(()) + } + + /// F2/F3 (Self's rulings, second Cut 1 fix batch): a tree with two + /// entries literally named `a` at the same level -- one a symlink + /// pointing outside the frozen root, one a subtree holding `pwn` -- must + /// be refused before anything is written, not partially materialized. + /// `git hash-object --literally` builds the tree directly, bypassing the + /// checks `git mktree` would apply, the same construction Soul's probe + /// used to find the regression this pins. + #[cfg(unix)] + #[test] + fn freeze_exact_refuses_a_duplicate_named_tree_that_would_write_outside_its_root() -> Result<()> { + use std::os::unix::fs::PermissionsExt; + + let temp = tempfile::tempdir()?; + fs::set_permissions(temp.path(), fs::Permissions::from_mode(0o755))?; + + let hash_object = |repo: &Path, content: &[u8]| -> Result { + let mut child = Command::new("git") + .args(["-c", "safe.directory=*", "-C"]) + .arg(repo) + .args(["hash-object", "-w", "--stdin"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn()?; + child.stdin.take().unwrap().write_all(content)?; + let output = child.wait_with_output()?; + ensure!(output.status.success(), "git hash-object failed"); + Ok(String::from_utf8(output.stdout)?.trim().to_owned()) + }; + + let outside = temp.path().join("outside-root-owned"); + fs::create_dir(&outside)?; + fs::set_permissions(&outside, fs::Permissions::from_mode(0o755))?; + + let origin_repo = temp.path().join("origin"); + fs::create_dir(&origin_repo)?; + git_at(&origin_repo, &["init", "--initial-branch=main"])?; + git_at(&origin_repo, &["config", "user.name", "Idunn Test"])?; + git_at( + &origin_repo, + &["config", "user.email", "idunn-test@example.invalid"], + )?; + let recipe = hash_object(&origin_repo, b"target = 'test'\n")?; + let pwn = hash_object(&origin_repo, b"written through a symlink by root\n")?; + let link = hash_object(&origin_repo, outside.to_string_lossy().as_bytes())?; + let subtree_output = Command::new("git") + .args(["-c", "safe.directory=*", "-C"]) + .arg(&origin_repo) + .args(["mktree"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .and_then(|mut child| { + use std::io::Write as _; + child + .stdin + .take() + .unwrap() + .write_all(format!("100644 blob {pwn}\tpwn\n").as_bytes())?; + child.wait_with_output() + })?; + ensure!(subtree_output.status.success(), "git mktree failed"); + let subtree = String::from_utf8(subtree_output.stdout)?.trim().to_owned(); + + let hex = |s: &str| -> Vec { + (0..20) + .map(|i| u8::from_str_radix(&s[2 * i..2 * i + 2], 16).unwrap()) + .collect() + }; + let mut raw = Vec::new(); + for (mode, name, sha) in [ + ("120000", "a", &link), + ("40000", "a", &subtree), + ("100644", "deployment.toml", &recipe), + ] { + raw.extend_from_slice(format!("{mode} {name}\0").as_bytes()); + raw.extend(hex(sha)); + } + let mut child = Command::new("git") + .args(["-c", "safe.directory=*", "-C"]) + .arg(&origin_repo) + .args(["hash-object", "-t", "tree", "--literally", "-w", "--stdin"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn()?; + child.stdin.take().unwrap().write_all(&raw)?; + let output = child.wait_with_output()?; + ensure!(output.status.success(), "git hash-object --literally failed"); + let tree = String::from_utf8(output.stdout)?.trim().to_owned(); + let commit = git_at(&origin_repo, &["commit-tree", &tree, "-m", "dup"])?; + git_at(&origin_repo, &["update-ref", "refs/heads/main", &commit])?; + ensure!( + Command::new("/bin/chown") + .args(["-R", "1000:1000"]) + .arg(&origin_repo) + .status()? + .success(), + "chowning the fixture origin repository" + ); + + let source_cache_root = temp.path().join("source-cache"); + let frozen_source_root = temp.path().join("frozen-source"); + fs::create_dir(&frozen_source_root)?; + fs::set_permissions(&frozen_source_root, fs::Permissions::from_mode(0o700))?; + let identity = ProcessIdentity { + uid: 1000, + gid: 1000, + }; + let driver = GitSourceDriver::new( + source_cache_root.clone(), + frozen_source_root.clone(), + Some(identity), + ); + let source = ExactSource { + origin: origin_repo.to_string_lossy().into_owned(), + checkout: source_cache_root.join("checkout"), + gitlinks: BTreeMap::new(), + recipe_path: PathBuf::from("deployment.toml"), + }; + + let result = driver.freeze_exact(&source, &commit, "txn-dup", &frozen_source_root); + assert!( + result.is_err(), + "a tree with a leaf entry aliasing another entry's ancestor must be refused" + ); + assert!( + !outside.join("pwn").exists(), + "the writer must never place content outside the frozen root, even on refusal" + ); + Ok(()) + } + + /// F4 (Self's ruling, second Cut 1 fix batch): `freeze_exact` refuses a + /// symlink that escapes the frozen root, whether the target is absolute + /// or a relative `..` walk, before the tree is ever published. This + /// exercises the guard through the public `freeze_exact` entry point + /// (not the `harden_frozen_source` unit alone), so removing the call + /// inside `freeze_exact` -- not just the function -- is what this pins. + #[cfg(unix)] + #[test] + fn freeze_exact_refuses_an_absolute_or_escaping_symlink() -> Result<()> { + use std::os::unix::fs::{PermissionsExt, symlink}; + + for (label, make_link) in [ + ( + "absolute", + Box::new(|repo: &Path| symlink("/etc/passwd", repo.join("l"))) as Box std::io::Result<()>>, + ), + ( + "escaping", + Box::new(|repo: &Path| { + fs::create_dir(repo.join("d"))?; + symlink("../../../outside-the-root", repo.join("d/l")) + }), + ), + ] { + let temp = tempfile::tempdir()?; + fs::set_permissions(temp.path(), fs::Permissions::from_mode(0o755))?; + let origin_repo = temp.path().join("origin"); + fs::create_dir(&origin_repo)?; + git_at(&origin_repo, &["init", "--initial-branch=main"])?; + git_at(&origin_repo, &["config", "user.name", "Idunn Test"])?; + git_at( + &origin_repo, + &["config", "user.email", "idunn-test@example.invalid"], + )?; + fs::write(origin_repo.join("deployment.toml"), b"target = 'test'\n")?; + make_link(&origin_repo)?; + git_at(&origin_repo, &["add", "--all"])?; + git_at(&origin_repo, &["commit", "-m", "fixture"])?; + let revision = git_at(&origin_repo, &["rev-parse", "HEAD"])?; + ensure!( + Command::new("/bin/chown") + .args(["-R", "1000:1000"]) + .arg(&origin_repo) + .status()? + .success(), + "chowning the fixture origin repository" + ); + + let source_cache_root = temp.path().join("source-cache"); + let frozen_source_root = temp.path().join("frozen-source"); + fs::create_dir(&frozen_source_root)?; + fs::set_permissions(&frozen_source_root, fs::Permissions::from_mode(0o700))?; + let identity = ProcessIdentity { + uid: 1000, + gid: 1000, + }; + let driver = GitSourceDriver::new( + source_cache_root.clone(), + frozen_source_root.clone(), + Some(identity), + ); + let source = ExactSource { + origin: origin_repo.to_string_lossy().into_owned(), + checkout: source_cache_root.join("checkout"), + gitlinks: BTreeMap::new(), + recipe_path: PathBuf::from("deployment.toml"), + }; + let result = driver.freeze_exact(&source, &revision, "txn-escape", &frozen_source_root); + assert!(result.is_err(), "{label} symlink must be refused"); + } + Ok(()) + } + + /// F5 (Self's ruling, second Cut 1 fix batch): a lexical `..`-count is + /// not enough once the chain passes back through another symlink. `D` + /// points at `.` (itself), and `L` walks through a dozen `D` hops before + /// finally leaving with `..` -- lexically that undercounts how far the + /// chain really goes, because each `D` the OS resolves is a fresh copy + /// of the root, not one ordinary path component. `L` actually resolves + /// to `/etc/passwd`. + #[cfg(unix)] + #[test] + fn freeze_exact_refuses_a_symlink_chain_that_escapes_through_a_self_referential_directory() -> Result<()> { + use std::os::unix::fs::{PermissionsExt, symlink}; + + let temp = tempfile::tempdir()?; + fs::set_permissions(temp.path(), fs::Permissions::from_mode(0o755))?; + let origin_repo = temp.path().join("origin"); + fs::create_dir(&origin_repo)?; + git_at(&origin_repo, &["init", "--initial-branch=main"])?; + git_at(&origin_repo, &["config", "user.name", "Idunn Test"])?; + git_at( + &origin_repo, + &["config", "user.email", "idunn-test@example.invalid"], + )?; + fs::write(origin_repo.join("deployment.toml"), b"target = 'test'\n")?; + symlink(".", origin_repo.join("D"))?; + let chain = "D/D/D/D/D/D/D/D/D/D/D/D/../../../../../../../../../../../../etc/passwd"; + symlink(chain, origin_repo.join("L"))?; + git_at(&origin_repo, &["add", "--all"])?; + git_at(&origin_repo, &["commit", "-m", "fixture"])?; + let revision = git_at(&origin_repo, &["rev-parse", "HEAD"])?; + ensure!( + Command::new("/bin/chown") + .args(["-R", "1000:1000"]) + .arg(&origin_repo) + .status()? + .success(), + "chowning the fixture origin repository" + ); + + let source_cache_root = temp.path().join("source-cache"); + let frozen_source_root = temp.path().join("frozen-source"); + fs::create_dir(&frozen_source_root)?; + fs::set_permissions(&frozen_source_root, fs::Permissions::from_mode(0o700))?; + let identity = ProcessIdentity { + uid: 1000, + gid: 1000, + }; + let driver = GitSourceDriver::new( + source_cache_root.clone(), + frozen_source_root.clone(), + Some(identity), + ); + let source = ExactSource { + origin: origin_repo.to_string_lossy().into_owned(), + checkout: source_cache_root.join("checkout"), + gitlinks: BTreeMap::new(), + recipe_path: PathBuf::from("deployment.toml"), + }; + let result = driver.freeze_exact(&source, &revision, "txn-chain", &frozen_source_root); + assert!( + result.is_err(), + "a symlink chain that resolves outside the root through a self-referential directory must be refused" + ); + Ok(()) + } + /// F2 (Self's ruling, Cut 1 fix batch): `freeze_exact` writes blobs raw /// from the object store, with no attribute-driven transform, across /// every transform `.gitattributes` can name: `eol=crlf`, `export-ignore`, diff --git a/tools/verify-mutations/cut1.psd1 b/tools/verify-mutations/cut1.psd1 index 008bfe4..c619b2a 100644 --- a/tools/verify-mutations/cut1.psd1 +++ b/tools/verify-mutations/cut1.psd1 @@ -261,92 +261,177 @@ Rule = 'freeze_exact writes blobs raw from the object store; it must never revert to git archive, which applies attribute-driven transforms.' Test = 'drivers::tests::freeze_exact_is_byte_exact_across_every_attribute_transform' Old = @' - fs::create_dir_all(destination) - .with_context(|| format!("creating {}", destination.display()))?; + ensure_frozen_directory(frozen_root, created_dirs, destination)?; let entries = self.git_tree_entries(repository, revision)?; - let blob_objects: Vec = entries - .iter() - .filter(|entry| entry.kind == "blob") - .map(|entry| entry.object.clone()) - .collect(); - let blobs = self.read_blobs(repository, &blob_objects)?; - let mut lfs_pointer_paths = Vec::new(); - for entry in &entries { - let target = destination.join(&entry.path); - if let Some(parent) = target.parent() { - fs::create_dir_all(parent)?; - } - match entry.mode.as_str() { - "100644" | "100755" => { - let content = blobs - .get(&entry.object) - .context("Git cat-file --batch omitted a requested blob")?; - fs::write(&target, content) - .with_context(|| format!("writing {}", target.display()))?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mode = if entry.mode == "100755" { 0o755 } else { 0o644 }; - fs::set_permissions(&target, fs::Permissions::from_mode(mode))?; - } - if is_lfs_pointer(content) { - lfs_pointer_paths.push(entry.path.clone()); - } - } - "120000" => { - let content = blobs - .get(&entry.object) - .context("Git cat-file --batch omitted a requested blob")?; - let link_target = std::str::from_utf8(content) - .context("frozen source symlink target is not UTF-8")?; - #[cfg(unix)] - std::os::unix::fs::symlink(link_target, &target) - .with_context(|| format!("creating symlink {}", target.display()))?; - } - "160000" => { - // Gitlinks are materialized by the caller, which knows - // each one's admitted origin; this entry only reserves - // the directory. - } - other => bail!( - "frozen source tree entry {} has an unsupported mode {other}", - entry.path.display() - ), - } - } - Ok(lfs_pointer_paths) '@ New = @' - fs::create_dir_all(destination) - .with_context(|| format!("creating {}", destination.display()))?; - let mut archive = self.git_command([ + ensure_frozen_directory(frozen_root, created_dirs, destination)?; + { + let mut archive = self.git_command([ + OsString::from("-C"), + repository.as_os_str().to_owned(), + OsString::from("archive"), + OsString::from("--format=tar"), + OsString::from(revision), + ])?; + archive.stdout(Stdio::piped()).stderr(Stdio::piped()); + let mut archive = archive.spawn().context("starting Git archive")?; + let archive_stdout = archive.stdout.take().context("Git archive has no stdout")?; + let mut extractor = Command::new("/bin/tar"); + extractor + .args([ + OsString::from("--extract"), + OsString::from("--file=-"), + OsString::from("--directory"), + destination.as_os_str().to_owned(), + OsString::from("--no-same-owner"), + ]) + .stdin(Stdio::from(archive_stdout)) + .stdout(Stdio::null()) + .stderr(Stdio::piped()); + let extractor = extractor.spawn().context("starting tar extractor")?; + let archive_output = archive.wait_with_output().context("waiting for Git archive")?; + let extractor_output = extractor.wait_with_output().context("waiting for tar extractor")?; + ensure!(archive_output.status.success(), "Git archive failed"); + ensure!(extractor_output.status.success(), "tar extraction failed"); + return Ok(Vec::new()); + } + #[allow(unreachable_code)] + let entries = self.git_tree_entries(repository, revision)?; +'@ + } + @{ + Id = 'cut1-fix-f1-no-bulk-fetch' + Rule = 'materialize_tree_raw bulk-fetches every blob it needs once, before reading any of them, rather than letting cat-file --batch lazily fetch them one at a time.' + Test = 'drivers::tests::freeze_exact_is_byte_exact_and_recipe_checked' + Old = @' + self.bulk_fetch_objects(repository, &object_order)?; +'@ + New = '' + } + @{ + Id = 'cut1-fix-f2-no-fsck-on-fetch' + Rule = 'the exact-revision fetch enables transfer.fsckObjects, so Git itself refuses a fetched tree with duplicate names.' + Test = 'drivers::tests::freeze_exact_refuses_a_duplicate_named_tree_that_would_write_outside_its_root' + Old = @' + self.git([ + OsString::from("-c"), + OsString::from("transfer.fsckObjects=true"), OsString::from("-C"), - repository.as_os_str().to_owned(), - OsString::from("archive"), - OsString::from("--format=tar"), - OsString::from(revision), - ])?; - archive.stdout(Stdio::piped()).stderr(Stdio::piped()); - let mut archive = archive.spawn().context("starting Git archive")?; - let archive_stdout = archive.stdout.take().context("Git archive has no stdout")?; - let mut extractor = Command::new("/bin/tar"); - extractor - .args([ - OsString::from("--extract"), - OsString::from("--file=-"), - OsString::from("--directory"), - destination.as_os_str().to_owned(), - OsString::from("--no-same-owner"), - ]) - .stdin(Stdio::from(archive_stdout)) - .stdout(Stdio::null()) - .stderr(Stdio::piped()); - let extractor = extractor.spawn().context("starting tar extractor")?; - let archive_output = archive.wait_with_output().context("waiting for Git archive")?; - let extractor_output = extractor.wait_with_output().context("waiting for tar extractor")?; - ensure!(archive_output.status.success(), "Git archive failed"); - ensure!(extractor_output.status.success(), "tar extraction failed"); - Ok(Vec::new()) + source.checkout.as_os_str().to_owned(), + OsString::from("fetch"), +'@ + New = @' + self.git([ + OsString::from("-C"), + source.checkout.as_os_str().to_owned(), + OsString::from("fetch"), +'@ + } + @{ + Id = 'cut1-fix-f2-no-alias-refusal' + Rule = 'git_tree_entries refuses a tree where one entry aliases another (a leaf name that is also another leaf''s ancestor, case-folded).' + Test = 'drivers::tests::freeze_exact_refuses_a_duplicate_named_tree_that_would_write_outside_its_root' + Old = @' + refuse_conflicting_tree_entries(&entries)?; +'@ + New = '' + } + @{ + Id = 'cut1-fix-f3-writer-follows-existing-entries' + Rule = 'ensure_frozen_directory never treats a path that already exists as safe to write through; only a directory this freeze itself created may be reused.' + Test = 'drivers::tests::freeze_exact_refuses_a_duplicate_named_tree_that_would_write_outside_its_root' + Old = @' + match fs::symlink_metadata(path) { + Ok(metadata) => bail!( +'@ + New = @' + match fs::symlink_metadata(path) { + Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => {} + Ok(metadata) => bail!( +'@ + } + @{ + Id = 'cut1-fix-f4-harden-pass-removed' + Rule = 'freeze_exact hardens the frozen tree (root-owned 0444/0555, symlinks refused if they escape) before it is ever published.' + Test = 'drivers::tests::freeze_exact_refuses_an_absolute_or_escaping_symlink' + Old = @' + harden_frozen_source(&partial)?; + let snapshot_sha256 = frozen_source_sha256(&partial)?; +'@ + New = @' + let snapshot_sha256 = frozen_source_sha256(&partial)?; +'@ + } + @{ + Id = 'cut1-fix-f5-lexical-symlink-check' + Rule = 'a frozen-source symlink is validated by resolving its whole chain on the filesystem, not by lexically counting ".." components.' + Test = 'drivers::tests::freeze_exact_refuses_a_symlink_chain_that_escapes_through_a_self_referential_directory' + Old = @' + let canonical_root = root.canonicalize().context("resolving frozen source root")?; + let canonical_target = path.canonicalize().with_context(|| { + format!("resolving frozen source symlink chain at {}", path.display()) + })?; + ensure!( + canonical_target.starts_with(&canonical_root), + "frozen source symlink escapes its root" + ); +'@ + New = @' + let _ = root; + let _ = path; +'@ + } + @{ + Id = 'cut1-fix-n1-readonly-dropped-named-plus-cache' + Rule = '--read-only is present on a Named network even when a cache root is also mounted.' + Test = 'drivers::tests::docker_run_args_keeps_read_only_with_a_named_network_and_a_cache_root' + Old = @' + args.push(bind_mount(cache_root, "/cache", false)?); +'@ + New = @' + args.push(bind_mount(cache_root, "/cache", false)?); + if matches!(spec.network, ContainerNetwork::Named(_)) { + args.retain(|a| a != "--read-only"); + } +'@ + } + @{ + Id = 'cut1-fix-n2-secret-writable-with-plain-env' + Rule = 'a secret mount is read-only regardless of how many plain environment entries the runner also carries.' + Test = 'drivers::tests::docker_run_args_keeps_secret_mounts_read_only_alongside_plain_environment' + Old = @' + args.push(bind_mount(&mount.host_path, &mount.container_path, true)?); +'@ + New = @' + args.push(bind_mount(&mount.host_path, &mount.container_path, spec.environment.len() == 1)?); +'@ + } + @{ + Id = 'cut1-fix-n3-stamp-dropped-with-secret-and-env' + Rule = 'the Idunn source stamp is never dropped from ContainerSpec::for_step''s environment, no matter what else the runner carries.' + Test = 'drivers::tests::container_spec_for_step_keeps_the_source_stamp_with_a_secret_and_plain_environment' + Old = @' + let network = match runner.network_profile.as_deref() { +'@ + New = @' + if !secret_mounts.is_empty() && environment.len() > 1 { + environment.remove(0); + } + let network = match runner.network_profile.as_deref() { +'@ + } + @{ + Id = 'cut1-fix-n5-lfs-flag-never-set' + Rule = 'a Git LFS pointer file materialized into a frozen tree is recorded in the returned LFS-pointer list.' + Test = 'drivers::tests::freeze_exact_sets_the_lfs_pointer_flag_for_a_pointer_file' + Old = @' + if is_lfs { + lfs_pointer_paths.push(first.path.clone()); + } +'@ + New = @' + let _ = is_lfs; '@ } ) diff --git a/tools/verify-mutations/soul2-mutants.sh b/tools/verify-mutations/soul2-mutants.sh new file mode 100644 index 0000000..e25b0fb --- /dev/null +++ b/tools/verify-mutations/soul2-mutants.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# Soul's own mutants against /src/src/drivers.rs; whole lib suite per mutant. +cd /src +F=src/drivers.rs +cp $F /tmp/drivers.orig +run() { + id=$1; shift + cp /tmp/drivers.orig $F + perl -0pi -e "$1" $F + if cmp -s $F /tmp/drivers.orig; then echo "MUTANT $id: ANCHOR MISSED (no change)"; return; fi + out=$(cargo test --lib 2>&1) + if echo "$out" | grep -q "error\[E\|could not compile"; then echo "MUTANT $id: NO BUILD"; echo "$out" | grep -A5 "^error" | head -20; return; fi + res=$(echo "$out" | grep "^test result") + fails=$(echo "$out" | grep -E "^test .* FAILED$" | sed 's/^test //; s/ \.\.\. FAILED//' | tr '\n' ' ') + if [ -n "$fails" ]; then echo "MUTANT $id: KILLED by: $fails | $res"; else echo "MUTANT $id: SURVIVED | $res"; fi +} +run S1-capdrop-only-on-bridge 's/(\n match spec\.seccomp \{)/\n if spec.network == ContainerNetwork::Bridge { args.retain(|a| a != "--cap-drop" && a != "ALL"); }$1/' +run S1b-readonly-dropped-on-named 's/(\n match spec\.seccomp \{)/$1/; s/( OsString::from\("--read-only"\),\n)//; s/(\n if let Some\(cache_root\) = &spec\.cache_root \{\n args\.push)/\n if !matches!(spec.network, ContainerNetwork::Named(_)) { args.insert(args.iter().position(|a| a == "--pids-limit").unwrap(), OsString::from("--read-only")); }$1/' +run S2a-cpus-round-half 's/f64::from\(spec\.cpu_quota_percent\) \/ 100\.0/(f64::from(spec.cpu_quota_percent) \/ 100.0 * 2.0).round() \/ 2.0/' +run S2b-cpus-quota-floor50 's/f64::from\(spec\.cpu_quota_percent\) \/ 100\.0/f64::from(spec.cpu_quota_percent \/ 50 * 50) \/ 100.0/' +run S2c-cpus-round-int 's/f64::from\(spec\.cpu_quota_percent\) \/ 100\.0/(f64::from(spec.cpu_quota_percent) \/ 100.0).round()/' +run S3a-env-prefix-passthrough 's/(which collides with the Idunn source stamp"\n \);\n)/$1 for (k, v) in &runner.environment { if k != name && k.starts_with(name.as_str()) { environment.push((k.clone(), v.clone())); } }\n/' +run S3b-env-idunn-prefix-ambient 's/( let mut secret_mounts = Vec::new\(\);\n)/$1 for (k, v) in &runner.environment { if k.starts_with("GAMECULT_") || k.starts_with("IDUNN_") { environment.push((k.clone(), v.clone())); } }\n/' +run S4-secret-mount-writable 's/args\.push\(bind_mount\(&mount\.host_path, &mount\.container_path, true\)\?\);/args.push(bind_mount(\&mount.host_path, \&mount.container_path, false)?);/' +run S5-explicit-none-is-bridge 's/None \| Some\("none"\) => ContainerNetwork::None,/None => ContainerNetwork::None,\n Some("none") => ContainerNetwork::Bridge,/' +run S6-cache-mount-rw-to-host-root 's/args\.push\(bind_mount\(cache_root, "\/cache", false\)\?\);/args.push(bind_mount(cache_root, "\/cache", false)?); args.push(OsString::from("--mount")); args.push(bind_mount(cache_root.parent().unwrap(), "\/cache-parent", false)?);/' +run S7-freeze-exact-skips-gitlinks 's/for \(path, fact\) in &gitlinks \{/for (path, fact) in gitlinks.iter().take(0) {/' +run S8-freeze-exact-skips-validate 's/ validate_frozen_source\(&partial\)\?;\n//' +run S8c-freeze-exact-skips-harden-and-validate 's/ harden_frozen_source\(&partial\)\?;\n validate_frozen_source\(&partial\)\?;\n//' +run S9-secret-validation-skipped 's/ validate_runner_secret\(path, identity\)\?;\n secret_mounts\.push/ secret_mounts.push/' +run S10-cache-root-validation-skipped 's/ if let Some\(cache_root\) = &runner\.cache_root \{\n ensure_runner_cache_root\(cache_root, identity\)\?;\n \}\n//' +run N1-named-plus-cache-drops-readonly 's/( args\.push\(bind_mount\(cache_root, "\/cache", false\)\?\);\n)/$1 if matches!(spec.network, ContainerNetwork::Named(_)) { args.retain(|a| a != "--read-only"); }\n/' +run N2-secret-writable-when-plain-env-too 's/args\.push\(bind_mount\(&mount\.host_path, &mount\.container_path, true\)\?\);/args.push(bind_mount(\&mount.host_path, \&mount.container_path, spec.environment.len() == 1)?);/' +run N3-stamp-dropped-with-secret-and-env 's/( let network = match runner\.network_profile\.as_deref\(\) \{)/ if !secret_mounts.is_empty() && environment.len() > 1 { environment.remove(0); }\n$1/' +run N4-stamp-refusal-removed 's/ ensure!\(\n name != source_stamp\.0,\n[^\n]*\n \);\n//' +run N5-lfs-flag-never-set 's/lfs_pointer_paths\.push\(entry\.path\.clone\(\)\);/let _ = \&entry;/' +run N6-exec-bit-dropped 's/let mode = if entry\.mode == "100755" \{ 0o755 \} else \{ 0o644 \};/let mode = 0o644;/' +run N7-symlink-as-file 's/std::os::unix::fs::symlink\(link_target, &target\)/fs::write(\&target, link_target)/' +cp /tmp/drivers.orig $F