Skip to main content

vtcode_safety/sandboxing/policy/
mod.rs

1//! Sandbox policy definitions
2//!
3//! Defines the isolation levels for command execution, following the Codex model.
4//! Implements the "three-question model" from the AI sandbox field guide:
5//! - **Boundary**: What is shared between code and host (kernel-enforced via Seatbelt/Landlock)
6//! - **Policy**: What can code touch (files, network, devices, syscalls)
7//! - **Lifecycle**: What survives between runs (session-scoped approvals)
8
9use std::path::{Path, PathBuf};
10
11use serde::{Deserialize, Serialize};
12use vtcode_commons::VtCodePaths;
13
14mod seccomp;
15
16pub use seccomp::{BLOCKED_SYSCALLS, FILTERED_SYSCALLS, SECCOMP_PROFILE_VERSION, SeccompProfile};
17
18/// A root directory that may be written to under the sandbox policy.
19#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
20
21pub struct WritableRoot {
22    /// Absolute path to the writable directory.
23    pub root: PathBuf,
24}
25
26impl WritableRoot {
27    /// Create a new writable root from a path.
28    #[must_use]
29    pub fn new(path: impl Into<PathBuf>) -> Self {
30        Self { root: path.into() }
31    }
32}
33
34/// Network allowlist entry for domain-based egress control.
35///
36/// Following the field guide's recommendation: "Default-deny outbound network, then allowlist."
37#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
38pub struct NetworkAllowlistEntry {
39    /// Domain pattern (e.g., "api.github.com", "*.npmjs.org")
40    pub(crate) domain: String,
41    /// Optional port (defaults to 443 for HTTPS)
42    #[serde(default = "default_https_port")]
43    pub(crate) port: u16,
44    /// Protocol (tcp or udp, defaults to tcp)
45    #[serde(default = "default_protocol")]
46    pub(crate) protocol: String,
47}
48
49fn default_https_port() -> u16 {
50    443
51}
52
53fn default_protocol() -> String {
54    "tcp".to_string()
55}
56
57impl NetworkAllowlistEntry {
58    /// Domain pattern this entry allows.
59    #[must_use]
60    pub fn domain(&self) -> &str {
61        &self.domain
62    }
63
64    /// Port this entry allows.
65    #[must_use]
66    pub const fn port(&self) -> u16 {
67        self.port
68    }
69
70    /// Create a new allowlist entry for HTTPS access to a domain.
71    #[must_use]
72    pub fn https(domain: impl Into<String>) -> Self {
73        Self {
74            domain: domain.into(),
75            port: 443,
76            protocol: "tcp".to_string(),
77        }
78    }
79
80    /// Create a new allowlist entry with custom port.
81    #[must_use]
82    pub fn with_port(domain: impl Into<String>, port: u16) -> Self {
83        Self {
84            domain: domain.into(),
85            port,
86            protocol: "tcp".to_string(),
87        }
88    }
89
90    /// Check if a domain matches this entry (supports wildcard prefix).
91    #[inline]
92    fn matches(&self, domain: &str, port: u16) -> bool {
93        if self.port != port {
94            return false;
95        }
96        if self.domain.starts_with("*.") {
97            let suffix = self.domain.get(1..).unwrap_or_default();
98            let exact = self.domain.get(2..).unwrap_or_default();
99            domain.ends_with(suffix) || domain == exact
100        } else {
101            domain == self.domain
102        }
103    }
104}
105
106/// Default sensitive paths that should be blocked from sandboxed processes.
107///
108/// Following the field guide's warning about "policy leakage":
109/// "If your sandbox can read ~/.ssh or mount host volumes, it can leak credentials."
110pub const DEFAULT_SENSITIVE_PATHS: &[&str] = &[
111    // SSH keys and configuration
112    "~/.ssh",
113    // AWS credentials
114    "~/.aws",
115    // Google Cloud credentials
116    "~/.config/gcloud",
117    // Azure credentials
118    "~/.azure",
119    // Kubernetes config (contains cluster credentials)
120    "~/.kube",
121    // Docker config (may contain registry auth)
122    "~/.docker",
123    // NPM tokens
124    "~/.npmrc",
125    // PyPI tokens
126    "~/.pypirc",
127    // GitHub CLI tokens
128    "~/.config/gh",
129    // Generic secrets directory
130    "~/.secrets",
131    // Gnupg keys
132    "~/.gnupg",
133    // 1Password CLI
134    "~/.config/op",
135    // Vault tokens
136    "~/.vault-token",
137    // Terraform credentials
138    "~/.terraform.d/credentials.tfrc.json",
139    // Cargo registry tokens
140    "~/.cargo/credentials.toml",
141    // Git credentials
142    "~/.git-credentials",
143    // Netrc (may contain passwords)
144    "~/.netrc",
145];
146
147#[cfg(windows)]
148const USERPROFILE_READ_ROOT_EXCLUSIONS: &[&str] = &[
149    ".ssh",
150    ".gnupg",
151    ".aws",
152    ".azure",
153    ".kube",
154    ".docker",
155    ".config",
156    ".npm",
157    ".pki",
158    ".terraform.d",
159];
160
161/// Sensitive path entry for blocking access to credential locations.
162#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
163pub struct SensitivePath {
164    /// Path pattern (supports ~ for home directory)
165    path: String,
166    /// Whether to block read access (true by default)
167    #[serde(default = "default_true")]
168    pub(crate) block_read: bool,
169    /// Whether to block write access (true by default)
170    #[serde(default = "default_true")]
171    pub(crate) block_write: bool,
172}
173
174fn default_true() -> bool {
175    true
176}
177
178impl SensitivePath {
179    /// Create a new sensitive path entry that blocks both read and write.
180    #[must_use]
181    pub fn new(path: impl Into<String>) -> Self {
182        Self {
183            path: path.into(),
184            block_read: true,
185            block_write: true,
186        }
187    }
188
189    /// Create a sensitive path entry that only blocks write access.
190    #[must_use]
191    fn write_only(path: impl Into<String>) -> Self {
192        Self {
193            path: path.into(),
194            block_read: false,
195            block_write: true,
196        }
197    }
198
199    /// Expand ~ to the user's home directory.
200    pub fn expand_path(&self) -> PathBuf {
201        if self.path.starts_with("~/")
202            && let Some(home) = dirs::home_dir()
203        {
204            return home.join(self.path.get(2..).unwrap_or_default());
205        } else if self.path == "~"
206            && let Some(home) = dirs::home_dir()
207        {
208            return home;
209        }
210        PathBuf::from(&self.path)
211    }
212
213    /// Check if a given path matches this sensitive path pattern.
214    pub(crate) fn matches(&self, path: &Path) -> bool {
215        let expanded = self.expand_path();
216        #[cfg(windows)]
217        {
218            let path_norm = normalize_windows_path(path);
219            let expanded_norm = normalize_windows_path(&expanded);
220            let mut expanded_prefix = expanded_norm.clone();
221            if !expanded_prefix.ends_with('/') {
222                expanded_prefix.push('/');
223            }
224            path_norm == expanded_norm || path_norm.starts_with(&expanded_prefix)
225        }
226        #[cfg(not(windows))]
227        path_starts_with_case_insensitive(path, &expanded)
228    }
229}
230
231#[cfg(not(windows))]
232pub(crate) fn path_starts_with_case_insensitive(path: &Path, prefix: &Path) -> bool {
233    let mut path_components = path.components();
234    prefix.components().all(|prefix_component| {
235        path_components.next().is_some_and(|path_component| {
236            path_component
237                .as_os_str()
238                .to_string_lossy()
239                .eq_ignore_ascii_case(prefix_component.as_os_str().to_string_lossy().as_ref())
240        })
241    })
242}
243
244#[cfg(windows)]
245fn normalize_windows_path(path: &Path) -> String {
246    path.to_string_lossy().replace('\\', "/").to_ascii_lowercase()
247}
248
249/// Get the default sensitive paths as SensitivePath entries.
250pub fn default_sensitive_paths() -> Vec<SensitivePath> {
251    match vtcode_sensitive_paths(&[]) {
252        Ok(paths) => paths,
253        Err(error) => {
254            tracing::warn!(%error, "VT Code path resolution failed; blocking absolute paths fail-closed");
255            let mut paths: Vec<SensitivePath> =
256                DEFAULT_SENSITIVE_PATHS.iter().map(|p| SensitivePath::new(*p)).collect();
257            paths.push(SensitivePath::new("/"));
258            paths
259        }
260    }
261}
262
263fn vtcode_sensitive_paths(environment: &[(&str, &str)]) -> anyhow::Result<Vec<SensitivePath>> {
264    let resolved = if environment.is_empty() {
265        VtCodePaths::resolve()?
266    } else {
267        VtCodePaths::from_environment(environment)?
268    };
269    let mut paths: Vec<SensitivePath> = DEFAULT_SENSITIVE_PATHS.iter().map(|p| SensitivePath::new(*p)).collect();
270    let resolved_roots = [
271        resolved.config_dir().to_path_buf(),
272        resolved.auth_dir(),
273        resolved.data_dir().to_path_buf(),
274        resolved.state_dir().to_path_buf(),
275        resolved.cache_dir().to_path_buf(),
276        resolved.runtime_dir().to_path_buf(),
277        resolved.executable_dir().to_path_buf(),
278        resolved.legacy_dir().to_path_buf(),
279    ];
280    for root in resolved_roots {
281        let path = root.display().to_string();
282        if !paths.iter().any(|existing| existing.path == path) {
283            paths.push(SensitivePath::new(path));
284        }
285    }
286
287    #[cfg(windows)]
288    {
289        for entry in USERPROFILE_READ_ROOT_EXCLUSIONS {
290            let path = format!("~/{}", entry);
291            if !paths.iter().any(|existing| existing.path == path) {
292                paths.push(SensitivePath::new(path));
293            }
294        }
295        Ok(paths)
296    }
297
298    #[cfg(not(windows))]
299    Ok(paths)
300}
301
302/// Workspace-local directories that tools outside the sandbox execute or read
303/// as configuration. Every writable root keeps these read-only: `.git` hooks,
304/// agent configuration (`.codex`, `.vtcode`, `.agents`, `.claude`, `.cursor`,
305/// `.gemini`, `.windsurf`, `.opencode`, `.devin`) and editor settings
306/// (`.vscode`, `.idea`). Hooks, plugins, and workflows in these directories —
307/// and an editor's format-on-save formatter — run with the user's privileges
308/// *outside* the sandbox, so a sandboxed write there is still a host escape.
309///
310/// Keep this in sync with the tool-level protection in
311/// `vtcode_core::permissions::is_protected_write_path`. The tool layer keeps a
312/// narrow exception for authoring project skills under `.agents/skills/`; the
313/// OS sandbox cannot carve out a subtree from a writable root, so it protects
314/// the whole directory.
315const PROTECTED_WRITABLE_ROOT_DIR_NAMES: &[&str] = &[
316    ".git",
317    ".vtcode",
318    ".codex",
319    ".agents",
320    ".claude",
321    ".cursor",
322    ".gemini",
323    ".windsurf",
324    ".opencode",
325    ".devin",
326    ".vscode",
327    ".idea",
328];
329
330fn protected_writable_root_sensitive_paths(writable_roots: &[WritableRoot]) -> Vec<SensitivePath> {
331    let mut paths = Vec::new();
332
333    for root in writable_roots {
334        for dir_name in PROTECTED_WRITABLE_ROOT_DIR_NAMES {
335            let protected_path = root.root.join(dir_name).display().to_string();
336            if !paths.iter().any(|existing: &SensitivePath| {
337                existing.path == protected_path && !existing.block_read && existing.block_write
338            }) {
339                paths.push(SensitivePath::write_only(protected_path));
340            }
341        }
342    }
343
344    paths
345}
346
347/// Resource limits for sandboxed execution.
348///
349/// Following the field guide's recommendation for resource accounting:
350/// "CPU, memory, disk, timeouts, and PIDs."
351#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
352pub struct ResourceLimits {
353    /// Maximum memory usage in megabytes (0 = unlimited).
354    #[serde(default)]
355    pub max_memory_mb: u64,
356
357    /// Maximum number of processes/threads (0 = unlimited).
358    /// Prevents fork bombs.
359    #[serde(default)]
360    pub max_pids: u32,
361
362    /// Maximum disk write in megabytes (0 = unlimited).
363    #[serde(default)]
364    pub max_disk_mb: u64,
365
366    /// CPU time limit in seconds (0 = unlimited).
367    #[serde(default)]
368    pub cpu_time_secs: u64,
369
370    /// Wall clock timeout in seconds (0 = use default).
371    #[serde(default)]
372    pub timeout_secs: u64,
373}
374
375impl Default for ResourceLimits {
376    fn default() -> Self {
377        Self {
378            max_memory_mb: 0,  // Unlimited by default
379            max_pids: 0,       // Unlimited by default
380            max_disk_mb: 0,    // Unlimited by default
381            cpu_time_secs: 0,  // Unlimited by default
382            timeout_secs: 300, // 5 minute wall clock default
383        }
384    }
385}
386
387impl ResourceLimits {
388    /// Create new resource limits with all values unlimited.
389    #[must_use]
390    pub fn unlimited() -> Self {
391        Self {
392            max_memory_mb: 0,
393            max_pids: 0,
394            max_disk_mb: 0,
395            cpu_time_secs: 0,
396            timeout_secs: 0,
397        }
398    }
399
400    /// Create conservative limits suitable for untrusted code.
401    /// Following field guide: "Resource limits: CPU, memory, disk, timeouts, and PIDs."
402    #[must_use]
403    pub fn conservative() -> Self {
404        Self {
405            max_memory_mb: 512,
406            max_pids: 64,
407            max_disk_mb: 1024,
408            cpu_time_secs: 60,
409            timeout_secs: 120,
410        }
411    }
412
413    /// Create moderate limits for semi-trusted code.
414    #[must_use]
415    pub fn moderate() -> Self {
416        Self {
417            max_memory_mb: 2048,
418            max_pids: 256,
419            max_disk_mb: 4096,
420            cpu_time_secs: 300,
421            timeout_secs: 600,
422        }
423    }
424
425    /// Create generous limits for trusted internal code.
426    #[must_use]
427    pub fn generous() -> Self {
428        Self {
429            max_memory_mb: 8192,
430            max_pids: 1024,
431            max_disk_mb: 16384,
432            cpu_time_secs: 0,
433            timeout_secs: 3600,
434        }
435    }
436
437    /// Builder: set memory limit.
438    #[must_use]
439    fn with_memory_mb(mut self, mb: u64) -> Self {
440        self.max_memory_mb = mb;
441        self
442    }
443
444    /// Builder: set PID limit.
445    #[must_use]
446    fn with_max_pids(mut self, pids: u32) -> Self {
447        self.max_pids = pids;
448        self
449    }
450
451    /// Builder: set disk limit.
452    #[must_use]
453    pub fn with_disk_mb(mut self, mb: u64) -> Self {
454        self.max_disk_mb = mb;
455        self
456    }
457
458    /// Builder: set CPU time limit.
459    #[must_use]
460    pub fn with_cpu_time_secs(mut self, secs: u64) -> Self {
461        self.cpu_time_secs = secs;
462        self
463    }
464
465    /// Builder: set timeout.
466    #[must_use]
467    fn with_timeout_secs(mut self, secs: u64) -> Self {
468        self.timeout_secs = secs;
469        self
470    }
471
472    /// Check if any limits are set.
473    #[inline]
474    #[must_use]
475    fn has_limits(&self) -> bool {
476        self.max_memory_mb > 0
477            || self.max_pids > 0
478            || self.max_disk_mb > 0
479            || self.cpu_time_secs > 0
480            || self.timeout_secs > 0
481    }
482
483    /// Get the effective timeout in seconds.
484    #[inline]
485    #[must_use]
486    fn effective_timeout_secs(&self) -> u64 {
487        if self.timeout_secs > 0 { self.timeout_secs } else { 300 }
488    }
489}
490
491/// Sandbox policy determining what operations are permitted during execution.
492///
493/// This follows the Codex sandboxing model with three main variants:
494/// - **ReadOnly**: Only read operations allowed (safe for viewing files)
495/// - **WorkspaceWrite**: Can write within specified directories
496/// - **DangerFullAccess**: No restrictions (dangerous, requires explicit approval)
497///
498/// The field guide's three-question model:
499/// 1. What is shared between this code and the host? (boundary)
500/// 2. What can the code touch? (policy - this enum)
501/// 3. What survives between runs? (lifecycle)
502#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
503#[serde(tag = "type", rename_all = "snake_case")]
504pub enum SandboxPolicy {
505    /// No write access to the filesystem; network access may be restricted or allowlisted.
506    ReadOnly {
507        /// Whether network access is enabled when no allowlist is set.
508        #[serde(default)]
509        network_access: bool,
510
511        /// Domain-based network egress allowlist.
512        #[serde(default)]
513        network_allowlist: Vec<NetworkAllowlistEntry>,
514    },
515
516    /// Write access limited to the specified roots; network controlled by allowlist.
517    WorkspaceWrite {
518        /// Directories where write access is permitted.
519        writable_roots: Vec<WritableRoot>,
520
521        /// Whether network access is allowed (legacy boolean, use network_allowlist for fine-grained control).
522        #[serde(default)]
523        network_access: bool,
524
525        /// Domain-based network egress allowlist.
526        /// When non-empty, only connections to these destinations are permitted.
527        /// Following field guide: "Default-deny outbound network, then allowlist."
528        #[serde(default)]
529        network_allowlist: Vec<NetworkAllowlistEntry>,
530
531        /// Sensitive paths to block (credentials, SSH keys, cloud configs).
532        /// Following field guide: prevents "policy leakage" of credentials.
533        /// Defaults to DEFAULT_SENSITIVE_PATHS if None.
534        #[serde(default)]
535        sensitive_paths: Option<Vec<SensitivePath>>,
536
537        /// Resource limits (memory, PIDs, disk, CPU).
538        /// Following field guide: prevents fork bombs, memory exhaustion.
539        #[serde(default)]
540        resource_limits: ResourceLimits,
541
542        /// Seccomp-BPF profile for Linux syscall filtering.
543        /// Following field guide: "Landlock + seccomp is the recommended Linux pattern."
544        #[serde(default)]
545        seccomp_profile: SeccompProfile,
546
547        /// Exclude the TMPDIR environment variable from writable roots.
548        #[serde(default)]
549        exclude_tmpdir_env_var: bool,
550
551        /// Exclude /tmp from writable roots.
552        #[serde(default)]
553        exclude_slash_tmp: bool,
554    },
555
556    /// Full access - no sandbox restrictions applied.
557    /// Use with extreme caution.
558    DangerFullAccess,
559
560    /// External sandbox - the caller is responsible for sandbox setup.
561    ExternalSandbox {
562        /// Description of the external sandbox mechanism.
563        description: String,
564    },
565}
566
567impl SandboxPolicy {
568    /// Create a read-only policy.
569    #[must_use]
570    pub fn read_only() -> Self {
571        Self::ReadOnly {
572            network_access: false,
573            network_allowlist: Vec::new(),
574        }
575    }
576
577    /// Create a new read-only policy (alias for backwards compatibility).
578    #[must_use]
579    pub fn new_read_only_policy() -> Self {
580        Self::read_only()
581    }
582
583    /// Create a read-only policy with a network allowlist.
584    #[must_use]
585    pub fn read_only_with_network(network_allowlist: Vec<NetworkAllowlistEntry>) -> Self {
586        Self::ReadOnly {
587            network_access: !network_allowlist.is_empty(),
588            network_allowlist,
589        }
590    }
591
592    /// Create a read-only policy with full network access.
593    #[must_use]
594    pub fn read_only_with_full_network() -> Self {
595        Self::ReadOnly {
596            network_access: true,
597            network_allowlist: Vec::new(),
598        }
599    }
600
601    /// Create a workspace-write policy with specified roots.
602    /// Uses default sensitive path blocking and strict seccomp profile.
603    #[must_use]
604    pub fn workspace_write(writable_roots: Vec<PathBuf>) -> Self {
605        Self::WorkspaceWrite {
606            writable_roots: writable_roots.into_iter().map(WritableRoot::new).collect(),
607            network_access: false,
608            network_allowlist: Vec::new(),
609            sensitive_paths: None,
610            resource_limits: ResourceLimits::default(),
611            seccomp_profile: SeccompProfile::strict(),
612            exclude_tmpdir_env_var: true,
613            exclude_slash_tmp: true,
614        }
615    }
616
617    /// Create a workspace-write policy with network allowlist.
618    #[must_use]
619    fn workspace_write_with_network(
620        writable_roots: Vec<PathBuf>,
621        network_allowlist: Vec<NetworkAllowlistEntry>,
622    ) -> Self {
623        Self::WorkspaceWrite {
624            writable_roots: writable_roots.into_iter().map(WritableRoot::new).collect(),
625            network_access: !network_allowlist.is_empty(),
626            network_allowlist,
627            sensitive_paths: None,
628            resource_limits: ResourceLimits::default(),
629            seccomp_profile: SeccompProfile::strict().with_network(),
630            exclude_tmpdir_env_var: true,
631            exclude_slash_tmp: true,
632        }
633    }
634
635    /// Create a workspace-write policy with custom sensitive path settings.
636    #[must_use]
637    pub fn workspace_write_with_sensitive_paths(
638        writable_roots: Vec<PathBuf>,
639        sensitive_paths: Vec<SensitivePath>,
640    ) -> Self {
641        Self::WorkspaceWrite {
642            writable_roots: writable_roots.into_iter().map(WritableRoot::new).collect(),
643            network_access: false,
644            network_allowlist: Vec::new(),
645            sensitive_paths: Some(sensitive_paths),
646            resource_limits: ResourceLimits::default(),
647            seccomp_profile: SeccompProfile::strict(),
648            exclude_tmpdir_env_var: true,
649            exclude_slash_tmp: true,
650        }
651    }
652
653    /// Create a workspace-write policy without sensitive path blocking (dangerous).
654    #[must_use]
655    fn workspace_write_no_sensitive_blocking(writable_roots: Vec<PathBuf>) -> Self {
656        Self::WorkspaceWrite {
657            writable_roots: writable_roots.into_iter().map(WritableRoot::new).collect(),
658            network_access: false,
659            network_allowlist: Vec::new(),
660            sensitive_paths: Some(Vec::new()),
661            resource_limits: ResourceLimits::default(),
662            seccomp_profile: SeccompProfile::strict(),
663            exclude_tmpdir_env_var: true,
664            exclude_slash_tmp: true,
665        }
666    }
667
668    /// Create a workspace-write policy with resource limits.
669    /// Useful for untrusted code that needs containment.
670    #[must_use]
671    fn workspace_write_with_limits(writable_roots: Vec<PathBuf>, resource_limits: ResourceLimits) -> Self {
672        Self::WorkspaceWrite {
673            writable_roots: writable_roots.into_iter().map(WritableRoot::new).collect(),
674            network_access: false,
675            network_allowlist: Vec::new(),
676            sensitive_paths: None,
677            resource_limits,
678            seccomp_profile: SeccompProfile::strict(),
679            exclude_tmpdir_env_var: true,
680            exclude_slash_tmp: true,
681        }
682    }
683
684    /// Create a fully-configured workspace-write policy.
685    #[must_use]
686    pub fn workspace_write_full(
687        writable_roots: Vec<PathBuf>,
688        network_allowlist: Vec<NetworkAllowlistEntry>,
689        sensitive_paths: Option<Vec<SensitivePath>>,
690        resource_limits: ResourceLimits,
691        seccomp_profile: SeccompProfile,
692    ) -> Self {
693        Self::WorkspaceWrite {
694            writable_roots: writable_roots.into_iter().map(WritableRoot::new).collect(),
695            network_access: !network_allowlist.is_empty(),
696            network_allowlist,
697            sensitive_paths,
698            resource_limits,
699            seccomp_profile,
700            exclude_tmpdir_env_var: true,
701            exclude_slash_tmp: true,
702        }
703    }
704
705    /// Create a full-access policy (dangerous).
706    #[must_use]
707    pub fn full_access() -> Self {
708        Self::DangerFullAccess
709    }
710
711    /// Check if the policy allows full network access (unrestricted).
712    #[inline]
713    #[must_use]
714    pub fn has_full_network_access(&self) -> bool {
715        match self {
716            Self::ReadOnly { network_access, network_allowlist }
717            | Self::WorkspaceWrite { network_access, network_allowlist, .. } => {
718                *network_access && network_allowlist.is_empty()
719            }
720            Self::DangerFullAccess | Self::ExternalSandbox { .. } => true,
721        }
722    }
723
724    /// Check if the policy has a network allowlist (domain-restricted access).
725    #[inline]
726    #[must_use]
727    pub fn has_network_allowlist(&self) -> bool {
728        match self {
729            Self::ReadOnly { network_allowlist, .. } | Self::WorkspaceWrite { network_allowlist, .. } => {
730                !network_allowlist.is_empty()
731            }
732            _ => false,
733        }
734    }
735
736    /// Get the network allowlist entries, if any.
737    #[inline]
738    #[must_use]
739    pub fn network_allowlist(&self) -> &[NetworkAllowlistEntry] {
740        match self {
741            Self::ReadOnly { network_allowlist, .. } | Self::WorkspaceWrite { network_allowlist, .. } => {
742                network_allowlist
743            }
744            _ => &[],
745        }
746    }
747
748    /// Check if network access to a specific domain:port is allowed.
749    #[inline]
750    #[must_use]
751    pub fn is_network_allowed(&self, domain: &str, port: u16) -> bool {
752        match self {
753            Self::ReadOnly { network_access, network_allowlist }
754            | Self::WorkspaceWrite { network_access, network_allowlist, .. } => {
755                if network_allowlist.is_empty() {
756                    *network_access
757                } else {
758                    network_allowlist.iter().any(|entry| entry.matches(domain, port))
759                }
760            }
761            Self::DangerFullAccess | Self::ExternalSandbox { .. } => true,
762        }
763    }
764
765    /// Get the effective sensitive paths to block.
766    /// Returns default paths if not explicitly configured.
767    #[must_use]
768    fn sensitive_paths(&self) -> Vec<SensitivePath> {
769        match self {
770            Self::ReadOnly { .. } => default_sensitive_paths(),
771            Self::WorkspaceWrite { sensitive_paths, .. } => {
772                sensitive_paths.clone().unwrap_or_else(default_sensitive_paths)
773            }
774            Self::DangerFullAccess | Self::ExternalSandbox { .. } => Vec::new(),
775        }
776    }
777
778    /// Get sensitive paths including write-only protected directories for writable roots.
779    #[must_use]
780    pub(crate) fn sensitive_paths_for_execution(&self, cwd: &Path) -> Vec<SensitivePath> {
781        match self {
782            Self::WorkspaceWrite { .. } => {
783                let mut sensitive_paths = self.sensitive_paths();
784                sensitive_paths.extend(protected_writable_root_sensitive_paths(&self.get_writable_roots_with_cwd(cwd)));
785                sensitive_paths
786            }
787            _ => self.sensitive_paths(),
788        }
789    }
790
791    /// Check if a path is a sensitive location that should be blocked.
792    #[inline]
793    #[must_use]
794    fn is_sensitive_path(&self, path: &Path) -> bool {
795        self.sensitive_paths().iter().any(|sp| sp.matches(path) && sp.block_read)
796    }
797
798    /// Check if write access to a path is blocked under this policy.
799    #[inline]
800    #[must_use]
801    fn is_path_write_blocked(&self, path: &Path, cwd: &Path) -> bool {
802        match self {
803            Self::DangerFullAccess | Self::ExternalSandbox { .. } => false,
804            _ => self
805                .sensitive_paths_for_execution(cwd)
806                .iter()
807                .any(|sp| sp.matches(path) && sp.block_write),
808        }
809    }
810
811    /// Check if read access to a path is allowed under this policy.
812    #[inline]
813    #[must_use]
814    pub fn is_path_readable(&self, path: &Path) -> bool {
815        match self {
816            Self::DangerFullAccess | Self::ExternalSandbox { .. } => true,
817            _ => !self.is_sensitive_path(path),
818        }
819    }
820
821    /// Get the resource limits for this policy.
822    #[must_use]
823    pub fn resource_limits(&self) -> ResourceLimits {
824        match self {
825            Self::ReadOnly { .. } => ResourceLimits::conservative(),
826            Self::WorkspaceWrite { resource_limits, .. } => resource_limits.clone(),
827            Self::DangerFullAccess | Self::ExternalSandbox { .. } => ResourceLimits::unlimited(),
828        }
829    }
830
831    /// Get the seccomp profile for this policy (Linux only).
832    #[must_use]
833    pub fn seccomp_profile(&self) -> SeccompProfile {
834        match self {
835            Self::ReadOnly { network_access, network_allowlist } => {
836                let mut profile = SeccompProfile::strict();
837                if *network_access || !network_allowlist.is_empty() {
838                    profile = profile.with_network();
839                }
840                profile
841            }
842            Self::WorkspaceWrite { seccomp_profile, .. } => seccomp_profile.clone(),
843            Self::DangerFullAccess | Self::ExternalSandbox { .. } => SeccompProfile::permissive(),
844        }
845    }
846
847    /// Check if the policy allows full disk write access.
848    #[inline]
849    #[must_use]
850    fn has_full_disk_write_access(&self) -> bool {
851        matches!(self, Self::DangerFullAccess | Self::ExternalSandbox { .. })
852    }
853
854    /// Check if the policy allows full disk read access.
855    #[inline]
856    #[must_use]
857    fn has_full_disk_read_access(&self) -> bool {
858        true
859    }
860
861    /// Get the list of writable roots including the current working directory.
862    ///
863    /// Consumers that re-check canonical (symlink-resolved) paths use this to
864    /// build a policy whose roots are in the same representation.
865    #[must_use]
866    pub fn get_writable_roots_with_cwd(&self, cwd: &Path) -> Vec<WritableRoot> {
867        match self {
868            Self::ReadOnly { .. } => vec![],
869            Self::WorkspaceWrite { writable_roots, .. } => {
870                let mut roots = writable_roots.clone();
871                let cwd_root = WritableRoot::new(cwd);
872                if !roots.contains(&cwd_root) {
873                    roots.push(cwd_root);
874                }
875                roots
876            }
877            Self::DangerFullAccess | Self::ExternalSandbox { .. } => {
878                vec![WritableRoot::new(cwd)]
879            }
880        }
881    }
882
883    /// Check if a path is writable under this policy.
884    #[inline]
885    #[must_use]
886    pub fn is_path_writable(&self, path: &Path, cwd: &Path) -> bool {
887        match self {
888            Self::ReadOnly { .. } => false,
889            Self::WorkspaceWrite { .. } => {
890                let writable = self.get_writable_roots_with_cwd(cwd);
891                writable.iter().any(|root| path.starts_with(&root.root)) && !self.is_path_write_blocked(path, cwd)
892            }
893            Self::DangerFullAccess | Self::ExternalSandbox { .. } => true,
894        }
895    }
896
897    /// Validate that another policy can be set from this one.
898    /// Used to enforce policy escalation restrictions.
899    fn can_set(&self, new_policy: &SandboxPolicy) -> anyhow::Result<()> {
900        use SandboxPolicy::*;
901
902        match (self, new_policy) {
903            // Can always downgrade
904            (DangerFullAccess, _) => Ok(()),
905            // Cannot escalate from ReadOnly to write-capable
906            (ReadOnly { .. }, WorkspaceWrite { .. } | DangerFullAccess) => {
907                Err(anyhow::anyhow!("cannot escalate from read-only to write-capable policy"))
908            }
909            // Other transitions are allowed
910            _ => Ok(()),
911        }
912    }
913
914    /// Get a human-readable description of the policy.
915    pub fn description(&self) -> &'static str {
916        match self {
917            Self::ReadOnly { .. } => "read-only access",
918            Self::WorkspaceWrite { .. } => "workspace write access",
919            Self::DangerFullAccess => "full access (dangerous)",
920            Self::ExternalSandbox { .. } => "external sandbox",
921        }
922    }
923}
924
925impl Default for SandboxPolicy {
926    fn default() -> Self {
927        Self::read_only()
928    }
929}
930
931#[cfg(test)]
932mod tests;