use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Duration;
use eggup_acquisition::{
AcquisitionError, AcquisitionRequest, AcquisitionTransport, CancelFlag, FetchLimits,
FetchOutcome,
};
use eggup_core::{
AbsentPolicy, ArtifactMember, ArtifactSet, CommitOwnership, ExactIdentityValidator,
InstallPlan, IntegrityRequirement, MemberId, Ownership, OwnershipVerifier, PermissionsIntent,
PreparedTransaction, ProductId, ReleaseId, Sha256Manifest, TransactionDisposition,
TransactionReceipt,
};
use crate::error::AppError;
const PUBLISHED_TARGETS: &[(&str, &str)] = &[
("aarch64-apple-darwin", "cargo-cleanme-aarch64-apple-darwin"),
(
"aarch64-unknown-linux-gnu",
"cargo-cleanme-aarch64-unknown-linux-gnu",
),
("x86_64-apple-darwin", "cargo-cleanme-x86_64-apple-darwin"),
(
"x86_64-pc-windows-msvc",
"cargo-cleanme-x86_64-pc-windows-msvc.exe",
),
(
"x86_64-unknown-linux-gnu",
"cargo-cleanme-x86_64-unknown-linux-gnu",
),
];
const PRODUCT: &str = "cargo-cleanme";
const MAX_METADATA_BYTES: usize = 1024 * 1024;
const MAX_ARTIFACT_BYTES: u64 = 128 * 1024 * 1024;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const TOTAL_TIMEOUT: Duration = Duration::from_secs(120);
fn expected_identity(version: &str) -> String {
format!("{PRODUCT} {version}\n")
}
pub fn host_target() -> Option<&'static str> {
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
{
Some("x86_64-unknown-linux-gnu")
}
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
{
Some("aarch64-unknown-linux-gnu")
}
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
{
Some("x86_64-apple-darwin")
}
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
{
Some("aarch64-apple-darwin")
}
#[cfg(all(target_os = "windows", target_arch = "x86_64"))]
{
Some("x86_64-pc-windows-msvc")
}
}
pub fn asset_for_target(triple: &str) -> Option<&'static str> {
PUBLISHED_TARGETS
.iter()
.find(|(t, _)| *t == triple)
.map(|(_, asset)| *asset)
}
fn crates_io_metadata_url() -> String {
format!("https://crates.io/api/v1/crates/{PRODUCT}")
}
fn release_asset_url(tag: &str, asset: &str) -> String {
format!("https://github.com/dbowm91/{PRODUCT}/releases/download/{tag}/{asset}")
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Provenance {
CargoManaged { bin_root: PathBuf, version: String },
VerifiableSelfManaged { digest: [u8; 32] },
CargoInstallOnlyHost { triple_hint: String },
UnprovableOwnership { detail: String },
}
impl Provenance {
pub fn code(&self) -> &'static str {
match self {
Provenance::CargoManaged { .. } => "cargo_managed",
Provenance::VerifiableSelfManaged { .. } => "self_managed",
Provenance::CargoInstallOnlyHost { .. } => "cargo_install_only_host",
Provenance::UnprovableOwnership { .. } => "unprovable_ownership",
}
}
pub fn remediation(&self) -> Option<String> {
match self {
Provenance::CargoManaged { .. } => {
Some(format!("cargo install {PRODUCT} --locked --force"))
}
Provenance::CargoInstallOnlyHost { .. } => {
Some(format!("cargo install {PRODUCT} --locked"))
}
Provenance::UnprovableOwnership { .. } => Some(format!(
"Reinstall with the published installer, then retry: \
https://github.com/dbowm91/{PRODUCT}"
)),
Provenance::VerifiableSelfManaged { .. } => None,
}
}
}
#[derive(Debug, Clone)]
struct LiveDigestVerifier {
expected: HashMap<MemberId, [u8; 32]>,
}
impl OwnershipVerifier for LiveDigestVerifier {
fn verify(&self, _member: &MemberId, destination: &Path) -> Ownership {
let Some(expected) = self.expected.get(_member) else {
return Ownership::Unknown;
};
match std::fs::symlink_metadata(destination) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ownership::Absent,
Err(_) => Ownership::Unknown,
Ok(meta) if meta.file_type().is_symlink() => Ownership::Foreign,
Ok(meta) if !meta.is_file() => Ownership::Foreign,
Ok(_) => match eggup_core::hash_file(destination) {
Ok(actual) if &actual == expected => Ownership::Owned,
Ok(_) => Ownership::Foreign,
Err(_) => Ownership::Unknown,
},
}
}
}
#[derive(Debug, Clone)]
pub struct UpdatePlan {
pub from_version: String,
pub to_version: String,
pub target: String,
pub asset: String,
pub tag: String,
pub provenance: Provenance,
}
#[derive(Debug)]
pub enum UpdateError {
TransportUnavailable { detail: String },
NoPublishedStableVersion { detail: String },
AlreadyCurrent { current: String, published: String },
NewerThanPublished { current: String, published: String },
Acquisition { stage: String, detail: String },
ReleaseEvidence { detail: String },
Transaction { detail: String },
Receipt {
disposition: &'static str,
detail: String,
},
Provenance { provenance: Provenance },
HostUnsupported { detail: String },
}
impl std::fmt::Display for UpdateError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
UpdateError::TransportUnavailable { detail } => {
write!(f, "the update transport is unavailable: {detail}")
}
UpdateError::NoPublishedStableVersion { detail } => {
write!(
f,
"the registry reported no usable stable version: {detail}"
)
}
UpdateError::AlreadyCurrent { current, published } => {
write!(
f,
"already at the latest stable version ({current}; published is {published})"
)
}
UpdateError::NewerThanPublished { current, published } => {
write!(
f,
"this build ({current}) is newer than the published release \
({published}); refusing to downgrade it"
)
}
UpdateError::Acquisition { stage, detail } => {
write!(f, "could not {stage}: {detail}")
}
UpdateError::ReleaseEvidence { detail } => {
write!(f, "release integrity evidence is unusable: {detail}")
}
UpdateError::Transaction { detail } => {
write!(f, "the update transaction failed: {detail}")
}
UpdateError::Receipt {
disposition,
detail,
} => {
write!(
f,
"the update did not commit cleanly ({disposition}): {detail}"
)
}
UpdateError::Provenance { provenance } => {
write!(
f,
"this installation cannot be updated by {PRODUCT} update ({})",
provenance.code()
)
}
UpdateError::HostUnsupported { detail } => {
write!(
f,
"this host has no published cargo-cleanme binary: {detail}"
)
}
}
}
}
impl std::error::Error for UpdateError {}
impl From<UpdateError> for AppError {
fn from(value: UpdateError) -> Self {
match value {
UpdateError::Provenance { provenance } => {
AppError::Provenance(remediation_text(&provenance))
}
other => AppError::Update(other.to_string()),
}
}
}
fn remediation_text(provenance: &Provenance) -> String {
match provenance.remediation() {
Some(command) => format!(
"{} is {}; run this instead:\n {command}",
PRODUCT,
provenance.code()
),
None => format!("{PRODUCT} is {}", provenance.code()),
}
}
pub fn classify_provenance(current_exe: &Path) -> Provenance {
classify_provenance_in(current_exe, default_cargo_home())
}
fn default_cargo_home() -> Option<PathBuf> {
std::env::var_os("CARGO_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cargo")))
}
pub fn classify_provenance_in(current_exe: &Path, cargo_home: Option<PathBuf>) -> Provenance {
let Some(target) = host_target() else {
return Provenance::CargoInstallOnlyHost {
triple_hint: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH),
};
};
let _ = target;
if binary_name(current_exe).is_empty() {
return Provenance::UnprovableOwnership {
detail: format!(
"the running executable {} has a non-UTF-8 file name no Cargo record can name",
current_exe.display()
),
};
}
if std::fs::symlink_metadata(current_exe).is_ok_and(|m| m.file_type().is_symlink()) {
return Provenance::UnprovableOwnership {
detail: format!(
"the running executable {} is a symlink, so its ownership cannot be proven",
current_exe.display()
),
};
}
if let Some(home) = cargo_home.as_deref() {
let bin_root = home.join("bin");
if current_exe.parent() == Some(bin_root.as_path()) {
return match read_cargo_record(home, PRODUCT, binary_name(current_exe)) {
CargoRecord::Recorded { version } => Provenance::CargoManaged { bin_root, version },
CargoRecord::DoesNotClaim { reason } => Provenance::UnprovableOwnership {
detail: format!(
"{} is inside the Cargo bin root {} but {reason}",
current_exe.display(),
bin_root.display()
),
},
CargoRecord::Absent => Provenance::UnprovableOwnership {
detail: format!(
"{} is inside the Cargo bin root {} but Cargo has no record file there",
current_exe.display(),
bin_root.display()
),
},
CargoRecord::Uninterpretable { detail } => Provenance::UnprovableOwnership {
detail: format!(
"{} is inside the Cargo bin root {} and {detail}",
current_exe.display(),
bin_root.display()
),
},
};
}
}
for root in cargo_roots_above(current_exe) {
match read_cargo_record(&root, PRODUCT, binary_name(current_exe)) {
CargoRecord::Recorded { version } => {
return Provenance::CargoManaged {
bin_root: root.join("bin"),
version,
};
}
CargoRecord::DoesNotClaim { .. } | CargoRecord::Absent => continue,
CargoRecord::Uninterpretable { detail } => {
return Provenance::UnprovableOwnership {
detail: format!(
"{} sits under the Cargo root {} and {detail}",
current_exe.display(),
root.display()
),
};
}
}
}
match eggup_core::hash_file(current_exe) {
Ok(digest) => Provenance::VerifiableSelfManaged { digest },
Err(error) => Provenance::UnprovableOwnership {
detail: format!(
"the running executable {} could not be hashed: {error}",
current_exe.display()
),
},
}
}
const CARGO_ROOT_SEARCH_DEPTH: usize = 4;
fn binary_name(path: &Path) -> &str {
path.file_name().and_then(|n| n.to_str()).unwrap_or("")
}
fn cargo_roots_above(path: &Path) -> Vec<PathBuf> {
let Some(bin_dir) = path.parent() else {
return Vec::new();
};
bin_dir
.ancestors()
.take(CARGO_ROOT_SEARCH_DEPTH + 1)
.filter_map(Path::parent)
.map(Path::to_path_buf)
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CargoRecord {
Recorded { version: String },
DoesNotClaim { reason: &'static str },
Absent,
Uninterpretable { detail: String },
}
impl CargoRecord {
pub fn is_uncertain(&self) -> bool {
matches!(self, CargoRecord::Uninterpretable { .. })
}
}
fn read_cargo_record(root: &Path, package: &str, binary: &str) -> CargoRecord {
let path = root.join(".crates.toml");
let metadata = match std::fs::metadata(&path) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return CargoRecord::Absent,
Err(error) => {
return CargoRecord::Uninterpretable {
detail: format!(
"the Cargo record {} exists but could not be inspected: {error}",
path.display()
),
};
}
Ok(metadata) => metadata,
};
if !metadata.is_file() {
return CargoRecord::Uninterpretable {
detail: format!("the Cargo record {} is not a regular file", path.display()),
};
}
if metadata.len() > MAX_METADATA_BYTES as u64 {
return CargoRecord::Uninterpretable {
detail: format!(
"the Cargo record {} is {} bytes, above the {MAX_METADATA_BYTES} byte ceiling",
path.display(),
metadata.len()
),
};
}
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(error) => {
return CargoRecord::Uninterpretable {
detail: format!(
"the Cargo record {} could not be read: {error}",
path.display()
),
};
}
};
let value: toml::Value = match toml::from_str(&text) {
Ok(value) => value,
Err(error) => {
return CargoRecord::Uninterpretable {
detail: format!(
"the Cargo record {} is not valid TOML: {error}",
path.display()
),
};
}
};
let Some(table) = value.get("v1").and_then(toml::Value::as_table) else {
return CargoRecord::Uninterpretable {
detail: format!(
"the Cargo record {} has no `v1` table, which is not a supported Cargo record shape",
path.display()
),
};
};
let mut saw_malformed_matching_package = false;
for (spec, executables) in table {
let Some((head, _source)) = spec.rsplit_once(')') else {
if spec.split_whitespace().next() == Some(package) {
saw_malformed_matching_package = true;
}
continue;
};
let mut fields = head.split_whitespace();
let Some(name) = fields.next() else {
continue;
};
if name != package {
continue;
}
let Some(version) = fields.next() else {
saw_malformed_matching_package = true;
continue;
};
let Some(names) = executables.as_array() else {
saw_malformed_matching_package = true;
continue;
};
if names.iter().any(|name| name.as_str() == Some(binary)) {
return CargoRecord::Recorded {
version: version.to_owned(),
};
}
}
if saw_malformed_matching_package {
return CargoRecord::Uninterpretable {
detail: format!(
"the Cargo record {} holds an entry for {package} whose version or executable \
list could not be interpreted",
path.display()
),
};
}
CargoRecord::DoesNotClaim {
reason: "the Cargo record for this root does not name this package",
}
}
pub fn published_stable_version(metadata: &[u8]) -> Result<String, UpdateError> {
let text =
std::str::from_utf8(metadata).map_err(|e| UpdateError::NoPublishedStableVersion {
detail: format!("registry metadata is not UTF-8: {e}"),
})?;
let value: serde_json::Value =
serde_json::from_str(text).map_err(|e| UpdateError::NoPublishedStableVersion {
detail: format!("registry metadata is not valid JSON: {e}"),
})?;
let version = value
.get("crate")
.and_then(|c| c.get("max_stable_version"))
.and_then(serde_json::Value::as_str)
.ok_or_else(|| UpdateError::NoPublishedStableVersion {
detail: "registry metadata has no crate.max_stable_version".to_owned(),
})?;
if !is_release_version(version) {
return Err(UpdateError::NoPublishedStableVersion {
detail: format!("{version:?} is not a plain X.Y.Z release"),
});
}
Ok(version.to_owned())
}
pub fn compare_release_versions(left: &str, right: &str) -> Option<std::cmp::Ordering> {
let parse = |value: &str| -> Option<[u64; 3]> {
let mut parts = value.split('.');
let mut out = [0u64; 3];
for slot in out.iter_mut() {
*slot = parts.next()?.parse::<u64>().ok()?;
}
if parts.next().is_some() {
return None;
}
Some(out)
};
Some(parse(left)?.cmp(&parse(right)?))
}
pub fn is_release_version(version: &str) -> bool {
let mut parts = version.split('.');
for _ in 0..3 {
match parts.next() {
Some(p) if !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) => {}
_ => return false,
}
}
parts.next().is_none()
}
pub trait UpdateEnvironment {
fn current_exe(&self) -> Result<PathBuf, UpdateError>;
fn cargo_home(&self) -> Option<PathBuf>;
fn current_version(&self) -> String;
fn staging_dir(&self) -> Result<PathBuf, UpdateError>;
fn fetch(&self, url: &str, destination: &Path) -> Result<u64, UpdateError>;
fn fetch_metadata(&self, url: &str, limit: usize) -> Result<Vec<u8>, UpdateError>;
fn cleanup(&self, staging: &Path) -> Result<(), String>;
}
const USER_AGENT: &str = concat!(
"cargo-cleanme/",
env!("CARGO_PKG_VERSION"),
" (+https://github.com/dbowm91/cargo-cleanme)"
);
struct HttpEnvironment {
transport: eggup_eggfetch::EggfetchTransport,
}
impl HttpEnvironment {
fn new() -> Result<Self, UpdateError> {
let config = eggup_eggfetch::EggfetchConfig::strict()
.user_agent(USER_AGENT)
.timeouts(CONNECT_TIMEOUT, TOTAL_TIMEOUT);
let transport = eggup_eggfetch::EggfetchTransport::strict(config).map_err(|error| {
UpdateError::TransportUnavailable {
detail: describe_acquisition(&error),
}
})?;
Ok(Self { transport })
}
fn limits(&self) -> FetchLimits {
FetchLimits {
max_metadata_bytes: MAX_METADATA_BYTES,
max_artifact_bytes: MAX_ARTIFACT_BYTES,
connect_timeout: CONNECT_TIMEOUT,
total_timeout: TOTAL_TIMEOUT,
}
}
}
impl UpdateEnvironment for HttpEnvironment {
fn current_exe(&self) -> Result<PathBuf, UpdateError> {
std::env::current_exe().map_err(|error| UpdateError::Transaction {
detail: format!("could not resolve the running executable: {error}"),
})
}
fn cargo_home(&self) -> Option<PathBuf> {
default_cargo_home()
}
fn current_version(&self) -> String {
env!("CARGO_PKG_VERSION").to_owned()
}
fn staging_dir(&self) -> Result<PathBuf, UpdateError> {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let unique =
std::env::temp_dir().join(format!("{PRODUCT}-update-{}-{nanos}", std::process::id()));
std::fs::create_dir(&unique).map_err(|error| UpdateError::Transaction {
detail: format!(
"could not create a private staging directory at {}: {error}",
unique.display()
),
})?;
Ok(unique)
}
fn fetch(&self, url: &str, destination: &Path) -> Result<u64, UpdateError> {
let request = AcquisitionRequest::new(url).map_err(|error| UpdateError::Acquisition {
stage: "build the release request".to_owned(),
detail: describe_acquisition(&error),
})?;
let cancel = CancelFlag::new();
let limits = self.limits();
let outcome = self
.transport
.fetch_artifact(&request, destination, limits, &cancel)
.map_err(|error| UpdateError::Acquisition {
stage: format!("download {url}"),
detail: describe_acquisition(&error),
})?;
match outcome {
FetchOutcome::Success(evidence) => Ok(evidence.bytes_written()),
FetchOutcome::NotFound => Err(UpdateError::ReleaseEvidence {
detail: format!("the release host reports {url} is absent"),
}),
}
}
fn fetch_metadata(&self, url: &str, limit: usize) -> Result<Vec<u8>, UpdateError> {
let request = AcquisitionRequest::new(url).map_err(|error| UpdateError::Acquisition {
stage: "build the registry request".to_owned(),
detail: describe_acquisition(&error),
})?;
let mut bounds = self.limits();
bounds.max_metadata_bytes = limit;
let cancel = CancelFlag::new();
let outcome = self
.transport
.fetch_metadata(&request, bounds, &cancel)
.map_err(|error| UpdateError::Acquisition {
stage: format!("read {url}"),
detail: describe_acquisition(&error),
})?;
match outcome {
FetchOutcome::Success(body) => Ok(body.bytes().to_vec()),
FetchOutcome::NotFound => Err(UpdateError::NoPublishedStableVersion {
detail: format!("the registry reports {url} is absent"),
}),
}
}
fn cleanup(&self, staging: &Path) -> Result<(), String> {
std::fs::remove_dir_all(staging).map_err(|error| error.to_string())
}
}
fn describe_acquisition(error: &AcquisitionError) -> String {
format!("{error:?}")
}
pub fn run(
environment: &dyn UpdateEnvironment,
check_only: bool,
) -> Result<UpdatePlan, UpdateError> {
let current_exe = environment.current_exe()?;
let current_version = environment.current_version();
let provenance = classify_provenance_in(¤t_exe, environment.cargo_home());
let target = match host_target() {
Some(target) => target,
None => {
return Err(UpdateError::Provenance { provenance });
}
};
let asset = asset_for_target(target).ok_or_else(|| UpdateError::HostUnsupported {
detail: format!("{target} has no contracted release asset"),
})?;
if !check_only && !matches!(provenance, Provenance::VerifiableSelfManaged { .. }) {
return Err(UpdateError::Provenance { provenance });
}
let metadata = environment.fetch_metadata(&crates_io_metadata_url(), MAX_METADATA_BYTES)?;
let to_version = published_stable_version(&metadata)?;
match compare_release_versions(&to_version, ¤t_version) {
Some(std::cmp::Ordering::Equal) => {
return Err(UpdateError::AlreadyCurrent {
current: current_version,
published: to_version,
});
}
Some(std::cmp::Ordering::Less) => {
return Err(UpdateError::NewerThanPublished {
current: current_version,
published: to_version,
});
}
Some(std::cmp::Ordering::Greater) => {}
None => {
return Err(UpdateError::NoPublishedStableVersion {
detail: format!(
"cannot order published {to_version:?} against running {current_version:?}"
),
});
}
}
let plan = UpdatePlan {
from_version: current_version,
to_version: to_version.clone(),
target: target.to_owned(),
asset: asset.to_owned(),
tag: format!("v{to_version}"),
provenance,
};
if check_only {
return Ok(plan);
}
if let Provenance::VerifiableSelfManaged { .. } = plan.provenance {
} else {
return Err(UpdateError::Provenance {
provenance: plan.provenance.clone(),
});
}
execute(environment, &plan, ¤t_exe)
}
fn execute(
environment: &dyn UpdateEnvironment,
plan: &UpdatePlan,
current_exe: &Path,
) -> Result<UpdatePlan, UpdateError> {
let live_digest = match &plan.provenance {
Provenance::VerifiableSelfManaged { digest } => *digest,
other => {
return Err(UpdateError::Provenance {
provenance: other.clone(),
});
}
};
let staging = environment.staging_dir()?;
let outcome = (|| -> Result<TransactionReceipt, UpdateError> {
let sidecar_path = staging.join(format!("{}.sha256", plan.asset));
environment.fetch(
&release_asset_url(&plan.tag, &format!("{}.sha256", plan.asset)),
&sidecar_path,
)?;
let sidecar_text = std::fs::read_to_string(&sidecar_path).map_err(|error| {
UpdateError::ReleaseEvidence {
detail: format!("the release checksum sidecar is unreadable: {error}"),
}
})?;
let manifest: Sha256Manifest =
eggup_core::parse_sha256_sidecar(&sidecar_text).map_err(|error| {
UpdateError::ReleaseEvidence {
detail: format!("the release checksum sidecar is malformed: {error}"),
}
})?;
let acquired = staging.join(&plan.asset);
let written = environment.fetch(&release_asset_url(&plan.tag, &plan.asset), &acquired)?;
if written == 0 {
return Err(UpdateError::ReleaseEvidence {
detail: format!("the release asset {} is empty", plan.asset),
});
}
match manifest.filename() {
Some(name) if name == plan.asset => {}
Some(name) => {
return Err(UpdateError::ReleaseEvidence {
detail: format!(
"the sidecar names {name:?}, not the requested asset {:?}",
plan.asset
),
});
}
None => {
return Err(UpdateError::ReleaseEvidence {
detail: format!(
"the sidecar does not name the requested asset {:?}",
plan.asset
),
});
}
}
let install_root = current_exe
.parent()
.ok_or_else(|| UpdateError::Transaction {
detail: "the running executable has no parent directory".to_owned(),
})?
.to_path_buf();
let member_id =
MemberId::new("cargo-cleanme").map_err(|error| UpdateError::Transaction {
detail: format!("could not name the update member: {error}"),
})?;
let file_name = current_exe
.file_name()
.ok_or_else(|| UpdateError::Transaction {
detail: "the running executable has no file name".to_owned(),
})?
.to_owned();
let member = ArtifactMember::new(member_id.clone(), acquired, file_name)
.map_err(|error| UpdateError::Transaction {
detail: format!("could not declare the update member: {error}"),
})?
.with_permissions(PermissionsIntent::Executable)
.with_integrity(IntegrityRequirement::Sha256(*manifest.digest()));
let artifacts = ArtifactSet::single(member).map_err(|error| UpdateError::Transaction {
detail: format!("could not assemble the update set: {error}"),
})?;
let install_plan = InstallPlan::new(
ProductId::new(PRODUCT).map_err(|error| UpdateError::Transaction {
detail: format!("invalid product identity: {error}"),
})?,
ReleaseId::new(plan.to_version.clone()).map_err(|error| UpdateError::Transaction {
detail: format!("invalid release identity: {error}"),
})?,
install_root,
artifacts,
)
.map_err(|error| UpdateError::Transaction {
detail: format!("the install plan is invalid: {error}"),
})?;
let prepared: PreparedTransaction =
install_plan
.prepare()
.map_err(|error| UpdateError::Transaction {
detail: format!("could not stage the update: {error}"),
})?;
let verified = prepared
.verify_integrity()
.map_err(|error| UpdateError::Transaction {
detail: format!("release integrity verification failed: {error}"),
})?;
let validator =
ExactIdentityValidator::new(member_id.clone(), expected_identity(&plan.to_version))
.args(["--version"]);
let validated =
verified
.validate(&validator)
.map_err(|error| UpdateError::Transaction {
detail: format!(
"the candidate did not identify itself as {} {}\n{error}",
PRODUCT, plan.to_version
),
})?;
let mut expected = HashMap::new();
expected.insert(member_id, live_digest);
let verifier = LiveDigestVerifier { expected };
validated
.commit(CommitOwnership::new(&verifier, AbsentPolicy::DenyCreate))
.map_err(|error| UpdateError::Transaction {
detail: format!("commit failed: {error}"),
})
})();
let cleanup = environment.cleanup(&staging);
let receipt = match outcome {
Ok(receipt) => receipt,
Err(error) => {
if let Err(detail) = cleanup {
eprintln!(
"cargo-cleanme: staging directory {} could not be removed after a failed update: {detail}",
staging.display()
);
}
return Err(error);
}
};
if let Err(detail) = cleanup {
return Err(UpdateError::Transaction {
detail: format!(
"the executable was replaced, but its staging directory {} could not be removed: {detail}",
staging.display()
),
});
}
let disposition = match receipt.disposition() {
TransactionDisposition::Committed => return Ok(plan.clone()),
TransactionDisposition::RolledBack => "rolled_back",
TransactionDisposition::RecoveryRequired => "recovery_required",
};
let detail = receipt
.failure()
.map(|f| f.detail().to_owned())
.unwrap_or_else(|| "no failure detail was recorded".to_owned());
Err(UpdateError::Receipt {
disposition,
detail,
})
}
pub fn update(check_only: bool) -> Result<UpdatePlan, UpdateError> {
let environment = HttpEnvironment::new()?;
run(&environment, check_only)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
use std::collections::HashMap as Map;
struct FixtureEnvironment {
exe: PathBuf,
cargo_home: Option<PathBuf>,
version: String,
staging: RefCell<Option<PathBuf>>,
created_staging: RefCell<Vec<PathBuf>>,
cleanup_calls: RefCell<usize>,
suppress_cleanup: bool,
cleanup_error: Option<String>,
responses: Map<String, Vec<u8>>,
transport_failures: Vec<String>,
absent: Vec<String>,
requested: RefCell<Vec<String>>,
}
impl FixtureEnvironment {
fn new(exe: PathBuf, version: &str) -> Self {
Self {
exe,
cargo_home: None,
version: version.to_owned(),
staging: RefCell::new(None),
created_staging: RefCell::new(Vec::new()),
cleanup_calls: RefCell::new(0),
suppress_cleanup: false,
cleanup_error: None,
responses: Map::new(),
transport_failures: Vec::new(),
absent: Vec::new(),
requested: RefCell::new(Vec::new()),
}
}
fn respond(mut self, url: &str, bytes: Vec<u8>) -> Self {
self.responses.insert(url.to_owned(), bytes);
self
}
fn cargo_home(mut self, home: PathBuf) -> Self {
self.cargo_home = Some(home);
self
}
fn fail_transport(mut self, url: &str) -> Self {
self.transport_failures.push(url.to_owned());
self
}
fn leaking_staging(mut self) -> Self {
self.suppress_cleanup = true;
self
}
#[cfg(unix)]
fn failing_cleanup(mut self, detail: &str) -> Self {
self.cleanup_error = Some(detail.to_owned());
self
}
fn cleanup_calls(&self) -> usize {
*self.cleanup_calls.borrow()
}
fn leaked_staging(&self) -> Vec<PathBuf> {
self.created_staging
.borrow()
.iter()
.filter(|path| path.exists())
.cloned()
.collect()
}
#[cfg_attr(not(unix), allow(dead_code))]
fn assert_no_staging_leak(&self, what: &str) {
assert_eq!(
self.created_staging.borrow().len(),
1,
"{what}: expected exactly one staging transaction, saw {:?}",
self.created_staging.borrow()
);
assert!(
self.cleanup_calls() > 0,
"{what}: production never reached the staging cleanup callback"
);
assert!(
self.leaked_staging().is_empty(),
"{what}: staging left behind: {:?}",
self.leaked_staging()
);
}
#[cfg_attr(not(unix), allow(dead_code))]
fn absent(mut self, url: &str) -> Self {
self.absent.push(url.to_owned());
self
}
fn registry(&self, version: &str) -> String {
format!(r#"{{"crate":{{"max_stable_version":"{version}"}}}}"#)
}
fn asset_url(tag: &str, asset: &str) -> String {
release_asset_url(tag, asset)
}
}
impl UpdateEnvironment for FixtureEnvironment {
fn current_exe(&self) -> Result<PathBuf, UpdateError> {
Ok(self.exe.clone())
}
fn cargo_home(&self) -> Option<PathBuf> {
self.cargo_home.clone()
}
fn current_version(&self) -> String {
self.version.clone()
}
fn staging_dir(&self) -> Result<PathBuf, UpdateError> {
let path = unique("cargo-cleanme-update-test");
std::fs::create_dir(&path).map_err(|e| UpdateError::Transaction {
detail: e.to_string(),
})?;
*self.staging.borrow_mut() = Some(path.clone());
self.created_staging.borrow_mut().push(path.clone());
Ok(path)
}
fn fetch(&self, url: &str, destination: &Path) -> Result<u64, UpdateError> {
self.requested.borrow_mut().push(url.to_owned());
if self.transport_failures.iter().any(|u| u == url) {
return Err(UpdateError::Acquisition {
stage: format!("download {url}"),
detail: "fixture transport failure".to_owned(),
});
}
if self.absent.iter().any(|u| u == url) {
return Err(UpdateError::ReleaseEvidence {
detail: format!("the release host reports {url} is absent"),
});
}
let bytes = self
.responses
.get(url)
.ok_or_else(|| UpdateError::ReleaseEvidence {
detail: format!("fixture has no response for {url}"),
})?;
std::fs::write(destination, bytes).map_err(|e| UpdateError::Acquisition {
stage: format!("stage {url}"),
detail: e.to_string(),
})?;
Ok(bytes.len() as u64)
}
fn fetch_metadata(&self, url: &str, _limit: usize) -> Result<Vec<u8>, UpdateError> {
self.requested.borrow_mut().push(url.to_owned());
if self.transport_failures.iter().any(|u| u == url) {
return Err(UpdateError::Acquisition {
stage: format!("read {url}"),
detail: "fixture transport failure".to_owned(),
});
}
self.responses
.get(url)
.cloned()
.ok_or_else(|| UpdateError::NoPublishedStableVersion {
detail: format!("fixture has no metadata for {url}"),
})
}
fn cleanup(&self, staging: &Path) -> Result<(), String> {
*self.cleanup_calls.borrow_mut() += 1;
if self.suppress_cleanup {
return Ok(());
}
if let Some(detail) = &self.cleanup_error {
return Err(detail.clone());
}
std::fs::remove_dir_all(staging).map_err(|e| e.to_string())?;
*self.staging.borrow_mut() = None;
Ok(())
}
}
fn unique(prefix: &str) -> PathBuf {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
std::env::temp_dir().join(format!(
"{prefix}-{}-{nanos}-{}",
std::process::id(),
COUNTER.fetch_add(1, Ordering::SeqCst)
))
}
fn candidate_bytes(version: &str) -> Vec<u8> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let path = unique(&format!("cargo-cleanme-candidate-{version}"));
std::fs::write(
&path,
format!(
"#!/bin/sh\n\
if [ \"$1\" = \"--version\" ]; then\n\
\x20 printf '{PRODUCT} {version}\\n'\n\
\x20 exit 0\n\
fi\n\
printf 'fixture candidate: unexpected argv\\n' >&2\n\
exit 2\n"
),
)
.unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
let bytes = std::fs::read(&path).unwrap();
let _ = std::fs::remove_file(&path);
bytes
}
#[cfg(not(unix))]
{
let _ = version;
b"MZ fixture candidate".to_vec()
}
}
fn sha2_digest(bytes: &[u8]) -> String {
let temp = unique("cc-digest");
std::fs::write(&temp, bytes).unwrap();
let digest = eggup_core::hash_file(&temp).unwrap();
let _ = std::fs::remove_file(&temp);
let mut out = String::with_capacity(64);
for byte in digest {
out.push_str(&format!("{byte:02x}"));
}
out
}
struct Fixture {
_dir: tempfile::TempDir,
live: PathBuf,
}
fn fixture(live_bytes: &[u8]) -> Fixture {
let dir = tempfile::tempdir().unwrap();
let install_dir = dir.path().join("bin");
std::fs::create_dir_all(&install_dir).unwrap();
let live = install_dir.join(if cfg!(windows) {
"cargo-cleanme.exe"
} else {
"cargo-cleanme"
});
std::fs::write(&live, live_bytes).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&live, std::fs::Permissions::from_mode(0o755)).unwrap();
}
Fixture { _dir: dir, live }
}
fn live_stub() -> Vec<u8> {
if cfg!(unix) {
b"#!/bin/sh\necho 'cargo-cleanme 0.0.1'\n".to_vec()
} else {
b"MZ live".to_vec()
}
}
fn release(
environment: FixtureEnvironment,
to: &str,
candidate: Vec<u8>,
sidecar_for: Option<&str>,
) -> FixtureEnvironment {
let tag = format!("v{to}");
let asset = asset_for_target(host_target().unwrap()).unwrap();
let digest = sha2_digest(&candidate);
let sidecar_name = sidecar_for.unwrap_or(asset);
let registry = environment.registry(to).into_bytes();
environment
.respond(&crates_io_metadata_url(), registry)
.respond(
&FixtureEnvironment::asset_url(&tag, &format!("{asset}.sha256")),
format!("{digest} {sidecar_name}\n").into_bytes(),
)
.respond(
&FixtureEnvironment::asset_url(&tag, asset),
candidate.clone(),
)
}
#[test]
fn version_authority_accepts_only_plain_releases() {
assert!(is_release_version("0.1.0"));
assert!(is_release_version("10.20.30"));
for rejected in [
"1.2",
"1.2.3.4",
"1.2.3-rc.1",
"1.2.3+build",
"v1.2.3",
"1.2.x",
"",
] {
assert!(
!is_release_version(rejected),
"{rejected} should be rejected"
);
}
}
#[test]
fn version_authority_reads_exactly_one_field() {
let good = published_stable_version(br#"{"crate":{"max_stable_version":"1.4.2"}}"#)
.expect("plain release accepted");
assert_eq!(good, "1.4.2");
}
#[test]
fn version_authority_rejects_prerelease_and_junk() {
for junk in [
&br#"{"crate":{"max_stable_version":"1.4.2-rc.1"}}"#[..],
&br#"{"crate":{"newest_version":"1.4.2"}}"#[..],
&br#"{"crate":{}}"#[..],
&b"not json"[..],
&b""[..],
] {
assert!(
published_stable_version(junk).is_err(),
"{:?} should be rejected",
String::from_utf8_lossy(junk)
);
}
}
#[test]
fn the_release_tag_is_constructed_not_scraped() {
let metadata = br#"{"crate":{"max_stable_version":"2.0.0"},"evil":{"tag":"../../etc"}}"#;
let plan = FixtureEnvironment::new(PathBuf::from("/nonexistent"), "0.1.0")
.respond(&crates_io_metadata_url(), metadata.to_vec());
let environment = release(plan, "2.0.0", candidate_bytes("2.0.0"), None);
let plan = run(&environment, true).expect("dry run resolves");
assert_eq!(plan.tag, "v2.0.0");
assert_eq!(plan.to_version, "2.0.0");
}
#[test]
fn already_current_is_not_an_error_to_hide() {
let base = FixtureEnvironment::new(PathBuf::from("/nonexistent"), "1.0.0");
let environment = release(base, "1.0.0", candidate_bytes("1.0.0"), None);
match run(&environment, true) {
Err(UpdateError::AlreadyCurrent { current, published }) => {
assert_eq!(current, "1.0.0");
assert_eq!(published, "1.0.0");
}
other => panic!("expected AlreadyCurrent, got {other:?}"),
}
}
#[test]
fn a_registry_outage_is_reported_not_guessed() {
let base = FixtureEnvironment::new(PathBuf::from("/nonexistent"), "0.1.0")
.fail_transport(&crates_io_metadata_url());
let error = run(&base, true).expect_err("transport failure must not resolve");
assert!(
matches!(error, UpdateError::Acquisition { .. }),
"{error:?}"
);
}
fn real_crates_toml(package: &str, version: &str, executables: &[&str]) -> String {
let names = executables
.iter()
.map(|name| format!("\"{name}\""))
.collect::<Vec<_>>()
.join(", ");
format!(
"[v1]\n\"{package} {version} \
(registry+https://github.com/rust-lang/crates.io-index)\" = [{names}]\n"
)
}
fn cargo_root_install(dir: &Path, version: &str) -> PathBuf {
let bin = dir.join("bin");
std::fs::create_dir_all(&bin).unwrap();
let live = bin.join(PRODUCT);
std::fs::write(&live, live_stub()).unwrap();
std::fs::write(
dir.join(".crates.toml"),
real_crates_toml(PRODUCT, version, &[PRODUCT]),
)
.unwrap();
live
}
#[test]
fn the_crates_toml_we_parse_is_the_one_cargo_writes() {
let captured = "[v1]\n\"cargo-cleanme 0.1.3 \
(registry+https://github.com/rust-lang/crates.io-index)\" = [\"cargo-cleanme\"]\n";
assert_eq!(
real_crates_toml(PRODUCT, "0.1.3", &[PRODUCT]),
captured,
"our fixture drifted from the bytes cargo writes"
);
let dir = tempfile::tempdir().unwrap();
let live = cargo_root_install(dir.path(), "0.1.3");
assert_eq!(
read_cargo_record(dir.path(), PRODUCT, PRODUCT),
CargoRecord::Recorded {
version: "0.1.3".to_owned()
}
);
assert!(matches!(
classify_provenance_in(&live, None),
Provenance::CargoManaged { .. }
));
}
#[test]
fn a_cargo_root_install_is_refused_even_when_it_is_not_the_cargo_home() {
let dir = tempfile::tempdir().unwrap();
let live = cargo_root_install(dir.path(), "0.1.3");
let elsewhere = tempfile::tempdir().unwrap();
let provenance = classify_provenance_in(&live, Some(elsewhere.path().to_path_buf()));
assert!(
matches!(provenance, Provenance::CargoManaged { .. }),
"a --root installation was not recognised as Cargo-managed: {provenance:?}"
);
assert_eq!(
provenance.remediation().as_deref(),
Some("cargo install cargo-cleanme --locked --force"),
"the manager command is the only correct answer for a Cargo-owned file"
);
}
#[test]
fn cargo_managed_installation_is_refused_with_the_manager_command() {
let dir = tempfile::tempdir().unwrap();
let cargo_home = dir.path().to_path_buf();
let bin = cargo_home.join("bin");
std::fs::create_dir_all(&bin).unwrap();
let live = bin.join("cargo-cleanme");
std::fs::write(&live, live_stub()).unwrap();
std::fs::write(
cargo_home.join(".crates.toml"),
real_crates_toml(PRODUCT, "0.1.0", &[PRODUCT]),
)
.unwrap();
let provenance = classify_provenance_in(&live, Some(cargo_home.clone()));
assert!(
matches!(provenance, Provenance::CargoManaged { .. }),
"{provenance:?}"
);
assert_eq!(
provenance.remediation().as_deref(),
Some("cargo install cargo-cleanme --locked --force")
);
let environment = FixtureEnvironment::new(live, "0.1.0").cargo_home(cargo_home.clone());
let environment = release(environment, "9.9.9", candidate_bytes("9.9.9"), None);
let error = run(&environment, false).expect_err("cargo-managed must be refused");
assert!(matches!(error, UpdateError::Provenance { .. }), "{error:?}");
let requested = environment.requested.borrow();
assert!(
requested.iter().all(|url| url == &crates_io_metadata_url()),
"a refused run fetched release bytes: {requested:?}"
);
}
#[test]
fn an_unrecorded_file_in_a_cargo_root_is_not_ours_to_replace() {
let dir = tempfile::tempdir().unwrap();
let cargo_home = dir.path().to_path_buf();
let bin = cargo_home.join("bin");
std::fs::create_dir_all(&bin).unwrap();
let live = bin.join("cargo-cleanme");
std::fs::write(&live, live_stub()).unwrap();
std::fs::write(
cargo_home.join(".crates.toml"),
real_crates_toml("some-other-tool", "3.0.0", &["sot"]),
)
.unwrap();
let outcome = classify_provenance_in(&live, Some(cargo_home.clone()));
match outcome {
Provenance::UnprovableOwnership { detail } => {
assert!(detail.contains("does not name this package"), "{detail}");
}
other => panic!("expected UnprovableOwnership, got {other:?}"),
}
}
fn broken_cargo_root(dir: &Path, record: Option<&str>) -> PathBuf {
let bin = dir.join("bin");
std::fs::create_dir_all(&bin).unwrap();
let live = bin.join(PRODUCT);
std::fs::write(&live, live_stub()).unwrap();
match record {
Some(text) => std::fs::write(dir.join(".crates.toml"), text).unwrap(),
None => {
let _ = std::fs::remove_file(dir.join(".crates.toml"));
}
}
live
}
fn assert_not_self_managed(provenance: &Provenance, context: &str) {
assert!(
!matches!(provenance, Provenance::VerifiableSelfManaged { .. }),
"{context} was classified self-managed, which authorizes replacing a file whose \
ownership was never proven: {provenance:?}"
);
}
#[test]
fn unreadable_cargo_metadata_can_never_become_self_managed() {
let dir = tempfile::tempdir().unwrap();
let live = broken_cargo_root(dir.path(), Some("this is not = valid = toml [[[\n"));
let provenance = classify_provenance_in(&live, Some(dir.path().to_path_buf()));
assert_not_self_managed(&provenance, "malformed Cargo metadata in a Cargo home");
assert!(
matches!(provenance, Provenance::UnprovableOwnership { .. }),
"expected UnprovableOwnership, got {provenance:?}"
);
}
#[test]
fn a_malformed_cargo_cleanme_record_is_not_skipped_into_self_managed() {
let dir = tempfile::tempdir().unwrap();
let live = broken_cargo_root(
dir.path(),
Some("[v1]\n\"cargo-cleanme 0.1.3 (registry+https://example.invalid)\" = 7\n"),
);
let provenance = classify_provenance_in(&live, Some(dir.path().to_path_buf()));
assert_not_self_managed(
&provenance,
"a malformed cargo-cleanme record in a Cargo home",
);
}
#[test]
fn an_unrelated_malformed_entry_does_not_hide_a_valid_record() {
let dir = tempfile::tempdir().unwrap();
let live = broken_cargo_root(
dir.path(),
Some(
"[v1]\n\
\"broken-tool (registry+https://example.invalid)\" = 7\n\
\"cargo-cleanme 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)\" \
= [\"cargo-cleanme\"]\n",
),
);
let provenance = classify_provenance_in(&live, Some(dir.path().to_path_buf()));
assert!(
matches!(&provenance, Provenance::CargoManaged { version, .. } if version == "0.1.3"),
"a valid record after an unrelated broken entry was not found: {provenance:?}"
);
}
#[test]
fn a_cargo_record_in_an_unsupported_shape_is_uncertain_not_absent() {
let dir = tempfile::tempdir().unwrap();
let live = broken_cargo_root(dir.path(), Some("[v2]\n\"anything\" = []\n"));
let provenance = classify_provenance_in(&live, Some(dir.path().to_path_buf()));
assert_not_self_managed(&provenance, "a .crates.toml in an unsupported shape");
}
#[test]
fn an_explicit_cargo_home_bin_with_a_missing_record_is_unprovable() {
let dir = tempfile::tempdir().unwrap();
let live = broken_cargo_root(dir.path(), None);
let provenance = classify_provenance_in(&live, Some(dir.path().to_path_buf()));
assert_not_self_managed(&provenance, "a Cargo home bin with no record file");
match provenance {
Provenance::UnprovableOwnership { detail } => {
assert!(detail.contains("no record file"), "{detail}");
}
other => panic!("expected UnprovableOwnership, got {other:?}"),
}
}
#[test]
fn an_ancestor_cargo_root_with_unreadable_metadata_is_unprovable() {
let dir = tempfile::tempdir().unwrap();
let live = broken_cargo_root(dir.path(), Some("[[[ not toml at all\n"));
let provenance = classify_provenance_in(&live, None);
assert_not_self_managed(&provenance, "a --root install with unreadable metadata");
assert!(
matches!(provenance, Provenance::UnprovableOwnership { .. }),
"expected UnprovableOwnership, got {provenance:?}"
);
}
#[test]
fn a_non_utf8_executable_name_in_a_cargo_root_is_unprovable() {
#[cfg(target_os = "linux")]
{
use std::os::unix::ffi::OsStrExt;
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join("bin");
std::fs::create_dir_all(&bin).unwrap();
let live = bin.join(std::ffi::OsStr::from_bytes(b"cargo-cleanme-\xff"));
std::fs::write(&live, live_stub()).unwrap();
std::fs::write(
dir.path().join(".crates.toml"),
real_crates_toml(PRODUCT, "0.1.3", &["cargo-cleanme"]),
)
.unwrap();
let provenance = classify_provenance_in(&live, Some(dir.path().to_path_buf()));
assert_not_self_managed(
&provenance,
"a non-UTF-8 executable name inside a Cargo root",
);
}
}
#[test]
fn a_non_utf8_executable_name_under_an_ancestor_cargo_root_is_unprovable() {
#[cfg(target_os = "linux")]
{
use std::os::unix::ffi::OsStrExt;
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join("bin");
std::fs::create_dir_all(&bin).unwrap();
let live = bin.join(std::ffi::OsStr::from_bytes(b"cargo-cleanme-\xff"));
std::fs::write(&live, live_stub()).unwrap();
std::fs::write(
dir.path().join(".crates.toml"),
real_crates_toml(PRODUCT, "0.1.3", &["cargo-cleanme"]),
)
.unwrap();
let provenance = classify_provenance_in(&live, None);
assert_not_self_managed(
&provenance,
"a non-UTF-8 executable name under an ancestor Cargo root",
);
assert!(
matches!(provenance, Provenance::UnprovableOwnership { .. }),
"expected UnprovableOwnership, got {provenance:?}"
);
}
}
#[test]
fn a_symlinked_executable_is_unprovable_not_self_managed() {
#[cfg(unix)]
{
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join("local/bin");
std::fs::create_dir_all(&bin).unwrap();
let real = bin.join(PRODUCT);
std::fs::write(&real, live_stub()).unwrap();
let link = bin.join(format!("{PRODUCT}-link"));
symlink(&real, &link).unwrap();
let provenance = classify_provenance_in(&link, None);
assert_not_self_managed(&provenance, "a symlinked executable");
assert!(
matches!(provenance, Provenance::UnprovableOwnership { .. }),
"expected UnprovableOwnership, got {provenance:?}"
);
}
}
#[test]
fn a_genuinely_self_managed_installer_layout_stays_self_managed() {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join("local/bin");
std::fs::create_dir_all(&bin).unwrap();
let live = bin.join(PRODUCT);
std::fs::write(&live, live_stub()).unwrap();
let provenance = classify_provenance_in(&live, None);
assert!(
matches!(provenance, Provenance::VerifiableSelfManaged { .. }),
"an installer layout with no Cargo evidence became {provenance:?}"
);
}
#[test]
fn the_cargo_root_search_cannot_miss_a_supported_layout() {
for nesting in 0..=CARGO_ROOT_SEARCH_DEPTH {
let dir = tempfile::tempdir().unwrap();
let mut root = dir.path().to_path_buf();
for level in 0..nesting {
root = root.join(format!("nest-{level}"));
}
std::fs::create_dir_all(&root).unwrap();
let live = cargo_root_install(&root, "0.1.3");
let roots = cargo_roots_above(&live);
assert!(
roots.contains(&root),
"a Cargo root {nesting} level(s) above the executable was missed: {root:?}"
);
assert_eq!(
roots.first().map(|r| r.as_path()),
live.parent().and_then(Path::parent),
"the nearest candidate root is not the executable's parent"
);
}
let deep = tempfile::tempdir().unwrap();
let mut deep_root = deep.path().to_path_buf();
for level in 0..24 {
deep_root = deep_root.join(format!("deep-{level}"));
}
let deep_live = cargo_root_install(&deep_root, "0.1.3");
let count = cargo_roots_above(&deep_live).len();
assert!(
count <= CARGO_ROOT_SEARCH_DEPTH + 1,
"24 levels of nesting produced {count} candidate roots, above the {CARGO_ROOT_SEARCH_DEPTH} bound"
);
}
#[test]
fn a_mutating_run_on_forbidden_provenance_makes_zero_registry_requests() {
for (label, record) in [
("malformed record", Some("[[[ not toml\n")),
("missing record", None),
] {
let dir = tempfile::tempdir().unwrap();
let live = broken_cargo_root(dir.path(), record);
let environment =
FixtureEnvironment::new(live.clone(), "0.1.0").cargo_home(dir.path().to_path_buf());
let environment = release(environment, "9.9.9", candidate_bytes("9.9.9"), None);
let error = run(&environment, false).expect_err("must refuse before the registry");
assert!(
matches!(error, UpdateError::Provenance { .. }),
"{label}: {error:?}"
);
let requested = environment.requested.borrow();
assert!(
requested.is_empty(),
"{label}: a refused run still contacted {requested:?}"
);
assert_eq!(
std::fs::read(&live).unwrap(),
live_stub(),
"{label}: a refused run modified the live executable"
);
}
}
#[test]
fn a_dry_run_still_reports_a_candidate_and_names_the_real_provenance() {
let dir = tempfile::tempdir().unwrap();
let live = broken_cargo_root(dir.path(), Some("[[[ not toml\n"));
let environment =
FixtureEnvironment::new(live.clone(), "0.1.0").cargo_home(dir.path().to_path_buf());
let environment = release(environment, "9.9.9", candidate_bytes("9.9.9"), None);
let plan = run(&environment, true).expect("a dry run still resolves a candidate");
assert_eq!(plan.to_version, "9.9.9");
assert!(
matches!(plan.provenance, Provenance::UnprovableOwnership { .. }),
"the dry run hid the provenance a real run would refuse on: {:?}",
plan.provenance
);
let requested = environment.requested.borrow();
assert!(
!requested.is_empty(),
"a dry run is expected to consult the version authority"
);
assert_eq!(
std::fs::read(&live).unwrap(),
live_stub(),
"a dry run wrote to the live executable"
);
}
#[test]
fn a_recorded_cargo_root_beyond_the_cargo_home_is_still_refused_before_the_registry() {
let dir = tempfile::tempdir().unwrap();
let live = cargo_root_install(dir.path(), "0.1.3");
let elsewhere = tempfile::tempdir().unwrap();
let environment =
FixtureEnvironment::new(live, "0.1.3").cargo_home(elsewhere.path().to_path_buf());
let environment = release(environment, "9.9.9", candidate_bytes("9.9.9"), None);
let error = run(&environment, false).expect_err("a Cargo root must be refused");
match error {
UpdateError::Provenance {
provenance: Provenance::CargoManaged { version, .. },
} => assert_eq!(version, "0.1.3"),
other => panic!("expected CargoManaged, got {other:?}"),
}
let requested = environment.requested.borrow();
assert!(
requested.is_empty(),
"the refused --root install still contacted {requested:?}"
);
}
#[test]
fn the_published_installer_layout_is_not_mistaken_for_a_cargo_root() {
let home = tempfile::tempdir().unwrap();
let bin = home.path().join(".local").join("bin");
std::fs::create_dir_all(&bin).unwrap();
let live = bin.join(PRODUCT);
std::fs::write(&live, live_stub()).unwrap();
std::fs::write(
home.path().join(".crates.toml"),
real_crates_toml("some-other-tool", "1.0.0", &[PRODUCT]),
)
.unwrap();
assert!(
matches!(
classify_provenance_in(&live, None),
Provenance::VerifiableSelfManaged { .. }
),
"an installer placement was wrongly claimed by a neighbouring Cargo record"
);
}
#[test]
fn a_cargo_record_that_omits_this_binary_does_not_claim_this_file() {
let dir = tempfile::tempdir().unwrap();
let bin = dir.path().join("bin");
std::fs::create_dir_all(&bin).unwrap();
let live = bin.join(PRODUCT);
std::fs::write(&live, live_stub()).unwrap();
std::fs::write(
dir.path().join(".crates.toml"),
real_crates_toml(PRODUCT, "0.1.3", &["cargo-cleanme-elsewhere"]),
)
.unwrap();
assert!(
!matches!(
classify_provenance_in(&live, None),
Provenance::CargoManaged { .. }
),
"a record for a different binary was used to claim this one"
);
}
#[test]
fn a_malformed_crates_toml_entry_does_not_hide_the_entry_after_it() {
let dir = tempfile::tempdir().unwrap();
let live = {
let bin = dir.path().join("bin");
std::fs::create_dir_all(&bin).unwrap();
let live = bin.join(PRODUCT);
std::fs::write(&live, live_stub()).unwrap();
live
};
let malformed = format!("\"{PRODUCT}\" = [\"{PRODUCT}\"]\n");
let record = real_crates_toml(PRODUCT, "0.1.3", &[PRODUCT]);
assert!(record.starts_with("[v1]\n"), "fixture shape changed");
let spliced = record.replacen("[v1]\n", &format!("[v1]\n{malformed}"), 1);
std::fs::write(dir.path().join(".crates.toml"), spliced).unwrap();
assert!(
matches!(
classify_provenance_in(&live, None),
Provenance::CargoManaged { .. }
),
"an unparseable leading entry hid the real record"
);
}
#[test]
fn a_self_managed_installation_is_proven_by_its_digest() {
let fx = fixture(&live_stub());
let expected = eggup_core::hash_file(&fx.live).unwrap();
match classify_provenance(&fx.live) {
Provenance::VerifiableSelfManaged { digest } => assert_eq!(digest, expected),
other => panic!("expected VerifiableSelfManaged, got {other:?}"),
}
}
#[test]
fn ownership_is_never_inferred_from_the_file_name() {
let dir = tempfile::tempdir().unwrap();
let fake = dir.path().join("bin").join("cargo-cleanme");
std::fs::create_dir_all(fake.parent().unwrap()).unwrap();
std::fs::create_dir(&fake).unwrap();
assert!(matches!(
classify_provenance(&fake),
Provenance::UnprovableOwnership { .. }
));
}
#[cfg(unix)]
#[test]
fn a_verified_candidate_replaces_the_live_binary() {
let fx = fixture(&live_stub());
let candidate = candidate_bytes("0.2.0");
let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
let environment = release(base, "0.2.0", candidate.clone(), None);
let plan = run(&environment, false).expect("update commits");
assert_eq!(plan.to_version, "0.2.0");
assert_eq!(std::fs::read(&fx.live).unwrap(), candidate);
}
#[cfg(unix)]
#[test]
fn a_checksum_mismatch_leaves_the_live_binary_untouched() {
let fx = fixture(&live_stub());
let before = std::fs::read(&fx.live).unwrap();
let asset = asset_for_target(host_target().unwrap()).unwrap();
let tag = "v0.2.0";
let environment = FixtureEnvironment::new(fx.live.clone(), "0.1.0")
.respond(
&crates_io_metadata_url(),
br#"{"crate":{"max_stable_version":"0.2.0"}}"#.to_vec(),
)
.respond(
&FixtureEnvironment::asset_url(tag, &format!("{asset}.sha256")),
format!("{} {asset}\n", "0".repeat(64)).into_bytes(),
)
.respond(
&FixtureEnvironment::asset_url(tag, asset),
candidate_bytes("0.2.0"),
);
let error = run(&environment, false).expect_err("mismatch must fail");
assert!(
matches!(error, UpdateError::Transaction { .. }),
"{error:?}"
);
assert_eq!(std::fs::read(&fx.live).unwrap(), before);
}
#[cfg(unix)]
#[test]
fn a_candidate_reporting_the_wrong_version_is_rejected_before_commit() {
let fx = fixture(&live_stub());
let before = std::fs::read(&fx.live).unwrap();
let lying = candidate_bytes("6.6.6");
let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
let environment = release(base, "0.2.0", lying.clone(), None);
let error = run(&environment, false).expect_err("wrong identity must fail");
let text = error.to_string();
assert!(text.contains("0.2.0"), "{text}");
assert_eq!(std::fs::read(&fx.live).unwrap(), before);
}
#[cfg(unix)]
#[test]
fn a_sidecar_naming_a_different_asset_is_rejected() {
let fx = fixture(&live_stub());
let before = std::fs::read(&fx.live).unwrap();
let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
let environment = release(
base,
"0.2.0",
candidate_bytes("0.2.0"),
Some("cargo-cleanme-some-other-target"),
);
let error = run(&environment, false).expect_err("mismatched sidecar must fail");
assert!(
matches!(error, UpdateError::ReleaseEvidence { .. }),
"{error:?}"
);
assert_eq!(std::fs::read(&fx.live).unwrap(), before);
}
#[cfg(unix)]
#[test]
fn an_absent_release_asset_is_not_replaced_with_anything() {
let fx = fixture(&live_stub());
let before = std::fs::read(&fx.live).unwrap();
let asset = asset_for_target(host_target().unwrap()).unwrap();
let environment = FixtureEnvironment::new(fx.live.clone(), "0.1.0")
.respond(
&crates_io_metadata_url(),
br#"{"crate":{"max_stable_version":"0.2.0"}}"#.to_vec(),
)
.respond(
&FixtureEnvironment::asset_url("v0.2.0", &format!("{asset}.sha256")),
format!("{} {asset}\n", sha2_digest(&candidate_bytes("0.2.0"))).into_bytes(),
)
.absent(&FixtureEnvironment::asset_url("v0.2.0", asset));
let error = run(&environment, false).expect_err("absent asset must fail");
assert!(
matches!(error, UpdateError::ReleaseEvidence { .. }),
"{error:?}"
);
assert_eq!(std::fs::read(&fx.live).unwrap(), before);
}
#[cfg_attr(not(unix), allow(dead_code))]
fn process_wide_staging_paths() -> Vec<PathBuf> {
let mut found = Vec::new();
if let Ok(entries) = std::fs::read_dir(std::env::temp_dir()) {
for entry in entries.flatten() {
let name = entry.file_name();
let name = name.to_string_lossy();
if name.starts_with("cargo-cleanme-update-test-") {
found.push(entry.path());
}
}
}
found
}
#[cfg(unix)]
#[test]
fn staging_is_cleaned_up_on_success_and_on_failure() {
let fx = fixture(&live_stub());
let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
let environment = release(base, "0.2.0", candidate_bytes("6.6.6"), None);
let _ = run(&environment, false);
environment.assert_no_staging_leak("failed transaction");
let fx = fixture(&live_stub());
let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
let environment = release(base, "0.2.0", candidate_bytes("0.2.0"), None);
run(&environment, false).expect("update commits");
environment.assert_no_staging_leak("successful transaction");
}
#[cfg(unix)]
#[test]
fn a_staging_cleanup_failure_is_reported_not_swallowed() {
let fx = fixture(&live_stub());
let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
let environment = release(base, "0.2.0", candidate_bytes("0.2.0"), None)
.failing_cleanup("Directory not empty");
let error = run(&environment, false)
.expect_err("a transaction that could not clean up must not report success");
assert!(
environment.cleanup_calls() > 0,
"premise: production must have reached the cleanup callback, \
otherwise this case proves nothing about a failed cleanup"
);
let UpdateError::Transaction { detail } = &error else {
panic!("expected a transaction error, got {error:?}");
};
assert!(
detail.contains("staging directory") && detail.contains("Directory not empty"),
"the failure must name the directory and the reason it survived: {detail}"
);
assert!(
detail.contains(
&environment.created_staging.borrow()[0]
.display()
.to_string()
),
"the failure must name the directory it could not remove: {detail}"
);
assert_eq!(
std::fs::read(&fx.live).unwrap(),
candidate_bytes("0.2.0"),
"the commit is the more important fact and still happened"
);
for path in environment.leaked_staging() {
let _ = std::fs::remove_dir_all(path);
}
}
#[test]
fn a_deliberately_leaked_staging_path_is_still_reported() {
let fx = fixture(&live_stub());
let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
let environment = release(base, "0.2.0", candidate_bytes("6.6.6"), None).leaking_staging();
let _ = run(&environment, false);
assert!(
environment.cleanup_calls() > 0,
"premise: production must still have reached the cleanup callback, \
otherwise this case proves nothing about a leaked path"
);
let leaked = environment.leaked_staging();
assert_eq!(
leaked,
environment.created_staging.borrow().clone(),
"the leak check must report exactly the paths this fixture created"
);
for path in leaked {
let _ = std::fs::remove_dir_all(path);
}
}
#[cfg(unix)]
#[test]
fn a_foreign_staging_directory_is_not_evidence_of_a_leak() {
let foreign = unique("cargo-cleanme-update-test");
std::fs::create_dir_all(&foreign).unwrap();
assert!(
process_wide_staging_paths().contains(&foreign),
"premise: the historical process-wide scan must see the foreign \
directory, or this case proves nothing about the old detector"
);
let fx = fixture(&live_stub());
let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
let environment = release(base, "0.2.0", candidate_bytes("0.2.0"), None);
run(&environment, false).expect("update commits");
environment.assert_no_staging_leak("subject beside a foreign staging path");
assert!(
process_wide_staging_paths().contains(&foreign),
"premise: the foreign directory must still be live, or the \
concurrency control did not test anything"
);
let _ = std::fs::remove_dir_all(&foreign);
}
#[test]
fn a_dry_run_downloads_nothing() {
let fx = fixture(&live_stub());
let base = FixtureEnvironment::new(fx.live.clone(), "0.1.0");
let environment = release(base, "0.2.0", candidate_bytes("0.2.0"), None);
run(&environment, true).expect("dry run resolves");
let requested = environment.requested.borrow();
assert_eq!(
requested.len(),
1,
"dry run fetched more than metadata: {requested:?}"
);
assert_eq!(requested[0], crates_io_metadata_url());
}
#[test]
fn the_published_target_table_matches_the_eggpack_contract() {
let contract_path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/release/eggpack/distribution.toml"
);
let contract = match std::fs::read_to_string(contract_path) {
Ok(contract) => contract,
Err(error) => {
assert!(
!std::path::Path::new(contract_path).exists(),
"the distribution contract is unreadable: {error}"
);
return;
}
};
for (triple, asset) in PUBLISHED_TARGETS {
assert!(
contract.contains(&format!("triple = \"{triple}\"")),
"{triple} is missing from the contract"
);
let expected = if triple.ends_with("-pc-windows-msvc") {
format!("cargo-cleanme-{triple}.exe")
} else {
format!("cargo-cleanme-{triple}")
};
assert_eq!(
*asset, expected,
"asset name for {triple} is not the contracted expansion"
);
}
assert_eq!(PUBLISHED_TARGETS.len(), 5);
}
#[test]
fn versions_order_numerically_not_lexically() {
use std::cmp::Ordering;
assert_eq!(
compare_release_versions("0.1.10", "0.1.9"),
Some(Ordering::Greater)
);
assert_eq!(
compare_release_versions("0.10.0", "0.9.9"),
Some(Ordering::Greater)
);
assert_eq!(
compare_release_versions("1.0.0", "1.0.0"),
Some(Ordering::Equal)
);
assert_eq!(
compare_release_versions("0.1.0", "0.2.0"),
Some(Ordering::Less)
);
for bad in [("1.2", "1.2.0"), ("1.2.3-rc.1", "1.2.3"), ("x", "1.2.3")] {
assert_eq!(compare_release_versions(bad.0, bad.1), None, "{bad:?}");
}
}
#[test]
fn a_newer_local_build_is_never_downgraded() {
let base = FixtureEnvironment::new(PathBuf::from("/nonexistent"), "0.1.1");
let environment = release(base, "0.1.0", candidate_bytes("0.1.0"), None);
match run(&environment, true) {
Err(UpdateError::NewerThanPublished { current, published }) => {
assert_eq!(current, "0.1.1");
assert_eq!(published, "0.1.0");
}
other => panic!("expected NewerThanPublished, got {other:?}"),
}
}
#[test]
fn an_older_published_version_is_not_offered_to_a_matching_build() {
let base = FixtureEnvironment::new(PathBuf::from("/nonexistent"), "0.1.0");
let environment = release(base, "0.1.0", candidate_bytes("0.1.0"), None);
assert!(matches!(
run(&environment, true),
Err(UpdateError::AlreadyCurrent { .. })
));
}
#[test]
fn the_production_transport_identifies_itself_descriptively() {
let environment =
HttpEnvironment::new().expect("the production transport must be constructible");
let agent = environment.transport.config().user_agent.clone();
assert!(
agent.contains(PRODUCT),
"the update User-Agent must name the product, got {agent:?}"
);
assert!(
!agent.starts_with("curl/") && agent != *"",
"the update User-Agent must not be a generic tool name, got {agent:?}"
);
assert_eq!(agent, USER_AGENT);
assert!(
agent.contains('/') && agent.contains(' '),
"expected a descriptive agent, got {agent:?}"
);
}
#[test]
fn the_version_authority_url_is_https_and_product_scoped() {
let url = crates_io_metadata_url();
assert!(url.starts_with("https://"), "{url}");
assert!(url.ends_with(PRODUCT), "{url}");
}
#[test]
fn release_urls_are_constructed_from_the_tag_and_contracted_asset() {
let asset = asset_for_target(host_target().unwrap()).unwrap();
let url = release_asset_url("v9.9.9", asset);
assert!(url.starts_with("https://github.com/dbowm91/cargo-cleanme/releases/download/"));
assert!(url.ends_with(asset), "{url}");
assert!(!url.contains(".."), "{url}");
}
#[test]
fn the_host_target_has_a_contracted_asset() {
let target = host_target().expect("the CI hosts are all published");
assert!(
asset_for_target(target).is_some(),
"{target} has no contracted asset"
);
}
}