Skip to main content

ant_node/upgrade/
mod.rs

1//! Auto-upgrade system with ML-DSA signature verification.
2//!
3//! This module handles:
4//! - Polling GitHub releases for new versions
5//! - Verifying ML-DSA-65 signatures on binaries
6//! - Replacing the running binary with rollback support
7//! - Staged rollout to prevent mass network restarts
8//! - Auto-apply: download, extract, verify, replace, restart
9
10mod 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
36/// Maximum allowed upgrade binary size (200 MiB).
37///
38/// This is a sanity limit to prevent memory exhaustion during ML-DSA verification,
39/// which requires loading the full binary into RAM.
40const MAX_BINARY_SIZE_BYTES: usize = 200 * 1024 * 1024;
41
42/// Information about an available upgrade.
43#[derive(Debug, Clone)]
44pub struct UpgradeInfo {
45    /// The new version.
46    pub version: Version,
47    /// Download URL for the binary.
48    pub download_url: String,
49    /// Signature URL.
50    pub signature_url: String,
51    /// Release notes.
52    pub release_notes: String,
53}
54
55/// Result of an upgrade operation.
56#[derive(Debug)]
57pub enum UpgradeResult {
58    /// Upgrade was successful and the process should exit to complete the restart.
59    Success {
60        /// The new version.
61        version: Version,
62        /// Exit code to use when terminating the process.
63        /// The caller should trigger graceful shutdown, then exit with this code.
64        exit_code: i32,
65    },
66    /// Upgrade failed, rolled back.
67    RolledBack {
68        /// Error that caused the rollback.
69        reason: String,
70    },
71    /// No upgrade available.
72    NoUpgrade,
73}
74
75/// Upgrade orchestrator with rollback support.
76///
77/// Handles the complete upgrade lifecycle:
78/// 1. Validate upgrade (prevent downgrade)
79/// 2. Download new binary and signature
80/// 3. Verify ML-DSA-65 signature
81/// 4. Create backup of current binary
82/// 5. Atomic replacement
83/// 6. Rollback on failure
84pub struct Upgrader {
85    /// Current running version.
86    current_version: Version,
87    /// HTTP client for downloads.
88    client: reqwest::Client,
89}
90
91impl Upgrader {
92    /// Create a new upgrader with the current package version.
93    #[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    /// Create an upgrader with a custom version (for testing).
105    #[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    /// Get the current version.
115    #[must_use]
116    pub fn current_version(&self) -> &Version {
117        &self.current_version
118    }
119
120    /// Validate that the upgrade is allowed (prevents downgrade).
121    ///
122    /// # Errors
123    ///
124    /// Returns an error if the target version is older than or equal to current.
125    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    /// Create a backup of the current binary.
136    ///
137    /// # Arguments
138    ///
139    /// * `current` - Path to the current binary
140    /// * `rollback_dir` - Directory to store the backup
141    ///
142    /// # Errors
143    ///
144    /// Returns an error if the backup cannot be created.
145    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    /// Restore binary from backup.
158    ///
159    /// # Arguments
160    ///
161    /// * `current` - Path to restore to
162    /// * `rollback_dir` - Directory containing the backup
163    ///
164    /// # Errors
165    ///
166    /// Returns an error if the backup cannot be restored.
167    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    /// Atomically replace the binary (rename on POSIX).
184    ///
185    /// Preserves file permissions from the original binary.
186    ///
187    /// # Arguments
188    ///
189    /// * `new_binary` - Path to the new binary
190    /// * `target` - Path to replace
191    ///
192    /// # Errors
193    ///
194    /// Returns an error if the replacement fails.
195    pub fn atomic_replace(&self, new_binary: &Path, target: &Path) -> Result<()> {
196        // Preserve original permissions on Unix
197        #[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        // Atomic rename
206        fs::rename(new_binary, target)?;
207        debug!("Atomic replacement complete");
208        Ok(())
209    }
210
211    /// Download a file to the specified path.
212    ///
213    /// # Errors
214    ///
215    /// Returns an error if the download fails.
216    async fn download(&self, url: &str, dest: &Path, kind: traffic::UpgradeFetch) -> Result<()> {
217        debug!("Downloading: {}", url);
218
219        // V2-834: count the body once fully read; anything short of that is
220        // an error for this fetch kind.
221        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    /// GET `url` and read the whole body.
238    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    /// Ensure the downloaded binary is within a sane size limit.
260    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    /// Create a temp directory for upgrades in the same directory as the target binary.
270    ///
271    /// Ensures `fs::rename` is atomic by keeping source/target on the same filesystem.
272    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    /// Perform upgrade with rollback support.
284    ///
285    /// This is the main upgrade entry point. It:
286    /// 1. Validates the upgrade (prevents downgrade)
287    /// 2. Creates a backup of the current binary
288    /// 3. Downloads the new binary and signature
289    /// 4. Verifies the ML-DSA-65 signature
290    /// 5. Atomically replaces the binary
291    /// 6. Rolls back on any failure
292    ///
293    /// # Arguments
294    ///
295    /// * `info` - Information about the upgrade to perform
296    /// * `current_binary` - Path to the currently running binary
297    /// * `rollback_dir` - Directory to store backup for rollback
298    ///
299    /// # Errors
300    ///
301    /// Returns an error only if both the upgrade AND rollback fail (critical).
302    pub async fn perform_upgrade(
303        &self,
304        info: &UpgradeInfo,
305        current_binary: &Path,
306        rollback_dir: &Path,
307    ) -> Result<UpgradeResult> {
308        // Auto-upgrade on Windows is not supported yet due to running-binary locks.
309        // We fail closed with an explicit reason rather than attempting a broken replace.
310        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        // 1. Validate upgrade
321        self.validate_upgrade(info)?;
322
323        // 2. Create backup
324        self.create_backup(current_binary, rollback_dir)?;
325
326        // 3. Download new binary and signature to temp directory
327        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        // 4. Verify signature
360        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        // 5. Atomic replacement
368        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    /// Whether the current platform supports in-place auto-upgrade.
388    ///
389    /// Supported on Unix (via `exec()`) and Windows (via `self-replace` crate).
390    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
401/// Legacy function for backward compatibility.
402///
403/// # Errors
404///
405/// Returns an error if the upgrade fails and rollback is not possible.
406pub 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 1: Backup creation
430    #[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(&current, original_content).unwrap();
439
440        let upgrader = Upgrader::new();
441        upgrader.create_backup(&current, &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 2: Restore from backup
453    #[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(&current, original).unwrap();
462
463        let upgrader = Upgrader::new();
464        upgrader.create_backup(&current, &rollback_dir).unwrap();
465
466        // Simulate corruption
467        fs::write(&current, b"corrupted content").unwrap();
468
469        // Restore
470        upgrader
471            .restore_from_backup(&current, &rollback_dir)
472            .unwrap();
473
474        assert_eq!(fs::read(&current).unwrap(), original);
475    }
476
477    /// Test 3: Atomic replacement
478    #[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(&current, b"old").unwrap();
485        fs::write(&new_binary, b"new").unwrap();
486
487        let upgrader = Upgrader::new();
488        upgrader.atomic_replace(&new_binary, &current).unwrap();
489
490        assert_eq!(fs::read(&current).unwrap(), b"new");
491        assert!(!new_binary.exists(), "Source should be moved, not copied");
492    }
493
494    /// Test 4: Downgrade prevention
495    #[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 5: Same version prevention
519    #[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 6: Upgrade validation passes for newer version
536    #[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 7: Restore fails without backup
552    #[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(&current, b"content").unwrap();
560
561        let upgrader = Upgrader::new();
562        let result = upgrader.restore_from_backup(&current, &rollback_dir);
563
564        assert!(result.is_err());
565        assert!(result.unwrap_err().to_string().contains("No backup"));
566    }
567
568    /// Test 8: Permissions preserved on Unix
569    #[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(&current, b"old").unwrap();
579        fs::write(&new_binary, b"new").unwrap();
580
581        // Set executable permissions on original
582        let mut perms = fs::metadata(&current).unwrap().permissions();
583        perms.set_mode(0o755);
584        fs::set_permissions(&current, perms).unwrap();
585
586        let upgrader = Upgrader::new();
587        upgrader.atomic_replace(&new_binary, &current).unwrap();
588
589        let new_perms = fs::metadata(&current).unwrap().permissions();
590        assert_eq!(
591            new_perms.mode() & 0o777,
592            0o755,
593            "Permissions should be preserved"
594        );
595    }
596
597    /// Test 9: Current version getter
598    #[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 10: Default implementation
606    #[test]
607    fn test_default_impl() {
608        let upgrader = Upgrader::default();
609        // Should not panic and should have a valid version
610        assert!(!upgrader.current_version().to_string().is_empty());
611    }
612
613    /// Test 11: Backup with special characters in filename
614    #[test]
615    fn test_backup_special_filename() {
616        let temp = TempDir::new().unwrap();
617        let current = temp.path().join("ant-node-v1.0.0");
618        let rollback_dir = temp.path().join("rollback");
619        fs::create_dir(&rollback_dir).unwrap();
620
621        fs::write(&current, b"content").unwrap();
622
623        let upgrader = Upgrader::new();
624        let result = upgrader.create_backup(&current, &rollback_dir);
625        assert!(result.is_ok());
626
627        let backup_path = rollback_dir.join("ant-node-v1.0.0.backup");
628        assert!(backup_path.exists());
629    }
630
631    /// Test 12: UpgradeInfo construction
632    #[test]
633    fn test_upgrade_info() {
634        let info = UpgradeInfo {
635            version: Version::new(1, 2, 3),
636            download_url: "https://example.com/binary".to_string(),
637            signature_url: "https://example.com/binary.sig".to_string(),
638            release_notes: "Bug fixes and improvements".to_string(),
639        };
640
641        assert_eq!(info.version, Version::new(1, 2, 3));
642        assert!(info.download_url.contains("example.com"));
643        assert!(info.signature_url.ends_with(".sig"));
644    }
645
646    /// Test 13: UpgradeResult variants
647    #[test]
648    fn test_upgrade_result_variants() {
649        let success = UpgradeResult::Success {
650            version: Version::new(1, 0, 0),
651            exit_code: 0,
652        };
653        assert!(matches!(success, UpgradeResult::Success { .. }));
654
655        let rolled_back = UpgradeResult::RolledBack {
656            reason: "Test failure".to_string(),
657        };
658        assert!(matches!(rolled_back, UpgradeResult::RolledBack { .. }));
659
660        let no_upgrade = UpgradeResult::NoUpgrade;
661        assert!(matches!(no_upgrade, UpgradeResult::NoUpgrade));
662    }
663
664    /// Test 14: Large file backup
665    #[test]
666    fn test_large_file_backup() {
667        let temp = TempDir::new().unwrap();
668        let current = temp.path().join("large_binary");
669        let rollback_dir = temp.path().join("rollback");
670        fs::create_dir(&rollback_dir).unwrap();
671
672        // Create 1MB file
673        let large_content: Vec<u8> = (0..1_000_000).map(|i| (i % 256) as u8).collect();
674        fs::write(&current, &large_content).unwrap();
675
676        let upgrader = Upgrader::new();
677        upgrader.create_backup(&current, &rollback_dir).unwrap();
678
679        let backup_path = rollback_dir.join("large_binary.backup");
680        assert_eq!(fs::read(&backup_path).unwrap(), large_content);
681    }
682
683    /// Test 15: Backup directory doesn't exist
684    #[test]
685    fn test_backup_nonexistent_rollback_dir() {
686        let temp = TempDir::new().unwrap();
687        let current = temp.path().join("binary");
688        let rollback_dir = temp.path().join("nonexistent");
689
690        fs::write(&current, b"content").unwrap();
691
692        let upgrader = Upgrader::new();
693        let result = upgrader.create_backup(&current, &rollback_dir);
694
695        assert!(result.is_err(), "Should fail if rollback dir doesn't exist");
696    }
697
698    /// Test 16: Tempdir for upgrades is created in target directory.
699    #[test]
700    fn test_tempdir_in_target_dir() {
701        let temp = TempDir::new().unwrap();
702        let current = temp.path().join("binary");
703        fs::write(&current, b"content").unwrap();
704
705        let tempdir = Upgrader::create_tempdir_in_target_dir(&current).unwrap();
706
707        assert_eq!(
708            tempdir.path().parent().unwrap(),
709            temp.path(),
710            "Upgrade tempdir should be in same dir as target"
711        );
712    }
713
714    /// Test 17: Enforce max binary size rejects huge downloads.
715    #[test]
716    fn test_enforce_max_binary_size_rejects_large() {
717        let too_large = MAX_BINARY_SIZE_BYTES + 1;
718        let result = Upgrader::enforce_max_binary_size(too_large);
719        assert!(result.is_err());
720    }
721
722    /// Test 18: Enforce max binary size accepts reasonable downloads.
723    #[test]
724    fn test_enforce_max_binary_size_accepts_small() {
725        let result = Upgrader::enforce_max_binary_size(1024);
726        assert!(result.is_ok());
727    }
728
729    #[test]
730    fn test_auto_upgrade_supported_on_all_platforms() {
731        assert!(Upgrader::auto_upgrade_supported());
732    }
733}