| 1 | //! Self-update for the `codewhale` binary. |
| 2 | //! |
| 3 | //! The `update` subcommand fetches the latest release from |
| 4 | //! `github.com/codewhale-hq/CodeWhale/releases/latest`, downloads the |
| 5 | //! platform-correct binary, verifies its SHA256 checksum, and atomically |
| 6 | //! replaces the currently running binary. |
| 7 | |
| 8 | use std::cmp::Ordering; |
| 9 | use std::collections::HashMap; |
| 10 | #[cfg(target_os = "android")] |
| 11 | use std::ffi::CStr; |
| 12 | #[cfg(any(target_os = "android", all(test, unix)))] |
| 13 | use std::ffi::OsStr; |
| 14 | use std::path::{Path, PathBuf}; |
| 15 | |
| 16 | use anyhow::{Context, Result, anyhow, bail}; |
| 17 | use codewhale_release::install::GITHUB_MIGRATION_HELP; |
| 18 | use codewhale_release::{ |
| 19 | CHECKSUM_MANIFEST_ASSET, InstallMethod, ReleaseChannel, ReleaseQuery, UPDATE_USER_AGENT, |
| 20 | UpdateTransportPolicy, cnb_mirror_override_active, cnb_mirror_supports_target, |
| 21 | cnb_release_base_url, compare_release_versions, is_beta_tag, mirror_asset_url, |
| 22 | parse_checksum_manifest, parse_release_json, read_release_metadata, read_update_response, |
| 23 | redact_url, redact_url_str, resolve_release_query, update_is_needed, |
| 24 | update_network_fallback_hint, update_redirect_policy, |
| 25 | }; |
| 26 | use reqwest::Proxy; |
| 27 | use std::io::Write; |
| 28 | use std::sync::Arc; |
| 29 | use std::time::Duration; |
| 30 | |
| 31 | use crate::hashing::sha256_hex; |
| 32 | use codewhale_release::signing::{self, SIGNATURE_ASSET, SignatureCheck}; |
| 33 | use codewhale_release::{autoupdate, installs}; |
| 34 | |
| 35 | mod compiled_host; |
| 36 | #[cfg(any(unix, windows))] |
| 37 | pub(crate) mod uninstall; |
| 38 | |
| 39 | const GITHUB_LATEST_RELEASE_PAGE_URL: &str = |
| 40 | "https://github.com/codewhale-hq/CodeWhale/releases/latest"; |
| 41 | const GITHUB_RELEASE_DOWNLOAD_BASE_URL: &str = |
| 42 | "https://github.com/codewhale-hq/CodeWhale/releases/download"; |
| 43 | const UPDATE_HTTP_ATTEMPTS: usize = 3; |
| 44 | const UPDATE_HTTP_RETRY_DELAY_MS: u64 = 100; |
| 45 | /// Ceiling for one asset download. Generous, because release binaries are tens |
| 46 | /// of megabytes and some of the networks this exists for are slow. |
| 47 | const UPDATE_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(5 * 60); |
| 48 | /// Ceiling for one checksum-manifest probe. The manifest is a few hundred |
| 49 | /// bytes, so this is only a backstop against a source that accepts the |
| 50 | /// connection and then stalls. GitHub gets the first attempt; an unavailable |
| 51 | /// manifest falls back to the supported mirror without waiting for a binary. |
| 52 | const MANIFEST_PROBE_TIMEOUT: Duration = Duration::from_secs(10); |
| 53 | const STAGED_MANIFEST: &str = "codewhale-artifacts-sha256.txt"; |
| 54 | const STAGED_SIGNATURE: &str = "codewhale-artifacts-sha256.txt.sig"; |
| 55 | #[cfg(target_os = "android")] |
| 56 | const ANDROID_PROC_SELF_MAPS: &str = "/proc/self/maps"; |
| 57 | |
| 58 | #[derive(Debug)] |
| 59 | pub(crate) struct PackageManaged(pub(crate) &'static str); |
| 60 | |
| 61 | impl std::fmt::Display for PackageManaged { |
| 62 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 63 | formatter.write_str(self.0) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | impl std::error::Error for PackageManaged {} |
| 68 | |
| 69 | /// Run the self-update workflow. |
| 70 | /// |
| 71 | /// OpenHarmony (HarmonyOS) won't compile this file, so no need to handle |
| 72 | pub fn run_update(beta: bool, check_only: bool, proxy_arg: Option<String>) -> Result<()> { |
| 73 | let executable_identity = update_executable_identity()?; |
| 74 | let current_exe = executable_identity.path.clone(); |
| 75 | let install_method = InstallMethod::detect(¤t_exe); |
| 76 | let legacy_binary = is_legacy_binary(¤t_exe); |
| 77 | ensure_supported_release_target(std::env::consts::OS, std::env::consts::ARCH)?; |
| 78 | |
| 79 | let plan = update_plan_for_exe(¤t_exe); |
| 80 | let channel = ReleaseChannel::from_beta_flag(beta); |
| 81 | let current_version = env!("CARGO_PKG_VERSION"); |
| 82 | let build_version = env!("CODEWHALE_BUILD_VERSION"); |
| 83 | let unreleased_checkout_build = build_version.ends_with(" (dev)"); |
| 84 | let proxy = proxy_arg |
| 85 | .as_deref() |
| 86 | .map(validate_and_build_proxy) |
| 87 | .transpose()?; |
| 88 | |
| 89 | println!("Checking for {} updates...", channel.label()); |
| 90 | println!("Current binary: {}", current_exe.display()); |
| 91 | println!("Current version: v{build_version}"); |
| 92 | if legacy_binary { |
| 93 | println!(); |
| 94 | println!("{}", legacy_binary_message(¤t_exe)); |
| 95 | } |
| 96 | if !install_method.supports_self_update() { |
| 97 | println!(); |
| 98 | println!("{}", installs::update_answer(install_method, ¤t_exe)); |
| 99 | if !check_only { |
| 100 | return Err(PackageManaged("Not updated: use the command above.").into()); |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | if check_only { |
| 105 | let fetched = fetch_latest_release(channel, proxy.as_ref()) |
| 106 | .with_context(update_network_fallback_hint)?; |
| 107 | let latest_tag = &fetched.release.tag_name; |
| 108 | println!("Latest {} release: {latest_tag}", channel.label()); |
| 109 | let replace_same_version = unreleased_checkout_build |
| 110 | && compare_release_versions(current_version, latest_tag)? == Ordering::Equal; |
| 111 | if update_is_needed(channel, current_version, latest_tag)? || replace_same_version { |
| 112 | if replace_same_version { |
| 113 | println!( |
| 114 | "This build is not a published release ({build_version}); the {latest_tag} release artifact replaces it." |
| 115 | ); |
| 116 | } |
| 117 | if install_method.supports_self_update() { |
| 118 | println!( |
| 119 | "Update available. Run `{} update` to install {latest_tag}.", |
| 120 | current_exe.display() |
| 121 | ); |
| 122 | } else { |
| 123 | println!("Update available: {latest_tag}, through the owner named above."); |
| 124 | } |
| 125 | println!( |
| 126 | "Release source: {}", |
| 127 | describe_release_source_for_check(&fetched, &plan.asset_stem, proxy.as_ref()) |
| 128 | ); |
| 129 | } else { |
| 130 | match compare_release_versions(current_version, latest_tag)? { |
| 131 | Ordering::Greater => { |
| 132 | println!("Current build is newer than the latest published release."); |
| 133 | } |
| 134 | Ordering::Less | Ordering::Equal => { |
| 135 | println!("Already up to date."); |
| 136 | } |
| 137 | } |
| 138 | } |
| 139 | return Ok(()); |
| 140 | } |
| 141 | |
| 142 | // Step 1: Fetch latest release metadata |
| 143 | let fetched = |
| 144 | fetch_latest_release(channel, proxy.as_ref()).with_context(update_network_fallback_hint)?; |
| 145 | let release = &fetched.release; |
| 146 | let latest_tag = &release.tag_name; |
| 147 | println!("Latest {} release: {latest_tag}", channel.label()); |
| 148 | |
| 149 | if fetched.source.is_pinned_mirror() && channel == ReleaseChannel::Beta { |
| 150 | println!( |
| 151 | "Using {}; --beta does not select GitHub beta releases in mirror mode.", |
| 152 | fetched.source.describe() |
| 153 | ); |
| 154 | } |
| 155 | let replace_same_version = unreleased_checkout_build |
| 156 | && compare_release_versions(current_version, latest_tag)? == Ordering::Equal; |
| 157 | if !update_is_needed(channel, current_version, latest_tag)? && !replace_same_version { |
| 158 | if compare_release_versions(current_version, latest_tag)? == Ordering::Greater { |
| 159 | println!( |
| 160 | "Current build is newer than the latest published release; keeping v{current_version}. No downgrade or download performed." |
| 161 | ); |
| 162 | } else { |
| 163 | println!("Already up to date; no download needed."); |
| 164 | } |
| 165 | return Ok(()); |
| 166 | } |
| 167 | if replace_same_version { |
| 168 | println!( |
| 169 | "This build is not a published release ({build_version}); installing the {latest_tag} release artifact over it." |
| 170 | ); |
| 171 | } |
| 172 | |
| 173 | let divergent = divergent_aliases(&plan, &executable_identity); |
| 174 | for target in &plan.target_paths { |
| 175 | if !divergent.contains(target) { |
| 176 | validate_update_target(target, &executable_identity)?; |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | let download = resolve_download_plan( |
| 181 | &fetched, |
| 182 | &plan.asset_stem, |
| 183 | proxy.as_ref(), |
| 184 | compiled_host::required_for(¤t_exe)?, |
| 185 | )?; |
| 186 | println!("Release source: {}", download.source.describe()); |
| 187 | let signature = fetch_signature(&download, latest_tag, proxy.as_ref())?; |
| 188 | |
| 189 | println!("Downloading {}...", download.binary_name); |
| 190 | let bytes = download_pinned_binary(&download, proxy.as_ref())?; |
| 191 | |
| 192 | preflight_downloaded_binary(&download.binary_name, &bytes)?; |
| 193 | |
| 194 | println!( |
| 195 | "SHA256 checksum verified against {CHECKSUM_MANIFEST_ASSET} from {}{}.", |
| 196 | download.source.label(), |
| 197 | if signature.is_verified() { |
| 198 | "; release signature verified" |
| 199 | } else { |
| 200 | "" |
| 201 | } |
| 202 | ); |
| 203 | |
| 204 | let mut host_update = compiled_host::prepare( |
| 205 | &download, |
| 206 | latest_tag, |
| 207 | plan.asset_stem.trim_start_matches("codewhale-"), |
| 208 | ¤t_exe, |
| 209 | proxy.as_ref(), |
| 210 | )?; |
| 211 | let replaced = |
| 212 | replace_command_paths(&executable_identity, &plan, &bytes, &divergent, &mut || { |
| 213 | if let Some(host) = &mut host_update { |
| 214 | host.publish()?; |
| 215 | } |
| 216 | Ok(()) |
| 217 | }); |
| 218 | let kept_previous = match replaced { |
| 219 | Ok(kept) => kept, |
| 220 | Err(error) => { |
| 221 | if let Some(host) = &mut host_update { |
| 222 | host.rollback().context( |
| 223 | "compiled-host rollback failed; retained backup path is reported below", |
| 224 | )?; |
| 225 | } |
| 226 | return Err(error); |
| 227 | } |
| 228 | }; |
| 229 | if let Some(host) = &host_update { |
| 230 | println!( |
| 231 | "Updated the qualified compiled image, notices and relink source beside this CLI; Node remains default." |
| 232 | ); |
| 233 | for path in host.recovery_paths() { |
| 234 | println!("Previous companion bytes retained at {}", path.display()); |
| 235 | } |
| 236 | } |
| 237 | if let Ok(home) = codewhale_config::codewhale_home() { |
| 238 | autoupdate::discard_staged(&home); |
| 239 | autoupdate::record_failure(&home, None); |
| 240 | let mut state = autoupdate::load_state(&home); |
| 241 | if state.skip_version.take().is_some() { |
| 242 | let _ = autoupdate::store_state(&home, &state); |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | println!( |
| 247 | "\n✅ Successfully updated to {latest_tag}!\n\ |
| 248 | Release source: {source}\n\ |
| 249 | Updated binaries:\n{targets}\n\ |
| 250 | \n\ |
| 251 | Restart the application to use the new version.\n\ |
| 252 | What's new: {notes}\n\ |
| 253 | {undo}", |
| 254 | undo = undo_hint(kept_previous, latest_tag), |
| 255 | source = download.source.describe(), |
| 256 | notes = autoupdate::changelog_url(latest_tag), |
| 257 | targets = plan |
| 258 | .target_paths |
| 259 | .iter() |
| 260 | .map(|path| format!(" - {} ({})", path.display(), download.binary_name)) |
| 261 | .collect::<Vec<_>>() |
| 262 | .join("\n") |
| 263 | ); |
| 264 | |
| 265 | Ok(()) |
| 266 | } |
| 267 | |
| 268 | fn fetch_signature( |
| 269 | download: &DownloadPlan, |
| 270 | tag: &str, |
| 271 | proxy: Option<&Proxy>, |
| 272 | ) -> Result<SignatureCheck> { |
| 273 | if signing::trusted_keys().is_empty() { |
| 274 | return Ok(SignatureCheck::NotConfigured); |
| 275 | } |
| 276 | let signature = download_url_with_timeout( |
| 277 | &format!("{}.sig", download.manifest_url), |
| 278 | proxy, |
| 279 | MANIFEST_PROBE_TIMEOUT, |
| 280 | ) |
| 281 | .with_context(|| { |
| 282 | format!( |
| 283 | "{SIGNATURE_ASSET} could not be fetched from {}; this build requires signed releases, so nothing was installed", |
| 284 | download.source.describe() |
| 285 | ) |
| 286 | })?; |
| 287 | match signing::verify_manifest(tag, &download.manifest_bytes, Some(&signature)) { |
| 288 | SignatureCheck::Verified => Ok(SignatureCheck::Verified), |
| 289 | other => bail!( |
| 290 | "{SIGNATURE_ASSET} from {} does not verify for {tag} ({other:?}); nothing was installed", |
| 291 | download.source.describe() |
| 292 | ), |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | fn divergent_aliases(plan: &UpdatePlan, identity: &UpdateExecutableIdentity) -> Vec<PathBuf> { |
| 297 | plan.target_paths |
| 298 | .iter() |
| 299 | .filter(|target| **target != identity.path) |
| 300 | .filter(|target| { |
| 301 | let Ok(meta) = std::fs::symlink_metadata(target) else { |
| 302 | return false; |
| 303 | }; |
| 304 | meta.is_file() |
| 305 | && same_owner(&meta, &identity.path) |
| 306 | && InstallMethod::owner(target).supports_self_update() |
| 307 | && std::fs::read(target).is_ok_and(|bytes| sha256_hex(&bytes) != identity.file_hash) |
| 308 | && installs::is_codewhale_binary(target) |
| 309 | }) |
| 310 | .cloned() |
| 311 | .collect() |
| 312 | } |
| 313 | |
| 314 | #[cfg(unix)] |
| 315 | fn same_owner(meta: &std::fs::Metadata, reference: &Path) -> bool { |
| 316 | use std::os::unix::fs::MetadataExt; |
| 317 | std::fs::metadata(reference).is_ok_and(|reference| reference.uid() == meta.uid()) |
| 318 | } |
| 319 | |
| 320 | #[cfg(not(unix))] |
| 321 | fn same_owner(_meta: &std::fs::Metadata, _reference: &Path) -> bool { |
| 322 | true |
| 323 | } |
| 324 | |
| 325 | fn save_previous(home: &Path, identity: &UpdateExecutableIdentity) -> Result<()> { |
| 326 | let bytes = std::fs::read(&identity.path).context("failed to read the running executable")?; |
| 327 | if sha256_hex(&bytes) != identity.file_hash { |
| 328 | bail!("the running executable changed before it could be kept for rollback"); |
| 329 | } |
| 330 | let dir = autoupdate::previous_dir(home); |
| 331 | installs::write_file_atomically(&dir, &autoupdate::binary_name(), &bytes, true)?; |
| 332 | autoupdate::store_json( |
| 333 | &dir.join("previous.json"), |
| 334 | &autoupdate::PreviousBinary { |
| 335 | version: env!("CARGO_PKG_VERSION").to_string(), |
| 336 | sha256: identity.file_hash.clone(), |
| 337 | }, |
| 338 | ) |
| 339 | } |
| 340 | |
| 341 | fn replace_command_paths( |
| 342 | identity: &UpdateExecutableIdentity, |
| 343 | plan: &UpdatePlan, |
| 344 | bytes: &[u8], |
| 345 | divergent: &[PathBuf], |
| 346 | before_replace: &mut dyn FnMut() -> Result<()>, |
| 347 | ) -> Result<bool> { |
| 348 | let home = codewhale_config::codewhale_home().ok(); |
| 349 | #[cfg(unix)] |
| 350 | let mut command_receipt = uninstall::CommandReceipt::capture(&identity.path)?; |
| 351 | #[cfg(unix)] |
| 352 | let had_receipt = command_receipt.is_some(); |
| 353 | #[cfg(windows)] |
| 354 | let had_receipt = uninstall::CommandReceipt::capture(&identity.path)?.is_some(); |
| 355 | let kept_previous = match &home { |
| 356 | Some(home) => { |
| 357 | save_previous(home, identity) |
| 358 | .context("could not keep the current version for `codewhale update --rollback`; nothing was replaced")?; |
| 359 | true |
| 360 | } |
| 361 | None => false, |
| 362 | }; |
| 363 | if !divergent.is_empty() { |
| 364 | let home = home |
| 365 | .as_deref() |
| 366 | .context("cannot resolve the Codewhale home for the recovery folder")?; |
| 367 | let mut batch = installs::RecoveryBatch::open(home)?; |
| 368 | for path in divergent { |
| 369 | validate_primary_update_identity(identity)?; |
| 370 | let moved = batch.move_in(path)?; |
| 371 | println!( |
| 372 | "Bringing {} in line with this release; the old copy is kept in {} for {} days. Undo: {}", |
| 373 | path.display(), |
| 374 | batch.dir.display(), |
| 375 | installs::RECOVERY_RETENTION_DAYS, |
| 376 | moved.undo_command() |
| 377 | ); |
| 378 | } |
| 379 | batch.finish(); |
| 380 | } |
| 381 | let replaced = (|| { |
| 382 | validate_primary_update_identity(identity)?; |
| 383 | before_replace()?; |
| 384 | replace_verified_downloads(&plan.target_paths, bytes, |target| { |
| 385 | validate_primary_update_identity(identity)?; |
| 386 | validate_update_target(target, identity) |
| 387 | }) |
| 388 | })(); |
| 389 | #[cfg(unix)] |
| 390 | let receipt_renewal = command_receipt |
| 391 | .as_mut() |
| 392 | .map(|receipt| receipt.renew(bytes)) |
| 393 | .transpose(); |
| 394 | #[cfg(windows)] |
| 395 | let receipt_renewal = if had_receipt { |
| 396 | uninstall::CommandReceipt::capture_accepting(&identity.path, Some(&sha256_hex(bytes))) |
| 397 | .and_then(|receipt| { |
| 398 | receipt |
| 399 | .context("command ownership receipt disappeared during update")? |
| 400 | .renew(bytes) |
| 401 | }) |
| 402 | .map(Some) |
| 403 | } else { |
| 404 | Ok(None) |
| 405 | }; |
| 406 | if let Err(error) = replaced { |
| 407 | #[cfg(any(unix, windows))] |
| 408 | if let Err(renewal) = receipt_renewal { |
| 409 | return Err(error.context(format!( |
| 410 | "command ownership receipt could not be renewed after partial update: {renewal:#}" |
| 411 | ))); |
| 412 | } |
| 413 | return Err(error); |
| 414 | } |
| 415 | #[cfg(any(unix, windows))] |
| 416 | receipt_renewal.context("binaries updated, but command ownership receipt renewal failed; preserved receipt/recovery paths require attention")?; |
| 417 | #[cfg(any(unix, windows))] |
| 418 | if !had_receipt { |
| 419 | adopt_receipt_for(&identity.path, bytes); |
| 420 | } |
| 421 | Ok(kept_previous) |
| 422 | } |
| 423 | |
| 424 | #[cfg(any(unix, windows))] |
| 425 | fn adopt_receipt_for(executable: &Path, bytes: &[u8]) { |
| 426 | let Some(directory) = executable.parent() else { |
| 427 | return; |
| 428 | }; |
| 429 | let directory = directory |
| 430 | .canonicalize() |
| 431 | .unwrap_or_else(|_| directory.to_path_buf()); |
| 432 | let digest = sha256_hex(bytes); |
| 433 | let entries: Vec<(String, String)> = uninstall::COMMANDS |
| 434 | .iter() |
| 435 | .filter(|name| { |
| 436 | installs::file_sha256(&directory.join(name)).is_ok_and(|hash| hash == digest) |
| 437 | }) |
| 438 | .map(|name| ((*name).to_string(), digest.clone())) |
| 439 | .collect(); |
| 440 | if entries.is_empty() { |
| 441 | return; |
| 442 | } |
| 443 | match installs::adopt_receipt(&directory, &entries) { |
| 444 | Ok(true) => println!( |
| 445 | "Recorded an install receipt in {}; `codewhale uninstall` can now remove this copy.", |
| 446 | directory.display() |
| 447 | ), |
| 448 | Ok(false) => {} |
| 449 | Err(error) => println!("Could not record an install receipt: {error:#}"), |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | pub fn run_stage(beta: bool, proxy_arg: Option<String>) -> Result<()> { |
| 454 | let result = stage_release(beta, proxy_arg); |
| 455 | if let Ok(home) = codewhale_config::codewhale_home() { |
| 456 | autoupdate::record_failure( |
| 457 | &home, |
| 458 | result |
| 459 | .as_ref() |
| 460 | .err() |
| 461 | .map(|error| format!("the background download failed: {error:#}")), |
| 462 | ); |
| 463 | } |
| 464 | result |
| 465 | } |
| 466 | |
| 467 | fn stage_release(beta: bool, proxy_arg: Option<String>) -> Result<()> { |
| 468 | let identity = update_executable_identity()?; |
| 469 | let exe = identity.path.clone(); |
| 470 | if !InstallMethod::detect(&exe).supports_self_update() { |
| 471 | bail!("This copy is not a release-binary install; nothing was staged."); |
| 472 | } |
| 473 | if compiled_host::required_for(&exe)? { |
| 474 | bail!( |
| 475 | "Background updates skip installs with the optional compiled host; run `codewhale update`." |
| 476 | ); |
| 477 | } |
| 478 | ensure_supported_release_target(std::env::consts::OS, std::env::consts::ARCH)?; |
| 479 | let home = codewhale_config::codewhale_home()?; |
| 480 | let mut state = autoupdate::load_state(&home); |
| 481 | state.last_stage_attempt_unix = codewhale_release::check::now_unix(); |
| 482 | let _ = autoupdate::store_state(&home, &state); |
| 483 | let channel = ReleaseChannel::from_beta_flag(beta); |
| 484 | let proxy = proxy_arg |
| 485 | .as_deref() |
| 486 | .map(validate_and_build_proxy) |
| 487 | .transpose()?; |
| 488 | let fetched = |
| 489 | fetch_latest_release(channel, proxy.as_ref()).with_context(update_network_fallback_hint)?; |
| 490 | let tag = fetched.release.tag_name.clone(); |
| 491 | let version = tag.trim_start_matches('v').to_string(); |
| 492 | state.last_stage_version = Some(version.clone()); |
| 493 | let _ = autoupdate::store_state(&home, &state); |
| 494 | if !update_is_needed(channel, env!("CARGO_PKG_VERSION"), &tag)? { |
| 495 | autoupdate::discard_staged(&home); |
| 496 | println!("Already up to date; nothing staged."); |
| 497 | return Ok(()); |
| 498 | } |
| 499 | if state.skip_version.as_deref() == Some(version.as_str()) { |
| 500 | println!("v{version} was rolled back on this machine; it is not staged again."); |
| 501 | return Ok(()); |
| 502 | } |
| 503 | if let Some(staged) = autoupdate::load_staged(&home) |
| 504 | && staged.version == version |
| 505 | && installs::file_sha256(&autoupdate::staged_dir(&home).join(autoupdate::binary_name())) |
| 506 | .is_ok_and(|hash| hash == staged.sha256) |
| 507 | { |
| 508 | println!("v{version} is already staged."); |
| 509 | return Ok(()); |
| 510 | } |
| 511 | let plan = update_plan_for_exe(&exe); |
| 512 | let download = resolve_download_plan(&fetched, &plan.asset_stem, proxy.as_ref(), false)?; |
| 513 | let signature = fetch_signature(&download, &tag, proxy.as_ref())?; |
| 514 | let bytes = download_pinned_binary(&download, proxy.as_ref())?; |
| 515 | preflight_downloaded_binary(&download.binary_name, &bytes)?; |
| 516 | autoupdate::discard_staged(&home); |
| 517 | let dir = autoupdate::staged_dir(&home); |
| 518 | installs::write_file_atomically(&dir, &autoupdate::binary_name(), &bytes, true)?; |
| 519 | installs::write_file_atomically(&dir, STAGED_MANIFEST, &download.manifest_bytes, false)?; |
| 520 | if signature.is_verified() { |
| 521 | let signature_bytes = download_url_with_timeout( |
| 522 | &format!("{}.sig", download.manifest_url), |
| 523 | proxy.as_ref(), |
| 524 | MANIFEST_PROBE_TIMEOUT, |
| 525 | )?; |
| 526 | installs::write_file_atomically(&dir, STAGED_SIGNATURE, &signature_bytes, false)?; |
| 527 | } |
| 528 | let target_dir = exe |
| 529 | .parent() |
| 530 | .context("executable has no parent")? |
| 531 | .canonicalize()?; |
| 532 | autoupdate::store_staged( |
| 533 | &home, |
| 534 | &autoupdate::StagedUpdate { |
| 535 | version: version.clone(), |
| 536 | sha256: sha256_hex(&bytes), |
| 537 | signed: signature.is_verified(), |
| 538 | source: download.source.describe(), |
| 539 | target_dir, |
| 540 | declined: false, |
| 541 | staged_at_unix: codewhale_release::check::now_unix(), |
| 542 | }, |
| 543 | )?; |
| 544 | println!( |
| 545 | "Staged v{version} from {} ({}). {}", |
| 546 | download.source.describe(), |
| 547 | if signature.is_verified() { |
| 548 | "signature verified" |
| 549 | } else { |
| 550 | "checksum verified; releases are not signed yet" |
| 551 | }, |
| 552 | if signature.is_verified() { |
| 553 | "It is applied the next time Codewhale starts." |
| 554 | } else { |
| 555 | "The next start asks before applying it." |
| 556 | } |
| 557 | ); |
| 558 | Ok(()) |
| 559 | } |
| 560 | |
| 561 | fn record_declined_update( |
| 562 | home: &Path, |
| 563 | staged: &mut autoupdate::StagedUpdate, |
| 564 | current: &str, |
| 565 | version: &str, |
| 566 | ) -> String { |
| 567 | staged.declined = true; |
| 568 | if let Err(error) = autoupdate::store_staged(home, staged) { |
| 569 | tracing::warn!(error = %format!("{error:#}"), "could not record declined update"); |
| 570 | return format!( |
| 571 | "Kept v{current}, but the decision was not saved ({error:#}); you will be asked again." |
| 572 | ); |
| 573 | } |
| 574 | format!("Kept v{current}. Run `codewhale update` whenever you want v{version}.") |
| 575 | } |
| 576 | |
| 577 | pub fn apply_staged_at_start(argv: &[std::ffi::OsString]) { |
| 578 | use std::io::IsTerminal; |
| 579 | let Ok(home) = codewhale_config::codewhale_home() else { |
| 580 | return; |
| 581 | }; |
| 582 | let Some(mut staged) = autoupdate::load_staged(&home) else { |
| 583 | return; |
| 584 | }; |
| 585 | let current = env!("CARGO_PKG_VERSION"); |
| 586 | if compare_release_versions(current, &staged.version).ok() != Some(Ordering::Less) |
| 587 | || autoupdate::load_state(&home).skip_version.as_deref() == Some(staged.version.as_str()) |
| 588 | { |
| 589 | autoupdate::discard_staged(&home); |
| 590 | return; |
| 591 | } |
| 592 | if autoupdate::resolve_mode(None, true).mode != autoupdate::UpdateMode::Auto { |
| 593 | return; |
| 594 | } |
| 595 | let Ok(identity) = update_executable_identity() else { |
| 596 | return; |
| 597 | }; |
| 598 | if !InstallMethod::detect(&identity.path).supports_self_update() |
| 599 | || identity |
| 600 | .path |
| 601 | .parent() |
| 602 | .and_then(|dir| dir.canonicalize().ok()) |
| 603 | .as_deref() |
| 604 | != Some(staged.target_dir.as_path()) |
| 605 | { |
| 606 | return; |
| 607 | } |
| 608 | let version = staged.version.clone(); |
| 609 | let fail = |reason: String| { |
| 610 | autoupdate::record_failure( |
| 611 | &home, |
| 612 | Some(format!( |
| 613 | "v{version} could not be applied at start: {reason}" |
| 614 | )), |
| 615 | ); |
| 616 | eprintln!( |
| 617 | "Couldn't apply v{version} ({reason}). Still on v{current}. Details: codewhale doctor" |
| 618 | ); |
| 619 | }; |
| 620 | let dir = autoupdate::staged_dir(&home); |
| 621 | let verified = (|| -> Result<(Vec<u8>, bool)> { |
| 622 | let bytes = std::fs::read(dir.join(autoupdate::binary_name())) |
| 623 | .context("the downloaded file is unreadable")?; |
| 624 | let manifest = std::fs::read(dir.join(STAGED_MANIFEST)) |
| 625 | .context("the downloaded checksum manifest is missing")?; |
| 626 | let signature = std::fs::read(dir.join(STAGED_SIGNATURE)).ok(); |
| 627 | let signed = match signing::verify_manifest(&version, &manifest, signature.as_deref()) { |
| 628 | SignatureCheck::Verified => true, |
| 629 | SignatureCheck::NotConfigured => false, |
| 630 | other => bail!("the release signature does not verify ({other:?})"), |
| 631 | }; |
| 632 | let asset = release_asset_name_for_prefix( |
| 633 | "codewhale", |
| 634 | std::env::consts::OS, |
| 635 | std::env::consts::ARCH, |
| 636 | ); |
| 637 | let checksums = parse_checksum_manifest( |
| 638 | std::str::from_utf8(&manifest).context("the checksum manifest is not UTF-8")?, |
| 639 | )?; |
| 640 | let expected = checksums |
| 641 | .get(&asset) |
| 642 | .with_context(|| format!("the checksum manifest does not list {asset}"))?; |
| 643 | if !sha256_hex(&bytes).eq_ignore_ascii_case(expected) { |
| 644 | bail!("the downloaded file does not match its checksum manifest"); |
| 645 | } |
| 646 | Ok((bytes, signed)) |
| 647 | })(); |
| 648 | let (bytes, signed) = match verified { |
| 649 | Ok(verified) => verified, |
| 650 | Err(error) => { |
| 651 | autoupdate::discard_staged(&home); |
| 652 | return fail(format!("{error:#}")); |
| 653 | } |
| 654 | }; |
| 655 | if !signed { |
| 656 | if staged.declined || !std::io::stdin().is_terminal() || !std::io::stderr().is_terminal() { |
| 657 | return; |
| 658 | } |
| 659 | eprint!( |
| 660 | "Codewhale v{version} is downloaded and its checksum verified. Releases are not signed yet, so it waits for your OK.\nInstall v{version} now? [y/N] " |
| 661 | ); |
| 662 | let _ = std::io::stderr().flush(); |
| 663 | let mut answer = String::new(); |
| 664 | let accepted = std::io::stdin().read_line(&mut answer).is_ok() |
| 665 | && matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes"); |
| 666 | if !accepted { |
| 667 | eprintln!( |
| 668 | "{}", |
| 669 | record_declined_update(&home, &mut staged, current, &version) |
| 670 | ); |
| 671 | return; |
| 672 | } |
| 673 | } |
| 674 | let plan = update_plan_for_exe(&identity.path); |
| 675 | let divergent = divergent_aliases(&plan, &identity); |
| 676 | let applied = (|| { |
| 677 | for target in &plan.target_paths { |
| 678 | if !divergent.contains(target) { |
| 679 | validate_update_target(target, &identity)?; |
| 680 | } |
| 681 | } |
| 682 | replace_command_paths(&identity, &plan, &bytes, &divergent, &mut || Ok(())) |
| 683 | })(); |
| 684 | let kept_previous = match applied { |
| 685 | Ok(kept) => kept, |
| 686 | Err(error) => return fail(format!("{error:#}")), |
| 687 | }; |
| 688 | autoupdate::discard_staged(&home); |
| 689 | autoupdate::record_failure(&home, None); |
| 690 | eprintln!( |
| 691 | "Updated to v{version} · What's new: {} · {}", |
| 692 | autoupdate::changelog_url(&version), |
| 693 | undo_hint(kept_previous, &version) |
| 694 | ); |
| 695 | #[cfg(unix)] |
| 696 | { |
| 697 | use std::os::unix::process::CommandExt; |
| 698 | let error = std::process::Command::new(&identity.path) |
| 699 | .args(argv.iter().skip(1)) |
| 700 | .exec(); |
| 701 | eprintln!("Restart Codewhale to run v{version} ({error})."); |
| 702 | std::process::exit(0); |
| 703 | } |
| 704 | #[cfg(not(unix))] |
| 705 | { |
| 706 | let _ = argv; |
| 707 | eprintln!("v{version} runs from the next start; this session continues on v{current}."); |
| 708 | } |
| 709 | } |
| 710 | |
| 711 | pub fn run_rollback() -> Result<()> { |
| 712 | let identity = update_executable_identity()?; |
| 713 | let method = InstallMethod::detect(&identity.path); |
| 714 | if !method.supports_self_update() { |
| 715 | bail!( |
| 716 | "This copy belongs to {label}, so `codewhale update --rollback` did not change it; install the version you want with {label}.", |
| 717 | label = method.label() |
| 718 | ); |
| 719 | } |
| 720 | let home = codewhale_config::codewhale_home()?; |
| 721 | let previous = autoupdate::load_previous(&home) |
| 722 | .context("There is no previous version to roll back to on this machine.")?; |
| 723 | let bytes = std::fs::read(autoupdate::previous_dir(&home).join(autoupdate::binary_name())) |
| 724 | .context("The previous version's binary is missing; nothing was changed.")?; |
| 725 | if sha256_hex(&bytes) != previous.sha256 { |
| 726 | bail!( |
| 727 | "The kept previous version no longer matches its recorded checksum; nothing was changed." |
| 728 | ); |
| 729 | } |
| 730 | if previous.sha256 == identity.file_hash { |
| 731 | println!("v{} is already the running version.", previous.version); |
| 732 | return Ok(()); |
| 733 | } |
| 734 | let current = env!("CARGO_PKG_VERSION"); |
| 735 | if let Some(blocker) = autoupdate::rollback_blocker(&previous.version, current) { |
| 736 | bail!( |
| 737 | "{}. Rollback did not replace the executable or change workspace state. Continue using v{current} and keep your workspace data.", |
| 738 | capitalized(&blocker) |
| 739 | ); |
| 740 | } |
| 741 | preflight_downloaded_binary(&autoupdate::binary_name(), &bytes)?; |
| 742 | let plan = update_plan_for_exe(&identity.path); |
| 743 | for target in &plan.target_paths { |
| 744 | validate_update_target(target, &identity)?; |
| 745 | } |
| 746 | println!( |
| 747 | "Rolling back {} from v{current} to v{}...", |
| 748 | identity.path.display(), |
| 749 | previous.version |
| 750 | ); |
| 751 | let kept_previous = replace_command_paths(&identity, &plan, &bytes, &[], &mut || Ok(()))?; |
| 752 | let mut state = autoupdate::load_state(&home); |
| 753 | state.skip_version = Some(current.to_string()); |
| 754 | autoupdate::store_state(&home, &state)?; |
| 755 | autoupdate::discard_staged(&home); |
| 756 | println!( |
| 757 | "Rolled back to v{}. v{current} will not be installed automatically again; the next newer release will. {}", |
| 758 | previous.version, |
| 759 | undo_hint(kept_previous, &previous.version) |
| 760 | ); |
| 761 | Ok(()) |
| 762 | } |
| 763 | |
| 764 | /// Fail closed when the downloaded bytes do not match the manifest that came |
| 765 | /// from the same source. A mismatch is never a reason to install anyway, and |
| 766 | /// never a reason to retry against the source that lost the probe: the two |
| 767 | /// build their own artifacts, so their checksums are not interchangeable. |
| 768 | fn verify_downloaded_asset(download: &DownloadPlan, bytes: &[u8]) -> Result<()> { |
| 769 | verify_manifest_asset(download, &download.binary_name, bytes) |
| 770 | } |
| 771 | |
| 772 | fn verify_manifest_asset(download: &DownloadPlan, name: &str, bytes: &[u8]) -> Result<()> { |
| 773 | let expected = download.checksums.get(name).with_context(|| { |
| 774 | format!( |
| 775 | "{CHECKSUM_MANIFEST_ASSET} from {} is missing {name}", |
| 776 | download.source.describe() |
| 777 | ) |
| 778 | })?; |
| 779 | let actual = sha256_hex(bytes); |
| 780 | if !actual.eq_ignore_ascii_case(expected) { |
| 781 | bail!( |
| 782 | "SHA256 mismatch for {name} from {}!\n expected: {expected}\n actual: {actual}", |
| 783 | download.source.describe() |
| 784 | ); |
| 785 | } |
| 786 | Ok(()) |
| 787 | } |
| 788 | |
| 789 | fn capitalized(text: &str) -> String { |
| 790 | let mut chars = text.chars(); |
| 791 | chars |
| 792 | .next() |
| 793 | .map(|first| first.to_uppercase().chain(chars).collect()) |
| 794 | .unwrap_or_default() |
| 795 | } |
| 796 | |
| 797 | /// The undo hint after replacing the running executable with `installed`, |
| 798 | /// only when a kept previous version exists and `--rollback` would accept it. |
| 799 | fn undo_hint(kept_previous: bool, installed: &str) -> String { |
| 800 | let previous = kept_previous |
| 801 | .then(codewhale_config::codewhale_home) |
| 802 | .and_then(Result::ok) |
| 803 | .and_then(|home| autoupdate::load_previous(&home)); |
| 804 | undo_hint_for(previous.as_ref().map(|p| p.version.as_str()), installed) |
| 805 | } |
| 806 | |
| 807 | /// `--rollback` runs from the installed binary, so the blocker is judged |
| 808 | /// against `installed`, not the version printing the hint. |
| 809 | fn undo_hint_for(previous: Option<&str>, installed: &str) -> String { |
| 810 | let Some(previous) = previous else { |
| 811 | return "No rollback: the previous version was not kept.".to_string(); |
| 812 | }; |
| 813 | match autoupdate::rollback_blocker(previous, installed) { |
| 814 | Some(blocker) => format!("No rollback: {blocker}."), |
| 815 | None => format!("Undo: codewhale update --rollback (back to v{previous})"), |
| 816 | } |
| 817 | } |
| 818 | |
| 819 | /// Resolve the executable that the updater is allowed to replace. |
| 820 | /// |
| 821 | /// Android's `std::env::current_exe()`, `AT_EXECFN`, and `/proc/self/exe` can |
| 822 | /// all identify Bionic's runtime linker rather than the launched program. On |
| 823 | /// Android, locate a marker compiled into this executable with `dladdr`, then |
| 824 | /// require the executable `/proc/self/maps` row containing that same address |
| 825 | /// to agree by canonical path, device, and inode. |
| 826 | #[derive(Debug, Clone)] |
| 827 | struct UpdateExecutableIdentity { |
| 828 | path: PathBuf, |
| 829 | file_hash: String, |
| 830 | #[cfg(target_os = "android")] |
| 831 | android_proof: AndroidExecutableProof, |
| 832 | } |
| 833 | |
| 834 | #[cfg(not(target_os = "android"))] |
| 835 | fn update_executable_identity() -> Result<UpdateExecutableIdentity> { |
| 836 | let path = std::env::current_exe().context("failed to determine current executable path")?; |
| 837 | let file_hash = sha256_hex(&std::fs::read(&path).context("failed to identify updater binary")?); |
| 838 | Ok(UpdateExecutableIdentity { path, file_hash }) |
| 839 | } |
| 840 | |
| 841 | #[cfg(target_os = "android")] |
| 842 | fn update_executable_identity() -> Result<UpdateExecutableIdentity> { |
| 843 | let android_proof = android_loaded_executable_proof()?; |
| 844 | Ok(UpdateExecutableIdentity { |
| 845 | file_hash: sha256_hex( |
| 846 | &std::fs::read(&android_proof.path).context("failed to identify updater binary")?, |
| 847 | ), |
| 848 | path: android_proof.path.clone(), |
| 849 | android_proof, |
| 850 | }) |
| 851 | } |
| 852 | |
| 853 | #[cfg(target_os = "android")] |
| 854 | #[inline(never)] |
| 855 | extern "C" fn android_update_image_marker() -> usize { |
| 856 | android_update_image_marker as *const () as usize |
| 857 | } |
| 858 | |
| 859 | #[cfg(target_os = "android")] |
| 860 | fn android_loaded_executable_proof() -> Result<AndroidExecutableProof> { |
| 861 | let marker = android_update_image_marker as *const () as usize as u64; |
| 862 | let dladdr_path = android_dladdr_path(android_update_image_marker as *const libc::c_void)?; |
| 863 | let maps = std::fs::read_to_string(ANDROID_PROC_SELF_MAPS) |
| 864 | .context("failed to read Android executable mappings from /proc/self/maps")?; |
| 865 | android_loaded_executable_proof_report(&maps, marker, &dladdr_path) |
| 866 | } |
| 867 | |
| 868 | #[cfg(target_os = "android")] |
| 869 | fn android_dladdr_path(marker: *const libc::c_void) -> Result<PathBuf> { |
| 870 | use std::os::unix::ffi::OsStrExt; |
| 871 | |
| 872 | let mut info = std::mem::MaybeUninit::<libc::Dl_info>::zeroed(); |
| 873 | // SAFETY: `marker` points to a function in this loaded image and `info` |
| 874 | // points to writable storage for the duration of the call. |
| 875 | let found = unsafe { libc::dladdr(marker, info.as_mut_ptr()) }; |
| 876 | if found == 0 { |
| 877 | bail!("Android dladdr could not locate the updater's loaded image"); |
| 878 | } |
| 879 | // SAFETY: A non-zero dladdr result initializes `info`. |
| 880 | let info = unsafe { info.assume_init() }; |
| 881 | if info.dli_fname.is_null() { |
| 882 | bail!("Android dladdr returned an empty loaded-image path"); |
| 883 | } |
| 884 | // SAFETY: `dli_fname` is a NUL-terminated string owned by the dynamic |
| 885 | // loader and remains valid while this image is loaded. |
| 886 | let bytes = unsafe { CStr::from_ptr(info.dli_fname) }.to_bytes(); |
| 887 | if bytes.is_empty() { |
| 888 | bail!("Android dladdr returned an empty loaded-image path"); |
| 889 | } |
| 890 | Ok(PathBuf::from(OsStr::from_bytes(bytes))) |
| 891 | } |
| 892 | |
| 893 | #[cfg(any(target_os = "android", all(test, unix)))] |
| 894 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 895 | struct AndroidImageMapping { |
| 896 | start: u64, |
| 897 | end: u64, |
| 898 | device_major: u32, |
| 899 | device_minor: u32, |
| 900 | inode: u64, |
| 901 | path: PathBuf, |
| 902 | } |
| 903 | |
| 904 | #[cfg(any(target_os = "android", all(test, unix)))] |
| 905 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 906 | enum AndroidExecutableProofKind { |
| 907 | DladdrAndProcMaps, |
| 908 | } |
| 909 | |
| 910 | #[cfg(any(target_os = "android", all(test, unix)))] |
| 911 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 912 | struct AndroidExecutableProof { |
| 913 | path: PathBuf, |
| 914 | device_major: u32, |
| 915 | device_minor: u32, |
| 916 | inode: u64, |
| 917 | proof_kind: AndroidExecutableProofKind, |
| 918 | } |
| 919 | |
| 920 | #[cfg(any(target_os = "android", all(test, unix)))] |
| 921 | fn parse_android_image_mapping(maps: &str, marker: u64) -> Result<AndroidImageMapping> { |
| 922 | let mut matching = None; |
| 923 | for (line_index, line) in maps.lines().enumerate() { |
| 924 | if line.trim().is_empty() { |
| 925 | continue; |
| 926 | } |
| 927 | let mut fields = line.split_whitespace(); |
| 928 | let range = fields |
| 929 | .next() |
| 930 | .with_context(|| format!("malformed /proc/self/maps line {}", line_index + 1))?; |
| 931 | let (start, end) = range |
| 932 | .split_once('-') |
| 933 | .with_context(|| format!("malformed mapping range `{range}`"))?; |
| 934 | let start = u64::from_str_radix(start, 16) |
| 935 | .with_context(|| format!("invalid mapping start `{start}`"))?; |
| 936 | let end = |
| 937 | u64::from_str_radix(end, 16).with_context(|| format!("invalid mapping end `{end}`"))?; |
| 938 | if !(start <= marker && marker < end) { |
| 939 | continue; |
| 940 | } |
| 941 | |
| 942 | let permissions = fields |
| 943 | .next() |
| 944 | .context("loaded-image mapping is missing permissions")?; |
| 945 | let _offset = fields |
| 946 | .next() |
| 947 | .context("loaded-image mapping is missing its file offset")?; |
| 948 | let device = fields |
| 949 | .next() |
| 950 | .context("loaded-image mapping is missing its device")?; |
| 951 | let inode = fields |
| 952 | .next() |
| 953 | .context("loaded-image mapping is missing its inode")? |
| 954 | .parse::<u64>() |
| 955 | .context("loaded-image mapping has an invalid inode")?; |
| 956 | let path = fields.collect::<Vec<_>>().join(" "); |
| 957 | |
| 958 | if permissions.as_bytes().get(2) != Some(&b'x') { |
| 959 | bail!("loaded-image mapping for updater marker is not executable"); |
| 960 | } |
| 961 | if inode == 0 { |
| 962 | bail!("loaded-image mapping for updater marker has no file inode"); |
| 963 | } |
| 964 | let (device_major, device_minor) = device |
| 965 | .split_once(':') |
| 966 | .context("loaded-image mapping has an invalid device")?; |
| 967 | let device_major = u32::from_str_radix(device_major, 16) |
| 968 | .context("loaded-image mapping has an invalid device major number")?; |
| 969 | let device_minor = u32::from_str_radix(device_minor, 16) |
| 970 | .context("loaded-image mapping has an invalid device minor number")?; |
| 971 | if path.is_empty() { |
| 972 | bail!("loaded-image mapping for updater marker has no pathname"); |
| 973 | } |
| 974 | |
| 975 | let mapping = AndroidImageMapping { |
| 976 | start, |
| 977 | end, |
| 978 | device_major, |
| 979 | device_minor, |
| 980 | inode, |
| 981 | path: PathBuf::from(path), |
| 982 | }; |
| 983 | if matching.replace(mapping).is_some() { |
| 984 | bail!("multiple /proc/self/maps rows contain the updater marker"); |
| 985 | } |
| 986 | } |
| 987 | |
| 988 | matching.ok_or_else(|| anyhow!("no /proc/self/maps row contains the updater marker")) |
| 989 | } |
| 990 | |
| 991 | #[cfg(all(test, unix))] |
| 992 | fn resolve_android_loaded_executable_report( |
| 993 | maps: &str, |
| 994 | marker: u64, |
| 995 | dladdr_path: &Path, |
| 996 | ) -> Result<PathBuf> { |
| 997 | Ok(android_loaded_executable_proof_report(maps, marker, dladdr_path)?.path) |
| 998 | } |
| 999 | |
| 1000 | #[cfg(any(target_os = "android", all(test, unix)))] |
| 1001 | fn android_loaded_executable_proof_report( |
| 1002 | maps: &str, |
| 1003 | marker: u64, |
| 1004 | dladdr_path: &Path, |
| 1005 | ) -> Result<AndroidExecutableProof> { |
| 1006 | let mapping = parse_android_image_mapping(maps, marker)?; |
| 1007 | validate_android_reported_path("dladdr", dladdr_path)?; |
| 1008 | validate_android_reported_path("/proc/self/maps", &mapping.path)?; |
| 1009 | |
| 1010 | let resolved_dladdr = dladdr_path.canonicalize().with_context(|| { |
| 1011 | format!( |
| 1012 | "failed to canonicalize Android dladdr path {}", |
| 1013 | dladdr_path.display() |
| 1014 | ) |
| 1015 | })?; |
| 1016 | let resolved_mapping = mapping.path.canonicalize().with_context(|| { |
| 1017 | format!( |
| 1018 | "failed to canonicalize Android loaded-image mapping {}", |
| 1019 | mapping.path.display() |
| 1020 | ) |
| 1021 | })?; |
| 1022 | if resolved_dladdr != resolved_mapping { |
| 1023 | bail!( |
| 1024 | "Android loaded-image authorities disagree: dladdr resolved to {}, but /proc/self/maps resolved to {}", |
| 1025 | resolved_dladdr.display(), |
| 1026 | resolved_mapping.display() |
| 1027 | ); |
| 1028 | } |
| 1029 | if is_android_linker_name(&resolved_mapping) { |
| 1030 | bail!( |
| 1031 | "Android loaded-image authorities resolved to runtime linker {}; refusing to use the linker as an update target", |
| 1032 | resolved_mapping.display() |
| 1033 | ); |
| 1034 | } |
| 1035 | if !is_executable_file(&resolved_mapping) { |
| 1036 | bail!( |
| 1037 | "Android loaded image `{}` is not an executable regular file; refusing to select an update target", |
| 1038 | resolved_mapping.display() |
| 1039 | ); |
| 1040 | } |
| 1041 | |
| 1042 | validate_android_mapping_identity(&mapping, &resolved_mapping)?; |
| 1043 | Ok(AndroidExecutableProof { |
| 1044 | path: resolved_mapping, |
| 1045 | device_major: mapping.device_major, |
| 1046 | device_minor: mapping.device_minor, |
| 1047 | inode: mapping.inode, |
| 1048 | proof_kind: AndroidExecutableProofKind::DladdrAndProcMaps, |
| 1049 | }) |
| 1050 | } |
| 1051 | |
| 1052 | #[cfg(any(target_os = "android", all(test, unix)))] |
| 1053 | fn validate_android_reported_path(authority: &str, path: &Path) -> Result<()> { |
| 1054 | if !path.is_absolute() { |
| 1055 | bail!( |
| 1056 | "Android {authority} reported non-absolute loaded-image path `{}`", |
| 1057 | path.display() |
| 1058 | ); |
| 1059 | } |
| 1060 | if path.to_string_lossy().ends_with(" (deleted)") { |
| 1061 | bail!( |
| 1062 | "Android {authority} reported deleted loaded image `{}`", |
| 1063 | path.display() |
| 1064 | ); |
| 1065 | } |
| 1066 | if is_android_linker_name(path) { |
| 1067 | bail!( |
| 1068 | "Android {authority} identifies runtime linker `{}`; refusing to use the linker as an update target", |
| 1069 | path.display() |
| 1070 | ); |
| 1071 | } |
| 1072 | Ok(()) |
| 1073 | } |
| 1074 | |
| 1075 | #[cfg(any(target_os = "android", all(test, unix)))] |
| 1076 | fn validate_android_mapping_identity( |
| 1077 | mapping: &AndroidImageMapping, |
| 1078 | candidate: &Path, |
| 1079 | ) -> Result<()> { |
| 1080 | use std::os::unix::fs::MetadataExt; |
| 1081 | |
| 1082 | let candidate_metadata = std::fs::metadata(candidate).with_context(|| { |
| 1083 | format!( |
| 1084 | "failed to stat Android update target {}", |
| 1085 | candidate.display() |
| 1086 | ) |
| 1087 | })?; |
| 1088 | let (candidate_major, candidate_minor) = android_device_parts(candidate_metadata.dev()); |
| 1089 | let identity_matches = mapping.device_major == candidate_major |
| 1090 | && mapping.device_minor == candidate_minor |
| 1091 | && mapping.inode == candidate_metadata.ino(); |
| 1092 | if !identity_matches { |
| 1093 | bail!( |
| 1094 | "Android loaded-image identity changed: /proc/self/maps has device/inode {:x}:{:x}:{}, but update target {} is {:x}:{:x}:{}; refusing to replace it", |
| 1095 | mapping.device_major, |
| 1096 | mapping.device_minor, |
| 1097 | mapping.inode, |
| 1098 | candidate.display(), |
| 1099 | candidate_major, |
| 1100 | candidate_minor, |
| 1101 | candidate_metadata.ino() |
| 1102 | ); |
| 1103 | } |
| 1104 | Ok(()) |
| 1105 | } |
| 1106 | |
| 1107 | #[cfg(any(target_os = "android", all(test, unix)))] |
| 1108 | fn android_device_parts(device: u64) -> (u32, u32) { |
| 1109 | // Linux/Bionic's dev_t encoding, matching makedev(3), major(3), and |
| 1110 | // minor(3). `/proc/self/maps` renders these components in hexadecimal. |
| 1111 | let major = ((device >> 8) & 0xfff) as u32; |
| 1112 | let minor = ((device & 0xff) | ((device >> 12) & 0xfff00)) as u32; |
| 1113 | (major, minor) |
| 1114 | } |
| 1115 | |
| 1116 | fn validate_primary_update_identity(identity: &UpdateExecutableIdentity) -> Result<()> { |
| 1117 | #[cfg(target_os = "android")] |
| 1118 | { |
| 1119 | let fresh = android_loaded_executable_proof()?; |
| 1120 | if fresh != identity.android_proof { |
| 1121 | bail!( |
| 1122 | "Android loaded-image proof changed from {:?} to {:?}; refusing to replace the update target", |
| 1123 | identity.android_proof, |
| 1124 | fresh |
| 1125 | ); |
| 1126 | } |
| 1127 | } |
| 1128 | let bytes = std::fs::read(&identity.path).context("failed to recheck updater binary")?; |
| 1129 | if sha256_hex(&bytes) != identity.file_hash { |
| 1130 | bail!( |
| 1131 | "The running executable path changed during the update; no further files were replaced. Run the intended executable again by its full path." |
| 1132 | ); |
| 1133 | } |
| 1134 | Ok(()) |
| 1135 | } |
| 1136 | |
| 1137 | /// Only the running binary and copies of those exact bytes are ours to update. |
| 1138 | /// Command names alone do not establish ownership of an existing sibling. |
| 1139 | fn validate_update_target(target: &Path, identity: &UpdateExecutableIdentity) -> Result<()> { |
| 1140 | if !InstallMethod::owner(target).supports_self_update() { |
| 1141 | bail!( |
| 1142 | "Refusing to replace managed/system path {}.\n\n{GITHUB_MIGRATION_HELP}", |
| 1143 | target.display() |
| 1144 | ); |
| 1145 | } |
| 1146 | let metadata = match std::fs::symlink_metadata(target) { |
| 1147 | Ok(metadata) => metadata, |
| 1148 | Err(error) if error.kind() == std::io::ErrorKind::NotFound && target != identity.path => { |
| 1149 | return Ok(()); |
| 1150 | } |
| 1151 | Err(error) => { |
| 1152 | return Err(error) |
| 1153 | .with_context(|| format!("failed to inspect update target {}", target.display())); |
| 1154 | } |
| 1155 | }; |
| 1156 | if !metadata.is_file() || metadata.is_symlink() { |
| 1157 | bail!( |
| 1158 | "Refusing to replace {}: the update target is not a regular file.\n\n{GITHUB_MIGRATION_HELP}", |
| 1159 | target.display() |
| 1160 | ); |
| 1161 | } |
| 1162 | let bytes = std::fs::read(target) |
| 1163 | .with_context(|| format!("failed to identify update target {}", target.display()))?; |
| 1164 | if sha256_hex(&bytes) != identity.file_hash { |
| 1165 | bail!( |
| 1166 | "Refusing to replace {}: its bytes differ from the running executable. This may be another installation or an unrelated command. No command is removed automatically.\n\n{GITHUB_MIGRATION_HELP}", |
| 1167 | target.display() |
| 1168 | ); |
| 1169 | } |
| 1170 | Ok(()) |
| 1171 | } |
| 1172 | |
| 1173 | fn replacement_parent(target: &Path) -> &Path { |
| 1174 | target |
| 1175 | .parent() |
| 1176 | .filter(|path| !path.as_os_str().is_empty()) |
| 1177 | .unwrap_or_else(|| Path::new(".")) |
| 1178 | } |
| 1179 | |
| 1180 | fn replace_verified_downloads<F>( |
| 1181 | target_paths: &[PathBuf], |
| 1182 | verified_bytes: &[u8], |
| 1183 | validate_target: F, |
| 1184 | ) -> Result<()> |
| 1185 | where |
| 1186 | F: Fn(&Path) -> Result<()>, |
| 1187 | { |
| 1188 | // Fail before mutating a sibling if the primary pathname no longer names |
| 1189 | // the process image that initiated this update. |
| 1190 | for path in target_paths { |
| 1191 | validate_target(path)?; |
| 1192 | } |
| 1193 | #[cfg(unix)] |
| 1194 | let mut replaced_by_parent: Vec<PathBuf> = Vec::new(); |
| 1195 | for path in target_paths.iter().rev() { |
| 1196 | #[cfg(unix)] |
| 1197 | let linked_from = replaced_by_parent |
| 1198 | .iter() |
| 1199 | .find(|existing| replacement_parent(existing) == replacement_parent(path)) |
| 1200 | .map(PathBuf::as_path); |
| 1201 | #[cfg(not(unix))] |
| 1202 | let linked_from: Option<&Path> = None; |
| 1203 | replace_binary_with_validation_and_link_source(path, verified_bytes, linked_from, || { |
| 1204 | // Re-check after each temp file is fully staged and immediately |
| 1205 | // before every destructive rename. The running command is first |
| 1206 | // in the plan and therefore replaced last, after its colocated |
| 1207 | // compatibility names have received the same verified bytes. |
| 1208 | validate_target(path) |
| 1209 | })?; |
| 1210 | #[cfg(unix)] |
| 1211 | if linked_from.is_none() { |
| 1212 | replaced_by_parent.push(path.clone()); |
| 1213 | } |
| 1214 | } |
| 1215 | Ok(()) |
| 1216 | } |
| 1217 | |
| 1218 | #[cfg(any(target_os = "android", all(test, unix)))] |
| 1219 | fn is_android_linker_name(path: &Path) -> bool { |
| 1220 | path.file_name() |
| 1221 | .and_then(OsStr::to_str) |
| 1222 | .is_some_and(|name| { |
| 1223 | matches!( |
| 1224 | name, |
| 1225 | "linker" |
| 1226 | | "linker64" |
| 1227 | | "linker_asan" |
| 1228 | | "linker_asan64" |
| 1229 | | "linker_hwasan" |
| 1230 | | "linker_hwasan64" |
| 1231 | ) |
| 1232 | }) |
| 1233 | } |
| 1234 | |
| 1235 | #[cfg(any(target_os = "android", all(test, unix)))] |
| 1236 | fn is_executable_file(path: &Path) -> bool { |
| 1237 | let Ok(metadata) = std::fs::metadata(path) else { |
| 1238 | return false; |
| 1239 | }; |
| 1240 | if !metadata.is_file() { |
| 1241 | return false; |
| 1242 | } |
| 1243 | |
| 1244 | #[cfg(unix)] |
| 1245 | { |
| 1246 | use std::os::unix::fs::PermissionsExt; |
| 1247 | metadata.permissions().mode() & 0o111 != 0 |
| 1248 | } |
| 1249 | |
| 1250 | #[cfg(not(unix))] |
| 1251 | { |
| 1252 | true |
| 1253 | } |
| 1254 | } |
| 1255 | |
| 1256 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1257 | struct FetchedRelease { |
| 1258 | release: Release, |
| 1259 | source: UpdateReleaseSource, |
| 1260 | } |
| 1261 | |
| 1262 | /// Where a release's assets come from. |
| 1263 | /// |
| 1264 | /// This names the *asset* origin, which is not always the origin of the release |
| 1265 | /// metadata: without an override the tag is resolved from GitHub, and only then |
| 1266 | /// is the asset source chosen between GitHub and the first-party CNB mirror. |
| 1267 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1268 | enum UpdateReleaseSource { |
| 1269 | /// Canonical GitHub Releases. |
| 1270 | GitHub, |
| 1271 | /// The first-party CNB mirror release for this exact tag (Linux x64 only). |
| 1272 | Cnb { base_url: String }, |
| 1273 | /// An operator-supplied asset directory (`CODEWHALE_RELEASE_BASE_URL`). |
| 1274 | Mirror { base_url: String }, |
| 1275 | } |
| 1276 | |
| 1277 | impl UpdateReleaseSource { |
| 1278 | /// Short, stable name for status output. |
| 1279 | fn label(&self) -> &'static str { |
| 1280 | match self { |
| 1281 | Self::GitHub => "GitHub Releases", |
| 1282 | Self::Cnb { .. } => "CNB mirror", |
| 1283 | Self::Mirror { .. } => "release mirror", |
| 1284 | } |
| 1285 | } |
| 1286 | |
| 1287 | /// The asset directory this source serves from, when it has one. |
| 1288 | fn base_url(&self) -> Option<&str> { |
| 1289 | match self { |
| 1290 | Self::GitHub => None, |
| 1291 | Self::Cnb { base_url } | Self::Mirror { base_url } => Some(base_url), |
| 1292 | } |
| 1293 | } |
| 1294 | |
| 1295 | /// Label plus asset directory — what status lines and the final receipt |
| 1296 | /// print, so "which source did this binary come from?" is answerable |
| 1297 | /// without rerunning the updater. |
| 1298 | fn describe(&self) -> String { |
| 1299 | match self.base_url() { |
| 1300 | Some(base_url) => format!("{} ({})", self.label(), redact_url_str(base_url)), |
| 1301 | None => self.label().to_string(), |
| 1302 | } |
| 1303 | } |
| 1304 | |
| 1305 | /// True when an environment override, not a probe, chose this source. Such |
| 1306 | /// a source also carries the pinned version. The same no-downgrade and |
| 1307 | /// already-current checks apply before downloading from any source. |
| 1308 | fn is_pinned_mirror(&self) -> bool { |
| 1309 | !matches!(self, Self::GitHub) |
| 1310 | } |
| 1311 | } |
| 1312 | |
| 1313 | /// One source that could serve this release, and the two URLs that must come |
| 1314 | /// from it together: the checksum manifest, and the binary that manifest |
| 1315 | /// covers. |
| 1316 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1317 | struct ReleaseSourceCandidate { |
| 1318 | source: UpdateReleaseSource, |
| 1319 | manifest_url: String, |
| 1320 | binary_name: String, |
| 1321 | binary_url: String, |
| 1322 | } |
| 1323 | |
| 1324 | /// A source locked in for this update, with its manifest already fetched, |
| 1325 | /// parsed, and confirmed to cover the binary we are about to download. |
| 1326 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1327 | struct DownloadPlan { |
| 1328 | source: UpdateReleaseSource, |
| 1329 | binary_name: String, |
| 1330 | binary_url: String, |
| 1331 | /// Parsed checksums from this same source, already confirmed to cover |
| 1332 | /// `binary_name`. A plan cannot exist without this proof. |
| 1333 | checksums: HashMap<String, String>, |
| 1334 | manifest_url: String, |
| 1335 | manifest_bytes: Vec<u8>, |
| 1336 | fallback_binaries: Vec<(UpdateReleaseSource, String)>, |
| 1337 | } |
| 1338 | |
| 1339 | /// Fetches one candidate's checksum manifest. Injected so the selection logic |
| 1340 | /// can be tested without a network. |
| 1341 | type ManifestFetcher = dyn Fn(&ReleaseSourceCandidate) -> Result<Vec<u8>> + Send + Sync; |
| 1342 | |
| 1343 | /// Build the candidate list for proactive source selection, or `None` when this |
| 1344 | /// update keeps a single canonical source. |
| 1345 | /// |
| 1346 | /// Selection applies only when the release metadata came from GitHub (an |
| 1347 | /// explicit override already named the source) and the target is one the CNB |
| 1348 | /// mirror actually publishes. Every other target is left exactly as it was. |
| 1349 | fn proactive_source_candidates( |
| 1350 | fetched: &FetchedRelease, |
| 1351 | asset_stem: &str, |
| 1352 | os: &str, |
| 1353 | rust_arch: &str, |
| 1354 | ) -> Option<Vec<ReleaseSourceCandidate>> { |
| 1355 | if fetched.source != UpdateReleaseSource::GitHub || !cnb_mirror_supports_target(os, rust_arch) { |
| 1356 | return None; |
| 1357 | } |
| 1358 | let mut candidates = Vec::new(); |
| 1359 | if let Some(github) = github_source_candidate(&fetched.release, asset_stem) { |
| 1360 | candidates.push(github); |
| 1361 | } |
| 1362 | candidates.push(cnb_source_candidate( |
| 1363 | &fetched.release.tag_name, |
| 1364 | os, |
| 1365 | rust_arch, |
| 1366 | )); |
| 1367 | Some(candidates) |
| 1368 | } |
| 1369 | |
| 1370 | /// The canonical GitHub candidate for a release the API already described. |
| 1371 | /// |
| 1372 | /// Asset URLs come from the release payload when it advertises them. A release |
| 1373 | /// that lists the platform binary but not the manifest still gets a candidate: |
| 1374 | /// GitHub serves release assets from a stable per-tag path, so the manifest is |
| 1375 | /// addressable even when the payload omits it. |
| 1376 | fn github_source_candidate(release: &Release, asset_stem: &str) -> Option<ReleaseSourceCandidate> { |
| 1377 | let asset = select_platform_asset(release, asset_stem)?; |
| 1378 | let manifest_url = select_checksum_manifest_asset(release) |
| 1379 | .map(|manifest| manifest.browser_download_url.clone()) |
| 1380 | .unwrap_or_else(|| { |
| 1381 | let tag_name = format!("v{}", release.tag_name.trim_start_matches('v')); |
| 1382 | mirror_asset_url( |
| 1383 | &format!("{GITHUB_RELEASE_DOWNLOAD_BASE_URL}/{tag_name}"), |
| 1384 | CHECKSUM_MANIFEST_ASSET, |
| 1385 | ) |
| 1386 | }); |
| 1387 | Some(ReleaseSourceCandidate { |
| 1388 | source: UpdateReleaseSource::GitHub, |
| 1389 | manifest_url, |
| 1390 | binary_name: asset.name.clone(), |
| 1391 | binary_url: asset.browser_download_url.clone(), |
| 1392 | }) |
| 1393 | } |
| 1394 | |
| 1395 | /// The first-party CNB candidate for this exact tag. |
| 1396 | /// |
| 1397 | /// CNB builds its own artifacts from the tagged source, so its manifest only |
| 1398 | /// describes its own binaries — which is precisely why the manifest and the |
| 1399 | /// binary have to be taken from the same source. |
| 1400 | fn cnb_source_candidate(tag_name: &str, os: &str, rust_arch: &str) -> ReleaseSourceCandidate { |
| 1401 | let base_url = cnb_release_base_url(tag_name); |
| 1402 | let binary_name = release_asset_name_for_prefix("codewhale", os, rust_arch); |
| 1403 | ReleaseSourceCandidate { |
| 1404 | manifest_url: mirror_asset_url(&base_url, CHECKSUM_MANIFEST_ASSET), |
| 1405 | binary_url: mirror_asset_url(&base_url, &binary_name), |
| 1406 | binary_name, |
| 1407 | source: UpdateReleaseSource::Cnb { base_url }, |
| 1408 | } |
| 1409 | } |
| 1410 | |
| 1411 | /// Decide where this update's bytes come from, and prove the choice before |
| 1412 | /// committing to it. |
| 1413 | fn resolve_download_plan( |
| 1414 | fetched: &FetchedRelease, |
| 1415 | asset_stem: &str, |
| 1416 | proxy: Option<&Proxy>, |
| 1417 | require_compiled_host: bool, |
| 1418 | ) -> Result<DownloadPlan> { |
| 1419 | match proactive_source_candidates( |
| 1420 | fetched, |
| 1421 | asset_stem, |
| 1422 | std::env::consts::OS, |
| 1423 | std::env::consts::ARCH, |
| 1424 | ) { |
| 1425 | Some(candidates) => { |
| 1426 | println!( |
| 1427 | "Probing {CHECKSUM_MANIFEST_ASSET} for {} from {}...", |
| 1428 | fetched.release.tag_name, |
| 1429 | candidate_labels(&candidates) |
| 1430 | ); |
| 1431 | let fetch = manifest_probe_fetcher(proxy); |
| 1432 | let qualified: Arc<ManifestFetcher> = Arc::new(move |candidate| { |
| 1433 | let bytes = fetch(candidate)?; |
| 1434 | if require_compiled_host { |
| 1435 | compiled_host::require_catalog_manifest(&bytes)?; |
| 1436 | } |
| 1437 | Ok(bytes) |
| 1438 | }); |
| 1439 | select_release_source(candidates, qualified).with_context(update_network_fallback_hint) |
| 1440 | } |
| 1441 | None => { |
| 1442 | let plan = single_source_download_plan(fetched, asset_stem, proxy)?; |
| 1443 | if require_compiled_host |
| 1444 | && !plan |
| 1445 | .checksums |
| 1446 | .contains_key("codewhale-extension-hosts.json") |
| 1447 | { |
| 1448 | bail!( |
| 1449 | "selected release source has no qualified compiled-host catalog; no files changed" |
| 1450 | ); |
| 1451 | } |
| 1452 | Ok(plan) |
| 1453 | } |
| 1454 | } |
| 1455 | } |
| 1456 | |
| 1457 | fn candidate_labels(candidates: &[ReleaseSourceCandidate]) -> String { |
| 1458 | candidates |
| 1459 | .iter() |
| 1460 | .map(|candidate| candidate.source.label()) |
| 1461 | .collect::<Vec<_>>() |
| 1462 | .join(" and ") |
| 1463 | } |
| 1464 | |
| 1465 | /// Name the source `--check` would download from, without downloading anything |
| 1466 | /// bigger than a manifest — and without contacting anything at all when an |
| 1467 | /// override already fixed the answer. |
| 1468 | fn describe_release_source_for_check( |
| 1469 | fetched: &FetchedRelease, |
| 1470 | asset_stem: &str, |
| 1471 | proxy: Option<&Proxy>, |
| 1472 | ) -> String { |
| 1473 | let Some(candidates) = proactive_source_candidates( |
| 1474 | fetched, |
| 1475 | asset_stem, |
| 1476 | std::env::consts::OS, |
| 1477 | std::env::consts::ARCH, |
| 1478 | ) else { |
| 1479 | return fetched.source.describe(); |
| 1480 | }; |
| 1481 | match select_release_source(candidates, manifest_probe_fetcher(proxy)) { |
| 1482 | Ok(plan) => plan.source.describe(), |
| 1483 | // A failed probe is a real answer for `--check` to report, not a reason |
| 1484 | // to fail a command whose whole job is to describe the release. |
| 1485 | Err(error) => format!("unresolved — {error:#}"), |
| 1486 | } |
| 1487 | } |
| 1488 | |
| 1489 | /// Resolve an explicit source or a platform without a supported fallback. |
| 1490 | /// |
| 1491 | /// This path is still fail-closed: every platform and every explicit mirror |
| 1492 | /// must publish a valid manifest from the same source that covers the selected |
| 1493 | /// binary. The binary is not downloaded until that proof exists. |
| 1494 | fn single_source_download_plan( |
| 1495 | fetched: &FetchedRelease, |
| 1496 | asset_stem: &str, |
| 1497 | proxy: Option<&Proxy>, |
| 1498 | ) -> Result<DownloadPlan> { |
| 1499 | let release = &fetched.release; |
| 1500 | let asset = select_platform_asset(release, asset_stem).with_context(|| { |
| 1501 | format!( |
| 1502 | "no asset found for platform {asset_stem} in release {}. \ |
| 1503 | Available assets: {}", |
| 1504 | release.tag_name, |
| 1505 | release |
| 1506 | .assets |
| 1507 | .iter() |
| 1508 | .map(|asset| asset.name.as_str()) |
| 1509 | .collect::<Vec<_>>() |
| 1510 | .join(", ") |
| 1511 | ) |
| 1512 | })?; |
| 1513 | |
| 1514 | let checksum_asset = select_checksum_manifest_asset(release).with_context(|| { |
| 1515 | format!( |
| 1516 | "release {} from {} does not publish required {CHECKSUM_MANIFEST_ASSET}; refusing to download {} without checksum verification", |
| 1517 | release.tag_name, |
| 1518 | fetched.source.describe(), |
| 1519 | asset.name |
| 1520 | ) |
| 1521 | })?; |
| 1522 | println!("Downloading {}...", checksum_asset.name); |
| 1523 | let checksum_bytes = download_url_with_timeout( |
| 1524 | &checksum_asset.browser_download_url, |
| 1525 | proxy, |
| 1526 | MANIFEST_PROBE_TIMEOUT, |
| 1527 | ) |
| 1528 | .with_context(|| { |
| 1529 | format!( |
| 1530 | "failed to download {} from {}\n{}", |
| 1531 | checksum_asset.name, |
| 1532 | fetched.source.describe(), |
| 1533 | update_network_fallback_hint() |
| 1534 | ) |
| 1535 | })?; |
| 1536 | let checksum_text = std::str::from_utf8(&checksum_bytes) |
| 1537 | .with_context(|| format!("{} is not valid UTF-8", checksum_asset.name))?; |
| 1538 | let checksums = parse_checksum_manifest(checksum_text).with_context(|| { |
| 1539 | format!( |
| 1540 | "failed to parse {} from {}", |
| 1541 | checksum_asset.name, |
| 1542 | fetched.source.describe() |
| 1543 | ) |
| 1544 | })?; |
| 1545 | if !checksums.contains_key(&asset.name) { |
| 1546 | bail!( |
| 1547 | "{} from {} does not list {}; refusing to download an unverified update", |
| 1548 | checksum_asset.name, |
| 1549 | fetched.source.describe(), |
| 1550 | asset.name |
| 1551 | ); |
| 1552 | } |
| 1553 | |
| 1554 | Ok(DownloadPlan { |
| 1555 | source: fetched.source.clone(), |
| 1556 | binary_name: asset.name.clone(), |
| 1557 | binary_url: asset.browser_download_url.clone(), |
| 1558 | checksums, |
| 1559 | manifest_url: checksum_asset.browser_download_url.clone(), |
| 1560 | manifest_bytes: checksum_bytes, |
| 1561 | fallback_binaries: Vec::new(), |
| 1562 | }) |
| 1563 | } |
| 1564 | |
| 1565 | fn manifest_probe_fetcher(proxy: Option<&Proxy>) -> Arc<ManifestFetcher> { |
| 1566 | let proxy = proxy.cloned(); |
| 1567 | Arc::new(move |candidate: &ReleaseSourceCandidate| { |
| 1568 | download_url_with_timeout( |
| 1569 | &candidate.manifest_url, |
| 1570 | proxy.as_ref(), |
| 1571 | MANIFEST_PROBE_TIMEOUT, |
| 1572 | ) |
| 1573 | }) |
| 1574 | } |
| 1575 | |
| 1576 | /// Try the official GitHub manifest first. Only an unavailable or unusable |
| 1577 | /// manifest admits the next configured source; a faster mirror never races |
| 1578 | /// GitHub. Each network probe has its own bounded timeout and retry policy. |
| 1579 | fn select_release_source( |
| 1580 | candidates: Vec<ReleaseSourceCandidate>, |
| 1581 | fetch_manifest: Arc<ManifestFetcher>, |
| 1582 | ) -> Result<DownloadPlan> { |
| 1583 | let mut candidates = candidates.into_iter(); |
| 1584 | let primary = candidates |
| 1585 | .next() |
| 1586 | .context("no release source publishes an asset for this platform")?; |
| 1587 | let (checksums, manifest_bytes) = probe_release_source(&primary, &*fetch_manifest) |
| 1588 | .with_context(|| { |
| 1589 | format!( |
| 1590 | "{} has no usable {CHECKSUM_MANIFEST_ASSET}; mirrors may only serve binaries that this manifest pins, so nothing was downloaded", |
| 1591 | primary.source.describe() |
| 1592 | ) |
| 1593 | })?; |
| 1594 | let fallback_binaries = candidates |
| 1595 | .filter(|candidate| candidate.binary_name == primary.binary_name) |
| 1596 | .map(|candidate| (candidate.source, candidate.binary_url)) |
| 1597 | .collect(); |
| 1598 | Ok(DownloadPlan { |
| 1599 | source: primary.source, |
| 1600 | binary_name: primary.binary_name, |
| 1601 | binary_url: primary.binary_url, |
| 1602 | checksums, |
| 1603 | manifest_url: primary.manifest_url, |
| 1604 | manifest_bytes, |
| 1605 | fallback_binaries, |
| 1606 | }) |
| 1607 | } |
| 1608 | |
| 1609 | fn download_pinned_binary(download: &DownloadPlan, proxy: Option<&Proxy>) -> Result<Vec<u8>> { |
| 1610 | let mut failures = Vec::new(); |
| 1611 | let sources = std::iter::once((&download.source, &download.binary_url)).chain( |
| 1612 | download |
| 1613 | .fallback_binaries |
| 1614 | .iter() |
| 1615 | .map(|(source, url)| (source, url)), |
| 1616 | ); |
| 1617 | for (source, url) in sources { |
| 1618 | match download_url(url, proxy) |
| 1619 | .and_then(|bytes| verify_downloaded_asset(download, &bytes).map(|()| bytes)) |
| 1620 | { |
| 1621 | Ok(bytes) => { |
| 1622 | if source != &download.source { |
| 1623 | println!( |
| 1624 | "Downloaded {} from {}; its SHA256 matches the {} manifest.", |
| 1625 | download.binary_name, |
| 1626 | source.describe(), |
| 1627 | download.source.label() |
| 1628 | ); |
| 1629 | } |
| 1630 | return Ok(bytes); |
| 1631 | } |
| 1632 | Err(error) => failures.push(format!(" - {}: {error:#}", source.describe())), |
| 1633 | } |
| 1634 | } |
| 1635 | bail!( |
| 1636 | "failed to download a {} whose SHA256 matches {CHECKSUM_MANIFEST_ASSET} from {}:\n{}\n{}", |
| 1637 | download.binary_name, |
| 1638 | download.source.describe(), |
| 1639 | failures.join("\n"), |
| 1640 | update_network_fallback_hint() |
| 1641 | ) |
| 1642 | } |
| 1643 | |
| 1644 | fn probe_release_source( |
| 1645 | candidate: &ReleaseSourceCandidate, |
| 1646 | fetch_manifest: &ManifestFetcher, |
| 1647 | ) -> Result<(HashMap<String, String>, Vec<u8>)> { |
| 1648 | let safe_manifest_url = redact_url_str(&candidate.manifest_url); |
| 1649 | let bytes = fetch_manifest(candidate) |
| 1650 | .with_context(|| format!("failed to fetch {safe_manifest_url}"))?; |
| 1651 | let text = std::str::from_utf8(&bytes) |
| 1652 | .with_context(|| format!("{safe_manifest_url} is not valid UTF-8"))?; |
| 1653 | let checksums = parse_checksum_manifest(text) |
| 1654 | .with_context(|| format!("failed to parse {safe_manifest_url}"))?; |
| 1655 | if !checksums.contains_key(&candidate.binary_name) { |
| 1656 | bail!( |
| 1657 | "{safe_manifest_url} does not list {}", |
| 1658 | candidate.binary_name |
| 1659 | ); |
| 1660 | } |
| 1661 | Ok((checksums, bytes)) |
| 1662 | } |
| 1663 | |
| 1664 | fn ensure_supported_release_target(os: &str, arch: &str) -> Result<()> { |
| 1665 | if os == "linux" && arch == "riscv64" { |
| 1666 | bail!( |
| 1667 | "Linux riscv64 release assets are temporarily unavailable because \ |
| 1668 | rquickjs-sys 0.12.0 does not ship riscv64gc-unknown-linux-gnu bindings. \ |
| 1669 | See docs/INSTALL.md for the current platform matrix." |
| 1670 | ); |
| 1671 | } |
| 1672 | Ok(()) |
| 1673 | } |
| 1674 | |
| 1675 | pub(crate) fn release_arch_for_rust_arch(arch: &str) -> &str { |
| 1676 | match arch { |
| 1677 | "aarch64" => "arm64", |
| 1678 | "x86_64" => "x64", |
| 1679 | other => other, |
| 1680 | } |
| 1681 | } |
| 1682 | |
| 1683 | /// Returns true when the binary name belongs to the pre-rebrand `deepseek-tui` era. |
| 1684 | pub(crate) fn is_legacy_binary(current_exe: &Path) -> bool { |
| 1685 | let exe_name = current_exe |
| 1686 | .file_name() |
| 1687 | .and_then(|name| name.to_str()) |
| 1688 | .unwrap_or("") |
| 1689 | .to_ascii_lowercase(); |
| 1690 | exe_name.starts_with("deepseek") |
| 1691 | } |
| 1692 | |
| 1693 | fn legacy_binary_message(current_exe: &Path) -> String { |
| 1694 | format!( |
| 1695 | "\ |
| 1696 | this binary ({exe}) is using the legacy deepseek/deepseek-tui command name. |
| 1697 | |
| 1698 | The package has been renamed to `codewhale`. A supported direct update can |
| 1699 | install the canonical `codewhale` command beside this legacy command when a |
| 1700 | newer verified release is available and the destination paths are safe to use. |
| 1701 | DeepSeek provider support is unchanged. |
| 1702 | |
| 1703 | {GITHUB_MIGRATION_HELP} |
| 1704 | |
| 1705 | Existing npm, Cargo, Homebrew, or system-managed commands are left to their |
| 1706 | package manager. See docs/INSTALL.md for secondary package routes. |
| 1707 | |
| 1708 | Once `codewhale` is on your PATH, run `codewhale update` for future updates.", |
| 1709 | exe = current_exe.display(), |
| 1710 | ) |
| 1711 | } |
| 1712 | |
| 1713 | fn command_name_for_exe(current_exe: &Path) -> String { |
| 1714 | let exe_name = current_exe |
| 1715 | .file_name() |
| 1716 | .and_then(|name| name.to_str()) |
| 1717 | .unwrap_or("codewhale") |
| 1718 | .to_ascii_lowercase(); |
| 1719 | exe_name |
| 1720 | .strip_suffix(".exe") |
| 1721 | .unwrap_or(&exe_name) |
| 1722 | .to_string() |
| 1723 | } |
| 1724 | |
| 1725 | fn command_path_beside(current_exe: &Path, command: &str) -> PathBuf { |
| 1726 | current_exe.with_file_name(format!("{command}{}", std::env::consts::EXE_SUFFIX)) |
| 1727 | } |
| 1728 | |
| 1729 | fn installed_command_path(current_exe: &Path, command: &str) -> PathBuf { |
| 1730 | if command_name_for_exe(current_exe) == command { |
| 1731 | current_exe.to_path_buf() |
| 1732 | } else { |
| 1733 | command_path_beside(current_exe, command) |
| 1734 | } |
| 1735 | } |
| 1736 | |
| 1737 | fn push_unique_path(paths: &mut Vec<PathBuf>, path: PathBuf) { |
| 1738 | if !paths.iter().any(|existing| existing == &path) { |
| 1739 | paths.push(path); |
| 1740 | } |
| 1741 | } |
| 1742 | |
| 1743 | fn push_update_path(paths: &mut Vec<PathBuf>, path: PathBuf, current_exe: &Path) { |
| 1744 | // Keep a same-target symlink as a symlink. Replacing its target refreshes |
| 1745 | // the alias too. Foreign/broken links stay in the plan and fail validation. |
| 1746 | // Compare canonical paths on both sides: `current_exe()` is not |
| 1747 | // canonicalized on macOS, so an install dir reached through a symlinked |
| 1748 | // directory would otherwise never match its own alias. |
| 1749 | let same_target_link = std::fs::symlink_metadata(&path).is_ok_and(|m| m.is_symlink()) |
| 1750 | && match [path.as_path(), current_exe].map(std::fs::canonicalize) { |
| 1751 | [Ok(resolved), exe] => resolved == current_exe || exe.is_ok_and(|exe| resolved == exe), |
| 1752 | _ => false, |
| 1753 | }; |
| 1754 | if !same_target_link { |
| 1755 | push_unique_path(paths, path); |
| 1756 | } |
| 1757 | } |
| 1758 | |
| 1759 | fn legacy_tui_command_exists_beside(current_exe: &Path) -> bool { |
| 1760 | command_name_for_exe(current_exe) == "deepseek-tui" |
| 1761 | || command_path_beside(current_exe, "deepseek-tui").exists() |
| 1762 | } |
| 1763 | |
| 1764 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1765 | struct UpdatePlan { |
| 1766 | target_paths: Vec<PathBuf>, |
| 1767 | asset_stem: String, |
| 1768 | } |
| 1769 | |
| 1770 | fn update_plan_for_exe(current_exe: &Path) -> UpdatePlan { |
| 1771 | let mut target_paths = Vec::new(); |
| 1772 | |
| 1773 | // Keep the process image first so reverse-order replacement updates the |
| 1774 | // command currently running the updater last. Pre-rebrand command names |
| 1775 | // retain their historical migration behavior: install canonical commands |
| 1776 | // beside them instead of overwriting the legacy path. |
| 1777 | if !is_legacy_binary(current_exe) { |
| 1778 | push_unique_path(&mut target_paths, current_exe.to_path_buf()); |
| 1779 | } |
| 1780 | |
| 1781 | let primary = installed_command_path(current_exe, "codewhale"); |
| 1782 | push_update_path(&mut target_paths, primary, current_exe); |
| 1783 | |
| 1784 | for alias in ["codew", "codewhale-tui"] { |
| 1785 | let alias_path = installed_command_path(current_exe, alias); |
| 1786 | let migrate_legacy_tui = alias == "codewhale-tui" |
| 1787 | && is_legacy_binary(current_exe) |
| 1788 | && legacy_tui_command_exists_beside(current_exe); |
| 1789 | if std::fs::symlink_metadata(&alias_path).is_ok() |
| 1790 | || command_name_for_exe(current_exe) == alias |
| 1791 | || migrate_legacy_tui |
| 1792 | { |
| 1793 | push_update_path(&mut target_paths, alias_path, current_exe); |
| 1794 | } |
| 1795 | } |
| 1796 | |
| 1797 | UpdatePlan { |
| 1798 | target_paths, |
| 1799 | asset_stem: release_asset_stem_for_prefix( |
| 1800 | "codewhale", |
| 1801 | std::env::consts::OS, |
| 1802 | std::env::consts::ARCH, |
| 1803 | ), |
| 1804 | } |
| 1805 | } |
| 1806 | |
| 1807 | fn release_asset_stem_for_prefix(prefix: &str, os: &str, rust_arch: &str) -> String { |
| 1808 | let arch = release_arch_for_rust_arch(rust_arch); |
| 1809 | format!("{prefix}-{os}-{arch}") |
| 1810 | } |
| 1811 | |
| 1812 | fn release_asset_name_for_prefix(prefix: &str, os: &str, rust_arch: &str) -> String { |
| 1813 | let stem = release_asset_stem_for_prefix(prefix, os, rust_arch); |
| 1814 | if os == "windows" { |
| 1815 | format!("{stem}.exe") |
| 1816 | } else { |
| 1817 | stem |
| 1818 | } |
| 1819 | } |
| 1820 | |
| 1821 | #[cfg(test)] |
| 1822 | fn release_asset_stem_for(current_exe: &Path, os: &str, rust_arch: &str) -> String { |
| 1823 | let _ = current_exe; |
| 1824 | release_asset_stem_for_prefix("codewhale", os, rust_arch) |
| 1825 | } |
| 1826 | |
| 1827 | fn asset_is_exact_platform_binary(asset_name: &str, binary_name: &str) -> bool { |
| 1828 | asset_name == binary_name || asset_name == format!("{binary_name}.exe") |
| 1829 | } |
| 1830 | |
| 1831 | /// The raw platform executable, and nothing else. |
| 1832 | /// |
| 1833 | /// The updater writes the downloaded bytes straight over the running binary; |
| 1834 | /// it never unpacks. An archive, signature, or sidecar that merely shares the |
| 1835 | /// stem (`codewhale-macos-arm64.tar.gz`) would pass the checksum — the manifest |
| 1836 | /// lists it too — and then replace the executable with a non-executable. A |
| 1837 | /// release without the raw binary has no asset for this platform. |
| 1838 | fn select_platform_asset<'a>(release: &'a Release, binary_name: &str) -> Option<&'a Asset> { |
| 1839 | release |
| 1840 | .assets |
| 1841 | .iter() |
| 1842 | .find(|asset| asset_is_exact_platform_binary(&asset.name, binary_name)) |
| 1843 | } |
| 1844 | |
| 1845 | fn select_checksum_manifest_asset(release: &Release) -> Option<&Asset> { |
| 1846 | release |
| 1847 | .assets |
| 1848 | .iter() |
| 1849 | .find(|asset| asset.name == CHECKSUM_MANIFEST_ASSET) |
| 1850 | } |
| 1851 | |
| 1852 | #[cfg(test)] |
| 1853 | fn expected_sha256_from_manifest(text: &str, asset_name: &str) -> Result<String> { |
| 1854 | let checksums = parse_checksum_manifest(text)?; |
| 1855 | checksums |
| 1856 | .get(asset_name) |
| 1857 | .cloned() |
| 1858 | .with_context(|| format!("checksum manifest is missing {asset_name}")) |
| 1859 | } |
| 1860 | |
| 1861 | /// GitHub release metadata. |
| 1862 | #[derive(serde::Deserialize, Debug, Clone, PartialEq, Eq)] |
| 1863 | struct Release { |
| 1864 | tag_name: String, |
| 1865 | #[serde(default)] |
| 1866 | prerelease: bool, |
| 1867 | assets: Vec<Asset>, |
| 1868 | } |
| 1869 | |
| 1870 | /// A single release asset. |
| 1871 | #[derive(serde::Deserialize, Debug, Clone, PartialEq, Eq)] |
| 1872 | struct Asset { |
| 1873 | name: String, |
| 1874 | browser_download_url: String, |
| 1875 | } |
| 1876 | |
| 1877 | /// Validate the proxy URL format and build a proxy for update HTTP requests. |
| 1878 | pub(crate) fn validate_and_build_proxy(proxy_str: &str) -> Result<Proxy> { |
| 1879 | let proxy_url = reqwest::Url::parse(proxy_str).with_context(|| { |
| 1880 | format!( |
| 1881 | "invalid proxy URL: {}\n\ |
| 1882 | Expected format: http://host:port, https://host:port, or socks5://host:port", |
| 1883 | redact_url_str(proxy_str) |
| 1884 | ) |
| 1885 | })?; |
| 1886 | Proxy::all(proxy_url).context("failed to configure update proxy") |
| 1887 | } |
| 1888 | |
| 1889 | fn update_http_client_with_policy( |
| 1890 | proxy: Option<&Proxy>, |
| 1891 | timeout: Duration, |
| 1892 | policy: &UpdateTransportPolicy, |
| 1893 | ) -> Result<reqwest::blocking::Client> { |
| 1894 | let mut builder = codewhale_release::platform_blocking_http_client_builder(); |
| 1895 | if let Some(proxy) = proxy { |
| 1896 | builder = builder.proxy(proxy.clone()); |
| 1897 | } |
| 1898 | builder |
| 1899 | .user_agent(UPDATE_USER_AGENT) |
| 1900 | .timeout(timeout) |
| 1901 | .redirect(update_redirect_policy(policy.clone())) |
| 1902 | .build() |
| 1903 | .context("failed to build update HTTP client") |
| 1904 | } |
| 1905 | |
| 1906 | /// Largest update response held in memory. Release archives are tens of |
| 1907 | /// megabytes; a server that keeps sending is cut off instead of exhausting |
| 1908 | /// memory before the checksum is ever compared. |
| 1909 | const UPDATE_MAX_RESPONSE_BYTES: usize = 512 * 1024 * 1024; |
| 1910 | |
| 1911 | fn update_transport_policy() -> UpdateTransportPolicy { |
| 1912 | let policy = UpdateTransportPolicy::from_env(); |
| 1913 | #[cfg(all(test, debug_assertions))] |
| 1914 | { |
| 1915 | policy.with_loopback_http(true) |
| 1916 | } |
| 1917 | #[cfg(not(all(test, debug_assertions)))] |
| 1918 | { |
| 1919 | policy |
| 1920 | } |
| 1921 | } |
| 1922 | |
| 1923 | /// Fetch the latest release metadata from GitHub. |
| 1924 | fn fetch_latest_release(channel: ReleaseChannel, proxy: Option<&Proxy>) -> Result<FetchedRelease> { |
| 1925 | match resolve_release_query(channel) { |
| 1926 | ReleaseQuery::Mirror { base_url, version } => { |
| 1927 | update_transport_policy() |
| 1928 | .check_str(&base_url) |
| 1929 | .with_context(|| { |
| 1930 | format!( |
| 1931 | "release mirror {} cannot be used", |
| 1932 | redact_url_str(&base_url) |
| 1933 | ) |
| 1934 | })?; |
| 1935 | Ok(FetchedRelease { |
| 1936 | release: release_from_mirror_base_url( |
| 1937 | &base_url, |
| 1938 | &version, |
| 1939 | std::env::consts::OS, |
| 1940 | std::env::consts::ARCH, |
| 1941 | ), |
| 1942 | source: pinned_mirror_source(base_url), |
| 1943 | }) |
| 1944 | } |
| 1945 | ReleaseQuery::GitHubLatest { url } => match fetch_latest_release_from_url(url, proxy) { |
| 1946 | Ok(release) => Ok(FetchedRelease { |
| 1947 | release, |
| 1948 | source: UpdateReleaseSource::GitHub, |
| 1949 | }), |
| 1950 | Err(api_error) => { |
| 1951 | eprintln!( |
| 1952 | "GitHub API release lookup failed; trying github.com releases/latest fallback..." |
| 1953 | ); |
| 1954 | Ok(FetchedRelease { |
| 1955 | release: fetch_latest_stable_release_from_redirect(proxy).with_context( |
| 1956 | || format!("GitHub API release lookup failed first: {api_error:#}"), |
| 1957 | )?, |
| 1958 | source: UpdateReleaseSource::GitHub, |
| 1959 | }) |
| 1960 | } |
| 1961 | }, |
| 1962 | ReleaseQuery::GitHubReleaseList { url } => Ok(FetchedRelease { |
| 1963 | release: fetch_latest_beta_release_from_url(url, proxy)?, |
| 1964 | source: UpdateReleaseSource::GitHub, |
| 1965 | }), |
| 1966 | } |
| 1967 | } |
| 1968 | |
| 1969 | /// Name the source an environment override selected. |
| 1970 | /// |
| 1971 | /// `CODEWHALE_USE_CNB_MIRROR` and `CODEWHALE_RELEASE_BASE_URL` both resolve to |
| 1972 | /// a base URL, but only the first is the first-party mirror — reporting them |
| 1973 | /// alike would hide which one a user actually asked for. |
| 1974 | fn pinned_mirror_source(base_url: String) -> UpdateReleaseSource { |
| 1975 | if cnb_mirror_override_active() { |
| 1976 | UpdateReleaseSource::Cnb { base_url } |
| 1977 | } else { |
| 1978 | UpdateReleaseSource::Mirror { base_url } |
| 1979 | } |
| 1980 | } |
| 1981 | |
| 1982 | fn release_from_mirror_base_url( |
| 1983 | base_url: &str, |
| 1984 | version: &str, |
| 1985 | os: &str, |
| 1986 | rust_arch: &str, |
| 1987 | ) -> Release { |
| 1988 | let tag_name = format!("v{}", version.trim_start_matches('v')); |
| 1989 | release_from_asset_base_url(&tag_name, base_url, os, rust_arch) |
| 1990 | } |
| 1991 | |
| 1992 | fn release_from_github_download_tag(tag_name: &str, os: &str, rust_arch: &str) -> Release { |
| 1993 | let tag_name = format!("v{}", tag_name.trim_start_matches('v')); |
| 1994 | let base_url = format!("{GITHUB_RELEASE_DOWNLOAD_BASE_URL}/{tag_name}"); |
| 1995 | release_from_asset_base_url(&tag_name, &base_url, os, rust_arch) |
| 1996 | } |
| 1997 | |
| 1998 | fn release_from_asset_base_url( |
| 1999 | tag_name: &str, |
| 2000 | base_url: &str, |
| 2001 | os: &str, |
| 2002 | rust_arch: &str, |
| 2003 | ) -> Release { |
| 2004 | let mut assets = vec![Asset { |
| 2005 | name: CHECKSUM_MANIFEST_ASSET.to_string(), |
| 2006 | browser_download_url: mirror_asset_url(base_url, CHECKSUM_MANIFEST_ASSET), |
| 2007 | }]; |
| 2008 | |
| 2009 | let name = release_asset_name_for_prefix("codewhale", os, rust_arch); |
| 2010 | assets.push(Asset { |
| 2011 | browser_download_url: mirror_asset_url(base_url, &name), |
| 2012 | name, |
| 2013 | }); |
| 2014 | |
| 2015 | Release { |
| 2016 | tag_name: tag_name.to_string(), |
| 2017 | prerelease: false, |
| 2018 | assets, |
| 2019 | } |
| 2020 | } |
| 2021 | |
| 2022 | fn fetch_release_json_once( |
| 2023 | url: &str, |
| 2024 | description: &str, |
| 2025 | proxy: Option<&Proxy>, |
| 2026 | ) -> Result<(reqwest::StatusCode, String)> { |
| 2027 | let safe_url = redact_url_str(url); |
| 2028 | let policy = update_transport_policy(); |
| 2029 | policy.check_str(url)?; |
| 2030 | let client = update_http_client_with_policy(proxy, UPDATE_DOWNLOAD_TIMEOUT, &policy)?; |
| 2031 | let response = client |
| 2032 | .get(url) |
| 2033 | .header(reqwest::header::ACCEPT, "application/vnd.github+json") |
| 2034 | .send() |
| 2035 | .map_err(reqwest::Error::without_url) |
| 2036 | .with_context(|| format!("failed to fetch {description} from {safe_url}"))?; |
| 2037 | let status = response.status(); |
| 2038 | let body = read_release_metadata(response) |
| 2039 | .with_context(|| format!("failed to read {description} response body from {safe_url}"))?; |
| 2040 | Ok((status, body)) |
| 2041 | } |
| 2042 | |
| 2043 | fn fetch_release_json(url: &str, description: &str, proxy: Option<&Proxy>) -> Result<String> { |
| 2044 | let safe_url = redact_url_str(url); |
| 2045 | let mut last_error = None; |
| 2046 | for attempt in 1..=UPDATE_HTTP_ATTEMPTS { |
| 2047 | match fetch_release_json_once(url, description, proxy) { |
| 2048 | Ok((status, body)) if status.is_success() => return Ok(body), |
| 2049 | Ok((status, body)) => { |
| 2050 | let error = |
| 2051 | anyhow!("failed to fetch {description} from {safe_url}: HTTP {status}\n{body}"); |
| 2052 | if should_retry_http_status(status) && attempt < UPDATE_HTTP_ATTEMPTS { |
| 2053 | last_error = Some(error); |
| 2054 | sleep_before_update_retry(attempt); |
| 2055 | continue; |
| 2056 | } |
| 2057 | return Err(error); |
| 2058 | } |
| 2059 | Err(error) if attempt < UPDATE_HTTP_ATTEMPTS => { |
| 2060 | last_error = Some(error); |
| 2061 | sleep_before_update_retry(attempt); |
| 2062 | } |
| 2063 | Err(error) => return Err(error), |
| 2064 | } |
| 2065 | } |
| 2066 | Err(last_error.unwrap_or_else(|| anyhow!("failed to fetch {description} from {safe_url}"))) |
| 2067 | } |
| 2068 | |
| 2069 | fn should_retry_http_status(status: reqwest::StatusCode) -> bool { |
| 2070 | status.is_server_error() |
| 2071 | || status == reqwest::StatusCode::REQUEST_TIMEOUT |
| 2072 | || status == reqwest::StatusCode::TOO_MANY_REQUESTS |
| 2073 | } |
| 2074 | |
| 2075 | fn sleep_before_update_retry(attempt: usize) { |
| 2076 | std::thread::sleep(Duration::from_millis( |
| 2077 | UPDATE_HTTP_RETRY_DELAY_MS * attempt as u64, |
| 2078 | )); |
| 2079 | } |
| 2080 | |
| 2081 | fn fetch_latest_release_from_url(url: &str, proxy: Option<&Proxy>) -> Result<Release> { |
| 2082 | let body = fetch_release_json(url, "release info", proxy)?; |
| 2083 | parse_release_json(&body, "release") |
| 2084 | } |
| 2085 | |
| 2086 | fn fetch_latest_stable_release_from_redirect(proxy: Option<&Proxy>) -> Result<Release> { |
| 2087 | let tag_name = |
| 2088 | fetch_latest_stable_tag_from_redirect_url(GITHUB_LATEST_RELEASE_PAGE_URL, proxy)?; |
| 2089 | Ok(release_from_github_download_tag( |
| 2090 | &tag_name, |
| 2091 | std::env::consts::OS, |
| 2092 | std::env::consts::ARCH, |
| 2093 | )) |
| 2094 | } |
| 2095 | |
| 2096 | fn fetch_latest_stable_tag_from_redirect_url(url: &str, proxy: Option<&Proxy>) -> Result<String> { |
| 2097 | let safe_url = redact_url_str(url); |
| 2098 | let policy = update_transport_policy(); |
| 2099 | policy.check_str(url)?; |
| 2100 | let client = update_http_client_with_policy(proxy, UPDATE_DOWNLOAD_TIMEOUT, &policy)?; |
| 2101 | let mut last_error = None; |
| 2102 | for attempt in 1..=UPDATE_HTTP_ATTEMPTS { |
| 2103 | match fetch_latest_stable_tag_from_redirect_url_once(&client, &policy, url) { |
| 2104 | Ok(tag_name) => return Ok(tag_name), |
| 2105 | Err(error) if attempt < UPDATE_HTTP_ATTEMPTS => { |
| 2106 | last_error = Some(error); |
| 2107 | sleep_before_update_retry(attempt); |
| 2108 | } |
| 2109 | Err(error) => return Err(error), |
| 2110 | } |
| 2111 | } |
| 2112 | Err(last_error |
| 2113 | .unwrap_or_else(|| anyhow!("failed to resolve latest stable release from {safe_url}"))) |
| 2114 | } |
| 2115 | |
| 2116 | fn fetch_latest_stable_tag_from_redirect_url_once( |
| 2117 | client: &reqwest::blocking::Client, |
| 2118 | policy: &UpdateTransportPolicy, |
| 2119 | url: &str, |
| 2120 | ) -> Result<String> { |
| 2121 | let safe_url = redact_url_str(url); |
| 2122 | let response = client |
| 2123 | .get(url) |
| 2124 | .send() |
| 2125 | .map_err(reqwest::Error::without_url) |
| 2126 | .with_context(|| format!("failed to fetch release redirect from {safe_url}"))?; |
| 2127 | let status = response.status(); |
| 2128 | let final_url = response.url().clone(); |
| 2129 | // Every hop was already checked; the page that names the tag must still be |
| 2130 | // an allowed host before its URL or body is trusted for a tag. |
| 2131 | policy |
| 2132 | .check_url(&final_url) |
| 2133 | .map_err(|message| anyhow!(message))?; |
| 2134 | if status.is_success() |
| 2135 | && let Some(tag_name) = release_tag_from_github_release_url(&final_url) |
| 2136 | { |
| 2137 | return Ok(tag_name); |
| 2138 | } |
| 2139 | let body = read_release_metadata(response) |
| 2140 | .with_context(|| format!("failed to read release redirect response from {safe_url}"))?; |
| 2141 | if !status.is_success() { |
| 2142 | bail!("failed to fetch release redirect from {safe_url}: HTTP {status}\n{body}"); |
| 2143 | } |
| 2144 | release_tag_from_github_release_html(&body).with_context(|| { |
| 2145 | format!( |
| 2146 | "release redirect did not resolve to a tag URL: {}", |
| 2147 | redact_url(&final_url) |
| 2148 | ) |
| 2149 | }) |
| 2150 | } |
| 2151 | |
| 2152 | fn release_tag_from_github_release_url(url: &reqwest::Url) -> Option<String> { |
| 2153 | let segments = url.path_segments()?.collect::<Vec<_>>(); |
| 2154 | segments |
| 2155 | .windows(3) |
| 2156 | .find(|window| window[0] == "releases" && window[1] == "tag") |
| 2157 | .map(|window| window[2].to_string()) |
| 2158 | .filter(|tag| is_plausible_release_tag(tag)) |
| 2159 | } |
| 2160 | |
| 2161 | /// A release tag becomes a URL path segment; only version-tag characters pass. |
| 2162 | fn is_plausible_release_tag(tag: &str) -> bool { |
| 2163 | !tag.is_empty() |
| 2164 | && tag.len() <= 64 |
| 2165 | && tag |
| 2166 | .chars() |
| 2167 | .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-' | '_' | '+')) |
| 2168 | } |
| 2169 | |
| 2170 | fn release_tag_from_github_release_html(body: &str) -> Option<String> { |
| 2171 | const MARKERS: &[&str] = &[ |
| 2172 | "/codewhale-hq/CodeWhale/releases/tag/", |
| 2173 | "/codewhale-hq/CodeWhale/releases/tag/", |
| 2174 | "/releases/tag/", |
| 2175 | ]; |
| 2176 | for marker in MARKERS { |
| 2177 | for rest in body.split(marker).skip(1) { |
| 2178 | let tag = rest |
| 2179 | .split(['"', '\'', '<', '>', '?', '#', '&']) |
| 2180 | .next() |
| 2181 | .unwrap_or("") |
| 2182 | .trim(); |
| 2183 | if is_plausible_release_tag(tag) { |
| 2184 | return Some(tag.to_string()); |
| 2185 | } |
| 2186 | } |
| 2187 | } |
| 2188 | None |
| 2189 | } |
| 2190 | |
| 2191 | fn fetch_latest_beta_release_from_url(url: &str, proxy: Option<&Proxy>) -> Result<Release> { |
| 2192 | let body = fetch_release_json(url, "release list", proxy)?; |
| 2193 | // GitHub caps this endpoint at 100 releases per page. Codewhale uses the |
| 2194 | // first page as the latest-beta search window, matching GitHub's ordering. |
| 2195 | let releases: Vec<Release> = parse_release_json(&body, "release list")?; |
| 2196 | |
| 2197 | releases |
| 2198 | .into_iter() |
| 2199 | .find(|release| is_beta_tag(&release.tag_name)) |
| 2200 | .context("no beta release found in GitHub releases") |
| 2201 | } |
| 2202 | |
| 2203 | /// Download a URL to bytes. |
| 2204 | fn download_url(url: &str, proxy: Option<&Proxy>) -> Result<Vec<u8>> { |
| 2205 | download_url_with_timeout(url, proxy, UPDATE_DOWNLOAD_TIMEOUT) |
| 2206 | } |
| 2207 | |
| 2208 | fn download_url_with_timeout( |
| 2209 | url: &str, |
| 2210 | proxy: Option<&Proxy>, |
| 2211 | timeout: Duration, |
| 2212 | ) -> Result<Vec<u8>> { |
| 2213 | let safe_url = redact_url_str(url); |
| 2214 | let mut last_error = None; |
| 2215 | for attempt in 1..=UPDATE_HTTP_ATTEMPTS { |
| 2216 | match download_url_once(url, proxy, timeout) { |
| 2217 | Ok((status, bytes)) if status.is_success() => return Ok(bytes), |
| 2218 | Ok((status, bytes)) => { |
| 2219 | let body = String::from_utf8_lossy(&bytes); |
| 2220 | let error = anyhow!("download failed with HTTP {status}: {body}"); |
| 2221 | if should_retry_http_status(status) && attempt < UPDATE_HTTP_ATTEMPTS { |
| 2222 | last_error = Some(error); |
| 2223 | sleep_before_update_retry(attempt); |
| 2224 | continue; |
| 2225 | } |
| 2226 | return Err(error); |
| 2227 | } |
| 2228 | Err(error) if attempt < UPDATE_HTTP_ATTEMPTS => { |
| 2229 | last_error = Some(error); |
| 2230 | sleep_before_update_retry(attempt); |
| 2231 | } |
| 2232 | Err(error) => return Err(error), |
| 2233 | } |
| 2234 | } |
| 2235 | Err(last_error.unwrap_or_else(|| anyhow!("failed to download {safe_url}"))) |
| 2236 | } |
| 2237 | |
| 2238 | fn download_url_once( |
| 2239 | url: &str, |
| 2240 | proxy: Option<&Proxy>, |
| 2241 | timeout: Duration, |
| 2242 | ) -> Result<(reqwest::StatusCode, Vec<u8>)> { |
| 2243 | download_url_once_with( |
| 2244 | &update_transport_policy(), |
| 2245 | UPDATE_MAX_RESPONSE_BYTES, |
| 2246 | url, |
| 2247 | proxy, |
| 2248 | timeout, |
| 2249 | ) |
| 2250 | } |
| 2251 | |
| 2252 | fn download_url_once_with( |
| 2253 | policy: &UpdateTransportPolicy, |
| 2254 | max_bytes: usize, |
| 2255 | url: &str, |
| 2256 | proxy: Option<&Proxy>, |
| 2257 | timeout: Duration, |
| 2258 | ) -> Result<(reqwest::StatusCode, Vec<u8>)> { |
| 2259 | let safe_url = redact_url_str(url); |
| 2260 | policy.check_str(url)?; |
| 2261 | let client = update_http_client_with_policy(proxy, timeout, policy)?; |
| 2262 | let response = client |
| 2263 | .get(url) |
| 2264 | .send() |
| 2265 | .map_err(reqwest::Error::without_url) |
| 2266 | .with_context(|| format!("failed to download {safe_url}"))?; |
| 2267 | let status = response.status(); |
| 2268 | let bytes = read_update_response(response, max_bytes) |
| 2269 | .with_context(|| format!("failed to read response body from {safe_url}"))?; |
| 2270 | Ok((status, bytes)) |
| 2271 | } |
| 2272 | |
| 2273 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] |
| 2274 | struct GlibcVersion { |
| 2275 | major: u32, |
| 2276 | minor: u32, |
| 2277 | patch: u32, |
| 2278 | } |
| 2279 | |
| 2280 | impl GlibcVersion { |
| 2281 | fn new(major: u32, minor: u32, patch: u32) -> Self { |
| 2282 | Self { |
| 2283 | major, |
| 2284 | minor, |
| 2285 | patch, |
| 2286 | } |
| 2287 | } |
| 2288 | |
| 2289 | fn display(self) -> String { |
| 2290 | if self.patch == 0 { |
| 2291 | format!("{}.{}", self.major, self.minor) |
| 2292 | } else { |
| 2293 | format!("{}.{}.{}", self.major, self.minor, self.patch) |
| 2294 | } |
| 2295 | } |
| 2296 | } |
| 2297 | |
| 2298 | fn parse_glibc_version(text: &str) -> Option<GlibcVersion> { |
| 2299 | text.split(|ch: char| !(ch.is_ascii_digit() || ch == '.')) |
| 2300 | .filter(|part| part.contains('.')) |
| 2301 | .find_map(parse_glibc_version_token) |
| 2302 | } |
| 2303 | |
| 2304 | fn parse_glibc_version_token(token: &str) -> Option<GlibcVersion> { |
| 2305 | let mut parts = token.split('.'); |
| 2306 | let major = parts.next()?.parse().ok()?; |
| 2307 | let minor = parts.next()?.parse().ok()?; |
| 2308 | let patch = parts.next().and_then(|part| part.parse().ok()).unwrap_or(0); |
| 2309 | Some(GlibcVersion::new(major, minor, patch)) |
| 2310 | } |
| 2311 | |
| 2312 | fn highest_required_glibc(bytes: &[u8]) -> Option<GlibcVersion> { |
| 2313 | const MARKER: &[u8] = b"GLIBC_"; |
| 2314 | let mut offset = 0; |
| 2315 | let mut highest = None; |
| 2316 | |
| 2317 | while let Some(found) = find_bytes(&bytes[offset..], MARKER) { |
| 2318 | let start = offset + found + MARKER.len(); |
| 2319 | let mut end = start; |
| 2320 | while end < bytes.len() && (bytes[end].is_ascii_digit() || bytes[end] == b'.') { |
| 2321 | end += 1; |
| 2322 | } |
| 2323 | if end > start |
| 2324 | && let Ok(token) = std::str::from_utf8(&bytes[start..end]) |
| 2325 | && let Some(version) = parse_glibc_version_token(token) |
| 2326 | && highest.is_none_or(|current| version > current) |
| 2327 | { |
| 2328 | highest = Some(version); |
| 2329 | } |
| 2330 | offset = start; |
| 2331 | } |
| 2332 | |
| 2333 | highest |
| 2334 | } |
| 2335 | |
| 2336 | fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> { |
| 2337 | if needle.is_empty() || haystack.len() < needle.len() { |
| 2338 | return None; |
| 2339 | } |
| 2340 | haystack |
| 2341 | .windows(needle.len()) |
| 2342 | .position(|window| window == needle) |
| 2343 | } |
| 2344 | |
| 2345 | fn glibc_check_disabled() -> bool { |
| 2346 | [ |
| 2347 | "CODEWHALE_SKIP_GLIBC_CHECK", |
| 2348 | "DEEPSEEK_TUI_SKIP_GLIBC_CHECK", |
| 2349 | "DEEPSEEK_SKIP_GLIBC_CHECK", |
| 2350 | ] |
| 2351 | .into_iter() |
| 2352 | .any(|name| std::env::var_os(name).is_some_and(|value| value == std::ffi::OsStr::new("1"))) |
| 2353 | } |
| 2354 | |
| 2355 | fn preflight_downloaded_binary(asset_name: &str, bytes: &[u8]) -> Result<()> { |
| 2356 | // glibc preflight is Linux-only (#4241). Rust treats `target_os = "android"` |
| 2357 | // as distinct from `"linux"`, so Termux/Android builds skip this check entirely |
| 2358 | // — Android uses Bionic libc, not glibc. |
| 2359 | if !cfg!(target_os = "linux") || glibc_check_disabled() { |
| 2360 | return Ok(()); |
| 2361 | } |
| 2362 | |
| 2363 | let Some(required) = highest_required_glibc(bytes) else { |
| 2364 | return Ok(()); |
| 2365 | }; |
| 2366 | let host = detect_host_glibc(); |
| 2367 | if host.is_some_and(|host| host >= required) { |
| 2368 | return Ok(()); |
| 2369 | } |
| 2370 | |
| 2371 | bail!( |
| 2372 | "{}", |
| 2373 | glibc_compatibility_message(asset_name, required, host) |
| 2374 | ); |
| 2375 | } |
| 2376 | |
| 2377 | fn detect_host_glibc() -> Option<GlibcVersion> { |
| 2378 | let getconf = std::process::Command::new("getconf") |
| 2379 | .arg("GNU_LIBC_VERSION") |
| 2380 | .output() |
| 2381 | .ok() |
| 2382 | .filter(|output| output.status.success()) |
| 2383 | .and_then(|output| String::from_utf8(output.stdout).ok()) |
| 2384 | .and_then(|output| parse_glibc_version(&output)); |
| 2385 | if getconf.is_some() { |
| 2386 | return getconf; |
| 2387 | } |
| 2388 | |
| 2389 | std::process::Command::new("ldd") |
| 2390 | .arg("--version") |
| 2391 | .output() |
| 2392 | .ok() |
| 2393 | .filter(|output| output.status.success()) |
| 2394 | .and_then(|output| { |
| 2395 | let mut text = String::from_utf8_lossy(&output.stdout).to_string(); |
| 2396 | if text.trim().is_empty() { |
| 2397 | text = String::from_utf8_lossy(&output.stderr).to_string(); |
| 2398 | } |
| 2399 | parse_glibc_version(&text) |
| 2400 | }) |
| 2401 | } |
| 2402 | |
| 2403 | fn glibc_compatibility_message( |
| 2404 | asset_name: &str, |
| 2405 | required: GlibcVersion, |
| 2406 | host: Option<GlibcVersion>, |
| 2407 | ) -> String { |
| 2408 | let host_line = match host { |
| 2409 | Some(host) => format!( |
| 2410 | "this system has glibc {}, which is too old for that asset.", |
| 2411 | host.display() |
| 2412 | ), |
| 2413 | None => "this system does not appear to provide glibc.".to_string(), |
| 2414 | }; |
| 2415 | format!( |
| 2416 | "\ |
| 2417 | Prebuilt Codewhale asset `{asset_name}` requires GLIBC_{required}, but {host_line} |
| 2418 | |
| 2419 | Official Codewhale Linux release assets (x64 and arm64) are static musl builds |
| 2420 | with no glibc dependency, so this binary is not an official release asset. Check |
| 2421 | the download source, or install from source on this host instead: |
| 2422 | |
| 2423 | cargo install codewhale-cli --locked |
| 2424 | |
| 2425 | Set CODEWHALE_SKIP_GLIBC_CHECK=1 to bypass this preflight at your own risk.", |
| 2426 | required = required.display(), |
| 2427 | ) |
| 2428 | } |
| 2429 | |
| 2430 | /// Replace the running binary. |
| 2431 | /// |
| 2432 | /// Writes the new binary to a secure temp file in the target directory, then |
| 2433 | /// installs it in place. Unix can atomically replace the executable path. On |
| 2434 | /// Windows an atomic replace is tried first; when that fails, as it does for a |
| 2435 | /// running executable, the current file is renamed out of the way before the |
| 2436 | /// new binary moves into the original path. |
| 2437 | #[cfg(test)] |
| 2438 | fn replace_binary(target: &Path, new_bytes: &[u8]) -> Result<()> { |
| 2439 | replace_binary_with_validation(target, new_bytes, || Ok(())) |
| 2440 | } |
| 2441 | |
| 2442 | #[cfg(unix)] |
| 2443 | struct LinkedTempPath(Option<PathBuf>); |
| 2444 | |
| 2445 | #[cfg(unix)] |
| 2446 | impl LinkedTempPath { |
| 2447 | fn path(&self) -> &Path { |
| 2448 | self.0.as_deref().expect("staged hard-link path") |
| 2449 | } |
| 2450 | |
| 2451 | fn disarm(&mut self) { |
| 2452 | self.0 = None; |
| 2453 | } |
| 2454 | } |
| 2455 | |
| 2456 | #[cfg(unix)] |
| 2457 | impl Drop for LinkedTempPath { |
| 2458 | fn drop(&mut self) { |
| 2459 | if let Some(path) = self.0.take() { |
| 2460 | let _ = std::fs::remove_file(path); |
| 2461 | } |
| 2462 | } |
| 2463 | } |
| 2464 | |
| 2465 | enum StagedReplacement { |
| 2466 | Written(tempfile::NamedTempFile), |
| 2467 | #[cfg(unix)] |
| 2468 | Linked(LinkedTempPath), |
| 2469 | } |
| 2470 | |
| 2471 | impl StagedReplacement { |
| 2472 | fn path(&self) -> &Path { |
| 2473 | match self { |
| 2474 | Self::Written(file) => file.path(), |
| 2475 | #[cfg(unix)] |
| 2476 | Self::Linked(file) => file.path(), |
| 2477 | } |
| 2478 | } |
| 2479 | |
| 2480 | fn metadata(&self) -> std::io::Result<std::fs::Metadata> { |
| 2481 | match self { |
| 2482 | Self::Written(file) => file.as_file().metadata(), |
| 2483 | #[cfg(unix)] |
| 2484 | Self::Linked(file) => std::fs::metadata(file.path()), |
| 2485 | } |
| 2486 | } |
| 2487 | |
| 2488 | fn is_linked(&self) -> bool { |
| 2489 | match self { |
| 2490 | Self::Written(_) => false, |
| 2491 | #[cfg(unix)] |
| 2492 | Self::Linked(_) => true, |
| 2493 | } |
| 2494 | } |
| 2495 | |
| 2496 | fn sync_written(&self) -> std::io::Result<()> { |
| 2497 | match self { |
| 2498 | Self::Written(file) => file.as_file().sync_all(), |
| 2499 | #[cfg(unix)] |
| 2500 | Self::Linked(_) => Ok(()), |
| 2501 | } |
| 2502 | } |
| 2503 | } |
| 2504 | |
| 2505 | #[cfg(unix)] |
| 2506 | fn try_stage_hard_link(source: &Path, parent: &Path) -> Option<LinkedTempPath> { |
| 2507 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 2508 | static LINK_SEQ: AtomicU64 = AtomicU64::new(0); |
| 2509 | for _ in 0..8 { |
| 2510 | let seq = LINK_SEQ.fetch_add(1, Ordering::Relaxed); |
| 2511 | let candidate = parent.join(format!( |
| 2512 | ".codewhale-update-link-{}-{seq}", |
| 2513 | std::process::id() |
| 2514 | )); |
| 2515 | if std::fs::hard_link(source, &candidate).is_ok() { |
| 2516 | return Some(LinkedTempPath(Some(candidate))); |
| 2517 | } |
| 2518 | } |
| 2519 | None |
| 2520 | } |
| 2521 | |
| 2522 | fn stage_replacement_binary( |
| 2523 | parent: &Path, |
| 2524 | new_bytes: &[u8], |
| 2525 | link_source: Option<&Path>, |
| 2526 | ) -> Result<StagedReplacement> { |
| 2527 | #[cfg(unix)] |
| 2528 | if let Some(source) = link_source |
| 2529 | && let Some(linked) = try_stage_hard_link(source, parent) |
| 2530 | { |
| 2531 | return Ok(StagedReplacement::Linked(linked)); |
| 2532 | } |
| 2533 | #[cfg(not(unix))] |
| 2534 | let _ = link_source; |
| 2535 | let mut tmp = tempfile::Builder::new() |
| 2536 | .prefix(".codewhale-update-") |
| 2537 | .tempfile_in(parent) |
| 2538 | .with_context(|| format!("failed to create temp file in {}", parent.display()))?; |
| 2539 | tmp.write_all(new_bytes) |
| 2540 | .with_context(|| format!("failed to write temp file at {}", tmp.path().display()))?; |
| 2541 | Ok(StagedReplacement::Written(tmp)) |
| 2542 | } |
| 2543 | |
| 2544 | #[cfg(test)] |
| 2545 | fn replace_binary_with_validation<F>( |
| 2546 | target: &Path, |
| 2547 | new_bytes: &[u8], |
| 2548 | validate_before_replace: F, |
| 2549 | ) -> Result<()> |
| 2550 | where |
| 2551 | F: FnOnce() -> Result<()>, |
| 2552 | { |
| 2553 | replace_binary_with_validation_and_link_source(target, new_bytes, None, validate_before_replace) |
| 2554 | } |
| 2555 | |
| 2556 | fn replace_binary_with_validation_and_link_source<F>( |
| 2557 | target: &Path, |
| 2558 | new_bytes: &[u8], |
| 2559 | link_source: Option<&Path>, |
| 2560 | validate_before_replace: F, |
| 2561 | ) -> Result<()> |
| 2562 | where |
| 2563 | F: FnOnce() -> Result<()>, |
| 2564 | { |
| 2565 | replace_binary_with_validation_and_link_permission_setter( |
| 2566 | target, |
| 2567 | new_bytes, |
| 2568 | link_source, |
| 2569 | validate_before_replace, |
| 2570 | |path, permissions| std::fs::set_permissions(path, permissions), |
| 2571 | ) |
| 2572 | } |
| 2573 | |
| 2574 | /// `apply_permissions` is a seam for `std::fs::set_permissions` so tests can |
| 2575 | /// exercise permission-setup failures without host-specific filesystem state. |
| 2576 | #[cfg(test)] |
| 2577 | fn replace_binary_with_validation_and_permission_setter<F, P>( |
| 2578 | target: &Path, |
| 2579 | new_bytes: &[u8], |
| 2580 | validate_before_replace: F, |
| 2581 | apply_permissions: P, |
| 2582 | ) -> Result<()> |
| 2583 | where |
| 2584 | F: FnOnce() -> Result<()>, |
| 2585 | P: Fn(&Path, std::fs::Permissions) -> std::io::Result<()>, |
| 2586 | { |
| 2587 | replace_binary_with_validation_and_link_permission_setter( |
| 2588 | target, |
| 2589 | new_bytes, |
| 2590 | None, |
| 2591 | validate_before_replace, |
| 2592 | apply_permissions, |
| 2593 | ) |
| 2594 | } |
| 2595 | |
| 2596 | fn replace_binary_with_validation_and_link_permission_setter<F, P>( |
| 2597 | target: &Path, |
| 2598 | new_bytes: &[u8], |
| 2599 | link_source: Option<&Path>, |
| 2600 | validate_before_replace: F, |
| 2601 | apply_permissions: P, |
| 2602 | ) -> Result<()> |
| 2603 | where |
| 2604 | F: FnOnce() -> Result<()>, |
| 2605 | P: Fn(&Path, std::fs::Permissions) -> std::io::Result<()>, |
| 2606 | { |
| 2607 | let parent = replacement_parent(target); |
| 2608 | let staged = stage_replacement_binary(parent, new_bytes, link_source)?; |
| 2609 | |
| 2610 | // Permission setup is part of pre-replacement validation: a staged binary |
| 2611 | // that cannot receive correct permissions must never replace a working |
| 2612 | // target, so every failure below aborts before any destructive rename. |
| 2613 | if target.exists() { |
| 2614 | // Preserve permissions from the original binary. |
| 2615 | let meta = std::fs::metadata(target).with_context(|| { |
| 2616 | format!( |
| 2617 | "failed to read permissions of update target {}", |
| 2618 | target.display() |
| 2619 | ) |
| 2620 | })?; |
| 2621 | let needs_apply = !staged.is_linked() |
| 2622 | || staged |
| 2623 | .metadata() |
| 2624 | .map(|current| current.permissions() != meta.permissions()) |
| 2625 | .unwrap_or(true); |
| 2626 | if needs_apply { |
| 2627 | apply_permissions(staged.path(), meta.permissions()).with_context(|| { |
| 2628 | format!( |
| 2629 | "failed to set permissions on staged update {} before replacing {}", |
| 2630 | staged.path().display(), |
| 2631 | target.display() |
| 2632 | ) |
| 2633 | })?; |
| 2634 | } |
| 2635 | } else { |
| 2636 | #[cfg(unix)] |
| 2637 | { |
| 2638 | use std::os::unix::fs::PermissionsExt; |
| 2639 | let needs_apply = !staged.is_linked() |
| 2640 | || staged |
| 2641 | .metadata() |
| 2642 | .map(|current| current.permissions().mode() & 0o7777 != 0o755) |
| 2643 | .unwrap_or(true); |
| 2644 | if needs_apply { |
| 2645 | apply_permissions(staged.path(), std::fs::Permissions::from_mode(0o755)) |
| 2646 | .with_context(|| { |
| 2647 | format!( |
| 2648 | "failed to set permissions on staged update {} before installing {}", |
| 2649 | staged.path().display(), |
| 2650 | target.display() |
| 2651 | ) |
| 2652 | })?; |
| 2653 | } |
| 2654 | } |
| 2655 | } |
| 2656 | |
| 2657 | // Independently verify the staged binary is executable before it may |
| 2658 | // replace the target; a chmod that silently did not stick would otherwise |
| 2659 | // install a binary that cannot run. |
| 2660 | #[cfg(unix)] |
| 2661 | { |
| 2662 | use std::os::unix::fs::PermissionsExt; |
| 2663 | let staged_mode = staged |
| 2664 | .metadata() |
| 2665 | .with_context(|| { |
| 2666 | format!( |
| 2667 | "failed to inspect staged update at {}", |
| 2668 | staged.path().display() |
| 2669 | ) |
| 2670 | })? |
| 2671 | .permissions() |
| 2672 | .mode(); |
| 2673 | if staged_mode & 0o111 == 0 { |
| 2674 | bail!( |
| 2675 | "staged update {} is not executable (mode {:03o}); refusing to replace {}", |
| 2676 | staged.path().display(), |
| 2677 | staged_mode & 0o7777, |
| 2678 | target.display() |
| 2679 | ); |
| 2680 | } |
| 2681 | } |
| 2682 | |
| 2683 | staged.sync_written().with_context(|| { |
| 2684 | format!( |
| 2685 | "failed to sync staged update at {}", |
| 2686 | staged.path().display() |
| 2687 | ) |
| 2688 | })?; |
| 2689 | |
| 2690 | validate_before_replace()?; |
| 2691 | |
| 2692 | #[cfg(windows)] |
| 2693 | { |
| 2694 | let StagedReplacement::Written(tmp) = staged; |
| 2695 | let tmp = match tmp.persist(target) { |
| 2696 | Ok(_) => return Ok(()), |
| 2697 | Err(error) if !target.exists() => bail!( |
| 2698 | "failed to install new binary at {}: {}", |
| 2699 | target.display(), |
| 2700 | error.error |
| 2701 | ), |
| 2702 | Err(error) => error.file, |
| 2703 | }; |
| 2704 | let backup = backup_path_for(target); |
| 2705 | std::fs::rename(target, &backup).with_context(|| { |
| 2706 | format!( |
| 2707 | "failed to move current executable {} to {}", |
| 2708 | target.display(), |
| 2709 | backup.display() |
| 2710 | ) |
| 2711 | })?; |
| 2712 | if let Err(err) = tmp.persist(target) { |
| 2713 | if backup.exists() |
| 2714 | && let Err(restore_error) = std::fs::rename(&backup, target) |
| 2715 | { |
| 2716 | bail!( |
| 2717 | "failed to install new binary at {}: {}; restoring the previous binary also failed: {}. It is at {} — move it back by hand.", |
| 2718 | target.display(), |
| 2719 | err.error, |
| 2720 | restore_error, |
| 2721 | backup.display() |
| 2722 | ); |
| 2723 | } |
| 2724 | bail!( |
| 2725 | "failed to install new binary at {}: {}", |
| 2726 | target.display(), |
| 2727 | err.error |
| 2728 | ); |
| 2729 | } |
| 2730 | let _ = std::fs::remove_file(&backup); |
| 2731 | } |
| 2732 | |
| 2733 | #[cfg(not(windows))] |
| 2734 | { |
| 2735 | match staged { |
| 2736 | StagedReplacement::Written(tmp) => { |
| 2737 | tmp.persist(target) |
| 2738 | .map_err(|err| err.error) |
| 2739 | .with_context(|| { |
| 2740 | format!("failed to rename temp file to {}", target.display()) |
| 2741 | })?; |
| 2742 | } |
| 2743 | #[cfg(unix)] |
| 2744 | StagedReplacement::Linked(mut linked) => { |
| 2745 | std::fs::rename(linked.path(), target).with_context(|| { |
| 2746 | format!("failed to rename temp file to {}", target.display()) |
| 2747 | })?; |
| 2748 | linked.disarm(); |
| 2749 | } |
| 2750 | } |
| 2751 | } |
| 2752 | |
| 2753 | Ok(()) |
| 2754 | } |
| 2755 | |
| 2756 | #[cfg(windows)] |
| 2757 | fn backup_path_for(target: &Path) -> std::path::PathBuf { |
| 2758 | let pid = std::process::id(); |
| 2759 | for index in 0..100 { |
| 2760 | let mut candidate = target.to_path_buf(); |
| 2761 | let suffix = if index == 0 { |
| 2762 | format!("old-{pid}") |
| 2763 | } else { |
| 2764 | format!("old-{pid}-{index}") |
| 2765 | }; |
| 2766 | candidate.set_extension(suffix); |
| 2767 | if !candidate.exists() { |
| 2768 | return candidate; |
| 2769 | } |
| 2770 | } |
| 2771 | target.with_extension(format!("old-{pid}-fallback")) |
| 2772 | } |
| 2773 | |
| 2774 | #[cfg(test)] |
| 2775 | mod tests { |
| 2776 | use super::*; |
| 2777 | use codewhale_release::UPDATE_ALLOWED_HOSTS_ENV; |
| 2778 | use std::ffi::OsString; |
| 2779 | use std::io::{Read, Write}; |
| 2780 | use std::net::TcpListener; |
| 2781 | use std::sync::mpsc; |
| 2782 | use std::sync::{Mutex, MutexGuard}; |
| 2783 | use std::thread; |
| 2784 | |
| 2785 | /// Release-source environment variables are process-wide, so the tests that |
| 2786 | /// exercise override precedence take this lock and restore what they found. |
| 2787 | static UPDATE_ENV_LOCK: Mutex<()> = Mutex::new(()); |
| 2788 | |
| 2789 | #[test] |
| 2790 | fn undo_hint_is_judged_against_the_installed_version() { |
| 2791 | // 0.10.3 -> 0.10.4: the installed v0.10.4 refuses to roll back to v0.10.3. |
| 2792 | let hint = undo_hint_for(Some("0.10.3"), "v0.10.4"); |
| 2793 | assert!(hint.starts_with("No rollback:"), "{hint}"); |
| 2794 | // An updater older than v0.10.3 must not offer an undo the new binary refuses. |
| 2795 | assert!(undo_hint_for(Some("0.10.2"), "0.10.4").starts_with("No rollback:")); |
| 2796 | assert_eq!( |
| 2797 | undo_hint_for(Some("0.10.4"), "0.10.5"), |
| 2798 | "Undo: codewhale update --rollback (back to v0.10.4)" |
| 2799 | ); |
| 2800 | assert!(undo_hint_for(None, "0.10.5").starts_with("No rollback:")); |
| 2801 | } |
| 2802 | |
| 2803 | const UPDATE_ENV_VARS: &[&str] = &[ |
| 2804 | codewhale_release::RELEASE_BASE_URL_ENV, |
| 2805 | codewhale_release::LEGACY_RELEASE_BASE_URL_ENV, |
| 2806 | codewhale_release::DEEPSEEK_RELEASE_BASE_URL_ENV, |
| 2807 | codewhale_release::CNB_MIRROR_ENV, |
| 2808 | codewhale_release::UPDATE_VERSION_ENV, |
| 2809 | codewhale_release::LEGACY_TUI_UPDATE_VERSION_ENV, |
| 2810 | codewhale_release::LEGACY_UPDATE_VERSION_ENV, |
| 2811 | codewhale_release::install::INSTALL_METHOD_ENV, |
| 2812 | UPDATE_ALLOWED_HOSTS_ENV, |
| 2813 | TEST_RELEASE_PUBLIC_KEY_ENV, |
| 2814 | ]; |
| 2815 | const TEST_RELEASE_PUBLIC_KEY_ENV: &str = "CODEWHALE_TEST_RELEASE_PUBLIC_KEY"; |
| 2816 | |
| 2817 | struct UpdateEnvGuard { |
| 2818 | previous: Vec<(&'static str, Option<OsString>)>, |
| 2819 | _lock: MutexGuard<'static, ()>, |
| 2820 | } |
| 2821 | |
| 2822 | impl UpdateEnvGuard { |
| 2823 | fn clear() -> Self { |
| 2824 | let lock = UPDATE_ENV_LOCK |
| 2825 | .lock() |
| 2826 | .unwrap_or_else(|poisoned| poisoned.into_inner()); |
| 2827 | let previous = UPDATE_ENV_VARS |
| 2828 | .iter() |
| 2829 | .map(|&name| (name, std::env::var_os(name))) |
| 2830 | .collect(); |
| 2831 | for &name in UPDATE_ENV_VARS { |
| 2832 | // SAFETY: tests that mutate these process-wide vars hold UPDATE_ENV_LOCK. |
| 2833 | unsafe { std::env::remove_var(name) }; |
| 2834 | } |
| 2835 | Self { |
| 2836 | previous, |
| 2837 | _lock: lock, |
| 2838 | } |
| 2839 | } |
| 2840 | } |
| 2841 | |
| 2842 | impl Drop for UpdateEnvGuard { |
| 2843 | fn drop(&mut self) { |
| 2844 | for (name, value) in &self.previous { |
| 2845 | // SAFETY: the guard still holds UPDATE_ENV_LOCK while restoring state. |
| 2846 | unsafe { |
| 2847 | match value { |
| 2848 | Some(value) => std::env::set_var(name, value), |
| 2849 | None => std::env::remove_var(name), |
| 2850 | } |
| 2851 | } |
| 2852 | } |
| 2853 | } |
| 2854 | } |
| 2855 | |
| 2856 | fn set_update_env(name: &str, value: &str) { |
| 2857 | // SAFETY: callers hold an UpdateEnvGuard, which serializes env mutation. |
| 2858 | unsafe { std::env::set_var(name, value) }; |
| 2859 | } |
| 2860 | |
| 2861 | #[cfg(unix)] |
| 2862 | fn write_test_executable(path: &Path) { |
| 2863 | std::fs::write(path, b"test executable").unwrap(); |
| 2864 | use std::os::unix::fs::PermissionsExt; |
| 2865 | std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap(); |
| 2866 | } |
| 2867 | |
| 2868 | /// Write a stand-in installed binary: real update targets carry an |
| 2869 | /// executable mode on Unix, which the updater now preserves and verifies. |
| 2870 | fn write_installed_binary(path: &Path, bytes: &[u8]) { |
| 2871 | std::fs::write(path, bytes).unwrap(); |
| 2872 | #[cfg(unix)] |
| 2873 | { |
| 2874 | use std::os::unix::fs::PermissionsExt; |
| 2875 | std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap(); |
| 2876 | } |
| 2877 | } |
| 2878 | |
| 2879 | /// Verify the arch mapping used when constructing asset names. |
| 2880 | /// The mapping must use release-asset naming (arm64/x64), not Rust |
| 2881 | /// stdlib constants (aarch64/x86_64). |
| 2882 | #[test] |
| 2883 | fn test_arch_mapping() { |
| 2884 | assert_eq!(release_arch_for_rust_arch("aarch64"), "arm64"); |
| 2885 | assert_eq!(release_arch_for_rust_arch("x86_64"), "x64"); |
| 2886 | // Pass-through for unknown arches |
| 2887 | assert_eq!(release_arch_for_rust_arch("riscv64"), "riscv64"); |
| 2888 | // The currently-compiled arch maps to a release asset name |
| 2889 | let compiled_arch = std::env::consts::ARCH; |
| 2890 | let asset_arch = release_arch_for_rust_arch(compiled_arch); |
| 2891 | // Must not contain the raw Rust constant names |
| 2892 | assert!( |
| 2893 | !asset_arch.contains("aarch64") && !asset_arch.contains("x86_64"), |
| 2894 | "asset arch '{asset_arch}' still uses raw Rust constant name" |
| 2895 | ); |
| 2896 | } |
| 2897 | |
| 2898 | #[test] |
| 2899 | fn linux_riscv64_update_is_explicitly_unsupported() { |
| 2900 | let err = ensure_supported_release_target("linux", "riscv64") |
| 2901 | .expect_err("linux riscv64 should not claim a release asset"); |
| 2902 | let message = err.to_string(); |
| 2903 | assert!(message.contains("Linux riscv64 release assets are temporarily unavailable")); |
| 2904 | assert!(message.contains("rquickjs-sys 0.12.0")); |
| 2905 | ensure_supported_release_target("linux", "aarch64").unwrap(); |
| 2906 | ensure_supported_release_target("macos", "aarch64").unwrap(); |
| 2907 | } |
| 2908 | |
| 2909 | #[cfg(unix)] |
| 2910 | const TEST_ANDROID_MARKER: u64 = 0x1800; |
| 2911 | |
| 2912 | #[cfg(unix)] |
| 2913 | fn test_android_mapping_line(path: &Path, permissions: &str) -> String { |
| 2914 | use std::os::unix::fs::MetadataExt; |
| 2915 | |
| 2916 | let metadata = std::fs::metadata(path).unwrap(); |
| 2917 | let (device_major, device_minor) = android_device_parts(metadata.dev()); |
| 2918 | format!( |
| 2919 | "1000-2000 {permissions} 00000000 {:x}:{:x} {} {}\n", |
| 2920 | device_major, |
| 2921 | device_minor, |
| 2922 | metadata.ino(), |
| 2923 | path.display() |
| 2924 | ) |
| 2925 | } |
| 2926 | |
| 2927 | #[cfg(unix)] |
| 2928 | #[test] |
| 2929 | fn android_loaded_image_resolves_agreed_mapping() { |
| 2930 | let dir = tempfile::TempDir::new().unwrap(); |
| 2931 | let executable = dir.path().join("codewhale"); |
| 2932 | write_test_executable(&executable); |
| 2933 | let maps = test_android_mapping_line(&executable, "r-xp"); |
| 2934 | |
| 2935 | let resolved = |
| 2936 | resolve_android_loaded_executable_report(&maps, TEST_ANDROID_MARKER, &executable) |
| 2937 | .unwrap(); |
| 2938 | |
| 2939 | assert_eq!(resolved, executable.canonicalize().unwrap()); |
| 2940 | assert_eq!(update_plan_for_exe(&resolved).target_paths[0], resolved); |
| 2941 | } |
| 2942 | |
| 2943 | #[cfg(unix)] |
| 2944 | #[test] |
| 2945 | fn android_loaded_image_canonicalizes_symlink_and_sibling_policy() { |
| 2946 | use std::os::unix::fs::symlink; |
| 2947 | |
| 2948 | let dir = tempfile::TempDir::new().unwrap(); |
| 2949 | let canonical_dir = dir.path().join("canonical"); |
| 2950 | let install_dir = dir.path().join("install"); |
| 2951 | std::fs::create_dir(&canonical_dir).unwrap(); |
| 2952 | std::fs::create_dir(&install_dir).unwrap(); |
| 2953 | let canonical_dispatcher = canonical_dir.join("codewhale"); |
| 2954 | let canonical_tui = canonical_dir.join("codewhale-tui"); |
| 2955 | let invoked = install_dir.join("codewhale"); |
| 2956 | write_test_executable(&canonical_dispatcher); |
| 2957 | write_test_executable(&canonical_tui); |
| 2958 | symlink(&canonical_dispatcher, &invoked).unwrap(); |
| 2959 | let maps = test_android_mapping_line(&invoked, "r-xp"); |
| 2960 | |
| 2961 | let resolved = |
| 2962 | resolve_android_loaded_executable_report(&maps, TEST_ANDROID_MARKER, &invoked).unwrap(); |
| 2963 | let target_paths = update_plan_for_exe(&resolved).target_paths; |
| 2964 | |
| 2965 | assert_eq!( |
| 2966 | target_paths, |
| 2967 | vec![ |
| 2968 | canonical_dispatcher.canonicalize().unwrap(), |
| 2969 | canonical_tui.canonicalize().unwrap() |
| 2970 | ] |
| 2971 | ); |
| 2972 | assert!(!target_paths.contains(&invoked)); |
| 2973 | } |
| 2974 | |
| 2975 | #[cfg(unix)] |
| 2976 | #[test] |
| 2977 | fn android_loaded_image_requires_marker_mapping() { |
| 2978 | let dir = tempfile::TempDir::new().unwrap(); |
| 2979 | let executable = dir.path().join("codewhale"); |
| 2980 | write_test_executable(&executable); |
| 2981 | let maps = test_android_mapping_line(&executable, "r-xp"); |
| 2982 | |
| 2983 | let error = resolve_android_loaded_executable_report(&maps, 0x3000, &executable) |
| 2984 | .expect_err("a marker outside every mapping must fail closed"); |
| 2985 | |
| 2986 | assert!( |
| 2987 | error.to_string().contains("no /proc/self/maps row"), |
| 2988 | "unexpected error: {error:#}" |
| 2989 | ); |
| 2990 | } |
| 2991 | |
| 2992 | #[cfg(unix)] |
| 2993 | #[test] |
| 2994 | fn android_loaded_image_requires_executable_mapping() { |
| 2995 | let dir = tempfile::TempDir::new().unwrap(); |
| 2996 | let executable = dir.path().join("codewhale"); |
| 2997 | write_test_executable(&executable); |
| 2998 | let maps = test_android_mapping_line(&executable, "rw-p"); |
| 2999 | |
| 3000 | let error = |
| 3001 | resolve_android_loaded_executable_report(&maps, TEST_ANDROID_MARKER, &executable) |
| 3002 | .expect_err("a non-executable marker mapping must fail closed"); |
| 3003 | |
| 3004 | assert!( |
| 3005 | error |
| 3006 | .to_string() |
| 3007 | .contains("mapping for updater marker is not executable"), |
| 3008 | "unexpected error: {error:#}" |
| 3009 | ); |
| 3010 | } |
| 3011 | |
| 3012 | #[cfg(unix)] |
| 3013 | #[test] |
| 3014 | fn android_loaded_image_rejects_anonymous_mapping() { |
| 3015 | let dir = tempfile::TempDir::new().unwrap(); |
| 3016 | let executable = dir.path().join("codewhale"); |
| 3017 | write_test_executable(&executable); |
| 3018 | let maps = "1000-2000 r-xp 00000000 00:00 0\n"; |
| 3019 | |
| 3020 | let error = |
| 3021 | resolve_android_loaded_executable_report(maps, TEST_ANDROID_MARKER, &executable) |
| 3022 | .expect_err("an anonymous marker mapping must fail closed"); |
| 3023 | |
| 3024 | assert!( |
| 3025 | error.to_string().contains("has no file inode"), |
| 3026 | "unexpected error: {error:#}" |
| 3027 | ); |
| 3028 | } |
| 3029 | |
| 3030 | #[cfg(unix)] |
| 3031 | #[test] |
| 3032 | fn android_loaded_image_rejects_relative_or_deleted_paths() { |
| 3033 | let dir = tempfile::TempDir::new().unwrap(); |
| 3034 | let executable = dir.path().join("codewhale"); |
| 3035 | write_test_executable(&executable); |
| 3036 | let metadata = std::fs::metadata(&executable).unwrap(); |
| 3037 | use std::os::unix::fs::MetadataExt; |
| 3038 | let (device_major, device_minor) = android_device_parts(metadata.dev()); |
| 3039 | let relative_maps = format!( |
| 3040 | "1000-2000 r-xp 00000000 {:x}:{:x} {} codewhale\n", |
| 3041 | device_major, |
| 3042 | device_minor, |
| 3043 | metadata.ino() |
| 3044 | ); |
| 3045 | let deleted = PathBuf::from(format!("{} (deleted)", executable.display())); |
| 3046 | |
| 3047 | let relative_error = resolve_android_loaded_executable_report( |
| 3048 | &relative_maps, |
| 3049 | TEST_ANDROID_MARKER, |
| 3050 | &executable, |
| 3051 | ) |
| 3052 | .expect_err("a relative maps pathname must fail closed"); |
| 3053 | let deleted_error = resolve_android_loaded_executable_report( |
| 3054 | &test_android_mapping_line(&executable, "r-xp"), |
| 3055 | TEST_ANDROID_MARKER, |
| 3056 | &deleted, |
| 3057 | ) |
| 3058 | .expect_err("a deleted dladdr pathname must fail closed"); |
| 3059 | |
| 3060 | assert!(relative_error.to_string().contains("non-absolute")); |
| 3061 | assert!(deleted_error.to_string().contains("deleted loaded image")); |
| 3062 | } |
| 3063 | |
| 3064 | #[cfg(unix)] |
| 3065 | #[test] |
| 3066 | fn android_loaded_image_rejects_linker_and_symlink_to_linker() { |
| 3067 | use std::os::unix::fs::symlink; |
| 3068 | |
| 3069 | let dir = tempfile::TempDir::new().unwrap(); |
| 3070 | let runtime_linker = dir.path().join("linker64"); |
| 3071 | let invoked = dir.path().join("codewhale"); |
| 3072 | write_test_executable(&runtime_linker); |
| 3073 | symlink(&runtime_linker, &invoked).unwrap(); |
| 3074 | let maps = test_android_mapping_line(&invoked, "r-xp"); |
| 3075 | |
| 3076 | let direct_error = resolve_android_loaded_executable_report( |
| 3077 | &maps, |
| 3078 | TEST_ANDROID_MARKER, |
| 3079 | Path::new("/system/bin/linker64"), |
| 3080 | ) |
| 3081 | .expect_err("a directly reported Bionic linker must fail closed"); |
| 3082 | let symlink_error = |
| 3083 | resolve_android_loaded_executable_report(&maps, TEST_ANDROID_MARKER, &invoked) |
| 3084 | .expect_err("a symlink to a linker must fail closed"); |
| 3085 | |
| 3086 | assert!( |
| 3087 | direct_error |
| 3088 | .to_string() |
| 3089 | .contains("identifies runtime linker") |
| 3090 | ); |
| 3091 | assert!( |
| 3092 | symlink_error |
| 3093 | .to_string() |
| 3094 | .contains("resolved to runtime linker") |
| 3095 | ); |
| 3096 | } |
| 3097 | |
| 3098 | #[cfg(unix)] |
| 3099 | #[test] |
| 3100 | fn android_linker_name_recognizes_bionic_loader_variants() { |
| 3101 | for name in [ |
| 3102 | "linker", |
| 3103 | "linker64", |
| 3104 | "linker_asan", |
| 3105 | "linker_asan64", |
| 3106 | "linker_hwasan", |
| 3107 | "linker_hwasan64", |
| 3108 | ] { |
| 3109 | assert!( |
| 3110 | is_android_linker_name( |
| 3111 | Path::new("/apex/com.android.runtime/bin") |
| 3112 | .join(name) |
| 3113 | .as_path() |
| 3114 | ), |
| 3115 | "{name} must never become an updater target" |
| 3116 | ); |
| 3117 | } |
| 3118 | assert!(!is_android_linker_name(Path::new("codewhale"))); |
| 3119 | } |
| 3120 | |
| 3121 | #[cfg(unix)] |
| 3122 | #[test] |
| 3123 | fn android_loaded_image_rejects_authority_disagreement() { |
| 3124 | let dir = tempfile::TempDir::new().unwrap(); |
| 3125 | let mapped = dir.path().join("mapped-codewhale"); |
| 3126 | let dladdr = dir.path().join("dladdr-codewhale"); |
| 3127 | write_test_executable(&mapped); |
| 3128 | write_test_executable(&dladdr); |
| 3129 | let maps = test_android_mapping_line(&mapped, "r-xp"); |
| 3130 | |
| 3131 | let error = resolve_android_loaded_executable_report(&maps, TEST_ANDROID_MARKER, &dladdr) |
| 3132 | .expect_err("dladdr and maps path disagreement must fail closed"); |
| 3133 | |
| 3134 | assert!( |
| 3135 | error.to_string().contains("authorities disagree"), |
| 3136 | "unexpected error: {error:#}" |
| 3137 | ); |
| 3138 | } |
| 3139 | |
| 3140 | #[cfg(unix)] |
| 3141 | #[test] |
| 3142 | fn android_loaded_image_rejects_non_executable_file() { |
| 3143 | let dir = tempfile::TempDir::new().unwrap(); |
| 3144 | let executable = dir.path().join("codewhale"); |
| 3145 | std::fs::write(&executable, b"not executable").unwrap(); |
| 3146 | let maps = test_android_mapping_line(&executable, "r-xp"); |
| 3147 | |
| 3148 | let error = |
| 3149 | resolve_android_loaded_executable_report(&maps, TEST_ANDROID_MARKER, &executable) |
| 3150 | .expect_err("a non-executable target file must fail closed"); |
| 3151 | |
| 3152 | assert!( |
| 3153 | error.to_string().contains("not an executable regular file"), |
| 3154 | "unexpected error: {error:#}" |
| 3155 | ); |
| 3156 | } |
| 3157 | |
| 3158 | #[cfg(unix)] |
| 3159 | #[test] |
| 3160 | fn android_loaded_image_rejects_device_inode_mismatch() { |
| 3161 | let dir = tempfile::TempDir::new().unwrap(); |
| 3162 | let executable = dir.path().join("codewhale"); |
| 3163 | write_test_executable(&executable); |
| 3164 | let metadata = std::fs::metadata(&executable).unwrap(); |
| 3165 | use std::os::unix::fs::MetadataExt; |
| 3166 | let (device_major, device_minor) = android_device_parts(metadata.dev()); |
| 3167 | let maps = format!( |
| 3168 | "1000-2000 r-xp 00000000 {:x}:{:x} {} {}\n", |
| 3169 | device_major, |
| 3170 | device_minor, |
| 3171 | metadata.ino() + 1, |
| 3172 | executable.display() |
| 3173 | ); |
| 3174 | |
| 3175 | let error = |
| 3176 | resolve_android_loaded_executable_report(&maps, TEST_ANDROID_MARKER, &executable) |
| 3177 | .expect_err("a different maps device/inode must fail closed"); |
| 3178 | |
| 3179 | assert!( |
| 3180 | error.to_string().contains("loaded-image identity changed"), |
| 3181 | "unexpected error: {error:#}" |
| 3182 | ); |
| 3183 | } |
| 3184 | |
| 3185 | #[cfg(unix)] |
| 3186 | #[test] |
| 3187 | fn android_loaded_image_recheck_detects_pre_replace_swap() { |
| 3188 | let dir = tempfile::TempDir::new().unwrap(); |
| 3189 | let candidate = dir.path().join("codewhale"); |
| 3190 | let replacement = dir.path().join("replacement"); |
| 3191 | write_test_executable(&candidate); |
| 3192 | let maps = test_android_mapping_line(&candidate, "r-xp"); |
| 3193 | |
| 3194 | write_test_executable(&replacement); |
| 3195 | std::fs::rename(&replacement, &candidate).unwrap(); |
| 3196 | let error = |
| 3197 | resolve_android_loaded_executable_report(&maps, TEST_ANDROID_MARKER, &candidate) |
| 3198 | .expect_err("a path swap after download must fail before replacement"); |
| 3199 | |
| 3200 | assert!( |
| 3201 | error.to_string().contains("loaded-image identity changed"), |
| 3202 | "unexpected error: {error:#}" |
| 3203 | ); |
| 3204 | } |
| 3205 | |
| 3206 | #[cfg(unix)] |
| 3207 | #[test] |
| 3208 | fn android_identity_preflight_prevents_all_paired_replacements() { |
| 3209 | let dir = tempfile::TempDir::new().unwrap(); |
| 3210 | let primary = dir.path().join("codewhale"); |
| 3211 | let sibling = dir.path().join("codewhale-tui"); |
| 3212 | let swapped_primary = dir.path().join("swapped-primary"); |
| 3213 | |
| 3214 | write_test_executable(&primary); |
| 3215 | std::fs::write(&primary, b"original running primary").unwrap(); |
| 3216 | let maps = test_android_mapping_line(&primary, "r-xp"); |
| 3217 | write_test_executable(&sibling); |
| 3218 | std::fs::write(&sibling, b"original sibling").unwrap(); |
| 3219 | write_test_executable(&swapped_primary); |
| 3220 | std::fs::write(&swapped_primary, b"externally swapped primary").unwrap(); |
| 3221 | std::fs::rename(&swapped_primary, &primary).unwrap(); |
| 3222 | |
| 3223 | let target_paths = vec![primary.clone(), sibling.clone()]; |
| 3224 | let error = replace_verified_downloads(&target_paths, b"downloaded binary", |_| { |
| 3225 | resolve_android_loaded_executable_report(&maps, TEST_ANDROID_MARKER, &primary) |
| 3226 | .map(|_| ()) |
| 3227 | }) |
| 3228 | .expect_err("identity mismatch must fail before either binary changes"); |
| 3229 | |
| 3230 | assert!( |
| 3231 | error.to_string().contains("loaded-image identity changed"), |
| 3232 | "unexpected error: {error:#}" |
| 3233 | ); |
| 3234 | assert_eq!( |
| 3235 | std::fs::read(&primary).unwrap(), |
| 3236 | b"externally swapped primary" |
| 3237 | ); |
| 3238 | assert_eq!(std::fs::read(&sibling).unwrap(), b"original sibling"); |
| 3239 | } |
| 3240 | |
| 3241 | #[cfg(unix)] |
| 3242 | #[test] |
| 3243 | fn android_identity_recheck_before_sibling_prevents_pair_split() { |
| 3244 | use std::cell::Cell; |
| 3245 | |
| 3246 | let dir = tempfile::TempDir::new().unwrap(); |
| 3247 | let primary = dir.path().join("codewhale"); |
| 3248 | let sibling = dir.path().join("codewhale-tui"); |
| 3249 | let swapped_primary = dir.path().join("swapped-primary"); |
| 3250 | write_test_executable(&primary); |
| 3251 | std::fs::write(&primary, b"original running primary").unwrap(); |
| 3252 | let maps = test_android_mapping_line(&primary, "r-xp"); |
| 3253 | write_test_executable(&sibling); |
| 3254 | std::fs::write(&sibling, b"original sibling").unwrap(); |
| 3255 | write_test_executable(&swapped_primary); |
| 3256 | std::fs::write(&swapped_primary, b"externally swapped primary").unwrap(); |
| 3257 | |
| 3258 | let target_paths = vec![primary.clone(), sibling.clone()]; |
| 3259 | let validation_calls = Cell::new(0); |
| 3260 | let error = replace_verified_downloads(&target_paths, b"downloaded binary", |_| { |
| 3261 | let call = validation_calls.get() + 1; |
| 3262 | validation_calls.set(call); |
| 3263 | if call <= target_paths.len() { |
| 3264 | return Ok(()); |
| 3265 | } |
| 3266 | std::fs::rename(&swapped_primary, &primary).unwrap(); |
| 3267 | resolve_android_loaded_executable_report(&maps, TEST_ANDROID_MARKER, &primary) |
| 3268 | .map(|_| ()) |
| 3269 | }) |
| 3270 | .expect_err("identity mismatch must fail before the staged sibling persists"); |
| 3271 | |
| 3272 | assert_eq!(validation_calls.get(), 3); |
| 3273 | assert!( |
| 3274 | error.to_string().contains("loaded-image identity changed"), |
| 3275 | "unexpected error: {error:#}" |
| 3276 | ); |
| 3277 | assert_eq!( |
| 3278 | std::fs::read(&primary).unwrap(), |
| 3279 | b"externally swapped primary" |
| 3280 | ); |
| 3281 | assert_eq!(std::fs::read(&sibling).unwrap(), b"original sibling"); |
| 3282 | } |
| 3283 | |
| 3284 | #[cfg(unix)] |
| 3285 | #[test] |
| 3286 | fn android_identity_jit_recheck_runs_after_staging_before_persist() { |
| 3287 | use std::cell::Cell; |
| 3288 | |
| 3289 | let dir = tempfile::TempDir::new().unwrap(); |
| 3290 | let primary = dir.path().join("codewhale"); |
| 3291 | let swapped_primary = dir.path().join("swapped-primary"); |
| 3292 | write_test_executable(&primary); |
| 3293 | std::fs::write(&primary, b"original running primary").unwrap(); |
| 3294 | let maps = test_android_mapping_line(&primary, "r-xp"); |
| 3295 | write_test_executable(&swapped_primary); |
| 3296 | std::fs::write(&swapped_primary, b"externally swapped primary").unwrap(); |
| 3297 | |
| 3298 | let target_paths = vec![primary.clone()]; |
| 3299 | let validation_calls = Cell::new(0); |
| 3300 | let error = replace_verified_downloads(&target_paths, b"downloaded binary", |_| { |
| 3301 | let call = validation_calls.get() + 1; |
| 3302 | validation_calls.set(call); |
| 3303 | if call == 1 { |
| 3304 | return Ok(()); |
| 3305 | } |
| 3306 | std::fs::rename(&swapped_primary, &primary).unwrap(); |
| 3307 | resolve_android_loaded_executable_report(&maps, TEST_ANDROID_MARKER, &primary) |
| 3308 | .map(|_| ()) |
| 3309 | }) |
| 3310 | .expect_err("the post-staging identity swap must fail before persist"); |
| 3311 | |
| 3312 | assert_eq!(validation_calls.get(), 2); |
| 3313 | assert!( |
| 3314 | error.to_string().contains("loaded-image identity changed"), |
| 3315 | "unexpected error: {error:#}" |
| 3316 | ); |
| 3317 | assert_eq!( |
| 3318 | std::fs::read(&primary).unwrap(), |
| 3319 | b"externally swapped primary" |
| 3320 | ); |
| 3321 | assert!( |
| 3322 | std::fs::read_dir(dir.path()).unwrap().all(|entry| { |
| 3323 | !entry |
| 3324 | .unwrap() |
| 3325 | .file_name() |
| 3326 | .to_string_lossy() |
| 3327 | .starts_with(".codewhale-update-") |
| 3328 | }), |
| 3329 | "failed validation must clean the staged temp file" |
| 3330 | ); |
| 3331 | } |
| 3332 | |
| 3333 | /// Every command name resolves to the sole implementation asset. |
| 3334 | #[test] |
| 3335 | fn every_invocation_name_uses_codewhale_release_asset() { |
| 3336 | for command in [ |
| 3337 | "codewhale", |
| 3338 | "codewhale.exe", |
| 3339 | "codew", |
| 3340 | "codew.exe", |
| 3341 | "codewhale-tui", |
| 3342 | "CodeWhale-TUI.exe", |
| 3343 | "deepseek", |
| 3344 | "deepseek-tui", |
| 3345 | "other-binary", |
| 3346 | ] { |
| 3347 | assert_eq!( |
| 3348 | release_asset_stem_for(Path::new(command), "macos", "aarch64"), |
| 3349 | "codewhale-macos-arm64" |
| 3350 | ); |
| 3351 | } |
| 3352 | } |
| 3353 | |
| 3354 | #[test] |
| 3355 | fn test_is_legacy_binary_detection() { |
| 3356 | assert!(is_legacy_binary(Path::new("deepseek"))); |
| 3357 | assert!(is_legacy_binary(Path::new("deepseek-tui"))); |
| 3358 | assert!(is_legacy_binary(Path::new("/usr/local/bin/deepseek"))); |
| 3359 | assert!(is_legacy_binary(Path::new("/usr/local/bin/deepseek-tui"))); |
| 3360 | assert!(is_legacy_binary(Path::new("DeepSeek.exe"))); |
| 3361 | assert!(is_legacy_binary(Path::new("DeepSeek-TUI.exe"))); |
| 3362 | assert!(!is_legacy_binary(Path::new("codewhale"))); |
| 3363 | assert!(!is_legacy_binary(Path::new("codewhale-tui"))); |
| 3364 | assert!(!is_legacy_binary(Path::new("codew"))); |
| 3365 | } |
| 3366 | |
| 3367 | #[test] |
| 3368 | fn package_managed_answers_name_their_owner_in_one_line() { |
| 3369 | for (method, exe, command) in [ |
| 3370 | ( |
| 3371 | InstallMethod::Npm, |
| 3372 | "/usr/local/lib/node_modules/codewhale/bin/codewhale", |
| 3373 | "npm install -g codewhale@latest", |
| 3374 | ), |
| 3375 | ( |
| 3376 | InstallMethod::Homebrew, |
| 3377 | "/opt/homebrew/Cellar/codewhale/0.10.4/bin/codewhale", |
| 3378 | "brew upgrade codewhale", |
| 3379 | ), |
| 3380 | ( |
| 3381 | InstallMethod::Cargo, |
| 3382 | "/home/u/.cargo/bin/codewhale", |
| 3383 | "cargo install codewhale-cli --locked --force", |
| 3384 | ), |
| 3385 | ( |
| 3386 | InstallMethod::Omarchy, |
| 3387 | "/usr/bin/codewhale", |
| 3388 | "omarchy update", |
| 3389 | ), |
| 3390 | ] { |
| 3391 | let answer = installs::update_answer(method, Path::new(exe)); |
| 3392 | let exact = installs::manager_update_command(method, Path::new(exe)); |
| 3393 | assert!(exact.starts_with(command), "{exact}"); |
| 3394 | assert!(answer.contains(&format!("`{exact}`")), "{answer}"); |
| 3395 | assert!(answer.contains("cannot update itself"), "{answer}"); |
| 3396 | assert!(!answer.contains('\n'), "{answer}"); |
| 3397 | } |
| 3398 | assert!( |
| 3399 | installs::update_answer( |
| 3400 | InstallMethod::Binary, |
| 3401 | Path::new("/home/u/.local/bin/codewhale") |
| 3402 | ) |
| 3403 | .contains("updates itself") |
| 3404 | ); |
| 3405 | } |
| 3406 | |
| 3407 | #[test] |
| 3408 | fn binary_override_cannot_authorize_a_known_package_install() { |
| 3409 | let _env = UpdateEnvGuard::clear(); |
| 3410 | set_update_env(codewhale_release::install::INSTALL_METHOD_ENV, "binary"); |
| 3411 | for (path, expected) in [ |
| 3412 | ( |
| 3413 | "/usr/local/lib/node_modules/codewhale/bin/codewhale", |
| 3414 | InstallMethod::Npm, |
| 3415 | ), |
| 3416 | ( |
| 3417 | "/opt/homebrew/Cellar/codewhale/0.9.11/bin/codewhale", |
| 3418 | InstallMethod::Homebrew, |
| 3419 | ), |
| 3420 | ("/home/u/.cargo/bin/codewhale", InstallMethod::Cargo), |
| 3421 | ] { |
| 3422 | assert_eq!(InstallMethod::detect(Path::new(path)), expected); |
| 3423 | } |
| 3424 | } |
| 3425 | |
| 3426 | #[test] |
| 3427 | fn explicit_mirror_cannot_downgrade_or_download_an_older_release() { |
| 3428 | let _env = UpdateEnvGuard::clear(); |
| 3429 | set_update_env( |
| 3430 | codewhale_release::RELEASE_BASE_URL_ENV, |
| 3431 | "http://127.0.0.1:0", |
| 3432 | ); |
| 3433 | set_update_env(codewhale_release::UPDATE_VERSION_ENV, "0.0.1"); |
| 3434 | for beta in [false, true] { |
| 3435 | run_update(beta, false, None) |
| 3436 | .expect("an older pinned version must return before any download"); |
| 3437 | } |
| 3438 | } |
| 3439 | |
| 3440 | #[cfg(not(target_os = "android"))] |
| 3441 | fn test_update_identity(path: &Path) -> UpdateExecutableIdentity { |
| 3442 | UpdateExecutableIdentity { |
| 3443 | path: path.to_path_buf(), |
| 3444 | file_hash: sha256_hex(&std::fs::read(path).unwrap()), |
| 3445 | } |
| 3446 | } |
| 3447 | |
| 3448 | #[cfg(not(target_os = "android"))] |
| 3449 | #[test] |
| 3450 | fn unrelated_alias_fails_before_any_command_is_replaced() { |
| 3451 | let dir = tempfile::TempDir::new().unwrap(); |
| 3452 | let primary = dir.path().join("codewhale"); |
| 3453 | let alias = dir.path().join("codew"); |
| 3454 | std::fs::write(&primary, b"running bytes").unwrap(); |
| 3455 | std::fs::write(&alias, b"unrelated executable").unwrap(); |
| 3456 | let identity = test_update_identity(&primary); |
| 3457 | let error = |
| 3458 | replace_verified_downloads(&[primary.clone(), alias.clone()], b"new bytes", |target| { |
| 3459 | validate_primary_update_identity(&identity)?; |
| 3460 | validate_update_target(target, &identity) |
| 3461 | }) |
| 3462 | .unwrap_err(); |
| 3463 | assert!(error.to_string().contains("bytes differ"), "{error:#}"); |
| 3464 | assert_eq!(std::fs::read(primary).unwrap(), b"running bytes"); |
| 3465 | assert_eq!(std::fs::read(alias).unwrap(), b"unrelated executable"); |
| 3466 | } |
| 3467 | |
| 3468 | #[cfg(not(target_os = "android"))] |
| 3469 | #[test] |
| 3470 | fn cargo_bin_write_follows_the_cargo_record_like_detection() { |
| 3471 | let _env = UpdateEnvGuard::clear(); |
| 3472 | let root = tempfile::TempDir::new().unwrap(); |
| 3473 | let cargo = root.path().join(".cargo"); |
| 3474 | let bin = cargo.join("bin"); |
| 3475 | std::fs::create_dir_all(&bin).unwrap(); |
| 3476 | let primary = bin.join("codewhale"); |
| 3477 | let sibling = bin.join("codew"); |
| 3478 | for path in [&primary, &sibling] { |
| 3479 | std::fs::write(path, b"running bytes").unwrap(); |
| 3480 | } |
| 3481 | let identity = test_update_identity(&primary); |
| 3482 | let agrees = |target: &Path| { |
| 3483 | let writable = validate_update_target(target, &identity).is_ok(); |
| 3484 | assert_eq!( |
| 3485 | writable, |
| 3486 | InstallMethod::detect(target).supports_self_update(), |
| 3487 | "{}", |
| 3488 | target.display() |
| 3489 | ); |
| 3490 | writable |
| 3491 | }; |
| 3492 | |
| 3493 | assert!( |
| 3494 | !agrees(&primary), |
| 3495 | "no Cargo record: a .cargo/bin file stays Cargo's" |
| 3496 | ); |
| 3497 | |
| 3498 | std::fs::write( |
| 3499 | cargo.join(".crates.toml"), |
| 3500 | b"[v1]\n\"ripgrep 14.1.0 (registry+https://github.com/rust-lang/crates.io-index)\" = [\"rg\"]\n", |
| 3501 | ) |
| 3502 | .unwrap(); |
| 3503 | assert!(agrees(&primary), "a record that lists only other crates"); |
| 3504 | assert!(agrees(&sibling)); |
| 3505 | |
| 3506 | std::fs::write( |
| 3507 | cargo.join(".crates.toml"), |
| 3508 | b"[v1]\n\"codewhale-cli 0.10.5 (registry+https://github.com/rust-lang/crates.io-index)\" = [\"codewhale\"]\n", |
| 3509 | ) |
| 3510 | .unwrap(); |
| 3511 | assert!(!agrees(&primary), "Cargo lists this command"); |
| 3512 | let error = replace_verified_downloads( |
| 3513 | &[sibling.clone(), primary.clone()], |
| 3514 | b"new bytes", |
| 3515 | |target| validate_update_target(target, &identity), |
| 3516 | ) |
| 3517 | .unwrap_err(); |
| 3518 | assert!( |
| 3519 | error.to_string().contains("managed/system path"), |
| 3520 | "{error:#}" |
| 3521 | ); |
| 3522 | assert_eq!(std::fs::read(&primary).unwrap(), b"running bytes"); |
| 3523 | assert_eq!(std::fs::read(&sibling).unwrap(), b"running bytes"); |
| 3524 | |
| 3525 | std::fs::remove_file(cargo.join(".crates.toml")).unwrap(); |
| 3526 | std::fs::create_dir(cargo.join(".crates.toml")).unwrap(); |
| 3527 | assert!(!agrees(&primary), "an unreadable record fails closed"); |
| 3528 | } |
| 3529 | |
| 3530 | #[cfg(not(target_os = "android"))] |
| 3531 | #[test] |
| 3532 | fn desktop_primary_swap_is_detected_before_siblings_change() { |
| 3533 | let dir = tempfile::TempDir::new().unwrap(); |
| 3534 | let primary = dir.path().join("codewhale"); |
| 3535 | let alias = dir.path().join("codew"); |
| 3536 | for path in [&primary, &alias] { |
| 3537 | std::fs::write(path, b"running bytes").unwrap(); |
| 3538 | } |
| 3539 | let identity = test_update_identity(&primary); |
| 3540 | std::fs::write(&primary, b"a different build").unwrap(); |
| 3541 | let error = |
| 3542 | replace_verified_downloads(&[primary.clone(), alias.clone()], b"new bytes", |target| { |
| 3543 | validate_primary_update_identity(&identity)?; |
| 3544 | validate_update_target(target, &identity) |
| 3545 | }) |
| 3546 | .unwrap_err(); |
| 3547 | assert!(error.to_string().contains("path changed"), "{error:#}"); |
| 3548 | assert_eq!(std::fs::read(primary).unwrap(), b"a different build"); |
| 3549 | assert_eq!(std::fs::read(alias).unwrap(), b"running bytes"); |
| 3550 | } |
| 3551 | |
| 3552 | #[cfg(all(unix, not(target_os = "android")))] |
| 3553 | #[test] |
| 3554 | fn same_target_symlink_survives_and_foreign_or_broken_links_are_refused() { |
| 3555 | use std::os::unix::fs::symlink; |
| 3556 | let dir = tempfile::TempDir::new().unwrap(); |
| 3557 | let primary = dir.path().canonicalize().unwrap().join("codewhale"); |
| 3558 | let alias = primary.with_file_name("codew"); |
| 3559 | write_installed_binary(&primary, b"running bytes"); |
| 3560 | symlink("codewhale", &alias).unwrap(); |
| 3561 | let identity = test_update_identity(&primary); |
| 3562 | let plan = update_plan_for_exe(&primary); |
| 3563 | assert_eq!(plan.target_paths.as_slice(), std::slice::from_ref(&primary)); |
| 3564 | replace_verified_downloads(&plan.target_paths, b"new bytes", |target| { |
| 3565 | validate_primary_update_identity(&identity)?; |
| 3566 | validate_update_target(target, &identity) |
| 3567 | }) |
| 3568 | .unwrap(); |
| 3569 | assert!(std::fs::symlink_metadata(&alias).unwrap().is_symlink()); |
| 3570 | assert_eq!(std::fs::read(&alias).unwrap(), b"new bytes"); |
| 3571 | std::fs::remove_file(&alias).unwrap(); |
| 3572 | symlink("foreign", &alias).unwrap(); |
| 3573 | for exists in [false, true] { |
| 3574 | if exists { |
| 3575 | std::fs::write(primary.with_file_name("foreign"), b"other").unwrap(); |
| 3576 | } |
| 3577 | let plan = update_plan_for_exe(&primary); |
| 3578 | assert!(plan.target_paths.contains(&alias)); |
| 3579 | let identity = test_update_identity(&primary); |
| 3580 | assert!(validate_update_target(&alias, &identity).is_err()); |
| 3581 | assert!(std::fs::symlink_metadata(&alias).unwrap().is_symlink()); |
| 3582 | } |
| 3583 | } |
| 3584 | |
| 3585 | #[cfg(all(unix, not(target_os = "android")))] |
| 3586 | #[test] |
| 3587 | fn same_target_symlink_is_kept_when_the_install_dir_is_reached_through_a_symlink() { |
| 3588 | use std::os::unix::fs::symlink; |
| 3589 | let dir = tempfile::TempDir::new().unwrap(); |
| 3590 | let root = dir.path().canonicalize().unwrap(); |
| 3591 | let real_dir = root.join("real-bin"); |
| 3592 | std::fs::create_dir(&real_dir).unwrap(); |
| 3593 | let linked_dir = root.join("linked-bin"); |
| 3594 | symlink(&real_dir, &linked_dir).unwrap(); |
| 3595 | // `current_exe()` on macOS reports the path as reached, not resolved. |
| 3596 | let primary = linked_dir.join("codewhale"); |
| 3597 | write_installed_binary(&primary, b"running bytes"); |
| 3598 | symlink("codewhale", linked_dir.join("codew")).unwrap(); |
| 3599 | let plan = update_plan_for_exe(&primary); |
| 3600 | assert_eq!(plan.target_paths.as_slice(), std::slice::from_ref(&primary)); |
| 3601 | } |
| 3602 | |
| 3603 | #[test] |
| 3604 | fn legacy_binary_message_gives_copy_pasteable_migration_steps() { |
| 3605 | let message = legacy_binary_message(Path::new("/usr/local/bin/deepseek-tui")); |
| 3606 | |
| 3607 | assert!(message.contains("legacy deepseek/deepseek-tui command name")); |
| 3608 | assert!(message.contains("canonical `codewhale` command")); |
| 3609 | assert!(message.contains("DeepSeek provider support")); |
| 3610 | assert!(message.contains("is unchanged")); |
| 3611 | assert!(message.contains(GITHUB_MIGRATION_HELP)); |
| 3612 | assert!(!message.contains("This update will install")); |
| 3613 | assert!(message.contains("command -v codewhale codew")); |
| 3614 | assert!(message.contains("package manager")); |
| 3615 | assert!(!message.contains("uninstall")); |
| 3616 | assert!(message.contains("https://github.com/codewhale-hq/CodeWhale/releases/latest")); |
| 3617 | } |
| 3618 | |
| 3619 | #[test] |
| 3620 | fn legacy_dispatcher_update_targets_canonical_compatibility_commands() { |
| 3621 | let dir = tempfile::TempDir::new().unwrap(); |
| 3622 | let dispatcher = dir |
| 3623 | .path() |
| 3624 | .join(format!("deepseek{}", std::env::consts::EXE_SUFFIX)); |
| 3625 | let tui = dir |
| 3626 | .path() |
| 3627 | .join(format!("deepseek-tui{}", std::env::consts::EXE_SUFFIX)); |
| 3628 | std::fs::write(&dispatcher, b"legacy dispatcher").unwrap(); |
| 3629 | std::fs::write(&tui, b"legacy tui").unwrap(); |
| 3630 | |
| 3631 | let plan = update_plan_for_exe(&dispatcher); |
| 3632 | |
| 3633 | assert_eq!( |
| 3634 | plan.target_paths, |
| 3635 | vec![ |
| 3636 | dir.path() |
| 3637 | .join(format!("codewhale{}", std::env::consts::EXE_SUFFIX)), |
| 3638 | dir.path() |
| 3639 | .join(format!("codewhale-tui{}", std::env::consts::EXE_SUFFIX)) |
| 3640 | ] |
| 3641 | ); |
| 3642 | assert!(plan.asset_stem.starts_with("codewhale-")); |
| 3643 | assert!(!plan.asset_stem.starts_with("codewhale-tui-")); |
| 3644 | } |
| 3645 | |
| 3646 | #[test] |
| 3647 | fn legacy_tui_update_targets_canonical_compatibility_commands() { |
| 3648 | let dir = tempfile::TempDir::new().unwrap(); |
| 3649 | let dispatcher = dir |
| 3650 | .path() |
| 3651 | .join(format!("deepseek{}", std::env::consts::EXE_SUFFIX)); |
| 3652 | let tui = dir |
| 3653 | .path() |
| 3654 | .join(format!("deepseek-tui{}", std::env::consts::EXE_SUFFIX)); |
| 3655 | std::fs::write(&dispatcher, b"legacy dispatcher").unwrap(); |
| 3656 | std::fs::write(&tui, b"legacy tui").unwrap(); |
| 3657 | |
| 3658 | let plan = update_plan_for_exe(&tui); |
| 3659 | |
| 3660 | assert_eq!( |
| 3661 | plan.target_paths, |
| 3662 | vec![ |
| 3663 | dir.path() |
| 3664 | .join(format!("codewhale{}", std::env::consts::EXE_SUFFIX)), |
| 3665 | dir.path() |
| 3666 | .join(format!("codewhale-tui{}", std::env::consts::EXE_SUFFIX)) |
| 3667 | ] |
| 3668 | ); |
| 3669 | assert!(plan.asset_stem.starts_with("codewhale-")); |
| 3670 | assert!(!plan.asset_stem.starts_with("codewhale-tui-")); |
| 3671 | } |
| 3672 | |
| 3673 | #[test] |
| 3674 | fn test_release_asset_stem_for_supported_platforms() { |
| 3675 | let cases = [ |
| 3676 | ("codewhale", "macos", "aarch64", "codewhale-macos-arm64"), |
| 3677 | ("codewhale", "macos", "x86_64", "codewhale-macos-x64"), |
| 3678 | ("codewhale", "linux", "x86_64", "codewhale-linux-x64"), |
| 3679 | ("codewhale", "windows", "x86_64", "codewhale-windows-x64"), |
| 3680 | ("codewhale", "windows", "aarch64", "codewhale-windows-arm64"), |
| 3681 | ("codew", "macos", "aarch64", "codewhale-macos-arm64"), |
| 3682 | ("codewhale-tui", "linux", "x86_64", "codewhale-linux-x64"), |
| 3683 | ]; |
| 3684 | |
| 3685 | for (exe, os, arch, expected) in cases { |
| 3686 | assert_eq!(release_asset_stem_for(Path::new(exe), os, arch), expected); |
| 3687 | } |
| 3688 | } |
| 3689 | |
| 3690 | #[test] |
| 3691 | fn update_plan_includes_existing_compatibility_tui_for_primary() { |
| 3692 | let dir = tempfile::TempDir::new().unwrap(); |
| 3693 | let dispatcher = dir |
| 3694 | .path() |
| 3695 | .join(format!("codewhale{}", std::env::consts::EXE_SUFFIX)); |
| 3696 | let tui = dir |
| 3697 | .path() |
| 3698 | .join(format!("codewhale-tui{}", std::env::consts::EXE_SUFFIX)); |
| 3699 | std::fs::write(&dispatcher, b"dispatcher").unwrap(); |
| 3700 | std::fs::write(&tui, b"tui").unwrap(); |
| 3701 | |
| 3702 | let plan = update_plan_for_exe(&dispatcher); |
| 3703 | let paths = plan |
| 3704 | .target_paths |
| 3705 | .iter() |
| 3706 | .map(PathBuf::as_path) |
| 3707 | .collect::<Vec<_>>(); |
| 3708 | |
| 3709 | assert_eq!(paths, vec![dispatcher.as_path(), tui.as_path()]); |
| 3710 | assert!(plan.asset_stem.starts_with("codewhale-")); |
| 3711 | assert!(!plan.asset_stem.starts_with("codewhale-tui-")); |
| 3712 | } |
| 3713 | |
| 3714 | #[test] |
| 3715 | fn update_plan_skips_missing_compatibility_commands() { |
| 3716 | let dir = tempfile::TempDir::new().unwrap(); |
| 3717 | let dispatcher = dir |
| 3718 | .path() |
| 3719 | .join(format!("codewhale{}", std::env::consts::EXE_SUFFIX)); |
| 3720 | std::fs::write(&dispatcher, b"dispatcher").unwrap(); |
| 3721 | |
| 3722 | let plan = update_plan_for_exe(&dispatcher); |
| 3723 | |
| 3724 | assert_eq!(plan.target_paths, vec![dispatcher]); |
| 3725 | assert!(plan.asset_stem.starts_with("codewhale-")); |
| 3726 | } |
| 3727 | |
| 3728 | #[test] |
| 3729 | fn v094_three_command_install_updates_every_path_from_primary_bytes() { |
| 3730 | let dir = tempfile::TempDir::new().unwrap(); |
| 3731 | let primary = dir |
| 3732 | .path() |
| 3733 | .join(format!("codewhale{}", std::env::consts::EXE_SUFFIX)); |
| 3734 | let codew = dir |
| 3735 | .path() |
| 3736 | .join(format!("codew{}", std::env::consts::EXE_SUFFIX)); |
| 3737 | let legacy_tui = dir |
| 3738 | .path() |
| 3739 | .join(format!("codewhale-tui{}", std::env::consts::EXE_SUFFIX)); |
| 3740 | for path in [&primary, &codew, &legacy_tui] { |
| 3741 | write_installed_binary(path, b"v0.9.4 old bytes"); |
| 3742 | } |
| 3743 | |
| 3744 | let plan = update_plan_for_exe(&primary); |
| 3745 | assert_eq!( |
| 3746 | plan.target_paths, |
| 3747 | vec![primary.clone(), codew.clone(), legacy_tui.clone()] |
| 3748 | ); |
| 3749 | assert!(plan.asset_stem.starts_with("codewhale-")); |
| 3750 | assert!(!plan.asset_stem.contains("codewhale-tui")); |
| 3751 | |
| 3752 | replace_verified_downloads(&plan.target_paths, b"v0.9.5 primary bytes", |_| Ok(())) |
| 3753 | .unwrap(); |
| 3754 | |
| 3755 | for path in [&primary, &codew, &legacy_tui] { |
| 3756 | assert_eq!(std::fs::read(path).unwrap(), b"v0.9.5 primary bytes"); |
| 3757 | } |
| 3758 | assert_ne!(std::fs::read(codew).unwrap(), b"v0.9.4 old bytes"); |
| 3759 | } |
| 3760 | |
| 3761 | #[test] |
| 3762 | fn direct_alias_invocation_keeps_running_path_first_and_updates_primary() { |
| 3763 | let dir = tempfile::TempDir::new().unwrap(); |
| 3764 | let primary = dir |
| 3765 | .path() |
| 3766 | .join(format!("codewhale{}", std::env::consts::EXE_SUFFIX)); |
| 3767 | let codew = dir |
| 3768 | .path() |
| 3769 | .join(format!("codew{}", std::env::consts::EXE_SUFFIX)); |
| 3770 | let legacy_tui = dir |
| 3771 | .path() |
| 3772 | .join(format!("codewhale-tui{}", std::env::consts::EXE_SUFFIX)); |
| 3773 | for invoked in [&codew, &legacy_tui] { |
| 3774 | for path in [&primary, &codew, &legacy_tui] { |
| 3775 | write_installed_binary(path, b"old"); |
| 3776 | } |
| 3777 | let plan = update_plan_for_exe(invoked); |
| 3778 | assert_eq!(plan.target_paths.first(), Some(invoked)); |
| 3779 | assert!(plan.target_paths.contains(&primary)); |
| 3780 | assert!(plan.target_paths.contains(&codew)); |
| 3781 | assert!(plan.target_paths.contains(&legacy_tui)); |
| 3782 | assert!(plan.asset_stem.starts_with("codewhale-")); |
| 3783 | assert!(!plan.asset_stem.starts_with("codewhale-tui-")); |
| 3784 | |
| 3785 | replace_verified_downloads(&plan.target_paths, b"new primary bytes", |_| Ok(())) |
| 3786 | .unwrap(); |
| 3787 | for path in [&primary, &codew, &legacy_tui] { |
| 3788 | assert_eq!(std::fs::read(path).unwrap(), b"new primary bytes"); |
| 3789 | } |
| 3790 | } |
| 3791 | } |
| 3792 | |
| 3793 | #[test] |
| 3794 | fn test_asset_matching_accepts_only_the_raw_binary() { |
| 3795 | for (asset, binary, expected) in [ |
| 3796 | ("codewhale-macos-arm64", "codewhale-macos-arm64", true), |
| 3797 | ( |
| 3798 | "codewhale-tui-windows-x64.exe", |
| 3799 | "codewhale-tui-windows-x64", |
| 3800 | true, |
| 3801 | ), |
| 3802 | ( |
| 3803 | "codewhale-macos-arm64.tar.gz", |
| 3804 | "codewhale-macos-arm64", |
| 3805 | false, |
| 3806 | ), |
| 3807 | ("codewhale-macos-arm64.zip", "codewhale-macos-arm64", false), |
| 3808 | ("codewhale-macos-arm64.sig", "codewhale-macos-arm64", false), |
| 3809 | ( |
| 3810 | "codewhale-tui-windows-x64.exe.sha256", |
| 3811 | "codewhale-tui-windows-x64", |
| 3812 | false, |
| 3813 | ), |
| 3814 | ("codewhale-macos-aarch64", "codewhale-macos-arm64", false), |
| 3815 | ] { |
| 3816 | assert_eq!( |
| 3817 | asset_is_exact_platform_binary(asset, binary), |
| 3818 | expected, |
| 3819 | "{asset} vs {binary}" |
| 3820 | ); |
| 3821 | } |
| 3822 | } |
| 3823 | |
| 3824 | #[test] |
| 3825 | fn select_platform_asset_prefers_bare_binary_over_archive() { |
| 3826 | let release = Release { |
| 3827 | tag_name: "v0.8.8".to_string(), |
| 3828 | prerelease: false, |
| 3829 | assets: vec![ |
| 3830 | Asset { |
| 3831 | name: "codewhale-macos-arm64.tar.gz".to_string(), |
| 3832 | browser_download_url: "https://example.invalid/codewhale-macos-arm64.tar.gz" |
| 3833 | .to_string(), |
| 3834 | }, |
| 3835 | Asset { |
| 3836 | name: "codewhale-macos-arm64".to_string(), |
| 3837 | browser_download_url: "https://example.invalid/codewhale-macos-arm64" |
| 3838 | .to_string(), |
| 3839 | }, |
| 3840 | ], |
| 3841 | }; |
| 3842 | |
| 3843 | let asset = |
| 3844 | select_platform_asset(&release, "codewhale-macos-arm64").expect("platform asset"); |
| 3845 | |
| 3846 | assert_eq!(asset.name, "codewhale-macos-arm64"); |
| 3847 | } |
| 3848 | |
| 3849 | /// Audit R02-04: the updater installs the downloaded bytes verbatim, so a |
| 3850 | /// release that ships only an archive/signature/sidecar for this platform |
| 3851 | /// has no installable asset rather than one that bricks the binary. |
| 3852 | #[test] |
| 3853 | fn select_platform_asset_never_substitutes_an_archive_or_sidecar() { |
| 3854 | let release = Release { |
| 3855 | tag_name: "v0.8.8".to_string(), |
| 3856 | prerelease: false, |
| 3857 | assets: ["tar.gz", "zip", "sig", "sbom.json"] |
| 3858 | .into_iter() |
| 3859 | .map(|ext| Asset { |
| 3860 | name: format!("codewhale-macos-arm64.{ext}"), |
| 3861 | browser_download_url: format!( |
| 3862 | "https://example.invalid/codewhale-macos-arm64.{ext}" |
| 3863 | ), |
| 3864 | }) |
| 3865 | .collect(), |
| 3866 | }; |
| 3867 | |
| 3868 | assert!(select_platform_asset(&release, "codewhale-macos-arm64").is_none()); |
| 3869 | } |
| 3870 | |
| 3871 | #[test] |
| 3872 | fn test_sha256_hex_known_value() { |
| 3873 | let data = b"hello"; |
| 3874 | let hash = sha256_hex(data); |
| 3875 | assert_eq!( |
| 3876 | hash, |
| 3877 | "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" |
| 3878 | ); |
| 3879 | } |
| 3880 | |
| 3881 | #[test] |
| 3882 | fn test_sha256_hex_empty() { |
| 3883 | let hash = sha256_hex(b""); |
| 3884 | assert_eq!( |
| 3885 | hash, |
| 3886 | "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" |
| 3887 | ); |
| 3888 | } |
| 3889 | |
| 3890 | #[test] |
| 3891 | fn glibc_version_parser_reads_getconf_and_symbol_text() { |
| 3892 | assert_eq!( |
| 3893 | parse_glibc_version("glibc 2.35\n"), |
| 3894 | Some(GlibcVersion::new(2, 35, 0)) |
| 3895 | ); |
| 3896 | assert_eq!( |
| 3897 | parse_glibc_version("requires GLIBC_2.39"), |
| 3898 | Some(GlibcVersion::new(2, 39, 0)) |
| 3899 | ); |
| 3900 | assert_eq!(parse_glibc_version("not glibc"), None); |
| 3901 | } |
| 3902 | |
| 3903 | #[test] |
| 3904 | fn highest_required_glibc_finds_highest_binary_symbol() { |
| 3905 | let bytes = b"\0GLIBC_2.17\0other\0GLIBC_2.39\0GLIBC_2.35"; |
| 3906 | |
| 3907 | assert_eq!( |
| 3908 | highest_required_glibc(bytes), |
| 3909 | Some(GlibcVersion::new(2, 39, 0)) |
| 3910 | ); |
| 3911 | } |
| 3912 | |
| 3913 | #[test] |
| 3914 | fn glibc_compatibility_message_is_codewhale_branded_and_actionable() { |
| 3915 | let message = glibc_compatibility_message( |
| 3916 | "codewhale-linux-x64", |
| 3917 | GlibcVersion::new(2, 39, 0), |
| 3918 | Some(GlibcVersion::new(2, 35, 0)), |
| 3919 | ); |
| 3920 | |
| 3921 | assert!(message.contains("Prebuilt Codewhale asset `codewhale-linux-x64`")); |
| 3922 | assert!(message.contains("requires GLIBC_2.39")); |
| 3923 | assert!(message.contains("this system has glibc 2.35")); |
| 3924 | assert!(message.contains("cargo install codewhale-cli --locked")); |
| 3925 | assert!(message.contains("(x64 and arm64) are static musl builds")); |
| 3926 | assert!(!message.contains("GNU "), "no stale GNU-build claim"); |
| 3927 | } |
| 3928 | |
| 3929 | #[test] |
| 3930 | fn parse_checksum_manifest_accepts_sha256sum_format() { |
| 3931 | let manifest = "\ |
| 3932 | 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 codewhale-macos-arm64 |
| 3933 | E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855 *codewhale-windows-x64.exe |
| 3934 | "; |
| 3935 | let checksums = parse_checksum_manifest(manifest).expect("valid manifest"); |
| 3936 | |
| 3937 | assert_eq!( |
| 3938 | checksums.get("codewhale-macos-arm64").map(String::as_str), |
| 3939 | Some("2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824") |
| 3940 | ); |
| 3941 | assert_eq!( |
| 3942 | checksums |
| 3943 | .get("codewhale-windows-x64.exe") |
| 3944 | .map(String::as_str), |
| 3945 | Some("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") |
| 3946 | ); |
| 3947 | } |
| 3948 | |
| 3949 | #[test] |
| 3950 | fn parse_checksum_manifest_rejects_malformed_lines() { |
| 3951 | let err = parse_checksum_manifest("not-a-hash codewhale-macos-arm64") |
| 3952 | .expect_err("invalid manifest line should fail"); |
| 3953 | assert!( |
| 3954 | err.to_string().contains("invalid SHA256 manifest line"), |
| 3955 | "unexpected error: {err:#}" |
| 3956 | ); |
| 3957 | } |
| 3958 | |
| 3959 | #[test] |
| 3960 | fn expected_sha256_from_manifest_requires_matching_asset() { |
| 3961 | let manifest = |
| 3962 | "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 other-asset\n"; |
| 3963 | let err = expected_sha256_from_manifest(manifest, "codewhale-macos-arm64") |
| 3964 | .expect_err("missing asset should fail"); |
| 3965 | assert!( |
| 3966 | err.to_string() |
| 3967 | .contains("checksum manifest is missing codewhale-macos-arm64"), |
| 3968 | "unexpected error: {err:#}" |
| 3969 | ); |
| 3970 | } |
| 3971 | |
| 3972 | #[test] |
| 3973 | fn test_replace_binary_creates_and_replaces() { |
| 3974 | let dir = tempfile::TempDir::new().unwrap(); |
| 3975 | let target = dir.path().join("codewhale-test"); |
| 3976 | // Write initial content |
| 3977 | write_installed_binary(&target, b"old binary"); |
| 3978 | |
| 3979 | replace_binary(&target, b"new binary content").unwrap(); |
| 3980 | let content = std::fs::read_to_string(&target).unwrap(); |
| 3981 | assert_eq!(content, "new binary content"); |
| 3982 | } |
| 3983 | |
| 3984 | #[test] |
| 3985 | fn test_replace_binary_creates_new_file() { |
| 3986 | let dir = tempfile::TempDir::new().unwrap(); |
| 3987 | let target = dir.path().join("codewhale-new-test"); |
| 3988 | |
| 3989 | replace_binary(&target, b"fresh binary").unwrap(); |
| 3990 | let content = std::fs::read_to_string(&target).unwrap(); |
| 3991 | assert_eq!(content, "fresh binary"); |
| 3992 | } |
| 3993 | |
| 3994 | fn assert_no_staged_temp_files(dir: &Path) { |
| 3995 | assert!( |
| 3996 | std::fs::read_dir(dir).unwrap().all(|entry| { |
| 3997 | !entry |
| 3998 | .unwrap() |
| 3999 | .file_name() |
| 4000 | .to_string_lossy() |
| 4001 | .starts_with(".codewhale-update-") |
| 4002 | }), |
| 4003 | "a failed permission setup must clean the staged temp file" |
| 4004 | ); |
| 4005 | } |
| 4006 | |
| 4007 | /// Regression test for #5727: a permission-setup failure on the staged |
| 4008 | /// binary must abort the update before the existing target is replaced. |
| 4009 | #[test] |
| 4010 | fn permission_failure_on_existing_target_aborts_before_replacement() { |
| 4011 | let dir = tempfile::TempDir::new().unwrap(); |
| 4012 | let target = dir.path().join("codewhale-test"); |
| 4013 | write_installed_binary(&target, b"old binary"); |
| 4014 | |
| 4015 | let error = replace_binary_with_validation_and_permission_setter( |
| 4016 | &target, |
| 4017 | b"new binary content", |
| 4018 | || Ok(()), |
| 4019 | |_, _| Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)), |
| 4020 | ) |
| 4021 | .expect_err("a chmod failure must fail the update"); |
| 4022 | |
| 4023 | assert!( |
| 4024 | error |
| 4025 | .to_string() |
| 4026 | .contains("failed to set permissions on staged update"), |
| 4027 | "unexpected error: {error:#}" |
| 4028 | ); |
| 4029 | assert_eq!( |
| 4030 | std::fs::read(&target).unwrap(), |
| 4031 | b"old binary", |
| 4032 | "the working binary must survive a permission-setup failure" |
| 4033 | ); |
| 4034 | assert_no_staged_temp_files(dir.path()); |
| 4035 | } |
| 4036 | |
| 4037 | /// Regression test for #5727, new-target path: when no binary exists yet |
| 4038 | /// the staged file still needs its 0o755 mode, and a chmod failure must |
| 4039 | /// abort instead of installing a non-executable file. |
| 4040 | #[cfg(unix)] |
| 4041 | #[test] |
| 4042 | fn permission_failure_on_new_target_aborts_install() { |
| 4043 | let dir = tempfile::TempDir::new().unwrap(); |
| 4044 | let target = dir.path().join("codewhale-new-test"); |
| 4045 | |
| 4046 | let error = replace_binary_with_validation_and_permission_setter( |
| 4047 | &target, |
| 4048 | b"fresh binary", |
| 4049 | || Ok(()), |
| 4050 | |_, _| Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)), |
| 4051 | ) |
| 4052 | .expect_err("a chmod failure must fail a fresh install"); |
| 4053 | |
| 4054 | assert!( |
| 4055 | error |
| 4056 | .to_string() |
| 4057 | .contains("failed to set permissions on staged update"), |
| 4058 | "unexpected error: {error:#}" |
| 4059 | ); |
| 4060 | assert!( |
| 4061 | !target.exists(), |
| 4062 | "a failed fresh install must not leave a target behind" |
| 4063 | ); |
| 4064 | assert_no_staged_temp_files(dir.path()); |
| 4065 | } |
| 4066 | |
| 4067 | /// Regression test for #5727: even when permission setup reports success, |
| 4068 | /// a staged binary without an executable mode must never replace the |
| 4069 | /// working target. |
| 4070 | #[cfg(unix)] |
| 4071 | #[test] |
| 4072 | fn non_executable_staged_update_aborts_before_replacement() { |
| 4073 | let dir = tempfile::TempDir::new().unwrap(); |
| 4074 | let target = dir.path().join("codewhale-test"); |
| 4075 | write_test_executable(&target); |
| 4076 | std::fs::write(&target, b"old binary").unwrap(); |
| 4077 | |
| 4078 | // A no-op setter models a chmod that claims success without sticking, |
| 4079 | // leaving the staged temp file at its default non-executable 0o600. |
| 4080 | let error = replace_binary_with_validation_and_permission_setter( |
| 4081 | &target, |
| 4082 | b"new binary content", |
| 4083 | || Ok(()), |
| 4084 | |_, _| Ok(()), |
| 4085 | ) |
| 4086 | .expect_err("a non-executable staged binary must fail the update"); |
| 4087 | |
| 4088 | assert!( |
| 4089 | error.to_string().contains("is not executable"), |
| 4090 | "unexpected error: {error:#}" |
| 4091 | ); |
| 4092 | assert_eq!( |
| 4093 | std::fs::read(&target).unwrap(), |
| 4094 | b"old binary", |
| 4095 | "the working binary must survive a non-executable staged update" |
| 4096 | ); |
| 4097 | assert_no_staged_temp_files(dir.path()); |
| 4098 | } |
| 4099 | |
| 4100 | #[cfg(all(unix, not(target_os = "android")))] |
| 4101 | #[test] |
| 4102 | fn replace_verified_downloads_hard_links_same_directory_targets() { |
| 4103 | use std::os::unix::fs::{MetadataExt, PermissionsExt}; |
| 4104 | |
| 4105 | let dir = tempfile::TempDir::new().unwrap(); |
| 4106 | let bin_dir = dir.path().join("bin"); |
| 4107 | let other_dir = dir.path().join("other"); |
| 4108 | std::fs::create_dir(&bin_dir).unwrap(); |
| 4109 | std::fs::create_dir(&other_dir).unwrap(); |
| 4110 | std::fs::set_permissions(&bin_dir, std::fs::Permissions::from_mode(0o755)).unwrap(); |
| 4111 | std::fs::set_permissions(&other_dir, std::fs::Permissions::from_mode(0o755)).unwrap(); |
| 4112 | |
| 4113 | let old_bytes = b"old-release-bytes"; |
| 4114 | let new_bytes = b"new-release-bytes"; |
| 4115 | let primary = bin_dir.join("codewhale"); |
| 4116 | let sibling = bin_dir.join("codew"); |
| 4117 | let alias = bin_dir.join("codewhale-tui"); |
| 4118 | let outside = other_dir.join("codewhale"); |
| 4119 | for path in [&primary, &sibling, &alias, &outside] { |
| 4120 | write_installed_binary(path, old_bytes); |
| 4121 | } |
| 4122 | |
| 4123 | replace_verified_downloads( |
| 4124 | &[ |
| 4125 | primary.clone(), |
| 4126 | sibling.clone(), |
| 4127 | alias.clone(), |
| 4128 | outside.clone(), |
| 4129 | ], |
| 4130 | new_bytes, |
| 4131 | |path| { |
| 4132 | let bytes = std::fs::read(path)?; |
| 4133 | anyhow::ensure!(bytes == old_bytes); |
| 4134 | Ok(()) |
| 4135 | }, |
| 4136 | ) |
| 4137 | .unwrap(); |
| 4138 | |
| 4139 | let primary_meta = std::fs::metadata(&primary).unwrap(); |
| 4140 | let sibling_meta = std::fs::metadata(&sibling).unwrap(); |
| 4141 | let alias_meta = std::fs::metadata(&alias).unwrap(); |
| 4142 | let outside_meta = std::fs::metadata(&outside).unwrap(); |
| 4143 | assert_eq!(std::fs::read(&primary).unwrap(), new_bytes); |
| 4144 | assert_eq!(std::fs::read(&sibling).unwrap(), new_bytes); |
| 4145 | assert_eq!(std::fs::read(&alias).unwrap(), new_bytes); |
| 4146 | assert_eq!(std::fs::read(&outside).unwrap(), new_bytes); |
| 4147 | assert_eq!( |
| 4148 | (primary_meta.dev(), primary_meta.ino()), |
| 4149 | (sibling_meta.dev(), sibling_meta.ino()) |
| 4150 | ); |
| 4151 | assert_eq!( |
| 4152 | (primary_meta.dev(), primary_meta.ino()), |
| 4153 | (alias_meta.dev(), alias_meta.ino()) |
| 4154 | ); |
| 4155 | assert_eq!(primary_meta.nlink(), 3); |
| 4156 | assert_ne!( |
| 4157 | (outside_meta.dev(), outside_meta.ino()), |
| 4158 | (primary_meta.dev(), primary_meta.ino()) |
| 4159 | ); |
| 4160 | assert_eq!(outside_meta.nlink(), 1); |
| 4161 | assert_no_staged_temp_files(&bin_dir); |
| 4162 | assert_no_staged_temp_files(&other_dir); |
| 4163 | } |
| 4164 | |
| 4165 | #[cfg(all(unix, not(target_os = "android")))] |
| 4166 | #[test] |
| 4167 | fn hard_linked_receipted_install_updates_and_renews_and_rejects_external_link() { |
| 4168 | use std::os::unix::fs::{MetadataExt, PermissionsExt}; |
| 4169 | |
| 4170 | let dir = tempfile::TempDir::new().unwrap(); |
| 4171 | let bin_dir = dir.path().join("bin"); |
| 4172 | std::fs::create_dir(&bin_dir).unwrap(); |
| 4173 | std::fs::set_permissions(&bin_dir, std::fs::Permissions::from_mode(0o755)).unwrap(); |
| 4174 | |
| 4175 | let old_bytes = b"old-receipted-binary"; |
| 4176 | let new_bytes = b"new-receipted-binary"; |
| 4177 | let old_hash = crate::hashing::sha256_hex(old_bytes); |
| 4178 | let new_hash = crate::hashing::sha256_hex(new_bytes); |
| 4179 | let primary = bin_dir.join("codewhale"); |
| 4180 | let sibling = bin_dir.join("codew"); |
| 4181 | write_installed_binary(&primary, old_bytes); |
| 4182 | std::fs::hard_link(&primary, &sibling).unwrap(); |
| 4183 | let receipt_path = bin_dir.join(codewhale_release::installs::RECEIPT_FILE); |
| 4184 | std::fs::write( |
| 4185 | &receipt_path, |
| 4186 | format!("{old_hash} codewhale\n{old_hash} codew\n"), |
| 4187 | ) |
| 4188 | .unwrap(); |
| 4189 | std::fs::set_permissions(&receipt_path, std::fs::Permissions::from_mode(0o644)).unwrap(); |
| 4190 | |
| 4191 | let old_inode = ( |
| 4192 | std::fs::metadata(&primary).unwrap().dev(), |
| 4193 | std::fs::metadata(&primary).unwrap().ino(), |
| 4194 | ); |
| 4195 | let mut receipt = uninstall::CommandReceipt::capture(&primary) |
| 4196 | .unwrap() |
| 4197 | .expect("receipted hard-linked pair should capture"); |
| 4198 | replace_verified_downloads(&[primary.clone(), sibling.clone()], new_bytes, |path| { |
| 4199 | let bytes = std::fs::read(path)?; |
| 4200 | anyhow::ensure!(crate::hashing::sha256_hex(&bytes) == old_hash); |
| 4201 | Ok(()) |
| 4202 | }) |
| 4203 | .unwrap(); |
| 4204 | let home = dir.path().join("home"); |
| 4205 | std::fs::create_dir(&home).unwrap(); |
| 4206 | receipt.renew_in(new_bytes, Ok(home.clone())).unwrap(); |
| 4207 | assert!(home.join("recovery").is_dir()); |
| 4208 | |
| 4209 | let primary_meta = std::fs::metadata(&primary).unwrap(); |
| 4210 | let sibling_meta = std::fs::metadata(&sibling).unwrap(); |
| 4211 | assert_eq!(std::fs::read(&primary).unwrap(), new_bytes); |
| 4212 | assert_eq!(std::fs::read(&sibling).unwrap(), new_bytes); |
| 4213 | assert_eq!( |
| 4214 | (primary_meta.dev(), primary_meta.ino()), |
| 4215 | (sibling_meta.dev(), sibling_meta.ino()) |
| 4216 | ); |
| 4217 | assert_ne!((primary_meta.dev(), primary_meta.ino()), old_inode); |
| 4218 | assert_eq!(primary_meta.nlink(), 2); |
| 4219 | let renewed_receipt = std::fs::read_to_string(&receipt_path).unwrap(); |
| 4220 | assert_eq!( |
| 4221 | renewed_receipt, |
| 4222 | format!("{new_hash} codew\n{new_hash} codewhale\n") |
| 4223 | ); |
| 4224 | assert!( |
| 4225 | uninstall::CommandReceipt::capture(&primary) |
| 4226 | .unwrap() |
| 4227 | .is_some() |
| 4228 | ); |
| 4229 | |
| 4230 | let foreign = dir.path().join("foreign-link"); |
| 4231 | std::fs::hard_link(&primary, &foreign).unwrap(); |
| 4232 | assert!(uninstall::CommandReceipt::capture(&primary).is_err()); |
| 4233 | assert_eq!(std::fs::read(&primary).unwrap(), new_bytes); |
| 4234 | assert_eq!(std::fs::read(&sibling).unwrap(), new_bytes); |
| 4235 | } |
| 4236 | |
| 4237 | /// Mocked GitHub release payload covering the sole implementation binary |
| 4238 | /// across the published platform/arch matrix, plus a checksum sibling that |
| 4239 | /// must never be picked as the binary. |
| 4240 | fn mocked_release() -> Release { |
| 4241 | let json = r#"{ |
| 4242 | "tag_name": "v0.8.8", |
| 4243 | "assets": [ |
| 4244 | { "name": "codewhale-linux-x64", "browser_download_url": "https://example.invalid/codewhale-linux-x64" }, |
| 4245 | { "name": "codewhale-macos-x64", "browser_download_url": "https://example.invalid/codewhale-macos-x64" }, |
| 4246 | { "name": "codewhale-macos-arm64", "browser_download_url": "https://example.invalid/codewhale-macos-arm64" }, |
| 4247 | { "name": "codewhale-windows-x64.exe", "browser_download_url": "https://example.invalid/codewhale-windows-x64.exe" }, |
| 4248 | { "name": "codewhale-windows-x64.exe.sha256", "browser_download_url": "https://example.invalid/codewhale-windows-x64.exe.sha256" }, |
| 4249 | { "name": "codewhale-windows-arm64.exe", "browser_download_url": "https://example.invalid/codewhale-windows-arm64.exe" } |
| 4250 | ] |
| 4251 | }"#; |
| 4252 | serde_json::from_str(json).expect("mock release JSON") |
| 4253 | } |
| 4254 | |
| 4255 | #[test] |
| 4256 | fn mocked_release_selects_dispatcher_asset_for_supported_platforms() { |
| 4257 | let release = mocked_release(); |
| 4258 | let cases = [ |
| 4259 | ("macos", "aarch64", "codewhale-macos-arm64"), |
| 4260 | ("macos", "x86_64", "codewhale-macos-x64"), |
| 4261 | ("linux", "x86_64", "codewhale-linux-x64"), |
| 4262 | ("windows", "x86_64", "codewhale-windows-x64.exe"), |
| 4263 | ("windows", "aarch64", "codewhale-windows-arm64.exe"), |
| 4264 | ]; |
| 4265 | |
| 4266 | for (os, arch, expected) in cases { |
| 4267 | let stem = release_asset_stem_for(Path::new("/usr/local/bin/codewhale"), os, arch); |
| 4268 | let asset = select_platform_asset(&release, &stem) |
| 4269 | .unwrap_or_else(|| panic!("no asset for {os}/{arch} (stem {stem})")); |
| 4270 | assert_eq!(asset.name, expected, "{os}/{arch}"); |
| 4271 | } |
| 4272 | } |
| 4273 | |
| 4274 | #[test] |
| 4275 | fn mocked_release_selects_primary_asset_when_compatibility_alias_invokes_update() { |
| 4276 | let release = mocked_release(); |
| 4277 | let stem = release_asset_stem_for( |
| 4278 | Path::new("/usr/local/bin/codewhale-tui"), |
| 4279 | "macos", |
| 4280 | "aarch64", |
| 4281 | ); |
| 4282 | let asset = select_platform_asset(&release, &stem).expect("primary platform asset"); |
| 4283 | assert_eq!(asset.name, "codewhale-macos-arm64"); |
| 4284 | |
| 4285 | let windows_stem = release_asset_stem_for(Path::new("C:\\codew.exe"), "windows", "aarch64"); |
| 4286 | let windows_asset = |
| 4287 | select_platform_asset(&release, &windows_stem).expect("Windows ARM64 primary asset"); |
| 4288 | assert_eq!(windows_asset.name, "codewhale-windows-arm64.exe"); |
| 4289 | } |
| 4290 | |
| 4291 | #[test] |
| 4292 | fn android_arm64_maps_to_android_release_assets() { |
| 4293 | // The generic format!("{prefix}-{os}-{arch}") path naturally produces |
| 4294 | // Android asset stems. Verify every supported command name resolves to |
| 4295 | // the primary Android asset, never Linux or a removed TUI asset (#4241). |
| 4296 | assert_eq!( |
| 4297 | release_asset_stem_for_prefix("codewhale", "android", "aarch64"), |
| 4298 | "codewhale-android-arm64" |
| 4299 | ); |
| 4300 | assert_eq!( |
| 4301 | release_asset_stem_for(Path::new("codewhale-tui"), "android", "aarch64"), |
| 4302 | "codewhale-android-arm64" |
| 4303 | ); |
| 4304 | assert_eq!( |
| 4305 | release_asset_stem_for(Path::new("codew"), "android", "aarch64"), |
| 4306 | "codewhale-android-arm64" |
| 4307 | ); |
| 4308 | } |
| 4309 | |
| 4310 | #[test] |
| 4311 | fn ensure_supported_release_target_accepts_android() { |
| 4312 | // Android/Termux is a supported release target (#4241). |
| 4313 | assert!(ensure_supported_release_target("android", "aarch64").is_ok()); |
| 4314 | } |
| 4315 | |
| 4316 | #[test] |
| 4317 | fn android_release_assets_never_select_linux_arm64() { |
| 4318 | // Sanity: the stem formatter must never produce a linux-* stem for android. |
| 4319 | let stem = release_asset_stem_for_prefix("codewhale", "android", "aarch64"); |
| 4320 | assert!( |
| 4321 | !stem.contains("linux"), |
| 4322 | "android stem must not contain linux: {stem}" |
| 4323 | ); |
| 4324 | } |
| 4325 | |
| 4326 | #[test] |
| 4327 | fn mirror_release_uses_base_url_and_platform_assets() { |
| 4328 | let release = release_from_mirror_base_url( |
| 4329 | "https://mirror.example/releases/v0.8.36/", |
| 4330 | "0.8.36", |
| 4331 | "linux", |
| 4332 | "x86_64", |
| 4333 | ); |
| 4334 | |
| 4335 | assert_eq!(release.tag_name, "v0.8.36"); |
| 4336 | assert_eq!(release.assets[0].name, CHECKSUM_MANIFEST_ASSET); |
| 4337 | assert_eq!( |
| 4338 | release.assets[0].browser_download_url, |
| 4339 | "https://mirror.example/releases/v0.8.36/codewhale-artifacts-sha256.txt" |
| 4340 | ); |
| 4341 | |
| 4342 | let dispatcher = |
| 4343 | select_platform_asset(&release, "codewhale-linux-x64").expect("dispatcher asset"); |
| 4344 | assert_eq!( |
| 4345 | dispatcher.browser_download_url, |
| 4346 | "https://mirror.example/releases/v0.8.36/codewhale-linux-x64" |
| 4347 | ); |
| 4348 | assert_eq!(release.assets.len(), 2); |
| 4349 | assert!( |
| 4350 | select_platform_asset(&release, "codewhale-tui-linux-x64").is_none(), |
| 4351 | "mirror fallback must not synthesize a removed TUI asset" |
| 4352 | ); |
| 4353 | } |
| 4354 | |
| 4355 | #[test] |
| 4356 | fn mirror_release_uses_windows_exe_asset_names() { |
| 4357 | let release = release_from_mirror_base_url( |
| 4358 | "https://mirror.example/releases/v0.8.36", |
| 4359 | "v0.8.36", |
| 4360 | "windows", |
| 4361 | "x86_64", |
| 4362 | ); |
| 4363 | |
| 4364 | assert_eq!(release.tag_name, "v0.8.36"); |
| 4365 | assert!( |
| 4366 | select_platform_asset(&release, "codewhale-windows-x64") |
| 4367 | .is_some_and(|asset| asset.name == "codewhale-windows-x64.exe") |
| 4368 | ); |
| 4369 | assert!(select_platform_asset(&release, "codewhale-tui-windows-x64").is_none()); |
| 4370 | |
| 4371 | let arm_release = release_from_mirror_base_url( |
| 4372 | "https://mirror.example/releases/v0.9.1", |
| 4373 | "v0.9.1", |
| 4374 | "windows", |
| 4375 | "aarch64", |
| 4376 | ); |
| 4377 | assert!( |
| 4378 | select_platform_asset(&arm_release, "codewhale-windows-arm64") |
| 4379 | .is_some_and(|asset| asset.name == "codewhale-windows-arm64.exe") |
| 4380 | ); |
| 4381 | } |
| 4382 | |
| 4383 | #[test] |
| 4384 | fn github_release_url_parser_extracts_tag() { |
| 4385 | let url = |
| 4386 | reqwest::Url::parse("https://github.com/codewhale-hq/CodeWhale/releases/tag/v0.8.61") |
| 4387 | .unwrap(); |
| 4388 | |
| 4389 | assert_eq!( |
| 4390 | release_tag_from_github_release_url(&url).as_deref(), |
| 4391 | Some("v0.8.61") |
| 4392 | ); |
| 4393 | } |
| 4394 | |
| 4395 | #[test] |
| 4396 | fn github_release_download_fallback_uses_deterministic_asset_urls() { |
| 4397 | let release = release_from_github_download_tag("0.8.61", "macos", "aarch64"); |
| 4398 | |
| 4399 | assert_eq!(release.tag_name, "v0.8.61"); |
| 4400 | assert_eq!( |
| 4401 | release.assets[0].browser_download_url, |
| 4402 | "https://github.com/codewhale-hq/CodeWhale/releases/download/v0.8.61/codewhale-artifacts-sha256.txt" |
| 4403 | ); |
| 4404 | let dispatcher = |
| 4405 | select_platform_asset(&release, "codewhale-macos-arm64").expect("dispatcher asset"); |
| 4406 | assert_eq!( |
| 4407 | dispatcher.browser_download_url, |
| 4408 | "https://github.com/codewhale-hq/CodeWhale/releases/download/v0.8.61/codewhale-macos-arm64" |
| 4409 | ); |
| 4410 | assert_eq!(release.assets.len(), 2); |
| 4411 | assert!(select_platform_asset(&release, "codewhale-tui-macos-arm64").is_none()); |
| 4412 | } |
| 4413 | |
| 4414 | #[test] |
| 4415 | fn latest_stable_redirect_fallback_reads_tag_url() { |
| 4416 | let (url, request_rx, handle) = serve_http_once("200 OK", "text/html", b"<html></html>"); |
| 4417 | let tag_url = url.replace("/release", "/codewhale-hq/CodeWhale/releases/tag/v9.9.9"); |
| 4418 | |
| 4419 | let tag = fetch_latest_stable_tag_from_redirect_url(&tag_url, None) |
| 4420 | .expect("tag should parse from final URL"); |
| 4421 | |
| 4422 | assert_eq!(tag, "v9.9.9"); |
| 4423 | let request = request_rx.recv().expect("captured request"); |
| 4424 | assert!( |
| 4425 | request.starts_with("GET /codewhale-hq/CodeWhale/releases/tag/v9.9.9 "), |
| 4426 | "got {request:?}" |
| 4427 | ); |
| 4428 | handle.join().expect("test server thread"); |
| 4429 | } |
| 4430 | |
| 4431 | #[test] |
| 4432 | fn github_release_html_parser_skips_empty_first_marker() { |
| 4433 | let body = r#" |
| 4434 | <a href="/codewhale-hq/CodeWhale/releases/tag/?expanded=true">generic</a> |
| 4435 | <a href="/codewhale-hq/CodeWhale/releases/tag/v9.9.9">latest</a> |
| 4436 | "#; |
| 4437 | |
| 4438 | assert_eq!( |
| 4439 | release_tag_from_github_release_html(body).as_deref(), |
| 4440 | Some("v9.9.9") |
| 4441 | ); |
| 4442 | } |
| 4443 | |
| 4444 | #[test] |
| 4445 | fn cnb_release_base_url_includes_tag_directory() { |
| 4446 | assert_eq!( |
| 4447 | codewhale_release::cnb_release_base_url("0.8.47"), |
| 4448 | "https://cnb.cool/codewhale.net/codewhale/-/releases/download/v0.8.47" |
| 4449 | ); |
| 4450 | assert_eq!( |
| 4451 | codewhale_release::cnb_release_base_url("v0.8.47"), |
| 4452 | "https://cnb.cool/codewhale.net/codewhale/-/releases/download/v0.8.47" |
| 4453 | ); |
| 4454 | } |
| 4455 | |
| 4456 | #[test] |
| 4457 | fn stable_update_is_needed_only_when_latest_is_newer() { |
| 4458 | assert!(update_is_needed(ReleaseChannel::Stable, "0.8.45", "v0.8.46").unwrap()); |
| 4459 | assert!(update_is_needed(ReleaseChannel::Stable, "0.8.45", "v0.9.0-beta.1").unwrap()); |
| 4460 | assert!(!update_is_needed(ReleaseChannel::Stable, "0.8.45", "v0.8.45").unwrap()); |
| 4461 | assert!(!update_is_needed(ReleaseChannel::Stable, "0.9.0", "v0.9.0-beta.1").unwrap()); |
| 4462 | assert!( |
| 4463 | !update_is_needed(ReleaseChannel::Stable, "0.9.0-beta.2", "v0.9.0-beta.1").unwrap() |
| 4464 | ); |
| 4465 | } |
| 4466 | |
| 4467 | #[test] |
| 4468 | fn beta_update_allows_switching_from_same_stable_to_beta() { |
| 4469 | assert!(update_is_needed(ReleaseChannel::Beta, "1.0.0", "v1.0.0-beta.2").unwrap()); |
| 4470 | assert!(!update_is_needed(ReleaseChannel::Beta, "1.0.0-beta.2", "v1.0.0-beta.2").unwrap()); |
| 4471 | assert!(!update_is_needed(ReleaseChannel::Beta, "1.0.0-beta.3", "v1.0.0-beta.2").unwrap()); |
| 4472 | assert!(update_is_needed(ReleaseChannel::Beta, "1.0.0-beta.2", "v1.0.0-beta.3").unwrap()); |
| 4473 | assert!(!update_is_needed(ReleaseChannel::Beta, "2.0.0", "v1.0.0-beta.3").unwrap()); |
| 4474 | assert!(!update_is_needed(ReleaseChannel::Beta, "1.0.0-rc.1", "v1.0.0-beta.3").unwrap()); |
| 4475 | } |
| 4476 | |
| 4477 | #[test] |
| 4478 | fn parse_release_version_accepts_tags_and_build_suffixes() { |
| 4479 | assert_eq!( |
| 4480 | codewhale_release::parse_release_version("v0.9.0-beta.1").unwrap(), |
| 4481 | semver::Version::parse("0.9.0-beta.1").unwrap() |
| 4482 | ); |
| 4483 | assert_eq!( |
| 4484 | codewhale_release::parse_release_version("0.8.45 (abcdef123456)").unwrap(), |
| 4485 | semver::Version::parse("0.8.45").unwrap() |
| 4486 | ); |
| 4487 | } |
| 4488 | |
| 4489 | #[test] |
| 4490 | fn beta_release_detection_requires_beta_tag() { |
| 4491 | let rc_prerelease = Release { |
| 4492 | tag_name: "v0.9.0-rc.1".to_string(), |
| 4493 | prerelease: true, |
| 4494 | assets: vec![], |
| 4495 | }; |
| 4496 | let beta_tag = Release { |
| 4497 | tag_name: "v0.9.0-beta.1".to_string(), |
| 4498 | prerelease: false, |
| 4499 | assets: vec![], |
| 4500 | }; |
| 4501 | let stable = Release { |
| 4502 | tag_name: "v0.9.0".to_string(), |
| 4503 | prerelease: false, |
| 4504 | assets: vec![], |
| 4505 | }; |
| 4506 | |
| 4507 | assert!(!is_beta_tag(&rc_prerelease.tag_name)); |
| 4508 | assert!(is_beta_tag(&beta_tag.tag_name)); |
| 4509 | assert!(!is_beta_tag(&stable.tag_name)); |
| 4510 | } |
| 4511 | |
| 4512 | #[test] |
| 4513 | fn update_fallback_hint_points_china_users_to_cnb_and_asset_mirrors() { |
| 4514 | let hint = update_network_fallback_hint(); |
| 4515 | |
| 4516 | assert!(hint.contains(codewhale_release::CNB_REPO_URL), "{hint}"); |
| 4517 | assert!( |
| 4518 | hint.contains(codewhale_release::RELEASE_BASE_URL_ENV), |
| 4519 | "{hint}" |
| 4520 | ); |
| 4521 | assert!( |
| 4522 | hint.contains(codewhale_release::UPDATE_VERSION_ENV), |
| 4523 | "{hint}" |
| 4524 | ); |
| 4525 | assert!(hint.contains("codewhale-cli"), "{hint}"); |
| 4526 | assert!(!hint.contains("codewhale-tui --locked"), "{hint}"); |
| 4527 | } |
| 4528 | |
| 4529 | fn serve_http_responses( |
| 4530 | responses: Vec<(&'static str, &'static str, &'static [u8])>, |
| 4531 | ) -> (String, mpsc::Receiver<String>, thread::JoinHandle<()>) { |
| 4532 | serve_http_owned_responses( |
| 4533 | responses |
| 4534 | .into_iter() |
| 4535 | .map(|(status, content_type, body)| (status, content_type, body.to_vec())) |
| 4536 | .collect(), |
| 4537 | ) |
| 4538 | } |
| 4539 | |
| 4540 | fn serve_http_owned_responses( |
| 4541 | responses: Vec<(&'static str, &'static str, Vec<u8>)>, |
| 4542 | ) -> (String, mpsc::Receiver<String>, thread::JoinHandle<()>) { |
| 4543 | let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server"); |
| 4544 | let addr = listener.local_addr().expect("test server addr"); |
| 4545 | let (request_tx, request_rx) = mpsc::channel(); |
| 4546 | |
| 4547 | let handle = thread::spawn(move || { |
| 4548 | for (status, content_type, body) in responses { |
| 4549 | let (mut stream, _) = listener.accept().expect("accept test request"); |
| 4550 | let mut buf = [0_u8; 4096]; |
| 4551 | let n = stream.read(&mut buf).expect("read test request"); |
| 4552 | request_tx |
| 4553 | .send(String::from_utf8_lossy(&buf[..n]).to_string()) |
| 4554 | .expect("send captured request"); |
| 4555 | |
| 4556 | write!( |
| 4557 | stream, |
| 4558 | "HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", |
| 4559 | body.len() |
| 4560 | ) |
| 4561 | .expect("write test response headers"); |
| 4562 | stream.write_all(&body).expect("write test response body"); |
| 4563 | } |
| 4564 | }); |
| 4565 | |
| 4566 | (format!("http://{addr}/release"), request_rx, handle) |
| 4567 | } |
| 4568 | |
| 4569 | fn serve_http_once( |
| 4570 | status: &'static str, |
| 4571 | content_type: &'static str, |
| 4572 | body: &'static [u8], |
| 4573 | ) -> (String, mpsc::Receiver<String>, thread::JoinHandle<()>) { |
| 4574 | serve_http_responses(vec![(status, content_type, body)]) |
| 4575 | } |
| 4576 | |
| 4577 | // Ordered source selection is deterministic and offline. A successful |
| 4578 | // GitHub manifest must not cause any mirror request. |
| 4579 | fn scripted_manifest_fetcher( |
| 4580 | script: Vec<(&'static str, Result<String, String>)>, |
| 4581 | ) -> Arc<ManifestFetcher> { |
| 4582 | let script: HashMap<_, _> = script.into_iter().collect(); |
| 4583 | Arc::new(move |candidate: &ReleaseSourceCandidate| { |
| 4584 | script |
| 4585 | .get(candidate.source.label()) |
| 4586 | .expect("unexpected source request") |
| 4587 | .clone() |
| 4588 | .map(String::into_bytes) |
| 4589 | .map_err(|message| anyhow!(message)) |
| 4590 | }) |
| 4591 | } |
| 4592 | |
| 4593 | fn manifest_covering_linux_x64() -> String { |
| 4594 | format!( |
| 4595 | "{} codewhale-linux-x64\n{} codew-linux-x64\n", |
| 4596 | "a".repeat(64), |
| 4597 | "b".repeat(64) |
| 4598 | ) |
| 4599 | } |
| 4600 | |
| 4601 | fn manifest_missing_linux_x64() -> String { |
| 4602 | format!("{} codewhale-macos-arm64\n", "c".repeat(64)) |
| 4603 | } |
| 4604 | |
| 4605 | fn github_fetched_release(tag_name: &str) -> FetchedRelease { |
| 4606 | FetchedRelease { |
| 4607 | release: Release { |
| 4608 | tag_name: tag_name.to_string(), |
| 4609 | prerelease: is_beta_tag(tag_name), |
| 4610 | assets: vec![ |
| 4611 | Asset { |
| 4612 | name: "codewhale-linux-x64".to_string(), |
| 4613 | browser_download_url: format!( |
| 4614 | "https://github.com/codewhale-hq/CodeWhale/releases/download/{tag_name}/codewhale-linux-x64" |
| 4615 | ), |
| 4616 | }, |
| 4617 | Asset { |
| 4618 | name: CHECKSUM_MANIFEST_ASSET.to_string(), |
| 4619 | browser_download_url: format!( |
| 4620 | "https://github.com/codewhale-hq/CodeWhale/releases/download/{tag_name}/{CHECKSUM_MANIFEST_ASSET}" |
| 4621 | ), |
| 4622 | }, |
| 4623 | ], |
| 4624 | }, |
| 4625 | source: UpdateReleaseSource::GitHub, |
| 4626 | } |
| 4627 | } |
| 4628 | |
| 4629 | fn candidates_for( |
| 4630 | fetched: &FetchedRelease, |
| 4631 | os: &str, |
| 4632 | arch: &str, |
| 4633 | ) -> Option<Vec<ReleaseSourceCandidate>> { |
| 4634 | proactive_source_candidates(fetched, "codewhale-linux-x64", os, arch) |
| 4635 | } |
| 4636 | |
| 4637 | fn linux_x64_candidates(tag_name: &str) -> Vec<ReleaseSourceCandidate> { |
| 4638 | candidates_for(&github_fetched_release(tag_name), "linux", "x86_64") |
| 4639 | .expect("linux x64 must try GitHub before the CNB mirror") |
| 4640 | } |
| 4641 | |
| 4642 | #[test] |
| 4643 | fn github_is_preferred_without_contacting_a_healthy_mirror() { |
| 4644 | let requested = Arc::new(Mutex::new(Vec::new())); |
| 4645 | let captured = Arc::clone(&requested); |
| 4646 | let fetch: Arc<ManifestFetcher> = Arc::new(move |candidate| { |
| 4647 | captured.lock().unwrap().push(candidate.source.label()); |
| 4648 | Ok(manifest_covering_linux_x64().into_bytes()) |
| 4649 | }); |
| 4650 | let plan = select_release_source(linux_x64_candidates("v9.9.9"), fetch).unwrap(); |
| 4651 | assert_eq!(plan.source, UpdateReleaseSource::GitHub); |
| 4652 | assert_eq!(*requested.lock().unwrap(), ["GitHub Releases"]); |
| 4653 | assert_eq!( |
| 4654 | plan.binary_url, |
| 4655 | "https://github.com/codewhale-hq/CodeWhale/releases/download/v9.9.9/codewhale-linux-x64" |
| 4656 | ); |
| 4657 | } |
| 4658 | |
| 4659 | #[test] |
| 4660 | fn cnb_never_supplies_the_manifest_after_a_github_manifest_failure() { |
| 4661 | for first_answer in [ |
| 4662 | Err("connection timed out".to_string()), |
| 4663 | Ok(manifest_missing_linux_x64()), |
| 4664 | Ok("not a checksum manifest".to_string()), |
| 4665 | Ok(String::new()), |
| 4666 | ] { |
| 4667 | let requested = Arc::new(Mutex::new(Vec::new())); |
| 4668 | let captured = Arc::clone(&requested); |
| 4669 | let fetch: Arc<ManifestFetcher> = Arc::new(move |candidate| { |
| 4670 | captured.lock().unwrap().push(candidate.source.label()); |
| 4671 | if candidate.source == UpdateReleaseSource::GitHub { |
| 4672 | first_answer |
| 4673 | .clone() |
| 4674 | .map(String::into_bytes) |
| 4675 | .map_err(|err| anyhow!(err)) |
| 4676 | } else { |
| 4677 | Ok(manifest_covering_linux_x64().into_bytes()) |
| 4678 | } |
| 4679 | }); |
| 4680 | let err = select_release_source(linux_x64_candidates("v9.9.9"), fetch) |
| 4681 | .expect_err("a mirror must never vouch for its own bytes"); |
| 4682 | assert!(format!("{err:#}").contains("GitHub Releases"), "{err:#}"); |
| 4683 | assert_eq!(*requested.lock().unwrap(), ["GitHub Releases"]); |
| 4684 | } |
| 4685 | } |
| 4686 | |
| 4687 | #[test] |
| 4688 | fn the_mirror_is_only_a_fallback_for_bytes_github_pins() { |
| 4689 | let fetch: Arc<ManifestFetcher> = |
| 4690 | Arc::new(|_| Ok(manifest_covering_linux_x64().into_bytes())); |
| 4691 | let plan = select_release_source(linux_x64_candidates("v9.9.9"), fetch).unwrap(); |
| 4692 | assert_eq!(plan.source, UpdateReleaseSource::GitHub); |
| 4693 | assert_eq!( |
| 4694 | plan.fallback_binaries, |
| 4695 | vec![( |
| 4696 | UpdateReleaseSource::Cnb { |
| 4697 | base_url: cnb_release_base_url("v9.9.9"), |
| 4698 | }, |
| 4699 | "https://cnb.cool/codewhale.net/codewhale/-/releases/download/v9.9.9/codewhale-linux-x64" |
| 4700 | .to_string() |
| 4701 | )] |
| 4702 | ); |
| 4703 | } |
| 4704 | |
| 4705 | #[test] |
| 4706 | fn selection_fails_closed_when_no_source_is_usable() { |
| 4707 | let fetch = scripted_manifest_fetcher(vec![ |
| 4708 | ("GitHub Releases", Err("dns failure".to_string())), |
| 4709 | ("CNB mirror", Ok(manifest_missing_linux_x64())), |
| 4710 | ]); |
| 4711 | |
| 4712 | let err = select_release_source(linux_x64_candidates("v9.9.9"), fetch) |
| 4713 | .expect_err("no usable source must fail rather than download unverified bytes"); |
| 4714 | let message = format!("{err:#}"); |
| 4715 | |
| 4716 | assert!( |
| 4717 | message.contains("dns failure") && message.contains("GitHub Releases"), |
| 4718 | "unexpected error: {message}" |
| 4719 | ); |
| 4720 | } |
| 4721 | |
| 4722 | #[test] |
| 4723 | fn only_supported_targets_have_cnb_as_a_fallback() { |
| 4724 | let fetched = github_fetched_release("v9.9.9"); |
| 4725 | |
| 4726 | for (os, arch) in [ |
| 4727 | ("linux", "aarch64"), |
| 4728 | ("linux", "riscv64"), |
| 4729 | ("macos", "x86_64"), |
| 4730 | ("macos", "aarch64"), |
| 4731 | ("windows", "x86_64"), |
| 4732 | ("android", "aarch64"), |
| 4733 | ] { |
| 4734 | assert!( |
| 4735 | candidates_for(&fetched, os, arch).is_none(), |
| 4736 | "{os}/{arch} must keep its single canonical source" |
| 4737 | ); |
| 4738 | } |
| 4739 | |
| 4740 | let raced = candidates_for(&fetched, "linux", "x86_64").expect("linux x64 fallback"); |
| 4741 | assert_eq!(raced.len(), 2); |
| 4742 | } |
| 4743 | |
| 4744 | #[test] |
| 4745 | fn cnb_candidate_targets_the_exact_tag_and_platform_asset() { |
| 4746 | let candidate = cnb_source_candidate("v0.9.0-beta.2", "linux", "x86_64"); |
| 4747 | |
| 4748 | assert_eq!( |
| 4749 | candidate.source, |
| 4750 | UpdateReleaseSource::Cnb { |
| 4751 | base_url: cnb_release_base_url("v0.9.0-beta.2"), |
| 4752 | } |
| 4753 | ); |
| 4754 | assert_eq!( |
| 4755 | candidate.manifest_url, |
| 4756 | "https://cnb.cool/codewhale.net/codewhale/-/releases/download/v0.9.0-beta.2/codewhale-artifacts-sha256.txt" |
| 4757 | ); |
| 4758 | assert_eq!( |
| 4759 | candidate.binary_url, |
| 4760 | "https://cnb.cool/codewhale.net/codewhale/-/releases/download/v0.9.0-beta.2/codewhale-linux-x64" |
| 4761 | ); |
| 4762 | assert_eq!(candidate.binary_name, "codewhale-linux-x64"); |
| 4763 | } |
| 4764 | |
| 4765 | #[test] |
| 4766 | fn github_candidate_addresses_the_manifest_even_when_the_payload_omits_it() { |
| 4767 | let release = Release { |
| 4768 | tag_name: "0.9.9".to_string(), |
| 4769 | prerelease: false, |
| 4770 | assets: vec![Asset { |
| 4771 | name: "codewhale-linux-x64".to_string(), |
| 4772 | browser_download_url: "https://cdn.example/codewhale-linux-x64".to_string(), |
| 4773 | }], |
| 4774 | }; |
| 4775 | |
| 4776 | let candidate = |
| 4777 | github_source_candidate(&release, "codewhale-linux-x64").expect("github candidate"); |
| 4778 | |
| 4779 | assert_eq!( |
| 4780 | candidate.manifest_url, |
| 4781 | "https://github.com/codewhale-hq/CodeWhale/releases/download/v0.9.9/codewhale-artifacts-sha256.txt" |
| 4782 | ); |
| 4783 | assert_eq!( |
| 4784 | candidate.binary_url, |
| 4785 | "https://cdn.example/codewhale-linux-x64" |
| 4786 | ); |
| 4787 | } |
| 4788 | |
| 4789 | #[test] |
| 4790 | fn every_single_source_platform_requires_a_checksum_manifest() { |
| 4791 | for (os, arch) in [ |
| 4792 | ("linux", "x86_64"), |
| 4793 | ("linux", "aarch64"), |
| 4794 | ("macos", "x86_64"), |
| 4795 | ("macos", "aarch64"), |
| 4796 | ("windows", "x86_64"), |
| 4797 | ("windows", "aarch64"), |
| 4798 | ("android", "aarch64"), |
| 4799 | ] { |
| 4800 | let asset_stem = release_asset_stem_for_prefix("codewhale", os, arch); |
| 4801 | let asset_name = release_asset_name_for_prefix("codewhale", os, arch); |
| 4802 | let fetched = FetchedRelease { |
| 4803 | release: Release { |
| 4804 | tag_name: "v9.9.9".to_string(), |
| 4805 | prerelease: false, |
| 4806 | assets: vec![Asset { |
| 4807 | name: asset_name.clone(), |
| 4808 | browser_download_url: format!("https://cdn.example/{asset_name}"), |
| 4809 | }], |
| 4810 | }, |
| 4811 | source: UpdateReleaseSource::GitHub, |
| 4812 | }; |
| 4813 | |
| 4814 | let err = single_source_download_plan(&fetched, &asset_stem, None) |
| 4815 | .expect_err("a missing manifest must fail before the binary download"); |
| 4816 | let message = format!("{err:#}"); |
| 4817 | assert!( |
| 4818 | message.contains("does not publish required codewhale-artifacts-sha256.txt"), |
| 4819 | "{os}/{arch} unexpectedly allowed an unverifiable plan: {message}" |
| 4820 | ); |
| 4821 | assert!(message.contains(&asset_name), "{os}/{arch}: {message}"); |
| 4822 | } |
| 4823 | } |
| 4824 | |
| 4825 | #[test] |
| 4826 | fn a_malformed_single_source_manifest_fails_before_binary_download() { |
| 4827 | let (manifest_url, request_rx, handle) = |
| 4828 | serve_http_once("200 OK", "text/plain", b"not a checksum manifest\n"); |
| 4829 | let fetched = FetchedRelease { |
| 4830 | release: Release { |
| 4831 | tag_name: "v9.9.9".to_string(), |
| 4832 | prerelease: false, |
| 4833 | assets: vec![ |
| 4834 | Asset { |
| 4835 | name: CHECKSUM_MANIFEST_ASSET.to_string(), |
| 4836 | browser_download_url: manifest_url, |
| 4837 | }, |
| 4838 | Asset { |
| 4839 | name: "codewhale-macos-arm64".to_string(), |
| 4840 | browser_download_url: "https://cdn.example/should-not-download".to_string(), |
| 4841 | }, |
| 4842 | ], |
| 4843 | }, |
| 4844 | source: UpdateReleaseSource::GitHub, |
| 4845 | }; |
| 4846 | |
| 4847 | let err = single_source_download_plan(&fetched, "codewhale-macos-arm64", None) |
| 4848 | .expect_err("a malformed manifest must fail closed"); |
| 4849 | let message = format!("{err:#}"); |
| 4850 | assert!(message.contains("failed to parse"), "{message}"); |
| 4851 | assert!( |
| 4852 | message.contains("invalid SHA256 manifest line"), |
| 4853 | "{message}" |
| 4854 | ); |
| 4855 | let request = request_rx.recv().expect("manifest request"); |
| 4856 | assert!(request.starts_with("GET /release "), "got {request:?}"); |
| 4857 | handle.join().expect("test server thread"); |
| 4858 | } |
| 4859 | |
| 4860 | #[test] |
| 4861 | fn a_single_source_manifest_must_cover_the_exact_platform_binary() { |
| 4862 | let manifest = format!("{} codewhale-linux-x64\n", "a".repeat(64)); |
| 4863 | let (manifest_url, request_rx, handle) = |
| 4864 | serve_http_owned_responses(vec![("200 OK", "text/plain", manifest.into_bytes())]); |
| 4865 | let fetched = FetchedRelease { |
| 4866 | release: Release { |
| 4867 | tag_name: "v9.9.9".to_string(), |
| 4868 | prerelease: false, |
| 4869 | assets: vec![ |
| 4870 | Asset { |
| 4871 | name: CHECKSUM_MANIFEST_ASSET.to_string(), |
| 4872 | browser_download_url: manifest_url, |
| 4873 | }, |
| 4874 | Asset { |
| 4875 | name: "codewhale-windows-x64.exe".to_string(), |
| 4876 | browser_download_url: "https://cdn.example/should-not-download.exe" |
| 4877 | .to_string(), |
| 4878 | }, |
| 4879 | ], |
| 4880 | }, |
| 4881 | source: UpdateReleaseSource::GitHub, |
| 4882 | }; |
| 4883 | |
| 4884 | let err = single_source_download_plan(&fetched, "codewhale-windows-x64", None) |
| 4885 | .expect_err("a manifest for another platform must fail closed"); |
| 4886 | let message = format!("{err:#}"); |
| 4887 | assert!( |
| 4888 | message.contains("does not list codewhale-windows-x64.exe"), |
| 4889 | "{message}" |
| 4890 | ); |
| 4891 | let request = request_rx.recv().expect("manifest request"); |
| 4892 | assert!(request.starts_with("GET /release "), "got {request:?}"); |
| 4893 | handle.join().expect("test server thread"); |
| 4894 | } |
| 4895 | |
| 4896 | #[test] |
| 4897 | fn an_explicit_mirror_remains_pinned_and_verified_from_that_mirror() { |
| 4898 | let bytes = b"verified mirror bytes"; |
| 4899 | let manifest = format!("{} codewhale-macos-arm64\n", sha256_hex(bytes)); |
| 4900 | let (url, request_rx, handle) = |
| 4901 | serve_http_owned_responses(vec![("200 OK", "text/plain", manifest.into_bytes())]); |
| 4902 | let base_url = url.trim_end_matches("/release").to_string(); |
| 4903 | let fetched = FetchedRelease { |
| 4904 | release: release_from_mirror_base_url(&base_url, "9.9.9", "macos", "aarch64"), |
| 4905 | source: UpdateReleaseSource::Mirror { |
| 4906 | base_url: base_url.clone(), |
| 4907 | }, |
| 4908 | }; |
| 4909 | |
| 4910 | let plan = single_source_download_plan(&fetched, "codewhale-macos-arm64", None) |
| 4911 | .expect("the explicit mirror's valid manifest should produce a plan"); |
| 4912 | assert_eq!( |
| 4913 | plan.source, |
| 4914 | UpdateReleaseSource::Mirror { |
| 4915 | base_url: base_url.clone(), |
| 4916 | } |
| 4917 | ); |
| 4918 | assert_eq!( |
| 4919 | plan.binary_url, |
| 4920 | mirror_asset_url(&base_url, "codewhale-macos-arm64") |
| 4921 | ); |
| 4922 | verify_downloaded_asset(&plan, bytes) |
| 4923 | .expect("the pinned mirror's checksum must verify its bytes"); |
| 4924 | let request = request_rx.recv().expect("manifest request"); |
| 4925 | assert!( |
| 4926 | request.starts_with("GET /codewhale-artifacts-sha256.txt "), |
| 4927 | "got {request:?}" |
| 4928 | ); |
| 4929 | handle.join().expect("test server thread"); |
| 4930 | } |
| 4931 | |
| 4932 | #[test] |
| 4933 | fn a_github_release_without_this_platform_leaves_cnb_as_the_only_candidate() { |
| 4934 | let fetched = FetchedRelease { |
| 4935 | release: Release { |
| 4936 | tag_name: "v9.9.9".to_string(), |
| 4937 | prerelease: false, |
| 4938 | assets: vec![Asset { |
| 4939 | name: "codewhale-macos-arm64".to_string(), |
| 4940 | browser_download_url: "https://cdn.example/codewhale-macos-arm64".to_string(), |
| 4941 | }], |
| 4942 | }, |
| 4943 | source: UpdateReleaseSource::GitHub, |
| 4944 | }; |
| 4945 | |
| 4946 | let candidates = candidates_for(&fetched, "linux", "x86_64").expect("linux x64 fallback"); |
| 4947 | |
| 4948 | assert_eq!(candidates.len(), 1); |
| 4949 | assert!(matches!( |
| 4950 | candidates[0].source, |
| 4951 | UpdateReleaseSource::Cnb { .. } |
| 4952 | )); |
| 4953 | } |
| 4954 | |
| 4955 | #[test] |
| 4956 | fn beta_tags_use_the_same_ordered_sources_as_stable_tags() { |
| 4957 | let candidates = linux_x64_candidates("v0.9.0-beta.2"); |
| 4958 | |
| 4959 | assert_eq!(candidates[0].source, UpdateReleaseSource::GitHub); |
| 4960 | assert_eq!( |
| 4961 | candidates[1].source, |
| 4962 | UpdateReleaseSource::Cnb { |
| 4963 | base_url: cnb_release_base_url("v0.9.0-beta.2"), |
| 4964 | }, |
| 4965 | "the beta tag must be carried into the CNB URL verbatim" |
| 4966 | ); |
| 4967 | } |
| 4968 | |
| 4969 | #[test] |
| 4970 | fn explicit_overrides_take_precedence_over_probing() { |
| 4971 | { |
| 4972 | let _env = UpdateEnvGuard::clear(); |
| 4973 | set_update_env( |
| 4974 | codewhale_release::RELEASE_BASE_URL_ENV, |
| 4975 | "https://mirror.example/assets", |
| 4976 | ); |
| 4977 | set_update_env(codewhale_release::UPDATE_VERSION_ENV, "9.9.9"); |
| 4978 | |
| 4979 | let fetched = fetch_latest_release(ReleaseChannel::Stable, None) |
| 4980 | .expect("a pinned mirror resolves without a network"); |
| 4981 | |
| 4982 | assert_eq!( |
| 4983 | fetched.source, |
| 4984 | UpdateReleaseSource::Mirror { |
| 4985 | base_url: "https://mirror.example/assets".to_string(), |
| 4986 | } |
| 4987 | ); |
| 4988 | assert!(fetched.source.is_pinned_mirror()); |
| 4989 | assert!( |
| 4990 | candidates_for(&fetched, "linux", "x86_64").is_none(), |
| 4991 | "an explicit base URL must never fall back to CNB" |
| 4992 | ); |
| 4993 | assert_eq!( |
| 4994 | describe_release_source_for_check(&fetched, "codewhale-linux-x64", None), |
| 4995 | "release mirror (https://mirror.example/assets)" |
| 4996 | ); |
| 4997 | } |
| 4998 | |
| 4999 | { |
| 5000 | let _env = UpdateEnvGuard::clear(); |
| 5001 | set_update_env(codewhale_release::CNB_MIRROR_ENV, "1"); |
| 5002 | set_update_env(codewhale_release::UPDATE_VERSION_ENV, "9.9.9"); |
| 5003 | |
| 5004 | let fetched = fetch_latest_release(ReleaseChannel::Stable, None) |
| 5005 | .expect("the CNB override resolves without a network"); |
| 5006 | |
| 5007 | assert_eq!( |
| 5008 | fetched.source, |
| 5009 | UpdateReleaseSource::Cnb { |
| 5010 | base_url: cnb_release_base_url("9.9.9"), |
| 5011 | }, |
| 5012 | "an explicit CNB request must be reported as CNB, not as a generic mirror" |
| 5013 | ); |
| 5014 | assert!( |
| 5015 | candidates_for(&fetched, "linux", "x86_64").is_none(), |
| 5016 | "an explicit CNB request must not fall back to GitHub" |
| 5017 | ); |
| 5018 | } |
| 5019 | |
| 5020 | { |
| 5021 | let _env = UpdateEnvGuard::clear(); |
| 5022 | set_update_env(codewhale_release::CNB_MIRROR_ENV, "1"); |
| 5023 | set_update_env( |
| 5024 | codewhale_release::RELEASE_BASE_URL_ENV, |
| 5025 | "https://mirror.example/assets", |
| 5026 | ); |
| 5027 | |
| 5028 | let fetched = fetch_latest_release(ReleaseChannel::Stable, None) |
| 5029 | .expect("a pinned mirror resolves without a network"); |
| 5030 | |
| 5031 | assert_eq!( |
| 5032 | fetched.source, |
| 5033 | UpdateReleaseSource::Mirror { |
| 5034 | base_url: "https://mirror.example/assets".to_string(), |
| 5035 | }, |
| 5036 | "an explicit base URL outranks the CNB flag" |
| 5037 | ); |
| 5038 | } |
| 5039 | } |
| 5040 | |
| 5041 | #[test] |
| 5042 | fn a_locked_source_serves_both_the_manifest_and_the_binary() { |
| 5043 | const BINARY: &[u8] = b"\x7fELF codewhale linux x64 payload"; |
| 5044 | let manifest = format!("{} codewhale-linux-x64\n", sha256_hex(BINARY)); |
| 5045 | let (url, request_rx, handle) = serve_http_owned_responses(vec![ |
| 5046 | ("200 OK", "text/plain", manifest.into_bytes()), |
| 5047 | ("200 OK", "application/octet-stream", BINARY.to_vec()), |
| 5048 | ]); |
| 5049 | let origin = url.trim_end_matches("/release").to_string(); |
| 5050 | let candidate = ReleaseSourceCandidate { |
| 5051 | source: UpdateReleaseSource::Cnb { |
| 5052 | base_url: origin.clone(), |
| 5053 | }, |
| 5054 | manifest_url: mirror_asset_url(&origin, CHECKSUM_MANIFEST_ASSET), |
| 5055 | binary_name: "codewhale-linux-x64".to_string(), |
| 5056 | binary_url: mirror_asset_url(&origin, "codewhale-linux-x64"), |
| 5057 | }; |
| 5058 | |
| 5059 | let plan = select_release_source(vec![candidate], manifest_probe_fetcher(None)) |
| 5060 | .expect("the only reachable source must win"); |
| 5061 | let bytes = download_url(&plan.binary_url, None).expect("binary download"); |
| 5062 | verify_downloaded_asset(&plan, &bytes) |
| 5063 | .expect("bytes from the locked source must match its own manifest"); |
| 5064 | |
| 5065 | assert_eq!(bytes, BINARY); |
| 5066 | let manifest_request = request_rx.recv().expect("manifest request"); |
| 5067 | let binary_request = request_rx.recv().expect("binary request"); |
| 5068 | assert!( |
| 5069 | manifest_request.starts_with("GET /codewhale-artifacts-sha256.txt "), |
| 5070 | "got {manifest_request:?}" |
| 5071 | ); |
| 5072 | assert!( |
| 5073 | binary_request.starts_with("GET /codewhale-linux-x64 "), |
| 5074 | "got {binary_request:?}" |
| 5075 | ); |
| 5076 | handle.join().expect("test server thread"); |
| 5077 | } |
| 5078 | |
| 5079 | #[test] |
| 5080 | fn a_release_is_refused_unless_a_trusted_key_signed_its_manifest() { |
| 5081 | const TEST_KEY: &str = "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c"; |
| 5082 | const TEST_KEY_SIGNATURE: &[u8] = b"vX9KZ7maFenoVCheguRaHu1npjRjKTa09ZCVvF6pbL3Yad5kNHvjWBIGZZbUQM9sO5Mnp86CxWJu82jhKZDADg=="; |
| 5083 | const OTHER_KEY_SIGNATURE: &[u8] = b"r34Q5uHYyc0fKHFUWH67MgTo/4o/F3V4cNM4hsgO3y/qWWZDWKMLHrElZGvApccUVItI0n+D2XTx/GyvhV5QDQ=="; |
| 5084 | let _env = UpdateEnvGuard::clear(); |
| 5085 | assert!(!signing::trusted_keys().is_empty()); |
| 5086 | let manifest = format!("{} codewhale-linux-x64\n", "a".repeat(64)).into_bytes(); |
| 5087 | let check = |status: &'static str, signature: &[u8]| { |
| 5088 | let (url, request_rx, handle) = |
| 5089 | serve_http_owned_responses(vec![(status, "text/plain", signature.to_vec())]); |
| 5090 | let origin = url.trim_end_matches("/release").to_string(); |
| 5091 | let plan = DownloadPlan { |
| 5092 | source: UpdateReleaseSource::Mirror { |
| 5093 | base_url: origin.clone(), |
| 5094 | }, |
| 5095 | binary_name: "codewhale-linux-x64".to_string(), |
| 5096 | binary_url: mirror_asset_url(&origin, "codewhale-linux-x64"), |
| 5097 | checksums: HashMap::from([("codewhale-linux-x64".to_string(), "a".repeat(64))]), |
| 5098 | manifest_url: mirror_asset_url(&origin, CHECKSUM_MANIFEST_ASSET), |
| 5099 | manifest_bytes: manifest.clone(), |
| 5100 | fallback_binaries: Vec::new(), |
| 5101 | }; |
| 5102 | let result = fetch_signature(&plan, "v9.9.9", None); |
| 5103 | let request = request_rx.recv().expect("signature request"); |
| 5104 | assert!( |
| 5105 | request.starts_with("GET /codewhale-artifacts-sha256.txt.sig "), |
| 5106 | "got {request:?}" |
| 5107 | ); |
| 5108 | handle.join().expect("test server thread"); |
| 5109 | result.map_err(|error| format!("{error:#}")) |
| 5110 | }; |
| 5111 | |
| 5112 | let missing = check("404 Not Found", b"").expect_err("an unsigned release"); |
| 5113 | assert!(missing.contains("requires signed releases"), "{missing}"); |
| 5114 | let unknown = check("200 OK", TEST_KEY_SIGNATURE).expect_err("an untrusted signer"); |
| 5115 | assert!(unknown.contains("does not verify"), "{unknown}"); |
| 5116 | |
| 5117 | set_update_env(TEST_RELEASE_PUBLIC_KEY_ENV, TEST_KEY); |
| 5118 | assert_eq!( |
| 5119 | check("200 OK", TEST_KEY_SIGNATURE), |
| 5120 | Ok(SignatureCheck::Verified) |
| 5121 | ); |
| 5122 | let other = check("200 OK", OTHER_KEY_SIGNATURE).expect_err("another key's signature"); |
| 5123 | assert!(other.contains("does not verify"), "{other}"); |
| 5124 | } |
| 5125 | |
| 5126 | #[test] |
| 5127 | fn a_checksum_mismatch_fails_closed_and_names_the_source() { |
| 5128 | let mut plan = DownloadPlan { |
| 5129 | source: UpdateReleaseSource::Cnb { |
| 5130 | base_url: cnb_release_base_url("v9.9.9"), |
| 5131 | }, |
| 5132 | binary_name: "codewhale-linux-x64".to_string(), |
| 5133 | binary_url: "https://cnb.example/codewhale-linux-x64".to_string(), |
| 5134 | checksums: HashMap::from([("codewhale-linux-x64".to_string(), "a".repeat(64))]), |
| 5135 | manifest_url: String::new(), |
| 5136 | manifest_bytes: Vec::new(), |
| 5137 | fallback_binaries: Vec::new(), |
| 5138 | }; |
| 5139 | |
| 5140 | let err = verify_downloaded_asset(&plan, b"tampered bytes") |
| 5141 | .expect_err("a mismatch must never install"); |
| 5142 | let message = format!("{err:#}"); |
| 5143 | assert!(message.contains("SHA256 mismatch"), "{message}"); |
| 5144 | assert!(message.contains("CNB mirror"), "{message}"); |
| 5145 | |
| 5146 | plan.checksums = HashMap::from([("codew-linux-x64".to_string(), "a".repeat(64))]); |
| 5147 | let err = verify_downloaded_asset(&plan, b"bytes") |
| 5148 | .expect_err("an uncovered asset must never install"); |
| 5149 | let message = format!("{err:#}"); |
| 5150 | assert!( |
| 5151 | message.contains("is missing codewhale-linux-x64"), |
| 5152 | "{message}" |
| 5153 | ); |
| 5154 | } |
| 5155 | |
| 5156 | #[test] |
| 5157 | fn release_sources_describe_themselves_for_status_and_receipts() { |
| 5158 | assert_eq!(UpdateReleaseSource::GitHub.describe(), "GitHub Releases"); |
| 5159 | assert!(!UpdateReleaseSource::GitHub.is_pinned_mirror()); |
| 5160 | |
| 5161 | let cnb = UpdateReleaseSource::Cnb { |
| 5162 | base_url: cnb_release_base_url("v9.9.9"), |
| 5163 | }; |
| 5164 | assert_eq!( |
| 5165 | cnb.describe(), |
| 5166 | "CNB mirror (https://cnb.cool/codewhale.net/codewhale/-/releases/download/v9.9.9)" |
| 5167 | ); |
| 5168 | assert!(cnb.is_pinned_mirror()); |
| 5169 | |
| 5170 | let mirror = UpdateReleaseSource::Mirror { |
| 5171 | base_url: "https://mirror.example/assets".to_string(), |
| 5172 | }; |
| 5173 | assert_eq!( |
| 5174 | mirror.describe(), |
| 5175 | "release mirror (https://mirror.example/assets)" |
| 5176 | ); |
| 5177 | assert!(mirror.is_pinned_mirror()); |
| 5178 | } |
| 5179 | |
| 5180 | #[test] |
| 5181 | fn validate_and_build_proxy_accepts_supported_proxy_urls() { |
| 5182 | validate_and_build_proxy("http://localhost:7897").expect("http proxy"); |
| 5183 | validate_and_build_proxy("https://proxy.example.com:8080").expect("https proxy"); |
| 5184 | validate_and_build_proxy("socks5://127.0.0.1:1080").expect("socks proxy"); |
| 5185 | } |
| 5186 | |
| 5187 | #[test] |
| 5188 | fn validate_and_build_proxy_rejects_malformed_urls() { |
| 5189 | let err = validate_and_build_proxy("not a valid url").expect_err("malformed URL"); |
| 5190 | assert!(err.to_string().contains("invalid proxy URL")); |
| 5191 | } |
| 5192 | |
| 5193 | #[test] |
| 5194 | fn fetch_latest_release_from_url_reads_mocked_release_json() { |
| 5195 | let body = br#"{ |
| 5196 | "tag_name": "v9.9.9", |
| 5197 | "assets": [ |
| 5198 | { "name": "codewhale-linux-x64", "browser_download_url": "http://example.invalid/codewhale-linux-x64" }, |
| 5199 | { "name": "codewhale-artifacts-sha256.txt", "browser_download_url": "http://example.invalid/codewhale-artifacts-sha256.txt" } |
| 5200 | ] |
| 5201 | }"#; |
| 5202 | let (url, request_rx, handle) = serve_http_once("200 OK", "application/json", body); |
| 5203 | let release = fetch_latest_release_from_url(&url, None).expect("release JSON should parse"); |
| 5204 | |
| 5205 | assert_eq!(release.tag_name, "v9.9.9"); |
| 5206 | assert_eq!(release.assets.len(), 2); |
| 5207 | |
| 5208 | let request = request_rx.recv().expect("captured request"); |
| 5209 | let request_lower = request.to_ascii_lowercase(); |
| 5210 | assert!(request.starts_with("GET /release "), "got {request:?}"); |
| 5211 | assert!( |
| 5212 | request_lower.contains("accept: application/vnd.github+json"), |
| 5213 | "got {request:?}" |
| 5214 | ); |
| 5215 | assert!( |
| 5216 | request_lower.contains("user-agent: codewhale-updater"), |
| 5217 | "got {request:?}" |
| 5218 | ); |
| 5219 | handle.join().expect("test server thread"); |
| 5220 | } |
| 5221 | |
| 5222 | #[test] |
| 5223 | fn fetch_latest_release_from_url_retries_transient_gateway_error() { |
| 5224 | let body = br#"{ |
| 5225 | "tag_name": "v9.9.9", |
| 5226 | "assets": [ |
| 5227 | { "name": "codewhale-linux-x64", "browser_download_url": "http://example.invalid/codewhale-linux-x64" } |
| 5228 | ] |
| 5229 | }"#; |
| 5230 | let (url, request_rx, handle) = serve_http_responses(vec![ |
| 5231 | ("504 Gateway Timeout", "text/plain", b"gateway timeout"), |
| 5232 | ("200 OK", "application/json", body), |
| 5233 | ]); |
| 5234 | let release = fetch_latest_release_from_url(&url, None) |
| 5235 | .expect("release JSON should parse after retry"); |
| 5236 | |
| 5237 | assert_eq!(release.tag_name, "v9.9.9"); |
| 5238 | let first = request_rx.recv().expect("first request"); |
| 5239 | let second = request_rx.recv().expect("second request"); |
| 5240 | assert!(first.starts_with("GET /release "), "got {first:?}"); |
| 5241 | assert!(second.starts_with("GET /release "), "got {second:?}"); |
| 5242 | handle.join().expect("test server thread"); |
| 5243 | } |
| 5244 | |
| 5245 | #[test] |
| 5246 | fn fetch_latest_release_from_url_reports_http_errors() { |
| 5247 | let (url, _request_rx, handle) = serve_http_responses(vec![ |
| 5248 | ("500 Internal Server Error", "text/plain", b"server broke"), |
| 5249 | ("500 Internal Server Error", "text/plain", b"server broke"), |
| 5250 | ("500 Internal Server Error", "text/plain", b"server broke"), |
| 5251 | ]); |
| 5252 | let err = fetch_latest_release_from_url(&url, None).expect_err("HTTP 500 should fail"); |
| 5253 | |
| 5254 | assert!( |
| 5255 | err.to_string().contains("HTTP 500"), |
| 5256 | "unexpected error: {err:#}" |
| 5257 | ); |
| 5258 | handle.join().expect("test server thread"); |
| 5259 | } |
| 5260 | |
| 5261 | #[test] |
| 5262 | fn fetch_latest_beta_release_from_url_selects_first_beta_release() { |
| 5263 | let body = br#"[ |
| 5264 | { "tag_name": "v0.9.0", "prerelease": false, "assets": [] }, |
| 5265 | { "tag_name": "v0.9.0-rc.1", "prerelease": true, "assets": [] }, |
| 5266 | { "tag_name": "v0.9.0-beta.2", "prerelease": true, "assets": [ |
| 5267 | { "name": "codewhale-linux-x64", "browser_download_url": "http://example.invalid/codewhale-linux-x64" } |
| 5268 | ] }, |
| 5269 | { "tag_name": "v0.9.0-beta.1", "prerelease": true, "assets": [] } |
| 5270 | ]"#; |
| 5271 | let (url, request_rx, handle) = serve_http_once("200 OK", "application/json", body); |
| 5272 | let release = |
| 5273 | fetch_latest_beta_release_from_url(&url, None).expect("beta release JSON should parse"); |
| 5274 | |
| 5275 | assert_eq!(release.tag_name, "v0.9.0-beta.2"); |
| 5276 | assert!(release.prerelease); |
| 5277 | |
| 5278 | let request = request_rx.recv().expect("captured request"); |
| 5279 | let request_lower = request.to_ascii_lowercase(); |
| 5280 | assert!(request.starts_with("GET /release "), "got {request:?}"); |
| 5281 | assert!( |
| 5282 | request_lower.contains("accept: application/vnd.github+json"), |
| 5283 | "got {request:?}" |
| 5284 | ); |
| 5285 | handle.join().expect("test server thread"); |
| 5286 | } |
| 5287 | |
| 5288 | #[test] |
| 5289 | fn fetch_latest_beta_release_from_url_reports_missing_beta() { |
| 5290 | let body = br#"[ |
| 5291 | { "tag_name": "v0.9.0", "prerelease": false, "assets": [] } |
| 5292 | ]"#; |
| 5293 | let (url, _request_rx, handle) = serve_http_once("200 OK", "application/json", body); |
| 5294 | let err = |
| 5295 | fetch_latest_beta_release_from_url(&url, None).expect_err("missing beta should fail"); |
| 5296 | |
| 5297 | assert!( |
| 5298 | err.to_string().contains("no beta release found"), |
| 5299 | "unexpected error: {err:#}" |
| 5300 | ); |
| 5301 | handle.join().expect("test server thread"); |
| 5302 | } |
| 5303 | |
| 5304 | #[test] |
| 5305 | fn download_url_retries_transient_gateway_error() { |
| 5306 | let (url, request_rx, handle) = serve_http_responses(vec![ |
| 5307 | ("503 Service Unavailable", "text/plain", b"try again"), |
| 5308 | ("200 OK", "application/octet-stream", b"\0binary bytes"), |
| 5309 | ]); |
| 5310 | let bytes = download_url(&url, None).expect("binary download should retry and succeed"); |
| 5311 | |
| 5312 | assert_eq!(bytes, b"\0binary bytes"); |
| 5313 | let first = request_rx.recv().expect("first request"); |
| 5314 | let second = request_rx.recv().expect("second request"); |
| 5315 | assert!(first.starts_with("GET /release "), "got {first:?}"); |
| 5316 | assert!(second.starts_with("GET /release "), "got {second:?}"); |
| 5317 | handle.join().expect("test server thread"); |
| 5318 | } |
| 5319 | |
| 5320 | #[test] |
| 5321 | fn download_url_reads_binary_body_with_updater_user_agent() { |
| 5322 | let (url, request_rx, handle) = |
| 5323 | serve_http_once("200 OK", "application/octet-stream", b"\0binary bytes"); |
| 5324 | let bytes = download_url(&url, None).expect("binary download should succeed"); |
| 5325 | |
| 5326 | assert_eq!(bytes, b"\0binary bytes"); |
| 5327 | |
| 5328 | let request = request_rx.recv().expect("captured request"); |
| 5329 | let request_lower = request.to_ascii_lowercase(); |
| 5330 | assert!(request.starts_with("GET /release "), "got {request:?}"); |
| 5331 | assert!( |
| 5332 | request_lower.contains("user-agent: codewhale-updater"), |
| 5333 | "got {request:?}" |
| 5334 | ); |
| 5335 | handle.join().expect("test server thread"); |
| 5336 | } |
| 5337 | |
| 5338 | fn url(text: &str) -> reqwest::Url { |
| 5339 | reqwest::Url::parse(text).expect("url") |
| 5340 | } |
| 5341 | |
| 5342 | #[test] |
| 5343 | fn update_hosts_are_an_allow_list_over_https() { |
| 5344 | let strict = UpdateTransportPolicy::strict(); |
| 5345 | for allowed in [ |
| 5346 | "https://github.com/codewhale-hq/CodeWhale/releases/latest", |
| 5347 | "https://api.github.com/repos/codewhale-hq/CodeWhale/releases/latest", |
| 5348 | "https://release-assets.githubusercontent.com/x", |
| 5349 | "https://objects.githubusercontent.com/x", |
| 5350 | "https://cnb.cool/codewhale.net/codewhale/-/releases/download/v1/a", |
| 5351 | ] { |
| 5352 | strict.check_url(&url(allowed)).expect(allowed); |
| 5353 | } |
| 5354 | for refused in [ |
| 5355 | "http://github.com/codewhale-hq/CodeWhale", |
| 5356 | "https://github.com.evil.example/a", |
| 5357 | "https://evilgithub.com/a", |
| 5358 | "https://notcnb.cool/a", |
| 5359 | "https://raw.githubusercontent.com/a", |
| 5360 | "https://203.0.113.9/a", |
| 5361 | "ftp://github.com/a", |
| 5362 | "http://127.0.0.1:9/a", |
| 5363 | ] { |
| 5364 | assert!(strict.check_url(&url(refused)).is_err(), "{refused}"); |
| 5365 | } |
| 5366 | } |
| 5367 | |
| 5368 | #[test] |
| 5369 | fn a_configured_mirror_host_is_allowed_and_must_be_https() { |
| 5370 | let _guard = UpdateEnvGuard::clear(); |
| 5371 | set_update_env( |
| 5372 | codewhale_release::RELEASE_BASE_URL_ENV, |
| 5373 | "https://Mirror.Internal.example:8443/CodeWhale/", |
| 5374 | ); |
| 5375 | let policy = UpdateTransportPolicy::from_env(); |
| 5376 | policy |
| 5377 | .check_url(&url("https://mirror.internal.example:8443/CodeWhale/v1/a")) |
| 5378 | .expect("the configured mirror host is allowed"); |
| 5379 | assert!( |
| 5380 | policy |
| 5381 | .check_url(&url("https://other.internal.example/a")) |
| 5382 | .is_err() |
| 5383 | ); |
| 5384 | assert!( |
| 5385 | policy |
| 5386 | .check_url(&url("http://mirror.internal.example/a")) |
| 5387 | .is_err(), |
| 5388 | "a mirror is never reached over plain HTTP" |
| 5389 | ); |
| 5390 | } |
| 5391 | |
| 5392 | #[test] |
| 5393 | fn extra_update_hosts_come_only_from_the_operator_environment() { |
| 5394 | let _guard = UpdateEnvGuard::clear(); |
| 5395 | set_update_env( |
| 5396 | UPDATE_ALLOWED_HOSTS_ENV, |
| 5397 | "cdn.one.example, CDN.two.example ,", |
| 5398 | ); |
| 5399 | let policy = UpdateTransportPolicy::from_env(); |
| 5400 | for host in ["cdn.one.example", "cdn.two.example"] { |
| 5401 | policy |
| 5402 | .check_url(&url(&format!("https://{host}/a"))) |
| 5403 | .expect(host); |
| 5404 | } |
| 5405 | assert!( |
| 5406 | policy |
| 5407 | .check_url(&url("https://cdn.three.example/a")) |
| 5408 | .is_err() |
| 5409 | ); |
| 5410 | assert!(policy.check_url(&url("http://cdn.one.example/a")).is_err()); |
| 5411 | } |
| 5412 | |
| 5413 | #[test] |
| 5414 | fn a_plain_http_mirror_is_refused_before_any_request() { |
| 5415 | let _guard = UpdateEnvGuard::clear(); |
| 5416 | set_update_env( |
| 5417 | codewhale_release::RELEASE_BASE_URL_ENV, |
| 5418 | "http://mirror.example/assets", |
| 5419 | ); |
| 5420 | let error = fetch_latest_release(ReleaseChannel::Stable, None) |
| 5421 | .expect_err("an HTTP mirror must be refused"); |
| 5422 | assert!(format!("{error:#}").contains("HTTPS"), "{error:#}"); |
| 5423 | } |
| 5424 | |
| 5425 | /// A listener that records whether anything connected to it. |
| 5426 | fn silent_listener() -> (TcpListener, String) { |
| 5427 | let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); |
| 5428 | listener.set_nonblocking(true).expect("nonblocking"); |
| 5429 | let addr = listener.local_addr().expect("addr"); |
| 5430 | (listener, format!("http://{addr}/asset")) |
| 5431 | } |
| 5432 | |
| 5433 | #[test] |
| 5434 | fn the_request_path_refuses_plain_http_and_unlisted_hosts_without_connecting() { |
| 5435 | let (listener, plain_url) = silent_listener(); |
| 5436 | let strict = UpdateTransportPolicy::strict(); |
| 5437 | let error = download_url_once_with( |
| 5438 | &strict, |
| 5439 | UPDATE_MAX_RESPONSE_BYTES, |
| 5440 | &plain_url, |
| 5441 | None, |
| 5442 | Duration::from_secs(5), |
| 5443 | ) |
| 5444 | .expect_err("plain HTTP is refused"); |
| 5445 | assert!(format!("{error:#}").contains("HTTPS"), "{error:#}"); |
| 5446 | assert!( |
| 5447 | listener.accept().is_err(), |
| 5448 | "no connection may be opened for a refused URL" |
| 5449 | ); |
| 5450 | let error = download_url_once_with( |
| 5451 | &strict, |
| 5452 | UPDATE_MAX_RESPONSE_BYTES, |
| 5453 | "https://download.evil.example/codewhale", |
| 5454 | None, |
| 5455 | Duration::from_secs(5), |
| 5456 | ) |
| 5457 | .expect_err("an unlisted host is refused"); |
| 5458 | assert!( |
| 5459 | format!("{error:#}").contains("not an allowed release host"), |
| 5460 | "{error:#}" |
| 5461 | ); |
| 5462 | } |
| 5463 | |
| 5464 | /// The redirect policy is exercised through the real built client against |
| 5465 | /// a live fixture. The fixture cannot speak TLS, so the request starts on |
| 5466 | /// plain HTTP (a start URL is the caller's check, covered above); the point |
| 5467 | /// is that the client then refuses to follow a hop that is not HTTPS to an |
| 5468 | /// allowed host, and never contacts it. |
| 5469 | #[test] |
| 5470 | fn the_built_client_refuses_to_follow_a_redirect_off_https_or_off_the_allow_list() { |
| 5471 | let (target, target_listener) = { |
| 5472 | let (listener, url) = silent_listener(); |
| 5473 | (url, listener) |
| 5474 | }; |
| 5475 | for location in [target.as_str(), "https://download.evil.example/next"] { |
| 5476 | let listener = TcpListener::bind("127.0.0.1:0").expect("bind"); |
| 5477 | let addr = listener.local_addr().expect("addr"); |
| 5478 | let location = location.to_string(); |
| 5479 | let server = thread::spawn(move || { |
| 5480 | let (mut stream, _) = listener.accept().expect("accept"); |
| 5481 | let mut buf = [0_u8; 2048]; |
| 5482 | let _ = stream.read(&mut buf).expect("read"); |
| 5483 | write!( |
| 5484 | stream, |
| 5485 | "HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" |
| 5486 | ) |
| 5487 | .expect("write"); |
| 5488 | }); |
| 5489 | let client = update_http_client_with_policy( |
| 5490 | None, |
| 5491 | Duration::from_secs(5), |
| 5492 | &UpdateTransportPolicy::strict(), |
| 5493 | ) |
| 5494 | .expect("client"); |
| 5495 | let error = client |
| 5496 | .get(format!("http://{addr}/start")) |
| 5497 | .send() |
| 5498 | .expect_err("the redirect must not be followed"); |
| 5499 | // reqwest keeps the policy's message in the error's source chain. |
| 5500 | let mut text = error.to_string(); |
| 5501 | let mut source = std::error::Error::source(&error); |
| 5502 | while let Some(cause) = source { |
| 5503 | text.push_str(&format!(": {cause}")); |
| 5504 | source = cause.source(); |
| 5505 | } |
| 5506 | assert!(text.contains("update redirect refused"), "{text}"); |
| 5507 | server.join().expect("fixture thread"); |
| 5508 | } |
| 5509 | assert!( |
| 5510 | target_listener.accept().is_err(), |
| 5511 | "the refused redirect target must never be contacted" |
| 5512 | ); |
| 5513 | } |
| 5514 | |
| 5515 | #[test] |
| 5516 | fn a_response_past_the_size_cap_is_refused_and_one_at_the_cap_is_kept() { |
| 5517 | let policy = UpdateTransportPolicy::strict().with_loopback_http(true); |
| 5518 | let (url, _rx, handle) = serve_http_once("200 OK", "application/octet-stream", &[7_u8; 64]); |
| 5519 | let error = download_url_once_with(&policy, 63, &url, None, Duration::from_secs(5)) |
| 5520 | .expect_err("one byte over the cap is refused"); |
| 5521 | assert!(format!("{error:#}").contains("update limit"), "{error:#}"); |
| 5522 | handle.join().expect("fixture thread"); |
| 5523 | |
| 5524 | let (url, _rx, handle) = serve_http_once("200 OK", "application/octet-stream", &[7_u8; 64]); |
| 5525 | let (_, bytes) = download_url_once_with(&policy, 64, &url, None, Duration::from_secs(5)) |
| 5526 | .expect("a body exactly at the cap is kept"); |
| 5527 | assert_eq!(bytes.len(), 64); |
| 5528 | handle.join().expect("fixture thread"); |
| 5529 | } |
| 5530 | |
| 5531 | #[test] |
| 5532 | fn release_errors_and_sources_redact_url_userinfo() { |
| 5533 | let _guard = UpdateEnvGuard::clear(); |
| 5534 | set_update_env( |
| 5535 | codewhale_release::RELEASE_BASE_URL_ENV, |
| 5536 | "http://user:secret@mirror.example/assets", |
| 5537 | ); |
| 5538 | let mirror_err = fetch_latest_release(ReleaseChannel::Stable, None) |
| 5539 | .expect_err("HTTP mirror with userinfo must fail"); |
| 5540 | let mirror_text = format!("{mirror_err:#}"); |
| 5541 | assert!(mirror_text.contains("HTTPS"), "{mirror_text}"); |
| 5542 | assert!(!mirror_text.contains("secret"), "{mirror_text}"); |
| 5543 | assert!(!mirror_text.contains("user:"), "{mirror_text}"); |
| 5544 | |
| 5545 | let mirror_desc = UpdateReleaseSource::Mirror { |
| 5546 | base_url: "https://user:secret@mirror.example/assets".to_string(), |
| 5547 | } |
| 5548 | .describe(); |
| 5549 | assert!( |
| 5550 | mirror_desc.contains("https://mirror.example/assets"), |
| 5551 | "{mirror_desc}" |
| 5552 | ); |
| 5553 | assert!(!mirror_desc.contains("secret"), "{mirror_desc}"); |
| 5554 | assert!(!mirror_desc.contains("user:"), "{mirror_desc}"); |
| 5555 | |
| 5556 | let closed = TcpListener::bind("127.0.0.1:0").expect("bind"); |
| 5557 | let closed_addr = closed.local_addr().expect("addr"); |
| 5558 | drop(closed); |
| 5559 | set_update_env(UPDATE_ALLOWED_HOSTS_ENV, "127.0.0.1"); |
| 5560 | let download_err = download_url_once_with( |
| 5561 | &UpdateTransportPolicy::from_env(), |
| 5562 | UPDATE_MAX_RESPONSE_BYTES, |
| 5563 | &format!("https://user:secret@{closed_addr}/codewhale"), |
| 5564 | None, |
| 5565 | Duration::from_secs(5), |
| 5566 | ) |
| 5567 | .expect_err("closed loopback HTTPS must fail without leaking userinfo"); |
| 5568 | let download_text = format!("{download_err:#}"); |
| 5569 | assert!( |
| 5570 | download_text.contains("failed to download"), |
| 5571 | "{download_text}" |
| 5572 | ); |
| 5573 | assert!(!download_text.contains("secret"), "{download_text}"); |
| 5574 | assert!(!download_text.contains("user:"), "{download_text}"); |
| 5575 | } |
| 5576 | |
| 5577 | #[test] |
| 5578 | fn release_tags_taken_from_a_page_must_look_like_tags() { |
| 5579 | let page = |tag: &str| { |
| 5580 | url(&format!( |
| 5581 | "https://github.com/codewhale-hq/CodeWhale/releases/tag/{tag}" |
| 5582 | )) |
| 5583 | }; |
| 5584 | assert_eq!( |
| 5585 | release_tag_from_github_release_url(&page("v0.10.1")).as_deref(), |
| 5586 | Some("v0.10.1") |
| 5587 | ); |
| 5588 | assert_eq!(release_tag_from_github_release_url(&page("%2e%2e")), None); |
| 5589 | assert_eq!( |
| 5590 | release_tag_from_github_release_html("<a href=\"/releases/tag/v1.2.3\">"), |
| 5591 | Some("v1.2.3".to_string()) |
| 5592 | ); |
| 5593 | assert_eq!( |
| 5594 | release_tag_from_github_release_html("<a href=\"/releases/tag/a%2Fb\">"), |
| 5595 | None |
| 5596 | ); |
| 5597 | } |
| 5598 | |
| 5599 | #[test] |
| 5600 | fn record_declined_update_warns_when_persist_fails_and_saves_on_success() { |
| 5601 | let sample = |target_dir: PathBuf| autoupdate::StagedUpdate { |
| 5602 | version: "0.10.5".to_string(), |
| 5603 | sha256: "a".repeat(64), |
| 5604 | signed: false, |
| 5605 | source: "https://example.invalid/codewhale".to_string(), |
| 5606 | target_dir, |
| 5607 | declined: false, |
| 5608 | staged_at_unix: 1, |
| 5609 | }; |
| 5610 | |
| 5611 | let unwritable_home = tempfile::tempdir().unwrap(); |
| 5612 | // Blocking `updates` with a regular file forces `store_staged` to fail portably. |
| 5613 | std::fs::write(unwritable_home.path().join("updates"), b"not-a-dir").unwrap(); |
| 5614 | let mut staged = sample(unwritable_home.path().to_path_buf()); |
| 5615 | let warning = |
| 5616 | record_declined_update(unwritable_home.path(), &mut staged, "0.10.4", "0.10.5"); |
| 5617 | assert!(warning.contains("not saved"), "{warning}"); |
| 5618 | assert!(warning.contains("you will be asked again"), "{warning}"); |
| 5619 | assert!(!warning.contains("whenever you want"), "{warning}"); |
| 5620 | |
| 5621 | let ok_home = tempfile::tempdir().unwrap(); |
| 5622 | let mut staged = sample(ok_home.path().to_path_buf()); |
| 5623 | let ok_msg = record_declined_update(ok_home.path(), &mut staged, "0.10.4", "0.10.5"); |
| 5624 | assert!(ok_msg.contains("whenever you want v0.10.5"), "{ok_msg}"); |
| 5625 | assert!(autoupdate::load_staged(ok_home.path()).unwrap().declined); |
| 5626 | } |
| 5627 | } |
| 5628 |