#![allow(missing_docs)]
use anyhow::{bail, Context, Result};
use fs2::FileExt;
use include_dir::{include_dir, Dir};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
static ASSETS: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/pentest");
pub const MARKER: &str = ".cxg-manifest.json";
const JOURNAL: &str = "pentest-transaction.json";
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", content = "path", rename_all = "snake_case")]
pub enum Origin {
Embedded,
Source(PathBuf),
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct Manifest {
pub schema: u32,
pub version: String,
pub origin: Origin,
pub digest: String,
pub files: BTreeMap<String, String>,
}
#[derive(Clone, Debug)]
pub struct Bundle {
files: BTreeMap<String, Vec<u8>>,
pub manifest: Manifest,
}
use crate::pentest_bundle::{excluded, hash, inventory_digest, relative};
impl Bundle {
pub fn new(files: BTreeMap<String, Vec<u8>>, version: &str, origin: Origin) -> Result<Self> {
for path in files.keys() {
if path.contains('\\') || !relative(Path::new(path)) || excluded(Path::new(path)) {
bail!("invalid bundle path: {path}");
}
}
if !files.contains_key("cxg_pentest.py") || !files.contains_key("requirements.txt") {
bail!("bundle must contain cxg_pentest.py and requirements.txt");
}
let hashes = files.iter().map(|(p, b)| (p.clone(), hash(b))).collect();
Ok(Self {
manifest: Manifest {
schema: 1,
version: version.into(),
origin,
digest: inventory_digest(&hashes),
files: hashes,
},
files,
})
}
pub fn embedded() -> Self {
fn collect(dir: &Dir<'_>, files: &mut BTreeMap<String, Vec<u8>>) {
for f in dir.files() {
if !excluded(f.path()) {
files.insert(
f.path().to_string_lossy().replace('\\', "/"),
f.contents().to_vec(),
);
}
}
for d in dir.dirs() {
if !excluded(d.path()) {
collect(d, files);
}
}
}
let mut files = BTreeMap::new();
collect(&ASSETS, &mut files);
let manifest: Manifest = serde_json::from_str(include_str!(concat!(
env!("OUT_DIR"),
"/pentest-manifest.json"
)))
.expect("valid build-time manifest");
Self { files, manifest }
}
pub fn source(root: &Path) -> Result<Self> {
let mut files = BTreeMap::new();
for entry in walkdir::WalkDir::new(root)
.follow_links(false)
.into_iter()
.filter_entry(|e| e.path() == root || !excluded(e.path().strip_prefix(root).unwrap()))
{
let e = entry.context("read source bundle")?;
if e.file_type().is_symlink() {
bail!("source bundle contains symlink: {}", e.path().display());
}
if e.file_type().is_file() {
files.insert(
e.path()
.strip_prefix(root)?
.to_string_lossy()
.replace('\\', "/"),
fs::read(e.path())?,
);
}
}
Self::new(
files,
env!("CARGO_PKG_VERSION"),
Origin::Source(root.canonicalize()?),
)
}
}
fn plain_path(root: &Path, rel: &Path) -> Result<PathBuf> {
if !relative(rel) {
bail!("unsafe managed path");
}
let mut path = root.to_path_buf();
if !fs::symlink_metadata(&path)?.file_type().is_dir() {
bail!("pipeline root is not a plain directory");
}
for component in rel.components() {
path.push(component);
if fs::symlink_metadata(&path)?.file_type().is_symlink() {
bail!("managed path is a symlink");
}
}
Ok(path)
}
fn read_manifest(tree: &Path) -> Result<Manifest> {
let m: Manifest = serde_json::from_slice(&fs::read(plain_path(tree, Path::new(MARKER))?)?)?;
if m.schema != 1 || m.files.is_empty() || inventory_digest(&m.files) != m.digest {
bail!("invalid manifest inventory/schema");
}
Ok(m)
}
fn verify(tree: &Path, manifest: &Manifest) -> Result<()> {
for (rel, expected) in &manifest.files {
let path = plain_path(tree, Path::new(rel))?;
if !fs::symlink_metadata(&path)?.is_file() || hash(&fs::read(path)?) != *expected {
bail!("managed file changed: {rel}");
}
}
Ok(())
}
fn exists(path: &Path) -> bool {
fs::symlink_metadata(path).is_ok()
}
fn sync_dir(path: &Path) -> Result<()> {
#[cfg(unix)]
File::open(path)?.sync_all()?;
#[cfg(not(unix))]
let _ = path;
Ok(())
}
fn private_dir(path: &Path) -> Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
fs::DirBuilder::new().mode(0o700).create(path)?;
}
#[cfg(not(unix))]
fs::create_dir(path)?;
Ok(())
}
fn write_sync(path: &Path, bytes: &[u8]) -> Result<()> {
let mut file = OpenOptions::new().write(true).create_new(true).open(path)?;
file.write_all(bytes)?;
file.sync_all()?;
Ok(())
}
#[derive(Debug, Serialize)]
pub struct Status {
pub binary_version: String,
pub expected_digest: String,
pub installed_digest: Option<String>,
pub install_origin: Option<Origin>,
pub freshness: String,
pub installed_path: PathBuf,
pub interrupted_transaction: bool,
}
#[derive(Debug, Serialize)]
pub struct Update {
#[serde(flatten)]
pub status: Status,
pub changed: bool,
pub backup_path: Option<PathBuf>,
}
#[derive(Debug, Serialize, Deserialize)]
struct Transaction {
stage: String,
backup: String,
had_old: bool,
manifest: Manifest,
}
#[derive(Debug)]
pub struct Lease {
_file: File,
}
#[derive(Debug)]
pub struct Installer {
root: PathBuf,
bundle: Bundle,
timeout: Duration,
#[cfg(test)]
fail_at: Option<&'static str>,
#[cfg(test)]
crash: bool,
}
impl Installer {
pub fn new(root: PathBuf, bundle: Bundle) -> Self {
Self {
root,
bundle,
timeout: Duration::from_secs(30),
#[cfg(test)]
fail_at: None,
#[cfg(test)]
crash: false,
}
}
pub fn active(&self) -> PathBuf {
self.root.join("pentest")
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
fn boundary(&self, _step: &str) -> Result<()> {
#[cfg(test)]
if self.fail_at == Some(_step) {
if self.crash {
std::process::exit(73);
}
bail!("injected interruption at {_step}");
}
Ok(())
}
fn lock(&self, exclusive: bool) -> Result<Lease> {
fs::create_dir_all(&self.root).context("create pipeline home (use a writable home)")?;
let path = self.root.join("pentest.lock");
if exists(&path) && !fs::symlink_metadata(&path)?.is_file() {
bail!("pipeline lock is not a plain file");
}
let file = OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.open(path)
.context("open pipeline lock")?;
let start = Instant::now();
let mut announced = false;
loop {
let result = if exclusive {
FileExt::try_lock_exclusive(&file)
} else {
FileExt::try_lock_shared(&file)
};
match result {
Ok(()) => return Ok(Lease { _file: file }),
Err(e) if e.raw_os_error() == fs2::lock_contended_error().raw_os_error() => {
if !announced {
eprintln!(
"Waiting for pentest {} lease; another run or update is active.",
if exclusive { "update" } else { "execution" }
);
announced = true;
}
if start.elapsed() >= self.timeout {
bail!("pipeline lock timeout; finish the active run/update and retry `cxg pentest update`");
}
std::thread::sleep(Duration::from_millis(25));
}
Err(e) => {
return Err(e).context("acquire pipeline lease; retry `cxg pentest update`")
}
}
}
}
pub fn status(&self) -> Status {
let installed = read_manifest(&self.active()).ok();
let interrupted = exists(&self.root.join(JOURNAL));
let freshness = if interrupted {
"interrupted"
} else if !exists(&self.active()) {
"missing"
} else if let Some(ref m) = installed {
if verify(&self.active(), m).is_err() {
"modified"
} else if m.digest != self.bundle.manifest.digest {
"stale"
} else {
"current"
}
} else {
"legacy_or_corrupt"
};
Status {
binary_version: self.bundle.manifest.version.clone(),
expected_digest: self.bundle.manifest.digest.clone(),
installed_digest: installed.as_ref().map(|m| m.digest.clone()),
install_origin: installed.map(|m| m.origin),
freshness: freshness.into(),
installed_path: self.active(),
interrupted_transaction: interrupted,
}
}
fn clear_journal(&self) -> Result<()> {
fs::remove_file(self.root.join(JOURNAL)).context("clear promotion journal")?;
sync_dir(&self.root)
}
fn recover(&self) -> Result<Option<Option<PathBuf>>> {
let journal = self.root.join(JOURNAL);
if !exists(&journal) {
return Ok(None);
}
if !fs::symlink_metadata(&journal)?.is_file() {
bail!("recovery journal is not a plain file");
}
let tx: Transaction = serde_json::from_slice(&fs::read(&journal)?)
.context("read recovery journal; preserve files and repair journal before retrying")?;
if !tx.stage.starts_with("pentest-stage-")
|| !relative(Path::new(&tx.stage))
|| Path::new(&tx.stage).components().count() != 1
|| !tx.backup.starts_with("pentest-backups/")
|| !relative(Path::new(&tx.backup))
|| Path::new(&tx.backup).components().count() != 2
|| tx.manifest.schema != 1
|| inventory_digest(&tx.manifest.files) != tx.manifest.digest
{
bail!("unsafe recovery journal; preserve files and repair journal before retrying");
}
let backup_root = self.root.join("pentest-backups");
if !fs::symlink_metadata(&backup_root)?.file_type().is_dir() {
bail!("recovery backup directory must be a plain directory");
}
let stage = self.root.join(&tx.stage);
let backup = self.root.join(&tx.backup);
let active = self.active();
if !exists(&stage)
&& read_manifest(&active).is_ok_and(|m| m == tx.manifest)
&& verify(&active, &tx.manifest).is_ok()
{
self.clear_journal()?;
return Ok(Some(tx.had_old.then_some(backup)));
}
if read_manifest(&stage).context("read staged recovery manifest")? != tx.manifest {
bail!("staged recovery manifest differs from journal; preserve the stage and retry after repair");
}
verify(&stage, &tx.manifest).context("verify recovery stage; no Python was launched")?;
if exists(&active) {
if exists(&backup) || !tx.had_old {
bail!("recovery has conflicting active/backup trees; preserve them and retry after repair");
}
self.boundary("backup")?;
fs::rename(&active, &backup).context(
"back up previous pipeline; check permissions and retry `cxg pentest update`",
)?;
sync_dir(backup.parent().unwrap())?;
sync_dir(&self.root)?;
}
self.boundary("old_moved")?;
self.boundary("before_new_move")?;
let promotion = {
#[cfg(test)]
if self.fail_at == Some("promotion_failure") {
Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"injected promotion failure",
))
} else {
fs::rename(&stage, &active)
}
#[cfg(not(test))]
fs::rename(&stage, &active)
};
if let Err(e) = promotion {
if !exists(&active) && exists(&backup) {
fs::rename(&backup, &active)
.context("restore old pipeline after failed promotion")?;
sync_dir(&self.root)?;
}
return Err(e).context(
"promote pipeline stage; retry `cxg pentest update` (stale pipeline was not run)",
);
}
sync_dir(&self.root)?;
self.boundary("new_moved")?;
verify(&active, &tx.manifest).context("verify promoted pipeline")?;
self.boundary("new_verified")?;
self.boundary("before_clear")?;
self.clear_journal()?;
Ok(Some(tx.had_old.then_some(backup)))
}
pub fn update(
&self,
force: bool,
from_embedded: bool,
source_override: bool,
) -> Result<Update> {
let _lease = self.lock(true)?;
let recovered = self
.recover()
.context("recover interrupted pipeline update")?;
if let Some(backup) = &recovered {
eprintln!("Recovered interrupted pentest pipeline update.");
if let Some(path) = backup {
eprintln!("Previous files saved at {}. Local edits and added files remain in this backup and are no longer active.", path.display());
}
}
let mut result = self.update_locked(force, from_embedded, source_override)?;
if !result.changed {
if let Some(backup) = recovered {
result.changed = true;
result.backup_path = backup;
}
}
Ok(result)
}
fn update_locked(
&self,
force: bool,
from_embedded: bool,
source_override: bool,
) -> Result<Update> {
let before = self.status();
if !force
&& before.freshness == "current"
&& ((self.bundle.manifest.origin == Origin::Embedded && !from_embedded)
|| before.install_origin.as_ref() == Some(&self.bundle.manifest.origin))
{
return Ok(Update {
status: before,
changed: false,
backup_path: None,
});
}
if self.bundle.manifest.origin == Origin::Embedded
&& !from_embedded
&& (source_override || matches!(before.install_origin, Some(Origin::Source(_))))
{
bail!("source-derived pipeline selected; to replace it explicitly run `cxg pentest update --from-embedded` (existing files will be backed up)");
}
let id = format!(
"{}-{}",
chrono::Utc::now().format("%Y%m%dT%H%M%SZ"),
uuid::Uuid::new_v4()
);
let stage_name = format!("pentest-stage-{id}");
let stage = self.root.join(&stage_name);
private_dir(&stage).context(
"create private pipeline stage; use a writable home and retry `cxg pentest update`",
)?;
self.boundary("stage_created")?;
for (rel, bytes) in &self.bundle.files {
let path = stage.join(rel);
fs::create_dir_all(path.parent().unwrap()).context("create staged directories")?;
self.boundary("write_file")?;
#[cfg(test)]
if self.fail_at == Some("disk_full") {
return Err(std::io::Error::new(
std::io::ErrorKind::WriteZero,
"injected disk full",
))
.context("write staged file; free disk space and retry `cxg pentest update`");
}
write_sync(&path, bytes).with_context(|| format!("write staged file {rel}; free disk space/check permissions and retry `cxg pentest update`"))?;
}
verify(&stage, &self.bundle.manifest).context("verify staged bundle")?;
write_sync(
&stage.join(MARKER),
&serde_json::to_vec_pretty(&self.bundle.manifest)?,
)
.context("write staged manifest")?;
for entry in walkdir::WalkDir::new(&stage).contents_first(true) {
let entry = entry?;
if entry.file_type().is_dir() {
sync_dir(entry.path())?;
}
}
sync_dir(&self.root)?;
self.boundary("stage_verified")?;
let backups = self.root.join("pentest-backups");
if !exists(&backups) {
private_dir(&backups).context(
"create backup directory; check permissions and retry `cxg pentest update`",
)?;
}
if !fs::symlink_metadata(&backups)?.file_type().is_dir() {
bail!("backup directory must be a plain directory; retry `cxg pentest update` after repair");
}
let backup_name = format!(
"pentest-backups/{id}-{}",
before.installed_digest.as_deref().unwrap_or("legacy")
);
let tx = Transaction {
stage: stage_name,
backup: backup_name,
had_old: exists(&self.active()),
manifest: self.bundle.manifest.clone(),
};
self.boundary("before_journal")?;
let journal_tmp = self
.root
.join(format!("pentest-journal-{}.tmp", uuid::Uuid::new_v4()));
write_sync(&journal_tmp, &serde_json::to_vec(&tx)?).context("write promotion journal")?;
fs::rename(journal_tmp, self.root.join(JOURNAL)).context("publish promotion journal")?;
let publication = (|| -> Result<()> {
sync_dir(&self.root)?;
self.boundary("journal_written")?;
self.recover()?;
self.boundary("journal_cleared")?;
Ok(())
})();
if let Err(error) = publication {
if exists(&self.root.join(JOURNAL)) {
self.rollback(&tx).with_context(|| format!("publication failed ({error:#}); rollback also failed; preserve journal and backup for recovery"))?;
}
return Err(error).context(
"pipeline publication failed; no Python was launched; retry `cxg pentest update`",
);
}
let backup = self.root.join(&tx.backup);
let result = Update {
status: self.status(),
changed: true,
backup_path: tx.had_old.then_some(backup),
};
self.announce(&before, &result);
Ok(result)
}
fn rollback(&self, tx: &Transaction) -> Result<()> {
let active = self.active();
let stage = self.root.join(&tx.stage);
let backup = self.root.join(&tx.backup);
if exists(&backup) {
if exists(&active) {
if exists(&stage) {
bail!("rollback has conflicting active and staged trees");
}
fs::rename(&active, &stage).context("preserve rejected generation")?;
}
fs::rename(&backup, &active).context("restore previous generation")?;
sync_dir(backup.parent().unwrap())?;
} else if !tx.had_old && exists(&active) {
if exists(&stage) {
bail!("rollback has conflicting active and staged trees");
}
fs::rename(&active, &stage).context("preserve rejected initial generation")?;
}
sync_dir(&self.root)?;
self.clear_journal()
}
fn announce(&self, before: &Status, result: &Update) {
eprintln!(
"Pentest pipeline updated {} → {} for CXG {}.",
before
.installed_digest
.as_deref()
.unwrap_or("missing/legacy"),
result.status.expected_digest,
result.status.binary_version
);
if let Some(path) = &result.backup_path {
eprintln!("Previous files saved at {}. Local edits and added files are preserved there and are no longer active (legacy trees are backed up in full).", path.display());
}
}
pub fn execution_lease(&self, source_override: bool) -> Result<Lease> {
loop {
let lease = self.lock(false)?;
let status = self.status();
if status.freshness == "current" {
return Ok(lease);
}
if !status.interrupted_transaction
&& (source_override || matches!(status.install_origin, Some(Origin::Source(_))))
{
bail!("source-derived pipeline selected; run `cxg pentest update --from-embedded` and unset CXG_SOURCE before dispatch");
}
drop(lease);
self.update(false, false, source_override)?;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::{Command, Stdio};
use tempfile::TempDir;
fn bundle(content: &str, version: &str) -> Bundle {
Bundle::new(
BTreeMap::from([
("cxg_pentest.py".into(), content.as_bytes().to_vec()),
("requirements.txt".into(), b"example".to_vec()),
("nested/helper.js".into(), b"helper".to_vec()),
]),
version,
Origin::Embedded,
)
.unwrap()
}
fn installer(root: &Path, content: &str) -> Installer {
Installer::new(root.to_path_buf(), bundle(content, "1.0"))
}
fn install(root: &Path, content: &str) -> Update {
installer(root, content)
.update(false, false, false)
.unwrap()
}
#[test]
fn embedded_manifest_covers_filtered_bundle() {
let b = Bundle::embedded();
let temp = TempDir::new().unwrap();
let i = Installer::new(temp.path().join("home"), b.clone());
i.update(false, false, false).unwrap();
let m = read_manifest(&i.active()).unwrap();
assert_eq!(m.files.len(), b.files.len());
assert!(m.files.contains_key("cxg_pentest.py"));
assert!(m.files.contains_key("requirements.txt"));
verify(&i.active(), &m).unwrap();
assert!(m.files.keys().all(|p| !excluded(Path::new(p))));
}
#[test]
fn freshness_depends_on_content_and_status_is_read_only() {
let temp = TempDir::new().unwrap();
let root = temp.path().join("absent");
let i = installer(&root, "old");
assert_eq!(i.status().freshness, "missing");
assert!(!root.exists());
assert!(install(&root, "old").changed);
assert!(!install(&root, "old").changed);
let different_version = Installer::new(root.clone(), bundle("old", "9.0"));
assert!(
!different_version
.update(false, false, false)
.unwrap()
.changed
);
assert!(install(&root, "new").changed);
}
#[test]
fn legacy_corrupt_missing_and_modified_files_refresh() {
for damage in ["legacy", "corrupt", "missing", "modified", "inventory"] {
let temp = TempDir::new().unwrap();
install(temp.path(), "old");
let i = installer(temp.path(), "old");
match damage {
"legacy" => fs::remove_file(i.active().join(MARKER)).unwrap(),
"corrupt" => fs::write(i.active().join(MARKER), "invalid").unwrap(),
"missing" => fs::remove_file(i.active().join("nested/helper.js")).unwrap(),
"modified" => fs::write(i.active().join("cxg_pentest.py"), "local").unwrap(),
"inventory" => {
let mut m = read_manifest(&i.active()).unwrap();
m.files.clear();
fs::write(i.active().join(MARKER), serde_json::to_vec(&m).unwrap()).unwrap();
}
_ => unreachable!(),
}
assert_ne!(i.status().freshness, "current");
let update = i.update(false, false, false).unwrap();
assert!(update.changed);
assert!(update.backup_path.unwrap().exists());
assert_eq!(i.status().freshness, "current");
}
}
#[test]
fn whole_tree_backup_preserves_user_files_removed_files_and_sibling_stores() {
let temp = TempDir::new().unwrap();
let mut old = bundle("old", "1.0");
old.files.insert("removed.py".into(), b"removed".to_vec());
old = Bundle::new(old.files, "1.0", Origin::Embedded).unwrap();
Installer::new(temp.path().into(), old)
.update(false, false, false)
.unwrap();
let i = installer(temp.path(), "new");
fs::write(i.active().join("user.txt"), "personal").unwrap();
fs::write(i.active().join("cxg_pentest.py"), "edited").unwrap();
for name in ["auth", "sessions", "templates"] {
fs::create_dir(temp.path().join(name)).unwrap();
fs::write(temp.path().join(name).join("keep"), name).unwrap();
}
let backup = i.update(false, false, false).unwrap().backup_path.unwrap();
assert_eq!(
fs::read_to_string(backup.join("user.txt")).unwrap(),
"personal"
);
assert_eq!(
fs::read_to_string(backup.join("cxg_pentest.py")).unwrap(),
"edited"
);
assert!(backup.join("removed.py").exists());
assert!(!i.active().join("removed.py").exists());
assert!(!i.active().join("user.txt").exists());
for name in ["auth", "sessions", "templates"] {
assert_eq!(
fs::read_to_string(temp.path().join(name).join("keep")).unwrap(),
name
);
}
}
#[cfg(unix)]
#[test]
fn symlinks_are_preserved_without_traversal() {
use std::os::unix::fs::symlink;
let temp = TempDir::new().unwrap();
let external = TempDir::new().unwrap();
fs::write(external.path().join("helper.js"), "outside").unwrap();
install(temp.path(), "old");
let i = installer(temp.path(), "new");
fs::remove_dir_all(i.active().join("nested")).unwrap();
symlink(external.path(), i.active().join("nested")).unwrap();
symlink(external.path(), i.active().join("user-link")).unwrap();
assert_eq!(i.status().freshness, "modified");
let backup = i.update(false, false, false).unwrap().backup_path.unwrap();
assert!(fs::symlink_metadata(backup.join("user-link"))
.unwrap()
.file_type()
.is_symlink());
assert!(fs::symlink_metadata(backup.join("nested"))
.unwrap()
.file_type()
.is_symlink());
assert_eq!(
fs::read_to_string(external.path().join("helper.js")).unwrap(),
"outside"
);
}
#[test]
fn source_install_requires_explicit_embedded_opt_in() {
let temp = TempDir::new().unwrap();
let mut source = bundle("source", "1.0");
source.manifest.origin = Origin::Source(PathBuf::from("development"));
Installer::new(temp.path().into(), source)
.update(false, false, true)
.unwrap();
let i = installer(temp.path(), "new");
assert!(i
.update(false, false, false)
.unwrap_err()
.to_string()
.contains("--from-embedded"));
assert!(i.execution_lease(false).is_err());
let result = i.update(false, true, true).unwrap();
assert!(result.backup_path.unwrap().exists());
assert_eq!(result.status.install_origin, Some(Origin::Embedded));
assert!(i.execution_lease(true).is_ok());
assert!(i.execution_lease(false).is_ok());
}
#[test]
fn source_to_embedded_same_content_changes_origin() {
let temp = TempDir::new().unwrap();
let mut source = bundle("same", "1.0");
source.manifest.origin = Origin::Source(PathBuf::from("development"));
Installer::new(temp.path().into(), source)
.update(false, false, false)
.unwrap();
let current = installer(temp.path(), "same");
assert!(current.execution_lease(true).is_ok());
assert!(!current.update(false, false, true).unwrap().changed);
assert!(matches!(
current.status().install_origin,
Some(Origin::Source(_))
));
let result = installer(temp.path(), "same")
.update(false, true, false)
.unwrap();
assert!(result.changed);
assert_eq!(result.status.install_origin, Some(Origin::Embedded));
}
#[test]
fn explicit_source_install_records_origin_even_when_bytes_match() {
let temp = TempDir::new().unwrap();
install(temp.path(), "same");
let mut source = bundle("same", "1.0");
source.manifest.origin = Origin::Source(PathBuf::from("development"));
let i = Installer::new(temp.path().into(), source);
assert!(i.update(false, false, false).unwrap().changed);
assert!(matches!(i.status().install_origin, Some(Origin::Source(_))));
}
#[test]
fn interruption_at_every_publication_boundary_recovers_complete_generation() {
for point in [
"stage_created",
"write_file",
"stage_verified",
"before_journal",
"journal_written",
"backup",
"old_moved",
"before_new_move",
"new_moved",
"new_verified",
"before_clear",
"journal_cleared",
] {
for old_content in ["old", "new"] {
let temp = TempDir::new().unwrap();
install(temp.path(), old_content);
let mut failing = installer(temp.path(), "new");
failing.fail_at = Some(point);
assert!(failing.update(true, false, false).is_err(), "{point}");
let good = installer(temp.path(), "new");
let _lease = good.execution_lease(false).unwrap();
assert_eq!(good.status().freshness, "current", "{point}");
assert_eq!(
fs::read_to_string(good.active().join("cxg_pentest.py")).unwrap(),
"new"
);
assert!(!exists(&temp.path().join(JOURNAL)));
}
}
}
#[test]
fn failed_stage_and_backup_never_replace_old_tree() {
for point in ["write_file", "backup"] {
let temp = TempDir::new().unwrap();
install(temp.path(), "old");
let mut i = installer(temp.path(), "new");
i.fail_at = Some(point);
assert!(i.update(false, false, false).is_err());
assert_eq!(
fs::read_to_string(i.active().join("cxg_pentest.py")).unwrap(),
"old"
);
assert_eq!(i.status().freshness, "stale");
}
let temp = TempDir::new().unwrap();
install(temp.path(), "old");
fs::remove_dir(temp.path().join("pentest-backups")).unwrap();
fs::write(temp.path().join("pentest-backups"), "blocked").unwrap();
let i = installer(temp.path(), "new");
assert!(i
.update(false, false, false)
.unwrap_err()
.to_string()
.contains("backup"));
assert_eq!(
fs::read_to_string(i.active().join("cxg_pentest.py")).unwrap(),
"old"
);
}
#[test]
fn lock_timeout_and_release() {
let temp = TempDir::new().unwrap();
install(temp.path(), "old");
let i = installer(temp.path(), "new").with_timeout(Duration::from_millis(50));
let shared = i.lock(false).unwrap();
assert!(i
.update(false, false, false)
.unwrap_err()
.to_string()
.contains("timeout"));
drop(shared);
assert!(i.update(false, false, false).unwrap().changed);
let writer = i.lock(true).unwrap();
assert!(i.execution_lease(false).is_err());
drop(writer);
assert!(i.execution_lease(false).is_ok());
}
const BOUNDARIES: &[&str] = &[
"stage_created",
"write_file",
"stage_verified",
"before_journal",
"journal_written",
"backup",
"old_moved",
"before_new_move",
"new_moved",
"new_verified",
"before_clear",
"journal_cleared",
];
#[test]
fn subprocess_crashes_at_publication_boundaries_recover_on_next_dispatch() {
for point in BOUNDARIES {
for had_old in [false, true] {
if !had_old && *point == "backup" {
continue;
}
let temp = TempDir::new().unwrap();
if had_old {
install(temp.path(), "old");
}
let status = child(temp.path(), &format!("crash:{point}"))
.wait()
.unwrap();
assert_eq!(status.code(), Some(73), "{point}");
let i = installer(temp.path(), "new");
let _lease = i.execution_lease(false).unwrap();
assert_eq!(i.status().freshness, "current", "{point}");
verify(&i.active(), &i.bundle.manifest).unwrap();
if had_old {
let backup = fs::read_dir(temp.path().join("pentest-backups"))
.unwrap()
.next()
.unwrap()
.unwrap()
.path();
assert_eq!(
fs::read_to_string(backup.join("cxg_pentest.py")).unwrap(),
"old"
);
}
}
}
}
#[test]
fn disk_full_and_failed_promotion_preserve_the_previous_generation() {
for point in ["disk_full", "promotion_failure"] {
let temp = TempDir::new().unwrap();
install(temp.path(), "old");
let mut failing = installer(temp.path(), "new");
failing.fail_at = Some(point);
assert!(failing.update(false, false, false).is_err());
assert_eq!(
fs::read_to_string(failing.active().join("cxg_pentest.py")).unwrap(),
"old"
);
let good = installer(temp.path(), "new");
let _lease = good.execution_lease(false).unwrap();
assert_eq!(good.status().freshness, "current");
}
}
fn child(root: &Path, mode: &str) -> std::process::Child {
Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"pentest_install::tests::lease_child",
"--nocapture",
])
.env("CXG_INSTALL_TEST_ROOT", root)
.env("CXG_INSTALL_TEST_MODE", mode)
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap()
}
#[test]
fn lease_child() {
let Some(root) = std::env::var_os("CXG_INSTALL_TEST_ROOT") else {
return;
};
let root = PathBuf::from(root);
let mut i = installer(&root, "new");
let mode = std::env::var("CXG_INSTALL_TEST_MODE").unwrap();
if let Some(point) = mode.strip_prefix("crash:") {
i.fail_at = Some(*BOUNDARIES.iter().find(|p| **p == point).unwrap());
i.crash = true;
i.update(true, false, false).unwrap();
panic!("crash boundary was not reached");
}
match mode.as_str() {
"hold" => {
let _lease = i.lock(false).unwrap();
fs::write(root.join("ready"), "ready").unwrap();
std::thread::sleep(Duration::from_secs(20));
}
"run" => {
let _lease = i.execution_lease(false).unwrap();
verify(&i.active(), &i.bundle.manifest).unwrap();
}
"update" => {
i.update(false, false, false).unwrap();
}
_ => unreachable!(),
}
}
#[test]
fn processes_race_one_upgrade_and_death_releases_shared_lease() {
let temp = TempDir::new().unwrap();
install(temp.path(), "old");
let mut holder = child(temp.path(), "hold");
let start = Instant::now();
while !temp.path().join("ready").exists() {
assert!(start.elapsed() < Duration::from_secs(10));
std::thread::sleep(Duration::from_millis(10));
}
let mut updater = child(temp.path(), "update");
let mut runner = child(temp.path(), "run");
std::thread::sleep(Duration::from_millis(100));
assert!(updater.try_wait().unwrap().is_none());
assert_eq!(
fs::read_to_string(temp.path().join("pentest/cxg_pentest.py")).unwrap(),
"old"
);
holder.kill().unwrap();
holder.wait().unwrap();
assert!(updater.wait().unwrap().success());
assert!(runner.wait().unwrap().success());
assert_eq!(
fs::read_dir(temp.path().join("pentest-backups"))
.unwrap()
.count(),
1
);
}
#[test]
fn unsafe_bundle_paths_are_rejected() {
for path in [
"../escape",
"/absolute",
"nested/../../escape",
"C:\\escape",
] {
let mut files = bundle("x", "1").files;
files.insert(path.into(), vec![]);
assert!(Bundle::new(files, "1", Origin::Embedded).is_err());
}
}
}