oxify-engine 0.1.0

Workflow execution engine for OxiFY - DAG orchestration, scheduling, and state management
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
//! Plugin Security Scanning and Verification
//!
//! Provides security checks for plugins before loading and execution.
//!
//! # Features
//!
//! - File integrity verification (hash checking)
//! - Permission analysis
//! - Resource usage limits verification
//! - Malicious pattern detection
//! - Dependency vulnerability scanning

use crate::plugin_manifest::{PluginManifest, ResourceRequirements};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::path::Path;
use thiserror::Error;

/// Security scan errors
#[derive(Error, Debug)]
pub enum SecurityError {
    #[error("Failed to read file: {0}")]
    IoError(String),

    #[error("Hash mismatch: expected {expected}, got {actual}")]
    HashMismatch { expected: String, actual: String },

    #[error("Suspicious pattern detected: {0}")]
    SuspiciousPattern(String),

    #[error("Excessive resource requirements: {0}")]
    ExcessiveResources(String),

    #[error("Dangerous permission: {0}")]
    DangerousPermission(String),

    #[error("Vulnerability detected: {0}")]
    VulnerabilityDetected(String),
}

/// Security scan result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityScanResult {
    /// Overall security score (0-100, higher is better)
    pub security_score: u8,
    /// File hash (SHA-256)
    pub file_hash: String,
    /// List of warnings
    pub warnings: Vec<SecurityWarning>,
    /// List of critical issues
    pub critical_issues: Vec<SecurityIssue>,
    /// Scan timestamp
    pub scanned_at: chrono::DateTime<chrono::Utc>,
}

/// Security warning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityWarning {
    /// Warning category
    pub category: SecurityCategory,
    /// Warning message
    pub message: String,
    /// Impact on security score
    pub score_impact: u8,
}

/// Security issue (critical)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityIssue {
    /// Issue category
    pub category: SecurityCategory,
    /// Issue description
    pub description: String,
    /// Recommended action
    pub recommendation: String,
}

/// Security categories
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SecurityCategory {
    /// File integrity issues
    FileIntegrity,
    /// Permission-related issues
    Permissions,
    /// Resource usage concerns
    Resources,
    /// Malicious code patterns
    MaliciousCode,
    /// Dependency vulnerabilities
    Dependencies,
    /// Network access concerns
    Network,
    /// Filesystem access concerns
    Filesystem,
}

/// Plugin security scanner
pub struct PluginSecurityScanner {
    /// Maximum allowed memory in MB
    max_memory_mb: u64,
    /// Maximum allowed CPU cores
    max_cpu_cores: u32,
    /// Allow network access
    allow_network: bool,
    /// Allow filesystem access
    allow_filesystem: bool,
    /// Known malicious patterns
    malicious_patterns: Vec<String>,
}

impl Default for PluginSecurityScanner {
    fn default() -> Self {
        Self {
            max_memory_mb: 1024, // 1GB
            max_cpu_cores: 4,
            allow_network: false,
            allow_filesystem: false,
            malicious_patterns: vec![
                "eval(".to_string(),
                "exec(".to_string(),
                "subprocess".to_string(),
                "__import__".to_string(),
                "dangerous_syscall".to_string(),
            ],
        }
    }
}

impl PluginSecurityScanner {
    /// Create a new security scanner
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a strict scanner with tight security
    pub fn strict() -> Self {
        Self {
            max_memory_mb: 256,
            max_cpu_cores: 1,
            allow_network: false,
            allow_filesystem: false,
            malicious_patterns: vec![
                "eval(".to_string(),
                "exec(".to_string(),
                "subprocess".to_string(),
                "__import__".to_string(),
                "dangerous_syscall".to_string(),
                "require(".to_string(),
                "import(".to_string(),
            ],
        }
    }

    /// Configure maximum memory
    pub fn with_max_memory(mut self, mb: u64) -> Self {
        self.max_memory_mb = mb;
        self
    }

    /// Configure network access
    pub fn with_network_access(mut self, allow: bool) -> Self {
        self.allow_network = allow;
        self
    }

    /// Configure filesystem access
    pub fn with_filesystem_access(mut self, allow: bool) -> Self {
        self.allow_filesystem = allow;
        self
    }

    /// Scan a plugin file
    pub fn scan_file(&self, path: &Path) -> Result<SecurityScanResult, SecurityError> {
        // Calculate file hash
        let file_hash = self.calculate_file_hash(path)?;

        let mut warnings = Vec::new();
        let mut critical_issues = Vec::new();

        // Scan file contents for malicious patterns
        if let Ok(content) = std::fs::read_to_string(path) {
            self.scan_for_malicious_patterns(&content, &mut warnings, &mut critical_issues);
        }

        // Calculate security score
        let security_score = self.calculate_security_score(&warnings, &critical_issues);

        Ok(SecurityScanResult {
            security_score,
            file_hash,
            warnings,
            critical_issues,
            scanned_at: chrono::Utc::now(),
        })
    }

    /// Scan a plugin manifest
    pub fn scan_manifest(
        &self,
        manifest: &PluginManifest,
    ) -> Result<SecurityScanResult, SecurityError> {
        let mut warnings = Vec::new();
        let mut critical_issues = Vec::new();

        // Check resource requirements
        self.check_resource_requirements(
            &manifest.capabilities.resource_requirements,
            &mut warnings,
            &mut critical_issues,
        );

        // Check permissions
        self.check_permissions(
            &manifest.capabilities.resource_requirements,
            &mut warnings,
            &mut critical_issues,
        );

        // Calculate security score
        let security_score = self.calculate_security_score(&warnings, &critical_issues);

        Ok(SecurityScanResult {
            security_score,
            file_hash: String::new(), // No file hash for manifest-only scan
            warnings,
            critical_issues,
            scanned_at: chrono::Utc::now(),
        })
    }

    /// Verify file hash
    pub fn verify_hash(&self, path: &Path, expected_hash: &str) -> Result<(), SecurityError> {
        let actual_hash = self.calculate_file_hash(path)?;

        if actual_hash != expected_hash {
            return Err(SecurityError::HashMismatch {
                expected: expected_hash.to_string(),
                actual: actual_hash,
            });
        }

        Ok(())
    }

    /// Calculate SHA-256 hash of a file
    fn calculate_file_hash(&self, path: &Path) -> Result<String, SecurityError> {
        let bytes = std::fs::read(path).map_err(|e| SecurityError::IoError(e.to_string()))?;

        let mut hasher = Sha256::new();
        hasher.update(&bytes);
        let result = hasher.finalize();

        Ok(hex::encode(result))
    }

    /// Scan content for malicious patterns
    fn scan_for_malicious_patterns(
        &self,
        content: &str,
        _warnings: &mut Vec<SecurityWarning>,
        critical_issues: &mut Vec<SecurityIssue>,
    ) {
        for pattern in &self.malicious_patterns {
            if content.contains(pattern) {
                critical_issues.push(SecurityIssue {
                    category: SecurityCategory::MaliciousCode,
                    description: format!("Detected potentially malicious pattern: {}", pattern),
                    recommendation: "Review the code carefully or reject the plugin".to_string(),
                });
            }
        }
    }

    /// Check resource requirements
    fn check_resource_requirements(
        &self,
        requirements: &ResourceRequirements,
        warnings: &mut Vec<SecurityWarning>,
        critical_issues: &mut Vec<SecurityIssue>,
    ) {
        // Check memory
        if let Some(max_mem) = requirements.max_memory_mb {
            if max_mem > self.max_memory_mb {
                critical_issues.push(SecurityIssue {
                    category: SecurityCategory::Resources,
                    description: format!(
                        "Plugin requires {}MB memory, exceeds limit of {}MB",
                        max_mem, self.max_memory_mb
                    ),
                    recommendation: "Increase limit or reject the plugin".to_string(),
                });
            } else if max_mem > self.max_memory_mb / 2 {
                warnings.push(SecurityWarning {
                    category: SecurityCategory::Resources,
                    message: format!("Plugin requires high memory: {}MB", max_mem),
                    score_impact: 10,
                });
            }
        }

        // Check CPU
        if let Some(cpu_cores) = requirements.cpu_cores {
            if cpu_cores > self.max_cpu_cores {
                warnings.push(SecurityWarning {
                    category: SecurityCategory::Resources,
                    message: format!(
                        "Plugin requires {} CPU cores, exceeds limit of {}",
                        cpu_cores, self.max_cpu_cores
                    ),
                    score_impact: 10,
                });
            }
        }
    }

    /// Check permissions
    fn check_permissions(
        &self,
        requirements: &ResourceRequirements,
        warnings: &mut Vec<SecurityWarning>,
        critical_issues: &mut Vec<SecurityIssue>,
    ) {
        // Check network permission
        if requirements.requires_network && !self.allow_network {
            critical_issues.push(SecurityIssue {
                category: SecurityCategory::Network,
                description: "Plugin requires network access but it is not allowed".to_string(),
                recommendation: "Enable network access or reject the plugin".to_string(),
            });
        } else if requirements.requires_network {
            warnings.push(SecurityWarning {
                category: SecurityCategory::Network,
                message: "Plugin has network access - potential data exfiltration risk".to_string(),
                score_impact: 15,
            });
        }

        // Check filesystem permission
        if requirements.requires_filesystem && !self.allow_filesystem {
            critical_issues.push(SecurityIssue {
                category: SecurityCategory::Filesystem,
                description: "Plugin requires filesystem access but it is not allowed".to_string(),
                recommendation: "Enable filesystem access or reject the plugin".to_string(),
            });
        } else if requirements.requires_filesystem {
            warnings.push(SecurityWarning {
                category: SecurityCategory::Filesystem,
                message: "Plugin has filesystem access - potential security risk".to_string(),
                score_impact: 15,
            });
        }
    }

    /// Calculate overall security score
    fn calculate_security_score(
        &self,
        warnings: &[SecurityWarning],
        critical_issues: &[SecurityIssue],
    ) -> u8 {
        let mut score = 100u8;

        // Deduct for warnings
        for warning in warnings {
            score = score.saturating_sub(warning.score_impact);
        }

        // Deduct heavily for critical issues
        let critical_deduction = (critical_issues.len() as u8).saturating_mul(30);
        score = score.saturating_sub(critical_deduction);

        score
    }
}

/// Security policy for plugin loading
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityPolicy {
    /// Minimum security score required (0-100)
    pub min_security_score: u8,
    /// Allow plugins with warnings
    pub allow_warnings: bool,
    /// Allow plugins with critical issues
    pub allow_critical_issues: bool,
    /// Require hash verification
    pub require_hash_verification: bool,
    /// Known good hashes
    pub known_good_hashes: HashMap<String, String>,
}

impl Default for SecurityPolicy {
    fn default() -> Self {
        Self {
            min_security_score: 70,
            allow_warnings: true,
            allow_critical_issues: false,
            require_hash_verification: false,
            known_good_hashes: HashMap::new(),
        }
    }
}

impl SecurityPolicy {
    /// Create a strict security policy
    pub fn strict() -> Self {
        Self {
            min_security_score: 90,
            allow_warnings: false,
            allow_critical_issues: false,
            require_hash_verification: true,
            known_good_hashes: HashMap::new(),
        }
    }

    /// Check if a scan result passes the policy
    pub fn check(&self, result: &SecurityScanResult) -> Result<(), SecurityError> {
        // Check security score
        if result.security_score < self.min_security_score {
            return Err(SecurityError::VulnerabilityDetected(format!(
                "Security score {} below minimum {}",
                result.security_score, self.min_security_score
            )));
        }

        // Check warnings
        if !self.allow_warnings && !result.warnings.is_empty() {
            return Err(SecurityError::VulnerabilityDetected(format!(
                "Plugin has {} warnings, which are not allowed",
                result.warnings.len()
            )));
        }

        // Check critical issues
        if !self.allow_critical_issues && !result.critical_issues.is_empty() {
            return Err(SecurityError::VulnerabilityDetected(format!(
                "Plugin has {} critical issues",
                result.critical_issues.len()
            )));
        }

        Ok(())
    }
}

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

    #[test]
    fn test_security_scanner_creation() {
        let scanner = PluginSecurityScanner::new();
        assert_eq!(scanner.max_memory_mb, 1024);
        assert_eq!(scanner.max_cpu_cores, 4);
    }

    #[test]
    fn test_strict_scanner() {
        let scanner = PluginSecurityScanner::strict();
        assert_eq!(scanner.max_memory_mb, 256);
        assert_eq!(scanner.max_cpu_cores, 1);
        assert!(!scanner.allow_network);
        assert!(!scanner.allow_filesystem);
    }

    #[test]
    fn test_scanner_configuration() {
        let scanner = PluginSecurityScanner::new()
            .with_max_memory(512)
            .with_network_access(true)
            .with_filesystem_access(true);

        assert_eq!(scanner.max_memory_mb, 512);
        assert!(scanner.allow_network);
        assert!(scanner.allow_filesystem);
    }

    #[test]
    fn test_security_score_calculation() {
        let scanner = PluginSecurityScanner::new();

        let warnings = vec![
            SecurityWarning {
                category: SecurityCategory::Resources,
                message: "High memory".to_string(),
                score_impact: 10,
            },
            SecurityWarning {
                category: SecurityCategory::Network,
                message: "Network access".to_string(),
                score_impact: 15,
            },
        ];

        let critical_issues = vec![];

        let score = scanner.calculate_security_score(&warnings, &critical_issues);
        assert_eq!(score, 75); // 100 - 10 - 15
    }

    #[test]
    fn test_security_score_with_critical_issues() {
        let scanner = PluginSecurityScanner::new();

        let warnings = vec![];
        let critical_issues = vec![SecurityIssue {
            category: SecurityCategory::MaliciousCode,
            description: "Malicious pattern".to_string(),
            recommendation: "Reject".to_string(),
        }];

        let score = scanner.calculate_security_score(&warnings, &critical_issues);
        assert_eq!(score, 70); // 100 - 30
    }

    #[test]
    fn test_security_policy_default() {
        let policy = SecurityPolicy::default();
        assert_eq!(policy.min_security_score, 70);
        assert!(policy.allow_warnings);
        assert!(!policy.allow_critical_issues);
    }

    #[test]
    fn test_security_policy_strict() {
        let policy = SecurityPolicy::strict();
        assert_eq!(policy.min_security_score, 90);
        assert!(!policy.allow_warnings);
        assert!(!policy.allow_critical_issues);
        assert!(policy.require_hash_verification);
    }

    #[test]
    fn test_policy_check_passes() {
        let policy = SecurityPolicy::default();
        let result = SecurityScanResult {
            security_score: 80,
            file_hash: "abc123".to_string(),
            warnings: vec![],
            critical_issues: vec![],
            scanned_at: chrono::Utc::now(),
        };

        assert!(policy.check(&result).is_ok());
    }

    #[test]
    fn test_policy_check_fails_score() {
        let policy = SecurityPolicy::default();
        let result = SecurityScanResult {
            security_score: 50,
            file_hash: "abc123".to_string(),
            warnings: vec![],
            critical_issues: vec![],
            scanned_at: chrono::Utc::now(),
        };

        assert!(policy.check(&result).is_err());
    }

    #[test]
    fn test_policy_check_fails_critical_issues() {
        let policy = SecurityPolicy::default();
        let result = SecurityScanResult {
            security_score: 80,
            file_hash: "abc123".to_string(),
            warnings: vec![],
            critical_issues: vec![SecurityIssue {
                category: SecurityCategory::MaliciousCode,
                description: "Malicious".to_string(),
                recommendation: "Reject".to_string(),
            }],
            scanned_at: chrono::Utc::now(),
        };

        assert!(policy.check(&result).is_err());
    }
}