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
use crate::config::model::{
    Config, DispatchRule, ExecutionMode, ProfileConfig, ProfileRole,
};
use crate::error::SboxError;

/// Built-in package manager preset.
struct Preset {
    install_patterns: &'static [&'static str],
    build_patterns: &'static [&'static str],
    install_writable: &'static [&'static str],
    build_writable: &'static [&'static str],
    network_allow: &'static [&'static str],
    lockfile_files: &'static [&'static str],
}

static PRESETS: &[(&str, Preset)] = &[
    (
        "npm",
        Preset {
            install_patterns: &["npm install*", "npm ci*", "npm i *"],
            build_patterns:   &["npm run build*", "npm run compile*"],
            install_writable: &["node_modules", "package-lock.json"],
            build_writable:   &["dist", "node_modules/.vite-temp", "node_modules/.tmp"],
            network_allow:    &["registry.npmjs.org"],
            lockfile_files:   &["package-lock.json", "npm-shrinkwrap.json"],
        },
    ),
    (
        "yarn",
        Preset {
            install_patterns: &["yarn install*", "yarn add*"],
            build_patterns:   &["yarn build*", "yarn run build*"],
            install_writable: &["node_modules", "yarn.lock"],
            build_writable:   &["dist", "node_modules/.vite-temp", "node_modules/.tmp"],
            network_allow:    &["registry.yarnpkg.com", "registry.npmjs.org"],
            lockfile_files:   &["yarn.lock"],
        },
    ),
    (
        "pnpm",
        Preset {
            install_patterns: &["pnpm install*", "pnpm i *", "pnpm add*"],
            build_patterns:   &["pnpm run build*", "pnpm build*"],
            install_writable: &["node_modules", "pnpm-lock.yaml"],
            build_writable:   &["dist", "node_modules/.vite-temp", "node_modules/.tmp"],
            network_allow:    &["registry.npmjs.org"],
            lockfile_files:   &["pnpm-lock.yaml"],
        },
    ),
    (
        "bun",
        Preset {
            install_patterns: &["bun install*", "bun i *", "bun add*"],
            build_patterns:   &["bun build*", "bun run build*"],
            install_writable: &["node_modules", "bun.lockb", "bun.lock"],
            build_writable:   &["dist", "node_modules/.vite-temp", "node_modules/.tmp"],
            network_allow:    &["registry.npmjs.org"],
            lockfile_files:   &["bun.lockb", "bun.lock"],
        },
    ),
    (
        "uv",
        Preset {
            install_patterns: &["uv sync*", "uv add*", "uv pip install*"],
            build_patterns:   &["uv build*", "uv run build*"],
            install_writable: &[".venv"],
            build_writable:   &["dist"],
            network_allow:    &["pypi.org", "files.pythonhosted.org"],
            lockfile_files:   &["uv.lock"],
        },
    ),
    (
        "pip",
        Preset {
            install_patterns: &["pip install*", "pip3 install*"],
            build_patterns:   &[],
            install_writable: &[".venv"],
            build_writable:   &[],
            network_allow:    &["pypi.org", "files.pythonhosted.org"],
            lockfile_files:   &["requirements.txt"],
        },
    ),
    (
        "poetry",
        Preset {
            install_patterns: &["poetry install*", "poetry add*"],
            build_patterns:   &["poetry build*"],
            install_writable: &[".venv"],
            build_writable:   &["dist"],
            network_allow:    &["pypi.org", "files.pythonhosted.org"],
            lockfile_files:   &["poetry.lock"],
        },
    ),
    (
        "cargo",
        Preset {
            install_patterns: &["cargo fetch*", "cargo build*"],
            build_patterns:   &["cargo build --release*"],
            install_writable: &["target"],
            build_writable:   &["target/release"],
            network_allow:    &["crates.io", "static.crates.io", "index.crates.io"],
            lockfile_files:   &["Cargo.lock"],
        },
    ),
    (
        "go",
        Preset {
            install_patterns: &["go get*", "go mod download*", "go mod tidy*"],
            build_patterns:   &["go build*"],
            install_writable: &["vendor"],
            build_writable:   &[],
            network_allow:    &["proxy.golang.org", "sum.golang.org"],
            lockfile_files:   &["go.sum"],
        },
    ),
];

fn lookup_preset(name: &str) -> Option<&'static Preset> {
    PRESETS.iter().find(|(n, _)| *n == name).map(|(_, p)| p)
}

/// Dispatch rule key encoding — encodes pm name and kind so plan.rs can render a friendly string.
/// Format: `pm:<name>:<kind>` e.g. `pm:npm:install`
fn dispatch_key(pm_name: &str, kind: &str) -> String {
    format!("pm:{pm_name}:{kind}")
}

fn make_install_profile(_pm_name: &str, preset: &'static Preset, pm: &crate::config::model::PackageManagerConfig) -> ProfileConfig {
    let writable_paths = pm
        .install_writable
        .clone()
        .unwrap_or_else(|| preset.install_writable.iter().map(|s| s.to_string()).collect());

    let network_allow = pm
        .network_allow
        .clone()
        .unwrap_or_else(|| preset.network_allow.iter().map(|s| s.to_string()).collect());

    let pre_run = pm
        .pre_run
        .clone()
        .unwrap_or_default();

    ProfileConfig {
        mode: ExecutionMode::Sandbox,
        image: None,
        network: Some("on".to_string()),
        writable: Some(false),
        require_pinned_image: None,
        require_lockfile: None,
        role: Some(ProfileRole::Install),
        lockfile_files: preset.lockfile_files.iter().map(|s| s.to_string()).collect(),
        pre_run,
        ports: Vec::new(),
        network_allow,
        capabilities: None,
        no_new_privileges: Some(true),
        read_only_rootfs: None,
        reuse_container: None,
        shell: None,
        writable_paths: Some(writable_paths),
    }
}

fn make_build_profile(_pm_name: &str, preset: &'static Preset, pm: &crate::config::model::PackageManagerConfig) -> ProfileConfig {
    let writable_paths = pm
        .build_writable
        .clone()
        .unwrap_or_else(|| preset.build_writable.iter().map(|s| s.to_string()).collect());

    ProfileConfig {
        mode: ExecutionMode::Sandbox,
        image: None,
        network: Some("off".to_string()),
        writable: Some(false),
        require_pinned_image: None,
        require_lockfile: None,
        role: Some(ProfileRole::Build),
        lockfile_files: Vec::new(),
        pre_run: Vec::new(),
        ports: Vec::new(),
        network_allow: Vec::new(),
        capabilities: None,
        no_new_privileges: Some(true),
        read_only_rootfs: None,
        reuse_container: None,
        shell: None,
        writable_paths: Some(writable_paths),
    }
}

fn make_default_profile() -> ProfileConfig {
    ProfileConfig {
        mode: ExecutionMode::Sandbox,
        image: None,
        network: Some("off".to_string()),
        writable: Some(false),
        require_pinned_image: None,
        require_lockfile: None,
        role: Some(ProfileRole::Run),
        lockfile_files: Vec::new(),
        pre_run: Vec::new(),
        ports: Vec::new(),
        network_allow: Vec::new(),
        capabilities: None,
        no_new_privileges: Some(true),
        read_only_rootfs: None,
        reuse_container: None,
        shell: None,
        writable_paths: Some(vec![]),
    }
}

/// Elaborates `package_manager:` into synthetic profiles and dispatch rules.
/// Called after deserialization, before validation.
/// User-defined profiles and dispatch rules always take precedence.
pub fn elaborate(config: &mut Config) -> Result<(), SboxError> {
    let pm = match config.package_manager.as_ref() {
        Some(pm) => pm.clone(),
        None => return Ok(()),
    };

    let preset = lookup_preset(&pm.name).ok_or_else(|| SboxError::ConfigValidation {
        message: format!(
            "unknown package_manager name `{}`; valid names: npm, yarn, pnpm, bun, uv, pip, poetry, cargo, go",
            pm.name
        ),
    })?;

    let pm_name = pm.name.clone();

    // Synthesize profiles (only insert if the user hasn't defined them already).
    let install_profile_key = format!("pm-{pm_name}-install");
    let build_profile_key = format!("pm-{pm_name}-build");

    if !config.profiles.contains_key(&install_profile_key) {
        config.profiles.insert(
            install_profile_key.clone(),
            make_install_profile(&pm_name, preset, &pm),
        );
    }

    if !config.profiles.contains_key(&build_profile_key) && !preset.build_patterns.is_empty() {
        config.profiles.insert(
            build_profile_key.clone(),
            make_build_profile(&pm_name, preset, &pm),
        );
    }

    // Synthesize the default profile only if the user hasn't defined one.
    if !config.profiles.contains_key("default") {
        config.profiles.insert("default".to_string(), make_default_profile());
    }

    // Prepend dispatch rules so user-defined rules take precedence (IndexMap preserves order).
    // We insert in reverse order so they end up in the right sequence after shift_insert(0, ...).
    if !preset.build_patterns.is_empty() {
        let build_key = dispatch_key(&pm_name, "build");
        if !config.dispatch.contains_key(&build_key) {
            config.dispatch.shift_insert(
                0,
                build_key,
                DispatchRule {
                    patterns: preset.build_patterns.iter().map(|s| s.to_string()).collect(),
                    profile: build_profile_key,
                },
            );
        }
    }

    let install_key = dispatch_key(&pm_name, "install");
    if !config.dispatch.contains_key(&install_key) {
        config.dispatch.shift_insert(
            0,
            install_key,
            DispatchRule {
                patterns: preset.install_patterns.iter().map(|s| s.to_string()).collect(),
                profile: install_profile_key,
            },
        );
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::model::PackageManagerConfig;

    fn base_config_with_pm(name: &str) -> Config {
        Config {
            version: 1,
            runtime: None,
            workspace: Some(crate::config::model::WorkspaceConfig {
                root: None,
                mount: Some("/workspace".to_string()),
                writable: Some(false),
                writable_paths: vec![],
                exclude_paths: vec![],
            }),
            identity: None,
            image: Some(crate::config::model::ImageConfig {
                reference: Some("node:22-bookworm-slim".to_string()),
                digest: None,
                verify_signature: None,
                build: None,
                preset: None,
                pull_policy: None,
                tag: None,
            }),
            environment: None,
            mounts: vec![],
            caches: vec![],
            secrets: vec![],
            profiles: indexmap::IndexMap::new(),
            dispatch: indexmap::IndexMap::new(),
            package_manager: Some(PackageManagerConfig {
                name: name.to_string(),
                install_writable: None,
                build_writable: None,
                network_allow: None,
                pre_run: None,
            }),
        }
    }

    #[test]
    fn test_npm_generates_install_profile() {
        let mut config = base_config_with_pm("npm");
        elaborate(&mut config).unwrap();

        let profile = config.profiles.get("pm-npm-install").unwrap();
        assert_eq!(profile.network.as_deref(), Some("on"));
        assert_eq!(profile.writable, Some(false));
        assert_eq!(
            profile.writable_paths.as_deref().unwrap(),
            &["node_modules", "package-lock.json"]
        );
        assert_eq!(profile.role, Some(ProfileRole::Install));
    }

    #[test]
    fn test_npm_generates_build_profile() {
        let mut config = base_config_with_pm("npm");
        elaborate(&mut config).unwrap();

        let profile = config.profiles.get("pm-npm-build").unwrap();
        assert_eq!(profile.network.as_deref(), Some("off"));
        assert!(profile.writable_paths.as_deref().unwrap().contains(&"dist".to_string()));
    }

    #[test]
    fn test_default_profile_inserted_when_absent() {
        let mut config = base_config_with_pm("npm");
        elaborate(&mut config).unwrap();
        assert!(config.profiles.contains_key("default"));
        let default = config.profiles.get("default").unwrap();
        assert_eq!(default.network.as_deref(), Some("off"));
        assert_eq!(default.writable_paths.as_deref().unwrap(), &[] as &[String]);
    }

    #[test]
    fn test_default_profile_not_overridden() {
        let mut config = base_config_with_pm("npm");
        // Pre-insert a user default profile with network on
        config.profiles.insert(
            "default".to_string(),
            ProfileConfig {
                mode: ExecutionMode::Sandbox,
                image: None,
                network: Some("on".to_string()),
                writable: Some(true),
                require_pinned_image: None,
                require_lockfile: None,
                role: None,
                lockfile_files: vec![],
                pre_run: vec![],
                ports: vec![],
                network_allow: vec![],
                capabilities: None,
                no_new_privileges: None,
                read_only_rootfs: None,
                reuse_container: None,
                shell: None,
                writable_paths: None,
            },
        );
        elaborate(&mut config).unwrap();
        // User's default should be preserved
        assert_eq!(
            config.profiles.get("default").unwrap().network.as_deref(),
            Some("on")
        );
    }

    #[test]
    fn test_dispatch_rules_prepended() {
        let mut config = base_config_with_pm("npm");
        // Pre-insert a user dispatch rule
        config.dispatch.insert(
            "my-rule".to_string(),
            DispatchRule {
                patterns: vec!["npm install --my-custom*".to_string()],
                profile: "default".to_string(),
            },
        );
        elaborate(&mut config).unwrap();
        // PM rules must be at indices 0 and 1, user rule at end
        let keys: Vec<&str> = config.dispatch.keys().map(|s| s.as_str()).collect();
        assert!(keys[0].starts_with("pm:npm:"));
        assert!(keys[1].starts_with("pm:npm:"));
        assert_eq!(*keys.last().unwrap(), "my-rule");
    }

    #[test]
    fn test_unknown_pm_name_errors() {
        let mut config = base_config_with_pm("gradle");
        let err = elaborate(&mut config).unwrap_err();
        assert!(matches!(err, SboxError::ConfigValidation { .. }));
    }

    #[test]
    fn test_install_writable_override() {
        let mut config = base_config_with_pm("npm");
        config.package_manager.as_mut().unwrap().install_writable =
            Some(vec!["node_modules".to_string(), ".cache".to_string()]);
        elaborate(&mut config).unwrap();
        assert_eq!(
            config.profiles.get("pm-npm-install").unwrap().writable_paths.as_deref().unwrap(),
            &["node_modules", ".cache"]
        );
    }

    #[test]
    fn test_no_pm_is_noop() {
        let mut config = base_config_with_pm("npm");
        config.package_manager = None;
        elaborate(&mut config).unwrap();
        assert!(config.profiles.is_empty());
        assert!(config.dispatch.is_empty());
    }
}