zerobox 0.3.3

Sandbox any command with file, network, and credential controls.
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
mod debug;
mod profile;
mod snapshot;

use debug::debug_log;

use std::path::Path;
use std::path::PathBuf;
use std::process::ExitCode;

use clap::{Parser, Subcommand};
use zerobox::Sandbox;
#[cfg(target_os = "linux")]
use zerobox::arg0;

#[derive(Parser, Debug)]
#[command(name = "zerobox", version, about, long_about = None)]
pub struct Cli {
    #[command(subcommand)]
    pub subcommand: Option<CliSubcommand>,

    #[arg(long, value_delimiter = ',', num_args = 1..)]
    pub allow_read: Option<Vec<PathBuf>>,

    #[arg(long, value_delimiter = ',', num_args = 1..)]
    pub deny_read: Option<Vec<PathBuf>>,

    #[arg(long, value_delimiter = ',', num_args = 0..)]
    pub allow_write: Option<Vec<PathBuf>>,

    #[arg(long, value_delimiter = ',', num_args = 1..)]
    pub deny_write: Option<Vec<PathBuf>>,

    #[arg(long, value_delimiter = ',', num_args = 0..)]
    pub allow_net: Option<Vec<String>>,

    #[arg(long, value_delimiter = ',', num_args = 1..)]
    pub deny_net: Option<Vec<String>>,

    #[arg(long, short = 'A')]
    pub allow_all: bool,

    #[arg(long, short = 'C')]
    pub cwd: Option<PathBuf>,

    #[arg(long)]
    pub no_sandbox: bool,

    #[arg(long)]
    pub strict_sandbox: bool,

    #[arg(long = "env", value_name = "KEY=VALUE")]
    pub set_env: Vec<String>,

    #[arg(long, value_delimiter = ',', num_args = 0..)]
    pub allow_env: Option<Vec<String>>,

    #[arg(long, value_delimiter = ',', num_args = 1..)]
    pub deny_env: Option<Vec<String>>,

    #[arg(long = "secret", value_name = "KEY=VALUE")]
    pub secret: Vec<String>,

    #[arg(long = "secret-host", value_name = "KEY=HOSTS")]
    pub secret_host: Vec<String>,

    #[arg(long)]
    pub debug: bool,

    #[arg(long = "profile", value_delimiter = ',')]
    pub profile: Vec<String>,

    #[arg(long)]
    pub snapshot: bool,

    #[arg(long)]
    pub restore: bool,

    #[arg(long = "snapshot-path", value_delimiter = ',', num_args = 1..)]
    pub snapshot_paths: Option<Vec<std::path::PathBuf>>,

    #[arg(long = "snapshot-exclude", value_delimiter = ',', num_args = 1..)]
    pub snapshot_exclude: Option<Vec<String>>,

    #[arg(trailing_var_arg = true)]
    pub command: Vec<String>,
}

#[derive(Subcommand, Debug)]
pub enum CliSubcommand {
    Snapshot {
        #[command(subcommand)]
        action: SnapshotAction,
    },
    Profile {
        #[command(subcommand)]
        action: ProfileAction,
    },
}

#[derive(Subcommand, Debug)]
pub enum ProfileAction {
    List,
    Schema,
    Show { name: String },
}

#[derive(Subcommand, Debug)]
pub enum SnapshotAction {
    List,
    Diff {
        id: String,
    },
    Restore {
        id: String,
    },
    Clean {
        #[arg(long, default_value = "30")]
        older_than: u64,
    },
}

fn exit_code_from_status(status: std::process::ExitStatus) -> ExitCode {
    if let Some(code) = status.code() {
        return ExitCode::from(code as u8);
    }
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        if let Some(signal) = status.signal() {
            return ExitCode::from((128 + signal) as u8);
        }
    }
    ExitCode::from(1)
}

fn main() -> ExitCode {
    #[cfg(target_os = "linux")]
    arg0::dispatch_linux_sandbox_helper();

    let cli = Cli::parse();

    #[cfg(target_os = "linux")]
    let arg0_guard = prepare_arg0_aliases(&cli);
    #[cfg(target_os = "linux")]
    let linux_sandbox_exe = arg0_guard
        .as_ref()
        .map(|guard| guard.zerobox_linux_sandbox_exe().to_path_buf());

    #[cfg(not(target_os = "linux"))]
    let linux_sandbox_exe = None;

    let runtime = match tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
    {
        Ok(runtime) => runtime,
        Err(e) => {
            eprintln!("error: failed to start async runtime: {e}");
            return ExitCode::from(1);
        }
    };

    runtime.block_on(tokio_main(cli, linux_sandbox_exe))
}

#[cfg(target_os = "linux")]
fn prepare_arg0_aliases(cli: &Cli) -> Option<arg0::Arg0PathEntryGuard> {
    if cli.subcommand.is_some() || cli.command.is_empty() || cli.no_sandbox || cli.allow_all {
        return None;
    }

    match arg0::prepend_path_entry_for_zerobox_aliases() {
        Ok(guard) => Some(guard),
        Err(e) => {
            eprintln!("warning: proceeding without Linux sandbox helper alias: {e}");
            None
        }
    }
}

async fn tokio_main(cli: Cli, linux_sandbox_exe: Option<PathBuf>) -> ExitCode {
    if let Some(CliSubcommand::Snapshot { action }) = &cli.subcommand {
        return snapshot::handle_subcommand(action);
    }
    if let Some(CliSubcommand::Profile { action }) = &cli.subcommand {
        return profile::handle_subcommand(action);
    }

    if cli.command.is_empty() {
        eprintln!("error: no command specified");
        return ExitCode::from(1);
    }

    if cli.strict_sandbox && (cli.no_sandbox || cli.allow_all) {
        eprintln!("error: --strict-sandbox cannot be combined with --no-sandbox or --allow-all");
        return ExitCode::from(1);
    }

    let dbg = cli.debug;
    if dbg {
        debug::init_tracing();
    }

    let mut sandbox = Sandbox::command(&cli.command[0])
        .args(&cli.command[1..])
        .linux_sandbox_exe_opt(linux_sandbox_exe);

    if let Some(ref cwd) = cli.cwd {
        sandbox = sandbox.cwd(cwd);
    }

    if cli.no_sandbox {
        sandbox = sandbox.no_sandbox().no_profile();
    } else if cli.allow_all {
        sandbox = sandbox.full_access().no_profile();
    } else {
        if cli.strict_sandbox {
            sandbox = sandbox.strict();
        }
        if !cli.profile.is_empty() {
            sandbox = sandbox.profiles(&cli.profile);
        }
    }
    // else: default profile loads automatically

    if let Some(ref paths) = cli.allow_read {
        for p in paths {
            sandbox = sandbox.allow_read(p);
        }
    }
    if let Some(ref paths) = cli.deny_read {
        for p in paths {
            sandbox = sandbox.deny_read(p);
        }
    }
    if let Some(ref paths) = cli.allow_write {
        if paths.is_empty() {
            sandbox = sandbox.allow_write_all();
        } else {
            for p in paths {
                sandbox = sandbox.allow_write(p);
            }
        }
    }
    if let Some(ref paths) = cli.deny_write {
        for p in paths {
            sandbox = sandbox.deny_write(p);
        }
    }

    if let Some(ref domains) = cli.allow_net {
        if domains.is_empty() {
            sandbox = sandbox.allow_net_all();
        } else {
            sandbox = sandbox.allow_net(domains);
        }
    }
    if let Some(ref domains) = cli.deny_net {
        sandbox = sandbox.deny_net(domains);
    }

    for pair in &cli.set_env {
        if let Some((key, value)) = pair.split_once('=') {
            sandbox = sandbox.env(key, value);
        } else {
            eprintln!("error: invalid --env value '{pair}': expected KEY=VALUE format");
            return ExitCode::from(1);
        }
    }
    if let Some(ref keys) = cli.allow_env {
        if keys.is_empty() {
            sandbox = sandbox.inherit_env();
        } else {
            sandbox = sandbox.allow_env(keys);
        }
    }
    if let Some(ref keys) = cli.deny_env {
        sandbox = sandbox.deny_env(keys);
    }

    for pair in &cli.secret {
        if let Some((key, value)) = pair.split_once('=') {
            if key.is_empty() {
                eprintln!("error: invalid --secret value '{pair}': key cannot be empty");
                return ExitCode::from(1);
            }
            sandbox = sandbox.secret(key, value);
        } else {
            eprintln!("error: invalid --secret value '{pair}': expected KEY=VALUE format");
            return ExitCode::from(1);
        }
    }
    for pair in &cli.secret_host {
        if let Some((key, hosts)) = pair.split_once('=') {
            sandbox = sandbox.secret_host(key, hosts);
        } else {
            eprintln!("error: invalid --secret-host value '{pair}': expected KEY=HOSTS format");
            return ExitCode::from(1);
        }
    }

    debug_log!(
        dbg,
        "cwd: {:?}",
        cli.cwd.as_deref().unwrap_or(Path::new("."))
    );

    let cwd = cli
        .cwd
        .clone()
        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
    let do_snapshot = cli.snapshot || cli.restore;
    let snapshot_state = if do_snapshot {
        match snapshot::build_snapshot_state(&cli, &cwd) {
            Ok(mut state) => match state.manager.create_baseline() {
                Ok(baseline) => {
                    debug_log!(
                        dbg,
                        "snapshot: baseline captured ({} files)",
                        baseline.files.len()
                    );
                    Some((state, baseline))
                }
                Err(e) => {
                    if cli.restore {
                        eprintln!("error: --restore requires snapshot but baseline failed: {e:#}");
                        return ExitCode::from(1);
                    }
                    eprintln!("warning: snapshot baseline failed: {e:#}");
                    None
                }
            },
            Err(e) => {
                if cli.restore {
                    eprintln!("error: --restore requires snapshot but setup failed: {e:#}");
                    return ExitCode::from(1);
                }
                eprintln!("warning: snapshot setup failed: {e:#}");
                None
            }
        }
    } else {
        None
    };

    let is_tty = std::io::IsTerminal::is_terminal(&std::io::stdin());

    let (exit, raw_exit_code) = if is_tty {
        match sandbox.status().await {
            Ok(status) => (exit_code_from_status(status), status.code()),
            Err(e) => {
                eprintln!("error: {e:#}");
                (ExitCode::from(1), Some(1))
            }
        }
    } else {
        match sandbox.run().await {
            Ok(output) => {
                use std::io::Write;
                let _ = std::io::stdout().write_all(&output.stdout);
                let _ = std::io::stderr().write_all(&output.stderr);
                (exit_code_from_status(output.status), output.status.code())
            }
            Err(e) => {
                eprintln!("error: {e:#}");
                (ExitCode::from(1), Some(1))
            }
        }
    };

    if let Some((mut state, baseline)) = snapshot_state {
        let incremental = state.manager.create_incremental(&baseline);

        if let Ok((_, ref changes)) = incremental {
            snapshot::print_summary_to(changes, &mut std::io::stderr());
        } else if let Err(ref e) = incremental {
            eprintln!("snapshot: incremental failed: {e:#}");
        }

        let mut meta = snapshot::build_session_metadata(&state, &cli, &baseline);
        meta.ended = Some(chrono::Utc::now().to_rfc3339());
        meta.exit_code = raw_exit_code;
        meta.snapshot_count = state.manager.snapshot_count();
        if let Ok((ref final_manifest, _)) = incremental {
            meta.merkle_roots.push(final_manifest.merkle_root);
        }
        if let Err(e) = state.manager.save_session(&meta) {
            eprintln!("snapshot: failed to save session: {e:#}");
        }

        if cli.restore {
            match state.manager.restore_to(&baseline) {
                Ok(applied) if !applied.is_empty() => {
                    eprintln!("snapshot: restored {} files", applied.len());
                }
                Err(e) => {
                    eprintln!("snapshot: restore failed: {e:#}");
                    return ExitCode::from(1);
                }
                _ => {}
            }
        }
    }

    exit
}