1use 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#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
20
21pub struct WritableRoot {
22 pub root: PathBuf,
24}
25
26impl WritableRoot {
27 #[must_use]
29 pub fn new(path: impl Into<PathBuf>) -> Self {
30 Self { root: path.into() }
31 }
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
38pub struct NetworkAllowlistEntry {
39 pub(crate) domain: String,
41 #[serde(default = "default_https_port")]
43 pub(crate) port: u16,
44 #[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 #[must_use]
60 pub fn domain(&self) -> &str {
61 &self.domain
62 }
63
64 #[must_use]
66 pub const fn port(&self) -> u16 {
67 self.port
68 }
69
70 #[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 #[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 #[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
106pub const DEFAULT_SENSITIVE_PATHS: &[&str] = &[
111 "~/.ssh",
113 "~/.aws",
115 "~/.config/gcloud",
117 "~/.azure",
119 "~/.kube",
121 "~/.docker",
123 "~/.npmrc",
125 "~/.pypirc",
127 "~/.config/gh",
129 "~/.secrets",
131 "~/.gnupg",
133 "~/.config/op",
135 "~/.vault-token",
137 "~/.terraform.d/credentials.tfrc.json",
139 "~/.cargo/credentials.toml",
141 "~/.git-credentials",
143 "~/.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#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
163pub struct SensitivePath {
164 path: String,
166 #[serde(default = "default_true")]
168 pub(crate) block_read: bool,
169 #[serde(default = "default_true")]
171 pub(crate) block_write: bool,
172}
173
174fn default_true() -> bool {
175 true
176}
177
178impl SensitivePath {
179 #[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 #[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 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 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
249pub 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
302const 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
352pub struct ResourceLimits {
353 #[serde(default)]
355 pub max_memory_mb: u64,
356
357 #[serde(default)]
360 pub max_pids: u32,
361
362 #[serde(default)]
364 pub max_disk_mb: u64,
365
366 #[serde(default)]
368 pub cpu_time_secs: u64,
369
370 #[serde(default)]
372 pub timeout_secs: u64,
373}
374
375impl Default for ResourceLimits {
376 fn default() -> Self {
377 Self {
378 max_memory_mb: 0, max_pids: 0, max_disk_mb: 0, cpu_time_secs: 0, timeout_secs: 300, }
384 }
385}
386
387impl ResourceLimits {
388 #[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 #[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 #[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 #[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 #[must_use]
439 fn with_memory_mb(mut self, mb: u64) -> Self {
440 self.max_memory_mb = mb;
441 self
442 }
443
444 #[must_use]
446 fn with_max_pids(mut self, pids: u32) -> Self {
447 self.max_pids = pids;
448 self
449 }
450
451 #[must_use]
453 pub fn with_disk_mb(mut self, mb: u64) -> Self {
454 self.max_disk_mb = mb;
455 self
456 }
457
458 #[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 #[must_use]
467 fn with_timeout_secs(mut self, secs: u64) -> Self {
468 self.timeout_secs = secs;
469 self
470 }
471
472 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
503#[serde(tag = "type", rename_all = "snake_case")]
504pub enum SandboxPolicy {
505 ReadOnly {
507 #[serde(default)]
509 network_access: bool,
510
511 #[serde(default)]
513 network_allowlist: Vec<NetworkAllowlistEntry>,
514 },
515
516 WorkspaceWrite {
518 writable_roots: Vec<WritableRoot>,
520
521 #[serde(default)]
523 network_access: bool,
524
525 #[serde(default)]
529 network_allowlist: Vec<NetworkAllowlistEntry>,
530
531 #[serde(default)]
535 sensitive_paths: Option<Vec<SensitivePath>>,
536
537 #[serde(default)]
540 resource_limits: ResourceLimits,
541
542 #[serde(default)]
545 seccomp_profile: SeccompProfile,
546
547 #[serde(default)]
549 exclude_tmpdir_env_var: bool,
550
551 #[serde(default)]
553 exclude_slash_tmp: bool,
554 },
555
556 DangerFullAccess,
559
560 ExternalSandbox {
562 description: String,
564 },
565}
566
567impl SandboxPolicy {
568 #[must_use]
570 pub fn read_only() -> Self {
571 Self::ReadOnly {
572 network_access: false,
573 network_allowlist: Vec::new(),
574 }
575 }
576
577 #[must_use]
579 pub fn new_read_only_policy() -> Self {
580 Self::read_only()
581 }
582
583 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[must_use]
707 pub fn full_access() -> Self {
708 Self::DangerFullAccess
709 }
710
711 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[inline]
849 #[must_use]
850 fn has_full_disk_write_access(&self) -> bool {
851 matches!(self, Self::DangerFullAccess | Self::ExternalSandbox { .. })
852 }
853
854 #[inline]
856 #[must_use]
857 fn has_full_disk_read_access(&self) -> bool {
858 true
859 }
860
861 #[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 #[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 fn can_set(&self, new_policy: &SandboxPolicy) -> anyhow::Result<()> {
900 use SandboxPolicy::*;
901
902 match (self, new_policy) {
903 (DangerFullAccess, _) => Ok(()),
905 (ReadOnly { .. }, WorkspaceWrite { .. } | DangerFullAccess) => {
907 Err(anyhow::anyhow!("cannot escalate from read-only to write-capable policy"))
908 }
909 _ => Ok(()),
911 }
912 }
913
914 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;