vetto 0.3.4

Daemon-less sandbox + security layer for AI coding agents (Landlock/Seatbelt, TUI statusline, post-session audit reports)
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
//! Boundary verification battery: prove from inside a throwaway sandbox that
//! the resolved policy actually denies secret reads, host loopback connects,
//! and writes outside every write root.
//!
//! Constraints:
//! - The sandbox under test is the real enforcement backend, one spawn per
//!   battery (`doctor::probe`); there is no simulation.
//! - `preflight` never fails for platform or backend reasons: an unusable
//!   backend yields an "unavailable" report so `--verify` can distinguish
//!   "no leaks" from "could not check".
//! - Leaks fail closed: exit code 1 in the CLI, refused session start for
//!   the supervised preflight.

use std::path::Path;
#[cfg(unix)]
use std::path::PathBuf;

#[cfg(unix)]
use anyhow::Context;

use crate::config::NetMode;
#[cfg(unix)]
use crate::policy;
use crate::policy::Policy;
use crate::sandbox;

#[cfg(unix)]
use crate::doctor::run_probe_script;
#[cfg(unix)]
use crate::policy::Tier;

#[cfg(unix)]
const STATUS_PASS: &str = "pass";
const STATUS_LEAK: &str = "LEAK";
const STATUS_INFO: &str = "info";
const STATUS_SKIPPED: &str = "skipped";

/// One battery check. `name` is a stable machine-readable identifier; the
/// variable part of the finding (path, byte counts) lives in `detail`.
#[derive(Debug, Clone)]
pub struct CheckResult {
    pub name: &'static str,
    pub status: &'static str,
    pub detail: String,
}

/// Battery outcome for one resolved policy. `tier`/`net` mirror the session
/// context the battery ran under.
#[derive(Debug, Clone)]
pub struct VerifyReport {
    pub tier: String,
    pub net: String,
    pub checks: Vec<CheckResult>,
}

impl VerifyReport {
    pub fn leaks(&self) -> usize {
        self.checks
            .iter()
            .filter(|check| check.status == STATUS_LEAK)
            .count()
    }

    /// "failed" on any leak; "unavailable" when every check is info/skipped
    /// AND the backend marked itself unable to run the battery (the
    /// `backend` info check is that marker); "pass" otherwise.
    pub fn status(&self) -> &'static str {
        if self.leaks() > 0 {
            return "failed";
        }
        let backend_marker = self
            .checks
            .iter()
            .any(|check| check.name == "backend" && check.status == STATUS_INFO);
        let no_verdicts = self
            .checks
            .iter()
            .all(|check| check.status == STATUS_INFO || check.status == STATUS_SKIPPED);
        if backend_marker && no_verdicts {
            "unavailable"
        } else {
            "pass"
        }
    }

    pub fn summary(&self) -> String {
        format!(
            "boundary verify: tier={} net={} checks={} leaks={}",
            self.tier,
            self.net,
            self.checks.len(),
            self.leaks()
        )
    }

    pub fn to_json(&self) -> serde_json::Value {
        serde_json::json!({
            "tier": self.tier,
            "net": self.net,
            "status": self.status(),
            "leaks": self.leaks(),
            "checks": self
                .checks
                .iter()
                .map(|check| {
                    serde_json::json!({
                        "name": check.name,
                        "status": check.status,
                        "detail": check.detail,
                    })
                })
                .collect::<Vec<serde_json::Value>>(),
        })
    }
}

/// `vetto verify`: resolve the policy exactly like the doctor probe (project
/// = cwd, home = $HOME, tier from the detected backend) and run the battery.
/// Exits 1 on any leak.
pub fn run_cli(
    json: bool,
    profile: &str,
    policy_path: Option<&Path>,
    net: &NetMode,
) -> anyhow::Result<()> {
    let backend = match sandbox::Backend::detect(net.clone(), false) {
        Ok(b) => b,
        Err(error) => {
            let rep = unavailable(
                net,
                "unknown",
                format!("backend cannot run the battery: {error:#}"),
            );
            if json {
                println!("{}", serde_json::to_string_pretty(&rep.to_json())?);
            } else {
                println!("{}", rep.summary());
                println!("boundary verify: UNAVAILABLE (backend could not run the battery)");
            }
            return Ok(());
        }
    };
    #[cfg(unix)]
    let report = {
        let tier = backend.tier().unwrap_or(policy::Tier::Full);
        let project = std::env::current_dir().context("getcwd")?;
        let home = std::env::var_os("HOME")
            .or_else(|| std::env::var_os("USERPROFILE"))
            .map(PathBuf::from)
            .context("neither $HOME nor %USERPROFILE% is set")?;
        let pol = policy::loader::load(profile, policy_path, &project, &home, tier)?;
        let unprepared = sandbox::production::UnpreparedProductionExecution::new(
            backend,
            pol,
            vec!["vetto-verify".to_string()],
            project,
            std::collections::HashMap::new(),
            net.clone(),
            None,
            sandbox::StdioMode::Inherit,
            "verify".to_string(),
        );
        let prepared = unprepared.prepare()?;
        preflight_contract(prepared.contract())?
    };
    #[cfg(not(unix))]
    let report = {
        let _ = (profile, policy_path, &backend);
        unavailable(net, "n/a", "verification battery is unix-only".to_string())
    };

    if json {
        println!("{}", serde_json::to_string_pretty(&report.to_json())?);
    } else {
        println!("{}", report.summary());
        for check in &report.checks {
            println!("  {:<9} {:<14} {}", check.status, check.name, check.detail);
        }
        match report.status() {
            "failed" => println!("boundary verify: FAILED ({} leak(s))", report.leaks()),
            "unavailable" => {
                println!("boundary verify: UNAVAILABLE (backend could not run the battery)")
            }
            _ => println!("boundary verify: PASS"),
        }
    }
    if report.leaks() > 0 {
        std::process::exit(1);
    }
    Ok(())
}

/// Battery against a caller-resolved policy (supervised `--verify` preflight).
pub fn preflight(pol: &Policy, net: &NetMode) -> anyhow::Result<VerifyReport> {
    #[cfg(not(unix))]
    {
        let _ = pol;
        Ok(unavailable(
            net,
            "n/a",
            "verification battery is unix-only".to_string(),
        ))
    }
    #[cfg(unix)]
    {
        let backend = match sandbox::Backend::detect(net.clone(), false) {
            Ok(backend) => backend,
            Err(error) => {
                return Ok(unavailable(
                    net,
                    "unknown",
                    format!("backend cannot run the battery: {error:#}"),
                ))
            }
        };
        let project = std::env::current_dir().context("getcwd")?;
        let unprepared = sandbox::production::UnpreparedProductionExecution::new(
            backend,
            pol.clone(),
            vec!["vetto-verify-probe".to_string()],
            project,
            std::collections::HashMap::new(),
            net.clone(),
            None,
            sandbox::StdioMode::Inherit,
            "verify".to_string(),
        );
        let prepared = unprepared.prepare()?;
        preflight_contract(prepared.contract())
    }
}

/// Battery against a sealed SecurityContract (Phase 2 authoritative boundary verification).
/// Consumes the exact sealed contract used by production execution; never rebuilds policy.
pub fn preflight_contract(
    contract: &crate::policy_ir::contract::SecurityContract,
) -> anyhow::Result<VerifyReport> {
    anyhow::ensure!(
        contract.verify_digest(),
        "invalid security contract digest (fail-closed, no agent execution)"
    );
    let production = contract.production.as_ref().ok_or_else(|| {
        anyhow::anyhow!("missing production installation contract in sealed contract")
    })?;
    #[cfg(not(unix))]
    {
        let _ = production;
        Ok(unavailable(
            &production.net,
            "n/a",
            "verification battery is unix-only".to_string(),
        ))
    }
    #[cfg(unix)]
    battery_contract(contract, &production.installation_policy, &production.net)
}

fn unavailable(net: &NetMode, tier: &str, detail: String) -> VerifyReport {
    VerifyReport {
        tier: tier.to_string(),
        net: net.label(),
        checks: vec![CheckResult {
            name: "backend",
            status: STATUS_INFO,
            detail,
        }],
    }
}

#[cfg(unix)]
fn pass(name: &'static str, detail: String) -> CheckResult {
    CheckResult {
        name,
        status: STATUS_PASS,
        detail,
    }
}

#[cfg(unix)]
fn leak(name: &'static str, detail: String) -> CheckResult {
    CheckResult {
        name,
        status: STATUS_LEAK,
        detail,
    }
}

#[cfg(unix)]
fn skipped(name: &'static str, detail: String) -> CheckResult {
    CheckResult {
        name,
        status: STATUS_SKIPPED,
        detail,
    }
}

#[cfg(unix)]
fn battery_contract(
    contract: &crate::policy_ir::contract::SecurityContract,
    pol: &Policy,
    net: &NetMode,
) -> anyhow::Result<VerifyReport> {
    anyhow::ensure!(
        contract.verify_digest(),
        "invalid security contract digest (fail-closed, no agent execution)"
    );
    let project = &contract.filesystem.workspace_root;
    let backend = match sandbox::Backend::detect(net.clone(), false) {
        Ok(backend) => backend,
        Err(error) => {
            return Ok(unavailable(
                net,
                "unknown",
                format!("backend cannot run the battery: {error:#}"),
            ))
        }
    };
    let tier = backend.tier();

    let mut checks: Vec<CheckResult> = Vec::new();
    let mut script_args: Vec<String> = pol
        .deny_resolved
        .iter()
        .map(|entry| entry.path.display().to_string())
        .collect();

    // Include masked secret paths from the contract
    for mask_path in &contract.filesystem.mask_paths {
        let s = mask_path.display().to_string();
        if !script_args.contains(&s) {
            script_args.push(s);
        }
    }

    // Host-side loopback listener
    let mut listener = None;
    match std::net::TcpListener::bind(("127.0.0.1", 0)) {
        Ok(bound) => match bound.local_addr() {
            Ok(addr) => {
                script_args.push(format!("NETCHECK:{}", addr.port()));
                listener = Some(bound);
            }
            Err(error) => checks.push(skipped(
                "net-loopback",
                format!("host listener local_addr failed: {error}"),
            )),
        },
        Err(error) => checks.push(skipped(
            "net-loopback",
            format!("host listener bind failed: {error}"),
        )),
    }

    // Write-outside probe target: outside workspace root
    let mut write_probe = None;
    if let Some(home) = std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
    {
        let in_allow = contract
            .filesystem
            .allow_write
            .iter()
            .any(|w| home.starts_with(w));
        if !pol.in_write_scope(&home) && !in_allow {
            let path = home.join(format!("vetto-verify-probe-{}", std::process::id()));
            script_args.push(format!("WRITECHECK:{}", path.display()));
            write_probe = Some(path);
        }
    }

    let probe = match run_probe_script(pol, project, script_args) {
        Ok(probe) => probe,
        Err(error) => {
            return Ok(unavailable(
                net,
                "unknown",
                format!("sandbox spawn failed: {error:#}"),
            ))
        }
    };
    drop(listener);
    if let Some(path) = &write_probe {
        let _ = std::fs::remove_file(path);
    }

    parse_probe_output(&probe.stdout, tier, &mut checks);
    let stderr = probe.stderr.trim();
    if !stderr.is_empty() {
        checks.push(CheckResult {
            name: "probe-stderr",
            status: STATUS_INFO,
            detail: stderr.to_string(),
        });
    }

    Ok(VerifyReport {
        tier: tier_label(tier),
        net: net.label(),
        checks,
    })
}

#[cfg(unix)]
fn tier_label(tier: Option<Tier>) -> String {
    match tier {
        Some(tier) => tier.label().to_string(),
        // macOS reports no FS tier; its enforcement mechanism is seatbelt.
        None if cfg!(target_os = "macos") => "seatbelt".to_string(),
        None => "none".to_string(),
    }
}

#[cfg(unix)]
fn net_pass_detail(tier: Option<Tier>) -> String {
    match tier {
        Some(Tier::Full) => "host loopback listener unreachable (netns isolation)".to_string(),
        Some(Tier::FsOnly) | Some(Tier::Seccomp) => {
            "host loopback listener unreachable (seccomp socket block)".to_string()
        }
        None if cfg!(target_os = "macos") => {
            "host loopback listener unreachable (seatbelt deny)".to_string()
        }
        None => "host loopback listener unreachable".to_string(),
    }
}

#[cfg(unix)]
fn parse_probe_output(output: &str, tier: Option<Tier>, checks: &mut Vec<CheckResult>) {
    for line in output.lines() {
        let mut parts = line.splitn(3, '|');
        let (kind, path, verdict) = match (parts.next(), parts.next(), parts.next()) {
            (Some(kind), Some(path), Some(verdict)) => (kind, path, verdict),
            _ => continue,
        };
        match (kind, verdict) {
            ("D", "contents-denied") => checks.push(pass(
                "deny-path",
                format!(
                    "{path}/: file contents denied (entry names may remain visible in FS-ONLY)"
                ),
            )),
            ("D", "content-readable") => checks.push(leak(
                "deny-path",
                format!("{path}/: file content is readable"),
            )),
            ("F", "unreadable") => checks.push(pass("deny-path", format!("{path}: open denied"))),
            ("F", bytes) => {
                let in_sandbox: u64 = bytes.parse().unwrap_or(0);
                let host = std::fs::metadata(path).map(|meta| meta.len()).unwrap_or(0);
                if host == 0 {
                    checks.push(pass(
                        "deny-path",
                        format!("{path}: empty on host; trivially safe"),
                    ));
                } else if in_sandbox == 0 {
                    checks.push(pass(
                        "deny-path",
                        format!("{path}: masked (appears empty inside)"),
                    ));
                } else {
                    checks.push(leak(
                        "deny-path",
                        format!("{path}: {in_sandbox}/{host} bytes readable"),
                    ));
                }
            }
            ("NET", "unreachable") => checks.push(pass("net-loopback", net_pass_detail(tier))),
            ("NET", "reachable") => checks.push(leak(
                "net-loopback",
                "sandbox reached a host loopback listener".to_string(),
            )),
            ("NET", "nobash") => checks.push(skipped(
                "net-loopback",
                "no bash inside the sandbox; /dev/tcp probe unavailable".to_string(),
            )),
            ("WRITE", "denied") => checks.push(pass(
                "write-outside",
                format!("write to {path} outside every write root denied"),
            )),
            ("WRITE", "allowed") => checks.push(leak(
                "write-outside",
                format!("wrote outside every write root: {path}"),
            )),
            _ => {}
        }
    }
}