wasm-sandbox 0.4.1

A secure WebAssembly sandbox with dead-simple ease of use, progressive complexity APIs, and comprehensive safety controls
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
//! Manifest parsing and validation

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::fs;

use serde::{Deserialize, Serialize};
use crate::error::{Error, Result, SandboxError};
use crate::security::{
    Capabilities, NetworkCapability, FilesystemCapability, 
    EnvironmentCapability, ProcessCapability, PortRange, HostSpec
};
use crate::runtime::RuntimeConfig;

/// Sandbox manifest format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SandboxManifest {
    /// Name of the application
    pub name: String,
    
    /// Version of the application
    pub version: String,
    
    /// Description of the application
    pub description: Option<String>,
    
    /// Runtime configuration
    #[serde(default)]
    pub runtime: ManifestRuntime,
    
    /// Security capabilities
    #[serde(default)]
    pub capabilities: ManifestCapabilities,
    
    /// Resource limits
    #[serde(default)]
    pub resource_limits: ManifestResourceLimits,
}

/// Runtime configuration in manifest
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestRuntime {
    /// WebAssembly runtime engine
    pub engine: String,
    
    /// Whether to enable debugging
    #[serde(default)]
    pub debug: bool,
    
    /// Whether to cache compiled modules
    #[serde(default = "default_true")]
    pub cache_modules: bool,
    
    /// Number of compilation threads
    #[serde(default = "default_threads")]
    pub compilation_threads: usize,
}

fn default_true() -> bool {
    true
}

fn default_threads() -> usize {
    num_cpus::get()
}

impl Default for ManifestRuntime {
    fn default() -> Self {
        Self {
            engine: "wasmtime".to_string(),
            debug: false,
            cache_modules: true,
            compilation_threads: num_cpus::get(),
        }
    }
}

/// Network capabilities in manifest
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestNetworkCapabilities {
    /// Network mode
    #[serde(default)]
    pub mode: String,
    
    /// Allowed hosts
    #[serde(default)]
    pub allowed_hosts: Vec<String>,
    
    /// Allowed ports
    #[serde(default)]
    pub allowed_ports: Vec<String>,
}

impl Default for ManifestNetworkCapabilities {
    fn default() -> Self {
        Self {
            mode: "none".to_string(),
            allowed_hosts: Vec::new(),
            allowed_ports: Vec::new(),
        }
    }
}

/// Filesystem capabilities in manifest
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestFilesystemCapabilities {
    /// Readable directories
    #[serde(default)]
    pub readable_dirs: Vec<String>,
    
    /// Writable directories
    #[serde(default)]
    pub writable_dirs: Vec<String>,
    
    /// Whether to allow file creation
    #[serde(default)]
    pub allow_create: bool,
    
    /// Whether to allow file deletion
    #[serde(default)]
    pub allow_delete: bool,
    
    /// Maximum file size
    pub max_file_size: Option<String>,
}

impl Default for ManifestFilesystemCapabilities {
    fn default() -> Self {
        Self {
            readable_dirs: Vec::new(),
            writable_dirs: Vec::new(),
            allow_create: false,
            allow_delete: false,
            max_file_size: None,
        }
    }
}

/// Environment capabilities in manifest
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestEnvironmentCapabilities {
    /// Environment mode
    #[serde(default)]
    pub mode: String,
    
    /// Environment variables
    #[serde(default)]
    pub vars: Vec<String>,
}

impl Default for ManifestEnvironmentCapabilities {
    fn default() -> Self {
        Self {
            mode: "none".to_string(),
            vars: Vec::new(),
        }
    }
}

/// Process capabilities in manifest
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestProcessCapabilities {
    /// Whether to allow process execution
    #[serde(default)]
    pub allow_execution: bool,
    
    /// Allowed commands
    #[serde(default)]
    pub allowed_commands: Vec<String>,
}

impl Default for ManifestProcessCapabilities {
    fn default() -> Self {
        Self {
            allow_execution: false,
            allowed_commands: Vec::new(),
        }
    }
}

/// Capabilities in manifest
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestCapabilities {
    /// Network capabilities
    #[serde(default)]
    pub network: ManifestNetworkCapabilities,
    
    /// Filesystem capabilities
    #[serde(default)]
    pub filesystem: ManifestFilesystemCapabilities,
    
    /// Environment capabilities
    #[serde(default)]
    pub environment: ManifestEnvironmentCapabilities,
    
    /// Process capabilities
    #[serde(default)]
    pub process: ManifestProcessCapabilities,
    
    /// Time capabilities
    #[serde(default)]
    pub time_mode: String,
    
    /// Random number generator capabilities
    #[serde(default)]
    pub random_mode: String,
    
    /// Custom capabilities
    #[serde(default)]
    pub custom: HashMap<String, String>,
}

impl Default for ManifestCapabilities {
    fn default() -> Self {
        Self {
            network: ManifestNetworkCapabilities::default(),
            filesystem: ManifestFilesystemCapabilities::default(),
            environment: ManifestEnvironmentCapabilities::default(),
            process: ManifestProcessCapabilities::default(),
            time_mode: "readonly".to_string(),
            random_mode: "pseudo".to_string(),
            custom: HashMap::new(),
        }
    }
}

/// Memory limits in manifest
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestMemoryLimits {
    /// Maximum memory
    pub max_memory: Option<String>,
    
    /// Reserved memory
    pub reserved_memory: Option<String>,
}

impl Default for ManifestMemoryLimits {
    fn default() -> Self {
        Self {
            max_memory: Some("64MB".to_string()),
            reserved_memory: Some("16MB".to_string()),
        }
    }
}

/// CPU limits in manifest
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestCpuLimits {
    /// Maximum execution time
    pub max_execution_time: Option<String>,
    
    /// CPU usage percentage
    pub cpu_usage_percentage: Option<u8>,
    
    /// Maximum threads
    pub max_threads: Option<u32>,
}

impl Default for ManifestCpuLimits {
    fn default() -> Self {
        Self {
            max_execution_time: Some("10s".to_string()),
            cpu_usage_percentage: Some(50),
            max_threads: Some(1),
        }
    }
}

/// I/O limits in manifest
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestIoLimits {
    /// Maximum read bytes
    pub max_read_bytes: Option<String>,
    
    /// Maximum write bytes
    pub max_write_bytes: Option<String>,
    
    /// Maximum open files
    pub max_open_files: Option<u32>,
}

impl Default for ManifestIoLimits {
    fn default() -> Self {
        Self {
            max_read_bytes: Some("10MB".to_string()),
            max_write_bytes: Some("5MB".to_string()),
            max_open_files: Some(10),
        }
    }
}

/// Resource limits in manifest
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestResourceLimits {
    /// Memory limits
    #[serde(default)]
    pub memory: ManifestMemoryLimits,
    
    /// CPU limits
    #[serde(default)]
    pub cpu: ManifestCpuLimits,
    
    /// I/O limits
    #[serde(default)]
    pub io: ManifestIoLimits,
}

impl Default for ManifestResourceLimits {
    fn default() -> Self {
        Self {
            memory: ManifestMemoryLimits::default(),
            cpu: ManifestCpuLimits::default(),
            io: ManifestIoLimits::default(),
        }
    }
}

impl SandboxManifest {
    /// Load a manifest from a file
    pub fn from_path(path: &Path) -> Result<Self> {
        let content = fs::read_to_string(path)
            .map_err(|e| Error::Filesystem { 
                operation: "read_manifest".to_string(), 
                path: path.to_path_buf(),
                reason: e.to_string() 
            })?;
        
        Self::from_str(&content)
    }
    
    /// Load a manifest from a string
    pub fn from_str(content: &str) -> Result<Self> {
        // Try to parse as TOML first
        if let Ok(manifest) = toml::from_str::<SandboxManifest>(content) {
            return Ok(manifest);
        }
        
        // Try to parse as JSON
        serde_json::from_str::<SandboxManifest>(content)
            .map_err(|e| SandboxError::Configuration {
                message: format!("Failed to parse manifest: {}", e),
                suggestion: Some("Check manifest syntax - supports both TOML and JSON".to_string()),
                field: Some("manifest".to_string()),
            })
    }
    
    /// Convert to runtime configuration
    pub fn to_runtime_config(&self) -> RuntimeConfig {
        RuntimeConfig {
            enable_fuel: true,
            enable_memory_limits: true,
            native_stack_trace: self.runtime.debug,
            debug_info: self.runtime.debug,
            compilation_threads: self.runtime.compilation_threads,
            cache_modules: self.runtime.cache_modules,
            cache_directory: None,
        }
    }
    
    /// Convert to capabilities
    pub fn to_capabilities(&self) -> Result<Capabilities> {
        // Parse network capabilities
        let network = match self.capabilities.network.mode.as_str() {
            "none" => NetworkCapability::None,
            "loopback" => NetworkCapability::Loopback,
            "allowed_hosts" => {
                let mut hosts = Vec::new();
                for host_spec in &self.capabilities.network.allowed_hosts {
                    // Parse host spec (format: "hostname:port" or "hostname:port-range")
                    let parts: Vec<&str> = host_spec.split(':').collect();
                    if parts.len() != 2 {
                        return Err(SandboxError::config_error(format!("Invalid host spec: {}", host_spec), None));
                    }
                    
                    let host = parts[0].to_string();
                    let port_spec = parts[1];
                    
                    let ports = if port_spec.contains('-') {
                        let port_parts: Vec<&str> = port_spec.split('-').collect();
                        if port_parts.len() != 2 {
                            return Err(SandboxError::config_error(format!("Invalid port range: {}", port_spec), None));
                        }
                        
                        let start = port_parts[0].parse::<u16>()
                            .map_err(|_| SandboxError::config_error(format!("Invalid port: {}", port_parts[0]), None))?;
                        let end = port_parts[1].parse::<u16>()
                            .map_err(|_| SandboxError::config_error(format!("Invalid port: {}", port_parts[1]), None))?;
                        
                        Some(PortRange::new(start, end))
                    } else {
                        let port = port_spec.parse::<u16>()
                            .map_err(|_| SandboxError::config_error(format!("Invalid port: {}", port_spec), None))?;
                        
                        Some(PortRange::single(port))
                    };
                    
                    hosts.push(HostSpec {
                        host,
                        ports,
                        secure: true, // Allow secure connections by default
                    });
                }
                
                NetworkCapability::AllowedHosts(hosts)
            },
            "allowed_ports" => {
                let mut ports = Vec::new();
                for port_spec in &self.capabilities.network.allowed_ports {
                    if port_spec.contains('-') {
                        let port_parts: Vec<&str> = port_spec.split('-').collect();
                        if port_parts.len() != 2 {
                            return Err(SandboxError::config_error(format!("Invalid port range: {}", port_spec), None));
                        }
                        
                        let start = port_parts[0].parse::<u16>()
                            .map_err(|_| SandboxError::config_error(format!("Invalid port: {}", port_parts[0]), None))?;
                        let end = port_parts[1].parse::<u16>()
                            .map_err(|_| SandboxError::config_error(format!("Invalid port: {}", port_parts[1]), None))?;
                        
                        ports.push(PortRange::new(start, end));
                    } else {
                        let port = port_spec.parse::<u16>()
                            .map_err(|_| SandboxError::config_error(format!("Invalid port: {}", port_spec), None))?;
                        
                        ports.push(PortRange::single(port));
                    }
                }
                
                NetworkCapability::AllowedPorts(ports)
            },
            "full" => NetworkCapability::Full,
            _ => {
                return Err(SandboxError::config_error(format!("Invalid network mode: {}", self.capabilities.network.mode), None));
            }
        };
        
        // Parse filesystem capabilities
        let filesystem = FilesystemCapability {
            readable_dirs: self.capabilities.filesystem.readable_dirs.iter()
                .map(|s| PathBuf::from(s))
                .collect(),
            writable_dirs: self.capabilities.filesystem.writable_dirs.iter()
                .map(|s| PathBuf::from(s))
                .collect(),
            max_file_size: self.capabilities.filesystem.max_file_size.as_ref()
                .and_then(|s| parse_size(s).ok()),
            allow_create: self.capabilities.filesystem.allow_create,
            allow_delete: self.capabilities.filesystem.allow_delete,
        };
        
        // Parse environment capabilities
        let environment = match self.capabilities.environment.mode.as_str() {
            "none" => EnvironmentCapability::None,
            "allowlist" => EnvironmentCapability::Allowlist(
                self.capabilities.environment.vars.clone()
            ),
            "denylist" => EnvironmentCapability::Denylist(
                self.capabilities.environment.vars.clone()
            ),
            "full" => EnvironmentCapability::Full,
            _ => {
                return Err(SandboxError::config_error(format!("Invalid environment mode: {}", self.capabilities.environment.mode), None));
            }
        };
        
        // Parse process capabilities
        let process = if self.capabilities.process.allow_execution {
            if self.capabilities.process.allowed_commands.is_empty() {
                ProcessCapability::Full
            } else {
                ProcessCapability::AllowedCommands(
                    self.capabilities.process.allowed_commands.clone()
                )
            }
        } else {
            ProcessCapability::None
        };
        
        Ok(Capabilities {
            network,
            filesystem,
            environment,
            process,
            time: match self.capabilities.time_mode.as_str() {
                "readonly" => crate::security::TimeCapability::ReadOnly,
                "full" => crate::security::TimeCapability::Full,
                _ => crate::security::TimeCapability::ReadOnly,
            },
            random: match self.capabilities.random_mode.as_str() {
                "none" => crate::security::RandomCapability::None,
                "pseudo" => crate::security::RandomCapability::PseudoOnly,
                "full" => crate::security::RandomCapability::Full,
                _ => crate::security::RandomCapability::PseudoOnly,
            },
            custom: HashMap::new(), // Custom capabilities are not supported in the manifest yet
        })
    }
}

/// Parse a size string (e.g. "10MB") into bytes
fn parse_size(size: &str) -> Result<u64> {
    let size = size.trim();
    
    if size.is_empty() {
        return Err(SandboxError::config_error("Empty size string".to_string(), None));
    }
    
    let mut num_str = String::new();
    let mut suffix = String::new();
    
    for c in size.chars() {
        if c.is_digit(10) || c == '.' {
            num_str.push(c);
        } else {
            suffix.push(c);
        }
    }
    
    if num_str.is_empty() {
        return Err(SandboxError::config_error(format!("Invalid size format: {}", size), None));
    }
    
    let num: f64 = num_str.parse()
        .map_err(|_| SandboxError::config_error(format!("Invalid number: {}", num_str), None))?;
    
    let multiplier = match suffix.trim().to_uppercase().as_str() {
        "" | "B" => 1,
        "K" | "KB" => 1024,
        "M" | "MB" => 1024 * 1024,
        "G" | "GB" => 1024 * 1024 * 1024,
        _ => return Err(SandboxError::config_error(format!("Invalid size suffix: {}", suffix), None)),
    };
    
    Ok((num * multiplier as f64) as u64)
}