cert-x-gen 1.9.2

Advanced Multi-Language Security Scanning Engine
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
# Sandbox Module

## Overview

The sandbox module provides per-language **dependency environments** for all supported programming languages in CERT-X-GEN — a separate package directory per runtime, for reproducibility and to keep template dependencies off the system package managers.

It is not a security boundary. Templates execute as ordinary child processes with the invoking user's privileges and full network and filesystem access. Review templates before running them. See [Security](#security) below.

## Architecture

### Core Components

```
sandbox/
├── mod.rs           # Sandbox manager and configuration
├── python.rs        # Python virtual environment
├── javascript.rs    # Node.js npm environment
├── ruby.rs          # Ruby gems environment
├── perl.rs          # Perl local::lib environment
├── php.rs           # PHP composer environment
├── rust.rs          # Rust cargo environment
├── go.rs            # Go modules environment
└── java.rs          # Java classpath environment
```

### Key Types

#### `Sandbox`
Main sandbox manager that coordinates all language environments.

```rust
pub struct Sandbox {
    config: SandboxConfig,
    initialized: bool,
}
```

#### `SandboxConfig`
Configuration for sandbox behavior and enabled languages.

```rust
pub struct SandboxConfig {
    pub root_dir: PathBuf,
    pub enable_python: bool,
    pub enable_javascript: bool,
    pub enable_ruby: bool,
    pub enable_perl: bool,
    pub enable_php: bool,
    pub enable_rust: bool,
    pub enable_go: bool,
    pub enable_java: bool,
    pub auto_init: bool,
}
```

#### `SandboxStatus`
Current status of the sandbox and all language runtimes.

```rust
pub struct SandboxStatus {
    pub initialized: bool,
    pub root_dir: PathBuf,
    pub python_ready: bool,
    pub javascript_ready: bool,
    // ... other languages
}
```

## Usage

### Basic Initialization

```rust
use cert_x_gen::sandbox::Sandbox;

// Create with default config
let mut sandbox = Sandbox::new();

// Initialize all languages
sandbox.init().await?;

// Check status
let status = sandbox.status();
println!("Ready languages: {:?}", status.ready_languages());
```

### Custom Configuration

```rust
use cert_x_gen::sandbox::{Sandbox, SandboxConfig};

let mut config = SandboxConfig::default();
config.enable_python = true;
config.enable_javascript = true;
config.enable_ruby = false; // Disable Ruby

let mut sandbox = Sandbox::with_config(config);
sandbox.init().await?;
```

### Installing Packages

```rust
use cert_x_gen::sandbox::{Sandbox, python};

let sandbox = Sandbox::new();

// Install Python packages
python::install_packages(&sandbox, &[
    "requests",
    "beautifulsoup4",
    "selenium",
]).await?;
```

### Executing Scripts

```rust
use cert_x_gen::sandbox::{Sandbox, python};
use std::path::Path;

let sandbox = Sandbox::new();

// Execute Python script in sandbox
let output = python::execute_script(
    &sandbox,
    Path::new("template.py"),
    &["arg1", "arg2"],
).await?;

println!("Output: {}", String::from_utf8_lossy(&output.stdout));
```

## Language-Specific APIs

### Python

```rust
// Initialize environment
python::init_environment(&sandbox).await?;

// Install packages
python::install_packages(&sandbox, &["requests", "beautifulsoup4"]).await?;

// Get Python executable path
let python_path = python::get_python_path(&sandbox);

// Execute script
let output = python::execute_script(&sandbox, script_path, args).await?;
```

### JavaScript/Node.js

```rust
// Initialize environment
javascript::init_environment(&sandbox).await?;

// Install packages
javascript::install_packages(&sandbox, &["axios", "cheerio"]).await?;

// Execute script
let output = javascript::execute_script(&sandbox, script_path, args).await?;
```

### Ruby

```rust
// Initialize environment
ruby::init_environment(&sandbox).await?;

// Install gems
ruby::install_gems(&sandbox, &["nokogiri", "rest-client"]).await?;

// Execute script
let output = ruby::execute_script(&sandbox, script_path, args).await?;
```

### Perl

```rust
// Initialize environment
perl::init_environment(&sandbox).await?;

// Install modules
perl::install_modules(&sandbox, &["LWP::UserAgent", "JSON"]).await?;

// Execute script
let output = perl::execute_script(&sandbox, script_path, args).await?;
```

### PHP

```rust
// Initialize environment
php::init_environment(&sandbox).await?;

// Install packages
php::install_packages(&sandbox, &["guzzlehttp/guzzle"]).await?;

// Execute script
let output = php::execute_script(&sandbox, script_path, args).await?;
```

### Rust

```rust
// Initialize environment
rust::init_environment(&sandbox).await?;

// Compile and execute
let output = rust::compile_and_execute(&sandbox, source_path, args).await?;
```

### Go

```rust
// Initialize environment
go::init_environment(&sandbox).await?;

// Compile and execute
let output = go::compile_and_execute(&sandbox, source_path, args).await?;
```

### Java

```rust
// Initialize environment
java::init_environment(&sandbox).await?;

// Compile and execute
let output = java::compile_and_execute(&sandbox, source_path, args).await?;
```

## Environment Variables

The sandbox sets language-specific environment variables:

| Language | Variable | Purpose |
|----------|----------|---------|
| Python | `VIRTUAL_ENV` | Virtual environment path |
| Python | `PYTHONUSERBASE` | User packages path |
| JavaScript | `NODE_PATH` | Node modules path |
| Ruby | `GEM_HOME` | Gems installation path |
| Perl | `PERL_LOCAL_LIB_ROOT` | Local lib path |
| PHP | `PHP_USER_INI` | PHP config path |
| Rust | `CARGO_TARGET_DIR` | Cargo build path |
| Go | `GOPATH` | Go workspace path |
| Java | `JAVA_HOME` | Java installation path |

Access environment variables:

```rust
let env_vars = sandbox.get_env_vars();
for (key, value) in env_vars {
    println!("{} = {}", key, value);
}
```

## Error Handling

All sandbox operations return `Result<T>` with appropriate error types:

```rust
use cert_x_gen::error::{Error, Result};

match sandbox.init().await {
    Ok(_) => println!("Sandbox initialized"),
    Err(Error::Config(msg)) => eprintln!("Config error: {}", msg),
    Err(Error::Command(msg)) => eprintln!("Command error: {}", msg),
    Err(e) => eprintln!("Error: {}", e),
}
```

## Testing

### Unit Tests

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

    #[tokio::test]
    async fn test_sandbox_init() {
        let mut sandbox = Sandbox::new();
        assert!(sandbox.init().await.is_ok());
        assert!(sandbox.is_initialized());
    }

    #[tokio::test]
    async fn test_python_packages() {
        let sandbox = Sandbox::new();
        let result = python::install_packages(&sandbox, &["requests"]).await;
        assert!(result.is_ok());
    }
}
```

### Integration Tests

```rust
#[tokio::test]
async fn test_full_workflow() {
    // Initialize sandbox
    let mut sandbox = Sandbox::new();
    sandbox.init().await.unwrap();

    // Install packages
    python::install_packages(&sandbox, &["requests"]).await.unwrap();

    // Execute script
    let script = r#"
import requests
print("Success!")
"#;
    
    let script_path = Path::new("/tmp/test_script.py");
    std::fs::write(script_path, script).unwrap();
    
    let output = python::execute_script(&sandbox, script_path, &[]).await.unwrap();
    assert!(output.status.success());
}
```

## Best Practices

### 1. Initialize Once

Initialize the sandbox once at startup:

```rust
// At application startup
let mut sandbox = Sandbox::new();
sandbox.init().await?;

// Reuse sandbox throughout application lifetime
```

### 2. Handle Missing Runtimes

Language runtimes may not be installed:

```rust
if let Err(e) = python::init_environment(&sandbox).await {
    tracing::warn!("Python not available: {}", e);
    // Continue without Python support
}
```

### 3. Cleanup

Clean up sandbox when no longer needed:

```rust
sandbox.clean()?;
```

### 4. Status Checks

Check sandbox status before use:

```rust
if !sandbox.is_initialized() {
    sandbox.init().await?;
}

let status = sandbox.status();
if status.python_ready {
    // Use Python
}
```

## Performance Considerations

### Initialization

- **First time**: 2-5 minutes (downloads packages)
- **Subsequent**: Instant (already initialized)

### Package Installation

- **Cache**: Packages are cached in sandbox
- **Network**: Only downloads when needed
- **Parallel**: Install multiple languages in parallel

### Script Execution

- **Overhead**: ~10ms per execution
- **No caching**: Scripts execute each time

## Security

### This module confines nothing

**Templates execute as ordinary child processes with the invoking user's privileges and full network and filesystem access. Review templates before running them.**

What this module separates is *packages*, not privileges:

- ✅ **Package separation**: Separate dependency directories per language
- ✅ **Environment variables**: Per-language `VIRTUAL_ENV`, `GEM_HOME`, `GOPATH`, …
- ❌ **Privileges**: Child processes inherit the invoking user's, unrestricted
- ❌ **Network access**: Not restricted
- ❌ **File system**: Full host file system access
- ❌ **CPU / memory**: Not limited

### Recommendations

All confinement must come from outside cxg:

1. **Use containers or VMs** for actual isolation
2. **Run as unprivileged user**
3. **Apply resource limits** (cgroups — cxg applies none of its own)
4. **Restrict network access** (firewall / network namespaces)
5. **Monitor execution** (logging)

## Troubleshooting

### Sandbox Not Initialized

```rust
if !sandbox.is_initialized() {
    sandbox.init().await?;
}
```

### Package Installation Failed

```rust
match python::install_packages(&sandbox, &["requests"]).await {
    Ok(_) => println!("Installed"),
    Err(e) => {
        eprintln!("Failed to install: {}", e);
        // Retry or use alternative package
    }
}
```

### Runtime Not Found

```rust
// Check if runtime is available before initializing
let has_python = Command::new("python3")
    .arg("--version")
    .output()
    .is_ok();

if has_python {
    python::init_environment(&sandbox).await?;
}
```

## Future Enhancements

- [ ] Binary caching for compiled languages
- [ ] Parallel package installation
- [ ] Package version locking
- [ ] Sandbox snapshots/restore
- [ ] Container integration
- [ ] WebAssembly runtime
- [ ] Lua scripting engine

## Related Modules

- `engine` - Template execution engines
- `executor` - Job execution coordinator
- `template` - Template interface
- `types` - Core types

## External Dependencies

- `tokio` - Async runtime
- `serde` - Serialization
- `serde_yaml` - YAML configuration
- `dirs` - User directories
- `tracing` - Logging

## Documentation

- [Manage template dependency environments]https://docs.bugb.io/cxg/guides/manage-dependency-environments/