1mod apply;
11mod binary_cache;
12mod cache_dir;
13mod monitor;
14mod release_cache;
15mod rollout;
16mod signature;
17pub(crate) mod traffic;
18
19pub use apply::{AutoApplyUpgrader, RESTART_EXIT_CODE};
20pub use binary_cache::BinaryCache;
21pub use cache_dir::upgrade_cache_dir;
22pub use monitor::{find_platform_asset, version_from_tag, Asset, GitHubRelease, UpgradeMonitor};
23pub use release_cache::ReleaseCache;
24pub use rollout::StagedRollout;
25pub use signature::{
26 verify_binary_signature, verify_binary_signature_with_key, verify_from_file,
27 verify_from_file_with_key, PUBLIC_KEY_SIZE, SIGNATURE_SIZE, SIGNING_CONTEXT,
28};
29
30use crate::error::{Error, Result};
31use crate::logging::{debug, info, warn};
32use semver::Version;
33use std::fs;
34use std::path::Path;
35
36const MAX_BINARY_SIZE_BYTES: usize = 200 * 1024 * 1024;
41
42#[derive(Debug, Clone)]
44pub struct UpgradeInfo {
45 pub version: Version,
47 pub download_url: String,
49 pub signature_url: String,
51 pub release_notes: String,
53}
54
55#[derive(Debug)]
57pub enum UpgradeResult {
58 Success {
60 version: Version,
62 exit_code: i32,
65 },
66 RolledBack {
68 reason: String,
70 },
71 NoUpgrade,
73}
74
75pub struct Upgrader {
85 current_version: Version,
87 client: reqwest::Client,
89}
90
91impl Upgrader {
92 #[must_use]
94 pub fn new() -> Self {
95 let current_version =
96 Version::parse(env!("CARGO_PKG_VERSION")).unwrap_or_else(|_| Version::new(0, 0, 0));
97
98 Self {
99 current_version,
100 client: reqwest::Client::new(),
101 }
102 }
103
104 #[cfg(test)]
106 #[must_use]
107 pub fn with_version(version: Version) -> Self {
108 Self {
109 current_version: version,
110 client: reqwest::Client::new(),
111 }
112 }
113
114 #[must_use]
116 pub fn current_version(&self) -> &Version {
117 &self.current_version
118 }
119
120 pub fn validate_upgrade(&self, info: &UpgradeInfo) -> Result<()> {
126 if info.version <= self.current_version {
127 return Err(Error::Upgrade(format!(
128 "Cannot downgrade from {} to {}",
129 self.current_version, info.version
130 )));
131 }
132 Ok(())
133 }
134
135 pub fn create_backup(&self, current: &Path, rollback_dir: &Path) -> Result<()> {
146 let filename = current
147 .file_name()
148 .ok_or_else(|| Error::Upgrade("Invalid binary path".to_string()))?;
149
150 let backup_path = rollback_dir.join(format!("{}.backup", filename.to_string_lossy()));
151
152 debug!("Creating backup at: {}", backup_path.display());
153 fs::copy(current, &backup_path)?;
154 Ok(())
155 }
156
157 pub fn restore_from_backup(&self, current: &Path, rollback_dir: &Path) -> Result<()> {
168 let filename = current
169 .file_name()
170 .ok_or_else(|| Error::Upgrade("Invalid binary path".to_string()))?;
171
172 let backup_path = rollback_dir.join(format!("{}.backup", filename.to_string_lossy()));
173
174 if !backup_path.exists() {
175 return Err(Error::Upgrade("No backup found for rollback".to_string()));
176 }
177
178 info!("Restoring from backup: {}", backup_path.display());
179 fs::copy(&backup_path, current)?;
180 Ok(())
181 }
182
183 pub fn atomic_replace(&self, new_binary: &Path, target: &Path) -> Result<()> {
196 #[cfg(unix)]
198 {
199 if let Ok(meta) = fs::metadata(target) {
200 let perms = meta.permissions();
201 fs::set_permissions(new_binary, perms)?;
202 }
203 }
204
205 fs::rename(new_binary, target)?;
207 debug!("Atomic replacement complete");
208 Ok(())
209 }
210
211 async fn download(&self, url: &str, dest: &Path, kind: traffic::UpgradeFetch) -> Result<()> {
217 debug!("Downloading: {}", url);
218
219 let bytes = match self.fetch_body(url).await {
222 Ok(bytes) => bytes,
223 Err(e) => {
224 traffic::record_error(kind);
225 return Err(e);
226 }
227 };
228 traffic::record_rx(kind, bytes.len());
229
230 Self::enforce_max_binary_size(bytes.len())?;
231
232 fs::write(dest, &bytes)?;
233 debug!("Downloaded {} bytes to {}", bytes.len(), dest.display());
234 Ok(())
235 }
236
237 async fn fetch_body(&self, url: &str) -> Result<bytes::Bytes> {
239 let response = self
240 .client
241 .get(url)
242 .send()
243 .await
244 .map_err(|e| Error::Network(format!("Download failed: {e}")))?;
245
246 if !response.status().is_success() {
247 return Err(Error::Network(format!(
248 "Download returned status: {}",
249 response.status()
250 )));
251 }
252
253 response
254 .bytes()
255 .await
256 .map_err(|e| Error::Network(format!("Failed to read response: {e}")))
257 }
258
259 fn enforce_max_binary_size(len: usize) -> Result<()> {
261 if len > MAX_BINARY_SIZE_BYTES {
262 return Err(Error::Upgrade(format!(
263 "Downloaded binary too large: {len} bytes (max {MAX_BINARY_SIZE_BYTES})"
264 )));
265 }
266 Ok(())
267 }
268
269 fn create_tempdir_in_target_dir(current_binary: &Path) -> Result<tempfile::TempDir> {
273 let target_dir = current_binary
274 .parent()
275 .ok_or_else(|| Error::Upgrade("Current binary has no parent directory".to_string()))?;
276
277 tempfile::Builder::new()
278 .prefix("ant-upgrade-")
279 .tempdir_in(target_dir)
280 .map_err(|e| Error::Upgrade(format!("Failed to create temp dir: {e}")))
281 }
282
283 pub async fn perform_upgrade(
303 &self,
304 info: &UpgradeInfo,
305 current_binary: &Path,
306 rollback_dir: &Path,
307 ) -> Result<UpgradeResult> {
308 if !Self::auto_upgrade_supported() {
311 warn!(
312 "Auto-upgrade is not supported on this platform; refusing upgrade to {}",
313 info.version
314 );
315 return Ok(UpgradeResult::RolledBack {
316 reason: "Auto-upgrade not supported on this platform".to_string(),
317 });
318 }
319
320 self.validate_upgrade(info)?;
322
323 self.create_backup(current_binary, rollback_dir)?;
325
326 let temp_dir = Self::create_tempdir_in_target_dir(current_binary)?;
328 let new_binary = temp_dir.path().join("new_binary");
329 let sig_path = temp_dir.path().join("signature");
330
331 if let Err(e) = self
332 .download(
333 &info.download_url,
334 &new_binary,
335 traffic::UpgradeFetch::Binary,
336 )
337 .await
338 {
339 warn!("Download failed: {e}");
340 return Ok(UpgradeResult::RolledBack {
341 reason: format!("Download failed: {e}"),
342 });
343 }
344
345 if let Err(e) = self
346 .download(
347 &info.signature_url,
348 &sig_path,
349 traffic::UpgradeFetch::Signature,
350 )
351 .await
352 {
353 warn!("Signature download failed: {e}");
354 return Ok(UpgradeResult::RolledBack {
355 reason: format!("Signature download failed: {e}"),
356 });
357 }
358
359 if let Err(e) = signature::verify_from_file(&new_binary, &sig_path) {
361 warn!("Signature verification failed: {e}");
362 return Ok(UpgradeResult::RolledBack {
363 reason: format!("Signature verification failed: {e}"),
364 });
365 }
366
367 if let Err(e) = self.atomic_replace(&new_binary, current_binary) {
369 warn!("Replacement failed, rolling back: {e}");
370 if let Err(restore_err) = self.restore_from_backup(current_binary, rollback_dir) {
371 return Err(Error::Upgrade(format!(
372 "Critical: replacement failed ({e}) AND rollback failed ({restore_err})"
373 )));
374 }
375 return Ok(UpgradeResult::RolledBack {
376 reason: format!("Replacement failed: {e}"),
377 });
378 }
379
380 info!("Successfully upgraded to version {}", info.version);
381 Ok(UpgradeResult::Success {
382 version: info.version.clone(),
383 exit_code: 0,
384 })
385 }
386
387 const fn auto_upgrade_supported() -> bool {
391 true
392 }
393}
394
395impl Default for Upgrader {
396 fn default() -> Self {
397 Self::new()
398 }
399}
400
401pub async fn perform_upgrade(
407 info: &UpgradeInfo,
408 current_binary: &Path,
409 rollback_dir: &Path,
410) -> Result<UpgradeResult> {
411 Upgrader::new()
412 .perform_upgrade(info, current_binary, rollback_dir)
413 .await
414}
415
416#[cfg(test)]
417#[allow(
418 clippy::unwrap_used,
419 clippy::expect_used,
420 clippy::doc_markdown,
421 clippy::cast_possible_truncation,
422 clippy::cast_sign_loss,
423 clippy::case_sensitive_file_extension_comparisons
424)]
425mod tests {
426 use super::*;
427 use tempfile::TempDir;
428
429 #[test]
431 fn test_backup_created() {
432 let temp = TempDir::new().unwrap();
433 let current = temp.path().join("current");
434 let rollback_dir = temp.path().join("rollback");
435 fs::create_dir(&rollback_dir).unwrap();
436
437 let original_content = b"old binary content";
438 fs::write(¤t, original_content).unwrap();
439
440 let upgrader = Upgrader::new();
441 upgrader.create_backup(¤t, &rollback_dir).unwrap();
442
443 let backup_path = rollback_dir.join("current.backup");
444 assert!(backup_path.exists(), "Backup file should exist");
445 assert_eq!(
446 fs::read(&backup_path).unwrap(),
447 original_content,
448 "Backup content should match"
449 );
450 }
451
452 #[test]
454 fn test_restore_from_backup() {
455 let temp = TempDir::new().unwrap();
456 let current = temp.path().join("binary");
457 let rollback_dir = temp.path().join("rollback");
458 fs::create_dir(&rollback_dir).unwrap();
459
460 let original = b"original content";
461 fs::write(¤t, original).unwrap();
462
463 let upgrader = Upgrader::new();
464 upgrader.create_backup(¤t, &rollback_dir).unwrap();
465
466 fs::write(¤t, b"corrupted content").unwrap();
468
469 upgrader
471 .restore_from_backup(¤t, &rollback_dir)
472 .unwrap();
473
474 assert_eq!(fs::read(¤t).unwrap(), original);
475 }
476
477 #[test]
479 fn test_atomic_replacement() {
480 let temp = TempDir::new().unwrap();
481 let current = temp.path().join("binary");
482 let new_binary = temp.path().join("new_binary");
483
484 fs::write(¤t, b"old").unwrap();
485 fs::write(&new_binary, b"new").unwrap();
486
487 let upgrader = Upgrader::new();
488 upgrader.atomic_replace(&new_binary, ¤t).unwrap();
489
490 assert_eq!(fs::read(¤t).unwrap(), b"new");
491 assert!(!new_binary.exists(), "Source should be moved, not copied");
492 }
493
494 #[test]
496 fn test_downgrade_prevention() {
497 let current_version = Version::new(1, 1, 0);
498 let older_version = Version::new(1, 0, 0);
499
500 let upgrader = Upgrader::with_version(current_version);
501
502 let info = UpgradeInfo {
503 version: older_version,
504 download_url: "test".to_string(),
505 signature_url: "test.sig".to_string(),
506 release_notes: "Old".to_string(),
507 };
508
509 let result = upgrader.validate_upgrade(&info);
510 assert!(result.is_err());
511 let err_msg = result.unwrap_err().to_string();
512 assert!(
513 err_msg.contains("downgrade") || err_msg.contains("Cannot"),
514 "Error should mention downgrade prevention: {err_msg}"
515 );
516 }
517
518 #[test]
520 fn test_same_version_prevention() {
521 let version = Version::new(1, 0, 0);
522 let upgrader = Upgrader::with_version(version.clone());
523
524 let info = UpgradeInfo {
525 version,
526 download_url: "test".to_string(),
527 signature_url: "test.sig".to_string(),
528 release_notes: "Same".to_string(),
529 };
530
531 let result = upgrader.validate_upgrade(&info);
532 assert!(result.is_err(), "Same version should be rejected");
533 }
534
535 #[test]
537 fn test_upgrade_validation_passes() {
538 let upgrader = Upgrader::with_version(Version::new(1, 0, 0));
539
540 let info = UpgradeInfo {
541 version: Version::new(1, 1, 0),
542 download_url: "test".to_string(),
543 signature_url: "test.sig".to_string(),
544 release_notes: "New".to_string(),
545 };
546
547 let result = upgrader.validate_upgrade(&info);
548 assert!(result.is_ok(), "Newer version should be accepted");
549 }
550
551 #[test]
553 fn test_restore_fails_without_backup() {
554 let temp = TempDir::new().unwrap();
555 let current = temp.path().join("binary");
556 let rollback_dir = temp.path().join("rollback");
557 fs::create_dir(&rollback_dir).unwrap();
558
559 fs::write(¤t, b"content").unwrap();
560
561 let upgrader = Upgrader::new();
562 let result = upgrader.restore_from_backup(¤t, &rollback_dir);
563
564 assert!(result.is_err());
565 assert!(result.unwrap_err().to_string().contains("No backup"));
566 }
567
568 #[cfg(unix)]
570 #[test]
571 fn test_permissions_preserved() {
572 use std::os::unix::fs::PermissionsExt;
573
574 let temp = TempDir::new().unwrap();
575 let current = temp.path().join("binary");
576 let new_binary = temp.path().join("new");
577
578 fs::write(¤t, b"old").unwrap();
579 fs::write(&new_binary, b"new").unwrap();
580
581 let mut perms = fs::metadata(¤t).unwrap().permissions();
583 perms.set_mode(0o755);
584 fs::set_permissions(¤t, perms).unwrap();
585
586 let upgrader = Upgrader::new();
587 upgrader.atomic_replace(&new_binary, ¤t).unwrap();
588
589 let new_perms = fs::metadata(¤t).unwrap().permissions();
590 assert_eq!(
591 new_perms.mode() & 0o777,
592 0o755,
593 "Permissions should be preserved"
594 );
595 }
596
597 #[test]
599 fn test_current_version_getter() {
600 let version = Version::new(2, 3, 4);
601 let upgrader = Upgrader::with_version(version.clone());
602 assert_eq!(*upgrader.current_version(), version);
603 }
604
605 #[test]
607 fn test_default_impl() {
608 let upgrader = Upgrader::default();
609 assert!(
611 !upgrader.current_version().to_string().is_empty(),
612 "expected a non-empty current version"
613 );
614 }
615
616 #[test]
618 fn test_backup_special_filename() {
619 let temp = TempDir::new().unwrap();
620 let current = temp.path().join("ant-node-v1.0.0");
621 let rollback_dir = temp.path().join("rollback");
622 fs::create_dir(&rollback_dir).unwrap();
623
624 fs::write(¤t, b"content").unwrap();
625
626 let upgrader = Upgrader::new();
627 let result = upgrader.create_backup(¤t, &rollback_dir);
628 assert!(result.is_ok());
629
630 let backup_path = rollback_dir.join("ant-node-v1.0.0.backup");
631 assert!(backup_path.exists());
632 }
633
634 #[test]
636 fn test_upgrade_info() {
637 let info = UpgradeInfo {
638 version: Version::new(1, 2, 3),
639 download_url: "https://example.com/binary".to_string(),
640 signature_url: "https://example.com/binary.sig".to_string(),
641 release_notes: "Bug fixes and improvements".to_string(),
642 };
643
644 assert_eq!(info.version, Version::new(1, 2, 3));
645 assert!(info.download_url.contains("example.com"));
646 assert!(info.signature_url.ends_with(".sig"));
647 }
648
649 #[test]
651 fn test_upgrade_result_variants() {
652 let success = UpgradeResult::Success {
653 version: Version::new(1, 0, 0),
654 exit_code: 0,
655 };
656 assert!(matches!(success, UpgradeResult::Success { .. }));
657
658 let rolled_back = UpgradeResult::RolledBack {
659 reason: "Test failure".to_string(),
660 };
661 assert!(matches!(rolled_back, UpgradeResult::RolledBack { .. }));
662
663 let no_upgrade = UpgradeResult::NoUpgrade;
664 assert!(matches!(no_upgrade, UpgradeResult::NoUpgrade));
665 }
666
667 #[test]
669 fn test_large_file_backup() {
670 let temp = TempDir::new().unwrap();
671 let current = temp.path().join("large_binary");
672 let rollback_dir = temp.path().join("rollback");
673 fs::create_dir(&rollback_dir).unwrap();
674
675 let large_content: Vec<u8> = (0..1_000_000).map(|i| (i % 256) as u8).collect();
677 fs::write(¤t, &large_content).unwrap();
678
679 let upgrader = Upgrader::new();
680 upgrader.create_backup(¤t, &rollback_dir).unwrap();
681
682 let backup_path = rollback_dir.join("large_binary.backup");
683 assert_eq!(fs::read(&backup_path).unwrap(), large_content);
684 }
685
686 #[test]
688 fn test_backup_nonexistent_rollback_dir() {
689 let temp = TempDir::new().unwrap();
690 let current = temp.path().join("binary");
691 let rollback_dir = temp.path().join("nonexistent");
692
693 fs::write(¤t, b"content").unwrap();
694
695 let upgrader = Upgrader::new();
696 let result = upgrader.create_backup(¤t, &rollback_dir);
697
698 assert!(result.is_err(), "Should fail if rollback dir doesn't exist");
699 }
700
701 #[test]
703 fn test_tempdir_in_target_dir() {
704 let temp = TempDir::new().unwrap();
705 let current = temp.path().join("binary");
706 fs::write(¤t, b"content").unwrap();
707
708 let tempdir = Upgrader::create_tempdir_in_target_dir(¤t).unwrap();
709
710 assert_eq!(
711 tempdir.path().parent().unwrap(),
712 temp.path(),
713 "Upgrade tempdir should be in same dir as target"
714 );
715 }
716
717 #[test]
719 fn test_enforce_max_binary_size_rejects_large() {
720 let too_large = MAX_BINARY_SIZE_BYTES + 1;
721 let result = Upgrader::enforce_max_binary_size(too_large);
722 assert!(result.is_err());
723 }
724
725 #[test]
727 fn test_enforce_max_binary_size_accepts_small() {
728 let result = Upgrader::enforce_max_binary_size(1024);
729 assert!(result.is_ok());
730 }
731
732 #[test]
733 fn test_auto_upgrade_supported_on_all_platforms() {
734 assert!(Upgrader::auto_upgrade_supported());
735 }
736}