pluggable 0.1.0

A comprehensive, async plugin system for Rust applications with dependency management and security
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
//! Plugin sandbox and isolation system

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::sync::RwLock;

use crate::core::{PluginError, PluginResult, SecurityContext};

/// Sandbox configuration for plugin isolation
#[derive(Debug, Clone)]
pub struct SandboxConfig {
    /// Isolated temporary directory for the plugin
    pub temp_directory: PathBuf,
    /// Maximum memory usage (in bytes)
    pub max_memory: Option<u64>,
    /// Maximum execution time (in seconds)
    pub max_execution_time: Option<u64>,
    /// Allowed environment variables
    pub allowed_env_vars: Vec<String>,
    /// Custom filesystem root (chroot-like behavior)
    pub filesystem_root: Option<PathBuf>,
    /// Network isolation enabled
    pub network_isolation: bool,
}

impl Default for SandboxConfig {
    fn default() -> Self {
        Self {
            temp_directory: std::env::temp_dir().join("pluggable-sandbox"),
            max_memory: Some(128 * 1024 * 1024), // 128MB default
            max_execution_time: Some(300),       // 5 minutes default
            allowed_env_vars: vec!["PATH".to_string(), "HOME".to_string(), "USER".to_string()],
            filesystem_root: None,
            network_isolation: false,
        }
    }
}

/// Plugin sandbox for runtime isolation
#[derive(Debug)]
pub struct Sandbox {
    plugin_name: String,
    config: SandboxConfig,
    security_context: SecurityContext,
    isolated_env: HashMap<String, String>,
    temp_dir: Option<PathBuf>,
    active: bool,
}

impl Sandbox {
    /// Create a new sandbox for a plugin
    pub fn new(
        plugin_name: String,
        config: SandboxConfig,
        security_context: SecurityContext,
    ) -> Self {
        Self {
            plugin_name,
            config,
            security_context,
            isolated_env: HashMap::new(),
            temp_dir: None,
            active: false,
        }
    }

    /// Initialize the sandbox environment
    pub async fn initialize(&mut self) -> PluginResult<()> {
        if self.active {
            return Err(PluginError::SandboxError(
                "Sandbox is already active".to_string(),
            ));
        }

        // Create isolated temporary directory
        let plugin_temp_dir = self.config.temp_directory.join(&self.plugin_name);
        tokio::fs::create_dir_all(&plugin_temp_dir)
            .await
            .map_err(|e| {
                PluginError::SandboxError(format!("Failed to create temp directory: {e}"))
            })?;

        self.temp_dir = Some(plugin_temp_dir);

        // Setup isolated environment variables
        self.setup_environment()?;

        self.active = true;
        Ok(())
    }

    /// Setup isolated environment variables
    fn setup_environment(&mut self) -> PluginResult<()> {
        // Start with a clean environment
        self.isolated_env.clear();

        // Add only allowed environment variables
        for var_name in &self.config.allowed_env_vars {
            if let Ok(value) = std::env::var(var_name) {
                self.isolated_env.insert(var_name.clone(), value);
            }
        }

        // Add sandbox-specific variables
        if let Some(temp_dir) = &self.temp_dir {
            self.isolated_env.insert(
                "PLUGIN_TEMP_DIR".to_string(),
                temp_dir.to_string_lossy().to_string(),
            );
        }

        self.isolated_env
            .insert("PLUGIN_NAME".to_string(), self.plugin_name.clone());

        self.isolated_env
            .insert("PLUGIN_SANDBOX".to_string(), "true".to_string());

        Ok(())
    }

    /// Get the isolated environment variables
    pub fn environment(&self) -> &HashMap<String, String> {
        &self.isolated_env
    }

    /// Get the isolated temporary directory
    pub fn temp_directory(&self) -> Option<&PathBuf> {
        self.temp_dir.as_ref()
    }

    /// Check if the sandbox is active
    pub fn is_active(&self) -> bool {
        self.active
    }

    /// Get the plugin name
    pub fn plugin_name(&self) -> &str {
        &self.plugin_name
    }

    /// Get the security context
    pub fn security_context(&self) -> &SecurityContext {
        &self.security_context
    }

    /// Validate file access within sandbox
    pub fn validate_file_access(&self, path: &Path) -> PluginResult<()> {
        if !self.active {
            return Err(PluginError::SandboxError(
                "Sandbox is not active".to_string(),
            ));
        }

        // Check if path is within allowed boundaries
        if let Some(root) = &self.config.filesystem_root {
            if !path.starts_with(root) {
                return Err(PluginError::PermissionDenied {
                    plugin: self.plugin_name.clone(),
                    action: format!("File access outside sandbox root: {}", path.display()),
                });
            }
        }

        // Always allow access to plugin's temp directory
        if let Some(temp_dir) = &self.temp_dir {
            if path.starts_with(temp_dir) {
                return Ok(());
            }
        }

        // Use security context to validate file access
        use crate::core::security::{AccessType, Permission};

        // Try different access types - we'll check the most permissive first
        let permissions_to_check = vec![
            Permission::FileSystem {
                path: path.to_path_buf(),
                access: AccessType::ReadWrite,
            },
            Permission::FileSystem {
                path: path.to_path_buf(),
                access: AccessType::Read,
            },
            Permission::FileSystem {
                path: path.to_path_buf(),
                access: AccessType::Write,
            },
            Permission::FileSystem {
                path: path.to_path_buf(),
                access: AccessType::Execute,
            },
        ];

        for permission in permissions_to_check {
            if self.security_context.has_permission(&permission) {
                return Ok(());
            }
        }

        Err(PluginError::PermissionDenied {
            plugin: self.plugin_name.clone(),
            action: format!("File access denied: {}", path.display()),
        })
    }

    /// Validate network access within sandbox
    pub fn validate_network_access(&self, host: &str, port: u16) -> PluginResult<()> {
        if !self.active {
            return Err(PluginError::SandboxError(
                "Sandbox is not active".to_string(),
            ));
        }

        if self.config.network_isolation {
            return Err(PluginError::PermissionDenied {
                plugin: self.plugin_name.clone(),
                action: "Network access disabled by sandbox isolation".to_string(),
            });
        }

        // Use security context to validate network access
        use crate::core::security::Permission;

        let permission = Permission::Network {
            hosts: vec![host.to_string()],
            ports: vec![port],
        };

        if self.security_context.has_permission(&permission) {
            Ok(())
        } else {
            Err(PluginError::PermissionDenied {
                plugin: self.plugin_name.clone(),
                action: format!("Network access denied: {host}:{port}"),
            })
        }
    }

    /// Validate process execution within sandbox
    pub fn validate_process_execution(&self, command: &str) -> PluginResult<()> {
        if !self.active {
            return Err(PluginError::SandboxError(
                "Sandbox is not active".to_string(),
            ));
        }

        // Use security context to validate process execution
        use crate::core::security::Permission;

        let permission = Permission::Process {
            commands: vec![command.to_string()],
        };

        if self.security_context.has_permission(&permission) {
            Ok(())
        } else {
            Err(PluginError::PermissionDenied {
                plugin: self.plugin_name.clone(),
                action: format!("Process execution denied: {command}"),
            })
        }
    }

    /// Clean up sandbox resources
    pub async fn cleanup(&mut self) -> PluginResult<()> {
        if !self.active {
            return Ok(());
        }

        // Clean up temporary directory
        if let Some(temp_dir) = &self.temp_dir {
            if temp_dir.exists() {
                tokio::fs::remove_dir_all(temp_dir).await.map_err(|e| {
                    PluginError::CleanupFailed(format!("Failed to cleanup temp directory: {e}"))
                })?;
            }
        }

        self.temp_dir = None;
        self.isolated_env.clear();
        self.active = false;

        Ok(())
    }
}

impl Drop for Sandbox {
    fn drop(&mut self) {
        // Best effort cleanup on drop
        if self.active {
            if let Some(temp_dir) = &self.temp_dir {
                if temp_dir.exists() {
                    let _ = std::fs::remove_dir_all(temp_dir);
                }
            }
        }
    }
}

/// Sandbox manager for creating and managing plugin sandboxes
#[derive(Debug, Default)]
pub struct SandboxManager {
    active_sandboxes: Arc<RwLock<HashMap<String, Sandbox>>>,
    default_config: SandboxConfig,
}

impl SandboxManager {
    /// Create a new sandbox manager
    pub fn new() -> Self {
        Self {
            active_sandboxes: Arc::new(RwLock::new(HashMap::new())),
            default_config: SandboxConfig::default(),
        }
    }

    /// Create a new sandbox manager with custom default config
    pub fn with_config(config: SandboxConfig) -> Self {
        Self {
            active_sandboxes: Arc::new(RwLock::new(HashMap::new())),
            default_config: config,
        }
    }

    /// Create a sandbox for a plugin
    pub async fn create_sandbox(
        &self,
        plugin_name: String,
        security_context: SecurityContext,
    ) -> PluginResult<()> {
        self.create_sandbox_with_config(plugin_name, self.default_config.clone(), security_context)
            .await
    }

    /// Create a sandbox with custom configuration
    pub async fn create_sandbox_with_config(
        &self,
        plugin_name: String,
        config: SandboxConfig,
        security_context: SecurityContext,
    ) -> PluginResult<()> {
        let mut sandboxes = self.active_sandboxes.write().await;

        if sandboxes.contains_key(&plugin_name) {
            return Err(PluginError::SandboxError(format!(
                "Sandbox for plugin '{plugin_name}' already exists"
            )));
        }

        let mut sandbox = Sandbox::new(plugin_name.clone(), config, security_context);
        sandbox.initialize().await?;

        sandboxes.insert(plugin_name, sandbox);
        Ok(())
    }

    /// Check if a sandbox exists for a plugin
    pub async fn has_sandbox(&self, plugin_name: &str) -> bool {
        let sandboxes = self.active_sandboxes.read().await;
        sandboxes.contains_key(plugin_name)
    }

    /// Validate file access for a plugin using its sandbox
    pub async fn validate_file_access(&self, plugin_name: &str, path: &Path) -> PluginResult<()> {
        let sandboxes = self.active_sandboxes.read().await;
        if let Some(sandbox) = sandboxes.get(plugin_name) {
            sandbox.validate_file_access(path)
        } else {
            Err(PluginError::SandboxError(format!(
                "No sandbox found for plugin '{plugin_name}'"
            )))
        }
    }

    /// Validate network access for a plugin using its sandbox
    pub async fn validate_network_access(
        &self,
        plugin_name: &str,
        host: &str,
        port: u16,
    ) -> PluginResult<()> {
        let sandboxes = self.active_sandboxes.read().await;
        if let Some(sandbox) = sandboxes.get(plugin_name) {
            sandbox.validate_network_access(host, port)
        } else {
            Err(PluginError::SandboxError(format!(
                "No sandbox found for plugin '{plugin_name}'"
            )))
        }
    }

    /// Validate process execution for a plugin using its sandbox
    pub async fn validate_process_execution(
        &self,
        plugin_name: &str,
        command: &str,
    ) -> PluginResult<()> {
        let sandboxes = self.active_sandboxes.read().await;
        if let Some(sandbox) = sandboxes.get(plugin_name) {
            sandbox.validate_process_execution(command)
        } else {
            Err(PluginError::SandboxError(format!(
                "No sandbox found for plugin '{plugin_name}'"
            )))
        }
    }

    /// Remove and cleanup a sandbox
    pub async fn remove_sandbox(&self, plugin_name: &str) -> PluginResult<()> {
        let mut sandboxes = self.active_sandboxes.write().await;

        if let Some(mut sandbox) = sandboxes.remove(plugin_name) {
            sandbox.cleanup().await?;
        }

        Ok(())
    }

    /// Get all active sandbox names
    pub async fn active_sandboxes(&self) -> Vec<String> {
        let sandboxes = self.active_sandboxes.read().await;
        sandboxes.keys().cloned().collect()
    }

    /// Cleanup all sandboxes
    pub async fn cleanup_all(&self) -> PluginResult<()> {
        let mut sandboxes = self.active_sandboxes.write().await;

        for (_, mut sandbox) in sandboxes.drain() {
            if let Err(e) = sandbox.cleanup().await {
                eprintln!(
                    "Warning: Failed to cleanup sandbox for '{}': {}",
                    sandbox.plugin_name(),
                    e
                );
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::security::{Permission, SecurityContext};
    use std::collections::HashSet;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_sandbox_creation() {
        let temp_dir = TempDir::new().unwrap();
        let config = SandboxConfig {
            temp_directory: temp_dir.path().to_path_buf(),
            ..Default::default()
        };

        let permissions = HashSet::new();
        let security_context = SecurityContext::new("test-plugin".to_string(), permissions);

        let mut sandbox = Sandbox::new("test-plugin".to_string(), config, security_context);
        assert!(!sandbox.is_active());

        sandbox.initialize().await.unwrap();
        assert!(sandbox.is_active());
        assert!(sandbox.temp_directory().is_some());
    }

    #[tokio::test]
    async fn test_sandbox_environment() {
        let temp_dir = TempDir::new().unwrap();
        let config = SandboxConfig {
            temp_directory: temp_dir.path().to_path_buf(),
            allowed_env_vars: vec!["PATH".to_string()],
            ..Default::default()
        };

        let permissions = HashSet::new();
        let security_context = SecurityContext::new("test-plugin".to_string(), permissions);

        let mut sandbox = Sandbox::new("test-plugin".to_string(), config, security_context);
        sandbox.initialize().await.unwrap();

        let env = sandbox.environment();
        assert!(env.contains_key("PLUGIN_NAME"));
        assert!(env.contains_key("PLUGIN_SANDBOX"));
        assert!(env.contains_key("PLUGIN_TEMP_DIR"));
        assert_eq!(env.get("PLUGIN_SANDBOX").unwrap(), "true");
    }

    #[tokio::test]
    async fn test_sandbox_file_access_validation() {
        let temp_dir = TempDir::new().unwrap();
        let config = SandboxConfig {
            temp_directory: temp_dir.path().to_path_buf(),
            ..Default::default()
        };

        let mut permissions = HashSet::new();
        permissions.insert(Permission::fs_read("/tmp"));
        let security_context = SecurityContext::new("test-plugin".to_string(), permissions);

        let mut sandbox = Sandbox::new("test-plugin".to_string(), config, security_context);
        sandbox.initialize().await.unwrap();

        // Should allow access to /tmp
        assert!(sandbox.validate_file_access(Path::new("/tmp/test")).is_ok());

        // Should deny access to /etc
        assert!(sandbox
            .validate_file_access(Path::new("/etc/passwd"))
            .is_err());

        // Should always allow access to plugin temp directory
        if let Some(temp_dir) = sandbox.temp_directory() {
            let test_file = temp_dir.join("test.txt");
            assert!(sandbox.validate_file_access(&test_file).is_ok());
        }
    }

    #[tokio::test]
    async fn test_sandbox_network_access_validation() {
        let temp_dir = TempDir::new().unwrap();
        let config = SandboxConfig {
            temp_directory: temp_dir.path().to_path_buf(),
            network_isolation: true,
            ..Default::default()
        };

        let permissions = HashSet::new();
        let security_context = SecurityContext::new("test-plugin".to_string(), permissions);

        let mut sandbox = Sandbox::new("test-plugin".to_string(), config, security_context);
        sandbox.initialize().await.unwrap();

        // Should deny network access due to isolation
        assert!(sandbox.validate_network_access("localhost", 8080).is_err());
    }

    #[tokio::test]
    async fn test_sandbox_manager() {
        let manager = SandboxManager::new();

        let permissions = HashSet::new();
        let security_context = SecurityContext::new("test-plugin".to_string(), permissions);

        // Create sandbox
        manager
            .create_sandbox("test-plugin".to_string(), security_context)
            .await
            .unwrap();

        // Check it exists
        assert!(manager.has_sandbox("test-plugin").await);
        assert_eq!(manager.active_sandboxes().await.len(), 1);

        // Remove sandbox
        manager.remove_sandbox("test-plugin").await.unwrap();
        assert!(!manager.has_sandbox("test-plugin").await);
        assert_eq!(manager.active_sandboxes().await.len(), 0);
    }

    #[tokio::test]
    async fn test_sandbox_cleanup() {
        let temp_dir = TempDir::new().unwrap();
        let plugin_temp = temp_dir.path().join("test-plugin");

        let config = SandboxConfig {
            temp_directory: temp_dir.path().to_path_buf(),
            ..Default::default()
        };

        let permissions = HashSet::new();
        let security_context = SecurityContext::new("test-plugin".to_string(), permissions);

        let mut sandbox = Sandbox::new("test-plugin".to_string(), config, security_context);
        sandbox.initialize().await.unwrap();

        // Verify temp directory was created
        assert!(plugin_temp.exists());

        // Cleanup sandbox
        sandbox.cleanup().await.unwrap();
        assert!(!sandbox.is_active());
    }
}