vetto 0.2.17

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
//! Policy representation after load-time resolution.

use serde::{Deserialize, Serialize};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};

/// Linux capability tier the policy was loaded for (affects masking strategy).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Tier {
    /// Landlock + namespaces: secrets masked with mount overlays.
    Full,
    /// Landlock only (no userns): project secrets masked by explicit
    /// enumeration into the read allowlist; overlay masking unavailable.
    FsOnly,
    /// Seccomp filter only (no Landlock, no namespaces): syscall hardening
    /// and network blocks only, no filesystem isolation.
    Seccomp,
}

impl Tier {
    pub fn label(&self) -> &'static str {
        match self {
            Tier::Full => "full",
            Tier::FsOnly => "fs-only",
            Tier::Seccomp => "seccomp",
        }
    }
}

/// Seccomp syscall filtering profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SeccompProfile {
    #[default]
    Default,
    AgentMin,
}

impl SeccompProfile {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "default" | "standard" => Some(Self::Default),
            "agent-min" | "agent_min" => Some(Self::AgentMin),
            _ => None,
        }
    }

    pub fn label(&self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::AgentMin => "agent-min",
        }
    }
}

/// Optional cgroup v2 resource limits configuration.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CgroupConfig {
    pub memory_max: Option<String>,
    pub pids_max: Option<String>,
    pub swap_max: Option<String>,
    pub cpu_max: Option<String>,
}

/// Optional seccomp user-notify supervisor configuration.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SeccompNotifyConfig {
    pub enabled: bool,
    pub default_action: Option<String>,
    #[serde(default)]
    pub allow_syscalls: Vec<String>,
}

/// The 7-level policy hierarchy source classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum PolicySourceKind {
    /// 1. System/Org Global Policy (`/etc/vetto/policy.toml` or `%ProgramData%\vetto\policy.toml`)
    SystemGlobal,
    /// 2. User Global Policy (`~/.config/vetto/policy.toml`)
    UserGlobal,
    /// 3. Built-in Profile (`default`, `strict`, `audit`, `permissive`)
    BuiltinProfile,
    /// 3b. Security Preset (`paranoid`, `balanced`, `yolo`)
    Preset,
    /// 4. Agent Preset (`codex`, `claude`, `cursor`, `aider`, `cline`, `opencode`, `copilot`, `custom`)
    AgentPreset,
    /// 5. Repository Policy (`.vetto/policy.toml` or `vetto.toml`)
    Repository,
    /// 5b. Repository Policy Fragment (`.vetto/policy.d/*.toml`)
    RepositoryFragment,
    /// 6. Local Override Policy (`.vetto.override.toml` or `.vetto/local.toml`)
    LocalOverride,
    /// 7a. Explicit CLI Flag (`--policy <file>`)
    CliExplicit,
    /// 7b. Runtime CLI Overrides (`--allow-write`, `--deny-read`, etc.)
    CliOverride,
}

impl PolicySourceKind {
    pub fn precedence(&self) -> u8 {
        match self {
            Self::SystemGlobal => 1,
            Self::UserGlobal => 2,
            Self::BuiltinProfile | Self::Preset => 3,
            Self::AgentPreset => 4,
            Self::Repository | Self::RepositoryFragment => 5,
            Self::LocalOverride => 6,
            Self::CliExplicit | Self::CliOverride => 7,
        }
    }

    pub fn label(&self) -> &'static str {
        match self {
            Self::SystemGlobal => "system-global",
            Self::UserGlobal => "user-global",
            Self::BuiltinProfile => "builtin-profile",
            Self::Preset => "preset",
            Self::AgentPreset => "agent-preset",
            Self::Repository => "repository",
            Self::RepositoryFragment => "repository-fragment",
            Self::LocalOverride => "local-override",
            Self::CliExplicit => "cli-explicit",
            Self::CliOverride => "cli-override",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DenyEntry {
    pub path: PathBuf,
    pub is_dir: bool,
}

/// User-facing metadata carried by a loaded policy.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PolicyMetadata {
    pub name: String,
    pub description: String,
    pub extends: Vec<String>,
    #[serde(default)]
    pub source_kind: Option<PolicySourceKind>,
    #[serde(default)]
    pub immutable: bool,
}

/// Optional IO rate limits for Windows Job Objects and supported platforms.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct IoRateLimit {
    pub max_iops: Option<u64>,
    pub max_bandwidth: Option<u64>,
}

impl IoRateLimit {
    pub fn merge_strictest(&mut self, other: &Self) {
        self.max_iops = strictest(self.max_iops, other.max_iops);
        self.max_bandwidth = strictest(self.max_bandwidth, other.max_bandwidth);
    }
}

/// Optional per-agent resource ceilings applied immediately before `execve`.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceLimits {
    pub cpu_seconds: Option<u64>,
    pub address_space_bytes: Option<u64>,
    pub processes: Option<u64>,
    pub open_files: Option<u64>,
    /// RLIMIT_FSIZE: maximum size of files the agent may create.
    pub file_size_bytes: Option<u64>,
    #[serde(default)]
    pub io_rate: Option<IoRateLimit>,
}

impl ResourceLimits {
    pub fn merge_strictest(&mut self, other: &Self) {
        self.cpu_seconds = strictest(self.cpu_seconds, other.cpu_seconds);
        self.address_space_bytes = strictest(self.address_space_bytes, other.address_space_bytes);
        self.processes = strictest(self.processes, other.processes);
        self.open_files = strictest(self.open_files, other.open_files);
        self.file_size_bytes = strictest(self.file_size_bytes, other.file_size_bytes);
        match (&mut self.io_rate, &other.io_rate) {
            (Some(existing), Some(incoming)) => existing.merge_strictest(incoming),
            (None, Some(incoming)) => self.io_rate = Some(incoming.clone()),
            _ => {}
        }
    }
}

fn strictest(left: Option<u64>, right: Option<u64>) -> Option<u64> {
    match (left, right) {
        (Some(left), Some(right)) => Some(left.min(right)),
        (Some(value), None) | (None, Some(value)) => Some(value),
        (None, None) => None,
    }
}

/// Environment variables explicitly allowed into the agent process, with optional subtractive deny list.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct EnvironmentPolicy {
    pub pass_through: Vec<String>,
    #[serde(default)]
    pub deny: Vec<String>,
}

impl EnvironmentPolicy {
    pub fn allows(&self, key: &OsStr) -> bool {
        let key = key.to_string_lossy();
        // Deny takes precedence
        let is_denied = self.deny.iter().any(|pattern| {
            pattern
                .strip_suffix('*')
                .map_or_else(|| pattern == key.as_ref(), |prefix| key.starts_with(prefix))
        });
        if is_denied {
            return false;
        }

        self.pass_through.iter().any(|pattern| {
            pattern
                .strip_suffix('*')
                .map_or_else(|| pattern == key.as_ref(), |prefix| key.starts_with(prefix))
        })
    }
}

/// Subtractive rules explicitly denying read, write, network, or env access.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SubtractiveRules {
    pub deny_write: Vec<PathBuf>,
    pub deny_read: Vec<PathBuf>,
    pub deny_env: Vec<String>,
    pub deny_network: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct Policy {
    pub name: String,
    /// Metadata from the effective policy layers.
    pub metadata: PolicyMetadata,
    /// Resource ceilings applied immediately before the agent `execve`.
    pub limits: ResourceLimits,
    /// Concrete read-write roots.
    pub allow_write: Vec<PathBuf>,
    /// Concrete read-only roots.
    pub allow_read: Vec<PathBuf>,
    /// Subtractive write deny rules.
    pub deny_write: Vec<PathBuf>,
    /// Subtractive read deny rules.
    pub deny_read: Vec<PathBuf>,
    /// Resolved display_only_deny paths that exist on this machine.
    pub deny_resolved: Vec<DenyEntry>,
    /// Environment allowlist applied immediately before agent execve.
    pub environment: EnvironmentPolicy,
    /// True when a policy layer denies direct network access. Session-level
    /// enforcement additionally depends on the CLI `--net` mode, which lives
    /// outside the policy: this field only records policy-layer intent.
    pub deny_network: bool,
    /// CIDR subnets allowed for network connections.
    pub allow_cidr: Vec<String>,
    /// Per-domain byte quotas (in bytes).
    pub net_quota: std::collections::HashMap<String, u64>,
    /// TCP ports allowed for binding in Landlock (ABI >= 4).
    pub net_bind_ports: Vec<u16>,
    /// TCP ports allowed for connecting in Landlock (ABI >= 4).
    pub net_connect_ports: Vec<u16>,
    /// Allowed unix domain socket paths / patterns.
    pub allow_unix_sockets: Vec<String>,
    /// Seccomp syscall filtering profile ("default" or "agent-min").
    pub seccomp_profile: SeccompProfile,
    /// Optional seccomp user-notify supervisor configuration.
    pub seccomp_notify: Option<SeccompNotifyConfig>,
    /// Optional cgroup v2 resource limits configuration.
    pub cgroup: Option<CgroupConfig>,
    /// CPU quota limit (e.g. "50%").
    pub cpu_max: Option<String>,
    /// I/O priority applied before exec (e.g. "idle", "best-effort").
    pub io_priority: Option<String>,
    /// Allowed device nodes in /dev for mount namespace.
    pub dev_allow: Option<Vec<String>>,
    /// macOS unified log (os_log / logger) opt-in.
    pub oslog: bool,
    /// Windows Less Privileged AppContainer (LPAC) mode opt-in.
    pub lpac: bool,
    /// Whether this policy is in immutable enterprise lockdown mode.
    pub is_immutable: bool,
    /// Whether system-level event logging (journald, EventLog, syslog) is enabled.
    pub system_log: bool,
    /// Automatically scan project for secrets at session start and deny them.
    pub auto_deny_secrets: bool,
    /// Secrets to proxy through host credential broker without exposing to agent.
    pub secret_proxies: Vec<String>,
    /// Read-only mounts inside the mount namespace.
    pub ro_mounts: Vec<PathBuf>,
    /// Protect Git repository from modification on main/master and destructive push.
    pub git_guard: bool,
    /// Create project snapshot at session start with rollback capability.
    pub snapshot: bool,
    /// Mount an isolated tmpfs over /tmp for the session.
    pub tmpfs_tmp: bool,
    /// Non-fatal findings surfaced to doctor/statusline/reports.
    pub warnings: Vec<String>,
}

impl Default for Policy {
    fn default() -> Self {
        Self {
            name: "default".to_string(),
            metadata: PolicyMetadata::default(),
            limits: ResourceLimits::default(),
            allow_write: Vec::new(),
            allow_read: Vec::new(),
            deny_write: Vec::new(),
            deny_read: Vec::new(),
            deny_resolved: Vec::new(),
            environment: EnvironmentPolicy::default(),
            deny_network: false,
            allow_cidr: Vec::new(),
            net_quota: std::collections::HashMap::new(),
            net_bind_ports: Vec::new(),
            net_connect_ports: Vec::new(),
            allow_unix_sockets: Vec::new(),
            seccomp_profile: SeccompProfile::Default,
            seccomp_notify: None,
            cgroup: None,
            cpu_max: None,
            io_priority: None,
            dev_allow: None,
            oslog: false,
            lpac: false,
            is_immutable: false,
            system_log: false,
            auto_deny_secrets: false,
            secret_proxies: Vec::new(),
            ro_mounts: Vec::new(),
            git_guard: false,
            snapshot: false,
            tmpfs_tmp: true,
            warnings: Vec::new(),
        }
    }
}

impl Policy {
    pub fn summary(&self) -> String {
        format!(
            "profile '{}': {} write root(s), {} read root(s), {} deny path(s) resolved",
            self.name,
            self.allow_write.len(),
            self.allow_read.len(),
            self.deny_resolved.len()
        )
    }

    /// Is `path` inside any write root? (fail-closed normalized prefix check)
    pub fn in_write_scope(&self, path: &Path) -> bool {
        let probed = normalize_scope_path(path);
        if self
            .deny_write
            .iter()
            .any(|denied| probed.starts_with(normalize_scope_path(denied)))
        {
            return false;
        }
        self.allow_write
            .iter()
            .any(|root| probed.starts_with(normalize_scope_path(root)))
    }

    /// Is `path` covered by an allow rule at all?
    pub fn in_read_scope(&self, path: &Path) -> bool {
        let probed = normalize_scope_path(path);
        if self
            .deny_read
            .iter()
            .any(|denied| probed.starts_with(normalize_scope_path(denied)))
        {
            return false;
        }
        let mut allowed = self.allow_read.iter().chain(self.allow_write.iter());
        allowed.any(|root| probed.starts_with(normalize_scope_path(root)))
    }
}

/// Collapse `.`, `..`, and redundant separators without touching the
/// filesystem (mirrors the loader's containment normalization).
fn lexical_normalize(path: &Path) -> PathBuf {
    use std::path::Component;
    let has_root = path.has_root();
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if !normalized.pop() && !has_root {
                    normalized.push(component.as_os_str());
                }
            }
            Component::Prefix(_) | Component::RootDir | Component::Normal(_) => {
                normalized.push(component.as_os_str());
            }
        }
    }
    normalized
}

/// Fail-closed normalization for scope decisions: resolve the longest
/// existing ancestor (follows symlink parents), then lexically normalize
/// the remainder. Pure lexical fallback when nothing exists, so `..`
/// escapes and symlink-parent escapes cannot evade the prefix comparison.
fn normalize_scope_path(path: &Path) -> PathBuf {
    if path.is_absolute() {
        let mut unresolved: Vec<std::ffi::OsString> = Vec::new();
        let mut cursor = path;
        loop {
            if let Ok(canonical) = std::fs::canonicalize(cursor) {
                let mut resolved = canonical;
                for component in unresolved.iter().rev() {
                    resolved.push(component);
                }
                return lexical_normalize(&resolved);
            }
            match (cursor.file_name(), cursor.parent()) {
                (Some(name), Some(parent)) if parent != cursor => {
                    unresolved.push(name.to_os_string());
                    cursor = parent;
                }
                _ => return lexical_normalize(path),
            }
        }
    } else {
        lexical_normalize(path)
    }
}

#[cfg(test)]
mod environment_tests {
    use super::EnvironmentPolicy;
    use std::ffi::OsStr;

    #[test]
    fn allowlist_is_exact_and_secrets_are_default_deny() {
        let policy = EnvironmentPolicy {
            pass_through: vec!["PATH".into(), "LC_*".into(), "SAFE_EXACT".into()],
            deny: vec!["LC_SECRET*".into()],
        };
        assert!(policy.allows(OsStr::new("PATH")));
        assert!(policy.allows(OsStr::new("LC_ALL")));
        assert!(!policy.allows(OsStr::new("LC_SECRET_VAL")));
        assert!(policy.allows(OsStr::new("SAFE_EXACT")));
        assert!(!policy.allows(OsStr::new("SAFE_EXACT_EXTRA")));
        for secret in [
            "GH_TOKEN",
            "OPENAI_API_KEY",
            "AWS_SECRET_ACCESS_KEY",
            "ANTHROPIC_API_KEY",
        ] {
            assert!(!policy.allows(OsStr::new(secret)), "leaked {secret}");
        }
    }
}