inferno-ai 0.10.3

Enterprise AI/ML model runner with automatic updates, real-time monitoring, and multi-interface support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
#![allow(dead_code, unused_imports, unused_variables, clippy::ptr_arg)]
//! # Safety Checker
//!
//! Pre-installation safety checks to ensure system compatibility,
//! sufficient resources, and safe upgrade conditions.

use super::{UpdateInfo, UpgradeConfig, UpgradeError, UpgradeResult};
use base64::Engine;
use ring::signature::{self, UnparsedPublicKey};
use std::io::Read;
use std::path::PathBuf;
use std::process::Command;
use sysinfo::{DiskExt, ProcessExt, System, SystemExt};
use tracing::{debug, info, warn};

/// Inferno's Ed25519 public key for signature verification
/// This key is used to verify update packages are from the official Inferno project
const INFERNO_PUBLIC_KEY: &[u8] = &[
    // Placeholder public key - in production, this would be the actual Ed25519 public key
    // Ed25519 public keys are 32 bytes
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];

/// Safety checker for pre-installation validation
pub struct SafetyChecker {
    config: UpgradeConfig,
    system: System,
}

/// System compatibility check result
#[derive(Debug, Clone)]
pub struct CompatibilityReport {
    pub os_compatible: bool,
    pub arch_compatible: bool,
    pub version_compatible: bool,
    pub dependencies_satisfied: bool,
    pub issues: Vec<String>,
    pub warnings: Vec<String>,
}

/// Resource availability check result
#[derive(Debug, Clone)]
pub struct ResourceReport {
    pub disk_space_sufficient: bool,
    pub memory_sufficient: bool,
    pub cpu_load_acceptable: bool,
    pub network_available: bool,
    pub available_disk_mb: u64,
    pub available_memory_mb: u64,
    pub cpu_usage_percent: f32,
    pub issues: Vec<String>,
}

impl SafetyChecker {
    /// Create a new safety checker
    pub fn new(config: &UpgradeConfig) -> Self {
        let mut system = System::new_all();
        system.refresh_all();

        Self {
            config: config.clone(),
            system,
        }
    }

    /// Perform comprehensive pre-installation safety checks
    pub async fn check_pre_installation(&mut self, update_info: &UpdateInfo) -> UpgradeResult<()> {
        info!("Running pre-installation safety checks");

        // Refresh system information
        self.system.refresh_all();

        // Run all safety checks
        if self.config.safety_checks.check_compatibility {
            self.check_system_compatibility(update_info).await?;
        }

        if self.config.safety_checks.check_disk_space {
            self.check_disk_space(update_info).await?;
        }

        if self.config.safety_checks.check_network {
            self.check_network_connectivity().await?;
        }

        if self.config.safety_checks.check_running_processes {
            self.check_running_processes().await?;
        }

        if self.config.safety_checks.check_dependencies {
            self.check_system_dependencies().await?;
        }

        info!("All pre-installation safety checks passed");
        Ok(())
    }

    /// Verify package integrity and authenticity
    pub async fn verify_package(
        &self,
        package_path: &PathBuf,
        update_info: &UpdateInfo,
    ) -> UpgradeResult<()> {
        info!("Verifying package integrity");

        // Check if file exists
        if !package_path.exists() {
            return Err(UpgradeError::InvalidPackage(
                "Package file not found".to_string(),
            ));
        }

        // Verify file size
        let file_size = std::fs::metadata(package_path)
            .map_err(|e| UpgradeError::InvalidPackage(e.to_string()))?
            .len();

        let platform = std::env::consts::OS;
        if let Some(expected_size) = update_info.size_bytes.get(platform) {
            if file_size != *expected_size {
                return Err(UpgradeError::VerificationFailed(format!(
                    "File size mismatch: expected {} bytes, got {} bytes",
                    expected_size, file_size
                )));
            }
        }

        // Verify file format based on extension
        self.verify_package_format(package_path).await?;

        // Verify digital signature if required
        if self.config.require_signatures {
            self.verify_package_signature(package_path, update_info)
                .await?;
        }

        // Additional malware scanning could go here
        if self.is_malware_scanning_available() {
            self.scan_for_malware(package_path).await?;
        }

        info!("Package verification completed successfully");
        Ok(())
    }

    /// Check system compatibility
    async fn check_system_compatibility(&self, update_info: &UpdateInfo) -> UpgradeResult<()> {
        debug!("Checking system compatibility");

        // Check OS compatibility
        let current_os = std::env::consts::OS;
        if !update_info.download_urls.contains_key(current_os) {
            return Err(UpgradeError::PlatformNotSupported(current_os.to_string()));
        }

        // Check architecture compatibility
        let current_arch = std::env::consts::ARCH;
        debug!("Current architecture: {}", current_arch);

        // Check minimum version requirements
        if let Some(min_version) = &update_info.minimum_version {
            let current_version = super::ApplicationVersion::current();
            if !current_version.is_compatible_with(min_version) {
                return Err(UpgradeError::VerificationFailed(format!(
                    "Current version {} is not compatible with minimum required version {}",
                    current_version.to_string(),
                    min_version.to_string()
                )));
            }
        }

        // Check system version (OS version)
        self.check_os_version_compatibility()?;

        Ok(())
    }

    /// Check available disk space
    async fn check_disk_space(&self, update_info: &UpdateInfo) -> UpgradeResult<()> {
        debug!("Checking disk space");

        let platform = std::env::consts::OS;
        let package_size = update_info.size_bytes.get(platform).copied().unwrap_or(0);

        // Account for decompression (estimate 3x package size)
        let required_space =
            package_size * 3 + (self.config.safety_checks.min_free_space_mb * 1024 * 1024);

        // Get available disk space
        let available_space = self.get_available_disk_space(&self.config.download_dir)?;

        if available_space < required_space {
            return Err(UpgradeError::InsufficientDiskSpace {
                required: required_space / 1024 / 1024,
                available: available_space / 1024 / 1024,
            });
        }

        debug!(
            "Disk space check passed: {} MB available, {} MB required",
            available_space / 1024 / 1024,
            required_space / 1024 / 1024
        );

        Ok(())
    }

    /// Check network connectivity
    async fn check_network_connectivity(&self) -> UpgradeResult<()> {
        debug!("Checking network connectivity");

        // Simple connectivity check - try to resolve a known domain
        let result = tokio::time::timeout(
            std::time::Duration::from_secs(10),
            tokio::net::lookup_host("api.github.com:443"),
        )
        .await;

        match result {
            Ok(Ok(_)) => {
                debug!("Network connectivity check passed");
                Ok(())
            }
            Ok(Err(e)) => Err(UpgradeError::NetworkError(format!(
                "DNS resolution failed: {}",
                e
            ))),
            Err(_) => Err(UpgradeError::NetworkError(
                "Network connectivity timeout".to_string(),
            )),
        }
    }

    /// Check for potentially interfering running processes
    async fn check_running_processes(&self) -> UpgradeResult<()> {
        debug!("Checking running processes");

        let dangerous_processes = vec!["antivirus", "scanner", "backup", "sync", "cloud"];

        for process in self.system.processes().values() {
            let process_name = process.name().to_lowercase();

            for dangerous in &dangerous_processes {
                if process_name.contains(dangerous) {
                    warn!(
                        "Potentially interfering process detected: {}",
                        process.name()
                    );
                    // For now, just warn. In production, you might want to:
                    // - Ask user to close the process
                    // - Automatically pause certain processes
                    // - Defer the upgrade
                }
            }
        }

        // Check if current application instances are running
        let current_exe =
            std::env::current_exe().map_err(|e| UpgradeError::Internal(e.to_string()))?;

        let current_name = current_exe
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("inferno");

        let mut running_instances = 0;
        for (pid, process) in self.system.processes() {
            if process.name().to_lowercase().contains("inferno")
                && *pid != sysinfo::get_current_pid().unwrap()
            {
                running_instances += 1;
            }
        }

        if running_instances > 0 {
            warn!(
                "Found {} other running instances of the application",
                running_instances
            );
        }

        Ok(())
    }

    /// Check system dependencies
    async fn check_system_dependencies(&self) -> UpgradeResult<()> {
        debug!("Checking system dependencies");

        // Check for required system libraries/tools
        #[cfg(target_os = "macos")]
        {
            self.check_macos_dependencies()?;
        }

        #[cfg(target_os = "linux")]
        {
            self.check_linux_dependencies()?;
        }

        #[cfg(target_os = "windows")]
        {
            self.check_windows_dependencies()?;
        }

        Ok(())
    }

    /// Verify package format
    async fn verify_package_format(&self, package_path: &PathBuf) -> UpgradeResult<()> {
        let extension = package_path
            .extension()
            .and_then(|ext| ext.to_str())
            .unwrap_or("");

        match extension.to_lowercase().as_str() {
            "tar" | "tgz" | "tar.gz" => self.verify_tar_format(package_path),
            "zip" => self.verify_zip_format(package_path),
            "pkg" => self.verify_pkg_format(package_path),
            "msi" | "exe" => self.verify_windows_format(package_path),
            "deb" => self.verify_deb_format(package_path),
            "rpm" => self.verify_rpm_format(package_path),
            _ => Err(UpgradeError::InvalidPackage(format!(
                "Unsupported package format: {}",
                extension
            ))),
        }
    }

    /// Verify digital signature using Ed25519
    async fn verify_package_signature(
        &self,
        package_path: &PathBuf,
        update_info: &UpdateInfo,
    ) -> UpgradeResult<()> {
        debug!("Verifying package digital signature");

        let platform = std::env::consts::OS;
        if let Some(signature_b64) = update_info.signatures.get(platform) {
            if signature_b64.is_empty() {
                return Err(UpgradeError::VerificationFailed(
                    "No signature provided".to_string(),
                ));
            }

            // Decode base64 signature
            let signature_bytes =
                base64::Engine::decode(&base64::engine::general_purpose::STANDARD, signature_b64)
                    .map_err(|e| {
                    UpgradeError::VerificationFailed(format!("Invalid signature encoding: {}", e))
                })?;

            // Read package file for verification
            let mut file = std::fs::File::open(package_path).map_err(|e| {
                UpgradeError::VerificationFailed(format!("Cannot open package: {}", e))
            })?;

            let mut package_bytes = Vec::new();
            file.read_to_end(&mut package_bytes).map_err(|e| {
                UpgradeError::VerificationFailed(format!("Cannot read package: {}", e))
            })?;

            // Create public key for verification
            let public_key = UnparsedPublicKey::new(&signature::ED25519, INFERNO_PUBLIC_KEY);

            // Verify signature
            public_key
                .verify(&package_bytes, &signature_bytes)
                .map_err(|_| {
                    UpgradeError::VerificationFailed(
                        "Signature verification failed - package may be tampered".to_string(),
                    )
                })?;

            info!("Package signature verified successfully");
        } else if self.config.require_signatures {
            return Err(UpgradeError::VerificationFailed(
                "Signature required but not provided".to_string(),
            ));
        }

        Ok(())
    }

    /// Scan for malware (if antivirus is available)
    async fn scan_for_malware(&self, package_path: &PathBuf) -> UpgradeResult<()> {
        debug!("Scanning package for malware");

        // This is a placeholder for malware scanning
        // In a real implementation, you might integrate with:
        // - Windows Defender API
        // - ClamAV on Linux
        // - Third-party antivirus APIs

        #[cfg(target_os = "windows")]
        {
            // Check Windows Defender
            if let Ok(output) = Command::new("powershell")
                .args(&[
                    "-Command",
                    "Get-MpComputerStatus | Select-Object RealTimeProtectionEnabled",
                ])
                .output()
            {
                if output.status.success() {
                    debug!("Windows Defender is available for scanning");
                }
            }
        }

        Ok(())
    }

    /// Check if malware scanning is available
    fn is_malware_scanning_available(&self) -> bool {
        #[cfg(target_os = "windows")]
        {
            Command::new("powershell")
                .args(&["-Command", "Get-MpComputerStatus"])
                .output()
                .map(|output| output.status.success())
                .unwrap_or(false)
        }

        #[cfg(target_os = "linux")]
        {
            Command::new("clamscan")
                .arg("--version")
                .output()
                .map(|output| output.status.success())
                .unwrap_or(false)
        }

        #[cfg(target_os = "macos")]
        {
            // macOS doesn't have built-in command-line antivirus
            false
        }

        #[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
        {
            false
        }
    }

    /// Get available disk space for a given path
    fn get_available_disk_space(&self, path: &PathBuf) -> UpgradeResult<u64> {
        for disk in self.system.disks() {
            if path.starts_with(disk.mount_point()) {
                return Ok(disk.available_space());
            }
        }

        // Fallback: try to get space for root filesystem
        if let Some(root_disk) = self.system.disks().first() {
            Ok(root_disk.available_space())
        } else {
            Err(UpgradeError::Internal(
                "Cannot determine available disk space".to_string(),
            ))
        }
    }

    /// Check OS version compatibility
    fn check_os_version_compatibility(&self) -> UpgradeResult<()> {
        let os_version = self.system.os_version();
        debug!("OS version: {:?}", os_version);

        #[cfg(target_os = "macos")]
        {
            // Check minimum macOS version (example: 10.15+)
            if let Some(version) = os_version {
                if self.is_macos_version_too_old(&version) {
                    return Err(UpgradeError::PlatformNotSupported(format!(
                        "macOS version {} is too old. Minimum version required: 10.15",
                        version
                    )));
                }
            }
        }

        #[cfg(target_os = "linux")]
        {
            // Check kernel version and distribution
            if let Some(version) = os_version {
                debug!("Linux version: {}", version);
                // Additional Linux-specific checks could go here
            }
        }

        Ok(())
    }

    // Platform-specific dependency checks
    #[cfg(target_os = "macos")]
    fn check_macos_dependencies(&self) -> UpgradeResult<()> {
        // Check for required macOS frameworks/libraries
        debug!("Checking macOS dependencies");
        Ok(())
    }

    #[cfg(target_os = "linux")]
    fn check_linux_dependencies(&self) -> UpgradeResult<()> {
        // Check for required Linux libraries
        debug!("Checking Linux dependencies");
        Ok(())
    }

    #[cfg(target_os = "windows")]
    fn check_windows_dependencies(&self) -> UpgradeResult<()> {
        // Check for required Windows components
        debug!("Checking Windows dependencies");
        Ok(())
    }

    // Package format verification methods
    fn verify_tar_format(&self, path: &PathBuf) -> UpgradeResult<()> {
        // Basic tar file validation
        Command::new("tar")
            .args(["-tf", path.to_str().unwrap()])
            .output()
            .map_err(|e| UpgradeError::InvalidPackage(format!("Tar validation failed: {}", e)))
            .and_then(|output| {
                if output.status.success() {
                    Ok(())
                } else {
                    Err(UpgradeError::InvalidPackage(
                        "Invalid tar file format".to_string(),
                    ))
                }
            })
    }

    fn verify_zip_format(&self, path: &PathBuf) -> UpgradeResult<()> {
        // Basic zip file validation
        use std::fs::File;
        let file = File::open(path).map_err(|e| UpgradeError::InvalidPackage(e.to_string()))?;

        // Check ZIP magic bytes
        use std::io::Read;
        let mut magic = [0u8; 4];
        let mut reader = file;
        reader
            .read_exact(&mut magic)
            .map_err(|e| UpgradeError::InvalidPackage(e.to_string()))?;

        if &magic == b"PK\x03\x04" || &magic == b"PK\x05\x06" || &magic == b"PK\x07\x08" {
            Ok(())
        } else {
            Err(UpgradeError::InvalidPackage(
                "Invalid ZIP file format".to_string(),
            ))
        }
    }

    fn verify_pkg_format(&self, _path: &PathBuf) -> UpgradeResult<()> {
        // macOS pkg validation would go here
        Ok(())
    }

    fn verify_windows_format(&self, _path: &PathBuf) -> UpgradeResult<()> {
        // Windows MSI/EXE validation would go here
        Ok(())
    }

    fn verify_deb_format(&self, path: &PathBuf) -> UpgradeResult<()> {
        // Debian package validation
        Command::new("dpkg")
            .args(["--info", path.to_str().unwrap()])
            .output()
            .map_err(|e| UpgradeError::InvalidPackage(format!("DEB validation failed: {}", e)))
            .and_then(|output| {
                if output.status.success() {
                    Ok(())
                } else {
                    Err(UpgradeError::InvalidPackage(
                        "Invalid DEB package format".to_string(),
                    ))
                }
            })
    }

    fn verify_rpm_format(&self, path: &PathBuf) -> UpgradeResult<()> {
        // RPM package validation
        Command::new("rpm")
            .args(["-qp", path.to_str().unwrap()])
            .output()
            .map_err(|e| UpgradeError::InvalidPackage(format!("RPM validation failed: {}", e)))
            .and_then(|output| {
                if output.status.success() {
                    Ok(())
                } else {
                    Err(UpgradeError::InvalidPackage(
                        "Invalid RPM package format".to_string(),
                    ))
                }
            })
    }

    #[cfg(target_os = "macos")]
    fn is_macos_version_too_old(&self, version: &str) -> bool {
        // Simple version comparison for macOS
        // This is a simplified check - a real implementation would use proper version parsing
        let major_version = version
            .split('.')
            .next()
            .and_then(|s| s.parse::<u32>().ok())
            .unwrap_or(0);

        major_version < 10 || (major_version == 10 && self.get_macos_minor_version(version) < 15)
    }

    #[cfg(target_os = "macos")]
    fn get_macos_minor_version(&self, version: &str) -> u32 {
        version
            .split('.')
            .nth(1)
            .and_then(|s| s.parse::<u32>().ok())
            .unwrap_or(0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn create_test_config() -> UpgradeConfig {
        let temp_dir = TempDir::new().unwrap();
        UpgradeConfig {
            download_dir: temp_dir.path().to_path_buf(),
            backup_dir: temp_dir.path().to_path_buf(),
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn test_safety_checker_creation() {
        let config = create_test_config();
        let checker = SafetyChecker::new(&config);
        assert!(checker.system.disks().len() > 0);
    }

    #[tokio::test]
    async fn test_network_connectivity() {
        let config = create_test_config();
        let checker = SafetyChecker::new(&config);

        // This test might fail in offline environments
        let result = checker.check_network_connectivity().await;
        if result.is_err() {
            println!(
                "Network connectivity test failed (expected in offline environments): {:?}",
                result
            );
        }
    }

    #[test]
    fn test_disk_space_calculation() {
        let config = create_test_config();
        let checker = SafetyChecker::new(&config);

        let space = checker.get_available_disk_space(&config.download_dir);
        assert!(space.is_ok());
        assert!(space.unwrap() > 0);
    }
}