heel 0.1.1

Cross-platform native sandboxing library for running untrusted code
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
use std::any::TypeId;
use std::path::{Path, PathBuf};

use crate::error::{Error, Result};
use crate::ipc::IpcRouter;
use crate::network::{DenyAll, NetworkPolicy};
use crate::security::SecurityConfig;
use crate::workdir::WorkingDir;

/// Resource limits for sandboxed processes
#[derive(Debug, Clone, Default)]
pub struct ResourceLimits {
    max_memory_bytes: Option<u64>,
    max_cpu_time_secs: Option<u64>,
    max_file_size_bytes: Option<u64>,
    max_processes: Option<u32>,
}

impl ResourceLimits {
    /// Create a new builder for resource limits
    pub fn builder() -> ResourceLimitsBuilder {
        ResourceLimitsBuilder::default()
    }

    pub fn max_memory_bytes(&self) -> Option<u64> {
        self.max_memory_bytes
    }

    pub fn max_cpu_time_secs(&self) -> Option<u64> {
        self.max_cpu_time_secs
    }

    pub fn max_file_size_bytes(&self) -> Option<u64> {
        self.max_file_size_bytes
    }

    pub fn max_processes(&self) -> Option<u32> {
        self.max_processes
    }
}

/// Builder for ResourceLimits
#[derive(Debug, Default)]
pub struct ResourceLimitsBuilder {
    inner: ResourceLimits,
}

impl ResourceLimitsBuilder {
    pub fn max_memory_bytes(mut self, bytes: u64) -> Self {
        self.inner.max_memory_bytes = Some(bytes);
        self
    }

    pub fn max_cpu_time_secs(mut self, secs: u64) -> Self {
        self.inner.max_cpu_time_secs = Some(secs);
        self
    }

    pub fn max_file_size_bytes(mut self, bytes: u64) -> Self {
        self.inner.max_file_size_bytes = Some(bytes);
        self
    }

    pub fn max_processes(mut self, count: u32) -> Self {
        self.inner.max_processes = Some(count);
        self
    }

    pub fn build(self) -> ResourceLimits {
        self.inner
    }
}

/// Configuration for Python virtual environment
#[derive(Debug, Clone)]
pub struct VenvConfig {
    path: PathBuf,
    python: Option<PathBuf>,
    packages: Vec<String>,
    system_site_packages: bool,
    use_uv: bool,
}

impl Default for VenvConfig {
    fn default() -> Self {
        Self {
            path: PathBuf::from(".sandbox-venv"),
            python: None,
            packages: Vec::new(),
            system_site_packages: true,
            use_uv: true,
        }
    }
}

impl VenvConfig {
    /// Create a new builder for VenvConfig
    pub fn builder() -> VenvConfigBuilder {
        VenvConfigBuilder::default()
    }

    pub fn path(&self) -> &Path {
        &self.path
    }

    pub fn python(&self) -> Option<&Path> {
        self.python.as_deref()
    }

    pub fn packages(&self) -> &[String] {
        &self.packages
    }

    pub fn system_site_packages(&self) -> bool {
        self.system_site_packages
    }

    pub fn use_uv(&self) -> bool {
        self.use_uv
    }
}

/// Builder for VenvConfig
#[derive(Debug, Default)]
pub struct VenvConfigBuilder {
    inner: VenvConfig,
}

impl VenvConfigBuilder {
    pub fn path(mut self, path: impl AsRef<Path>) -> Self {
        self.inner.path = path.as_ref().to_path_buf();
        self
    }

    pub fn python(mut self, python: impl AsRef<Path>) -> Self {
        self.inner.python = Some(python.as_ref().to_path_buf());
        self
    }

    pub fn package(mut self, pkg: impl Into<String>) -> Self {
        self.inner.packages.push(pkg.into());
        self
    }

    pub fn packages(mut self, pkgs: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.inner.packages.extend(pkgs.into_iter().map(Into::into));
        self
    }

    pub fn system_site_packages(mut self, enabled: bool) -> Self {
        self.inner.system_site_packages = enabled;
        self
    }

    pub fn use_uv(mut self, enabled: bool) -> Self {
        self.inner.use_uv = enabled;
        self
    }

    pub fn build(self) -> VenvConfig {
        self.inner
    }
}

/// Python sandbox configuration
#[derive(Debug, Clone)]
pub struct PythonConfig {
    venv: VenvConfig,
    allow_pip_install: bool,
}

impl Default for PythonConfig {
    fn default() -> Self {
        Self {
            venv: VenvConfig::default(),
            allow_pip_install: true,
        }
    }
}

impl PythonConfig {
    /// Create a new builder for PythonConfig
    pub fn builder() -> PythonConfigBuilder {
        PythonConfigBuilder::default()
    }

    pub fn venv(&self) -> &VenvConfig {
        &self.venv
    }

    pub fn allow_pip_install(&self) -> bool {
        self.allow_pip_install
    }
}

/// Builder for PythonConfig
#[derive(Debug, Default)]
pub struct PythonConfigBuilder {
    inner: PythonConfig,
}

impl PythonConfigBuilder {
    pub fn venv(mut self, config: VenvConfig) -> Self {
        self.inner.venv = config;
        self
    }

    pub fn allow_pip_install(mut self, enabled: bool) -> Self {
        self.inner.allow_pip_install = enabled;
        self
    }

    pub fn build(self) -> PythonConfig {
        self.inner
    }
}

/// Sandbox configuration data (without network policy)
///
/// This is used internally after the network policy has been extracted
/// for the NetworkProxy.
pub struct SandboxConfigData {
    pub(crate) security: SecurityConfig,
    pub(crate) writable_paths: Vec<PathBuf>,
    pub(crate) readable_paths: Vec<PathBuf>,
    pub(crate) executable_paths: Vec<PathBuf>,
    pub(crate) network_deny_all: bool,
    pub(crate) python: Option<PythonConfig>,
    pub(crate) working_dir: PathBuf,
    pub(crate) working_dir_auto_created: bool,
    pub(crate) filesystem_strict: bool,
    pub(crate) writable_file_system: bool,
    pub(crate) env_passthrough: Vec<String>,
    pub(crate) limits: ResourceLimits,
    pub(crate) ipc: Option<IpcRouter>,
    /// Runtime IPC TCP port selected by the sandbox server.
    /// `None` means IPC is disabled.
    pub(crate) ipc_port: Option<u16>,
    /// Whether to allow writing to /dev/tty (controlling terminal).
    /// When false, all output must go through stdout/stderr pipes.
    pub(crate) allow_tty_write: bool,
}

impl SandboxConfigData {
    pub fn writable_file_system(&self) -> bool {
        self.writable_file_system
    }

    pub fn security(&self) -> &SecurityConfig {
        &self.security
    }

    pub fn writable_paths(&self) -> &[PathBuf] {
        &self.writable_paths
    }

    pub fn readable_paths(&self) -> &[PathBuf] {
        &self.readable_paths
    }

    pub fn executable_paths(&self) -> &[PathBuf] {
        &self.executable_paths
    }

    pub fn network_deny_all(&self) -> bool {
        self.network_deny_all
    }

    pub fn python(&self) -> Option<&PythonConfig> {
        self.python.as_ref()
    }

    pub fn working_dir(&self) -> &Path {
        &self.working_dir
    }

    pub fn filesystem_strict(&self) -> bool {
        self.filesystem_strict
    }

    pub fn env_passthrough(&self) -> &[String] {
        &self.env_passthrough
    }

    pub fn limits(&self) -> &ResourceLimits {
        &self.limits
    }

    pub fn ipc(&self) -> Option<&IpcRouter> {
        self.ipc.as_ref()
    }

    pub fn ipc_port(&self) -> Option<u16> {
        self.ipc_port
    }

    pub fn allow_tty_write(&self) -> bool {
        self.allow_tty_write
    }

    pub(crate) fn set_ipc_port(&mut self, port: Option<u16>) {
        self.ipc_port = port;
    }
}

/// Main sandbox configuration
pub struct SandboxConfig<N: NetworkPolicy = DenyAll> {
    network: N,
    security: SecurityConfig,
    writable_paths: Vec<PathBuf>,
    readable_paths: Vec<PathBuf>,
    executable_paths: Vec<PathBuf>,
    network_deny_all: bool,
    python: Option<PythonConfig>,
    working_dir: PathBuf,
    working_dir_auto_created: bool,
    filesystem_strict: bool,
    writable_file_system: bool,
    env_passthrough: Vec<String>,
    limits: ResourceLimits,
    ipc: Option<IpcRouter>,
    allow_tty_write: bool,
}

impl SandboxConfig<DenyAll> {
    /// Create a new SandboxConfig with default settings
    ///
    /// This creates a random working directory in the current directory
    /// using four English words connected by hyphens.
    pub fn new() -> Result<Self> {
        SandboxConfigBuilder::default().build()
    }

    /// Create a new builder for SandboxConfig
    pub fn builder() -> SandboxConfigBuilder<DenyAll> {
        SandboxConfigBuilder::default()
    }
}

impl<N: NetworkPolicy> SandboxConfig<N> {
    /// Consume the config and return the network policy and remaining config data
    ///
    /// This is used internally by Sandbox to extract the policy for the NetworkProxy.
    pub(crate) fn into_parts(self) -> (N, SandboxConfigData) {
        (
            self.network,
            SandboxConfigData {
                security: self.security,
                writable_paths: self.writable_paths,
                readable_paths: self.readable_paths,
                executable_paths: self.executable_paths,
                network_deny_all: self.network_deny_all,
                python: self.python,
                working_dir: self.working_dir,
                working_dir_auto_created: self.working_dir_auto_created,
                filesystem_strict: self.filesystem_strict,
                writable_file_system: self.writable_file_system,
                env_passthrough: self.env_passthrough,
                limits: self.limits,
                ipc: self.ipc,
                ipc_port: None,
                allow_tty_write: self.allow_tty_write,
            },
        )
    }

    pub fn writable_file_system(&self) -> bool {
        self.writable_file_system
    }

    pub fn network(&self) -> &N {
        &self.network
    }

    pub fn security(&self) -> &SecurityConfig {
        &self.security
    }

    pub fn writable_paths(&self) -> &[PathBuf] {
        &self.writable_paths
    }

    pub fn readable_paths(&self) -> &[PathBuf] {
        &self.readable_paths
    }

    pub fn executable_paths(&self) -> &[PathBuf] {
        &self.executable_paths
    }

    pub fn python(&self) -> Option<&PythonConfig> {
        self.python.as_ref()
    }

    pub fn working_dir(&self) -> &Path {
        &self.working_dir
    }

    pub fn filesystem_strict(&self) -> bool {
        self.filesystem_strict
    }

    pub fn env_passthrough(&self) -> &[String] {
        &self.env_passthrough
    }

    pub fn limits(&self) -> &ResourceLimits {
        &self.limits
    }

    pub fn ipc(&self) -> Option<&IpcRouter> {
        self.ipc.as_ref()
    }
}

/// Builder for SandboxConfig
pub struct SandboxConfigBuilder<N: NetworkPolicy = DenyAll> {
    network: N,
    security: SecurityConfig,
    writable_paths: Vec<PathBuf>,
    readable_paths: Vec<PathBuf>,
    executable_paths: Vec<PathBuf>,
    network_deny_all: bool,
    python: Option<PythonConfig>,
    working_dir: Option<PathBuf>,
    filesystem_strict: bool,
    writable_file_system: bool,
    env_passthrough: Vec<String>,
    limits: ResourceLimits,
    ipc: Option<IpcRouter>,
    allow_tty_write: bool,
}

impl Default for SandboxConfigBuilder<DenyAll> {
    fn default() -> Self {
        Self {
            network: DenyAll,
            security: SecurityConfig::default(),
            writable_paths: Vec::new(),
            readable_paths: Vec::new(),
            executable_paths: Vec::new(),
            network_deny_all: true,
            python: None,
            working_dir: None, // Will generate random name on build()
            filesystem_strict: true,
            writable_file_system: false,
            env_passthrough: Vec::new(),
            limits: ResourceLimits::default(),
            ipc: None,
            allow_tty_write: false, // Default: deny /dev/tty writes to capture all output
        }
    }
}

impl<N: NetworkPolicy> SandboxConfigBuilder<N> {
    /// Set the network policy (changes the generic type)
    pub fn network<M: NetworkPolicy>(self, policy: M) -> SandboxConfigBuilder<M> {
        SandboxConfigBuilder {
            network: policy,
            security: self.security,
            writable_paths: self.writable_paths,
            readable_paths: self.readable_paths,
            executable_paths: self.executable_paths,
            network_deny_all: TypeId::of::<M>() == TypeId::of::<DenyAll>(),
            python: self.python,
            working_dir: self.working_dir,
            filesystem_strict: self.filesystem_strict,
            writable_file_system: self.writable_file_system,
            env_passthrough: self.env_passthrough,
            limits: self.limits,
            ipc: self.ipc,
            allow_tty_write: self.allow_tty_write,
        }
    }

    /// Set the security configuration
    pub fn security(mut self, security: SecurityConfig) -> Self {
        self.security = security;
        self
    }

    pub fn writable_path(mut self, path: impl AsRef<Path>) -> Self {
        self.writable_paths.push(path.as_ref().to_path_buf());
        self
    }

    pub fn writable_paths(mut self, paths: impl IntoIterator<Item = impl AsRef<Path>>) -> Self {
        self.writable_paths
            .extend(paths.into_iter().map(|p| p.as_ref().to_path_buf()));
        self
    }

    pub fn readable_path(mut self, path: impl AsRef<Path>) -> Self {
        self.readable_paths.push(path.as_ref().to_path_buf());
        self
    }

    pub fn readable_paths(mut self, paths: impl IntoIterator<Item = impl AsRef<Path>>) -> Self {
        self.readable_paths
            .extend(paths.into_iter().map(|p| p.as_ref().to_path_buf()));
        self
    }

    pub fn executable_path(mut self, path: impl AsRef<Path>) -> Self {
        self.executable_paths.push(path.as_ref().to_path_buf());
        self
    }

    pub fn executable_paths(mut self, paths: impl IntoIterator<Item = impl AsRef<Path>>) -> Self {
        self.executable_paths
            .extend(paths.into_iter().map(|p| p.as_ref().to_path_buf()));
        self
    }

    pub fn python(mut self, config: PythonConfig) -> Self {
        self.python = Some(config);
        self
    }

    /// Enable strict filesystem mode (deny reads outside sandbox/allowlist).
    pub fn filesystem_strict(mut self, enabled: bool) -> Self {
        self.filesystem_strict = enabled;
        self
    }

    /// Enable globally writable filesystem
    pub fn writable_file_system(mut self, enabled: bool) -> Self {
        self.writable_file_system = enabled;
        self
    }

    /// Set the working directory path
    ///
    /// If not set, a random directory name will be generated in the current directory.
    /// The directory will be created if it doesn't exist.
    pub fn working_dir(mut self, path: impl AsRef<Path>) -> Self {
        self.working_dir = Some(path.as_ref().to_path_buf());
        self
    }

    pub fn env_passthrough(mut self, var: impl Into<String>) -> Self {
        self.env_passthrough.push(var.into());
        self
    }

    pub fn env_passthroughs(mut self, vars: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.env_passthrough
            .extend(vars.into_iter().map(Into::into));
        self
    }

    pub fn limits(mut self, limits: ResourceLimits) -> Self {
        self.limits = limits;
        self
    }

    /// Set the IPC router for handling commands from sandboxed processes
    pub fn ipc(mut self, router: IpcRouter) -> Self {
        self.ipc = Some(router);
        self
    }

    /// Allow writing to /dev/tty (controlling terminal)
    ///
    /// When false (default), sandboxed processes cannot write directly to the terminal,
    /// ensuring all output goes through captured stdout/stderr.
    /// Enable this for interactive sessions that need terminal access.
    pub fn allow_tty_write(mut self, enabled: bool) -> Self {
        self.allow_tty_write = enabled;
        self
    }

    pub fn build(self) -> Result<SandboxConfig<N>> {
        // Resolve working directory: use specified path or create random one
        let working_dir_auto_created = self.working_dir.is_none();
        let working_dir = match self.working_dir {
            Some(path) => {
                // User specified a path - create if needed
                if !path.exists() {
                    std::fs::create_dir_all(&path).map_err(|e| {
                        Error::IoError(format!(
                            "Failed to create working directory '{}': {}",
                            path.display(),
                            e
                        ))
                    })?;
                    tracing::debug!(path = %path.display(), "created working directory");
                }
                path
            }
            None => {
                // Generate random working directory
                let work_dir = WorkingDir::random()?;
                tracing::info!(path = %work_dir.path().display(), "created random working directory");
                work_dir.path().to_path_buf()
            }
        };

        Ok(SandboxConfig {
            network: self.network,
            security: self.security,
            writable_paths: self.writable_paths,
            readable_paths: self.readable_paths,
            executable_paths: self.executable_paths,
            network_deny_all: self.network_deny_all,
            python: self.python,
            working_dir,
            working_dir_auto_created,
            filesystem_strict: self.filesystem_strict,
            writable_file_system: self.writable_file_system,
            env_passthrough: self.env_passthrough,
            limits: self.limits,
            ipc: self.ipc,
            allow_tty_write: self.allow_tty_write,
        })
    }
}

/// Create a strict sandbox config with no network and minimal access
///
/// Strict mode denies filesystem reads outside the sandbox/allowlist.
pub fn strict_preset() -> Result<SandboxConfig<DenyAll>> {
    SandboxConfigBuilder::default()
        .filesystem_strict(true)
        .build()
}

/// Create a sandbox config for Python development with pip install capability
pub fn python_dev_preset() -> Result<SandboxConfig<DenyAll>> {
    SandboxConfigBuilder::default()
        .python(PythonConfig::builder().allow_pip_install(true).build())
        .build()
}

/// Create a sandbox config for Python data science with common tools
pub fn python_data_science_preset() -> Result<SandboxConfig<DenyAll>> {
    SandboxConfigBuilder::default()
        .python(
            PythonConfig::builder()
                .venv(
                    VenvConfig::builder()
                        .packages(["numpy", "pandas", "matplotlib", "scikit-learn"])
                        .system_site_packages(true)
                        .build(),
                )
                .allow_pip_install(true)
                .build(),
        )
        .executable_path("/usr/bin/ffmpeg")
        .executable_path("/usr/local/bin/ffmpeg")
        .readable_path("/usr/share")
        .build()
}