sboxd 0.1.9

Policy-driven command runner for sandboxed dependency installation
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
use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use crate::cli::ShimCommand;
use crate::error::SboxError;

/// Package managers and runtimes that sbox knows how to intercept.
/// Install-time tools (npm, pip, ...) catch supply-chain attacks at the source.
/// Runtime tools (node, python3, go, ...) close the post-install artifact gap:
/// code planted in node_modules/.bin during install can't run unsandboxed if `node` is shimmed.
const SHIM_TARGETS: &[&str] = &[
    // package managers / installers
    "npm", "npx", "pnpm", "yarn", "bun", "uv", "pip", "pip3", "poetry", "cargo", "composer",
    "bundle",
    // runtimes — prevent post-install artifacts from running on the bare host
    "node", "python3", "python", "go", "ruby",
];

pub fn execute(command: &ShimCommand) -> Result<ExitCode, SboxError> {
    if command.verify {
        return execute_verify(command);
    }

    let shim_dir = resolve_shim_dir(command)?;

    if !command.dry_run {
        fs::create_dir_all(&shim_dir).map_err(|source| SboxError::InitWrite {
            path: shim_dir.clone(),
            source,
        })?;
    }

    let mut created = 0usize;
    let mut skipped = 0usize;

    for &name in SHIM_TARGETS {
        let dest = shim_file_path(&shim_dir, name);

        if dest.exists() && !command.force && !command.dry_run {
            println!(
                "skip   {} (already exists; use --force to overwrite)",
                dest.display()
            );
            skipped += 1;
            continue;
        }

        let real_binary = find_real_binary(name, &shim_dir);
        let script = render_shim(name, real_binary.as_deref());

        if command.dry_run {
            match &real_binary {
                Some(p) => println!("would create {} -> {}", dest.display(), p.display()),
                None => println!("would create {} (real binary not found)", dest.display()),
            }
            created += 1;
            continue;
        }

        fs::write(&dest, &script).map_err(|source| SboxError::InitWrite {
            path: dest.clone(),
            source,
        })?;

        set_executable(&dest).map_err(|source| SboxError::InitWrite {
            path: dest.clone(),
            source,
        })?;

        match &real_binary {
            Some(p) => println!("created {} -> {}", dest.display(), p.display()),
            None => println!(
                "created {} (real binary not found at shim time)",
                dest.display()
            ),
        }
        created += 1;
    }

    if !command.dry_run {
        println!();
        if created > 0 {
            println!(
                "Add {} to your PATH before the real package manager binaries:",
                shim_dir.display()
            );
            println!();
            #[cfg(windows)]
            println!("  set PATH={};%PATH%", shim_dir.display());
            #[cfg(not(windows))]
            println!("  export PATH=\"{}:$PATH\"", shim_dir.display());
            println!();
            #[cfg(not(windows))]
            println!("Then restart your shell or run: source ~/.bashrc");
            #[cfg(windows)]
            println!("Then restart your terminal.");
        }
        if skipped > 0 {
            println!("({skipped} skipped — use --force to overwrite)");
        }
    }

    Ok(ExitCode::SUCCESS)
}

/// Return the full path for a shim file, including platform-specific extension.
fn shim_file_path(dir: &Path, name: &str) -> PathBuf {
    #[cfg(windows)]
    {
        dir.join(format!("{name}.cmd"))
    }
    #[cfg(not(windows))]
    {
        dir.join(name)
    }
}

/// For each shim target, check whether:
/// 1. A shim file exists in the shim dir.
/// 2. The shim dir appears in PATH before the directory that contains the real binary.
///
/// Returns (ok_count, problem_count). Prints a line per target.
pub fn verify_shims(shim_dir: &Path) -> (usize, usize) {
    let mut ok = 0usize;
    let mut problems = 0usize;

    let path_os = std::env::var_os("PATH").unwrap_or_default();
    let path_dirs: Vec<std::path::PathBuf> = std::env::split_paths(&path_os).collect();

    // Index of the shim dir in PATH, if present.
    let shim_pos = path_dirs.iter().position(|d| d == shim_dir);

    for &name in SHIM_TARGETS {
        let shim_file = shim_file_path(shim_dir, name);

        if !shim_file.exists() {
            println!("missing  {name:<12}  shim not found at {}", shim_file.display());
            problems += 1;
            continue;
        }

        // Find the real binary position in PATH (skip the shim dir itself).
        let real_pos = path_dirs.iter().enumerate().find_map(|(i, dir)| {
            if dir == shim_dir {
                return None;
            }
            #[cfg(windows)]
            {
                for ext in &[".exe", ".cmd", ".bat"] {
                    if dir.join(format!("{name}{ext}")).is_file() {
                        return Some(i);
                    }
                }
                None
            }
            #[cfg(not(windows))]
            {
                let candidate = dir.join(name);
                if is_executable_file(&candidate) {
                    Some(i)
                } else {
                    None
                }
            }
        });

        match (shim_pos, real_pos) {
            (Some(sp), Some(rp)) if sp < rp => {
                println!("ok       {name:<12}  shim is active (PATH position {sp} < {rp})");
                ok += 1;
            }
            (Some(_sp), Some(rp)) => {
                println!(
                    "shadowed {name:<12}  real binary at PATH position {rp} comes before shim dir; \
                     move {} earlier in PATH",
                    shim_dir.display()
                );
                problems += 1;
            }
            (None, _) => {
                println!(
                    "inactive {name:<12}  shim exists but {} is not in PATH",
                    shim_dir.display()
                );
                problems += 1;
            }
            (Some(_), None) => {
                println!("ok       {name:<12}  shim active (no real binary found elsewhere in PATH)");
                ok += 1;
            }
        }
    }

    (ok, problems)
}

fn execute_verify(command: &ShimCommand) -> Result<ExitCode, SboxError> {
    let shim_dir = resolve_shim_dir(command)?;
    println!("shim dir: {}\n", shim_dir.display());

    let (ok, problems) = verify_shims(&shim_dir);

    println!();
    println!("{ok} ok, {problems} problem(s)");

    if problems > 0 {
        println!(
            "\nRun `sbox shim` to (re)create missing shims, then ensure {} is first in PATH.",
            shim_dir.display()
        );
        Ok(ExitCode::FAILURE)
    } else {
        Ok(ExitCode::SUCCESS)
    }
}

fn resolve_shim_dir(command: &ShimCommand) -> Result<PathBuf, SboxError> {
    if let Some(dir) = &command.dir {
        let abs = if dir.is_absolute() {
            dir.clone()
        } else {
            std::env::current_dir()
                .map_err(|source| SboxError::CurrentDirectory { source })?
                .join(dir)
        };
        return Ok(abs);
    }

    // Default: ~/.local/bin  (Unix) or %USERPROFILE%\.local\bin  (Windows)
    if let Some(home) = crate::platform::home_dir() {
        return Ok(home.join(".local").join("bin"));
    }

    // Last resort: use current directory
    std::env::current_dir().map_err(|source| SboxError::CurrentDirectory { source })
}

/// Search PATH for `name`, skipping `exclude_dir` to avoid resolving the shim itself.
fn find_real_binary(name: &str, exclude_dir: &Path) -> Option<PathBuf> {
    let path_os = std::env::var_os("PATH")?;
    for dir in std::env::split_paths(&path_os) {
        if dir == exclude_dir {
            continue;
        }
        // On Windows also search for name.exe / name.cmd / name.bat
        #[cfg(windows)]
        {
            for ext in &["", ".exe", ".cmd", ".bat"] {
                let candidate = dir.join(format!("{name}{ext}"));
                if candidate.is_file() {
                    return Some(candidate);
                }
            }
        }
        #[cfg(not(windows))]
        {
            let candidate = dir.join(name);
            if is_executable_file(&candidate) {
                return Some(candidate);
            }
        }
    }
    None
}

#[cfg(not(windows))]
fn is_executable_file(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    path.metadata()
        .map(|m| m.is_file() && (m.permissions().mode() & 0o111) != 0)
        .unwrap_or(false)
}

/// Make a file executable. On Unix sets the rwxr-xr-x permission bits.
/// On Windows files are executable by virtue of being writable; this is a no-op.
fn set_executable(path: &Path) -> std::io::Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(path)?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions(path, perms)?;
    }
    #[cfg(windows)]
    {
        let _ = path; // Windows: executable by extension (.cmd), nothing to set
    }
    Ok(())
}

/// Render a shim script for the given package manager name.
///
/// - Unix: POSIX `/bin/sh` script that walks up the directory tree looking for `sbox.yaml`.
/// - Windows: `.cmd` batch script with equivalent walk-up logic.
fn render_shim(name: &str, real_binary: Option<&Path>) -> String {
    #[cfg(not(windows))]
    return render_shim_posix(name, real_binary);

    #[cfg(windows)]
    return render_shim_cmd(name, real_binary);
}

/// POSIX shell shim (Unix / macOS / Linux).
#[cfg(not(windows))]
fn render_shim_posix(name: &str, real_binary: Option<&Path>) -> String {
    let fallback = match real_binary {
        Some(path) => format!(
            "printf 'sbox: no sbox.yaml found — running {name} unsandboxed\\n' >&2\nexec {path} \"$@\"",
            path = path.display()
        ),
        None => format!(
            "printf 'sbox shim: {name}: real binary not found; reinstall or run `sbox shim` again\\n' >&2\nexit 127"
        ),
    };

    // Note: the ${_sbox_d%/*} shell parameter expansion is written literally here.
    // It strips the last path component, walking up the directory tree.
    format!(
        "#!/bin/sh\n\
         # sbox shim: {name}\n\
         # Generated by `sbox shim`. Re-run `sbox shim --dir DIR` to regenerate.\n\
         _sbox_d=\"$PWD\"\n\
         while true; do\n\
         \x20 if [ -f \"$_sbox_d/sbox.yaml\" ]; then\n\
         \x20   exec sbox run -- {name} \"$@\"\n\
         \x20 fi\n\
         \x20 [ \"$_sbox_d\" = \"/\" ] && break\n\
         \x20 _sbox_d=\"${{_sbox_d%/*}}\"\n\
         \x20 [ -z \"$_sbox_d\" ] && _sbox_d=\"/\"\n\
         done\n\
         {fallback}\n"
    )
}

/// Windows CMD (.cmd) shim.
#[cfg(windows)]
fn render_shim_cmd(name: &str, real_binary: Option<&Path>) -> String {
    let fallback = match real_binary {
        Some(path) => format!(
            "echo sbox: no sbox.yaml found -- running {name} unsandboxed 1>&2\r\n\"{path}\" %*\r\nexit /b %ERRORLEVEL%",
            path = path.display()
        ),
        None => format!(
            "echo sbox shim: {name}: real binary not found; reinstall or run `sbox shim` again 1>&2\r\nexit /b 127"
        ),
    };

    format!(
        "@echo off\r\n\
         :: sbox shim: {name}\r\n\
         :: Generated by `sbox shim`. Re-run `sbox shim --dir DIR` to regenerate.\r\n\
         setlocal enabledelayedexpansion\r\n\
         set \"_sbox_d=%CD%\"\r\n\
         :_sbox_walk_{name}\r\n\
         if exist \"%_sbox_d%\\sbox.yaml\" (\r\n\
         \x20   sbox run -- {name} %*\r\n\
         \x20   exit /b %ERRORLEVEL%\r\n\
         )\r\n\
         for %%P in (\"%_sbox_d%\\..\") do set \"_sbox_parent=%%~fP\"\r\n\
         if \"!_sbox_parent!\"==\"!_sbox_d!\" goto _sbox_fallback_{name}\r\n\
         set \"_sbox_d=!_sbox_parent!\"\r\n\
         goto _sbox_walk_{name}\r\n\
         :_sbox_fallback_{name}\r\n\
         {fallback}\r\n"
    )
}


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

    #[test]
    fn shim_contains_sbox_run_delegation() {
        let script = render_shim("npm", Some(std::path::Path::new("/usr/bin/npm")));
        assert!(script.contains("sbox run -- npm"));
        assert!(script.contains("sbox.yaml"));
    }

    #[test]
    fn shim_fallback_when_real_binary_missing() {
        let script = render_shim("npm", None);
        assert!(script.contains("real binary not found"));
        #[cfg(not(windows))]
        assert!(script.contains("exit 127"));
        #[cfg(windows)]
        assert!(script.contains("exit /b 127"));
    }

    #[test]
    fn shim_walks_to_root() {
        let script = render_shim("uv", Some(std::path::Path::new("/usr/local/bin/uv")));
        #[cfg(not(windows))]
        {
            assert!(script.contains("_sbox_d%/*"));
            assert!(script.contains("[ \"$_sbox_d\" = \"/\" ] && break"));
        }
        #[cfg(windows)]
        {
            assert!(script.contains("_sbox_parent"));
            assert!(script.contains("goto _sbox_walk_uv"));
        }
    }

    /// Verify the generated .cmd script contains all the structural elements needed
    /// to walk up the directory tree and fall back to the real binary.
    #[cfg(windows)]
    #[test]
    fn cmd_shim_structure() {
        let script =
            render_shim("npm", Some(std::path::Path::new(r"C:\Program Files\nodejs\npm.cmd")));

        // Must be a batch file
        assert!(script.contains("@echo off"), "must suppress echo");

        // Must check for sbox.yaml and delegate
        assert!(script.contains("sbox.yaml"), "must check for sbox.yaml");
        assert!(script.contains("sbox run -- npm %*"), "must delegate to sbox run");

        // Walk-up logic: parent dir extraction and loop label
        assert!(
            script.contains("goto _sbox_walk_npm"),
            "must have a labelled walk loop"
        );
        assert!(
            script.contains("_sbox_parent"),
            "must compute parent directory"
        );

        // Fallback to the real binary when no sbox.yaml is found
        assert!(
            script.contains(r"C:\Program Files\nodejs\npm.cmd"),
            "must reference real binary path"
        );
    }

    #[cfg(windows)]
    #[test]
    fn cmd_shim_fallback_when_no_real_binary() {
        let script = render_shim("uv", None);
        assert!(script.contains("real binary not found"));
        assert!(script.contains("exit /b 127"));
    }
}