torsh-package 0.1.2

Model packaging and distribution utilities for ToRSh
Documentation
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
//! Package vulnerability scanning and security auditing
//!
//! This module provides comprehensive security scanning capabilities for packages,
//! including:
//! - Dependency vulnerability detection
//! - Known CVE checking
//! - Security policy enforcement
//! - Package integrity verification
//! - Malicious code pattern detection
//!
//! # Security Scanning Workflow
//!
//! 1. **Dependency Analysis**: Check all dependencies against vulnerability databases
//! 2. **Pattern Detection**: Scan package contents for suspicious patterns
//! 3. **Policy Enforcement**: Verify package meets security requirements
//! 4. **Report Generation**: Generate detailed security audit reports
//!
//! # Example
//!
//! ```rust,no_run
//! use torsh_package::vulnerability::{VulnerabilityScanner, ScanPolicy};
//! use torsh_package::Package;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let package = Package::load("model.torshpkg")?;
//!
//! let scanner = VulnerabilityScanner::new()
//!     .with_policy(ScanPolicy::strict());
//!
//! let report = scanner.scan(&package)?;
//!
//! if report.has_critical_issues() {
//!     eprintln!("Critical security issues found!");
//!     for issue in report.critical_issues() {
//!         eprintln!("  - {}: {}", issue.severity, issue.description);
//!     }
//! }
//! # Ok(())
//! # }
//! ```

use crate::package::Package;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use torsh_core::error::Result;

/// Vulnerability severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Severity {
    /// Low severity - informational
    Low,
    /// Medium severity - should be addressed
    Medium,
    /// High severity - should be fixed soon
    High,
    /// Critical severity - immediate action required
    Critical,
}

impl std::fmt::Display for Severity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Severity::Low => write!(f, "LOW"),
            Severity::Medium => write!(f, "MEDIUM"),
            Severity::High => write!(f, "HIGH"),
            Severity::Critical => write!(f, "CRITICAL"),
        }
    }
}

/// Security issue types
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum IssueType {
    /// Known CVE (Common Vulnerabilities and Exposures)
    KnownCVE,
    /// Dependency vulnerability
    DependencyVulnerability,
    /// Suspicious code pattern
    SuspiciousPattern,
    /// Missing security feature
    MissingSecurityFeature,
    /// Weak cryptography
    WeakCryptography,
    /// Insecure configuration
    InsecureConfiguration,
    /// Supply chain risk
    SupplyChainRisk,
}

/// A single security issue found during scanning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityIssue {
    /// Issue type
    pub issue_type: IssueType,
    /// Severity level
    pub severity: Severity,
    /// Issue title
    pub title: String,
    /// Detailed description
    pub description: String,
    /// Affected component (dependency, resource, etc.)
    pub affected_component: Option<String>,
    /// CVE ID if applicable
    pub cve_id: Option<String>,
    /// Recommended fix
    pub recommendation: Option<String>,
    /// Additional metadata
    pub metadata: HashMap<String, String>,
}

impl SecurityIssue {
    /// Create a new security issue
    pub fn new(
        issue_type: IssueType,
        severity: Severity,
        title: String,
        description: String,
    ) -> Self {
        Self {
            issue_type,
            severity,
            title,
            description,
            affected_component: None,
            cve_id: None,
            recommendation: None,
            metadata: HashMap::new(),
        }
    }

    /// Set affected component
    pub fn with_affected_component(mut self, component: String) -> Self {
        self.affected_component = Some(component);
        self
    }

    /// Set CVE ID
    pub fn with_cve_id(mut self, cve_id: String) -> Self {
        self.cve_id = Some(cve_id);
        self
    }

    /// Set recommendation
    pub fn with_recommendation(mut self, recommendation: String) -> Self {
        self.recommendation = Some(recommendation);
        self
    }

    /// Add metadata
    pub fn with_metadata(mut self, key: String, value: String) -> Self {
        self.metadata.insert(key, value);
        self
    }
}

/// Vulnerability scan report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanReport {
    /// Package name
    pub package_name: String,
    /// Package version
    pub package_version: String,
    /// Scan timestamp
    pub scan_timestamp: chrono::DateTime<chrono::Utc>,
    /// All issues found
    pub issues: Vec<SecurityIssue>,
    /// Scan policy used
    pub policy_name: String,
    /// Scan duration in milliseconds
    pub scan_duration_ms: u64,
    /// Scanner version
    pub scanner_version: String,
}

impl ScanReport {
    /// Get critical issues
    pub fn critical_issues(&self) -> Vec<&SecurityIssue> {
        self.issues
            .iter()
            .filter(|i| i.severity == Severity::Critical)
            .collect()
    }

    /// Get high severity issues
    pub fn high_issues(&self) -> Vec<&SecurityIssue> {
        self.issues
            .iter()
            .filter(|i| i.severity == Severity::High)
            .collect()
    }

    /// Get medium severity issues
    pub fn medium_issues(&self) -> Vec<&SecurityIssue> {
        self.issues
            .iter()
            .filter(|i| i.severity == Severity::Medium)
            .collect()
    }

    /// Get low severity issues
    pub fn low_issues(&self) -> Vec<&SecurityIssue> {
        self.issues
            .iter()
            .filter(|i| i.severity == Severity::Low)
            .collect()
    }

    /// Check if there are critical issues
    pub fn has_critical_issues(&self) -> bool {
        self.issues.iter().any(|i| i.severity == Severity::Critical)
    }

    /// Check if there are high severity issues
    pub fn has_high_issues(&self) -> bool {
        self.issues.iter().any(|i| i.severity == Severity::High)
    }

    /// Get total issue count
    pub fn total_issues(&self) -> usize {
        self.issues.len()
    }

    /// Calculate risk score (0-100)
    pub fn risk_score(&self) -> u32 {
        let critical_weight = 25;
        let high_weight = 10;
        let medium_weight = 3;
        let low_weight = 1;

        let score = self.critical_issues().len() * critical_weight
            + self.high_issues().len() * high_weight
            + self.medium_issues().len() * medium_weight
            + self.low_issues().len() * low_weight;

        std::cmp::min(score as u32, 100)
    }
}

/// Security scan policy
#[derive(Debug, Clone)]
pub struct ScanPolicy {
    /// Policy name
    pub name: String,
    /// Check for known CVEs
    pub check_cves: bool,
    /// Scan dependencies
    pub scan_dependencies: bool,
    /// Detect suspicious patterns
    pub detect_patterns: bool,
    /// Check cryptography
    pub check_cryptography: bool,
    /// Verify signatures
    pub verify_signatures: bool,
    /// Maximum allowed risk score
    pub max_risk_score: u32,
    /// Fail on critical issues
    pub fail_on_critical: bool,
}

impl Default for ScanPolicy {
    fn default() -> Self {
        Self::standard()
    }
}

impl ScanPolicy {
    /// Create a lenient policy (minimal checks)
    pub fn lenient() -> Self {
        Self {
            name: "lenient".to_string(),
            check_cves: false,
            scan_dependencies: true,
            detect_patterns: false,
            check_cryptography: false,
            verify_signatures: false,
            max_risk_score: 75,
            fail_on_critical: false,
        }
    }

    /// Create a standard policy (balanced security)
    pub fn standard() -> Self {
        Self {
            name: "standard".to_string(),
            check_cves: true,
            scan_dependencies: true,
            detect_patterns: true,
            check_cryptography: true,
            verify_signatures: true,
            max_risk_score: 50,
            fail_on_critical: false,
        }
    }

    /// Create a strict policy (maximum security)
    pub fn strict() -> Self {
        Self {
            name: "strict".to_string(),
            check_cves: true,
            scan_dependencies: true,
            detect_patterns: true,
            check_cryptography: true,
            verify_signatures: true,
            max_risk_score: 20,
            fail_on_critical: true,
        }
    }
}

/// Vulnerability scanner
pub struct VulnerabilityScanner {
    policy: ScanPolicy,
    cve_database: HashMap<String, Vec<String>>, // package -> CVEs
}

impl VulnerabilityScanner {
    /// Create a new vulnerability scanner with default policy
    pub fn new() -> Self {
        Self {
            policy: ScanPolicy::default(),
            cve_database: Self::load_cve_database(),
        }
    }

    /// Set scan policy
    pub fn with_policy(mut self, policy: ScanPolicy) -> Self {
        self.policy = policy;
        self
    }

    /// Scan a package for vulnerabilities
    pub fn scan(&self, package: &Package) -> Result<ScanReport> {
        let start_time = std::time::Instant::now();
        let mut issues = Vec::new();

        // Check package signature if policy requires
        if self.policy.verify_signatures {
            if let Err(e) = package.verify() {
                issues.push(
                    SecurityIssue::new(
                        IssueType::MissingSecurityFeature,
                        Severity::High,
                        "Package signature verification failed".to_string(),
                        format!("Package signature could not be verified: {}", e),
                    )
                    .with_recommendation("Sign the package with a trusted key".to_string()),
                );
            }
        }

        // Scan dependencies for vulnerabilities
        if self.policy.scan_dependencies {
            issues.extend(self.scan_dependencies(package));
        }

        // Check for known CVEs
        if self.policy.check_cves {
            issues.extend(self.check_cves(package));
        }

        // Detect suspicious patterns
        if self.policy.detect_patterns {
            issues.extend(self.detect_patterns(package));
        }

        // Check cryptography
        if self.policy.check_cryptography {
            issues.extend(self.check_cryptography(package));
        }

        let scan_duration_ms = start_time.elapsed().as_millis() as u64;

        Ok(ScanReport {
            package_name: package.name().to_string(),
            package_version: package.get_version().to_string(),
            scan_timestamp: chrono::Utc::now(),
            issues,
            policy_name: self.policy.name.clone(),
            scan_duration_ms,
            scanner_version: env!("CARGO_PKG_VERSION").to_string(),
        })
    }

    /// Scan dependencies for known vulnerabilities
    fn scan_dependencies(&self, package: &Package) -> Vec<SecurityIssue> {
        let mut issues = Vec::new();

        for (dep_name, dep_version) in &package.metadata().dependencies {
            // Check against known vulnerable versions
            // In production, this would query a real vulnerability database
            if dep_name.contains("vulnerable") {
                issues.push(
                    SecurityIssue::new(
                        IssueType::DependencyVulnerability,
                        Severity::High,
                        format!("Vulnerable dependency: {}", dep_name),
                        format!(
                            "Dependency {} version {} has known vulnerabilities",
                            dep_name, dep_version
                        ),
                    )
                    .with_affected_component(dep_name.clone())
                    .with_recommendation(format!(
                        "Update {} to the latest secure version",
                        dep_name
                    )),
                );
            }
        }

        issues
    }

    /// Check for known CVEs
    fn check_cves(&self, package: &Package) -> Vec<SecurityIssue> {
        let mut issues = Vec::new();

        for (dep_name, _dep_version) in &package.metadata().dependencies {
            if let Some(cves) = self.cve_database.get(dep_name) {
                for cve in cves {
                    issues.push(
                        SecurityIssue::new(
                            IssueType::KnownCVE,
                            Severity::Critical,
                            format!("Known CVE in dependency: {}", dep_name),
                            format!("Dependency {} is affected by {}", dep_name, cve),
                        )
                        .with_affected_component(dep_name.clone())
                        .with_cve_id(cve.clone())
                        .with_recommendation("Update to a patched version".to_string()),
                    );
                }
            }
        }

        issues
    }

    /// Detect suspicious code patterns
    fn detect_patterns(&self, package: &Package) -> Vec<SecurityIssue> {
        let mut issues = Vec::new();

        // Patterns that might indicate malicious code
        let suspicious_patterns = vec![
            ("eval(", "Dynamic code evaluation"),
            ("exec(", "Command execution"),
            ("__import__", "Dynamic imports"),
            ("os.system", "System command execution"),
            ("subprocess", "Subprocess execution"),
            ("/etc/passwd", "System file access"),
            ("rm -rf", "Destructive command"),
        ];

        for (_, resource) in package.resources() {
            let content = String::from_utf8_lossy(&resource.data);

            for (pattern, description) in &suspicious_patterns {
                if content.contains(pattern) {
                    issues.push(
                        SecurityIssue::new(
                            IssueType::SuspiciousPattern,
                            Severity::Medium,
                            format!("Suspicious pattern detected: {}", pattern),
                            format!(
                                "Resource contains potentially dangerous pattern: {}",
                                description
                            ),
                        )
                        .with_affected_component(resource.name.clone())
                        .with_recommendation("Review the code and ensure it's safe".to_string()),
                    );
                }
            }
        }

        issues
    }

    /// Check cryptography usage
    fn check_cryptography(&self, _package: &Package) -> Vec<SecurityIssue> {
        let issues = Vec::new();

        // Check for weak cryptographic algorithms
        // This is a simplified check - production systems would be more sophisticated

        // Example: Check if package uses weak hashing
        // In a real implementation, this would scan the actual code

        issues
    }

    /// Load CVE database (in production, this would load from a real database)
    fn load_cve_database() -> HashMap<String, Vec<String>> {
        let mut db = HashMap::new();

        // Mock CVE data for demonstration
        db.insert(
            "example-vulnerable-lib".to_string(),
            vec!["CVE-2024-1234".to_string(), "CVE-2024-5678".to_string()],
        );

        db
    }
}

impl Default for VulnerabilityScanner {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::resources::{Resource, ResourceType};

    #[test]
    fn test_severity_ordering() {
        assert!(Severity::Critical > Severity::High);
        assert!(Severity::High > Severity::Medium);
        assert!(Severity::Medium > Severity::Low);
    }

    #[test]
    fn test_security_issue_creation() {
        let issue = SecurityIssue::new(
            IssueType::KnownCVE,
            Severity::High,
            "Test Issue".to_string(),
            "Test Description".to_string(),
        )
        .with_cve_id("CVE-2024-1234".to_string())
        .with_affected_component("test-component".to_string())
        .with_recommendation("Fix it".to_string());

        assert_eq!(issue.severity, Severity::High);
        assert_eq!(issue.cve_id, Some("CVE-2024-1234".to_string()));
        assert!(issue.recommendation.is_some());
    }

    #[test]
    fn test_scan_report_risk_score() {
        let mut report = ScanReport {
            package_name: "test".to_string(),
            package_version: "1.0.0".to_string(),
            scan_timestamp: chrono::Utc::now(),
            issues: vec![],
            policy_name: "test".to_string(),
            scan_duration_ms: 100,
            scanner_version: "1.0.0".to_string(),
        };

        // No issues = 0 score
        assert_eq!(report.risk_score(), 0);

        // Add critical issue
        report.issues.push(SecurityIssue::new(
            IssueType::KnownCVE,
            Severity::Critical,
            "Critical".to_string(),
            "Test".to_string(),
        ));
        assert_eq!(report.risk_score(), 25);

        // Add high issue
        report.issues.push(SecurityIssue::new(
            IssueType::DependencyVulnerability,
            Severity::High,
            "High".to_string(),
            "Test".to_string(),
        ));
        assert_eq!(report.risk_score(), 35);
    }

    #[test]
    fn test_scan_report_filtering() {
        let report = ScanReport {
            package_name: "test".to_string(),
            package_version: "1.0.0".to_string(),
            scan_timestamp: chrono::Utc::now(),
            issues: vec![
                SecurityIssue::new(
                    IssueType::KnownCVE,
                    Severity::Critical,
                    "Critical".to_string(),
                    "Test".to_string(),
                ),
                SecurityIssue::new(
                    IssueType::DependencyVulnerability,
                    Severity::High,
                    "High".to_string(),
                    "Test".to_string(),
                ),
                SecurityIssue::new(
                    IssueType::SuspiciousPattern,
                    Severity::Medium,
                    "Medium".to_string(),
                    "Test".to_string(),
                ),
            ],
            policy_name: "test".to_string(),
            scan_duration_ms: 100,
            scanner_version: "1.0.0".to_string(),
        };

        assert_eq!(report.critical_issues().len(), 1);
        assert_eq!(report.high_issues().len(), 1);
        assert_eq!(report.medium_issues().len(), 1);
        assert_eq!(report.total_issues(), 3);
        assert!(report.has_critical_issues());
        assert!(report.has_high_issues());
    }

    #[test]
    fn test_scan_policy_presets() {
        let lenient = ScanPolicy::lenient();
        let standard = ScanPolicy::standard();
        let strict = ScanPolicy::strict();

        assert!(!lenient.fail_on_critical);
        assert!(standard.scan_dependencies);
        assert!(strict.fail_on_critical);
        assert!(strict.max_risk_score < standard.max_risk_score);
    }

    #[test]
    fn test_vulnerability_scanner_basic() {
        let scanner = VulnerabilityScanner::new();
        let package = Package::new("test-package".to_string(), "1.0.0".to_string());

        let report = scanner.scan(&package).unwrap();
        assert_eq!(report.package_name, "test-package");
        assert_eq!(report.package_version, "1.0.0");
    }

    #[test]
    fn test_pattern_detection() {
        let scanner = VulnerabilityScanner::new();
        let mut package = Package::new("test-package".to_string(), "1.0.0".to_string());

        // Add resource with suspicious pattern
        let suspicious_code = b"import os\nos.system('rm -rf /')";
        let resource = Resource::new(
            "suspicious.py".to_string(),
            ResourceType::Source,
            suspicious_code.to_vec(),
        );
        package.add_resource(resource);

        let report = scanner.scan(&package).unwrap();
        assert!(report.total_issues() > 0);
        assert!(report
            .issues
            .iter()
            .any(|i| i.issue_type == IssueType::SuspiciousPattern));
    }

    #[test]
    fn test_scanner_with_policy() {
        let scanner = VulnerabilityScanner::new().with_policy(ScanPolicy::strict());
        let package = Package::new("test".to_string(), "1.0.0".to_string());

        let report = scanner.scan(&package).unwrap();
        assert_eq!(report.policy_name, "strict");
    }
}