macro_rules! private_workdir {
() => {
r#"set -e; d="$(mktemp -d)"; trap 'rm -rf "$d"' EXIT; printf 'DPkg::Lock::Timeout "600";\n' >"$d/apt.conf"; export APT_CONFIG="$d/apt.conf""#
};
}
#[cfg(test)]
pub const PRIVATE_WORKDIR: &str = private_workdir!();
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RootScript(String);
pub const PRELUDE: &str = concat!(private_workdir!(), "; export LC_ALL=C");
impl RootScript {
#[must_use]
pub fn new(body: impl AsRef<str>) -> Self {
Self(format!("{PRELUDE}; {}", body.as_ref()))
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
#[must_use]
pub fn with_after_prelude(self, first: &str) -> String {
let body = self.0.strip_prefix(PRELUDE).unwrap_or(&self.0);
format!("{PRELUDE}; {first}{body}")
}
}
impl std::ops::Deref for RootScript {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for RootScript {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
pub const NEED_CURL: &str = r"command -v curl >/dev/null || { if command -v apt-get >/dev/null; then apt-get update; apt-get install -y curl ca-certificates; else dnf install -y curl ca-certificates; fi; }";
pub const NEED_UNZIP: &str =
r"command -v unzip >/dev/null || { if command -v apt-get >/dev/null; then apt-get update; apt-get install -y unzip; else dnf install -y unzip; fi; }";
pub const NEED_GPG: &str = r#"command -v gpg >/dev/null || { if command -v apt-get >/dev/null; then apt-get update; apt-get install -y gnupg; else dnf install -y gnupg2; fi; }; mkdir -p -m 700 "$d/gnupg""#;
#[must_use]
pub fn check_keys(fingerprints: &[&str], vendor: &str) -> String {
let want = expected(fingerprints);
format!(
r#"k="$(gpg --homedir "$d/gnupg" --batch --show-keys --with-colons "$d/key" | awk -F: '$1=="pub"{{p=1}} $1=="fpr"&&p{{print $10; p=0}}' | LC_ALL=C sort | paste -s -d ' ' -)"; [ "$k" = "{want}" ] || {{ echo "{vendor}'s signing key isn't the expected one (fingerprint {want}, got: $k). Nothing was installed." >&2; exit 1; }}"#
)
}
fn expected(fingerprints: &[&str]) -> String {
let mut sorted = fingerprints.to_vec();
sorted.sort_unstable();
sorted.join(" ")
}
#[cfg(test)]
mod tests {
#[test]
fn the_private_workdir_makes_apt_wait_for_the_dpkg_lock() {
assert!(
PRIVATE_WORKDIR.contains(r#"DPkg::Lock::Timeout "600";"#) && PRIVATE_WORKDIR.contains(r#"export APT_CONFIG="$d/apt.conf""#),
"{PRIVATE_WORKDIR}"
);
assert!(crate::testing::sh_parses(PRIVATE_WORKDIR), "not valid sh: {PRIVATE_WORKDIR}");
#[cfg(unix)]
{
let out = crate::testing::sh(&format!("{PRIVATE_WORKDIR}; cat \"$APT_CONFIG\""), &[]);
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), r#"DPkg::Lock::Timeout "600";"#);
}
}
use super::*;
#[cfg(unix)]
fn ran(script: &RootScript) -> (Option<i32>, String) {
let out = crate::testing::sh(script, &[("LANG", "fr_FR.UTF-8"), ("LC_ALL", "fr_FR.UTF-8")]);
(out.status.code, String::from_utf8_lossy(&out.stdout).into_owned())
}
#[test]
fn what_runs_after_the_prelude_comes_before_the_body() {
let script = RootScript::new("echo body").with_after_prelude("echo first");
assert_eq!(script, format!("{PRELUDE}; echo first; echo body"));
}
#[test]
fn a_root_script_is_its_body_after_the_prelude() {
let script = RootScript::new("apt-get install -y qemu-system");
assert_eq!(&*script, format!("{PRELUDE}; apt-get install -y qemu-system"));
assert!(PRELUDE.starts_with(PRIVATE_WORKDIR), "{PRELUDE}");
assert!(crate::testing::sh_parses(&script), "not valid sh: {script}");
}
#[cfg(unix)]
#[test]
fn a_root_script_stops_at_its_first_failing_command_with_its_status() {
let (code, said) = ran(&RootScript::new("echo before; sh -c 'exit 100'; echo after"));
assert_eq!(code, Some(100));
assert_eq!(said.trim(), "before");
assert_eq!(ran(&RootScript::new("false || true; echo after")), (Some(0), "after\n".to_owned()));
}
#[cfg(unix)]
#[test]
fn a_root_script_reads_tools_in_the_c_locale_whatever_the_users() {
assert_eq!(ran(&RootScript::new(r#"echo "$LC_ALL""#)), (Some(0), "C\n".to_owned()));
}
#[test]
fn curl_and_gpg_come_through_apt_where_it_is_else_dnf() {
for need in [NEED_CURL, NEED_GPG, NEED_UNZIP] {
assert!(
need.contains("if command -v apt-get >/dev/null; then apt-get") && need.contains("else dnf install -y"),
"{need}"
);
assert!(crate::testing::sh_parses(need), "not valid sh: {need}");
}
assert!(NEED_GPG.contains("dnf install -y gnupg2"), "Fedora's package is gnupg2");
}
#[test]
fn a_keyring_is_checked_for_every_pinned_key_in_the_order_the_check_reads_them() {
assert_eq!(expected(&["827C", "44C6"]), "44C6 827C");
assert_eq!(expected(&["9DC8"]), "9DC8");
let check = check_keys(&["827C", "44C6"], "A vendor");
assert!(check.contains(r#"[ "$k" = "44C6 827C" ]"#), "{check}");
assert!(check.contains(r#"--homedir "$d/gnupg""#) && check.contains("LC_ALL=C sort"), "{check}");
assert!(
crate::testing::sh_parses(&format!("{PRIVATE_WORKDIR}; {NEED_GPG}; {check}")),
"not valid sh: {check}"
);
}
#[cfg(unix)]
fn checked(pinned: &[&str], listing: &str) -> (bool, String) {
let script = format!(
"d=/nonexistent; gpg() {{ printf '%s' '{listing}'; }}; {}; echo went on",
check_keys(pinned, "A vendor's archive")
);
let out = crate::testing::sh(&script, &[]);
(
String::from_utf8_lossy(&out.stdout).contains("went on"),
String::from_utf8_lossy(&out.stderr).into_owned(),
)
}
#[cfg(unix)]
#[test]
fn only_a_keyring_of_exactly_the_pinned_keys_goes_on() {
let both = "pub:-:4096:1:ED65462EC8D5E4C5:::::\nfpr:::::::::827C:\nuid:-::::::::Vendor 2025:\npub:-:4096:1:ED444FF07D8D0BF6:::::\nfpr:::::::::44C6:\nsub:-:4096:1:A8373E18FC0D0DCB:::::\nfpr:::::::::0D76:\n";
assert!(checked(&["827C", "44C6"], both).0, "both pinned keys, in any order");
let (went_on, said) = checked(&["827C"], both);
assert!(!went_on && said.contains("isn't the expected one (fingerprint 827C, got: 44C6 827C)"), "{said}");
let (missing_went_on, missing_said) = checked(&["827C", "44C6"], "pub:-:4096:1:X:::::\nfpr:::::::::827C:\n");
assert!(!missing_went_on && missing_said.contains("got: 827C)"), "one missing: {missing_said}");
assert!(!checked(&["827C"], "<html>captive portal</html>").0);
}
}