From ec865ca671ee8dad7d1998c0121e04d1dfcd1920 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 11:54:30 +0100 Subject: [PATCH] [linux] Tests: unpacking hostile archives, the atomic switch, health check and auto rollback (red: the code follows) --- crates/linux/tests/common/mod.rs | 45 ++++++ crates/linux/tests/switch.rs | 254 +++++++++++++++++++++++++++++++ crates/linux/tests/unpack.rs | 131 ++++++++++++++++ crates/protocol/src/lib.rs | 2 +- 4 files changed, 431 insertions(+), 1 deletion(-) create mode 100644 crates/linux/tests/common/mod.rs create mode 100644 crates/linux/tests/switch.rs create mode 100644 crates/linux/tests/unpack.rs diff --git a/crates/linux/tests/common/mod.rs b/crates/linux/tests/common/mod.rs new file mode 100644 index 0000000..4c9d390 --- /dev/null +++ b/crates/linux/tests/common/mod.rs @@ -0,0 +1,45 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::io::Write; + +use flate2::Compression; +use flate2::write::GzEncoder; + +/// A .tar.gz of regular files (path, contents, executable). +pub fn targz(files: &[(&str, &[u8], bool)]) -> Vec { + let mut b = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::fast())); + for (path, data, exec) in files { + let mut h = tar::Header::new_gnu(); + h.set_size(data.len() as u64); + h.set_mode(if *exec { 0o755 } else { 0o644 }); + h.set_entry_type(tar::EntryType::Regular); + b.append_data(&mut h, path, *data).unwrap(); + } + b.into_inner().unwrap().finish().unwrap() +} + +/// A .tar.gz with one raw entry whose name and type the tar crate would not let us write. +pub fn raw_targz(name: &[u8], kind: tar::EntryType, data: &[u8], link: &[u8]) -> Vec { + let mut h = tar::Header::new_old(); + { + let old = h.as_old_mut(); + old.name[..name.len()].copy_from_slice(name); + old.linkname[..link.len()].copy_from_slice(link); + } + h.set_size(data.len() as u64); + h.set_mode(0o644); + h.set_entry_type(kind); + h.set_cksum(); + let mut tarball = Vec::new(); + tarball.extend_from_slice(h.as_bytes()); + tarball.extend_from_slice(data); + tarball.resize(tarball.len().div_ceil(512) * 512, 0); + tarball.extend_from_slice(&[0u8; 1024]); + let mut gz = GzEncoder::new(Vec::new(), Compression::fast()); + gz.write_all(&tarball).unwrap(); + gz.finish().unwrap() +} diff --git a/crates/linux/tests/switch.rs b/crates/linux/tests/switch.rs new file mode 100644 index 0000000..08c3660 --- /dev/null +++ b/crates/linux/tests/switch.rs @@ -0,0 +1,254 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The Linux target (mandatory, tests first): the atomic symlink switch, the restart, the health +//! check, and auto rollback when the check fails. Real files and symlinks; systemd and the health +//! endpoint are fakes here (the container test, tests/linux, uses real systemd). + +#![cfg(any(target_os = "linux", target_os = "android"))] +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use std::cell::RefCell; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use common::*; +use legatus_linux::{Health, Layout, LinuxBackend, Outcome, Plan, Services}; + +/// systemd as the tests see it: records restarts; a release is "active" unless its dir holds BROKEN. +struct FakeSystemd { + layout: Layout, + calls: RefCell>, + fail_restart_of: Option, +} + +impl Services for FakeSystemd { + fn restart(&self, unit: &str) -> Result<(), String> { + let v = self.layout.current("shop").unwrap_or_default(); + self.calls.borrow_mut().push(format!("restart {unit} @{v}")); + if self.fail_restart_of.as_deref() == Some(v.as_str()) { + return Err(format!("Job for {unit} failed")); + } + Ok(()) + } + fn is_active(&self, _unit: &str) -> bool { + let cur = self.layout.current_dir("shop"); + cur.is_some_and(|d| !d.join("BROKEN").exists()) + } +} + +/// The health URL answers 2xx unless the current release holds UNHEALTHY. +struct FakeHealth(Layout); +impl Health for FakeHealth { + fn check(&self, _url: &str) -> bool { + self.0 + .current_dir("shop") + .is_some_and(|d| !d.join("UNHEALTHY").exists()) + } +} + +fn backend( + fail_restart_of: Option<&str>, +) -> (tempfile::TempDir, LinuxBackend) { + let dir = tempfile::tempdir().unwrap(); + let layout = Layout::new(dir.path().join("apps")); + let sd = FakeSystemd { + layout: layout.clone(), + calls: RefCell::new(Vec::new()), + fail_restart_of: fail_restart_of.map(str::to_owned), + }; + let b = LinuxBackend::new(layout.clone(), sd, FakeHealth(layout)) + .with_poll(Duration::from_millis(5)); + (dir, b) +} + +fn plan(version: &str) -> Plan<'_> { + Plan { + app: "shop", + version, + unit: "shop.service", + health_url: Some("http://127.0.0.1:8080/health"), + health_timeout: Duration::from_millis(200), + keep: 3, + } +} + +fn good(v: &str) -> Vec { + targz(&[("bin/shop", format!("version {v}").as_bytes(), true)]) +} + +#[test] +fn a_healthy_release_is_switched_to_and_restarted() { + let (_d, b) = backend(None); + let out = b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap(); + assert_eq!(out, Outcome::Succeeded { previous: None }); + assert_eq!(b.layout().current("shop").as_deref(), Some("1.0.0")); + let out = b.deploy(&plan("1.1.0"), &good("2")[..], "s2").unwrap(); + assert_eq!( + out, + Outcome::Succeeded { + previous: Some("1.0.0".into()) + } + ); + assert_eq!(b.layout().current("shop").as_deref(), Some("1.1.0")); + assert_eq!( + *b.services().calls.borrow(), + vec![ + "restart shop.service @1.0.0".to_owned(), + "restart shop.service @1.1.0".to_owned() + ] + ); + // `current` is a relative symlink into releases/. + let link = std::fs::read_link(b.layout().current_link("shop")).unwrap(); + assert_eq!(link, PathBuf::from("releases/1.1.0")); + assert_eq!(b.deployed(), vec![("shop".to_owned(), "1.1.0".to_owned())]); +} + +#[test] +fn a_failed_health_check_rolls_back_automatically() { + let (_d, b) = backend(None); + b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap(); + let bad = targz(&[("bin/shop", b"v2", true), ("UNHEALTHY", b"", false)]); + let out = b.deploy(&plan("2.0.0"), &bad[..], "s2").unwrap(); + assert_eq!( + out, + Outcome::RolledBack { + to: "1.0.0".into(), + healthy: true, + reason: out.reason().to_owned() + } + ); + assert!(out.reason().contains("health"), "{}", out.reason()); + assert_eq!(b.layout().current("shop").as_deref(), Some("1.0.0")); + // Restarted on the new release, then again on the old one. + assert_eq!( + *b.services().calls.borrow(), + vec![ + "restart shop.service @1.0.0".to_owned(), + "restart shop.service @2.0.0".to_owned(), + "restart shop.service @1.0.0".to_owned() + ] + ); + // The failed release stays on disk for a look, but is not current. + assert!(b.layout().release_dir("shop", "2.0.0").exists()); +} + +#[test] +fn an_inactive_unit_rolls_back_even_without_a_health_url() { + let (_d, b) = backend(None); + b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap(); + let crashes = targz(&[("bin/shop", b"v2", true), ("BROKEN", b"", false)]); + let mut p = plan("2.0.0"); + p.health_url = None; + let out = b.deploy(&p, &crashes[..], "s2").unwrap(); + assert!( + matches!(out, Outcome::RolledBack { ref to, healthy: true, .. } if to == "1.0.0"), + "{out:?}" + ); + assert_eq!(b.layout().current("shop").as_deref(), Some("1.0.0")); +} + +#[test] +fn a_failed_restart_rolls_back() { + let (_d, b) = backend(Some("2.0.0")); + b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap(); + let out = b.deploy(&plan("2.0.0"), &good("2")[..], "s2").unwrap(); + assert!( + matches!(out, Outcome::RolledBack { ref to, .. } if to == "1.0.0"), + "{out:?}" + ); + assert!(out.reason().contains("failed"), "{}", out.reason()); +} + +#[test] +fn a_first_release_that_fails_has_nothing_to_roll_back_to() { + let (_d, b) = backend(None); + let bad = targz(&[("bin/shop", b"v1", true), ("UNHEALTHY", b"", false)]); + let out = b.deploy(&plan("1.0.0"), &bad[..], "s1").unwrap(); + assert!(matches!(out, Outcome::Failed { .. }), "{out:?}"); +} + +#[test] +fn a_rollback_that_is_unhealthy_too_says_so() { + let (_d, b) = backend(None); + b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap(); + // The old release breaks meanwhile (say, a database it needs is gone). + std::fs::write( + b.layout().release_dir("shop", "1.0.0").join("UNHEALTHY"), + b"", + ) + .unwrap(); + let bad = targz(&[("bin/shop", b"v2", true), ("UNHEALTHY", b"", false)]); + let out = b.deploy(&plan("2.0.0"), &bad[..], "s2").unwrap(); + assert!( + matches!(out, Outcome::RolledBack { healthy: false, .. }), + "{out:?}" + ); +} + +#[test] +fn the_switch_is_atomic() { + let (_d, b) = backend(None); + b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap(); + b.deploy(&plan("2.0.0"), &good("2")[..], "s2").unwrap(); + let link = b.layout().current_link("shop"); + let stop = Arc::new(AtomicBool::new(false)); + let reader = { + let (link, stop) = (link.clone(), stop.clone()); + std::thread::spawn(move || { + let mut reads = 0u64; + while !stop.load(Ordering::Relaxed) { + // `current` always exists and always points at a whole release. + let target = std::fs::read_link(&link).expect("current vanished during a switch"); + let s = target.to_string_lossy().into_owned(); + assert!(s == "releases/1.0.0" || s == "releases/2.0.0", "{s}"); + assert!(link.join("bin/shop").exists(), "current pointed at nothing"); + reads += 1; + } + reads + }) + }; + for i in 0..400 { + let v = if i % 2 == 0 { "1.0.0" } else { "2.0.0" }; + b.switch("shop", v).unwrap(); + } + stop.store(true, Ordering::Relaxed); + let reads = reader.join().unwrap(); + assert!(reads > 0); + // No temporary links are left behind. + let names: Vec = std::fs::read_dir(b.layout().app_dir("shop")) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!( + names.iter().filter(|n| n.starts_with('.')).count(), + 0, + "{names:?}" + ); +} + +#[test] +fn old_releases_are_pruned_but_current_and_previous_kept() { + let (_d, b) = backend(None); + for (i, v) in ["1.0.0", "1.1.0", "1.2.0", "1.3.0", "1.4.0"] + .iter() + .enumerate() + { + let mut p = plan(v); + p.keep = 2; + b.deploy(&p, &good(&i.to_string())[..], &format!("s{i}")) + .unwrap(); + } + let mut left: Vec = std::fs::read_dir(b.layout().releases_dir("shop")) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|n| !n.ends_with(".sha256")) + .collect(); + left.sort(); + assert_eq!(left, vec!["1.3.0".to_owned(), "1.4.0".to_owned()]); +} diff --git a/crates/linux/tests/unpack.rs b/crates/linux/tests/unpack.rs new file mode 100644 index 0000000..e13b7b8 --- /dev/null +++ b/crates/linux/tests/unpack.rs @@ -0,0 +1,131 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Unpacking (tests first): a signed archive can still hold a mistake; nothing escapes the +//! release dir, links and special files are refused, and a refused archive leaves nothing behind. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use common::*; +use legatus_linux::{Layout, UnpackError, unpack}; + +fn layout() -> (tempfile::TempDir, Layout) { + let dir = tempfile::tempdir().unwrap(); + let l = Layout::new(dir.path().join("apps")); + (dir, l) +} + +#[test] +fn a_good_archive_becomes_a_release_dir() { + let (_d, l) = layout(); + let a = targz(&[ + ("bin/shop", b"#!/bin/sh\necho hi\n", true), + ("static/index.html", b"

hi

", false), + ]); + let dir = unpack(&l, "shop", "1.4.0", &a[..], "sha-one").unwrap(); + assert_eq!(dir, l.release_dir("shop", "1.4.0")); + assert_eq!( + std::fs::read(dir.join("static/index.html")).unwrap(), + b"

hi

" + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(dir.join("bin/shop")) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o755); + let mode = std::fs::metadata(dir.join("static/index.html")) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o644); + } + // The same version with the same content again: reused, not unpacked twice. + assert_eq!(unpack(&l, "shop", "1.4.0", &a[..], "sha-one").unwrap(), dir); + // The same version with other content: refused, the existing one untouched. + let other = targz(&[("bin/shop", b"evil", true)]); + assert!(matches!( + unpack(&l, "shop", "1.4.0", &other[..], "sha-two"), + Err(UnpackError::VersionClash) + )); + assert_eq!( + std::fs::read(dir.join("bin/shop")).unwrap(), + b"#!/bin/sh\necho hi\n" + ); +} + +fn assert_refused_and_clean(l: &Layout, archive: &[u8]) { + let r = unpack(l, "shop", "2.0.0", archive, "sha"); + assert!(r.is_err(), "{r:?}"); + assert!(!l.release_dir("shop", "2.0.0").exists()); + let releases = l.releases_dir("shop"); + if releases.exists() { + let left: Vec<_> = std::fs::read_dir(&releases).unwrap().collect(); + assert!(left.is_empty(), "staging left behind: {left:?}"); + } +} + +#[test] +fn paths_that_climb_out_are_refused() { + let (d, l) = layout(); + for name in [ + &b"../evil"[..], + b"/etc/evil", + b"a/../../evil", + b"a\\..\\evil", + ] { + assert_refused_and_clean(&l, &raw_targz(name, tar::EntryType::Regular, b"x", b"")); + } + assert!(!d.path().join("evil").exists()); + assert!(!d.path().join("apps").join("evil").exists()); +} + +#[test] +fn links_and_special_files_are_refused() { + let (_d, l) = layout(); + assert_refused_and_clean( + &l, + &raw_targz(b"link", tar::EntryType::Symlink, b"", b"/etc/passwd"), + ); + assert_refused_and_clean( + &l, + &raw_targz(b"hard", tar::EntryType::Link, b"", b"/etc/passwd"), + ); + assert_refused_and_clean(&l, &raw_targz(b"dev", tar::EntryType::Char, b"", b"")); + assert_refused_and_clean(&l, &raw_targz(b"fifo", tar::EntryType::Fifo, b"", b"")); +} + +#[test] +fn garbage_and_duplicates_are_refused() { + let (_d, l) = layout(); + assert_refused_and_clean(&l, b"not gzip at all"); + let dup = targz(&[("a", b"1", false), ("a", b"2", false)]); + assert_refused_and_clean(&l, &dup); + assert_refused_and_clean(&l, &targz(&[])); +} + +#[test] +fn bad_app_or_version_names_never_reach_the_disk() { + let (_d, l) = layout(); + let a = targz(&[("x", b"1", false)]); + for (app, version) in [ + ("../shop", "1"), + ("shop", "../1"), + ("shop", ".."), + ("Shop", "1"), + ("shop", ""), + ] { + assert!( + matches!( + unpack(&l, app, version, &a[..], "s"), + Err(UnpackError::Name) + ), + "{app} {version}" + ); + } +} diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs index 9ac529f..91d5a61 100644 --- a/crates/protocol/src/lib.rs +++ b/crates/protocol/src/lib.rs @@ -47,7 +47,7 @@ pub fn hex(b: &[u8]) -> String { /// Lowercase or uppercase hex to bytes. pub(crate) fn unhex(s: &str) -> Option> { - if s.len() % 2 != 0 { + if !s.len().is_multiple_of(2) { return None; } (0..s.len())