返回 CodeWhale
policy.rs
根目录 / crates / sandbox / src / policy.rs
1 //! Sandbox policy definitions for command execution restrictions.
2 //!
3 //! This module defines the policies that control what resources a sandboxed
4 //! process can access. Policies range from full unrestricted access to
5 //! tightly controlled workspace-only write access.
6
7 use serde::{Deserialize, Serialize};
8 use std::fs;
9 use std::path::{Path, PathBuf};
10
11 #[cfg(test)]
12 use codewhale_execpolicy::command_safety::SafetyLevel;
13
14 /// Determines execution restrictions for shell commands.
15 ///
16 /// The sandbox policy controls filesystem access, network access, and other
17 /// system resources for executed commands. Choose the most restrictive policy
18 /// that still allows your command to function.
19 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20 #[serde(tag = "type", rename_all = "kebab-case")]
21 pub enum SandboxPolicy {
22 /// No restrictions whatsoever. Use with extreme caution.
23 ///
24 /// This policy disables all sandboxing and allows full system access.
25 /// Only use this when absolutely necessary and the command source is trusted.
26 #[serde(rename = "danger-full-access")]
27 DangerFullAccess,
28
29 /// Read-only access to the entire filesystem.
30 ///
31 /// The process can read any file but cannot write anywhere.
32 /// Useful for analysis tools that need broad read access.
33 #[serde(rename = "read-only")]
34 ReadOnly {
35 #[serde(default)]
36 network_access: bool,
37 },
38
39 /// Indicates the process is already running in an external sandbox.
40 ///
41 /// Use this when CodeWhale is itself running inside a container,
42 /// VM, or other sandboxed environment. This avoids double-sandboxing
43 /// which can cause issues.
44 #[serde(rename = "external-sandbox")]
45 ExternalSandbox {
46 /// Whether network access is allowed in the external sandbox.
47 #[serde(default)]
48 network_access: bool,
49 },
50
51 /// Read-only filesystem access plus write access to specified directories.
52 ///
53 /// This is the default and recommended policy. It allows:
54 /// - Read access to the entire filesystem (for tools, libraries, etc.)
55 /// - Write access only to the current working directory and specified roots
56 /// - Optional network access
57 #[serde(rename = "workspace-write")]
58 WorkspaceWrite {
59 /// Additional directories where writes are allowed.
60 #[serde(default, skip_serializing_if = "Vec::is_empty")]
61 writable_roots: Vec<PathBuf>,
62
63 /// Whether outbound network connections are permitted.
64 #[serde(default)]
65 network_access: bool,
66
67 /// Exclude TMPDIR from writable paths.
68 #[serde(default)]
69 exclude_tmpdir: bool,
70
71 /// Exclude /tmp from writable paths.
72 #[serde(default)]
73 exclude_slash_tmp: bool,
74 },
75 }
76
77 /// Execution boundary available to apply a sandbox policy for this session.
78 ///
79 /// The engine snapshots this once at construction so model-visible turn
80 /// metadata stays byte-stable even if a local wrapper is installed or removed
81 /// while the session is running. An external backend accepts a raw command and
82 /// delegates isolation to its service, so it must not inherit local
83 /// workspace/network enforcement claims.
84 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
85 pub enum SandboxEnforcement {
86 /// A local OS wrapper (Seatbelt or opt-in bubblewrap) is configured.
87 LocalOs,
88 /// Shell execution is routed to a configured external service.
89 ExternalBackend,
90 /// No local wrapper or external execution backend is available.
91 Unavailable,
92 }
93
94 impl Default for SandboxPolicy {
95 /// Returns the default policy: workspace-write with no extra roots and no network.
96 fn default() -> Self {
97 SandboxPolicy::WorkspaceWrite {
98 writable_roots: vec![],
99 network_access: false,
100 exclude_tmpdir: false,
101 exclude_slash_tmp: false,
102 }
103 }
104 }
105
106 pub const DEFAULT_DENY_GLOBS: &[&str] = &["~/.ssh", "~/.aws", ".env", ".env.*"];
107
108 const SANDBOX_OVERLAY_MAX_BYTES: usize = 64 * 1024;
109 const MAX_GLOB_WALK_DEPTH: usize = 8;
110 const MAX_GLOB_WALK_ENTRIES: usize = 16_384;
111
112 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
113 #[serde(rename_all = "kebab-case")]
114 pub enum SandboxProfile {
115 #[default]
116 Workspace,
117 ReadOnly,
118 Strict,
119 Off,
120 }
121
122 impl SandboxProfile {
123 #[must_use]
124 pub fn from_name(name: &str) -> Option<Self> {
125 match name.trim().to_ascii_lowercase().as_str() {
126 "workspace" | "workspace-write" => Some(Self::Workspace),
127 "read-only" | "readonly" => Some(Self::ReadOnly),
128 "strict" => Some(Self::Strict),
129 "off" | "danger-full-access" => Some(Self::Off),
130 _ => None,
131 }
132 }
133
134 #[must_use]
135 pub fn as_str(self) -> &'static str {
136 match self {
137 Self::Workspace => "workspace",
138 Self::ReadOnly => "read-only",
139 Self::Strict => "strict",
140 Self::Off => "off",
141 }
142 }
143
144 #[must_use]
145 pub fn to_policy(self) -> SandboxPolicy {
146 match self {
147 Self::Workspace => SandboxPolicy::default(),
148 Self::ReadOnly => SandboxPolicy::read_only(),
149 Self::Strict => SandboxPolicy::WorkspaceWrite {
150 writable_roots: vec![],
151 network_access: false,
152 exclude_tmpdir: true,
153 exclude_slash_tmp: true,
154 },
155 Self::Off => SandboxPolicy::DangerFullAccess,
156 }
157 }
158 }
159
160 #[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
161 pub struct SandboxOverlay {
162 #[serde(default)]
163 pub extends: Option<SandboxProfile>,
164 #[serde(default)]
165 pub restrict_network: Option<bool>,
166 #[serde(default)]
167 pub read_only: Vec<PathBuf>,
168 #[serde(default)]
169 pub read_write: Vec<PathBuf>,
170 #[serde(default)]
171 pub deny: Vec<String>,
172 }
173
174 #[derive(Debug, Clone, PartialEq, Eq)]
175 pub struct ResolvedSandboxOverlay {
176 pub profile: SandboxProfile,
177 pub policy: SandboxPolicy,
178 pub read_only_paths: Vec<PathBuf>,
179 pub deny_globs: Vec<String>,
180 }
181
182 impl SandboxOverlay {
183 pub fn load_from_workspace(cwd: &Path) -> Result<Option<Self>, String> {
184 use std::io::Read as _;
185 let cw_dir = cwd.join(".codewhale");
186 let dir_meta = match fs::symlink_metadata(&cw_dir) {
187 Ok(meta) => meta,
188 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
189 Err(err) => return Err(format!("failed to inspect {}: {err}", cw_dir.display())),
190 };
191 if dir_meta.file_type().is_symlink() || !dir_meta.file_type().is_dir() {
192 return Err(format!("{} must be a real directory", cw_dir.display()));
193 }
194 let path = cw_dir.join("sandbox.toml");
195 let metadata = match fs::symlink_metadata(&path) {
196 Ok(meta) => meta,
197 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
198 Err(err) => return Err(format!("failed to inspect {}: {err}", path.display())),
199 };
200 if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
201 return Err(format!("{} must be a regular file", path.display()));
202 }
203 let file = fs::File::open(&path)
204 .map_err(|err| format!("failed to read {}: {err}", path.display()))?;
205 let mut raw = String::new();
206 file.take((SANDBOX_OVERLAY_MAX_BYTES + 1) as u64)
207 .read_to_string(&mut raw)
208 .map_err(|err| format!("failed to read {}: {err}", path.display()))?;
209 if raw.len() > SANDBOX_OVERLAY_MAX_BYTES {
210 return Err(format!(
211 "{} exceeds the {} byte limit",
212 path.display(),
213 SANDBOX_OVERLAY_MAX_BYTES
214 ));
215 }
216 Self::parse_toml(&raw).map(Some)
217 }
218
219 pub fn parse_toml(src: &str) -> Result<Self, String> {
220 let mut overlay = Self::default();
221 let mut lines = src.lines().enumerate().peekable();
222 while let Some((line_no, raw_line)) = lines.next() {
223 let line = strip_toml_comment(raw_line).trim();
224 if line.is_empty() {
225 continue;
226 }
227 let Some((raw_key, raw_value)) = line.split_once('=') else {
228 return Err(format!(
229 "sandbox.toml:{}: expected `key = value`",
230 line_no + 1
231 ));
232 };
233 let key = raw_key.trim();
234 let mut value = raw_value.trim().to_string();
235 if value.starts_with('[') && !array_is_closed(&value) {
236 for (_, next_raw) in lines.by_ref() {
237 let next_trimmed = strip_toml_comment(next_raw).trim();
238 if next_trimmed.is_empty() {
239 continue;
240 }
241 value.push(' ');
242 value.push_str(next_trimmed);
243 if array_is_closed(&value) {
244 break;
245 }
246 }
247 }
248 match key {
249 "extends" => {
250 let s = parse_toml_string(&value)
251 .map_err(|e| format!("sandbox.toml:{}: extends: {e}", line_no + 1))?;
252 let profile = SandboxProfile::from_name(&s).ok_or_else(|| {
253 format!(
254 "sandbox.toml:{}: unknown sandbox profile `{s}` (expected workspace, read-only, strict, or off)",
255 line_no + 1
256 )
257 })?;
258 overlay.extends = Some(profile);
259 }
260 "restrict_network" => match value.as_str() {
261 "true" => overlay.restrict_network = Some(true),
262 "false" => overlay.restrict_network = Some(false),
263 _ => {
264 return Err(format!(
265 "sandbox.toml:{}: restrict_network must be true or false",
266 line_no + 1
267 ));
268 }
269 },
270 "read_only" => {
271 let items = parse_toml_string_array(&value)
272 .map_err(|e| format!("sandbox.toml:{}: read_only: {e}", line_no + 1))?;
273 for item in &items {
274 reject_control_chars(item)
275 .map_err(|e| format!("sandbox.toml:{}: read_only: {e}", line_no + 1))?;
276 }
277 overlay.read_only = items.into_iter().map(PathBuf::from).collect();
278 }
279 "read_write" => {
280 let items = parse_toml_string_array(&value)
281 .map_err(|e| format!("sandbox.toml:{}: read_write: {e}", line_no + 1))?;
282 for item in &items {
283 reject_control_chars(item).map_err(|e| {
284 format!("sandbox.toml:{}: read_write: {e}", line_no + 1)
285 })?;
286 }
287 overlay.read_write = items.into_iter().map(PathBuf::from).collect();
288 }
289 "deny" => {
290 let items = parse_toml_string_array(&value)
291 .map_err(|e| format!("sandbox.toml:{}: deny: {e}", line_no + 1))?;
292 for item in &items {
293 reject_control_chars(item)
294 .map_err(|e| format!("sandbox.toml:{}: deny: {e}", line_no + 1))?;
295 }
296 overlay.deny = items;
297 }
298 _ => {
299 return Err(format!(
300 "sandbox.toml:{}: unsupported key `{key}`",
301 line_no + 1
302 ));
303 }
304 }
305 }
306 Ok(overlay)
307 }
308
309 #[must_use]
310 pub fn resolve(&self, fallback: SandboxProfile, cwd: &Path) -> ResolvedSandboxOverlay {
311 let profile = self.extends.unwrap_or(fallback);
312 let base_policy = profile.to_policy();
313 base_policy.apply_workspace_overlay_with_profile(self, profile, cwd)
314 }
315 }
316
317 fn strip_toml_comment(line: &str) -> &str {
318 let mut in_double = false;
319 let mut in_single = false;
320 let mut escaped = false;
321 for (idx, ch) in line.char_indices() {
322 if escaped {
323 escaped = false;
324 continue;
325 }
326 if in_double {
327 if ch == '\\' {
328 escaped = true;
329 } else if ch == '"' {
330 in_double = false;
331 }
332 } else if in_single {
333 if ch == '\'' {
334 in_single = false;
335 }
336 } else {
337 match ch {
338 '"' => in_double = true,
339 '\'' => in_single = true,
340 '#' => return &line[..idx],
341 _ => {}
342 }
343 }
344 }
345 line
346 }
347
348 fn array_is_closed(value: &str) -> bool {
349 let mut in_double = false;
350 let mut in_single = false;
351 let mut escaped = false;
352 let mut depth = 0usize;
353 for ch in value.chars() {
354 if escaped {
355 escaped = false;
356 continue;
357 }
358 if in_double {
359 if ch == '\\' {
360 escaped = true;
361 } else if ch == '"' {
362 in_double = false;
363 }
364 } else if in_single {
365 if ch == '\'' {
366 in_single = false;
367 }
368 } else {
369 match ch {
370 '"' => in_double = true,
371 '\'' => in_single = true,
372 '[' => depth += 1,
373 ']' => depth = depth.saturating_sub(1),
374 _ => {}
375 }
376 }
377 }
378 !in_double && !in_single && depth == 0 && value.trim_end().ends_with(']')
379 }
380
381 fn parse_toml_string(raw: &str) -> Result<String, String> {
382 let trimmed = raw.trim();
383 if let Some(inner) = trimmed
384 .strip_prefix('\'')
385 .and_then(|s| s.strip_suffix('\''))
386 {
387 return Ok(inner.to_string());
388 }
389 if let Some(inner) = trimmed.strip_prefix('"').and_then(|s| s.strip_suffix('"')) {
390 let mut out = String::with_capacity(inner.len());
391 let mut chars = inner.chars();
392 while let Some(ch) = chars.next() {
393 if ch == '\\' {
394 match chars.next() {
395 Some('"') => out.push('"'),
396 Some('\\') => out.push('\\'),
397 Some('n') => out.push('\n'),
398 Some('t') => out.push('\t'),
399 Some('r') => out.push('\r'),
400 Some(other) => {
401 out.push('\\');
402 out.push(other);
403 }
404 None => return Err("unterminated escape sequence".to_string()),
405 }
406 } else {
407 out.push(ch);
408 }
409 }
410 return Ok(out);
411 }
412 Err("expected quoted string".to_string())
413 }
414
415 fn parse_toml_string_array(raw: &str) -> Result<Vec<String>, String> {
416 let trimmed = raw.trim();
417 let Some(inner) = trimmed.strip_prefix('[').and_then(|s| s.strip_suffix(']')) else {
418 return Err("expected array `[...]`".to_string());
419 };
420 let mut items = Vec::new();
421 let mut current = String::new();
422 let mut in_double = false;
423 let mut in_single = false;
424 let mut escaped = false;
425 for ch in inner.chars() {
426 if escaped {
427 current.push(ch);
428 escaped = false;
429 continue;
430 }
431 if in_double {
432 current.push(ch);
433 if ch == '\\' {
434 escaped = true;
435 } else if ch == '"' {
436 in_double = false;
437 }
438 } else if in_single {
439 current.push(ch);
440 if ch == '\'' {
441 in_single = false;
442 }
443 } else {
444 match ch {
445 '"' => {
446 in_double = true;
447 current.push(ch);
448 }
449 '\'' => {
450 in_single = true;
451 current.push(ch);
452 }
453 ',' => {
454 let token = current.trim();
455 if !token.is_empty() {
456 items.push(parse_toml_string(token)?);
457 }
458 current.clear();
459 }
460 _ => current.push(ch),
461 }
462 }
463 }
464 let tail = current.trim();
465 if !tail.is_empty() {
466 items.push(parse_toml_string(tail)?);
467 }
468 Ok(items)
469 }
470
471 fn reject_control_chars(value: &str) -> Result<(), String> {
472 if value.chars().any(|ch| ch.is_control()) {
473 return Err("control characters are not permitted".to_string());
474 }
475 Ok(())
476 }
477
478 pub(crate) fn canonical_or_self(path: &Path) -> PathBuf {
479 path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
480 }
481
482 fn lexically_normalize(path: &Path) -> PathBuf {
483 use std::path::Component;
484 let mut normalized = PathBuf::new();
485 for component in path.components() {
486 match component {
487 Component::CurDir => {}
488 Component::ParentDir => {
489 normalized.pop();
490 }
491 other => normalized.push(other.as_os_str()),
492 }
493 }
494 normalized
495 }
496
497 fn resolve_confined_workspace_path(path: &Path, cwd: &Path) -> Option<PathBuf> {
498 let canonical_cwd = canonical_or_self(cwd);
499 let expanded = expand_overlay_home(path);
500 let joined = if expanded.is_absolute() {
501 expanded
502 } else {
503 canonical_cwd.join(expanded)
504 };
505 let candidate = if joined.exists() {
506 canonical_or_self(&joined)
507 } else {
508 lexically_normalize(&joined)
509 };
510 (candidate != Path::new("/") && candidate.starts_with(&canonical_cwd)).then_some(candidate)
511 }
512
513 fn resolve_overlay_path(path: &Path, cwd: &Path) -> PathBuf {
514 let expanded = expand_overlay_home(path);
515 if expanded.is_absolute() {
516 expanded
517 } else {
518 canonical_or_self(cwd).join(expanded)
519 }
520 }
521
522 fn expand_overlay_home(path: &Path) -> PathBuf {
523 let Some(text) = path.to_str() else {
524 return path.to_path_buf();
525 };
526 if text == "~" {
527 return resolve_home_dir().unwrap_or_else(|| path.to_path_buf());
528 }
529 if let Some(rest) = text.strip_prefix("~/")
530 && let Some(home) = resolve_home_dir()
531 {
532 return home.join(rest);
533 }
534 path.to_path_buf()
535 }
536
537 fn resolve_home_dir() -> Option<PathBuf> {
538 if let Ok(home) = std::env::var("HOME")
539 && !home.trim().is_empty()
540 {
541 return Some(PathBuf::from(home));
542 }
543 dirs::home_dir()
544 }
545
546 fn has_glob_meta(pattern: &str) -> bool {
547 pattern.contains('*') || pattern.contains('?')
548 }
549
550 #[must_use]
551 pub fn glob_matches(pattern: &str, text: &str) -> bool {
552 let p: Vec<char> = pattern.chars().collect();
553 let t: Vec<char> = text.chars().collect();
554 glob_match_slice(&p, &t)
555 }
556
557 fn glob_match_slice(pattern: &[char], text: &[char]) -> bool {
558 if pattern.is_empty() {
559 return text.is_empty();
560 }
561 if pattern.len() >= 2 && pattern[0] == '*' && pattern[1] == '*' {
562 let mut rest = &pattern[2..];
563 if rest.first() == Some(&'/') {
564 rest = &rest[1..];
565 if glob_match_slice(rest, text) {
566 return true;
567 }
568 for i in 0..text.len() {
569 if text[i] == '/' && glob_match_slice(rest, &text[i + 1..]) {
570 return true;
571 }
572 }
573 return false;
574 }
575 for i in 0..=text.len() {
576 if glob_match_slice(rest, &text[i..]) {
577 return true;
578 }
579 }
580 return false;
581 }
582 match pattern[0] {
583 '*' => {
584 if glob_match_slice(&pattern[1..], text) {
585 return true;
586 }
587 for (i, ch) in text.iter().enumerate() {
588 if *ch == '/' {
589 break;
590 }
591 if glob_match_slice(&pattern[1..], &text[i + 1..]) {
592 return true;
593 }
594 }
595 false
596 }
597 '?' => !text.is_empty() && text[0] != '/' && glob_match_slice(&pattern[1..], &text[1..]),
598 ch => !text.is_empty() && text[0] == ch && glob_match_slice(&pattern[1..], &text[1..]),
599 }
600 }
601
602 fn push_sbpl_regex_literal(out: &mut String, literal: &str) {
603 for ch in literal.chars() {
604 match ch {
605 '.' | '+' | '*' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '^' | '$' | '|' | '\\' => {
606 out.push('\\');
607 out.push(ch);
608 }
609 _ => out.push(ch),
610 }
611 }
612 }
613
614 fn push_sbpl_regex_glob(out: &mut String, pattern: &str) {
615 let chars: Vec<char> = pattern.chars().collect();
616 let mut idx = 0;
617 while idx < chars.len() {
618 if chars[idx] == '*' && idx + 1 < chars.len() && chars[idx + 1] == '*' {
619 if idx + 2 < chars.len() && chars[idx + 2] == '/' {
620 out.push_str("(.*/)?");
621 idx += 3;
622 } else {
623 out.push_str(".*");
624 idx += 2;
625 }
626 continue;
627 }
628 match chars[idx] {
629 '*' => out.push_str("[^/]*"),
630 '?' => out.push_str("[^/]"),
631 '.' | '+' | '(' | ')' | '[' | ']' | '{' | '}' | '^' | '$' | '|' | '\\' => {
632 out.push('\\');
633 out.push(chars[idx]);
634 }
635 ch => out.push(ch),
636 }
637 idx += 1;
638 }
639 }
640
641 #[must_use]
642 pub fn glob_to_sbpl_regex(pattern: &str, cwd: &Path) -> Option<String> {
643 let trimmed = pattern.trim();
644 if trimmed.is_empty() || trimmed.chars().any(|ch| ch.is_control()) {
645 return None;
646 }
647 let normalized = trimmed.replace('\\', "/");
648 let mut regex = String::from("^");
649 if normalized == "~" {
650 let home = canonical_or_self(&resolve_home_dir()?);
651 let home_str = home.to_string_lossy();
652 push_sbpl_regex_literal(&mut regex, home_str.trim_end_matches(['/', '\\']));
653 } else if let Some(rest) = normalized.strip_prefix("~/") {
654 let home = canonical_or_self(&resolve_home_dir()?);
655 let home_str = home.to_string_lossy();
656 let trimmed_home = home_str.trim_end_matches(['/', '\\']);
657 push_sbpl_regex_literal(&mut regex, trimmed_home);
658 regex.push('/');
659 push_sbpl_regex_glob(&mut regex, rest.trim_start_matches("./"));
660 } else if normalized.starts_with('/') {
661 push_sbpl_regex_glob(&mut regex, &normalized);
662 } else {
663 let base = canonical_or_self(cwd);
664 let base_str = base.to_string_lossy();
665 let trimmed_base = base_str.trim_end_matches(['/', '\\']);
666 push_sbpl_regex_literal(&mut regex, trimmed_base);
667 regex.push('/');
668 push_sbpl_regex_glob(&mut regex, normalized.trim_start_matches("./"));
669 }
670 if !has_glob_meta(&normalized) {
671 regex.push_str("(/.*)?");
672 }
673 regex.push('$');
674 Some(regex)
675 }
676
677 #[must_use]
678 pub fn expand_deny_globs_in_workspace(globs: &[String], cwd: &Path) -> Vec<PathBuf> {
679 let mut matched = Vec::new();
680 let canonical_cwd = canonical_or_self(cwd);
681 for raw in globs {
682 let pattern = raw.trim();
683 if pattern.is_empty() {
684 continue;
685 }
686 let normalized = pattern.replace('\\', "/");
687 if !has_glob_meta(&normalized) {
688 let path = resolve_overlay_path(Path::new(pattern), &canonical_cwd);
689 if path.exists() && !matched.contains(&path) {
690 matched.push(path);
691 }
692 continue;
693 }
694 let (base_dir, raw_rel) = if let Some(rest) = normalized.strip_prefix("~/") {
695 let Some(home) = resolve_home_dir() else {
696 continue;
697 };
698 (canonical_or_self(&home), rest)
699 } else if let Some(rest) = normalized.strip_prefix('/') {
700 (PathBuf::from("/"), rest)
701 } else {
702 (canonical_cwd.clone(), normalized.as_str())
703 };
704 let rel_pattern = raw_rel.trim_start_matches("./");
705 let static_prefix = static_relative_glob_prefix(rel_pattern);
706 let search_root = if static_prefix.as_os_str().is_empty() {
707 base_dir.clone()
708 } else {
709 base_dir.join(&static_prefix)
710 };
711 if !search_root.exists() {
712 continue;
713 }
714 let mut visited = 0usize;
715 walk_and_match_glob(
716 &search_root,
717 &base_dir,
718 rel_pattern,
719 0,
720 &mut visited,
721 &mut matched,
722 );
723 }
724 matched
725 }
726
727 fn static_relative_glob_prefix(pattern: &str) -> PathBuf {
728 let mut prefix = PathBuf::new();
729 for part in pattern.split('/') {
730 if part.is_empty() || part == "." {
731 continue;
732 }
733 if has_glob_meta(part) {
734 break;
735 }
736 prefix.push(part);
737 }
738 prefix
739 }
740
741 fn walk_and_match_glob(
742 dir: &Path,
743 base_dir: &Path,
744 pattern: &str,
745 depth: usize,
746 visited: &mut usize,
747 matched: &mut Vec<PathBuf>,
748 ) {
749 if depth > MAX_GLOB_WALK_DEPTH || *visited >= MAX_GLOB_WALK_ENTRIES {
750 return;
751 }
752 let Ok(entries) = fs::read_dir(dir) else {
753 return;
754 };
755 for entry in entries.flatten() {
756 if *visited >= MAX_GLOB_WALK_ENTRIES {
757 break;
758 }
759 *visited += 1;
760 let path = entry.path();
761 if let Ok(rel) = path.strip_prefix(base_dir) {
762 let candidate = rel.to_string_lossy().replace('\\', "/");
763 if glob_matches(pattern, &candidate) && !matched.contains(&path) {
764 matched.push(path.clone());
765 }
766 }
767 if let Ok(ft) = entry.file_type()
768 && ft.is_dir()
769 && !ft.is_symlink()
770 {
771 walk_and_match_glob(&path, base_dir, pattern, depth + 1, visited, matched);
772 }
773 }
774 }
775
776 impl SandboxPolicy {
777 #[must_use]
778 pub fn from_profile(profile: SandboxProfile) -> Self {
779 profile.to_policy()
780 }
781
782 #[must_use]
783 pub fn apply_workspace_overlay(
784 &self,
785 overlay: &SandboxOverlay,
786 cwd: &Path,
787 ) -> ResolvedSandboxOverlay {
788 let base_profile = match self {
789 SandboxPolicy::DangerFullAccess => SandboxProfile::Off,
790 SandboxPolicy::ReadOnly { .. } => SandboxProfile::ReadOnly,
791 SandboxPolicy::WorkspaceWrite {
792 exclude_tmpdir: true,
793 exclude_slash_tmp: true,
794 network_access: false,
795 ..
796 } => SandboxProfile::Strict,
797 SandboxPolicy::WorkspaceWrite { .. } | SandboxPolicy::ExternalSandbox { .. } => {
798 SandboxProfile::Workspace
799 }
800 };
801 let (profile, base) = match (self, overlay.extends) {
802 (SandboxPolicy::DangerFullAccess, Some(requested)) => {
803 (requested, requested.to_policy())
804 }
805 (SandboxPolicy::ReadOnly { .. }, _) => (SandboxProfile::ReadOnly, self.clone()),
806 (SandboxPolicy::WorkspaceWrite { .. }, Some(SandboxProfile::ReadOnly)) => (
807 SandboxProfile::ReadOnly,
808 SandboxProfile::ReadOnly.to_policy(),
809 ),
810 (
811 SandboxPolicy::WorkspaceWrite { writable_roots, .. },
812 Some(SandboxProfile::Strict),
813 ) => (
814 SandboxProfile::Strict,
815 SandboxPolicy::WorkspaceWrite {
816 writable_roots: writable_roots.clone(),
817 network_access: false,
818 exclude_tmpdir: true,
819 exclude_slash_tmp: true,
820 },
821 ),
822 _ => (base_profile, self.clone()),
823 };
824 base.apply_workspace_overlay_with_profile(overlay, profile, cwd)
825 }
826
827 fn apply_workspace_overlay_with_profile(
828 &self,
829 overlay: &SandboxOverlay,
830 profile: SandboxProfile,
831 cwd: &Path,
832 ) -> ResolvedSandboxOverlay {
833 let mut policy = self.clone();
834 if overlay.restrict_network == Some(true) {
835 match &mut policy {
836 SandboxPolicy::WorkspaceWrite { network_access, .. }
837 | SandboxPolicy::ReadOnly { network_access }
838 | SandboxPolicy::ExternalSandbox { network_access } => {
839 *network_access = false;
840 }
841 SandboxPolicy::DangerFullAccess => {}
842 }
843 }
844 if !overlay.read_write.is_empty()
845 && let SandboxPolicy::WorkspaceWrite { writable_roots, .. } = &mut policy
846 {
847 for path in &overlay.read_write {
848 if let Some(resolved) = resolve_confined_workspace_path(path, cwd)
849 && !writable_roots.contains(&resolved)
850 {
851 writable_roots.push(resolved);
852 }
853 }
854 }
855 let read_only_paths: Vec<PathBuf> = overlay
856 .read_only
857 .iter()
858 .filter(|p| !p.to_string_lossy().chars().any(|ch| ch.is_control()))
859 .map(|p| resolve_overlay_path(p, cwd))
860 .collect();
861 let mut deny_globs = Vec::new();
862 if policy.should_sandbox() {
863 for default_glob in DEFAULT_DENY_GLOBS {
864 deny_globs.push((*default_glob).to_string());
865 }
866 }
867 for custom in &overlay.deny {
868 let trimmed = custom.trim();
869 if !trimmed.is_empty()
870 && !trimmed.chars().any(|ch| ch.is_control())
871 && !deny_globs.iter().any(|existing| existing == trimmed)
872 {
873 deny_globs.push(trimmed.to_string());
874 }
875 }
876 ResolvedSandboxOverlay {
877 profile,
878 policy,
879 read_only_paths,
880 deny_globs,
881 }
882 }
883
884 pub fn config_value(&self) -> &'static str {
885 match self {
886 SandboxPolicy::ReadOnly { .. } => "read-only",
887 SandboxPolicy::WorkspaceWrite { .. } => "workspace-write",
888 SandboxPolicy::DangerFullAccess => "danger-full-access",
889 SandboxPolicy::ExternalSandbox { .. } => "external-sandbox",
890 }
891 }
892
893 pub fn read_only() -> Self {
894 SandboxPolicy::ReadOnly {
895 network_access: false,
896 }
897 }
898
899 /// Create a workspace-write policy with network access enabled.
900 pub fn workspace_with_network() -> Self {
901 SandboxPolicy::WorkspaceWrite {
902 writable_roots: vec![],
903 network_access: true,
904 exclude_tmpdir: false,
905 exclude_slash_tmp: false,
906 }
907 }
908
909 /// Create a workspace-write policy with additional writable directories.
910 pub fn workspace_with_roots(roots: Vec<PathBuf>, network: bool) -> Self {
911 SandboxPolicy::WorkspaceWrite {
912 writable_roots: roots,
913 network_access: network,
914 exclude_tmpdir: false,
915 exclude_slash_tmp: false,
916 }
917 }
918
919 /// Returns true if the policy allows writing to any file on the filesystem.
920 pub fn has_full_disk_write_access(&self) -> bool {
921 matches!(
922 self,
923 SandboxPolicy::DangerFullAccess | SandboxPolicy::ExternalSandbox { .. }
924 )
925 }
926
927 /// Returns true if the policy allows outbound network connections.
928 pub fn has_network_access(&self) -> bool {
929 match self {
930 SandboxPolicy::DangerFullAccess => true,
931 SandboxPolicy::ReadOnly { network_access }
932 | SandboxPolicy::ExternalSandbox { network_access }
933 | SandboxPolicy::WorkspaceWrite { network_access, .. } => *network_access,
934 }
935 }
936
937 /// Returns true if the sandbox should be applied (not bypassed).
938 pub fn should_sandbox(&self) -> bool {
939 !matches!(
940 self,
941 SandboxPolicy::DangerFullAccess | SandboxPolicy::ExternalSandbox { .. }
942 )
943 }
944
945 /// Compact, deterministic posture label for model- and user-facing
946 /// surfaces (`<turn_meta>`, sandbox-denial hints). Byte-stable for a
947 /// given policy so per-turn metadata stays cache-friendly.
948 #[must_use]
949 pub fn posture_label(&self) -> String {
950 match self {
951 SandboxPolicy::DangerFullAccess => "full access (sandbox disabled)".to_string(),
952 SandboxPolicy::ReadOnly { network_access } => format!(
953 "read-only (shell writes are blocked;{} ordinary approval does not change this)",
954 if *network_access {
955 " network allowed;"
956 } else {
957 ""
958 }
959 ),
960 SandboxPolicy::ExternalSandbox { network_access } => format!(
961 "external sandbox (host-managed; network {})",
962 if *network_access {
963 "allowed"
964 } else {
965 "blocked"
966 }
967 ),
968 SandboxPolicy::WorkspaceWrite {
969 writable_roots,
970 network_access,
971 ..
972 } => format!(
973 "workspace-write (writes inside the workspace{}; network {})",
974 if writable_roots.len() > 1 {
975 " and approved roots"
976 } else {
977 ""
978 },
979 if *network_access {
980 "allowed"
981 } else {
982 "blocked"
983 }
984 ),
985 }
986 }
987
988 /// Render the policy together with the session-pinned execution boundary.
989 ///
990 /// Local wrappers may truthfully retain the policy's concrete filesystem
991 /// and network claims. External backends receive a raw command and delegate
992 /// isolation to their service, so their label names only the requested
993 /// policy and explicitly leaves the actual boundary unverified. When no
994 /// backend exists, restrictive policies are identified as policy-only.
995 #[must_use]
996 pub fn posture_label_with_enforcement(&self, enforcement: SandboxEnforcement) -> String {
997 if enforcement == SandboxEnforcement::ExternalBackend {
998 let requested_policy = match self {
999 SandboxPolicy::DangerFullAccess => "full-access",
1000 SandboxPolicy::ReadOnly { .. } => "read-only",
1001 SandboxPolicy::ExternalSandbox { .. } => "external-sandbox",
1002 SandboxPolicy::WorkspaceWrite { .. } => "workspace-write",
1003 };
1004 return format!(
1005 "{requested_policy} policy (external execution backend configured; filesystem/network isolation unverified by Codewhale)"
1006 );
1007 }
1008
1009 let label = self.posture_label();
1010 match enforcement {
1011 SandboxEnforcement::LocalOs if self.should_sandbox() => {
1012 format!("{label} (local OS sandbox applied)")
1013 }
1014 SandboxEnforcement::Unavailable if self.should_sandbox() => {
1015 format!("{label} (policy only; no execution sandbox available)")
1016 }
1017 SandboxEnforcement::LocalOs | SandboxEnforcement::Unavailable => label,
1018 SandboxEnforcement::ExternalBackend => unreachable!("handled above"),
1019 }
1020 }
1021
1022 /// Posture label with the no-new-privileges kernel flag's effect on
1023 /// privilege escalation named, for surfaces that can observe the live
1024 /// flag state.
1025 ///
1026 /// `no_new_privs_active` is `Some(true)` when the irreversible flag is set
1027 /// on this process tree, `Some(false)` when startup relaxed it, and `None`
1028 /// on platforms without the flag (see
1029 /// [`super::process_hardening::no_new_privs_active`]). Only the full-access
1030 /// posture gains a clause: it is the posture whose name promises
1031 /// unrestricted privilege transitions (#5723), so a residual setuid block
1032 /// there is a lie of omission. Narrower postures keep the plain label —
1033 /// setuid was never expected to work inside them.
1034 #[must_use]
1035 pub fn posture_label_with_no_new_privs(&self, no_new_privs_active: Option<bool>) -> String {
1036 match (self, no_new_privs_active) {
1037 (SandboxPolicy::DangerFullAccess, Some(true)) => format!(
1038 "{}; sudo/setuid still blocked by the no-new-privs kernel flag set at startup",
1039 self.posture_label()
1040 ),
1041 (SandboxPolicy::DangerFullAccess, Some(false)) => format!(
1042 "{}; sudo/setuid allowed (no-new-privs relaxed at startup)",
1043 self.posture_label()
1044 ),
1045 _ => self.posture_label(),
1046 }
1047 }
1048
1049 /// Render the policy together with the session-pinned execution boundary
1050 /// and the live no-new-privileges flag state.
1051 ///
1052 /// The setuid clause only describes privilege transitions in *this*
1053 /// process tree, so an external execution backend — where commands run on
1054 /// the configured service — keeps the plain enforcement label.
1055 #[must_use]
1056 pub fn posture_label_with_enforcement_and_no_new_privs(
1057 &self,
1058 enforcement: SandboxEnforcement,
1059 no_new_privs_active: Option<bool>,
1060 ) -> String {
1061 match (self, enforcement) {
1062 (SandboxPolicy::DangerFullAccess, SandboxEnforcement::ExternalBackend) => {
1063 self.posture_label_with_enforcement(enforcement)
1064 }
1065 (SandboxPolicy::DangerFullAccess, _) => {
1066 self.posture_label_with_no_new_privs(no_new_privs_active)
1067 }
1068 _ => self.posture_label_with_enforcement(enforcement),
1069 }
1070 }
1071
1072 /// Get the list of writable roots for this policy.
1073 ///
1074 /// This includes:
1075 /// - The current working directory
1076 /// - Any explicitly specified `writable_roots`
1077 /// - /tmp (unless excluded)
1078 /// - TMPDIR (unless excluded)
1079 ///
1080 /// For policies with full write access, returns an empty vec since
1081 /// there's no need to enumerate specific paths.
1082 pub fn get_writable_roots(&self, cwd: &Path) -> Vec<WritableRoot> {
1083 match self {
1084 // Full write access or read-only - no enumeration needed
1085 SandboxPolicy::DangerFullAccess
1086 | SandboxPolicy::ExternalSandbox { .. }
1087 | SandboxPolicy::ReadOnly { .. } => vec![],
1088
1089 // Workspace write - enumerate all writable paths
1090 SandboxPolicy::WorkspaceWrite {
1091 writable_roots,
1092 exclude_tmpdir,
1093 exclude_slash_tmp,
1094 ..
1095 } => {
1096 let mut roots: Vec<PathBuf> = writable_roots.clone();
1097 let mut workspace_roots = roots.clone();
1098
1099 // Add the current working directory
1100 roots.push(canonical_or_self(cwd));
1101 workspace_roots.extend(roots.last().cloned());
1102
1103 // Git worktrees keep mutable metadata outside the worktree
1104 // directory. Allow only the gitdir and commondir derived from
1105 // a workspace `.git` pointer, preserving the workspace boundary
1106 // for all other external paths.
1107 let mut git_dir_roots = Vec::new();
1108 for root in roots.clone() {
1109 let git_dirs = resolve_git_worktree_writable_roots(&root);
1110 git_dir_roots.extend(git_dirs.iter().cloned());
1111 roots.extend(git_dirs);
1112 }
1113
1114 // Add /tmp unless excluded
1115 if !exclude_slash_tmp && let Ok(tmp) = Path::new("/tmp").canonicalize() {
1116 roots.push(tmp);
1117 }
1118
1119 // Add TMPDIR unless excluded
1120 if !exclude_tmpdir
1121 && let Ok(tmpdir) = std::env::var("TMPDIR")
1122 && let Ok(canonical) = Path::new(&tmpdir).canonicalize()
1123 {
1124 roots.push(canonical);
1125 }
1126
1127 // Convert to WritableRoot with read-only subpaths
1128 roots
1129 .into_iter()
1130 .map(|root| {
1131 let mut read_only_subpaths = Vec::new();
1132
1133 // Protect .codewhale/ and .deepseek/ from modification, and
1134 // the git hooks and config that later run or configure
1135 // commands outside the sandbox. A workspace root protects
1136 // .codewhale/ even before it exists.
1137 let workspace = workspace_roots.contains(&root);
1138 let codewhale_dir = root.join(".codewhale");
1139 if workspace || codewhale_dir.is_dir() {
1140 read_only_subpaths.push(codewhale_dir);
1141 }
1142 let deepseek_dir = root.join(".deepseek");
1143 if deepseek_dir.is_dir() {
1144 read_only_subpaths.push(deepseek_dir);
1145 }
1146 let git_dir = if git_dir_roots.contains(&root) {
1147 root.clone()
1148 } else {
1149 root.join(".git")
1150 };
1151 if git_dir.is_dir() {
1152 read_only_subpaths.push(git_dir.join("hooks"));
1153 read_only_subpaths.push(git_dir.join("config"));
1154 }
1155
1156 WritableRoot {
1157 root,
1158 read_only_subpaths,
1159 }
1160 })
1161 .collect()
1162 }
1163 }
1164 }
1165 }
1166
1167 fn resolve_git_worktree_writable_roots(root: &Path) -> Vec<PathBuf> {
1168 let Some(pointer) = resolve_gitdir_pointer(root) else {
1169 return Vec::new();
1170 };
1171 let git_dir = pointer.git_dir;
1172 let Some(common_dir) = resolve_git_common_dir(&git_dir) else {
1173 return Vec::new();
1174 };
1175 if !git_dir.starts_with(common_dir.join("worktrees")) {
1176 return Vec::new();
1177 }
1178 if !worktree_metadata_points_back_to_workspace(&git_dir, &pointer.git_file) {
1179 return Vec::new();
1180 }
1181
1182 vec![git_dir, common_dir]
1183 }
1184
1185 #[derive(Debug)]
1186 struct GitDirPointer {
1187 git_dir: PathBuf,
1188 git_file: PathBuf,
1189 }
1190
1191 fn resolve_gitdir_pointer(root: &Path) -> Option<GitDirPointer> {
1192 let search_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1193 for ancestor in search_root.ancestors() {
1194 let git_file = ancestor.join(".git");
1195 if !git_file.is_file() {
1196 continue;
1197 }
1198
1199 let contents = fs::read_to_string(&git_file).ok()?;
1200 let value = contents
1201 .lines()
1202 .find_map(|line| line.strip_prefix("gitdir:"))?
1203 .trim();
1204 if value.is_empty() {
1205 return None;
1206 }
1207
1208 let path = PathBuf::from(value);
1209 let resolved = if path.is_absolute() {
1210 path
1211 } else {
1212 ancestor.join(path)
1213 };
1214
1215 return Some(GitDirPointer {
1216 git_dir: resolved.canonicalize().ok()?,
1217 git_file: git_file.canonicalize().ok()?,
1218 });
1219 }
1220
1221 None
1222 }
1223
1224 fn resolve_git_common_dir(git_dir: &Path) -> Option<PathBuf> {
1225 let contents = fs::read_to_string(git_dir.join("commondir")).ok()?;
1226 let value = contents.lines().next()?.trim();
1227 if value.is_empty() {
1228 return None;
1229 }
1230
1231 let path = PathBuf::from(value);
1232 let resolved = if path.is_absolute() {
1233 path
1234 } else {
1235 git_dir.join(path)
1236 };
1237
1238 resolved.canonicalize().ok()
1239 }
1240
1241 fn worktree_metadata_points_back_to_workspace(git_dir: &Path, expected_git_file: &Path) -> bool {
1242 let Some(actual_git_file) = resolve_gitdir_back_pointer(git_dir) else {
1243 return false;
1244 };
1245 actual_git_file == expected_git_file
1246 }
1247
1248 fn resolve_gitdir_back_pointer(git_dir: &Path) -> Option<PathBuf> {
1249 let contents = fs::read_to_string(git_dir.join("gitdir")).ok()?;
1250 let value = contents.lines().next()?.trim();
1251 if value.is_empty() {
1252 return None;
1253 }
1254
1255 let path = PathBuf::from(value);
1256 let resolved = if path.is_absolute() {
1257 path
1258 } else {
1259 git_dir.join(path)
1260 };
1261
1262 resolved.canonicalize().ok()
1263 }
1264
1265 /// A directory tree where writes are allowed, with optional read-only subpaths.
1266 ///
1267 /// This allows fine-grained control like "allow writes to /project but not /project/.deepseek".
1268 #[derive(Debug, Clone, PartialEq, Eq)]
1269 pub struct WritableRoot {
1270 /// The root directory where writes are allowed.
1271 pub root: PathBuf,
1272
1273 /// Subdirectories within root that should remain read-only.
1274 pub read_only_subpaths: Vec<PathBuf>,
1275 }
1276
1277 impl WritableRoot {
1278 /// Create a new writable root with no read-only exceptions.
1279 pub fn new(root: PathBuf) -> Self {
1280 Self {
1281 root,
1282 read_only_subpaths: vec![],
1283 }
1284 }
1285
1286 /// Create a writable root with specific read-only subpaths.
1287 pub fn with_exceptions(root: PathBuf, read_only: Vec<PathBuf>) -> Self {
1288 Self {
1289 root,
1290 read_only_subpaths: read_only,
1291 }
1292 }
1293
1294 /// Check if a path is writable under this root.
1295 ///
1296 /// Returns true if the path is under the root and not under any read-only subpath.
1297 pub fn is_path_writable(&self, path: &Path) -> bool {
1298 // Must be under the root
1299 if !path.starts_with(&self.root) {
1300 return false;
1301 }
1302
1303 // Must not be under any read-only subpath
1304 for subpath in &self.read_only_subpaths {
1305 if path.starts_with(subpath) {
1306 return false;
1307 }
1308 }
1309
1310 true
1311 }
1312 }
1313
1314 /// Map a command safety classification to the appropriate sandbox policy (#2186).
1315 ///
1316 /// - `Safe` / `WorkspaceSafe` → use the default sandbox policy
1317 /// - `RequiresApproval` → user must approve before execution (handled by caller)
1318 /// - `Dangerous` → blocked unless in YOLO mode with trust
1319 #[cfg(test)]
1320 pub fn map_safety_level_to_behavior(
1321 level: SafetyLevel,
1322 default_policy: &SandboxPolicy,
1323 ) -> SandboxPolicyBehavior {
1324 match level {
1325 SafetyLevel::Safe | SafetyLevel::WorkspaceSafe => {
1326 SandboxPolicyBehavior::Sandboxed(default_policy.clone())
1327 }
1328 SafetyLevel::RequiresApproval => SandboxPolicyBehavior::RequiresApproval,
1329 SafetyLevel::Dangerous => SandboxPolicyBehavior::Blocked,
1330 }
1331 }
1332
1333 /// Behavior decision for a sandboxed command based on safety level.
1334 #[cfg(test)]
1335 #[derive(Debug, Clone)]
1336 pub enum SandboxPolicyBehavior {
1337 /// Execute with the given sandbox policy.
1338 Sandboxed(SandboxPolicy),
1339 /// User approval required before execution.
1340 RequiresApproval,
1341 /// Block execution entirely (unless YOLO+trust).
1342 Blocked,
1343 }
1344
1345 #[cfg(test)]
1346 mod tests {
1347 use super::*;
1348
1349 #[test]
1350 fn test_default_policy() {
1351 let policy = SandboxPolicy::default();
1352 assert!(matches!(policy, SandboxPolicy::WorkspaceWrite { .. }));
1353 assert!(!policy.has_network_access());
1354 assert!(policy.should_sandbox());
1355 }
1356
1357 #[test]
1358 fn test_full_access_policy() {
1359 let policy = SandboxPolicy::DangerFullAccess;
1360 assert!(policy.has_full_disk_write_access());
1361 assert!(policy.has_network_access());
1362 assert!(!policy.should_sandbox());
1363 }
1364
1365 #[test]
1366 fn posture_labels_name_the_binding_fact() {
1367 // This label is shared by interactive and non-interactive postures, so
1368 // state only the invariant. The denial hint names the Ask-only path.
1369 let read_only = SandboxPolicy::read_only().posture_label();
1370 assert!(read_only.contains("read-only"), "{read_only}");
1371 assert!(read_only.contains("ordinary approval"), "{read_only}");
1372
1373 assert!(
1374 SandboxPolicy::default()
1375 .posture_label()
1376 .starts_with("workspace-write"),
1377 );
1378 assert!(
1379 SandboxPolicy::DangerFullAccess
1380 .posture_label()
1381 .contains("full access"),
1382 );
1383 assert!(
1384 SandboxPolicy::ExternalSandbox {
1385 network_access: false
1386 }
1387 .posture_label()
1388 .contains("network blocked"),
1389 );
1390 }
1391
1392 #[test]
1393 fn enforcement_labels_distinguish_local_external_and_unavailable() {
1394 let local =
1395 SandboxPolicy::default().posture_label_with_enforcement(SandboxEnforcement::LocalOs);
1396 assert!(local.starts_with("workspace-write"), "{local}");
1397 assert!(local.contains("local OS sandbox applied"), "{local}");
1398
1399 let unavailable = SandboxPolicy::read_only()
1400 .posture_label_with_enforcement(SandboxEnforcement::Unavailable);
1401 assert!(
1402 unavailable.contains("policy only; no execution sandbox available"),
1403 "{unavailable}"
1404 );
1405
1406 let external = SandboxPolicy::default()
1407 .posture_label_with_enforcement(SandboxEnforcement::ExternalBackend);
1408 assert!(external.starts_with("workspace-write policy"), "{external}");
1409 assert!(
1410 external.contains("external execution backend configured"),
1411 "{external}"
1412 );
1413 assert!(
1414 external.contains("isolation unverified by Codewhale"),
1415 "{external}"
1416 );
1417 assert!(
1418 !external.contains("writes inside the workspace"),
1419 "{external}"
1420 );
1421 assert!(!external.contains("network allowed"), "{external}");
1422
1423 let full_external = SandboxPolicy::DangerFullAccess
1424 .posture_label_with_enforcement(SandboxEnforcement::ExternalBackend);
1425 assert!(
1426 full_external.starts_with("full-access policy"),
1427 "{full_external}"
1428 );
1429 assert!(
1430 !full_external.contains("sandbox disabled"),
1431 "{full_external}"
1432 );
1433
1434 let full_unavailable = SandboxPolicy::DangerFullAccess
1435 .posture_label_with_enforcement(SandboxEnforcement::Unavailable);
1436 assert_eq!(
1437 full_unavailable,
1438 SandboxPolicy::DangerFullAccess.posture_label()
1439 );
1440 }
1441
1442 #[test]
1443 fn posture_labels_disclose_the_no_new_privs_flag_for_full_access() {
1444 // #5723: "full access" promises unrestricted privilege transitions, so
1445 // the label must say when the irreversible kernel flag still blocks
1446 // sudo/setuid — and when the startup posture relaxed it.
1447 let blocked = SandboxPolicy::DangerFullAccess.posture_label_with_no_new_privs(Some(true));
1448 assert!(
1449 blocked.contains("full access (sandbox disabled)"),
1450 "{blocked}"
1451 );
1452 assert!(blocked.contains("sudo/setuid still blocked"), "{blocked}");
1453 assert!(blocked.contains("no-new-privs"), "{blocked}");
1454
1455 let relaxed = SandboxPolicy::DangerFullAccess.posture_label_with_no_new_privs(Some(false));
1456 assert!(relaxed.contains("sudo/setuid allowed"), "{relaxed}");
1457
1458 // No flag on this platform → the plain label, byte-identical.
1459 let unknown = SandboxPolicy::DangerFullAccess.posture_label_with_no_new_privs(None);
1460 assert_eq!(unknown, SandboxPolicy::DangerFullAccess.posture_label());
1461
1462 // Narrower postures never promised setuid; the clause is full-access
1463 // only, in either flag state.
1464 for flag in [Some(true), Some(false), None] {
1465 assert_eq!(
1466 SandboxPolicy::default().posture_label_with_no_new_privs(flag),
1467 SandboxPolicy::default().posture_label(),
1468 );
1469 assert_eq!(
1470 SandboxPolicy::read_only().posture_label_with_no_new_privs(flag),
1471 SandboxPolicy::read_only().posture_label(),
1472 );
1473 }
1474 }
1475
1476 #[test]
1477 fn enforcement_and_no_new_privs_labels_compose_only_where_they_apply() {
1478 // The setuid clause describes this process tree; an external backend
1479 // runs commands on its own service, so its label stays untouched.
1480 let external = SandboxPolicy::DangerFullAccess
1481 .posture_label_with_enforcement_and_no_new_privs(
1482 SandboxEnforcement::ExternalBackend,
1483 Some(true),
1484 );
1485 assert_eq!(
1486 external,
1487 SandboxPolicy::DangerFullAccess
1488 .posture_label_with_enforcement(SandboxEnforcement::ExternalBackend),
1489 "{external}"
1490 );
1491
1492 let local_blocked = SandboxPolicy::DangerFullAccess
1493 .posture_label_with_enforcement_and_no_new_privs(
1494 SandboxEnforcement::LocalOs,
1495 Some(true),
1496 );
1497 assert!(
1498 local_blocked.contains("sudo/setuid still blocked"),
1499 "{local_blocked}"
1500 );
1501
1502 // Other postures keep exactly the enforcement label.
1503 let workspace = SandboxPolicy::default().posture_label_with_enforcement_and_no_new_privs(
1504 SandboxEnforcement::LocalOs,
1505 Some(false),
1506 );
1507 assert_eq!(
1508 workspace,
1509 SandboxPolicy::default().posture_label_with_enforcement(SandboxEnforcement::LocalOs),
1510 "{workspace}"
1511 );
1512 }
1513
1514 #[test]
1515 fn test_read_only_policy() {
1516 let policy = SandboxPolicy::read_only();
1517 assert!(!policy.has_full_disk_write_access());
1518 assert!(!policy.has_network_access());
1519 assert!(policy.should_sandbox());
1520 }
1521
1522 #[test]
1523 fn test_workspace_with_network() {
1524 let policy = SandboxPolicy::workspace_with_network();
1525 assert!(policy.has_network_access());
1526 assert!(policy.should_sandbox());
1527 }
1528
1529 #[test]
1530 fn workspace_write_includes_git_worktree_metadata_roots() {
1531 let tmp = tempfile::tempdir().expect("tempdir");
1532 let common_git_dir = tmp.path().join("main-repo").join(".git");
1533 let worktree_git_dir = common_git_dir.join("worktrees").join("feature");
1534 let worktree = tmp.path().join("feature-worktree");
1535 std::fs::create_dir_all(&worktree_git_dir).expect("mkdir gitdir");
1536 std::fs::create_dir_all(&worktree).expect("mkdir worktree");
1537 std::fs::write(
1538 worktree.join(".git"),
1539 format!("gitdir: {}\n", worktree_git_dir.display()),
1540 )
1541 .expect("write git pointer");
1542 std::fs::write(worktree_git_dir.join("commondir"), "../..").expect("write commondir");
1543 std::fs::write(
1544 worktree_git_dir.join("gitdir"),
1545 worktree.join(".git").display().to_string(),
1546 )
1547 .expect("write gitdir back pointer");
1548
1549 let policy = SandboxPolicy::WorkspaceWrite {
1550 writable_roots: vec![worktree.clone()],
1551 network_access: true,
1552 exclude_tmpdir: true,
1553 exclude_slash_tmp: true,
1554 };
1555
1556 let root_paths: Vec<PathBuf> = policy
1557 .get_writable_roots(&worktree)
1558 .into_iter()
1559 .map(|root| root.root)
1560 .collect();
1561
1562 assert!(root_paths.contains(&worktree.canonicalize().expect("canonical worktree")));
1563 assert!(root_paths.contains(&worktree_git_dir.canonicalize().expect("canonical gitdir")));
1564 assert!(root_paths.contains(&common_git_dir.canonicalize().expect("canonical common git")));
1565 }
1566
1567 #[test]
1568 fn workspace_write_resolves_git_worktree_metadata_from_subdirectory() {
1569 let tmp = tempfile::tempdir().expect("tempdir");
1570 let common_git_dir = tmp.path().join("main-repo").join(".git");
1571 let worktree_git_dir = common_git_dir.join("worktrees").join("feature");
1572 let worktree = tmp.path().join("feature-worktree");
1573 let nested = worktree.join("crates").join("cli");
1574 std::fs::create_dir_all(&worktree_git_dir).expect("mkdir gitdir");
1575 std::fs::create_dir_all(&nested).expect("mkdir nested worktree path");
1576 std::fs::write(
1577 worktree.join(".git"),
1578 format!("gitdir: {}\n", worktree_git_dir.display()),
1579 )
1580 .expect("write git pointer");
1581 std::fs::write(worktree_git_dir.join("commondir"), "../..").expect("write commondir");
1582 std::fs::write(
1583 worktree_git_dir.join("gitdir"),
1584 worktree.join(".git").display().to_string(),
1585 )
1586 .expect("write gitdir back pointer");
1587
1588 let policy = SandboxPolicy::WorkspaceWrite {
1589 writable_roots: vec![],
1590 network_access: true,
1591 exclude_tmpdir: true,
1592 exclude_slash_tmp: true,
1593 };
1594
1595 let root_paths: Vec<PathBuf> = policy
1596 .get_writable_roots(&nested)
1597 .into_iter()
1598 .map(|root| root.root)
1599 .collect();
1600
1601 assert!(root_paths.contains(&nested.canonicalize().expect("canonical nested cwd")));
1602 assert!(root_paths.contains(&worktree_git_dir.canonicalize().expect("canonical gitdir")));
1603 assert!(root_paths.contains(&common_git_dir.canonicalize().expect("canonical common git")));
1604 }
1605
1606 #[test]
1607 fn workspace_write_rejects_non_reciprocal_git_worktree_metadata() {
1608 let tmp = tempfile::tempdir().expect("tempdir");
1609 let common_git_dir = tmp.path().join("main-repo").join(".git");
1610 let worktree_git_dir = common_git_dir.join("worktrees").join("feature");
1611 let worktree = tmp.path().join("feature-worktree");
1612 let other_worktree = tmp.path().join("other-worktree");
1613 std::fs::create_dir_all(&worktree_git_dir).expect("mkdir gitdir");
1614 std::fs::create_dir_all(&worktree).expect("mkdir worktree");
1615 std::fs::create_dir_all(&other_worktree).expect("mkdir other worktree");
1616 std::fs::write(
1617 worktree.join(".git"),
1618 format!("gitdir: {}\n", worktree_git_dir.display()),
1619 )
1620 .expect("write git pointer");
1621 std::fs::write(worktree_git_dir.join("commondir"), "../..").expect("write commondir");
1622 std::fs::write(
1623 worktree_git_dir.join("gitdir"),
1624 other_worktree.join(".git").display().to_string(),
1625 )
1626 .expect("write mismatched gitdir back pointer");
1627 std::fs::write(
1628 other_worktree.join(".git"),
1629 "gitdir: /tmp/not-this-worktree\n",
1630 )
1631 .expect("write other git pointer");
1632
1633 let policy = SandboxPolicy::WorkspaceWrite {
1634 writable_roots: vec![worktree.clone()],
1635 network_access: true,
1636 exclude_tmpdir: true,
1637 exclude_slash_tmp: true,
1638 };
1639
1640 let root_paths: Vec<PathBuf> = policy
1641 .get_writable_roots(&worktree)
1642 .into_iter()
1643 .map(|root| root.root)
1644 .collect();
1645
1646 assert!(root_paths.contains(&worktree.canonicalize().expect("canonical worktree")));
1647 assert!(!root_paths.contains(&worktree_git_dir.canonicalize().expect("canonical gitdir")));
1648 assert!(
1649 !root_paths.contains(&common_git_dir.canonicalize().expect("canonical common git"))
1650 );
1651 }
1652
1653 #[test]
1654 fn test_writable_root_basic() {
1655 let root = WritableRoot::new(PathBuf::from("/project"));
1656 assert!(root.is_path_writable(Path::new("/project/src/main.rs")));
1657 assert!(!root.is_path_writable(Path::new("/other/file.txt")));
1658 }
1659
1660 #[test]
1661 fn test_writable_root_with_exceptions() {
1662 let root = WritableRoot::with_exceptions(
1663 PathBuf::from("/project"),
1664 vec![PathBuf::from("/project/.deepseek")],
1665 );
1666 assert!(root.is_path_writable(Path::new("/project/src/main.rs")));
1667 assert!(!root.is_path_writable(Path::new("/project/.deepseek/config")));
1668 }
1669
1670 #[test]
1671 fn test_safety_level_mapping() {
1672 let default = SandboxPolicy::default();
1673
1674 // Safe commands get sandboxed
1675 assert!(matches!(
1676 map_safety_level_to_behavior(SafetyLevel::Safe, &default),
1677 SandboxPolicyBehavior::Sandboxed(_)
1678 ));
1679 assert!(matches!(
1680 map_safety_level_to_behavior(SafetyLevel::WorkspaceSafe, &default),
1681 SandboxPolicyBehavior::Sandboxed(_)
1682 ));
1683
1684 // RequiresApproval gets RequiresApproval
1685 assert!(matches!(
1686 map_safety_level_to_behavior(SafetyLevel::RequiresApproval, &default),
1687 SandboxPolicyBehavior::RequiresApproval
1688 ));
1689
1690 // Dangerous gets Blocked
1691 assert!(matches!(
1692 map_safety_level_to_behavior(SafetyLevel::Dangerous, &default),
1693 SandboxPolicyBehavior::Blocked
1694 ));
1695 }
1696
1697 #[test]
1698 fn test_policy_serialization() {
1699 let policy = SandboxPolicy::WorkspaceWrite {
1700 writable_roots: vec![PathBuf::from("/extra")],
1701 network_access: true,
1702 exclude_tmpdir: false,
1703 exclude_slash_tmp: false,
1704 };
1705
1706 let json = serde_json::to_string(&policy).unwrap();
1707 assert!(json.contains("workspace-write"));
1708
1709 let parsed: SandboxPolicy = serde_json::from_str(&json).unwrap();
1710 assert_eq!(policy, parsed);
1711 }
1712
1713 #[test]
1714 fn named_sandbox_profiles_keep_workspace_default_on() {
1715 assert_eq!(SandboxProfile::default(), SandboxProfile::Workspace);
1716 assert_eq!(
1717 SandboxProfile::from_name("workspace"),
1718 Some(SandboxProfile::Workspace)
1719 );
1720 assert_eq!(
1721 SandboxProfile::from_name("read-only"),
1722 Some(SandboxProfile::ReadOnly)
1723 );
1724 assert_eq!(
1725 SandboxProfile::from_name("strict"),
1726 Some(SandboxProfile::Strict)
1727 );
1728 assert_eq!(SandboxProfile::from_name("off"), Some(SandboxProfile::Off));
1729 assert_eq!(SandboxProfile::from_name("unknown"), None);
1730
1731 let workspace = SandboxPolicy::from_profile(SandboxProfile::Workspace);
1732 assert!(workspace.should_sandbox());
1733 assert!(!workspace.has_network_access());
1734
1735 let read_only = SandboxPolicy::from_profile(SandboxProfile::ReadOnly);
1736 assert!(read_only.should_sandbox());
1737 assert!(matches!(
1738 read_only,
1739 SandboxPolicy::ReadOnly {
1740 network_access: false
1741 }
1742 ));
1743
1744 let strict = SandboxPolicy::from_profile(SandboxProfile::Strict);
1745 assert!(strict.should_sandbox());
1746 assert!(matches!(
1747 strict,
1748 SandboxPolicy::WorkspaceWrite {
1749 network_access: false,
1750 exclude_tmpdir: true,
1751 exclude_slash_tmp: true,
1752 ..
1753 }
1754 ));
1755
1756 let off = SandboxPolicy::from_profile(SandboxProfile::Off);
1757 assert!(!off.should_sandbox());
1758 assert!(off.has_full_disk_write_access());
1759 }
1760
1761 #[test]
1762 fn sandbox_overlay_parses_and_preserves_default_denies() {
1763 let dir = tempfile::tempdir().expect("tempdir");
1764 let cw_dir = dir.path().join(".codewhale");
1765 std::fs::create_dir_all(&cw_dir).expect("mkdir .codewhale");
1766 std::fs::write(
1767 cw_dir.join("sandbox.toml"),
1768 r#"
1769 # project sandbox overlay
1770 extends = "strict"
1771 restrict_network = true
1772 read_only = ["docs", "config/prod"]
1773 read_write = [
1774 "target",
1775 "tmp/cache",
1776 ]
1777 deny = ["secrets/*.key", "**/*.pem"]
1778 "#,
1779 )
1780 .expect("write sandbox.toml");
1781
1782 let overlay = SandboxOverlay::load_from_workspace(dir.path())
1783 .expect("load overlay")
1784 .expect("overlay present");
1785 assert_eq!(overlay.extends, Some(SandboxProfile::Strict));
1786 assert_eq!(overlay.restrict_network, Some(true));
1787 assert_eq!(overlay.read_only.len(), 2);
1788 assert_eq!(overlay.read_write.len(), 2);
1789 assert_eq!(overlay.deny, vec!["secrets/*.key", "**/*.pem"]);
1790
1791 let resolved = overlay.resolve(SandboxProfile::Workspace, dir.path());
1792 assert_eq!(resolved.profile, SandboxProfile::Strict);
1793 assert!(!resolved.policy.has_network_access());
1794 assert!(resolved.deny_globs.iter().any(|g| g == "~/.ssh"));
1795 assert!(resolved.deny_globs.iter().any(|g| g == "~/.aws"));
1796 assert!(resolved.deny_globs.iter().any(|g| g == ".env"));
1797 assert!(resolved.deny_globs.iter().any(|g| g == ".env.*"));
1798 assert!(resolved.deny_globs.iter().any(|g| g == "secrets/*.key"));
1799 assert!(resolved.deny_globs.iter().any(|g| g == "**/*.pem"));
1800 }
1801
1802 #[test]
1803 fn deny_globs_match_and_expand_in_workspace() {
1804 let dir = tempfile::tempdir().expect("tempdir");
1805 let secrets = dir.path().join("secrets");
1806 std::fs::create_dir_all(&secrets).expect("mkdir secrets");
1807 std::fs::write(dir.path().join(".env"), "SECRET=1").expect("write .env");
1808 std::fs::write(dir.path().join(".env.local"), "LOCAL=1").expect("write .env.local");
1809 std::fs::write(secrets.join("prod.key"), "KEY").expect("write prod.key");
1810 std::fs::write(secrets.join("readme.txt"), "ok").expect("write readme.txt");
1811
1812 assert!(glob_matches("secrets/*.key", "secrets/prod.key"));
1813 assert!(!glob_matches("secrets/*.key", "secrets/readme.txt"));
1814 assert!(glob_matches("**/*.key", "a/b/prod.key"));
1815 assert!(glob_matches("**/*.key", "prod.key"));
1816
1817 let globs = vec![
1818 ".env".to_string(),
1819 ".env.*".to_string(),
1820 "secrets/*.key".to_string(),
1821 ];
1822 let matched = expand_deny_globs_in_workspace(&globs, dir.path());
1823 let canonical = dir.path().canonicalize().expect("canonical");
1824 assert!(matched.contains(&canonical.join(".env")));
1825 assert!(matched.contains(&canonical.join(".env.local")));
1826 assert!(matched.contains(&canonical.join("secrets").join("prod.key")));
1827 assert!(!matched.contains(&canonical.join("secrets").join("readme.txt")));
1828
1829 let regex = glob_to_sbpl_regex("secrets/*.key", dir.path()).expect("regex");
1830 assert!(regex.starts_with('^'));
1831 assert!(regex.ends_with('$'));
1832 assert!(regex.contains("secrets/[^/]*\\.key"));
1833 }
1834
1835 #[test]
1836 fn hostile_overlay_cannot_weaken_active_sandbox_or_inject_controls() {
1837 let dir = tempfile::tempdir().expect("tempdir");
1838 let root = dir.path().canonicalize().expect("canonical");
1839 let hostile = SandboxOverlay::parse_toml(
1840 r#"
1841 extends = "off"
1842 restrict_network = false
1843 read_write = ["/", "~", "~/.ssh", "../escape", "sub/ok"]
1844 "#,
1845 )
1846 .expect("parse hostile");
1847
1848 let from_workspace = SandboxPolicy::default().apply_workspace_overlay(&hostile, &root);
1849 assert!(from_workspace.policy.should_sandbox());
1850 assert!(!from_workspace.policy.has_network_access());
1851 assert!(from_workspace.deny_globs.iter().any(|g| g == "~/.ssh"));
1852 assert!(from_workspace.deny_globs.iter().any(|g| g == ".env"));
1853 if let SandboxPolicy::WorkspaceWrite { writable_roots, .. } = &from_workspace.policy {
1854 assert_eq!(writable_roots, &vec![root.join("sub/ok")]);
1855 } else {
1856 panic!("expected WorkspaceWrite");
1857 }
1858
1859 let from_ro = SandboxPolicy::read_only().apply_workspace_overlay(&hostile, &root);
1860 assert!(matches!(
1861 from_ro.policy,
1862 SandboxPolicy::ReadOnly {
1863 network_access: false
1864 }
1865 ));
1866 assert!(from_ro.deny_globs.iter().any(|g| g == ".env"));
1867
1868 assert!(SandboxOverlay::parse_toml("deny = [\"a\\nb\"]").is_err());
1869 assert!(SandboxOverlay::parse_toml("read_only = [\"a\\rb\"]").is_err());
1870 assert!(glob_to_sbpl_regex("a\nb", &root).is_none());
1871
1872 #[cfg(unix)]
1873 {
1874 let outside = tempfile::tempdir().expect("outside");
1875 std::fs::write(
1876 outside.path().join("sandbox.toml"),
1877 "extends = \"strict\"\n",
1878 )
1879 .expect("write outside");
1880 let sym_ws = tempfile::tempdir().expect("sym_ws");
1881 std::os::unix::fs::symlink(outside.path(), sym_ws.path().join(".codewhale"))
1882 .expect("symlink .codewhale");
1883 assert!(SandboxOverlay::load_from_workspace(sym_ws.path()).is_err());
1884 }
1885 }
1886 }
1887
1887 lines RUST