mockforge-plugin-loader 0.3.141

Plugin loader with security sandboxing and validation for MockForge
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//! # MockForge Plugin Loader
//!
//! Secure plugin loading and validation system for MockForge.
//! This crate provides the plugin loader that handles:
//!
//! - Plugin discovery and validation
//! - Security sandboxing and capability checking
//! - WebAssembly module loading and instantiation
//! - Plugin lifecycle management
//!
//! ## Security Features
//!
//! - **WASM Sandboxing**: All plugins run in isolated WebAssembly environments
//! - **Capability Validation**: Strict permission checking before plugin execution
//! - **Resource Limits**: Memory, CPU, and execution time constraints
//! - **Code Signing**: Optional plugin signature verification

use std::path::Path;
use std::path::PathBuf;

// Import types from plugin core
use mockforge_plugin_core::{
    PluginAuthor, PluginId, PluginInfo, PluginInstance, PluginManifest, PluginVersion,
};

pub mod git;
pub mod installer;
pub mod invocation_metrics;
pub mod loader;
pub mod memory_tracking;
pub mod metadata;
pub mod registry;
pub mod remote;
pub mod runtime_adapter;
pub mod sandbox;
pub mod signature;
pub mod signature_gen;
pub mod validator;

/// Re-export commonly used types
pub use git::*;
pub use installer::*;
pub use invocation_metrics::{
    InvocationMetric, InvocationMetricsBus, InvocationStatus, InvocationTimer,
};
pub use loader::*;
pub use memory_tracking::{MemoryStats, MemoryTracker};
pub use metadata::*;
pub use registry::*;
pub use remote::*;
pub use runtime_adapter::*;
pub use sandbox::*;
pub use signature::*;
pub use signature_gen::*;
pub use validator::*;

/// Plugin loader result type
pub type LoaderResult<T> = Result<T, PluginLoaderError>;

/// Plugin loader error types
#[derive(Debug, thiserror::Error)]
pub enum PluginLoaderError {
    /// Plugin loading failed
    #[error("Plugin loading error: {message}")]
    LoadError {
        /// Error message describing the load failure
        message: String,
    },

    /// Plugin validation failed
    #[error("Plugin validation error: {message}")]
    ValidationError {
        /// Error message describing the validation failure
        message: String,
    },

    /// Security violation during plugin loading
    #[error("Security violation: {violation}")]
    SecurityViolation {
        /// Description of the security violation
        violation: String,
    },

    /// Plugin manifest error
    #[error("Plugin manifest error: {message}")]
    ManifestError {
        /// Error message describing the manifest issue
        message: String,
    },

    /// WebAssembly module error
    #[error("WebAssembly module error: {message}")]
    WasmError {
        /// Error message describing the WASM issue
        message: String,
    },

    /// File system error
    #[error("File system error: {message}")]
    FsError {
        /// Error message describing the file system issue
        message: String,
    },

    /// Plugin already loaded
    #[error("Plugin already loaded: {plugin_id}")]
    AlreadyLoaded {
        /// ID of the plugin that is already loaded
        plugin_id: PluginId,
    },

    /// Plugin not found
    #[error("Plugin not found: {plugin_id}")]
    NotFound {
        /// ID of the plugin that was not found
        plugin_id: PluginId,
    },

    /// Plugin dependency error
    #[error("Plugin dependency error: {message}")]
    DependencyError {
        /// Error message describing the dependency issue
        message: String,
    },

    /// Resource limit exceeded
    #[error("Resource limit exceeded: {message}")]
    ResourceLimit {
        /// Error message describing the resource limit that was exceeded
        message: String,
    },

    /// Plugin execution error
    #[error("Plugin execution error: {message}")]
    ExecutionError {
        /// Error message describing the execution failure
        message: String,
    },
}

impl PluginLoaderError {
    /// Create a load error
    pub fn load<S: Into<String>>(message: S) -> Self {
        Self::LoadError {
            message: message.into(),
        }
    }

    /// Create a validation error
    pub fn validation<S: Into<String>>(message: S) -> Self {
        Self::ValidationError {
            message: message.into(),
        }
    }

    /// Create a security violation error
    pub fn security<S: Into<String>>(violation: S) -> Self {
        Self::SecurityViolation {
            violation: violation.into(),
        }
    }

    /// Create a manifest error
    pub fn manifest<S: Into<String>>(message: S) -> Self {
        Self::ManifestError {
            message: message.into(),
        }
    }

    /// Create a WASM error
    pub fn wasm<S: Into<String>>(message: S) -> Self {
        Self::WasmError {
            message: message.into(),
        }
    }

    /// Create a file system error
    pub fn fs<S: Into<String>>(message: S) -> Self {
        Self::FsError {
            message: message.into(),
        }
    }

    /// Create an already loaded error
    pub fn already_loaded(plugin_id: PluginId) -> Self {
        Self::AlreadyLoaded { plugin_id }
    }

    /// Create a not found error
    pub fn not_found(plugin_id: PluginId) -> Self {
        Self::NotFound { plugin_id }
    }

    /// Create a dependency error
    pub fn dependency<S: Into<String>>(message: S) -> Self {
        Self::DependencyError {
            message: message.into(),
        }
    }

    /// Create a resource limit error
    pub fn resource_limit<S: Into<String>>(message: S) -> Self {
        Self::ResourceLimit {
            message: message.into(),
        }
    }

    /// Create an execution error
    pub fn execution<S: Into<String>>(message: S) -> Self {
        Self::ExecutionError {
            message: message.into(),
        }
    }

    /// Check if this is a security-related error
    pub fn is_security_error(&self) -> bool {
        matches!(self, PluginLoaderError::SecurityViolation { .. })
    }
}

/// Plugin loader configuration
#[derive(Debug, Clone)]
pub struct PluginLoaderConfig {
    /// Plugin directories to scan
    pub plugin_dirs: Vec<String>,
    /// Allow unsigned plugins (for development)
    pub allow_unsigned: bool,
    /// Trusted public keys for plugin signing (key IDs)
    pub trusted_keys: Vec<String>,
    /// Key data storage (key_id -> key_bytes)
    pub key_data: std::collections::HashMap<String, Vec<u8>>,
    /// Maximum plugins to load
    pub max_plugins: usize,
    /// Plugin loading timeout
    pub load_timeout_secs: u64,
    /// Enable debug logging
    pub debug_logging: bool,
    /// Skip WASM validation (for testing)
    pub skip_wasm_validation: bool,
}

impl Default for PluginLoaderConfig {
    fn default() -> Self {
        Self {
            plugin_dirs: vec!["~/.mockforge/plugins".to_string(), "./plugins".to_string()],
            allow_unsigned: false,
            trusted_keys: vec!["trusted-dev-key".to_string()],
            key_data: std::collections::HashMap::new(),
            max_plugins: 100,
            load_timeout_secs: 30,
            debug_logging: false,
            skip_wasm_validation: false,
        }
    }
}

/// Plugin loading context
#[derive(Debug, Clone)]
pub struct PluginLoadContext {
    /// Plugin ID
    pub plugin_id: PluginId,
    /// Plugin manifest
    pub manifest: PluginManifest,
    /// Plugin file path
    pub plugin_path: String,
    /// Loading timestamp
    pub load_time: chrono::DateTime<chrono::Utc>,
    /// Loader configuration
    pub config: PluginLoaderConfig,
}

impl PluginLoadContext {
    /// Create new loading context
    pub fn new(
        plugin_id: PluginId,
        manifest: PluginManifest,
        plugin_path: String,
        config: PluginLoaderConfig,
    ) -> Self {
        Self {
            plugin_id,
            manifest,
            plugin_path,
            load_time: chrono::Utc::now(),
            config,
        }
    }
}

/// Plugin loading statistics
#[derive(Debug, Clone, Default)]
pub struct PluginLoadStats {
    /// Total plugins discovered
    pub discovered: usize,
    /// Plugins successfully loaded
    pub loaded: usize,
    /// Plugins that failed to load
    pub failed: usize,
    /// Plugins skipped due to validation
    pub skipped: usize,
    /// Loading start time
    pub start_time: Option<chrono::DateTime<chrono::Utc>>,
    /// Loading end time
    pub end_time: Option<chrono::DateTime<chrono::Utc>>,
}

impl PluginLoadStats {
    /// Record loading start
    pub fn start_loading(&mut self) {
        self.start_time = Some(chrono::Utc::now());
    }

    /// Record loading completion
    pub fn finish_loading(&mut self) {
        self.end_time = Some(chrono::Utc::now());
    }

    /// Record successful plugin load
    pub fn record_success(&mut self) {
        self.loaded += 1;
        self.discovered += 1;
    }

    /// Record failed plugin load
    pub fn record_failure(&mut self) {
        self.failed += 1;
        self.discovered += 1;
    }

    /// Record skipped plugin
    pub fn record_skipped(&mut self) {
        self.skipped += 1;
        self.discovered += 1;
    }

    /// Get loading duration
    pub fn duration(&self) -> Option<chrono::Duration> {
        match (self.start_time, self.end_time) {
            (Some(start), Some(end)) => Some(end - start),
            _ => None,
        }
    }

    /// Get success rate as percentage
    pub fn success_rate(&self) -> f64 {
        if self.discovered == 0 {
            1.0 // No plugins discovered means 100% success (no failures)
        } else {
            (self.loaded as f64 / self.discovered as f64) * 100.0
        }
    }

    /// Get total number of plugins processed
    pub fn total_plugins(&self) -> usize {
        self.loaded + self.failed + self.skipped
    }
}

/// Plugin discovery result
#[derive(Debug, Clone)]
pub struct PluginDiscovery {
    /// Plugin ID
    pub plugin_id: PluginId,
    /// Plugin manifest
    pub manifest: PluginManifest,
    /// Plugin file path
    pub path: String,
    /// Whether plugin is valid
    pub is_valid: bool,
    /// Validation errors (if any)
    pub errors: Vec<String>,
}

impl PluginDiscovery {
    /// Create successful discovery
    pub fn success(plugin_id: PluginId, manifest: PluginManifest, path: String) -> Self {
        Self {
            plugin_id,
            manifest,
            path,
            is_valid: true,
            errors: Vec::new(),
        }
    }

    /// Create failed discovery
    pub fn failure(plugin_id: PluginId, path: String, errors: Vec<String>) -> Self {
        let plugin_id_clone = PluginId(plugin_id.0.clone());
        Self {
            plugin_id,
            manifest: PluginManifest::new(PluginInfo::new(
                plugin_id_clone,
                PluginVersion::new(0, 0, 0),
                "Unknown",
                "Plugin failed to load",
                PluginAuthor::new("unknown"),
            )),
            path,
            is_valid: false,
            errors,
        }
    }

    /// Check if discovery was successful
    pub fn is_success(&self) -> bool {
        self.is_valid
    }

    /// Get first error (if any)
    pub fn first_error(&self) -> Option<&str> {
        self.errors.first().map(|s| s.as_str())
    }
}

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

    // ===== PluginLoaderError Tests =====

    #[test]
    fn test_plugin_loader_error_types() {
        let load_error = PluginLoaderError::LoadError {
            message: "test error".to_string(),
        };
        assert!(matches!(load_error, PluginLoaderError::LoadError { .. }));

        let validation_error = PluginLoaderError::ValidationError {
            message: "validation failed".to_string(),
        };
        assert!(matches!(validation_error, PluginLoaderError::ValidationError { .. }));
    }

    #[test]
    fn test_error_helper_constructors() {
        let load_err = PluginLoaderError::load("load failed");
        assert!(matches!(load_err, PluginLoaderError::LoadError { .. }));

        let validation_err = PluginLoaderError::validation("validation failed");
        assert!(matches!(validation_err, PluginLoaderError::ValidationError { .. }));

        let security_err = PluginLoaderError::security("security violation");
        assert!(matches!(security_err, PluginLoaderError::SecurityViolation { .. }));

        let manifest_err = PluginLoaderError::manifest("manifest error");
        assert!(matches!(manifest_err, PluginLoaderError::ManifestError { .. }));

        let wasm_err = PluginLoaderError::wasm("wasm error");
        assert!(matches!(wasm_err, PluginLoaderError::WasmError { .. }));

        let fs_err = PluginLoaderError::fs("fs error");
        assert!(matches!(fs_err, PluginLoaderError::FsError { .. }));

        let dep_err = PluginLoaderError::dependency("dependency error");
        assert!(matches!(dep_err, PluginLoaderError::DependencyError { .. }));

        let resource_err = PluginLoaderError::resource_limit("resource limit");
        assert!(matches!(resource_err, PluginLoaderError::ResourceLimit { .. }));

        let exec_err = PluginLoaderError::execution("execution error");
        assert!(matches!(exec_err, PluginLoaderError::ExecutionError { .. }));
    }

    #[test]
    fn test_error_already_loaded() {
        let plugin_id = PluginId::new("test-plugin");
        let err = PluginLoaderError::already_loaded(plugin_id.clone());
        assert!(matches!(err, PluginLoaderError::AlreadyLoaded { .. }));
        assert_eq!(err.to_string(), format!("Plugin already loaded: {}", plugin_id));
    }

    #[test]
    fn test_error_not_found() {
        let plugin_id = PluginId::new("missing-plugin");
        let err = PluginLoaderError::not_found(plugin_id.clone());
        assert!(matches!(err, PluginLoaderError::NotFound { .. }));
        assert_eq!(err.to_string(), format!("Plugin not found: {}", plugin_id));
    }

    #[test]
    fn test_is_security_error() {
        let security_err = PluginLoaderError::security("test");
        assert!(security_err.is_security_error());

        let load_err = PluginLoaderError::load("test");
        assert!(!load_err.is_security_error());
    }

    #[test]
    fn test_error_display() {
        let err = PluginLoaderError::load("test message");
        let err_str = err.to_string();
        assert!(err_str.contains("Plugin loading error"));
        assert!(err_str.contains("test message"));
    }

    // ===== PluginLoaderConfig Tests =====

    #[test]
    fn test_plugin_loader_config_default() {
        let config = PluginLoaderConfig::default();
        assert_eq!(config.plugin_dirs.len(), 2);
        assert!(!config.allow_unsigned);
        assert_eq!(config.max_plugins, 100);
        assert_eq!(config.load_timeout_secs, 30);
        assert!(!config.debug_logging);
        assert!(!config.skip_wasm_validation);
    }

    #[test]
    fn test_plugin_loader_config_clone() {
        let config = PluginLoaderConfig::default();
        let cloned = config.clone();
        assert_eq!(config.max_plugins, cloned.max_plugins);
        assert_eq!(config.load_timeout_secs, cloned.load_timeout_secs);
    }

    // ===== PluginLoadContext Tests =====

    #[test]
    fn test_plugin_load_context_creation() {
        let plugin_id = PluginId::new("test-plugin");
        let manifest = PluginManifest::new(PluginInfo::new(
            plugin_id.clone(),
            PluginVersion::new(1, 0, 0),
            "Test Plugin",
            "A test plugin",
            PluginAuthor::new("test-author"),
        ));
        let config = PluginLoaderConfig::default();

        let context = PluginLoadContext::new(
            plugin_id.clone(),
            manifest.clone(),
            "/tmp/plugin".to_string(),
            config.clone(),
        );

        assert_eq!(context.plugin_id, plugin_id);
        assert_eq!(context.plugin_path, "/tmp/plugin");
        assert_eq!(context.config.max_plugins, config.max_plugins);
    }

    // ===== PluginLoadStats Tests =====

    #[test]
    fn test_plugin_load_stats_default() {
        let stats = PluginLoadStats::default();
        assert_eq!(stats.discovered, 0);
        assert_eq!(stats.loaded, 0);
        assert_eq!(stats.failed, 0);
        assert_eq!(stats.skipped, 0);
        assert!(stats.start_time.is_none());
        assert!(stats.end_time.is_none());
    }

    #[test]
    fn test_plugin_load_stats_timing() {
        let mut stats = PluginLoadStats::default();
        assert!(stats.duration().is_none());

        stats.start_loading();
        assert!(stats.start_time.is_some());
        assert!(stats.duration().is_none());

        std::thread::sleep(std::time::Duration::from_millis(10));

        stats.finish_loading();
        assert!(stats.end_time.is_some());
        assert!(stats.duration().is_some());
        let duration = stats.duration().unwrap();
        assert!(duration.num_milliseconds() >= 10);
    }

    #[test]
    fn test_plugin_load_stats_record_success() {
        let mut stats = PluginLoadStats::default();
        stats.record_success();
        assert_eq!(stats.loaded, 1);
        assert_eq!(stats.discovered, 1);

        stats.record_success();
        assert_eq!(stats.loaded, 2);
        assert_eq!(stats.discovered, 2);
    }

    #[test]
    fn test_plugin_load_stats_record_failure() {
        let mut stats = PluginLoadStats::default();
        stats.record_failure();
        assert_eq!(stats.failed, 1);
        assert_eq!(stats.discovered, 1);
    }

    #[test]
    fn test_plugin_load_stats_record_skipped() {
        let mut stats = PluginLoadStats::default();
        stats.record_skipped();
        assert_eq!(stats.skipped, 1);
        assert_eq!(stats.discovered, 1);
    }

    #[test]
    fn test_plugin_load_stats_success_rate() {
        let mut stats = PluginLoadStats::default();
        // No plugins discovered = 1.0 (implementation returns 1.0, not 100.0)
        assert_eq!(stats.success_rate(), 1.0);

        stats.record_success();
        stats.record_success();
        stats.record_failure();
        stats.record_skipped();
        // 2 loaded / 4 discovered = 50%
        assert_eq!(stats.success_rate(), 50.0);
    }

    #[test]
    fn test_plugin_load_stats_total_plugins() {
        let mut stats = PluginLoadStats::default();
        assert_eq!(stats.total_plugins(), 0);

        stats.record_success();
        stats.record_failure();
        stats.record_skipped();
        assert_eq!(stats.total_plugins(), 3);
    }

    #[test]
    fn test_plugin_load_stats_clone() {
        let mut stats = PluginLoadStats::default();
        stats.record_success();
        stats.start_loading();

        let cloned = stats.clone();
        assert_eq!(cloned.loaded, stats.loaded);
        assert_eq!(cloned.discovered, stats.discovered);
        assert_eq!(cloned.start_time, stats.start_time);
    }

    // ===== PluginDiscovery Tests =====

    #[test]
    fn test_plugin_discovery_success() {
        let plugin_id = PluginId("test-plugin".to_string());
        let manifest = PluginManifest::new(PluginInfo::new(
            plugin_id.clone(),
            PluginVersion::new(1, 0, 0),
            "Test Plugin",
            "A test plugin",
            PluginAuthor::new("test-author"),
        ));

        let result = PluginDiscovery::success(plugin_id, manifest, "/path/to/plugin".to_string());

        assert!(result.is_success());
        assert!(result.first_error().is_none());
        assert!(result.is_valid);
        assert!(result.errors.is_empty());
    }

    #[test]
    fn test_plugin_discovery_failure() {
        let plugin_id = PluginId("failing-plugin".to_string());
        let errors = vec!["Error 1".to_string(), "Error 2".to_string()];

        let result =
            PluginDiscovery::failure(plugin_id, "/path/to/plugin".to_string(), errors.clone());

        assert!(!result.is_success());
        assert_eq!(result.first_error(), Some("Error 1"));
        assert_eq!(result.errors.len(), 2);
        assert!(!result.is_valid);
    }

    #[test]
    fn test_plugin_discovery_failure_with_empty_errors() {
        let plugin_id = PluginId("failing-plugin".to_string());
        let errors = vec![];

        let result = PluginDiscovery::failure(plugin_id, "/path/to/plugin".to_string(), errors);

        assert!(!result.is_success());
        assert!(result.first_error().is_none());
        assert!(result.errors.is_empty());
    }

    #[test]
    fn test_plugin_discovery_clone() {
        let plugin_id = PluginId("test-plugin".to_string());
        let manifest = PluginManifest::new(PluginInfo::new(
            plugin_id.clone(),
            PluginVersion::new(1, 0, 0),
            "Test",
            "Test",
            PluginAuthor::new("test"),
        ));

        let discovery = PluginDiscovery::success(plugin_id, manifest, "/path".to_string());
        let cloned = discovery.clone();

        assert_eq!(discovery.plugin_id, cloned.plugin_id);
        assert_eq!(discovery.is_valid, cloned.is_valid);
    }

    // ===== Module Exports Tests =====

    #[test]
    fn test_module_exports() {
        // Verify main types are accessible
        let _ = std::marker::PhantomData::<PluginLoader>;
        let _ = std::marker::PhantomData::<PluginRegistry>;
        let _ = std::marker::PhantomData::<PluginValidator>;
        // Compilation test - if this compiles, the types are properly defined
    }

    #[test]
    fn test_loader_result_type() {
        let success: LoaderResult<i32> = Ok(42);
        assert!(success.is_ok());
        match success {
            Ok(val) => assert_eq!(val, 42),
            Err(_) => panic!("expected Ok"),
        }

        let error: LoaderResult<i32> = Err(PluginLoaderError::load("test"));
        assert!(error.is_err());
    }
}