mockforge-plugin-loader 0.3.147

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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
//! WebAssembly sandbox for secure plugin execution
//!
//! This module provides the sandboxed execution environment for plugins,
//! including resource limits, security boundaries, and isolation.

use super::*;
use crate::invocation_metrics::{InvocationMetricsBus, InvocationTimer};
use crate::memory_tracking::MemoryTracker;
use mockforge_plugin_core::{
    PluginCapabilities, PluginContext, PluginHealth, PluginId, PluginMetrics, PluginResult,
    PluginState,
};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use wasmtime::{Engine, Linker, Module, ResourceLimiter, Store};
use wasmtime_wasi::{WasiCtx, WasiCtxBuilder};

/// Per-store data carried by every WASM `Store` in this sandbox.
///
/// Bundles the WASI context (for stdio + filesystem capability bits)
/// with a [`MemoryTracker`] that Wasmtime calls back via the
/// `ResourceLimiter` trait. The tracker has to live inside the store
/// data because Wasmtime's modern API (`Store::limiter`) takes a
/// closure `|t: &mut T| &mut dyn ResourceLimiter` — there's no way to
/// hand it an externally-owned tracker.
pub struct SandboxStoreData {
    /// WASI context for stdio inheritance + filesystem capabilities.
    pub wasi: WasiCtx,
    /// Memory + table accounting installed on the store via
    /// `Store::limiter`.
    pub tracker: MemoryTracker,
}

/// Build a fully-configured `Store` with the `MemoryTracker` installed
/// as a `ResourceLimiter`. Centralized so the real `new` and the stub
/// `stub_new` can't drift on how the limiter gets wired up.
fn make_store(engine: &Engine, max_memory_bytes: usize) -> Store<SandboxStoreData> {
    let wasi = WasiCtxBuilder::new().inherit_stderr().inherit_stdout().build();
    let tracker = MemoryTracker::with_byte_limit(max_memory_bytes);
    let mut store = Store::new(engine, SandboxStoreData { wasi, tracker });
    store.limiter(|d| &mut d.tracker as &mut dyn ResourceLimiter);
    store
}

/// Plugin sandbox for secure execution
pub struct PluginSandbox {
    /// WebAssembly engine (optional)
    engine: Option<Arc<Engine>>,
    /// Sandbox configuration
    _config: PluginLoaderConfig,
    /// Active sandboxes
    active_sandboxes: RwLock<HashMap<PluginId, SandboxInstance>>,
    /// Per-invocation metrics bus. One per sandbox; cloned `Arc` is
    /// stamped onto each `SandboxInstance` so `execute_function` can
    /// record without round-tripping through the parent.
    metrics_bus: Arc<InvocationMetricsBus>,
}

impl PluginSandbox {
    /// Create a new plugin sandbox
    pub fn new(config: PluginLoaderConfig) -> Self {
        // Create WebAssembly engine for plugin execution
        let engine = Some(Arc::new(Engine::default()));

        Self {
            engine,
            _config: config,
            active_sandboxes: RwLock::new(HashMap::new()),
            metrics_bus: Arc::new(InvocationMetricsBus::new()),
        }
    }

    /// Get the per-invocation metrics bus. Subscribe to receive a live
    /// stream of [`InvocationMetric`] events. Suitable for the admin UI
    /// or an OTLP exporter.
    ///
    /// [`InvocationMetric`]: crate::invocation_metrics::InvocationMetric
    pub fn metrics_bus(&self) -> Arc<InvocationMetricsBus> {
        self.metrics_bus.clone()
    }

    /// Create a plugin instance in the sandbox
    pub async fn create_plugin_instance(
        &self,
        context: &PluginLoadContext,
    ) -> LoaderResult<PluginInstance> {
        let plugin_id = &context.plugin_id;

        // Check if sandbox already exists
        {
            let sandboxes = self.active_sandboxes.read().await;
            if sandboxes.contains_key(plugin_id) {
                return Err(PluginLoaderError::already_loaded(plugin_id.clone()));
            }
        }

        // Create sandbox instance
        let sandbox = if let Some(ref engine) = self.engine {
            SandboxInstance::new(engine, context, self.metrics_bus.clone()).await?
        } else {
            // Create a stub sandbox instance when WebAssembly is disabled
            SandboxInstance::stub_new(context, self.metrics_bus.clone()).await?
        };

        // Store sandbox instance
        let mut sandboxes = self.active_sandboxes.write().await;
        sandboxes.insert(plugin_id.clone(), sandbox);

        // Create core plugin instance
        let mut core_instance = PluginInstance::new(plugin_id.clone(), context.manifest.clone());
        core_instance.set_state(PluginState::Ready);

        Ok(core_instance)
    }

    /// Execute a plugin function in the sandbox
    pub async fn execute_plugin_function(
        &self,
        plugin_id: &PluginId,
        function_name: &str,
        context: &PluginContext,
        input: &[u8],
    ) -> LoaderResult<PluginResult<serde_json::Value>> {
        let mut sandboxes = self.active_sandboxes.write().await;
        let sandbox = sandboxes
            .get_mut(plugin_id)
            .ok_or_else(|| PluginLoaderError::not_found(plugin_id.clone()))?;

        sandbox.execute_function(function_name, context, input).await
    }

    /// Get plugin health from sandbox
    pub async fn get_plugin_health(&self, plugin_id: &PluginId) -> LoaderResult<PluginHealth> {
        let sandboxes = self.active_sandboxes.read().await;
        let sandbox = sandboxes
            .get(plugin_id)
            .ok_or_else(|| PluginLoaderError::not_found(plugin_id.clone()))?;

        Ok(sandbox.get_health().await)
    }

    /// Destroy a plugin sandbox
    pub async fn destroy_sandbox(&self, plugin_id: &PluginId) -> LoaderResult<()> {
        let mut sandboxes = self.active_sandboxes.write().await;
        if let Some(mut sandbox) = sandboxes.remove(plugin_id) {
            sandbox.destroy().await?;
        }
        Ok(())
    }

    /// List active sandboxes
    pub async fn list_active_sandboxes(&self) -> Vec<PluginId> {
        let sandboxes = self.active_sandboxes.read().await;
        sandboxes.keys().cloned().collect()
    }

    /// Get sandbox resource usage
    pub async fn get_sandbox_resources(
        &self,
        plugin_id: &PluginId,
    ) -> LoaderResult<SandboxResources> {
        let sandboxes = self.active_sandboxes.read().await;
        let sandbox = sandboxes
            .get(plugin_id)
            .ok_or_else(|| PluginLoaderError::not_found(plugin_id.clone()))?;

        Ok(sandbox.get_resources().await)
    }

    /// Check sandbox health
    pub async fn check_sandbox_health(&self, plugin_id: &PluginId) -> LoaderResult<SandboxHealth> {
        let sandboxes = self.active_sandboxes.read().await;
        let sandbox = sandboxes
            .get(plugin_id)
            .ok_or_else(|| PluginLoaderError::not_found(plugin_id.clone()))?;

        Ok(sandbox.check_health().await)
    }
}

/// Individual sandbox instance
pub struct SandboxInstance {
    /// Plugin ID
    plugin_id: PluginId,
    /// WebAssembly module
    _module: Module,
    /// WebAssembly store
    store: Store<SandboxStoreData>,
    /// Linker for the instance
    linker: Linker<SandboxStoreData>,
    /// Sandbox resources
    resources: SandboxResources,
    /// Health monitor
    health: SandboxHealth,
    /// Execution limits
    limits: ExecutionLimits,
    /// Bus for emitting per-invocation metrics. Shared with the parent
    /// `PluginSandbox`.
    metrics_bus: Arc<InvocationMetricsBus>,
}

impl SandboxInstance {
    /// Create a new sandbox instance
    async fn new(
        engine: &Engine,
        context: &PluginLoadContext,
        metrics_bus: Arc<InvocationMetricsBus>,
    ) -> LoaderResult<Self> {
        let plugin_id = &context.plugin_id;

        // Load WASM module
        let module = Module::from_file(engine, &context.plugin_path)
            .map_err(|e| PluginLoaderError::wasm(format!("Failed to load WASM module: {}", e)))?;

        // Set up execution limits up front so the memory cap is wired
        // into the store from creation time.
        let plugin_capabilities = PluginCapabilities::default();
        let limits = ExecutionLimits::from_capabilities(&plugin_capabilities);

        let mut store = make_store(engine, limits.max_memory_bytes);

        // Create linker
        let linker = Linker::new(engine);

        // Add WASI functions using the updated API
        // For now, skip WASI integration until proper wasmtime-wasi version is resolved
        // This is a non-critical feature for the main MockForge functionality

        // Instantiate the module
        linker
            .instantiate(&mut store, &module)
            .map_err(|e| PluginLoaderError::wasm(format!("Failed to instantiate module: {}", e)))?;

        Ok(Self {
            plugin_id: plugin_id.clone(),
            _module: module,
            store,
            linker,
            resources: SandboxResources::default(),
            health: SandboxHealth::healthy(),
            limits,
            metrics_bus,
        })
    }

    /// Create a stub sandbox instance (when WebAssembly is disabled)
    async fn stub_new(
        context: &PluginLoadContext,
        metrics_bus: Arc<InvocationMetricsBus>,
    ) -> LoaderResult<Self> {
        let plugin_id = &context.plugin_id;

        // Create dummy values for when WebAssembly is disabled
        let engine = Engine::default();
        let module = Module::new(&engine, [])
            .map_err(|e| PluginLoaderError::wasm(format!("Failed to create stub module: {}", e)))?;

        let plugin_capabilities = PluginCapabilities::default();
        let limits = ExecutionLimits::from_capabilities(&plugin_capabilities);

        let store = make_store(&engine, limits.max_memory_bytes);
        let linker = Linker::new(&engine);

        Ok(Self {
            plugin_id: plugin_id.clone(),
            _module: module,
            store,
            linker,
            resources: SandboxResources::default(),
            health: SandboxHealth::healthy(),
            limits,
            metrics_bus,
        })
    }

    /// Execute a function in the sandbox
    async fn execute_function(
        &mut self,
        function_name: &str,
        context: &PluginContext,
        input: &[u8],
    ) -> LoaderResult<PluginResult<serde_json::Value>> {
        // Update resource tracking
        self.resources.execution_count += 1;
        self.resources.last_execution = chrono::Utc::now();

        // Check execution limits
        if self.resources.execution_count > self.limits.max_executions {
            return Err(PluginLoaderError::resource_limit(format!(
                "Maximum executions exceeded: {} allowed, {} used",
                self.limits.max_executions, self.resources.execution_count
            )));
        }

        // Check time limits
        let time_since_last = chrono::Utc::now().signed_duration_since(self.resources.created_at);
        let time_since_last_std =
            std::time::Duration::from_secs(time_since_last.num_seconds() as u64);
        if time_since_last_std > self.limits.max_lifetime {
            return Err(PluginLoaderError::resource_limit(format!(
                "Maximum lifetime exceeded: {}s allowed, {}s used",
                self.limits.max_lifetime.as_secs(),
                time_since_last_std.as_secs()
            )));
        }

        // Start the per-invocation metrics timer. Finished on either
        // success or failure path below; the limit-check early-returns
        // above happen before this point and don't emit a metric (no
        // plugin code ran).
        let timer = InvocationTimer::start(
            self.metrics_bus.clone(),
            self.plugin_id.clone(),
            function_name.to_string(),
        );

        // Prepare function call
        let start_time = std::time::Instant::now();

        // Get function from linker
        let func_lookup = self.linker.get(&mut self.store, "", function_name);
        if func_lookup.is_none() {
            // Function-not-found: count as a failed invocation in both
            // the aggregate counters and the per-invocation bus.
            self.resources.error_count += 1;
            let err_msg = format!("Function '{}' not found", function_name);
            timer.finish_failure(err_msg.clone(), self.resources.peak_memory_usage as u64);
            return Err(PluginLoaderError::execution(err_msg));
        }

        // Execute function (simplified - real implementation would handle WASM calling conventions)
        let result = self.call_wasm_function(function_name, context, input).await;

        // Update resource tracking
        let execution_time = start_time.elapsed();
        self.resources.total_execution_time += execution_time;
        self.resources.last_execution_time = execution_time;

        if execution_time > self.resources.max_execution_time {
            self.resources.max_execution_time = execution_time;
        }

        // Read peak memory from the `MemoryTracker` installed on the
        // store. Wasmtime calls back into the tracker via
        // `ResourceLimiter::memory_growing` whenever the WASM module
        // grows linear memory, so this is a real observation — not the
        // 0 placeholder from the previous iteration of this code path.
        // Mirror it onto the aggregate `SandboxResources` for the
        // existing health-check + status surfaces.
        let peak_memory_bytes = self.store.data().tracker.peak_memory() as u64;
        if (peak_memory_bytes as usize) > self.resources.peak_memory_usage {
            self.resources.peak_memory_usage = peak_memory_bytes as usize;
        }
        self.resources.memory_usage = self.store.data().tracker.current_memory();

        match result {
            Ok(data) => {
                self.resources.success_count += 1;
                timer.finish_success(peak_memory_bytes);
                Ok(PluginResult::success(data, execution_time.as_millis() as u64))
            }
            Err(e) => {
                self.resources.error_count += 1;
                timer.finish_failure(e.clone(), peak_memory_bytes);
                Ok(PluginResult::failure(e, execution_time.as_millis() as u64))
            }
        }
    }

    /// Call WebAssembly function
    async fn call_wasm_function(
        &mut self,
        function_name: &str,
        context: &PluginContext,
        input: &[u8],
    ) -> Result<serde_json::Value, String> {
        // Serialize context and input for WASM
        let context_json = serde_json::to_string(context)
            .map_err(|e| format!("Failed to serialize context: {}", e))?;
        let combined_input = format!("{}\n{}", context_json, String::from_utf8_lossy(input));

        // Get the exported function from the linker
        let func_extern = self
            .linker
            .get(&mut self.store, "", function_name)
            .ok_or_else(|| format!("Function '{}' not found in WASM module", function_name))?;
        let func = func_extern
            .into_func()
            .ok_or_else(|| format!("Export '{}' is not a function", function_name))?;

        // Allocate memory in WASM for the input string
        let input_bytes = combined_input.as_bytes();
        let input_len = input_bytes.len() as i32;

        // Get alloc function
        let alloc_extern = self.linker.get(&mut self.store, "", "alloc").ok_or_else(|| {
            "WASM module must export an 'alloc' function for memory allocation".to_string()
        })?;
        let alloc_func = alloc_extern
            .into_func()
            .ok_or_else(|| "Export 'alloc' is not a function".to_string())?;

        let mut alloc_result = [wasmtime::Val::I32(0)];
        alloc_func
            .call(&mut self.store, &[wasmtime::Val::I32(input_len)], &mut alloc_result)
            .map_err(|e| format!("Failed to allocate memory for input: {}", e))?;

        let input_ptr = match alloc_result[0] {
            wasmtime::Val::I32(ptr) => ptr,
            _ => return Err("alloc function did not return a valid pointer".to_string()),
        };

        // Write the input string to WASM memory
        let memory_extern = self
            .linker
            .get(&mut self.store, "", "memory")
            .ok_or_else(|| "WASM module must export a 'memory'".to_string())?;
        let memory = memory_extern
            .into_memory()
            .ok_or_else(|| "Export 'memory' is not a memory".to_string())?;

        memory
            .write(&mut self.store, input_ptr as usize, input_bytes)
            .map_err(|e| format!("Failed to write input to WASM memory: {}", e))?;

        // Call the plugin function with the input pointer and length
        let mut func_result = [wasmtime::Val::I32(0), wasmtime::Val::I32(0)];
        func.call(
            &mut self.store,
            &[wasmtime::Val::I32(input_ptr), wasmtime::Val::I32(input_len)],
            &mut func_result,
        )
        .map_err(|e| format!("Failed to call WASM function '{}': {}", function_name, e))?;

        // Extract the return values (assuming the function returns (ptr, len))
        let output_ptr = match func_result[0] {
            wasmtime::Val::I32(ptr) => ptr,
            _ => {
                return Err(format!(
                    "Function '{}' did not return a valid output pointer",
                    function_name
                ))
            }
        };

        let output_len = match func_result[1] {
            wasmtime::Val::I32(len) => len,
            _ => {
                return Err(format!(
                    "Function '{}' did not return a valid output length",
                    function_name
                ))
            }
        };

        // Read the output from WASM memory
        let mut output_bytes = vec![0u8; output_len as usize];
        memory
            .read(&mut self.store, output_ptr as usize, &mut output_bytes)
            .map_err(|e| format!("Failed to read output from WASM memory: {}", e))?;

        // Deallocate the memory if there's a dealloc function
        if let Some(dealloc_extern) = self.linker.get(&mut self.store, "", "dealloc") {
            if let Some(dealloc_func) = dealloc_extern.into_func() {
                let _ = dealloc_func.call(
                    &mut self.store,
                    &[wasmtime::Val::I32(input_ptr), wasmtime::Val::I32(input_len)],
                    &mut [],
                );
                let _ = dealloc_func.call(
                    &mut self.store,
                    &[
                        wasmtime::Val::I32(output_ptr),
                        wasmtime::Val::I32(output_len),
                    ],
                    &mut [],
                );
            }
        }

        // Parse the output as JSON
        let output_str = String::from_utf8(output_bytes)
            .map_err(|e| format!("Failed to convert output to string: {}", e))?;

        serde_json::from_str(&output_str)
            .map_err(|e| format!("Failed to parse WASM output as JSON: {}", e))
    }

    /// Get sandbox health
    async fn get_health(&self) -> PluginHealth {
        if self.health.is_healthy {
            PluginHealth::healthy(
                "Sandbox is healthy".to_string(),
                PluginMetrics {
                    total_executions: self.resources.execution_count,
                    successful_executions: self.resources.success_count,
                    failed_executions: self.resources.error_count,
                    avg_execution_time_ms: self.resources.avg_execution_time_ms(),
                    max_execution_time_ms: self.resources.max_execution_time.as_millis() as u64,
                    memory_usage_bytes: self.resources.memory_usage,
                    peak_memory_usage_bytes: self.resources.peak_memory_usage,
                },
            )
        } else {
            PluginHealth::unhealthy(
                PluginState::Error,
                self.health.last_error.clone(),
                PluginMetrics::default(),
            )
        }
    }

    /// Get sandbox resources
    async fn get_resources(&self) -> SandboxResources {
        self.resources.clone()
    }

    /// Check sandbox health
    async fn check_health(&self) -> SandboxHealth {
        self.health.clone()
    }

    /// Destroy the sandbox
    async fn destroy(&mut self) -> LoaderResult<()> {
        // Cleanup resources
        self.health.is_healthy = false;
        self.health.last_error = "Sandbox destroyed".to_string();
        Ok(())
    }
}

/// Sandbox resource tracking
#[derive(Debug, Clone, Default)]
pub struct SandboxResources {
    /// Total execution count
    pub execution_count: u64,
    /// Successful execution count
    pub success_count: u64,
    /// Error execution count
    pub error_count: u64,
    /// Total execution time
    pub total_execution_time: std::time::Duration,
    /// Last execution time
    pub last_execution_time: std::time::Duration,
    /// Maximum execution time
    pub max_execution_time: std::time::Duration,
    /// Current memory usage
    pub memory_usage: usize,
    /// Peak memory usage
    pub peak_memory_usage: usize,
    /// Creation time
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// Last execution time
    pub last_execution: chrono::DateTime<chrono::Utc>,
}

impl SandboxResources {
    /// Get average execution time in milliseconds
    pub fn avg_execution_time_ms(&self) -> f64 {
        if self.execution_count == 0 {
            0.0
        } else {
            self.total_execution_time.as_millis() as f64 / self.execution_count as f64
        }
    }

    /// Get success rate as percentage
    pub fn success_rate(&self) -> f64 {
        if self.execution_count == 0 {
            0.0
        } else {
            (self.success_count as f64 / self.execution_count as f64) * 100.0
        }
    }

    /// Check if resource limits are exceeded
    pub fn check_limits(&self, limits: &ExecutionLimits) -> bool {
        self.execution_count <= limits.max_executions
            && self.memory_usage <= limits.max_memory_bytes
            && self.total_execution_time <= limits.max_total_time
    }
}

/// Sandbox health status
#[derive(Debug, Clone)]
pub struct SandboxHealth {
    /// Whether sandbox is healthy
    pub is_healthy: bool,
    /// Last health check time
    pub last_check: chrono::DateTime<chrono::Utc>,
    /// Last error message
    pub last_error: String,
    /// Health check results
    pub checks: Vec<HealthCheck>,
}

impl SandboxHealth {
    /// Create healthy status
    pub fn healthy() -> Self {
        Self {
            is_healthy: true,
            last_check: chrono::Utc::now(),
            last_error: String::new(),
            checks: Vec::new(),
        }
    }

    /// Create unhealthy status
    pub fn unhealthy<S: Into<String>>(error: S) -> Self {
        Self {
            is_healthy: false,
            last_check: chrono::Utc::now(),
            last_error: error.into(),
            checks: Vec::new(),
        }
    }

    /// Add health check result
    pub fn add_check(&mut self, check: HealthCheck) {
        let failed = !check.passed;
        let error_message = if failed {
            Some(check.message.clone())
        } else {
            None
        };

        self.checks.push(check);
        self.last_check = chrono::Utc::now();

        // Update overall health
        if failed {
            self.is_healthy = false;
            if let Some(msg) = error_message {
                self.last_error = msg;
            }
        }
    }

    /// Run health checks
    pub async fn run_checks(&mut self, resources: &SandboxResources, limits: &ExecutionLimits) {
        self.checks.clear();

        // Memory usage check
        let memory_check = if resources.memory_usage <= limits.max_memory_bytes {
            HealthCheck::pass("Memory usage within limits")
        } else {
            HealthCheck::fail(format!(
                "Memory usage {} exceeds limit {}",
                resources.memory_usage, limits.max_memory_bytes
            ))
        };
        self.add_check(memory_check);

        // Execution count check
        let execution_check = if resources.execution_count <= limits.max_executions {
            HealthCheck::pass("Execution count within limits")
        } else {
            HealthCheck::fail(format!(
                "Execution count {} exceeds limit {}",
                resources.execution_count, limits.max_executions
            ))
        };
        self.add_check(execution_check);

        // Success rate check
        let success_rate = resources.success_rate();
        let success_check = if success_rate >= 90.0 {
            HealthCheck::pass(format!("Success rate: {:.1}%", success_rate))
        } else {
            HealthCheck::fail(format!("Low success rate: {:.1}%", success_rate))
        };
        self.add_check(success_check);
    }
}

/// Health check result
#[derive(Debug, Clone)]
pub struct HealthCheck {
    /// Check name
    pub name: String,
    /// Whether check passed
    pub passed: bool,
    /// Check message
    pub message: String,
    /// Check timestamp
    pub timestamp: chrono::DateTime<chrono::Utc>,
}

impl HealthCheck {
    /// Create passing check
    pub fn pass<S: Into<String>>(message: S) -> Self {
        Self {
            name: "health_check".to_string(),
            passed: true,
            message: message.into(),
            timestamp: chrono::Utc::now(),
        }
    }

    /// Create failing check
    pub fn fail<S: Into<String>>(message: S) -> Self {
        Self {
            name: "health_check".to_string(),
            passed: false,
            message: message.into(),
            timestamp: chrono::Utc::now(),
        }
    }
}

/// Execution limits for sandbox
#[derive(Debug, Clone)]
pub struct ExecutionLimits {
    /// Maximum number of executions
    pub max_executions: u64,
    /// Maximum total execution time
    pub max_total_time: std::time::Duration,
    /// Maximum lifetime
    pub max_lifetime: std::time::Duration,
    /// Maximum memory usage
    pub max_memory_bytes: usize,
    /// Maximum CPU time per execution
    pub max_cpu_time_per_execution: std::time::Duration,
}

impl Default for ExecutionLimits {
    fn default() -> Self {
        Self {
            max_executions: 1000,
            max_total_time: std::time::Duration::from_secs(300), // 5 minutes
            max_lifetime: std::time::Duration::from_secs(3600),  // 1 hour
            max_memory_bytes: 10 * 1024 * 1024,                  // 10MB
            max_cpu_time_per_execution: std::time::Duration::from_secs(5),
        }
    }
}

impl ExecutionLimits {
    /// Create limits from plugin capabilities
    pub fn from_capabilities(capabilities: &PluginCapabilities) -> Self {
        Self {
            max_executions: 10000, // Override with capability-based limits
            max_total_time: std::time::Duration::from_secs(600), // 10 minutes
            max_lifetime: std::time::Duration::from_secs(86400), // 24 hours
            max_memory_bytes: capabilities.resources.max_memory_bytes,
            max_cpu_time_per_execution: std::time::Duration::from_millis(
                (capabilities.resources.max_cpu_percent * 1000.0) as u64,
            ),
        }
    }
}

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

    #[tokio::test]
    async fn test_sandbox_resources() {
        let resources = SandboxResources {
            execution_count: 10,
            success_count: 8,
            error_count: 2,
            total_execution_time: std::time::Duration::from_millis(1000),
            ..Default::default()
        };

        assert_eq!(resources.avg_execution_time_ms(), 100.0);
        assert_eq!(resources.success_rate(), 80.0);
    }

    #[tokio::test]
    async fn test_execution_limits() {
        let limits = ExecutionLimits::default();
        assert_eq!(limits.max_executions, 1000);
        assert_eq!(limits.max_memory_bytes, 10 * 1024 * 1024);
    }

    #[tokio::test]
    async fn test_health_checks() {
        let mut health = SandboxHealth::healthy();
        assert!(health.is_healthy);

        health.add_check(HealthCheck::fail("Test failure"));
        assert!(!health.is_healthy);
        assert_eq!(health.last_error, "Test failure");
    }

    #[tokio::test]
    async fn test_plugin_sandbox_creation() {
        let config = PluginLoaderConfig::default();
        let sandbox = PluginSandbox::new(config);

        let active = sandbox.list_active_sandboxes().await;
        assert!(active.is_empty());
    }
}