sandbox-command 0.1.0

An asynchronous `Command` like process launcher that uses `bwrap` or `sandbox-exec` for controlled sandbox process execution.
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
//! A command-builder replacement that launches children through the host OS sandbox.
//!
//! This crate intentionally stops at process creation. Callers decide whether
//! to wait, collect output, or stream the child's pipes themselves.

use std::{
    collections::{BTreeMap, BTreeSet},
    ffi::{OsStr, OsString},
    path::{Path, PathBuf},
    process::{ExitStatus, Output, Stdio},
    sync::{
        OnceLock,
        atomic::{AtomicUsize, Ordering},
    },
};
use thiserror::Error;
use tokio::{
    io::AsyncReadExt,
    process::{Child, ChildStderr, ChildStdin, ChildStdout, Command},
};

#[derive(Debug, Error)]
pub enum SandboxCommandError {
    #[error("sandbox initialization failed: {0}")]
    Initialization(String),
    #[error("sandbox command failed to start: {0}")]
    Spawn(#[source] std::io::Error),
    #[error("sandbox command path is invalid: {0}")]
    InvalidPath(String),
}

struct PreparedCommand {
    command: Command,
    cleanup: Option<PathBuf>,
}

/// A spawned sandboxed process.
///
/// This is intentionally a small child-process wrapper rather than a stream
/// abstraction. It exists so macOS sandbox profiles can remain on disk until
/// `sandbox-exec` has finished with them; callers still choose whether to
/// consume pipes, wait, or collect output.
pub struct SandboxChild {
    child: Child,
    pub stdin: Option<ChildStdin>,
    pub stdout: Option<ChildStdout>,
    pub stderr: Option<ChildStderr>,
    cleanup: Option<PathBuf>,
}

impl SandboxChild {
    pub fn id(&self) -> Option<u32> {
        self.child.id()
    }

    pub fn take_stdin(&mut self) -> Option<ChildStdin> {
        self.stdin.take()
    }

    pub fn take_stdout(&mut self) -> Option<ChildStdout> {
        self.stdout.take()
    }

    pub fn take_stderr(&mut self) -> Option<ChildStderr> {
        self.stderr.take()
    }

    pub async fn kill(&mut self) -> std::io::Result<()> {
        self.child.kill().await
    }

    pub fn start_kill(&mut self) -> std::io::Result<()> {
        self.child.start_kill()
    }

    pub async fn wait(&mut self) -> std::io::Result<ExitStatus> {
        let result = self.child.wait().await;
        if result.is_ok() {
            self.clean_up();
        }
        result
    }

    pub fn try_wait(&mut self) -> std::io::Result<Option<ExitStatus>> {
        let result = self.child.try_wait();
        if matches!(result, Ok(Some(_))) {
            self.clean_up();
        }
        result
    }

    pub async fn wait_with_output(mut self) -> std::io::Result<Output> {
        // Match Tokio's `Child::wait_with_output`: close the parent's stdin
        // handle so a child waiting for EOF cannot deadlock the collection.
        let _ = self.stdin.take();
        let mut stdout = self.stdout.take();
        let mut stderr = self.stderr.take();
        let stdout_read = async {
            let mut output = Vec::new();
            if let Some(stdout) = stdout.as_mut() {
                stdout.read_to_end(&mut output).await?;
            }
            Ok::<_, std::io::Error>(output)
        };
        let stderr_read = async {
            let mut output = Vec::new();
            if let Some(stderr) = stderr.as_mut() {
                stderr.read_to_end(&mut output).await?;
            }
            Ok::<_, std::io::Error>(output)
        };
        let (stdout, stderr) = tokio::try_join!(stdout_read, stderr_read)?;
        let status = self.wait().await?;
        Ok(Output {
            status,
            stdout,
            stderr,
        })
    }

    fn clean_up(&mut self) {
        remove_profile(self.cleanup.take());
    }
}

impl Drop for SandboxChild {
    fn drop(&mut self) {
        self.clean_up();
    }
}

/// A command builder with the familiar `Command` interface plus sandbox mount
/// controls. Output handling is deliberately left to the caller.
pub struct SandboxCommand {
    program: OsString,
    args: Vec<OsString>,
    env: BTreeMap<OsString, OsString>,
    removed_env: BTreeSet<OsString>,
    clear_env: bool,
    current_dir: Option<PathBuf>,
    stdin: Option<Stdio>,
    stdout: Option<Stdio>,
    stderr: Option<Stdio>,
    kill_on_drop: bool,
    rw_binds: Vec<PathBuf>,
    ro_binds: Vec<PathBuf>,
}

impl SandboxCommand {
    /// Verify that the platform sandbox is available. Call this during
    /// application startup; the result is cached for later commands.
    pub fn initialize() -> Result<(), SandboxCommandError> {
        platform().map(|_| ())
    }

    pub fn new(program: impl AsRef<OsStr>) -> Self {
        Self {
            program: program.as_ref().to_owned(),
            args: Vec::new(),
            env: BTreeMap::new(),
            removed_env: BTreeSet::new(),
            clear_env: false,
            current_dir: None,
            stdin: None,
            stdout: None,
            stderr: None,
            kill_on_drop: false,
            rw_binds: Vec::new(),
            ro_binds: Vec::new(),
        }
    }

    pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
        self.args.push(arg.as_ref().to_owned());
        self
    }

    pub fn args<I, S>(&mut self, args: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        self.args
            .extend(args.into_iter().map(|arg| arg.as_ref().to_owned()));
        self
    }

    pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Self {
        let key = key.as_ref().to_owned();
        self.removed_env.remove(&key);
        self.env.insert(key, value.as_ref().to_owned());
        self
    }

    pub fn envs<I, K, V>(&mut self, envs: I) -> &mut Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<OsStr>,
        V: AsRef<OsStr>,
    {
        for (key, value) in envs {
            self.env(key, value);
        }
        self
    }

    pub fn env_remove(&mut self, key: impl AsRef<OsStr>) -> &mut Self {
        let key = key.as_ref().to_owned();
        self.env.remove(&key);
        self.removed_env.insert(key);
        self
    }

    pub fn env_clear(&mut self) -> &mut Self {
        self.clear_env = true;
        self.env.clear();
        self.removed_env.clear();
        self
    }

    pub fn current_dir(&mut self, path: impl Into<PathBuf>) -> &mut Self {
        self.current_dir = Some(path.into());
        self
    }

    pub fn stdin(&mut self, cfg: Stdio) -> &mut Self {
        self.stdin = Some(cfg);
        self
    }

    pub fn stdout(&mut self, cfg: Stdio) -> &mut Self {
        self.stdout = Some(cfg);
        self
    }

    pub fn stderr(&mut self, cfg: Stdio) -> &mut Self {
        self.stderr = Some(cfg);
        self
    }

    pub fn kill_on_drop(&mut self, kill: bool) -> &mut Self {
        self.kill_on_drop = kill;
        self
    }

    /// Add a writable path at the same location inside the sandbox.
    pub fn bind_rw(&mut self, path: impl Into<PathBuf>) -> &mut Self {
        self.rw_binds.push(path.into());
        self
    }

    /// Add a read-only path at the same location inside the sandbox.
    pub fn bind_ro(&mut self, path: impl Into<PathBuf>) -> &mut Self {
        self.ro_binds.push(path.into());
        self
    }

    pub fn spawn(&mut self) -> Result<SandboxChild, SandboxCommandError> {
        let cwd = self
            .current_dir
            .clone()
            .unwrap_or(std::env::current_dir().map_err(SandboxCommandError::Spawn)?);
        let cwd = cwd.canonicalize().map_err(|error| {
            SandboxCommandError::InvalidPath(format!("{}: {error}", cwd.display()))
        })?;
        let PreparedCommand {
            mut command,
            cleanup,
        } = platform()?.command(self, &cwd)?;

        command.current_dir(&cwd).kill_on_drop(self.kill_on_drop);
        if let Some(stdin) = self.stdin.take() {
            command.stdin(stdin);
        }
        if let Some(stdout) = self.stdout.take() {
            command.stdout(stdout);
        }
        if let Some(stderr) = self.stderr.take() {
            command.stderr(stderr);
        }
        if self.clear_env {
            command.env_clear();
        }
        command.envs(&self.env);
        for key in &self.removed_env {
            command.env_remove(key);
        }

        let mut child = match command.spawn() {
            Ok(child) => child,
            Err(error) => {
                remove_profile(cleanup);
                return Err(SandboxCommandError::Spawn(error));
            }
        };
        Ok(SandboxChild {
            stdin: child.stdin.take(),
            stdout: child.stdout.take(),
            stderr: child.stderr.take(),
            child,
            cleanup,
        })
    }
}

fn remove_profile(path: Option<PathBuf>) {
    if let Some(path) = path {
        let _ = std::fs::remove_file(path);
    }
}

enum Platform {
    #[cfg(target_os = "linux")]
    Linux { bwrap: PathBuf },
    #[cfg(target_os = "macos")]
    Macos,
}

impl Platform {
    fn command(
        &self,
        command: &SandboxCommand,
        cwd: &Path,
    ) -> Result<PreparedCommand, SandboxCommandError> {
        match self {
            #[cfg(target_os = "linux")]
            Self::Linux { bwrap } => linux_command(bwrap, command, cwd),
            #[cfg(target_os = "macos")]
            Self::Macos => macos_command(command, cwd),
        }
    }
}

fn platform() -> Result<&'static Platform, SandboxCommandError> {
    static PLATFORM: OnceLock<Result<Platform, String>> = OnceLock::new();
    PLATFORM
        .get_or_init(|| detect_platform().map_err(|error| error.to_string()))
        .as_ref()
        .map_err(|error| SandboxCommandError::Initialization(error.clone()))
}

#[cfg(target_os = "linux")]
fn detect_platform() -> Result<Platform, SandboxCommandError> {
    let bwrap = find_program("bwrap").ok_or_else(|| {
        SandboxCommandError::Initialization(
            "required sandbox executable `bwrap` was not found".into(),
        )
    })?;
    Ok(Platform::Linux { bwrap })
}

#[cfg(target_os = "macos")]
fn detect_platform() -> Result<Platform, SandboxCommandError> {
    if !Path::new("/usr/bin/sandbox-exec").is_file() {
        return Err(SandboxCommandError::Initialization(
            "required sandbox executable `/usr/bin/sandbox-exec` was not found".into(),
        ));
    }
    Ok(Platform::Macos)
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn detect_platform() -> Result<Platform, SandboxCommandError> {
    Err(SandboxCommandError::Initialization(
        "sandbox-command supports only Linux and macOS".into(),
    ))
}

#[cfg(target_os = "linux")]
fn find_program(program: &str) -> Option<PathBuf> {
    std::env::var_os("PATH")?
        .split_paths()
        .map(|dir| dir.join(program))
        .find(|path| path.is_file())
}

#[cfg(target_os = "linux")]
fn linux_command(
    bwrap: &Path,
    command: &SandboxCommand,
    cwd: &Path,
) -> Result<PreparedCommand, SandboxCommandError> {
    let mut wrapped = Command::new(bwrap);
    let cwd = cwd.to_string_lossy();
    wrapped.args([
        "--bind",
        &cwd,
        &cwd,
        "--chdir",
        &cwd,
        "--ro-bind",
        "/usr",
        "/usr",
        "--symlink",
        "usr/lib",
        "/lib",
        "--symlink",
        "usr/bin",
        "/bin",
        "--symlink",
        "usr/sbin",
        "/sbin",
        "--proc",
        "/proc",
        "--dev",
        "/dev",
        "--dir",
        "/tmp",
        "--share-net",
        "--die-with-parent",
    ]);
    if Path::new("/etc/resolv.conf").exists() {
        wrapped.args(["--ro-bind", "/etc/resolv.conf", "/etc/resolv.conf"]);
    }
    if Path::new("/etc/alternatives").is_dir() {
        wrapped.args(["--ro-bind", "/etc/alternatives", "/etc/alternatives"]);
    }
    for path in &command.ro_binds {
        let path = path.to_string_lossy();
        wrapped.args(["--ro-bind", &path, &path]);
    }
    for path in &command.rw_binds {
        let path = path.to_string_lossy();
        wrapped.args(["--bind", &path, &path]);
    }
    wrapped.arg("--").arg(&command.program).args(&command.args);
    Ok(PreparedCommand {
        command: wrapped,
        cleanup: None,
    })
}

#[cfg(target_os = "macos")]
fn macos_command(
    command: &SandboxCommand,
    cwd: &Path,
) -> Result<PreparedCommand, SandboxCommandError> {
    static PROFILE_COUNTER: AtomicUsize = AtomicUsize::new(0);
    let profile_path = std::env::temp_dir().join(format!(
        "sandbox-command-{}-{}.sb",
        std::process::id(),
        PROFILE_COUNTER.fetch_add(1, Ordering::Relaxed)
    ));
    let profile = profile_for(cwd, &command.rw_binds);
    std::fs::write(&profile_path, profile).map_err(|error| {
        SandboxCommandError::Initialization(format!("cannot write sandbox profile: {error}"))
    })?;
    let mut wrapped = Command::new("/usr/bin/sandbox-exec");
    wrapped
        .arg("-f")
        .arg(profile_path.as_os_str())
        .arg(&command.program)
        .args(&command.args);
    Ok(PreparedCommand {
        command: wrapped,
        cleanup: Some(profile_path),
    })
}

#[cfg(target_os = "macos")]
fn profile_for(cwd: &Path, rw_binds: &[PathBuf]) -> String {
    let quote = |path: &Path| {
        format!(
            "\"{}\"",
            path.to_string_lossy()
                .replace('\\', "\\\\")
                .replace('"', "\\\"")
        )
    };
    let mut profile = format!(
        "(version 1)\n(deny default)\n(allow network*)\n(allow process-exec)\n(allow process-fork)\n(allow signal)\n(allow sysctl-read)\n(allow file-read-data file-read-metadata file-map-executable (subpath \"/\"))\n(allow file-write* (subpath \"/dev/null\"))\n(allow file-write* (subpath {}))\n(allow file-write* (subpath \"/private/tmp\"))\n(allow file-write* (subpath \"/tmp\"))\n(allow file-write* (subpath \"/var/folders\"))\n",
        quote(cwd)
    );
    for path in rw_binds {
        profile.push_str(&format!("(allow file-write* (subpath {}))\n", quote(path)));
    }
    profile
}

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

    #[tokio::test]
    async fn spawns_a_sandboxed_child() {
        let root = tempfile::tempdir().unwrap();
        let mut command = SandboxCommand::new("/usr/bin/printf");
        command
            .current_dir(root.path())
            .arg("hello")
            .stdout(Stdio::piped());
        let child = match command.spawn() {
            Ok(child) => child,
            Err(SandboxCommandError::Initialization(_)) => return,
            Err(error) => panic!("unexpected error: {error}"),
        };
        let output = child.wait_with_output().await.unwrap();
        if !output.status.success() && !cfg!(target_os = "macos") {
            return;
        }
        assert!(output.status.success());
        assert_eq!(output.stdout, b"hello");
    }
}