sboxd 0.1.4

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
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
use std::fs;
use std::path::PathBuf;
use std::process::ExitCode;

use dialoguer::{Confirm, Input, Select, theme::ColorfulTheme};

use crate::cli::{Cli, InitCommand};
use crate::error::SboxError;

pub fn execute(cli: &Cli, command: &InitCommand) -> Result<ExitCode, SboxError> {
    if command.interactive {
        return execute_interactive(cli, command);
    }

    let target = resolve_output_path(cli, command)?;
    if target.exists() && !command.force {
        return Err(SboxError::InitConfigExists { path: target });
    }

    if let Some(parent) = target.parent() {
        fs::create_dir_all(parent).map_err(|source| SboxError::InitWrite {
            path: target.clone(),
            source,
        })?;
    }

    let preset = command.preset.as_deref().unwrap_or("generic");
    let template = render_template(preset)?;
    fs::write(&target, template).map_err(|source| SboxError::InitWrite {
        path: target.clone(),
        source,
    })?;

    println!("created {}", target.display());
    Ok(ExitCode::SUCCESS)
}

// ── Interactive wizard ────────────────────────────────────────────────────────

fn execute_interactive(cli: &Cli, command: &InitCommand) -> Result<ExitCode, SboxError> {
    let target = resolve_output_path(cli, command)?;
    if target.exists() && !command.force {
        return Err(SboxError::InitConfigExists { path: target });
    }

    let theme = ColorfulTheme::default();
    println!("sbox interactive setup");
    println!("──────────────────────");
    println!("Use arrow keys to select, Enter to confirm.\n");

    // ── Simple vs Advanced ────────────────────────────────────────────────────
    let mode_idx = Select::with_theme(&theme)
        .with_prompt("Setup mode")
        .items(&[
            "simple   — package_manager preset (recommended)",
            "advanced — manual profiles and dispatch rules",
        ])
        .default(0)
        .interact()
        .map_err(|_| SboxError::CurrentDirectory {
            source: std::io::Error::other("prompt cancelled"),
        })?;

    let config = if mode_idx == 0 {
        execute_interactive_simple(&theme)?
    } else {
        execute_interactive_advanced(&theme)?
    };

    // ── Write ─────────────────────────────────────────────────────────────────
    if let Some(parent) = target.parent() {
        fs::create_dir_all(parent).map_err(|source| SboxError::InitWrite {
            path: target.clone(),
            source,
        })?;
    }
    fs::write(&target, &config).map_err(|source| SboxError::InitWrite {
        path: target.clone(),
        source,
    })?;

    println!("\ncreated {}", target.display());
    println!("Run `sbox plan -- <command>` to preview the resolved policy.");
    Ok(ExitCode::SUCCESS)
}

fn execute_interactive_simple(theme: &ColorfulTheme) -> Result<String, SboxError> {
    // ── Package manager ───────────────────────────────────────────────────────
    let pm_idx = Select::with_theme(theme)
        .with_prompt("Package manager")
        .items(&["npm", "yarn", "pnpm", "bun", "uv", "pip", "poetry", "cargo", "go"])
        .default(0)
        .interact()
        .map_err(|_| SboxError::CurrentDirectory {
            source: std::io::Error::other("prompt cancelled"),
        })?;
    let (pm_name, default_image) = [
        ("npm",    "node:22-bookworm-slim"),
        ("yarn",   "node:22-bookworm-slim"),
        ("pnpm",   "node:22-bookworm-slim"),
        ("bun",    "oven/bun:latest"),
        ("uv",     "python:3.13-slim"),
        ("pip",    "python:3.13-slim"),
        ("poetry", "python:3.13-slim"),
        ("cargo",  "rust:1-bookworm"),
        ("go",     "golang:1.23-bookworm"),
    ][pm_idx];

    // ── Image ─────────────────────────────────────────────────────────────────
    let image: String = Input::with_theme(theme)
        .with_prompt("Container image")
        .default(default_image.to_string())
        .interact_text()
        .map_err(|_| SboxError::CurrentDirectory {
            source: std::io::Error::other("prompt cancelled"),
        })?;

    // ── Backend ───────────────────────────────────────────────────────────────
    let backend_idx = Select::with_theme(theme)
        .with_prompt("Container backend")
        .items(&["auto (detect podman or docker)", "podman", "docker"])
        .default(0)
        .interact()
        .map_err(|_| SboxError::CurrentDirectory {
            source: std::io::Error::other("prompt cancelled"),
        })?;
    let runtime_block = match backend_idx {
        1 => "runtime:\n  backend: podman\n  rootless: true\n",
        2 => "runtime:\n  backend: docker\n  rootless: false\n",
        _ => "",
    };

    let exclude_paths = default_exclude_paths(pm_name);

    Ok(format!(
        "version: 1\n\
         \n\
         {runtime_block}\
         \n\
         workspace:\n\
           mount: /workspace\n\
           writable: false\n\
           exclude_paths:\n\
         {exclude_paths}\
         \n\
         image:\n\
           ref: {image}\n\
         \n\
         environment:\n\
           pass_through:\n\
             - TERM\n\
         \n\
         package_manager:\n\
           name: {pm_name}\n"
    ))
}

fn default_exclude_paths(pm_name: &str) -> String {
    let common = vec![
        "    - \".ssh/*\"",
        "    - \".aws/*\"",
    ];
    let extras: &[&str] = match pm_name {
        "npm" | "yarn" | "pnpm" | "bun" => &[
            "    - .env",
            "    - .env.local",
            "    - .env.production",
            "    - .env.development",
            "    - .npmrc",
            "    - .netrc",
        ],
        "uv" | "pip" | "poetry" => &[
            "    - .env",
            "    - .env.local",
            "    - .netrc",
        ],
        _ => &[],
    };

    let mut lines: Vec<&str> = extras.to_vec();
    lines.extend_from_slice(&common);
    lines.join("\n") + "\n"
}

fn execute_interactive_advanced(theme: &ColorfulTheme) -> Result<String, SboxError> {
    // ── Backend ───────────────────────────────────────────────────────────────
    let backend_idx = Select::with_theme(theme)
        .with_prompt("Container backend")
        .items(&["auto (detect podman or docker)", "podman", "docker"])
        .default(0)
        .interact()
        .map_err(|_| SboxError::CurrentDirectory {
            source: std::io::Error::other("prompt cancelled"),
        })?;
    let (backend_line, rootless_line) = match backend_idx {
        1 => ("  backend: podman", "  rootless: true"),
        2 => ("  backend: docker", "  rootless: false"),
        _ => ("  # backend: auto-detected", "  rootless: true"),
    };

    // ── Preset / image ────────────────────────────────────────────────────────
    let preset_idx = Select::with_theme(theme)
        .with_prompt("Language / ecosystem")
        .items(&["node", "python", "rust", "go", "generic", "custom image"])
        .default(0)
        .interact()
        .map_err(|_| SboxError::CurrentDirectory {
            source: std::io::Error::other("prompt cancelled"),
        })?;

    let preset = ["node", "python", "rust", "go", "generic", "custom"][preset_idx];

    let (default_image, default_writable_paths, default_dispatch) = match preset {
        "node"   => ("node:22-bookworm-slim", vec!["node_modules", "package-lock.json", "dist"], node_dispatch()),
        "python" => ("python:3.13-slim",       vec![".venv"],                                   python_dispatch()),
        "rust"   => ("rust:1-bookworm",         vec!["target"],                                  rust_dispatch()),
        "go"     => ("golang:1.23-bookworm",    vec![],                                          go_dispatch()),
        _        => ("ubuntu:24.04",            vec![],                                          String::new()),
    };

    let image: String = Input::with_theme(theme)
        .with_prompt("Container image")
        .default(default_image.to_string())
        .interact_text()
        .map_err(|_| SboxError::CurrentDirectory {
            source: std::io::Error::other("prompt cancelled"),
        })?;

    // ── Network ───────────────────────────────────────────────────────────────
    let network_idx = Select::with_theme(theme)
        .with_prompt("Default network access in sandbox")
        .items(&[
            "off  — no internet (recommended for installs)",
            "on   — full internet access",
        ])
        .default(0)
        .interact()
        .map_err(|_| SboxError::CurrentDirectory {
            source: std::io::Error::other("prompt cancelled"),
        })?;
    let network = if network_idx == 0 { "off" } else { "on" };

    // ── Workspace writable paths ──────────────────────────────────────────────
    let default_wp = default_writable_paths.join(", ");
    let wp_input: String = Input::with_theme(theme)
        .with_prompt("Writable paths in workspace (comma-separated)")
        .default(default_wp)
        .allow_empty(true)
        .interact_text()
        .map_err(|_| SboxError::CurrentDirectory {
            source: std::io::Error::other("prompt cancelled"),
        })?;
    let writable_paths: Vec<String> = wp_input
        .split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();

    // ── Dispatch rules ────────────────────────────────────────────────────────
    let add_dispatch = if !default_dispatch.is_empty() {
        Confirm::with_theme(theme)
            .with_prompt(format!("Add default dispatch rules for {preset}?"))
            .default(true)
            .interact()
            .map_err(|_| SboxError::CurrentDirectory {
                source: std::io::Error::other("prompt cancelled"),
            })?
    } else {
        false
    };

    // ── Render ────────────────────────────────────────────────────────────────
    let writable_paths_yaml = if writable_paths.is_empty() {
        "    []".to_string()
    } else {
        writable_paths
            .iter()
            .map(|p| format!("    - {p}"))
            .collect::<Vec<_>>()
            .join("\n")
    };

    let workspace_writable = writable_paths.is_empty();
    let dispatch_section = if add_dispatch {
        format!("dispatch:\n{default_dispatch}")
    } else {
        "dispatch: {}".to_string()
    };

    Ok(format!("version: 1

runtime:
{backend_line}
{rootless_line}

workspace:
  root: .
  mount: /workspace
  writable: {workspace_writable}
  writable_paths:
{writable_paths_yaml}
  exclude_paths:
    - .env
    - .env.local
    - .env.production
    - .env.development
    - \"*.pem\"
    - \"*.key\"
    - .npmrc
    - .netrc
    - \".ssh/*\"
    - \".aws/*\"

image:
  ref: {image}

environment:
  pass_through:
    - TERM
  set: {{}}
  deny: []

profiles:
  default:
    mode: sandbox
    network: {network}
    writable: true
    no_new_privileges: true

{dispatch_section}
"))
}

// ── Default dispatch rules per preset (advanced mode) ────────────────────────

fn node_dispatch() -> String {
    "  npm-install:\n    match:\n      - \"npm install*\"\n      - \"npm ci\"\n    profile: default\n  \
     yarn-install:\n    match:\n      - \"yarn install*\"\n    profile: default\n  \
     pnpm-install:\n    match:\n      - \"pnpm install*\"\n    profile: default\n"
        .to_string()
}

fn python_dispatch() -> String {
    "  pip-install:\n    match:\n      - \"pip install*\"\n      - \"pip3 install*\"\n    profile: default\n  \
     uv-sync:\n    match:\n      - \"uv sync*\"\n    profile: default\n  \
     poetry-install:\n    match:\n      - \"poetry install*\"\n    profile: default\n"
        .to_string()
}

fn rust_dispatch() -> String {
    "  cargo-build:\n    match:\n      - \"cargo build*\"\n      - \"cargo check*\"\n    profile: default\n"
        .to_string()
}

fn go_dispatch() -> String {
    "  go-get:\n    match:\n      - \"go get*\"\n      - \"go mod download*\"\n    profile: default\n"
        .to_string()
}

// ── Non-interactive (--preset) ────────────────────────────────────────────────

fn resolve_output_path(cli: &Cli, command: &InitCommand) -> Result<PathBuf, SboxError> {
    let cwd = std::env::current_dir().map_err(|source| SboxError::CurrentDirectory { source })?;
    let base = cli.workspace.clone().unwrap_or(cwd);

    Ok(match &command.output {
        Some(path) if path.is_absolute() => path.clone(),
        Some(path) => base.join(path),
        None => base.join("sbox.yaml"),
    })
}

pub fn render_template(preset: &str) -> Result<String, SboxError> {
    match preset {
        "node" => Ok(
"version: 1

workspace:
  mount: /workspace
  writable: false
  exclude_paths:
    - .env
    - .env.local
    - .env.production
    - .env.development
    - .npmrc
    - .netrc
    - \".ssh/*\"
    - \".aws/*\"

image:
  ref: node:22-bookworm-slim

environment:
  pass_through:
    - TERM

package_manager:
  name: npm
".to_string()),

        "python" => Ok(
"version: 1

workspace:
  mount: /workspace
  writable: false
  exclude_paths:
    - .env
    - .env.local
    - .netrc
    - \".ssh/*\"
    - \".aws/*\"

image:
  ref: python:3.13-slim

environment:
  pass_through:
    - TERM

package_manager:
  name: uv
".to_string()),

        "rust" => Ok(
"version: 1

workspace:
  mount: /workspace
  writable: false
  exclude_paths:
    - \".ssh/*\"
    - \".aws/*\"

image:
  ref: rust:1-bookworm

environment:
  pass_through:
    - TERM

package_manager:
  name: cargo
".to_string()),

        "go" => Ok(
"version: 1

workspace:
  mount: /workspace
  writable: false
  exclude_paths:
    - \".ssh/*\"
    - \".aws/*\"

image:
  ref: golang:1.23-bookworm

environment:
  pass_through:
    - TERM

package_manager:
  name: go
".to_string()),

        "generic" | "polyglot" => Ok(
"version: 1

runtime:
  backend: podman
  rootless: true

workspace:
  root: .
  mount: /workspace
  writable: true
  exclude_paths:
    - \".ssh/*\"
    - \".aws/*\"

image:
  ref: ubuntu:24.04

environment:
  pass_through:
    - TERM
  set: {}
  deny: []

profiles:
  default:
    mode: sandbox
    network: off
    writable: true
    no_new_privileges: true

  host:
    mode: host
    network: on
    writable: true

dispatch: {}
".to_string()),

        other => Err(SboxError::UnknownPreset {
            name: other.to_string(),
        }),
    }
}

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

    #[test]
    fn renders_node_template_with_package_manager() {
        let rendered = render_template("node").expect("node preset should exist");
        assert!(rendered.contains("ref: node:22-bookworm-slim"));
        assert!(rendered.contains("package_manager:"));
        assert!(rendered.contains("name: npm"));
        assert!(!rendered.contains("profiles:"));
    }

    #[test]
    fn renders_python_template_with_package_manager() {
        let rendered = render_template("python").expect("python preset should exist");
        assert!(rendered.contains("ref: python:3.13-slim"));
        assert!(rendered.contains("name: uv"));
    }

    #[test]
    fn renders_rust_template_with_package_manager() {
        let rendered = render_template("rust").expect("rust preset should exist");
        assert!(rendered.contains("ref: rust:1-bookworm"));
        assert!(rendered.contains("name: cargo"));
    }

    #[test]
    fn renders_generic_template_with_profiles() {
        let rendered = render_template("generic").expect("generic preset should exist");
        assert!(rendered.contains("profiles:"));
        assert!(!rendered.contains("package_manager:"));
    }
}