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
//! Security and permission management for plugins

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use crate::core::sandbox::{Sandbox, SandboxConfig};
use crate::core::{PluginError, PluginResult};

/// Types of access permissions
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AccessType {
    /// Read-only access
    Read,
    /// Write-only access
    Write,
    /// Execute access
    Execute,
    /// Read and write access
    ReadWrite,
}

/// System capabilities that plugins can request
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SystemCapability {
    /// Get system hostname
    GetHostname,
    /// Get system information (OS, version, etc.)
    GetSystemInfo,
    /// Get current user information
    GetCurrentUser,
    /// List running processes
    ListProcesses,
    /// Get environment variables
    GetEnvironment,
    /// Set environment variables
    SetEnvironment,
}

/// Permission types that plugins can request
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Permission {
    /// File system access to specific path
    FileSystem { path: PathBuf, access: AccessType },
    /// Network access to specific hosts and ports
    Network { hosts: Vec<String>, ports: Vec<u16> },
    /// Process execution permissions
    Process { commands: Vec<String> },
    /// Environment variable access
    Environment { variables: Vec<String> },
    /// System capability access
    System { capabilities: Vec<SystemCapability> },
    /// Temporary directory access (automatically granted)
    TempDir,
}

impl Permission {
    /// Create a filesystem read permission
    pub fn fs_read(path: impl Into<PathBuf>) -> Self {
        Self::FileSystem {
            path: path.into(),
            access: AccessType::Read,
        }
    }

    /// Create a filesystem write permission
    pub fn fs_write(path: impl Into<PathBuf>) -> Self {
        Self::FileSystem {
            path: path.into(),
            access: AccessType::Write,
        }
    }

    /// Create a filesystem read-write permission
    pub fn fs_read_write(path: impl Into<PathBuf>) -> Self {
        Self::FileSystem {
            path: path.into(),
            access: AccessType::ReadWrite,
        }
    }

    /// Create a process execution permission
    pub fn process(commands: Vec<String>) -> Self {
        Self::Process { commands }
    }

    /// Create a network access permission
    pub fn network(hosts: Vec<String>, ports: Vec<u16>) -> Self {
        Self::Network { hosts, ports }
    }

    /// Create an environment variable access permission
    pub fn environment(variables: Vec<String>) -> Self {
        Self::Environment { variables }
    }

    /// Create a system capability permission
    pub fn system(capabilities: Vec<SystemCapability>) -> Self {
        Self::System { capabilities }
    }
}

/// Security context for plugin execution
#[derive(Debug, Clone)]
pub struct SecurityContext {
    plugin_name: String,
    granted_permissions: HashSet<Permission>,
    temp_dir: Option<PathBuf>,
}

impl SecurityContext {
    /// Create a new security context for a plugin
    pub fn new(plugin_name: String, permissions: HashSet<Permission>) -> Self {
        Self {
            plugin_name,
            granted_permissions: permissions,
            temp_dir: None,
        }
    }

    /// Check if a permission is granted
    pub fn has_permission(&self, permission: &Permission) -> bool {
        // Always allow temp directory access
        if matches!(permission, Permission::TempDir) {
            return true;
        }

        // Check for exact permission match
        if self.granted_permissions.contains(permission) {
            return true;
        }

        // Check for broader permissions that cover this request
        self.check_broader_permissions(permission)
    }

    /// Check if broader permissions cover the requested permission
    fn check_broader_permissions(&self, requested: &Permission) -> bool {
        match requested {
            Permission::FileSystem { path, access } => {
                // Check if we have broader filesystem permissions
                for granted in &self.granted_permissions {
                    if let Permission::FileSystem {
                        path: granted_path,
                        access: granted_access,
                    } = granted
                    {
                        if self.path_is_covered(path, granted_path)
                            && self.access_is_covered(access, granted_access)
                        {
                            return true;
                        }
                    }
                }
                false
            }
            Permission::Network { hosts, ports } => {
                // Check if we have broader network permissions
                for granted in &self.granted_permissions {
                    if let Permission::Network {
                        hosts: granted_hosts,
                        ports: granted_ports,
                    } = granted
                    {
                        if self.hosts_are_covered(hosts, granted_hosts)
                            && self.ports_are_covered(ports, granted_ports)
                        {
                            return true;
                        }
                    }
                }
                false
            }
            Permission::Process { commands } => {
                // Check if we have broader process permissions
                for granted in &self.granted_permissions {
                    if let Permission::Process {
                        commands: granted_commands,
                    } = granted
                    {
                        if self.commands_are_covered(commands, granted_commands) {
                            return true;
                        }
                    }
                }
                false
            }
            Permission::Environment { variables } => {
                // Check if we have broader environment permissions
                for granted in &self.granted_permissions {
                    if let Permission::Environment {
                        variables: granted_vars,
                    } = granted
                    {
                        if self.variables_are_covered(variables, granted_vars) {
                            return true;
                        }
                    }
                }
                false
            }
            Permission::System { capabilities } => {
                // Check if we have broader system permissions
                for granted in &self.granted_permissions {
                    if let Permission::System {
                        capabilities: granted_caps,
                    } = granted
                    {
                        if self.capabilities_are_covered(capabilities, granted_caps) {
                            return true;
                        }
                    }
                }
                false
            }
            Permission::TempDir => true, // Always allowed
        }
    }

    /// Check if a path is covered by a granted path
    fn path_is_covered(&self, requested: &Path, granted: &Path) -> bool {
        // Exact match
        if requested == granted {
            return true;
        }

        // Check if requested path is under granted path
        requested.starts_with(granted)
    }

    /// Check if requested access is covered by granted access
    fn access_is_covered(&self, requested: &AccessType, granted: &AccessType) -> bool {
        match (requested, granted) {
            // Exact match
            (a, b) if a == b => true,
            // ReadWrite covers both Read and Write
            (AccessType::Read, AccessType::ReadWrite) => true,
            (AccessType::Write, AccessType::ReadWrite) => true,
            _ => false,
        }
    }

    /// Check if requested hosts are covered by granted hosts
    fn hosts_are_covered(&self, requested: &[String], granted: &[String]) -> bool {
        requested.iter().all(|req_host| {
            granted.iter().any(|granted_host| {
                req_host == granted_host || granted_host == "*" || granted_host == "localhost"
            })
        })
    }

    /// Check if requested ports are covered by granted ports
    fn ports_are_covered(&self, requested: &[u16], granted: &[u16]) -> bool {
        requested.iter().all(|req_port| granted.contains(req_port))
    }

    /// Check if requested commands are covered by granted commands
    fn commands_are_covered(&self, requested: &[String], granted: &[String]) -> bool {
        requested.iter().all(|req_cmd| {
            granted
                .iter()
                .any(|granted_cmd| req_cmd == granted_cmd || granted_cmd == "*")
        })
    }

    /// Check if requested variables are covered by granted variables
    fn variables_are_covered(&self, requested: &[String], granted: &[String]) -> bool {
        requested.iter().all(|req_var| {
            granted
                .iter()
                .any(|granted_var| req_var == granted_var || granted_var == "*")
        })
    }

    /// Check if requested capabilities are covered by granted capabilities
    fn capabilities_are_covered(
        &self,
        requested: &[SystemCapability],
        granted: &[SystemCapability],
    ) -> bool {
        requested.iter().all(|req_cap| granted.contains(req_cap))
    }

    /// Set the temporary directory for this plugin
    pub fn set_temp_dir(&mut self, temp_dir: PathBuf) {
        self.temp_dir = Some(temp_dir);
    }

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

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

    /// Get all granted permissions
    pub fn granted_permissions(&self) -> &HashSet<Permission> {
        &self.granted_permissions
    }
}

/// Security manager for handling plugin permissions
#[derive(Debug, Default)]
pub struct SecurityManager {
    plugin_permissions: HashMap<String, HashSet<Permission>>,
    global_restrictions: HashSet<Permission>,
}

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

    /// Grant permissions to a plugin
    pub fn grant_permissions(&mut self, plugin_name: &str, permissions: Vec<Permission>) {
        let permission_set: HashSet<Permission> = permissions.into_iter().collect();
        self.plugin_permissions
            .insert(plugin_name.to_string(), permission_set);
    }

    /// Check if a plugin has a specific permission
    pub fn check_permission(&self, plugin_name: &str, permission: &Permission) -> bool {
        // Check global restrictions first
        if self.global_restrictions.contains(permission) {
            return false;
        }

        // Check plugin-specific permissions
        if let Some(permissions) = self.plugin_permissions.get(plugin_name) {
            let context = SecurityContext::new(plugin_name.to_string(), permissions.clone());
            context.has_permission(permission)
        } else {
            false
        }
    }

    /// Create a security context for a plugin
    pub fn create_context(&self, plugin_name: &str) -> PluginResult<SecurityContext> {
        let permissions = self
            .plugin_permissions
            .get(plugin_name)
            .cloned()
            .unwrap_or_default();

        Ok(SecurityContext::new(plugin_name.to_string(), permissions))
    }

    /// Add global restrictions (permissions that no plugin can have)
    pub fn add_global_restriction(&mut self, permission: Permission) {
        self.global_restrictions.insert(permission);
    }

    /// Remove global restriction
    pub fn remove_global_restriction(&mut self, permission: &Permission) {
        self.global_restrictions.remove(permission);
    }

    /// Validate that a plugin's requested permissions are allowed
    pub fn validate_plugin_permissions(
        &self,
        plugin_name: &str,
        requested_permissions: &[Permission],
    ) -> PluginResult<()> {
        for permission in requested_permissions {
            if self.global_restrictions.contains(permission) {
                return Err(PluginError::PermissionDenied {
                    plugin: plugin_name.to_string(),
                    action: format!("Permission denied by global restriction: {permission:?}"),
                });
            }
        }
        Ok(())
    }

    /// Get all permissions granted to a plugin
    pub fn get_plugin_permissions(&self, plugin_name: &str) -> Vec<Permission> {
        self.plugin_permissions
            .get(plugin_name)
            .cloned()
            .unwrap_or_default()
            .into_iter()
            .collect()
    }

    /// Revoke all permissions from a plugin
    pub fn revoke_plugin_permissions(&mut self, plugin_name: &str) {
        self.plugin_permissions.remove(plugin_name);
    }

    /// Get all plugins with granted permissions
    pub fn get_plugins_with_permissions(&self) -> Vec<String> {
        self.plugin_permissions.keys().cloned().collect()
    }

    /// Create a sandbox for a plugin with its granted permissions
    pub fn create_sandbox(&self, plugin_name: &str) -> PluginResult<Sandbox> {
        let security_context = self.create_context(plugin_name)?;
        let config = SandboxConfig::default();

        Ok(Sandbox::new(
            plugin_name.to_string(),
            config,
            security_context,
        ))
    }

    /// Create a sandbox with custom configuration
    pub fn create_sandbox_with_config(
        &self,
        plugin_name: &str,
        config: SandboxConfig,
    ) -> PluginResult<Sandbox> {
        let security_context = self.create_context(plugin_name)?;

        Ok(Sandbox::new(
            plugin_name.to_string(),
            config,
            security_context,
        ))
    }
}

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

    #[test]
    fn test_permission_creation() {
        let fs_read = Permission::fs_read("/tmp");
        assert!(matches!(fs_read, Permission::FileSystem { .. }));

        let process = Permission::process(vec!["git".to_string()]);
        assert!(matches!(process, Permission::Process { .. }));

        let network = Permission::network(vec!["localhost".to_string()], vec![8080]);
        assert!(matches!(network, Permission::Network { .. }));
    }

    #[test]
    fn test_security_context_basic_permissions() {
        let mut permissions = HashSet::new();
        permissions.insert(Permission::fs_read("/tmp"));
        permissions.insert(Permission::TempDir);

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

        assert!(context.has_permission(&Permission::fs_read("/tmp")));
        assert!(context.has_permission(&Permission::TempDir));
        assert!(!context.has_permission(&Permission::fs_write("/tmp")));
    }

    #[test]
    fn test_security_context_broader_permissions() {
        let mut permissions = HashSet::new();
        permissions.insert(Permission::fs_read_write("/tmp"));

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

        // ReadWrite should cover both Read and Write
        assert!(context.has_permission(&Permission::fs_read("/tmp")));
        assert!(context.has_permission(&Permission::fs_write("/tmp")));
        assert!(context.has_permission(&Permission::fs_read_write("/tmp")));
    }

    #[test]
    fn test_security_context_path_hierarchy() {
        let mut permissions = HashSet::new();
        permissions.insert(Permission::fs_read("/tmp"));

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

        // Should have access to subdirectories
        assert!(context.has_permission(&Permission::fs_read("/tmp/subdir")));
        assert!(context.has_permission(&Permission::fs_read("/tmp/file.txt")));

        // Should not have access to parent directories
        assert!(!context.has_permission(&Permission::fs_read("/")));
        assert!(!context.has_permission(&Permission::fs_read("/home")));
    }

    #[test]
    fn test_security_manager_grant_and_check() {
        let mut manager = SecurityManager::new();

        let permissions = vec![
            Permission::fs_read("/tmp"),
            Permission::process(vec!["git".to_string()]),
        ];

        manager.grant_permissions("test-plugin", permissions);

        assert!(manager.check_permission("test-plugin", &Permission::fs_read("/tmp")));
        assert!(
            manager.check_permission("test-plugin", &Permission::process(vec!["git".to_string()]))
        );
        assert!(!manager.check_permission("test-plugin", &Permission::fs_write("/tmp")));
    }

    #[test]
    fn test_security_manager_global_restrictions() {
        let mut manager = SecurityManager::new();

        // Grant permission to plugin
        manager.grant_permissions("test-plugin", vec![Permission::fs_read("/etc")]);

        // Add global restriction
        manager.add_global_restriction(Permission::fs_read("/etc"));

        // Should be denied due to global restriction
        assert!(!manager.check_permission("test-plugin", &Permission::fs_read("/etc")));
    }

    #[test]
    fn test_security_manager_validation() {
        let mut manager = SecurityManager::new();
        manager.add_global_restriction(Permission::fs_read("/etc"));

        let result = manager.validate_plugin_permissions(
            "test-plugin",
            &[Permission::fs_read("/etc"), Permission::fs_read("/tmp")],
        );

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PluginError::PermissionDenied { .. }
        ));
    }

    #[test]
    fn test_security_context_network_wildcards() {
        let mut permissions = HashSet::new();
        permissions.insert(Permission::network(vec!["*".to_string()], vec![8080, 3000]));

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

        assert!(context.has_permission(&Permission::network(
            vec!["localhost".to_string()],
            vec![8080]
        )));
        assert!(context.has_permission(&Permission::network(
            vec!["example.com".to_string()],
            vec![3000]
        )));
        assert!(!context.has_permission(&Permission::network(
            vec!["localhost".to_string()],
            vec![9000]
        )));
    }

    #[test]
    fn test_security_context_process_wildcards() {
        let mut permissions = HashSet::new();
        permissions.insert(Permission::process(vec!["*".to_string()]));

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

        assert!(context.has_permission(&Permission::process(vec!["git".to_string()])));
        assert!(context.has_permission(&Permission::process(vec!["npm".to_string()])));
        assert!(context.has_permission(&Permission::process(vec!["any-command".to_string()])));
    }
}