fix(executor): fail closed on every stage3 verification failure

The unpinned stage3 path warned and continued when the DIGESTS download
failed, when no SHA-512 entry matched, when gpg or the Gentoo release key
was missing, when the key import failed, and when gpg could not start.
All of these now stop the install before extraction, as do a bad
signature and a hash mismatch. The pinned path requires a valid 64-hex
pin (placeholder refused) before any network use. require_tools covers
gpg/sha256sum/sha512sum and stage_install checks them first.

16 regression tests cover every failure branch (nonzero exit and
cannot-start for hash, probe, import and verify) plus both positive
paths.
This commit is contained in:
Phoebus 2026-09-25 19:49:37 -07:00
parent 15b69f524d
commit 216267064c
2 changed files with 497 additions and 44 deletions

View file

@ -1,9 +1,21 @@
//! Gentoo stage3 acquisition and verification. //! Gentoo stage3 acquisition and verification.
//! //!
//! The stage3 tarball may be pinned (URL + SHA-256) or resolved from the //! Two verification paths, both fail closed:
//! Gentoo mirror. Unpinned downloads verify the signed DIGESTS file and its //!
//! SHA-512 entry. Signature verification fails closed when gpg and the Gentoo //! - Pinned (URL + SHA-256): the pin must be a valid 64-digit hex digest. Its
//! release key are available. //! trust comes from being supplied independently of the download (test
//! config, build manifest), never from the mirror. The tarball hash must
//! match before extraction.
//! - Unpinned (mirror resolution, the default): the tarball must be
//! accompanied by Gentoo's signed DIGESTS file. The DIGESTS signature must
//! verify against the trusted Gentoo release key with `gpg`, and the
//! tarball's SHA-512 must match the signed entry, following Gentoo's stage3
//! verification guidance (`gpg --verify <tarball>.DIGESTS`, then compare the
//! SHA-512 hash).
//!
//! A missing verifier, key, DIGESTS file, or hash entry stops the install. A
//! bad signature or a mismatched hash stops the install. Nothing warns and
//! continues.
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -13,8 +25,24 @@ use crate::command::{CommandOutput, CommandSpec};
use crate::error::{ExecError, Result}; use crate::error::{ExecError, Result};
use crate::exec::Exec; use crate::exec::Exec;
/// Trusted Gentoo release public key shipped in the live installer image.
/// The build provisions this file and checks its fingerprint against Gentoo's
/// published release-key information
/// (https://www.gentoo.org/downloads/signatures/); the installer never
/// fetches an unauthenticated key.
pub const GENTOO_RELEASE_KEY: &str = "/usr/share/openpgp-keys/gentoo-release.asc";
/// Path of the trusted Gentoo release key. `PHOEBUS_GENTOO_RELEASE_KEY`
/// overrides it for tests; production always uses [`GENTOO_RELEASE_KEY`].
pub fn release_key_path() -> PathBuf {
match std::env::var("PHOEBUS_GENTOO_RELEASE_KEY") {
Ok(dir) if !dir.is_empty() => PathBuf::from(dir),
_ => PathBuf::from(GENTOO_RELEASE_KEY),
}
}
pub fn require_tools(exec: &Exec) -> Result<()> { pub fn require_tools(exec: &Exec) -> Result<()> {
exec.require_tools(&["curl", "tar"]) exec.require_tools(&["curl", "tar", "gpg", "sha256sum", "sha512sum"])
} }
/// Resolve the stage3 download URL. /// Resolve the stage3 download URL.
@ -45,8 +73,10 @@ pub fn resolve_url(exec: &Exec, config: &InstallConfig) -> Result<String> {
} }
fn hash_file(exec: &Exec, program: &str, path: &Path) -> Result<String> { fn hash_file(exec: &Exec, program: &str, path: &Path) -> Result<String> {
let out = exec.runner.execute( // Routed through `Exec::run` so a nonzero exit status fails closed; only
&CommandSpec::new("stage_install", "hash stage3", program).arg(path.to_string_lossy()), // the hash on a successful run is accepted.
let out = exec.run(
CommandSpec::new("stage_install", "hash stage3", program).arg(path.to_string_lossy()),
)?; )?;
out.stdout_lossy() out.stdout_lossy()
.split_whitespace() .split_whitespace()
@ -55,8 +85,30 @@ fn hash_file(exec: &Exec, program: &str, path: &Path) -> Result<String> {
.ok_or_else(|| ExecError::operation("stage_install", "hash", "empty hash output")) .ok_or_else(|| ExecError::operation("stage_install", "hash", "empty hash output"))
} }
/// A pinned SHA-256 must be 64 hex digits and not a placeholder. The pin is
/// trusted only because it was supplied independently of the download.
fn validate_pin(pin: &str) -> Result<()> {
let valid = pin.len() == 64
&& pin.chars().all(|c| c.is_ascii_hexdigit())
&& !pin.chars().all(|c| c == '0');
if !valid {
return Err(ExecError::operation(
"stage_install",
"verify stage3",
"pinned STAGE3_SHA256 must be 64 hex digits (a real digest supplied \
independently of the download); refusing to install",
));
}
Ok(())
}
/// Download and verify the stage3 tarball into `state_dir`. /// Download and verify the stage3 tarball into `state_dir`.
pub fn fetch(exec: &Exec, config: &InstallConfig, state_dir: &Path) -> Result<PathBuf> { pub fn fetch(exec: &Exec, config: &InstallConfig, state_dir: &Path) -> Result<PathBuf> {
// The pinned path trusts the independently supplied digest, never the
// mirror: require a valid pin before any network use.
if !config.stage3.sha256.is_empty() {
validate_pin(&config.stage3.sha256)?;
}
let url = resolve_url(exec, config)?; let url = resolve_url(exec, config)?;
let dest = state_dir.join("stage3-systemd.tar.xz"); let dest = state_dir.join("stage3-systemd.tar.xz");
std::fs::create_dir_all(state_dir).map_err(|e| ExecError::io(state_dir.to_path_buf(), e))?; std::fs::create_dir_all(state_dir).map_err(|e| ExecError::io(state_dir.to_path_buf(), e))?;
@ -70,8 +122,9 @@ pub fn fetch(exec: &Exec, config: &InstallConfig, state_dir: &Path) -> Result<Pa
)?; )?;
if !config.stage3.sha256.is_empty() { if !config.stage3.sha256.is_empty() {
// The pin was validated above; require the download to match it.
let got = hash_file(exec, "sha256sum", &dest)?; let got = hash_file(exec, "sha256sum", &dest)?;
if got != config.stage3.sha256 { if !got.eq_ignore_ascii_case(&config.stage3.sha256) {
return Err(ExecError::operation( return Err(ExecError::operation(
"stage_install", "stage_install",
"verify stage3", "verify stage3",
@ -91,17 +144,24 @@ pub fn fetch(exec: &Exec, config: &InstallConfig, state_dir: &Path) -> Result<Pa
} }
fn verify_digests(exec: &Exec, url: &str, dest: &Path) -> Result<()> { fn verify_digests(exec: &Exec, url: &str, dest: &Path) -> Result<()> {
verify_digests_with_key(exec, url, dest, &release_key_path())
}
fn verify_digests_with_key(exec: &Exec, url: &str, dest: &Path, key: &Path) -> Result<()> {
let digests = dest.with_extension("xz.DIGESTS"); let digests = dest.with_extension("xz.DIGESTS");
let spec = CommandSpec::new("stage_install", "download stage3 DIGESTS", "curl") let spec = CommandSpec::new("stage_install", "download stage3 DIGESTS", "curl")
.args(["-fsSL", "-o"]) .args(["-fsSL", "-o"])
.arg(digests.to_string_lossy().to_string()) .arg(digests.to_string_lossy().to_string())
.arg(format!("{url}.DIGESTS")); .arg(format!("{url}.DIGESTS"));
if exec.run(spec).is_err() { if let Err(e) = exec.run(spec) {
exec.logger let _ = std::fs::remove_file(&digests);
.warn("could not fetch stage3 DIGESTS; checksum not verified"); return Err(ExecError::operation(
return Ok(()); "stage_install",
"verify stage3",
format!("could not fetch the signed stage3 DIGESTS; refusing to install an unverified stage3 ({e})"),
));
} }
if let Err(e) = verify_signature(exec, &digests) { if let Err(e) = verify_signature_with_key(exec, &digests, key) {
let _ = std::fs::remove_file(&digests); let _ = std::fs::remove_file(&digests);
return Err(e); return Err(e);
} }
@ -110,12 +170,14 @@ fn verify_digests(exec: &Exec, url: &str, dest: &Path) -> Result<()> {
let want = parse_digests_sha512(&text, base); let want = parse_digests_sha512(&text, base);
let _ = std::fs::remove_file(&digests); let _ = std::fs::remove_file(&digests);
let Some(want) = want else { let Some(want) = want else {
exec.logger return Err(ExecError::operation(
.warn("no SHA-512 entry found in DIGESTS; checksum not verified"); "stage_install",
return Ok(()); "verify stage3",
"no SHA-512 entry for the stage3 tarball in the signed DIGESTS; refusing to install",
));
}; };
let got = hash_file(exec, "sha512sum", dest)?; let got = hash_file(exec, "sha512sum", dest)?;
if got != want { if !got.eq_ignore_ascii_case(&want) {
return Err(ExecError::operation( return Err(ExecError::operation(
"stage_install", "stage_install",
"verify stage3", "verify stage3",
@ -160,43 +222,51 @@ pub fn parse_digests_sha512(text: &str, target_filename: &str) -> Option<String>
None None
} }
fn verify_signature(exec: &Exec, digests: &Path) -> Result<()> { fn verify_signature_with_key(exec: &Exec, digests: &Path, key: &Path) -> Result<()> {
let key = "/usr/share/openpgp-keys/gentoo-release.asc"; // Probe the verifier through the runner (not merely PATH) so a missing
if crate::exec::find_in_path("gpg").is_none() || !Path::new(key).is_file() { // or broken gpg stops the install, including under test doubles.
exec.logger if let Err(e) =
.warn("gpg or Gentoo release key unavailable; skipping signature check"); exec.run(CommandSpec::new("stage_install", "check stage3 verifier", "gpg").arg("--version"))
return Ok(()); {
return Err(ExecError::operation(
"stage_install",
"verify stage3 DIGESTS signature",
format!("gpg is required to authenticate the stage3 DIGESTS signature but is unavailable; refusing to install ({e})"),
));
}
if !key.is_file() {
return Err(ExecError::operation(
"stage_install",
"verify stage3 DIGESTS signature",
format!(
"trusted Gentoo release key is missing at {}; refusing to install",
key.display()
),
));
} }
let home = tempfile::tempdir().map_err(|e| ExecError::io(std::env::temp_dir(), e))?; let home = tempfile::tempdir().map_err(|e| ExecError::io(std::env::temp_dir(), e))?;
let home_str = home.path().to_string_lossy().to_string(); let home_str = home.path().to_string_lossy().to_string();
let import = CommandSpec::new("stage_install", "import Gentoo release key", "gpg") let import = CommandSpec::new("stage_install", "import Gentoo release key", "gpg")
.args(["--batch", "--quiet", "--import", key]) .args(["--batch", "--quiet", "--import"])
.arg(key.to_string_lossy().to_string())
.env("GNUPGHOME", &home_str); .env("GNUPGHOME", &home_str);
if exec.runner.execute(&import).is_err() { if let Err(e) = exec.run(import) {
exec.logger return Err(ExecError::operation(
.warn("could not import Gentoo release key; skipping signature check"); "stage_install",
return Ok(()); "verify stage3 DIGESTS signature",
format!("could not import the Gentoo release key; refusing to install ({e})"),
));
} }
let verify = CommandSpec::new("stage_install", "verify stage3 DIGESTS signature", "gpg") let verify = CommandSpec::new("stage_install", "verify stage3 DIGESTS signature", "gpg")
.args(["--batch", "--verify"]) .args(["--batch", "--verify"])
.arg(digests.to_string_lossy().to_string()) .arg(digests.to_string_lossy().to_string())
.env("GNUPGHOME", &home_str); .env("GNUPGHOME", &home_str);
match exec.runner.execute(&verify) { // `Exec::run` fails closed on both a nonzero exit (bad signature) and a
Ok(out) => { // process that cannot start; either stops the install before extraction.
exec.logger.output(&out.stdout); let out = exec.run(verify)?;
exec.logger.output(&out.stderr); exec.logger.output(&out.stdout);
if out.success { exec.logger.output(&out.stderr);
Ok(()) Ok(())
} else {
Err(ExecError::operation(
"stage_install",
"verify stage3 DIGESTS signature",
"signature verification FAILED",
))
}
}
Err(_) => Ok(()),
}
} }
pub fn extract(exec: &Exec, root: &Path, tarball: &Path) -> Result<()> { pub fn extract(exec: &Exec, root: &Path, tarball: &Path) -> Result<()> {
@ -223,6 +293,110 @@ pub fn dry_output() -> CommandOutput {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::command::{NeverRunner, ProcessRunner, RecordingRunner};
use crate::log::Logger;
use phoebus_core::Redactor;
use std::collections::VecDeque;
use std::sync::Mutex;
use std::time::Duration;
fn make_exec(runner: RecordingRunner) -> Exec {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
}
fn ok_out(stdout: &str) -> CommandOutput {
CommandOutput {
status: 0,
success: true,
stdout: stdout.as_bytes().to_vec(),
stderr: Vec::new(),
duration: Duration::from_millis(1),
}
}
fn fail_out(stderr: &str) -> CommandOutput {
CommandOutput {
status: 1,
success: false,
stdout: Vec::new(),
stderr: stderr.as_bytes().to_vec(),
duration: Duration::from_millis(1),
}
}
/// Test double that answers successive commands from a queue, so tests can
/// drive multi-step flows (probe ok, import fails, ...) that share one
/// program name.
struct SeqRunner {
recorded: Mutex<Vec<CommandSpec>>,
queue: Mutex<VecDeque<CommandOutput>>,
}
impl SeqRunner {
fn new(outputs: Vec<CommandOutput>) -> Self {
Self {
recorded: Mutex::new(Vec::new()),
queue: Mutex::new(outputs.into()),
}
}
fn programs(&self) -> Vec<String> {
self.recorded
.lock()
.unwrap()
.iter()
.map(|s| s.program.clone())
.collect()
}
}
impl ProcessRunner for SeqRunner {
fn execute(&self, spec: &CommandSpec) -> Result<CommandOutput> {
self.recorded.lock().unwrap().push(spec.clone());
self.queue.lock().unwrap().pop_front().ok_or_else(|| {
ExecError::operation(
&spec.stage,
&spec.operation,
"no canned response left in the test runner",
)
})
}
}
fn seq_exec(outputs: Vec<CommandOutput>) -> (Exec, std::sync::Arc<SeqRunner>) {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
let runner = std::sync::Arc::new(SeqRunner::new(outputs));
struct Shared(std::sync::Arc<SeqRunner>);
impl ProcessRunner for Shared {
fn execute(&self, spec: &CommandSpec) -> Result<CommandOutput> {
self.0.execute(spec)
}
}
let exec = Exec::new(
Box::new(Shared(runner.clone())),
logger,
false,
path.join("root"),
path,
);
(exec, runner)
}
fn pinned_config(sha256: &str) -> InstallConfig {
let mut config = InstallConfig::default();
config.stage3.url = "https://example.invalid/stage3.tar.xz".into();
config.stage3.sha256 = sha256.into();
config
}
fn digest_text(name: &str, hash: &str) -> String {
format!(
"-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\n# SHA512 HASH\n{hash} {name}\n-----BEGIN PGP SIGNATURE-----\n"
)
}
#[test] #[test]
fn parse_digests_picks_sha512_over_blake2b() { fn parse_digests_picks_sha512_over_blake2b() {
@ -256,4 +430,280 @@ e6ae2b1930064878203ab8d134fc081a252c8073730628222ee1cc4a201a56ed9c64dc7b19f1fa40
Some("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef") Some("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
); );
} }
#[test]
fn pinned_pin_format_is_required() {
assert!(validate_pin(&"a".repeat(64)).is_ok());
assert!(validate_pin(&"A".repeat(64)).is_ok());
assert!(validate_pin("").is_err());
assert!(validate_pin("abc").is_err());
assert!(validate_pin(&"a".repeat(63)).is_err());
assert!(validate_pin(&"a".repeat(65)).is_err());
assert!(validate_pin(&format!("{}g", "a".repeat(63))).is_err());
// A placeholder pin carries no trust and is refused.
assert!(validate_pin(&"0".repeat(64)).is_err());
}
#[test]
fn pinned_path_verifies_a_matching_download() {
let pin = "b".repeat(64);
let runner = RecordingRunner::new();
runner.set_response(
"sha256sum",
ok_out(&format!("{pin} stage3-systemd.tar.xz")),
);
let exec = make_exec(runner.clone());
let state = tempfile::tempdir().unwrap();
let dest = fetch(&exec, &pinned_config(&pin), state.path()).unwrap();
assert_eq!(
dest.file_name().unwrap().to_string_lossy(),
"stage3-systemd.tar.xz"
);
// The mirror's DIGESTS path is never consulted for a pinned tarball.
assert!(
!runner
.recorded()
.iter()
.any(|s| s.args.iter().any(|a| a.contains("DIGESTS"))),
"pinned verification must not fetch DIGESTS"
);
}
#[test]
fn pinned_path_rejects_a_mismatch() {
let runner = RecordingRunner::new();
runner.set_response("sha256sum", ok_out(&format!("{} x", "c".repeat(64))));
let exec = make_exec(runner);
let state = tempfile::tempdir().unwrap();
let err = fetch(&exec, &pinned_config(&"d".repeat(64)), state.path()).unwrap_err();
assert!(err.to_string().contains("mismatch"), "{err}");
}
#[test]
fn pinned_path_rejects_a_placeholder_pin_before_any_hash() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let state = tempfile::tempdir().unwrap();
let err = fetch(&exec, &pinned_config(&"0".repeat(64)), state.path()).unwrap_err();
assert!(err.to_string().contains("64 hex digits"), "{err}");
// Fail fast: neither the download nor the hash may run.
assert!(
runner.is_empty(),
"invalid pin must stop before any command"
);
}
#[test]
fn pinned_path_rejects_a_malformed_pin() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let state = tempfile::tempdir().unwrap();
let err = fetch(&exec, &pinned_config("not-a-digest"), state.path()).unwrap_err();
assert!(err.to_string().contains("64 hex digits"), "{err}");
assert!(
runner.is_empty(),
"invalid pin must stop before any command"
);
}
#[test]
fn hash_command_nonzero_exit_fails_closed() {
let runner = RecordingRunner::new();
runner.fail("sha512sum", "cannot read file");
let exec = make_exec(runner);
let err = hash_file(&exec, "sha512sum", Path::new("/nonexistent")).unwrap_err();
assert!(err.to_string().contains("sha512sum"), "{err}");
}
#[test]
fn hash_command_that_cannot_start_fails_closed() {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
let exec = Exec::new(
Box::new(NeverRunner),
logger,
false,
path.join("root"),
path,
);
let err = hash_file(&exec, "sha512sum", Path::new("/nonexistent")).unwrap_err();
assert!(err.to_string().contains("disabled"), "{err}");
}
#[test]
fn digests_download_failure_stops_install() {
let runner = RecordingRunner::new();
runner.fail("curl", "network down");
let exec = make_exec(runner);
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("stage3.tar.xz");
let key = dir.path().join("gentoo-release.asc");
std::fs::write(&key, "key").unwrap();
let err =
verify_digests_with_key(&exec, "https://example.invalid/stage3.tar.xz", &dest, &key)
.unwrap_err();
assert!(err.to_string().contains("DIGESTS"), "{err}");
assert!(err.to_string().contains("refusing"), "{err}");
}
#[test]
fn missing_sha512_entry_stops_install() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("stage3.tar.xz");
// A signed DIGESTS with no entry for our tarball.
std::fs::write(
dest.with_extension("xz.DIGESTS"),
digest_text("other-file.tar.xz", &"e".repeat(128)),
)
.unwrap();
let key = dir.path().join("gentoo-release.asc");
std::fs::write(&key, "key").unwrap();
let err =
verify_digests_with_key(&exec, "https://example.invalid/stage3.tar.xz", &dest, &key)
.unwrap_err();
assert!(err.to_string().contains("SHA-512 entry"), "{err}");
}
#[test]
fn missing_release_key_stops_install() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let dir = tempfile::tempdir().unwrap();
let digests = dir.path().join("stage3.DIGESTS");
std::fs::write(&digests, "signed").unwrap();
let err =
verify_signature_with_key(&exec, &digests, &dir.path().join("absent-release.asc"))
.unwrap_err();
assert!(err.to_string().contains("missing"), "{err}");
assert!(err.to_string().contains("refusing"), "{err}");
}
#[test]
fn verifier_that_cannot_start_stops_install() {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
let exec = Exec::new(
Box::new(NeverRunner),
logger,
false,
path.join("root"),
path,
);
let dir = tempfile::tempdir().unwrap();
let digests = dir.path().join("stage3.DIGESTS");
std::fs::write(&digests, "signed").unwrap();
let key = dir.path().join("gentoo-release.asc");
std::fs::write(&key, "key").unwrap();
let err = verify_signature_with_key(&exec, &digests, &key).unwrap_err();
assert!(err.to_string().contains("unavailable"), "{err}");
}
#[test]
fn failed_key_import_stops_install() {
// Probe ok, import exits nonzero.
let (exec, runner) = seq_exec(vec![ok_out("gpg 2.4"), fail_out("no key")]);
let dir = tempfile::tempdir().unwrap();
let digests = dir.path().join("stage3.DIGESTS");
std::fs::write(&digests, "signed").unwrap();
let key = dir.path().join("gentoo-release.asc");
std::fs::write(&key, "key").unwrap();
let err = verify_signature_with_key(&exec, &digests, &key).unwrap_err();
assert!(err.to_string().contains("import"), "{err}");
assert_eq!(runner.programs(), vec!["gpg", "gpg"]);
}
#[test]
fn bad_signature_stops_install() {
// Probe ok, import ok, verification exits nonzero.
let (exec, _) = seq_exec(vec![ok_out("gpg 2.4"), ok_out("imported"), fail_out("BAD")]);
let dir = tempfile::tempdir().unwrap();
let digests = dir.path().join("stage3.DIGESTS");
std::fs::write(&digests, "signed").unwrap();
let key = dir.path().join("gentoo-release.asc");
std::fs::write(&key, "key").unwrap();
let err = verify_signature_with_key(&exec, &digests, &key).unwrap_err();
assert!(err.to_string().contains("verify stage3 DIGESTS"), "{err}");
}
#[test]
fn unpinned_signed_digests_path_succeeds() {
let want = "f".repeat(128);
let (exec, runner) = seq_exec(vec![
ok_out("digests fetched"),
ok_out("gpg 2.4"),
ok_out("imported"),
ok_out("gpg: Good signature"),
ok_out(&format!("{want} stage3.tar.xz")),
]);
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("stage3.tar.xz");
std::fs::write(
dest.with_extension("xz.DIGESTS"),
digest_text("stage3.tar.xz", &want),
)
.unwrap();
let key = dir.path().join("gentoo-release.asc");
std::fs::write(&key, "key").unwrap();
verify_digests_with_key(&exec, "https://example.invalid/stage3.tar.xz", &dest, &key)
.unwrap();
assert_eq!(
runner.programs(),
vec!["curl", "gpg", "gpg", "gpg", "sha512sum"]
);
// The DIGESTS copy is discarded after use.
assert!(!dest.with_extension("xz.DIGESTS").exists());
}
#[test]
fn unpinned_hash_mismatch_stops_install() {
let (exec, _) = seq_exec(vec![
ok_out("digests fetched"),
ok_out("gpg 2.4"),
ok_out("imported"),
ok_out("gpg: Good signature"),
ok_out(&format!("{} stage3.tar.xz", "1".repeat(128))),
]);
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("stage3.tar.xz");
std::fs::write(
dest.with_extension("xz.DIGESTS"),
digest_text("stage3.tar.xz", &"2".repeat(128)),
)
.unwrap();
let key = dir.path().join("gentoo-release.asc");
std::fs::write(&key, "key").unwrap();
let err =
verify_digests_with_key(&exec, "https://example.invalid/stage3.tar.xz", &dest, &key)
.unwrap_err();
assert!(err.to_string().contains("mismatch"), "{err}");
}
#[test]
fn fetch_with_unavailable_verifier_fails_before_extraction() {
let runner = RecordingRunner::new();
runner.fail("gpg", "not installed");
let exec = make_exec(runner.clone());
let state = tempfile::tempdir().unwrap();
let mut config = InstallConfig::default();
config.stage3.url = "https://example.invalid/stage3.tar.xz".into();
let err = fetch(&exec, &config, state.path()).unwrap_err();
assert!(err.to_string().contains("DIGESTS"), "{err}");
// The tarball download ran, but no hash and no extraction followed.
assert!(!runner.programs().contains(&"sha512sum".to_string()));
assert!(!runner.programs().contains(&"tar".to_string()));
}
#[test]
fn release_key_path_override_is_honoured() {
// The only test that touches this variable; every other stage3 test
// passes its key explicitly, so no parallel test can observe it.
let dir = tempfile::tempdir().unwrap();
let custom = dir.path().join("custom.asc");
std::env::set_var("PHOEBUS_GENTOO_RELEASE_KEY", &custom);
assert_eq!(release_key_path(), custom);
std::env::remove_var("PHOEBUS_GENTOO_RELEASE_KEY");
assert_eq!(release_key_path(), PathBuf::from(GENTOO_RELEASE_KEY));
}
} }

View file

@ -365,6 +365,9 @@ impl Installer {
.info("[dry-run] would fetch and extract the stage3"); .info("[dry-run] would fetch and extract the stage3");
return Ok(()); return Ok(());
} }
// Fail fast when the stage3 verifier (gpg, hashes, download tools) is
// missing: an unverifiable stage3 must never reach extraction.
stage3::require_tools(&self.exec)?;
stage3::fetch(&self.exec, &self.config, &self.exec.state_dir)?; stage3::fetch(&self.exec, &self.config, &self.exec.state_dir)?;
let tarball = self.exec.state_dir.join("stage3-systemd.tar.xz"); let tarball = self.exec.state_dir.join("stage3-systemd.tar.xz");
stage3::extract(&self.exec, std::path::Path::new(&self.exec.root), &tarball) stage3::extract(&self.exec, std::path::Path::new(&self.exec.root), &tarball)