Skip to main content

blyte_agent/
sandbox.rs

1//! Sandbox profile generation and host sandbox detection for macOS (Seatbelt) and Linux (Landlock).
2//!
3//! Restricts local shell command execution to prevent writes outside of the workspace,
4//! git common directory, temporary folders, and standard developer tool caches.
5//!
6//! # Platform differences and scope limits
7//!
8//! - On macOS, Seatbelt (SBPL) restricts writes and denies reading credential stores and
9//!   environment secret files unless explicitly permitted via allow-lists.
10//! - On Linux, Landlock restricts writes and restricts reads via an allowlist: commands can read
11//!   only system directories, the workspace, tool caches under `$HOME`, and `--allow-read` grants;
12//!   credential stores and other files under `$HOME` are not granted and therefore unreadable.
13//!   The harness environment filter applies on both platforms.
14//!
15//! # Network isolation (`--network=off`)
16//!
17//! - On macOS, Seatbelt denies outbound network connections while allowing loopback (`localhost:*`)
18//!   and Unix domain sockets, then explicitly denies known Docker daemon sockets.
19//! - On Linux, Landlock (ABI >= 4, Linux 6.7+) handles TCP connection restriction (`AccessNet::ConnectTcp`),
20//!   denying all outbound TCP connections (including localhost). UDP and Unix sockets are not restricted by Landlock.
21
22pub mod grants;
23
24use std::path::{Path, PathBuf};
25
26/// Sandbox profile restricting command execution.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum Profile {
29    /// An SBPL profile string for `sandbox-exec` on macOS.
30    Seatbelt(String),
31    /// A list of write-allowed directory paths for Landlock on Linux.
32    Landlock(Vec<PathBuf>),
33    /// A list of write-allowed directory paths for Landlock on Linux, blocking outbound TCP connections.
34    LandlockOffline(Vec<PathBuf>),
35    /// Write-allowed and read-allowed directory paths for Landlock on Linux, optionally blocking outbound TCP connections.
36    LandlockConfined {
37        write: Vec<PathBuf>,
38        read: Vec<PathBuf>,
39        block_tcp: bool,
40    },
41}
42
43impl From<String> for Profile {
44    fn from(s: String) -> Self {
45        Profile::Seatbelt(s)
46    }
47}
48
49impl From<&str> for Profile {
50    fn from(s: &str) -> Self {
51        Profile::Seatbelt(s.to_string())
52    }
53}
54
55/// Returns the Landlock ABI version supported by the running kernel, or 0 if unsupported or on other platforms.
56#[cfg(target_os = "linux")]
57pub fn landlock_abi() -> i64 {
58    unsafe {
59        libc::syscall(
60            libc::SYS_landlock_create_ruleset,
61            std::ptr::null::<libc::c_void>(),
62            0usize,
63            1u32,
64        ) as i64
65    }
66}
67
68/// Returns the Landlock ABI version supported by the running kernel, or 0 if unsupported or on other platforms.
69#[cfg(not(target_os = "linux"))]
70pub fn landlock_abi() -> i64 {
71    0
72}
73
74/// Returns whether sandbox execution is available on this system.
75///
76/// On macOS, returns true when `/usr/bin/sandbox-exec` is present on disk.
77/// On Linux, returns true when the kernel supports Landlock.
78/// On other platforms, returns false.
79pub fn available() -> bool {
80    #[cfg(target_os = "macos")]
81    {
82        Path::new("/usr/bin/sandbox-exec").exists()
83    }
84    #[cfg(target_os = "linux")]
85    {
86        landlock_abi() >= 1
87    }
88    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
89    {
90        false
91    }
92}
93
94/// Escapes a path for inclusion in an SBPL rule.
95fn escape_path(path: &Path) -> String {
96    let s = path.to_string_lossy();
97    s.replace('\\', "\\\\").replace('"', "\\\"")
98}
99
100fn escape_subpath(path: &Path) -> String {
101    let canon = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
102    escape_path(&canon)
103}
104
105/// Generates an SBPL (Seatbelt Profile Language) profile denying file writes outside allowed paths.
106///
107/// # Arguments
108///
109/// * `allowed` - Paths where file write operations should be permitted.
110///
111/// # Returns
112///
113/// An SBPL profile string allowing general operations, denying writes by default, and
114/// explicitly whitelisting writes under each path in `allowed` plus `/dev/null`, `/dev/tty`, and `/dev/fd`.
115pub fn profile(allowed: &[PathBuf]) -> String {
116    // Start with the base policy: allow default operations, but deny all file writes.
117    let mut out = String::from("(version 1)(allow default)(deny file-write*)");
118
119    // Allow recursive writes under each specified path, resolving symlinks when possible.
120    for path in allowed {
121        let escaped = escape_subpath(path);
122        out.push_str(&format!(r#"(allow file-write* (subpath "{escaped}"))"#));
123    }
124
125    // Permit writes to essential standard I/O pseudo-devices.
126    out.push_str(
127        r#"(allow file-write* (literal "/dev/null") (literal "/dev/tty") (subpath "/dev/fd"))"#,
128    );
129    out
130}
131
132/// Returns the list of standard credential and secret store paths under `home` that should be denied reading.
133pub fn read_denied(home: &Path) -> Vec<PathBuf> {
134    const DENIED_PATHS: &[&str] = &[
135        ".ssh",
136        ".aws",
137        ".azure",
138        ".config/blyte/env",
139        ".config/gcloud",
140        ".config/gh",
141        ".kube",
142        ".gnupg",
143        ".docker/config.json",
144        ".git-credentials",
145        ".netrc",
146        ".pypirc",
147        ".cargo/credentials.toml",
148        ".cargo/credentials",
149        ".codex",
150        "Library/Keychains",
151        "Library/Cookies",
152        "Library/Safari",
153        "Library/Application Support/Google/Chrome",
154        "Library/Application Support/Firefox",
155        "Library/Application Support/Arc",
156        "Library/Application Support/BraveSoftware",
157    ];
158    DENIED_PATHS.iter().map(|sub| home.join(sub)).collect()
159}
160
161/// Returns the list of standard read-allowed paths for a confined Landlock sandbox on Linux.
162///
163/// In order: system roots, tool directories under `home` (if given), and `allow_read` grants.
164pub fn read_allowed(home: Option<&Path>, allow_read: &[PathBuf]) -> Vec<PathBuf> {
165    let mut allowed = Vec::new();
166
167    const SYSTEM_ROOTS: &[&str] = &[
168        "/usr", "/lib", "/lib32", "/lib64", "/libx32", "/bin", "/sbin", "/etc", "/opt", "/proc",
169        "/sys", "/dev", "/run", "/var", "/tmp", "/snap", "/nix",
170    ];
171    for root in SYSTEM_ROOTS {
172        allowed.push(PathBuf::from(root));
173    }
174
175    if let Some(home) = home {
176        const TOOL_DIRS: &[&str] = &[
177            ".cargo",
178            ".rustup",
179            ".cache",
180            ".local/bin",
181            ".local/lib",
182            ".local/share/uv",
183            ".local/share/pnpm",
184            ".local/share/mise",
185            ".npm",
186            ".nvm",
187            ".pyenv",
188            ".rbenv",
189            ".asdf",
190            ".bun",
191            ".deno",
192            ".gradle",
193            ".m2",
194            "go",
195            ".config/git",
196            ".gitconfig",
197            ".gitignore_global",
198            ".gitattributes",
199            ".profile",
200            ".bashrc",
201            ".bash_profile",
202            ".bash_login",
203            ".inputrc",
204            ".editorconfig",
205            ".docker/buildx",
206        ];
207        for sub in TOOL_DIRS {
208            allowed.push(home.join(sub));
209        }
210    }
211
212    allowed.extend(allow_read.iter().cloned());
213    allowed
214}
215
216/// System temporary directories where tests may create and read `.env` files.
217const TEMP_DOT_ENV_DIRS: &[&str] = &["/private/tmp", "/private/var/folders"];
218
219/// Generates an SBPL profile denying file writes outside `write`, denying file reads under
220/// `deny_read` and any `.env` file, allowing `.env` files under `/private/tmp` and
221/// `/private/var/folders` outside `workspace` (so tests can read `.env` files they create in temp
222/// folders while the workspace `.env` stays denied), and granting file reads back under
223/// `allow_read`.
224/// Reads are denied as `file-read-data`: contents and directory listings are refused, but `stat`
225/// still works (pytest stats every path while collecting, including `.env`).
226pub fn profile_with(
227    workspace: &Path,
228    write: &[PathBuf],
229    deny_read: &[PathBuf],
230    allow_read: &[PathBuf],
231) -> String {
232    let mut out = profile(write);
233    for path in deny_read {
234        let escaped = escape_subpath(path);
235        out.push_str(&format!(r#"(deny file-read-data (subpath "{escaped}"))"#));
236    }
237    out.push_str(r##"(deny file-read-data (regex #"/\.env$"))"##);
238    let escaped_ws = escape_subpath(workspace);
239    for dir in TEMP_DOT_ENV_DIRS {
240        out.push_str(&format!(
241            r##"(allow file-read-data (require-all (subpath "{dir}") (require-not (subpath "{escaped_ws}")) (regex #"/\.env$")))"##
242        ));
243    }
244    for path in allow_read {
245        let escaped = escape_subpath(path);
246        out.push_str(&format!(r#"(allow file-read-data (subpath "{escaped}"))"#));
247    }
248    out
249}
250
251fn push_home_local_grants(home_path: &Path, allowed: &mut Vec<PathBuf>) {
252    #[cfg(target_os = "macos")]
253    {
254        allowed.push(home_path.join(".local"));
255    }
256    #[cfg(not(target_os = "macos"))]
257    {
258        let local_dir = home_path.join(".local");
259        if let Ok(entries) = std::fs::read_dir(&local_dir) {
260            let mut paths: Vec<PathBuf> = entries
261                .flatten()
262                .filter(|entry| {
263                    let name = entry.file_name();
264                    name != std::ffi::OsStr::new("state")
265                        && name != std::ffi::OsStr::new("bin")
266                        && name != std::ffi::OsStr::new("lib")
267                })
268                .map(|entry| entry.path())
269                .collect();
270            paths.sort();
271            allowed.extend(paths);
272        }
273        let state_dir = local_dir.join("state");
274        if let Ok(entries) = std::fs::read_dir(&state_dir) {
275            let mut paths: Vec<PathBuf> = entries
276                .flatten()
277                .filter(|entry| entry.file_name() != std::ffi::OsStr::new("blyte"))
278                .map(|entry| entry.path())
279                .collect();
280            paths.sort();
281            allowed.extend(paths);
282        }
283    }
284}
285
286fn push_home_grants(allowed: &mut Vec<PathBuf>) {
287    if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
288        let home_path = PathBuf::from(home);
289        for sub in [
290            ".cargo",
291            ".cache",
292            ".npm",
293            "Library/Caches",
294            ".gradle",
295            ".m2",
296            "go/pkg",
297            ".docker/buildx",
298        ] {
299            allowed.push(home_path.join(sub));
300        }
301        push_home_local_grants(&home_path, allowed);
302    }
303}
304
305/// Returns the blyte state directory (`$BLYTE_STATE_DIR` when set and non-empty, else
306/// `$XDG_STATE_HOME/blyte` when set, else `$HOME/.local/state/blyte`).
307pub fn state_blyte_dir() -> Option<PathBuf> {
308    if let Some(dir) = std::env::var_os("BLYTE_STATE_DIR") {
309        if !dir.is_empty() {
310            return Some(PathBuf::from(dir));
311        }
312    }
313    if let Some(xdg) = std::env::var_os("XDG_STATE_HOME") {
314        if !xdg.is_empty() {
315            return Some(PathBuf::from(xdg).join("blyte"));
316        }
317    }
318    std::env::var_os("HOME")
319        .filter(|h| !h.is_empty())
320        .map(|h| PathBuf::from(h).join(".local").join("state").join("blyte"))
321}
322
323fn fnv1a64(bytes: &[u8]) -> u64 {
324    let mut hash: u64 = 0xcbf29ce484222325;
325    for &b in bytes {
326        hash ^= u64::from(b);
327        hash = hash.wrapping_mul(0x100000001b3);
328    }
329    hash
330}
331
332/// Returns the directory holding surface authentication tokens (`<state_blyte_dir>/surface`).
333pub fn surface_token_dir() -> Option<PathBuf> {
334    state_blyte_dir().map(|d| d.join("surface"))
335}
336
337/// Returns the path to the surface authentication token for `main_checkout`.
338pub fn surface_token_path(main_checkout: &Path) -> Result<PathBuf, String> {
339    let dir = surface_token_dir().ok_or_else(|| {
340        "cannot determine surface token directory: neither XDG_STATE_HOME nor HOME is set"
341            .to_string()
342    })?;
343    let canon = canonicalize_existing_prefix(main_checkout);
344    let key = format!("{:016x}", fnv1a64(canon.as_os_str().as_encoded_bytes()));
345    Ok(dir.join(format!("{key}.token")))
346}
347
348/// A surface id is `s` followed by exactly 16 lowercase hex digits.
349pub fn validate_surface_id(id: &str) -> Result<(), String> {
350    let bytes = id.as_bytes();
351    let valid = bytes.len() == 17
352        && bytes[0] == b's'
353        && bytes[1..]
354            .iter()
355            .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
356    if valid {
357        Ok(())
358    } else {
359        Err(format!("invalid surface id: {id}"))
360    }
361}
362
363/// `<surface_token_dir()>/<id>.token`. Errors if the id is invalid or the directory is unknown.
364pub fn surface_token_path_for_id(surface_id: &str) -> Result<PathBuf, String> {
365    validate_surface_id(surface_id)?;
366    let dir = surface_token_dir().ok_or_else(|| {
367        "cannot determine surface token directory: neither XDG_STATE_HOME nor HOME is set"
368            .to_string()
369    })?;
370    Ok(dir.join(format!("{surface_id}.token")))
371}
372
373/// `<surface_token_dir()>/<id>.message`. Errors if the id is invalid or the directory is unknown.
374pub fn surface_message_path_for_id(surface_id: &str) -> Result<PathBuf, String> {
375    validate_surface_id(surface_id)?;
376    let dir = surface_token_dir().ok_or_else(|| {
377        "cannot determine surface token directory: neither XDG_STATE_HOME nor HOME is set"
378            .to_string()
379    })?;
380    Ok(dir.join(format!("{surface_id}.message")))
381}
382
383const MAX_SYMLINK_DEPTH: usize = 40;
384
385enum PathPart {
386    Prefix(std::ffi::OsString),
387    RootDir,
388    CurDir,
389    ParentDir,
390    Normal(std::ffi::OsString),
391}
392
393impl From<std::path::Component<'_>> for PathPart {
394    fn from(comp: std::path::Component<'_>) -> Self {
395        match comp {
396            std::path::Component::Prefix(p) => Self::Prefix(p.as_os_str().to_os_string()),
397            std::path::Component::RootDir => Self::RootDir,
398            std::path::Component::CurDir => Self::CurDir,
399            std::path::Component::ParentDir => Self::ParentDir,
400            std::path::Component::Normal(s) => Self::Normal(s.to_os_string()),
401        }
402    }
403}
404
405fn resolve_real_path(path: &Path) -> Result<PathBuf, String> {
406    let abs = if path.is_absolute() {
407        path.to_path_buf()
408    } else {
409        std::env::current_dir()
410            .map_err(|e| format!("cannot determine current directory: {e}"))?
411            .join(path)
412    };
413    match abs.canonicalize() {
414        Ok(resolved) => return Ok(resolved),
415        Err(e)
416            if matches!(
417                e.kind(),
418                std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
419            ) => {}
420        Err(e) => return Err(format!("cannot canonicalize {}: {e}", abs.display())),
421    }
422
423    let mut queue: std::collections::VecDeque<PathPart> =
424        abs.components().map(PathPart::from).collect();
425    let mut cur = PathBuf::new();
426    let mut missing = false;
427    let mut symlinks_followed = 0usize;
428
429    while let Some(part) = queue.pop_front() {
430        match part {
431            PathPart::Prefix(p) => cur.push(p),
432            PathPart::RootDir => cur.push(std::path::MAIN_SEPARATOR_STR),
433            PathPart::CurDir => {}
434            PathPart::ParentDir => {
435                cur.pop();
436            }
437            PathPart::Normal(name) => {
438                cur.push(&name);
439                if missing {
440                    continue;
441                }
442                match std::fs::symlink_metadata(&cur) {
443                    Ok(meta) if meta.file_type().is_symlink() => {
444                        symlinks_followed += 1;
445                        if symlinks_followed > MAX_SYMLINK_DEPTH {
446                            return Err(format!(
447                                "cannot canonicalize {}: too many levels of symbolic links",
448                                abs.display()
449                            ));
450                        }
451                        let target = std::fs::read_link(&cur)
452                            .map_err(|e| format!("cannot read link {}: {e}", cur.display()))?;
453                        if target.is_absolute() {
454                            cur.clear();
455                        } else {
456                            cur.pop();
457                        }
458                        for comp in target.components().rev() {
459                            queue.push_front(PathPart::from(comp));
460                        }
461                    }
462                    Ok(_) => {}
463                    Err(e)
464                        if matches!(
465                            e.kind(),
466                            std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
467                        ) =>
468                    {
469                        cur.pop();
470                        if !cur.as_os_str().is_empty() {
471                            cur = cur.canonicalize().map_err(|ce| {
472                                format!("cannot canonicalize {}: {ce}", cur.display())
473                            })?;
474                        }
475                        cur.push(&name);
476                        missing = true;
477                    }
478                    Err(e) => {
479                        return Err(format!("cannot canonicalize {}: {e}", cur.display()));
480                    }
481                }
482            }
483        }
484    }
485
486    if !missing && !cur.as_os_str().is_empty() {
487        if let Ok(resolved) = cur.canonicalize() {
488            return Ok(resolved);
489        }
490    }
491    Ok(cur)
492}
493
494fn resolve_protected_prefix(path: &Path) -> Result<PathBuf, String> {
495    let abs = if path.is_absolute() {
496        path.to_path_buf()
497    } else {
498        std::env::current_dir()
499            .map_err(|e| format!("cannot determine current directory: {e}"))?
500            .join(path)
501    };
502    let mut probe = abs.as_path();
503    let mut tail: Vec<std::ffi::OsString> = Vec::new();
504    loop {
505        match probe.canonicalize() {
506            Ok(mut resolved) => {
507                for part in tail.into_iter().rev() {
508                    resolved.push(part);
509                }
510                return Ok(resolved);
511            }
512            Err(e)
513                if matches!(
514                    e.kind(),
515                    std::io::ErrorKind::NotFound
516                        | std::io::ErrorKind::NotADirectory
517                        | std::io::ErrorKind::PermissionDenied
518                ) =>
519            {
520                let Some(name) = probe.file_name() else {
521                    return Err(format!("cannot canonicalize {}: {e}", probe.display()));
522                };
523                tail.push(name.to_os_string());
524                let Some(parent) = probe.parent() else {
525                    return Err(format!("cannot canonicalize {}: {e}", probe.display()));
526                };
527                probe = parent;
528            }
529            Err(e) => {
530                return Err(format!("cannot canonicalize {}: {e}", probe.display()));
531            }
532        }
533    }
534}
535
536/// Returns the paths denied for reading by the sandbox profile, resolved on their existing prefix.
537pub fn protected_read_paths() -> Result<Vec<PathBuf>, String> {
538    let mut raw = Vec::new();
539    if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
540        let home_path = Path::new(&home);
541        raw.extend(read_denied(home_path));
542        let blyte_env = home_path.join(".config/blyte/env");
543        if !raw.contains(&blyte_env) {
544            raw.push(blyte_env);
545        }
546    }
547    if let Some(dir) = surface_token_dir() {
548        if !raw.contains(&dir) {
549            raw.push(dir);
550        }
551    }
552    let mut out = Vec::with_capacity(raw.len());
553    for path in raw {
554        let resolved = resolve_protected_prefix(&path)?;
555        if !out.contains(&resolved) {
556            out.push(resolved);
557        }
558    }
559    Ok(out)
560}
561
562pub(crate) fn is_protected_read_with(path: &Path, protected: &[PathBuf]) -> Result<bool, String> {
563    let real = resolve_real_path(path)?;
564    let dot_env = std::ffi::OsStr::new(".env");
565    if path.file_name() == Some(dot_env) || real.file_name() == Some(dot_env) {
566        return Ok(true);
567    }
568    Ok(protected.iter().any(|p| real.starts_with(p)))
569}
570
571/// Reports whether `path` resolves to a credential path or `.env` file denied for reading.
572pub fn is_protected_read(path: &Path) -> Result<bool, String> {
573    let protected = protected_read_paths()?;
574    is_protected_read_with(path, &protected)
575}
576
577/// Reports whether `workspace_root` is a non-repository research scratch folder under `state_dir`.
578pub fn is_run_scratch_workspace(workspace_root: &Path, state_dir: &Path) -> bool {
579    let Ok(rel) = workspace_root.strip_prefix(state_dir) else {
580        return false;
581    };
582    let mut comps = rel.components();
583    let (Some(c0), Some(c1), Some(c2), Some(c3), None) = (
584        comps.next(),
585        comps.next(),
586        comps.next(),
587        comps.next(),
588        comps.next(),
589    ) else {
590        return false;
591    };
592    let (
593        std::path::Component::Normal(p0),
594        std::path::Component::Normal(p1),
595        std::path::Component::Normal(p2),
596        std::path::Component::Normal(p3),
597    ) = (c0, c1, c2, c3)
598    else {
599        return false;
600    };
601    p0 == "folders"
602        && p2 == "runs"
603        && p3
604            .to_str()
605            .and_then(|s| s.strip_suffix(".scratch"))
606            .is_some_and(|prefix| !prefix.is_empty())
607        && p1.to_str().is_some_and(|s| {
608            s.len() == 16 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
609        })
610}
611
612pub(crate) fn is_in_blyte_own_dir(real_target: &Path) -> Result<bool, String> {
613    let mut raw = Vec::new();
614    if let Some(dir) = state_blyte_dir() {
615        raw.push(dir);
616    }
617    if let Some(xdg) = std::env::var_os("XDG_STATE_HOME").filter(|d| !d.is_empty()) {
618        raw.push(PathBuf::from(xdg).join("blyte"));
619    }
620    if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
621        let home_path = PathBuf::from(home);
622        raw.push(home_path.join(".local").join("state").join("blyte"));
623        raw.push(home_path.join(".config").join("blyte"));
624    }
625    for dir in raw {
626        let resolved = resolve_protected_prefix(&dir)?;
627        if real_target.starts_with(&resolved) {
628            return Ok(true);
629        }
630    }
631    Ok(false)
632}
633
634fn canonicalize_existing_prefix(path: &Path) -> PathBuf {
635    if let Ok(canon) = path.canonicalize() {
636        return canon;
637    }
638    let mut tail = Vec::new();
639    let mut cur = path;
640    while let Some(name) = cur.file_name() {
641        tail.push(name.to_os_string());
642        match cur.parent() {
643            Some(parent) => {
644                cur = parent;
645                if let Ok(mut canon) = cur.canonicalize() {
646                    for part in tail.into_iter().rev() {
647                        canon.push(part);
648                    }
649                    return canon;
650                }
651            }
652            None => break,
653        }
654    }
655    path.to_path_buf()
656}
657
658#[cfg(target_os = "macos")]
659const PROTECTED_HOME_PATHS: &[&str] = &[
660    ".cargo/bin",
661    ".cargo/config",
662    ".cargo/config.toml",
663    ".cargo/credentials",
664    ".cargo/credentials.toml",
665    ".cargo/env",
666    ".cargo/env.fish",
667    ".cargo/env.nu",
668    ".local/bin",
669    ".local/lib",
670    ".local/state/blyte",
671    ".local/share/uv/tools",
672    ".local/share/mise",
673    ".local/share/pipx",
674    ".local/share/keyrings",
675    ".gradle/init.d",
676    ".m2/settings.xml",
677];
678
679#[cfg(target_os = "macos")]
680fn deny_protected_home_writes(mut profile: String) -> String {
681    if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
682        let home_path = PathBuf::from(home);
683        for sub in PROTECTED_HOME_PATHS {
684            let escaped = escape_path(&canonicalize_existing_prefix(&home_path.join(sub)));
685            profile.push_str(&format!(r#"(deny file-write* (subpath "{escaped}"))"#));
686        }
687    }
688    profile
689}
690
691#[cfg(target_os = "macos")]
692/// Seatbelt lets an earlier `allow file-read-data` override a later `deny file-read*`, so each read
693/// deny here is written for `file-read-data` as well.
694fn deny_state_blyte_write(mut profile: String) -> String {
695    if let Some(dir) = state_blyte_dir() {
696        let escaped = escape_path(&canonicalize_existing_prefix(&dir));
697        profile.push_str(&format!(r#"(deny file-write* (subpath "{escaped}"))"#));
698    }
699    if let Some(dir) = surface_token_dir() {
700        let escaped = escape_path(&canonicalize_existing_prefix(&dir));
701        profile.push_str(&format!(
702            r#"(deny file-read* (subpath "{escaped}"))(deny file-read-data (subpath "{escaped}"))"#
703        ));
704    }
705    if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
706        let env_path = PathBuf::from(home).join(".config/blyte/env");
707        let escaped = escape_path(&canonicalize_existing_prefix(&env_path));
708        profile.push_str(&format!(
709            r#"(deny file-read* (subpath "{escaped}"))(deny file-read-data (subpath "{escaped}"))"#
710        ));
711    }
712    profile
713}
714
715/// Computes the default list of write-allowed paths for a local workspace run.
716///
717/// Includes the workspace root, the git common directory (if in a git repo), system temp dirs,
718/// and common developer caches under `$HOME`.
719///
720/// # Arguments
721///
722/// * `root` - Workspace directory path.
723///
724/// # Returns
725///
726/// A vector of paths that should be allowed for file writes under the sandbox.
727pub fn default_allowed(root: &Path) -> Vec<PathBuf> {
728    let mut allowed = Vec::new();
729    allowed.push(root.to_path_buf());
730
731    if let Some(common_dir) = git_common_dir(root) {
732        allowed.push(common_dir);
733    }
734
735    allowed.push(PathBuf::from("/private/tmp"));
736    allowed.push(PathBuf::from("/private/var/folders"));
737    allowed.push(PathBuf::from("/tmp"));
738    allowed.push(PathBuf::from("/var/tmp"));
739    allowed.push(PathBuf::from("/dev"));
740
741    if let Some(tmp) = std::env::var_os("TMPDIR") {
742        if !tmp.is_empty() {
743            allowed.push(PathBuf::from(tmp));
744        }
745    }
746
747    push_home_grants(&mut allowed);
748
749    // Allow tool caches in enclosing node_modules above the worktree (vitest's .vite-temp, etc.).
750    let home = std::env::var_os("HOME")
751        .filter(|h| !h.is_empty())
752        .map(PathBuf::from);
753    let home_canon = home.as_deref().and_then(|h| h.canonicalize().ok());
754    let is_home = |p: &Path| -> bool {
755        if let Some(h) = home.as_deref() {
756            if p == h {
757                return true;
758            }
759        }
760        if let Some(hc) = home_canon.as_deref() {
761            if p == hc || p.canonicalize().ok().as_deref() == Some(hc) {
762                return true;
763            }
764        }
765        false
766    };
767
768    if !is_home(root) {
769        for a in root.ancestors().skip(1) {
770            if is_home(a) {
771                break;
772            }
773            let nm = a.join("node_modules");
774            if nm.is_dir() {
775                for name in [".vite-temp", ".vite", ".cache"] {
776                    let dir = nm.join(name);
777                    let _ = std::fs::create_dir_all(&dir);
778                    allowed.push(dir);
779                }
780            }
781        }
782    }
783
784    allowed
785}
786
787fn git_common_dir(root: &Path) -> Option<PathBuf> {
788    let output = std::process::Command::new("git")
789        .args(["-C"])
790        .arg(root)
791        .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
792        .output()
793        .ok()?;
794    if !output.status.success() {
795        return None;
796    }
797    let text = String::from_utf8_lossy(&output.stdout);
798    let line = text.lines().map(str::trim).find(|s| !s.is_empty())?;
799    Some(PathBuf::from(line))
800}
801
802/// Returns whether `root` is inside a git repository.
803pub fn is_git_repository(root: &Path) -> bool {
804    git_common_dir(root).is_some()
805}
806
807fn canonicalize_or_missing(path: &Path) -> Result<PathBuf, String> {
808    match path.canonicalize() {
809        Ok(p) => Ok(p),
810        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(path.to_path_buf()),
811        Err(e) => Err(format!("cannot canonicalize {}: {e}", path.display())),
812    }
813}
814
815fn main_checkout_root(root: &Path) -> PathBuf {
816    if let Some(common_dir) = git_common_dir(root) {
817        if common_dir.file_name() == Some(std::ffi::OsStr::new(".git")) {
818            if let Some(main_root) = common_dir.parent() {
819                return main_root
820                    .canonicalize()
821                    .unwrap_or_else(|_| main_root.to_path_buf());
822            }
823        }
824    }
825    root.canonicalize().unwrap_or_else(|_| root.to_path_buf())
826}
827
828fn main_checkout_root_checked(root: &Path) -> Result<PathBuf, String> {
829    if let Some(common_dir) = git_common_dir(root) {
830        if common_dir.file_name() == Some(std::ffi::OsStr::new(".git")) {
831            if let Some(main_root) = common_dir.parent() {
832                return canonicalize_or_missing(main_root);
833            }
834        }
835    }
836    canonicalize_or_missing(root)
837}
838
839fn create_private_temp_dir(path: &Path) -> Result<bool, String> {
840    if let Some(parent) = path.parent() {
841        std::fs::create_dir_all(parent).map_err(|e| {
842            format!(
843                "cannot create private temp directory {}: {e}",
844                path.display()
845            )
846        })?;
847    }
848    #[cfg(unix)]
849    {
850        use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
851        let mut builder = std::fs::DirBuilder::new();
852        builder.mode(0o700);
853        let created = match builder.create(path) {
854            Ok(()) => true,
855            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
856                let meta = std::fs::metadata(path).map_err(|me| {
857                    format!(
858                        "cannot inspect private temp directory {}: {me}",
859                        path.display()
860                    )
861                })?;
862                if !meta.is_dir() {
863                    return Err(format!(
864                        "cannot create private temp directory {}: path exists and is not a directory",
865                        path.display()
866                    ));
867                }
868                false
869            }
870            Err(e) => {
871                return Err(format!(
872                    "cannot create private temp directory {}: {e}",
873                    path.display()
874                ));
875            }
876        };
877        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).map_err(|e| {
878            format!(
879                "cannot set permissions on private temp directory {}: {e}",
880                path.display()
881            )
882        })?;
883        Ok(created)
884    }
885    #[cfg(not(unix))]
886    {
887        match std::fs::create_dir(path) {
888            Ok(()) => Ok(true),
889            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
890                let meta = std::fs::metadata(path).map_err(|me| {
891                    format!(
892                        "cannot inspect private temp directory {}: {me}",
893                        path.display()
894                    )
895                })?;
896                if !meta.is_dir() {
897                    return Err(format!(
898                        "cannot create private temp directory {}: path exists and is not a directory",
899                        path.display()
900                    ));
901                }
902                Ok(false)
903            }
904            Err(e) => Err(format!(
905                "cannot create private temp directory {}: {e}",
906                path.display()
907            )),
908        }
909    }
910}
911
912/// Returns the `.wt/tasks` directory under the main checkout for `root`.
913pub fn conversation_tasks_dir(root: &Path) -> PathBuf {
914    main_checkout_root(root).join(".wt").join("tasks")
915}
916
917/// Writable directories for a conversation sandbox and an optional private `TMPDIR` created when
918/// one or more default entries contained the repository root.
919#[derive(Debug, Clone, PartialEq, Eq)]
920pub struct ConversationPaths {
921    pub allowed: Vec<PathBuf>,
922    pub tmpdir: Option<PathBuf>,
923    pub created_tmpdir: bool,
924}
925
926/// Sandbox profile and optional private `TMPDIR` for a conversation shell.
927#[derive(Debug, Clone, PartialEq, Eq)]
928pub struct ConversationSandbox {
929    pub profile: Profile,
930    pub tmpdir: Option<PathBuf>,
931}
932
933/// Computes the writable directories for the `--converse` sandbox and creates a private temp
934/// directory under `<root>/.wt/tmp/<pid>` whenever an ancestor of `root` (or `root` itself) had to
935/// be removed from the default list.
936pub fn conversation_paths(root: &Path) -> Result<ConversationPaths, String> {
937    let root_cmp = canonicalize_or_missing(root)?;
938    let common_dir = git_common_dir(root);
939    let is_repo = common_dir.is_some();
940    let main_cmp = match common_dir {
941        Some(ref dir) if dir.file_name() == Some(std::ffi::OsStr::new(".git")) => {
942            match dir.parent() {
943                Some(main_root) => canonicalize_or_missing(main_root)?,
944                None => root_cmp.clone(),
945            }
946        }
947        _ => root_cmp.clone(),
948    };
949    let mut raw = vec![
950        PathBuf::from("/private/tmp"),
951        PathBuf::from("/private/var/folders"),
952        PathBuf::from("/tmp"),
953        PathBuf::from("/var/tmp"),
954        PathBuf::from("/dev"),
955    ];
956
957    if let Some(tmp) = std::env::var_os("TMPDIR") {
958        if !tmp.is_empty() {
959            raw.push(PathBuf::from(tmp));
960        }
961    }
962
963    push_home_grants(&mut raw);
964
965    let mut allowed = Vec::with_capacity(raw.len() + 2);
966    if is_repo {
967        allowed.push(main_cmp.join(".wt").join("tasks"));
968    }
969    let mut removed = false;
970    for entry in raw {
971        let entry_cmp = canonicalize_or_missing(&entry)?;
972        if root_cmp.starts_with(&entry_cmp) || main_cmp.starts_with(&entry_cmp) {
973            removed = true;
974        } else {
975            allowed.push(entry);
976        }
977    }
978
979    let (tmpdir, created_tmpdir) = if removed {
980        let private_tmp = if is_repo {
981            root_cmp
982                .join(".wt")
983                .join("tmp")
984                .join(std::process::id().to_string())
985        } else {
986            let mut temp_grants = Vec::new();
987            if let Some(tmp) = std::env::var_os("TMPDIR") {
988                if !tmp.is_empty() {
989                    temp_grants.push(PathBuf::from(tmp));
990                }
991            }
992            temp_grants.push(PathBuf::from("/private/tmp"));
993            temp_grants.push(PathBuf::from("/tmp"));
994            temp_grants.push(PathBuf::from("/var/tmp"));
995
996            let mut chosen = None;
997            for grant in temp_grants {
998                let grant_cmp = canonicalize_or_missing(&grant)?;
999                if root_cmp.starts_with(&grant_cmp) || grant_cmp.starts_with(&root_cmp) {
1000                    continue;
1001                }
1002                if grant_cmp.is_dir() {
1003                    chosen = Some(grant_cmp);
1004                    break;
1005                }
1006            }
1007            let Some(grant) = chosen else {
1008                return Err(format!(
1009                    "cannot choose private temp directory for {}: no remaining writable temp directory",
1010                    root.display()
1011                ));
1012            };
1013            grant.join(format!("blyte-{}", std::process::id()))
1014        };
1015        let created = create_private_temp_dir(&private_tmp)?;
1016        allowed.push(private_tmp.clone());
1017        (Some(private_tmp), created)
1018    } else {
1019        (None, false)
1020    };
1021
1022    Ok(ConversationPaths {
1023        allowed,
1024        tmpdir,
1025        created_tmpdir,
1026    })
1027}
1028
1029/// Returns the writable directories allowed for the `--converse` sandboxed shell:
1030/// `.wt/tasks` under the main checkout, system temporary directories, and common developer caches,
1031/// excluding any entry that is `root` or an ancestor of it.
1032pub fn conversation_allowed(root: &Path) -> Result<Vec<PathBuf>, String> {
1033    Ok(conversation_paths(root)?.allowed)
1034}
1035
1036fn path_exists(path: &Path) -> Result<bool, String> {
1037    match std::fs::metadata(path) {
1038        Ok(_) => Ok(true),
1039        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
1040        Err(e) => Err(format!("cannot check {}: {e}", path.display())),
1041    }
1042}
1043
1044pub(crate) fn is_open_edit_worktree_id(
1045    wt_dir: &Path,
1046    id: &std::ffi::OsStr,
1047) -> Result<bool, String> {
1048    let mut edit_name = id.to_os_string();
1049    edit_name.push(".edit.json");
1050    let edit_marker = wt_dir.join(edit_name);
1051    if !path_exists(&edit_marker)? {
1052        return Ok(false);
1053    }
1054    let mut summary_name = id.to_os_string();
1055    summary_name.push(".json");
1056    let summary_marker = wt_dir.join(summary_name);
1057    if path_exists(&summary_marker)? {
1058        return Ok(false);
1059    }
1060    let worktree = wt_dir.join(id);
1061    match std::fs::metadata(&worktree) {
1062        Ok(m) => Ok(m.is_dir()),
1063        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
1064        Err(e) => Err(format!("cannot check {}: {e}", worktree.display())),
1065    }
1066}
1067
1068/// Returns the sorted worktree directories `<main_checkout>/.wt/<id>` for currently open direct
1069/// edits (where `<id>.edit.json` exists, `<id>.json` does not, and `<id>` is a directory).
1070pub fn open_edit_worktrees(main_checkout: &Path) -> Result<Vec<PathBuf>, String> {
1071    let wt_dir = main_checkout.join(".wt");
1072    let entries = match std::fs::read_dir(&wt_dir) {
1073        Ok(e) => e,
1074        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1075        Err(e) => return Err(format!("cannot read {}: {e}", wt_dir.display())),
1076    };
1077    let mut worktrees = Vec::new();
1078    for entry in entries {
1079        let entry = entry.map_err(|e| format!("cannot read {}: {e}", wt_dir.display()))?;
1080        let name = entry.file_name();
1081        let Some(name_str) = name.to_str() else {
1082            continue;
1083        };
1084        let Some(id) = name_str.strip_suffix(".edit.json") else {
1085            continue;
1086        };
1087        if id.is_empty() {
1088            continue;
1089        }
1090        if is_open_edit_worktree_id(&wt_dir, std::ffi::OsStr::new(id))? {
1091            worktrees.push(wt_dir.join(id));
1092        }
1093    }
1094    worktrees.sort();
1095    Ok(worktrees)
1096}
1097
1098#[cfg(target_os = "macos")]
1099fn allow_edit_worktrees(mut base: String, edit_worktrees: &[PathBuf]) -> String {
1100    for wt in edit_worktrees {
1101        let canon = wt.canonicalize().unwrap_or_else(|_| wt.to_path_buf());
1102        let escaped_wt = escape_path(&canon);
1103        let escaped_git = escape_path(&canon.join(".git"));
1104        base.push_str(&format!(
1105            r#"(allow file-write* (subpath "{escaped_wt}"))(deny file-write* (literal "{escaped_git}"))"#
1106        ));
1107    }
1108    base
1109}
1110
1111/// Returns the `--converse` sandbox profile and optional private `TMPDIR` for the current platform.
1112pub fn conversation_sandbox(
1113    root: &Path,
1114    allow_read: &[PathBuf],
1115) -> Result<ConversationSandbox, String> {
1116    conversation_sandbox_net(root, allow_read, true)
1117}
1118
1119/// Returns the `--converse` sandbox profile and optional private `TMPDIR` with network configuration.
1120pub fn conversation_sandbox_net(
1121    root: &Path,
1122    allow_read: &[PathBuf],
1123    network: bool,
1124) -> Result<ConversationSandbox, String> {
1125    conversation_sandbox_with_edits(root, allow_read, network, &[])
1126}
1127
1128#[cfg(not(target_os = "macos"))]
1129const CARVE_WRITE_EXCLUDED: &[&str] = &[
1130    "credentials",
1131    "credentials.toml",
1132    "bin",
1133    "config",
1134    "config.toml",
1135    "env",
1136    "env.fish",
1137    "env.nu",
1138];
1139
1140#[cfg(not(target_os = "macos"))]
1141fn confine_linux_sandbox(
1142    write: Vec<PathBuf>,
1143    read: Vec<PathBuf>,
1144    allow_read: &[PathBuf],
1145    network: bool,
1146    existing_tmpdir: Option<PathBuf>,
1147) -> Result<ConversationSandbox, String> {
1148    let home = std::env::var_os("HOME")
1149        .filter(|h| !h.is_empty())
1150        .map(PathBuf::from);
1151    if let Some(home_path) = home.as_deref() {
1152        let cargo_dir = home_path.join(".cargo");
1153        if cargo_dir.is_dir() {
1154            for sub in ["registry", "git"] {
1155                let dir = cargo_dir.join(sub);
1156                std::fs::create_dir_all(&dir)
1157                    .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
1158            }
1159        }
1160    }
1161
1162    let protected = protected_read_paths()?;
1163    let mut own_protected = Vec::new();
1164    if let Some(home_path) = home.as_deref() {
1165        own_protected.push(resolve_protected_prefix(
1166            &home_path.join(".config/blyte/env"),
1167        )?);
1168    }
1169    if let Some(dir) = surface_token_dir() {
1170        let resolved = resolve_protected_prefix(&dir)?;
1171        if !own_protected.contains(&resolved) {
1172            own_protected.push(resolved);
1173        }
1174    }
1175
1176    let mut temp_dirs = vec![
1177        PathBuf::from("/tmp"),
1178        PathBuf::from("/var/tmp"),
1179        PathBuf::from("/private/tmp"),
1180        PathBuf::from("/private/var/folders"),
1181    ];
1182    let env_tmpdir = std::env::var_os("TMPDIR")
1183        .filter(|t| !t.is_empty())
1184        .map(PathBuf::from);
1185    if let Some(tmp) = env_tmpdir.as_ref() {
1186        temp_dirs.push(tmp.clone());
1187    }
1188
1189    let mut carve_dirs = Vec::new();
1190    if let Some(home_path) = home.as_deref() {
1191        carve_dirs.push(home_path.join(".cargo"));
1192    }
1193
1194    let descend_dirs = [PathBuf::from("/var"), PathBuf::from("/opt")];
1195    let descend_stop: Vec<PathBuf> = home.into_iter().collect();
1196
1197    let rules = grants::GrantRules {
1198        protected: &protected,
1199        own_protected: &own_protected,
1200        temp_dirs: &temp_dirs,
1201        carve_dirs: &carve_dirs,
1202        carve_write_excluded: CARVE_WRITE_EXCLUDED,
1203        descend_dirs: &descend_dirs,
1204        descend_stop: &descend_stop,
1205        user_allow_read: allow_read,
1206    };
1207    let mut confined = grants::confine_grants(write, read, &rules)?;
1208
1209    let tmpdir = if !confined.dropped_temp.is_empty() && existing_tmpdir.is_none() {
1210        let mut candidates = Vec::new();
1211        if let Some(tmp) = env_tmpdir {
1212            candidates.push(tmp);
1213        }
1214        candidates.push(PathBuf::from("/tmp"));
1215        candidates.push(PathBuf::from("/var/tmp"));
1216        let chosen = grants::choose_private_tmp(&candidates, &confined.dropped_temp, &protected)?;
1217        create_private_temp_dir(&chosen)?;
1218        confined.write.push(chosen.clone());
1219        Some(chosen)
1220    } else {
1221        existing_tmpdir
1222    };
1223
1224    Ok(ConversationSandbox {
1225        profile: Profile::LandlockConfined {
1226            write: confined.write,
1227            read: confined.read,
1228            block_tcp: !network,
1229        },
1230        tmpdir,
1231    })
1232}
1233
1234/// Returns the `--converse` sandbox profile and optional private `TMPDIR` allowing writes in the
1235/// given open edit worktrees.
1236pub fn conversation_sandbox_with_edits(
1237    root: &Path,
1238    allow_read: &[PathBuf],
1239    network: bool,
1240    edit_worktrees: &[PathBuf],
1241) -> Result<ConversationSandbox, String> {
1242    let paths = conversation_paths(root)?;
1243    #[cfg(target_os = "macos")]
1244    {
1245        let deny_read = match std::env::var_os("HOME") {
1246            Some(home) if !home.is_empty() => read_denied(Path::new(&home)),
1247            _ => Vec::new(),
1248        };
1249        let base = deny_protected_home_writes(deny_state_blyte_write(allow_edit_worktrees(
1250            profile_with(root, &paths.allowed, &deny_read, allow_read),
1251            edit_worktrees,
1252        )));
1253        let profiled = if network {
1254            base
1255        } else {
1256            let socks = match std::env::var_os("HOME") {
1257                Some(home) if !home.is_empty() => docker_sockets(Path::new(&home)),
1258                _ => Vec::new(),
1259            };
1260            offline(base, &socks)
1261        };
1262        Ok(ConversationSandbox {
1263            profile: Profile::Seatbelt(deny_unix_sockets(profiled, &current_agent_sockets())),
1264            tmpdir: paths.tmpdir,
1265        })
1266    }
1267    #[cfg(not(target_os = "macos"))]
1268    {
1269        let home = std::env::var_os("HOME");
1270        let home_path = home.as_ref().filter(|h| !h.is_empty()).map(Path::new);
1271        let mut extra_read = vec![root.to_path_buf()];
1272        if let Some(common_dir) = git_common_dir(root) {
1273            extra_read.push(common_dir);
1274        }
1275        let main_wt = main_checkout_root_checked(root)?.join(".wt");
1276        if main_wt.exists() {
1277            extra_read.push(main_wt);
1278        }
1279        extra_read.extend_from_slice(allow_read);
1280        let mut write = paths.allowed;
1281        write.extend(edit_worktrees.iter().cloned());
1282        let read = read_allowed(home_path, &extra_read);
1283        confine_linux_sandbox(write, read, allow_read, network, paths.tmpdir)
1284    }
1285}
1286
1287/// Builds the `--converse` sandbox including all currently open edit worktrees.
1288pub fn conversation_sandbox_for_open_edits(
1289    root: &Path,
1290    allow_read: &[PathBuf],
1291    network: bool,
1292) -> Result<ConversationSandbox, String> {
1293    let main = main_checkout_root_checked(root)?;
1294    let edits = open_edit_worktrees(&main)?;
1295    conversation_sandbox_with_edits(root, allow_read, network, &edits)
1296}
1297
1298/// Returns the `--converse` sandbox profile for the current platform.
1299pub fn conversation_profile(root: &Path, allow_read: &[PathBuf]) -> Result<Profile, String> {
1300    Ok(conversation_sandbox(root, allow_read)?.profile)
1301}
1302
1303/// Returns the `--converse` sandbox profile with network configuration.
1304pub fn conversation_profile_net(
1305    root: &Path,
1306    allow_read: &[PathBuf],
1307    network: bool,
1308) -> Result<Profile, String> {
1309    Ok(conversation_sandbox_net(root, allow_read, network)?.profile)
1310}
1311
1312/// Builds the `--converse` sandbox profile including all currently open edit worktrees.
1313pub fn conversation_profile_for_open_edits(
1314    root: &Path,
1315    allow_read: &[PathBuf],
1316    network: bool,
1317) -> Result<Profile, String> {
1318    Ok(conversation_sandbox_for_open_edits(root, allow_read, network)?.profile)
1319}
1320
1321/// Returns the standard Unix socket paths used by Docker and container runtimes.
1322pub fn docker_sockets(home: &Path) -> Vec<PathBuf> {
1323    vec![
1324        PathBuf::from("/var/run/docker.sock"),
1325        home.join(".docker/run/docker.sock"),
1326        home.join(".colima/default/docker.sock"),
1327        home.join(".orbstack/run/docker.sock"),
1328    ]
1329}
1330
1331/// Returns the Unix socket paths used by ssh and gpg agents, in order and without duplicates.
1332///
1333/// Includes `ssh_auth_sock` when given, followed by the standard gpg-agent and 1Password agent
1334/// socket paths under `home`. On Linux, Landlock does not control connecting to a Unix socket by
1335/// path, so only environment scrubbing (`SSH_AUTH_SOCK` and `SSH_AGENT_PID`) applies there.
1336pub fn agent_sockets(home: &Path, ssh_auth_sock: Option<&Path>) -> Vec<PathBuf> {
1337    let mut out = Vec::new();
1338    if let Some(sock) = ssh_auth_sock {
1339        if !sock.as_os_str().is_empty() {
1340            out.push(sock.to_path_buf());
1341        }
1342    }
1343    for rel in [
1344        ".gnupg/S.gpg-agent.ssh",
1345        ".gnupg/S.gpg-agent",
1346        ".1password/agent.sock",
1347        "Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock",
1348    ] {
1349        let path = home.join(rel);
1350        if !out.contains(&path) {
1351            out.push(path);
1352        }
1353    }
1354    out
1355}
1356
1357#[cfg(target_os = "macos")]
1358fn current_agent_sockets() -> Vec<PathBuf> {
1359    let ssh_auth_sock = if crate::shell::is_pass_env("SSH_AUTH_SOCK") {
1360        None
1361    } else {
1362        std::env::var_os("SSH_AUTH_SOCK")
1363            .filter(|v| !v.is_empty())
1364            .map(PathBuf::from)
1365    };
1366    match std::env::var_os("HOME") {
1367        Some(home) if !home.is_empty() => agent_sockets(Path::new(&home), ssh_auth_sock.as_deref()),
1368        _ => ssh_auth_sock.into_iter().collect(),
1369    }
1370}
1371
1372fn deny_unix_sockets(mut profile: String, sockets: &[PathBuf]) -> String {
1373    if sockets.is_empty() {
1374        return profile;
1375    }
1376    let mut paths = Vec::new();
1377    for s in sockets {
1378        if !paths.contains(s) {
1379            paths.push(s.clone());
1380        }
1381        let canon = canonicalize_existing_prefix(s);
1382        if canon != *s && !paths.contains(&canon) {
1383            paths.push(canon);
1384        }
1385    }
1386    profile.push_str("(deny network-outbound");
1387    for p in paths {
1388        let escaped = escape_path(&p);
1389        profile.push_str(&format!(
1390            r#" (remote unix-socket (path-literal "{escaped}"))"#
1391        ));
1392    }
1393    profile.push(')');
1394    profile
1395}
1396
1397/// Augments an SBPL profile string with network-denial rules, allowing loopback and unix sockets,
1398/// then denying the specified Docker unix sockets (and their canonicalised paths if different).
1399pub fn offline(mut profile: String, docker_sockets: &[PathBuf]) -> String {
1400    profile.push_str(
1401        r#"(deny network-outbound)(allow network-outbound (remote ip "localhost:*"))(allow network-outbound (remote unix-socket))"#,
1402    );
1403    deny_unix_sockets(profile, docker_sockets)
1404}
1405
1406#[cfg(target_os = "macos")]
1407fn is_in_non_state_protected_home(real_path: &Path) -> bool {
1408    let in_blyte_state = state_blyte_dir().is_some_and(|state_dir| {
1409        let real_state = canonicalize_existing_prefix(&state_dir);
1410        real_path.starts_with(&real_state)
1411    }) || std::env::var_os("HOME")
1412        .filter(|h| !h.is_empty())
1413        .is_some_and(|home| {
1414            let real_default_state =
1415                canonicalize_existing_prefix(&PathBuf::from(home).join(".local/state/blyte"));
1416            real_path.starts_with(&real_default_state)
1417        });
1418    !in_blyte_state
1419        && std::env::var_os("HOME")
1420            .filter(|h| !h.is_empty())
1421            .is_some_and(|home| {
1422                let home_path = PathBuf::from(home);
1423                PROTECTED_HOME_PATHS.iter().any(|sub| {
1424                    let protected = canonicalize_existing_prefix(&home_path.join(sub));
1425                    real_path.starts_with(&protected)
1426                })
1427            })
1428}
1429
1430#[cfg(target_os = "macos")]
1431fn default_profile_base(root: &Path, allow_read: &[PathBuf]) -> String {
1432    let deny_read = match std::env::var_os("HOME") {
1433        Some(home) if !home.is_empty() => read_denied(Path::new(&home)),
1434        _ => Vec::new(),
1435    };
1436    let mut profile = deny_protected_home_writes(deny_state_blyte_write(profile_with(
1437        root,
1438        &default_allowed(root),
1439        &deny_read,
1440        allow_read,
1441    )));
1442    let real_root = canonicalize_existing_prefix(root);
1443    let is_scratch = state_blyte_dir().is_some_and(|state_dir| {
1444        let real_state = canonicalize_existing_prefix(&state_dir);
1445        is_run_scratch_workspace(&real_root, &real_state)
1446    });
1447    let reallow_root = is_scratch || is_in_non_state_protected_home(&real_root);
1448    if reallow_root {
1449        let escaped = escape_path(&real_root);
1450        profile.push_str(&format!(r#"(allow file-write* (subpath "{escaped}"))"#));
1451    }
1452    if let Some(common_dir) = git_common_dir(root) {
1453        let real_common = canonicalize_existing_prefix(&common_dir);
1454        let covered_by_root = reallow_root && real_common.starts_with(&real_root);
1455        if !covered_by_root && is_in_non_state_protected_home(&real_common) {
1456            let escaped = escape_path(&real_common);
1457            profile.push_str(&format!(r#"(allow file-write* (subpath "{escaped}"))"#));
1458        }
1459        for sub in ["hooks", "config"] {
1460            let escaped = escape_path(&canonicalize_existing_prefix(&real_common.join(sub)));
1461            profile.push_str(&format!(r#"(deny file-write* (subpath "{escaped}"))"#));
1462        }
1463    }
1464    profile
1465}
1466
1467/// Returns the default macOS sandbox profile.
1468///
1469/// Denies writes outside `default_allowed` and reads under credential stores.
1470#[cfg(target_os = "macos")]
1471fn default_profile(root: &Path, allow_read: &[PathBuf]) -> Profile {
1472    Profile::Seatbelt(deny_unix_sockets(
1473        default_profile_base(root, allow_read),
1474        &current_agent_sockets(),
1475    ))
1476}
1477
1478/// Returns the default macOS sandbox profile with network configuration.
1479///
1480/// When `network` is true, returns the same profile as [`default_profile`].
1481/// When `network` is false, returns an offline profile denying outbound network connections.
1482#[cfg(target_os = "macos")]
1483fn default_profile_net(root: &Path, allow_read: &[PathBuf], network: bool) -> Profile {
1484    if network {
1485        return default_profile(root, allow_read);
1486    }
1487    let base = default_profile_base(root, allow_read);
1488    let socks = match std::env::var_os("HOME") {
1489        Some(home) if !home.is_empty() => docker_sockets(Path::new(&home)),
1490        _ => Vec::new(),
1491    };
1492    Profile::Seatbelt(deny_unix_sockets(
1493        offline(base, &socks),
1494        &current_agent_sockets(),
1495    ))
1496}
1497
1498/// Returns the default sandbox profile and optional private `TMPDIR` with network enabled.
1499pub fn default_sandbox(root: &Path, allow_read: &[PathBuf]) -> Result<ConversationSandbox, String> {
1500    default_sandbox_net(root, allow_read, true)
1501}
1502
1503/// Returns the default sandbox profile and optional private `TMPDIR`.
1504pub fn default_sandbox_net(
1505    root: &Path,
1506    allow_read: &[PathBuf],
1507    network: bool,
1508) -> Result<ConversationSandbox, String> {
1509    #[cfg(target_os = "macos")]
1510    {
1511        Ok(ConversationSandbox {
1512            profile: default_profile_net(root, allow_read, network),
1513            tmpdir: None,
1514        })
1515    }
1516    #[cfg(not(target_os = "macos"))]
1517    {
1518        let home = std::env::var_os("HOME");
1519        let home_path = home.as_ref().filter(|h| !h.is_empty()).map(Path::new);
1520        let write = default_allowed(root);
1521        let read = read_allowed(home_path, allow_read);
1522        confine_linux_sandbox(write, read, allow_read, network, None)
1523    }
1524}
1525
1526/// Sets up Landlock sandbox rules in the child process before exec.
1527#[cfg(target_os = "linux")]
1528pub(crate) fn landlock_pre_exec(
1529    cmd: &mut std::process::Command,
1530    write: &[PathBuf],
1531    read: Option<&[PathBuf]>,
1532    block_tcp: bool,
1533) -> std::io::Result<()> {
1534    use landlock::{
1535        path_beneath_rules, Access, AccessFs, AccessNet, Ruleset, RulesetAttr, RulesetCreated,
1536        RulesetCreatedAttr, ABI,
1537    };
1538    use std::os::unix::process::CommandExt;
1539    use std::sync::Mutex;
1540
1541    if block_tcp && landlock_abi() < 4 {
1542        return Err(std::io::Error::new(
1543            std::io::ErrorKind::Unsupported,
1544            "needs Linux 6.7 or later",
1545        ));
1546    }
1547
1548    let mut ruleset = Ruleset::default()
1549        .handle_access(AccessFs::from_write(ABI::V5))
1550        .map_err(std::io::Error::other)?;
1551
1552    if read.is_some() {
1553        ruleset = ruleset
1554            .handle_access(AccessFs::from_read(ABI::V5))
1555            .map_err(std::io::Error::other)?;
1556    }
1557
1558    if block_tcp {
1559        ruleset = ruleset
1560            .handle_access(AccessNet::ConnectTcp)
1561            .map_err(std::io::Error::other)?;
1562    }
1563
1564    let ruleset: RulesetCreated = ruleset.create().map_err(std::io::Error::other)?;
1565
1566    let ruleset: RulesetCreated = match read {
1567        Some(read_paths) => ruleset
1568            .add_rules(path_beneath_rules(write, AccessFs::from_all(ABI::V5)))
1569            .map_err(std::io::Error::other)?
1570            .add_rules(path_beneath_rules(read_paths, AccessFs::from_read(ABI::V5)))
1571            .map_err(std::io::Error::other)?,
1572        None => ruleset
1573            .add_rules(path_beneath_rules(write, AccessFs::from_write(ABI::V5)))
1574            .map_err(std::io::Error::other)?,
1575    };
1576
1577    let ruleset = Mutex::new(Some(ruleset));
1578    unsafe {
1579        cmd.pre_exec(move || {
1580            // SAFETY: In the child process after fork in a multi-threaded parent,
1581            // we must not allocate memory or use non-async-signal-safe functions.
1582            // On error return Err(std::io::Error::from_raw_os_error(libc::EPERM)),
1583            // never a formatted error.
1584            let mut guard = ruleset
1585                .lock()
1586                .map_err(|_| std::io::Error::from_raw_os_error(libc::EPERM))?;
1587            let r = guard
1588                .take()
1589                .ok_or_else(|| std::io::Error::from_raw_os_error(libc::EPERM))?;
1590            if r.restrict_self().is_err() {
1591                return Err(std::io::Error::from_raw_os_error(libc::EPERM));
1592            }
1593            Ok(())
1594        });
1595    }
1596    Ok(())
1597}
1598
1599#[cfg(test)]
1600mod tests {
1601    use super::*;
1602
1603    #[test]
1604    fn open_edit_worktrees_empty_when_wt_missing() {
1605        let tmp = tempfile::tempdir().unwrap();
1606        assert_eq!(
1607            open_edit_worktrees(tmp.path()).unwrap(),
1608            Vec::<PathBuf>::new()
1609        );
1610    }
1611
1612    #[test]
1613    fn open_edit_worktrees_sorted_and_filtered() {
1614        let tmp = tempfile::tempdir().unwrap();
1615        let wt = tmp.path().join(".wt");
1616        std::fs::create_dir_all(wt.join("B")).unwrap();
1617        std::fs::create_dir_all(wt.join("A")).unwrap();
1618        std::fs::create_dir_all(wt.join("Done")).unwrap();
1619        std::fs::create_dir_all(wt.join("NoMarker")).unwrap();
1620        std::fs::write(wt.join("NotADir"), "file\n").unwrap();
1621
1622        std::fs::write(wt.join("B.edit.json"), "{}\n").unwrap();
1623        std::fs::write(wt.join("A.edit.json"), "{}\n").unwrap();
1624        std::fs::write(wt.join("Done.edit.json"), "{}\n").unwrap();
1625        std::fs::write(wt.join("Done.json"), "{}\n").unwrap();
1626        std::fs::write(wt.join("MissingDir.edit.json"), "{}\n").unwrap();
1627        std::fs::write(wt.join("NotADir.edit.json"), "{}\n").unwrap();
1628
1629        let got = open_edit_worktrees(tmp.path()).unwrap();
1630        assert_eq!(got, vec![wt.join("A"), wt.join("B")]);
1631    }
1632
1633    #[test]
1634    fn open_edit_worktrees_errors_on_unreadable_wt() {
1635        let tmp = tempfile::tempdir().unwrap();
1636        let wt = tmp.path().join(".wt");
1637        std::fs::write(&wt, "not a directory\n").unwrap();
1638        let err = open_edit_worktrees(tmp.path()).unwrap_err();
1639        assert!(err.contains(&wt.display().to_string()), "{err}");
1640    }
1641
1642    #[cfg(target_os = "macos")]
1643    #[test]
1644    fn conversation_profile_with_edits_denies_worktree_git() {
1645        let tmp = tempfile::tempdir().unwrap();
1646        let wt = tmp.path().join(".wt/E1");
1647        std::fs::create_dir_all(&wt).unwrap();
1648        let Profile::Seatbelt(sbpl) =
1649            conversation_sandbox_with_edits(tmp.path(), &[], false, std::slice::from_ref(&wt))
1650                .unwrap()
1651                .profile
1652        else {
1653            panic!("expected Seatbelt profile on macOS");
1654        };
1655        let canon = wt.canonicalize().unwrap();
1656        let escaped_wt = escape_path(&canon);
1657        let escaped_git = escape_path(&canon.join(".git"));
1658        let expected = format!(
1659            r#"(allow file-write* (subpath "{escaped_wt}"))(deny file-write* (literal "{escaped_git}"))"#
1660        );
1661        assert!(sbpl.contains(&expected), "{sbpl}");
1662    }
1663}