use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Profile {
Seatbelt(String),
Landlock(Vec<PathBuf>),
LandlockOffline(Vec<PathBuf>),
LandlockConfined {
write: Vec<PathBuf>,
read: Vec<PathBuf>,
block_tcp: bool,
},
}
impl From<String> for Profile {
fn from(s: String) -> Self {
Profile::Seatbelt(s)
}
}
impl From<&str> for Profile {
fn from(s: &str) -> Self {
Profile::Seatbelt(s.to_string())
}
}
#[cfg(target_os = "linux")]
pub fn landlock_abi() -> i64 {
unsafe {
libc::syscall(
libc::SYS_landlock_create_ruleset,
std::ptr::null::<libc::c_void>(),
0usize,
1u32,
) as i64
}
}
#[cfg(not(target_os = "linux"))]
pub fn landlock_abi() -> i64 {
0
}
pub fn available() -> bool {
#[cfg(target_os = "macos")]
{
Path::new("/usr/bin/sandbox-exec").exists()
}
#[cfg(target_os = "linux")]
{
landlock_abi() >= 1
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
{
false
}
}
fn escape_path(path: &Path) -> String {
let s = path.to_string_lossy();
s.replace('\\', "\\\\").replace('"', "\\\"")
}
fn escape_subpath(path: &Path) -> String {
let canon = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
escape_path(&canon)
}
pub fn profile(allowed: &[PathBuf]) -> String {
let mut out = String::from("(version 1)(allow default)(deny file-write*)");
for path in allowed {
let escaped = escape_subpath(path);
out.push_str(&format!(r#"(allow file-write* (subpath "{escaped}"))"#));
}
out.push_str(
r#"(allow file-write* (literal "/dev/null") (literal "/dev/tty") (subpath "/dev/fd"))"#,
);
out
}
pub fn read_denied(home: &Path) -> Vec<PathBuf> {
const DENIED_PATHS: &[&str] = &[
".ssh",
".aws",
".azure",
".config/blyte/env",
".config/gcloud",
".config/gh",
".kube",
".gnupg",
".docker/config.json",
".git-credentials",
".netrc",
".pypirc",
".cargo/credentials.toml",
".cargo/credentials",
".codex",
"Library/Keychains",
"Library/Cookies",
"Library/Safari",
"Library/Application Support/Google/Chrome",
"Library/Application Support/Firefox",
"Library/Application Support/Arc",
"Library/Application Support/BraveSoftware",
];
DENIED_PATHS.iter().map(|sub| home.join(sub)).collect()
}
pub fn read_allowed(home: Option<&Path>, allow_read: &[PathBuf]) -> Vec<PathBuf> {
let mut allowed = Vec::new();
const SYSTEM_ROOTS: &[&str] = &[
"/usr", "/lib", "/lib32", "/lib64", "/libx32", "/bin", "/sbin", "/etc", "/opt", "/proc",
"/sys", "/dev", "/run", "/var", "/tmp", "/snap", "/nix",
];
for root in SYSTEM_ROOTS {
allowed.push(PathBuf::from(root));
}
if let Some(home) = home {
const TOOL_DIRS: &[&str] = &[
".cargo",
".rustup",
".cache",
".local/bin",
".local/lib",
".local/share/uv",
".local/share/pnpm",
".local/share/mise",
".npm",
".nvm",
".pyenv",
".rbenv",
".asdf",
".bun",
".deno",
".gradle",
".m2",
"go",
".config/git",
".gitconfig",
".gitignore_global",
".gitattributes",
".profile",
".bashrc",
".bash_profile",
".bash_login",
".inputrc",
".editorconfig",
".docker/buildx",
];
for sub in TOOL_DIRS {
allowed.push(home.join(sub));
}
}
allowed.extend(allow_read.iter().cloned());
allowed
}
const TEMP_DOT_ENV_DIRS: &[&str] = &["/private/tmp", "/private/var/folders"];
pub fn profile_with(
workspace: &Path,
write: &[PathBuf],
deny_read: &[PathBuf],
allow_read: &[PathBuf],
) -> String {
let mut out = profile(write);
for path in deny_read {
let escaped = escape_subpath(path);
out.push_str(&format!(r#"(deny file-read-data (subpath "{escaped}"))"#));
}
out.push_str(r##"(deny file-read-data (regex #"/\.env$"))"##);
let escaped_ws = escape_subpath(workspace);
for dir in TEMP_DOT_ENV_DIRS {
out.push_str(&format!(
r##"(allow file-read-data (require-all (subpath "{dir}") (require-not (subpath "{escaped_ws}")) (regex #"/\.env$")))"##
));
}
for path in allow_read {
let escaped = escape_subpath(path);
out.push_str(&format!(r#"(allow file-read-data (subpath "{escaped}"))"#));
}
out
}
fn push_home_local_grants(home_path: &Path, allowed: &mut Vec<PathBuf>) {
#[cfg(target_os = "macos")]
{
allowed.push(home_path.join(".local"));
}
#[cfg(not(target_os = "macos"))]
{
let local_dir = home_path.join(".local");
if let Ok(entries) = std::fs::read_dir(&local_dir) {
let mut paths: Vec<PathBuf> = entries
.flatten()
.filter(|entry| entry.file_name() != std::ffi::OsStr::new("state"))
.map(|entry| entry.path())
.collect();
paths.sort();
allowed.extend(paths);
}
let state_dir = local_dir.join("state");
if let Ok(entries) = std::fs::read_dir(&state_dir) {
let mut paths: Vec<PathBuf> = entries
.flatten()
.filter(|entry| entry.file_name() != std::ffi::OsStr::new("blyte"))
.map(|entry| entry.path())
.collect();
paths.sort();
allowed.extend(paths);
}
}
}
pub fn state_blyte_dir() -> Option<PathBuf> {
if let Some(xdg) = std::env::var_os("XDG_STATE_HOME") {
if !xdg.is_empty() {
return Some(PathBuf::from(xdg).join("blyte"));
}
}
std::env::var_os("HOME")
.filter(|h| !h.is_empty())
.map(|h| PathBuf::from(h).join(".local").join("state").join("blyte"))
}
fn fnv1a64(bytes: &[u8]) -> u64 {
let mut hash: u64 = 0xcbf29ce484222325;
for &b in bytes {
hash ^= u64::from(b);
hash = hash.wrapping_mul(0x100000001b3);
}
hash
}
pub fn surface_token_dir() -> Option<PathBuf> {
state_blyte_dir().map(|d| d.join("surface"))
}
pub fn surface_token_path(main_checkout: &Path) -> Result<PathBuf, String> {
let dir = surface_token_dir().ok_or_else(|| {
"cannot determine surface token directory: neither XDG_STATE_HOME nor HOME is set"
.to_string()
})?;
let canon = canonicalize_existing_prefix(main_checkout);
let key = format!("{:016x}", fnv1a64(canon.as_os_str().as_encoded_bytes()));
Ok(dir.join(format!("{key}.token")))
}
pub fn validate_surface_id(id: &str) -> Result<(), String> {
let bytes = id.as_bytes();
let valid = bytes.len() == 17
&& bytes[0] == b's'
&& bytes[1..]
.iter()
.all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
if valid {
Ok(())
} else {
Err(format!("invalid surface id: {id}"))
}
}
pub fn surface_token_path_for_id(surface_id: &str) -> Result<PathBuf, String> {
validate_surface_id(surface_id)?;
let dir = surface_token_dir().ok_or_else(|| {
"cannot determine surface token directory: neither XDG_STATE_HOME nor HOME is set"
.to_string()
})?;
Ok(dir.join(format!("{surface_id}.token")))
}
pub fn surface_message_path_for_id(surface_id: &str) -> Result<PathBuf, String> {
validate_surface_id(surface_id)?;
let dir = surface_token_dir().ok_or_else(|| {
"cannot determine surface token directory: neither XDG_STATE_HOME nor HOME is set"
.to_string()
})?;
Ok(dir.join(format!("{surface_id}.message")))
}
const MAX_SYMLINK_DEPTH: usize = 40;
enum PathPart {
Prefix(std::ffi::OsString),
RootDir,
CurDir,
ParentDir,
Normal(std::ffi::OsString),
}
impl From<std::path::Component<'_>> for PathPart {
fn from(comp: std::path::Component<'_>) -> Self {
match comp {
std::path::Component::Prefix(p) => Self::Prefix(p.as_os_str().to_os_string()),
std::path::Component::RootDir => Self::RootDir,
std::path::Component::CurDir => Self::CurDir,
std::path::Component::ParentDir => Self::ParentDir,
std::path::Component::Normal(s) => Self::Normal(s.to_os_string()),
}
}
}
fn resolve_real_path(path: &Path) -> Result<PathBuf, String> {
let abs = if path.is_absolute() {
path.to_path_buf()
} else {
std::env::current_dir()
.map_err(|e| format!("cannot determine current directory: {e}"))?
.join(path)
};
match abs.canonicalize() {
Ok(resolved) => return Ok(resolved),
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
) => {}
Err(e) => return Err(format!("cannot canonicalize {}: {e}", abs.display())),
}
let mut queue: std::collections::VecDeque<PathPart> =
abs.components().map(PathPart::from).collect();
let mut cur = PathBuf::new();
let mut missing = false;
let mut symlinks_followed = 0usize;
while let Some(part) = queue.pop_front() {
match part {
PathPart::Prefix(p) => cur.push(p),
PathPart::RootDir => cur.push(std::path::MAIN_SEPARATOR_STR),
PathPart::CurDir => {}
PathPart::ParentDir => {
cur.pop();
}
PathPart::Normal(name) => {
cur.push(&name);
if missing {
continue;
}
match std::fs::symlink_metadata(&cur) {
Ok(meta) if meta.file_type().is_symlink() => {
symlinks_followed += 1;
if symlinks_followed > MAX_SYMLINK_DEPTH {
return Err(format!(
"cannot canonicalize {}: too many levels of symbolic links",
abs.display()
));
}
let target = std::fs::read_link(&cur)
.map_err(|e| format!("cannot read link {}: {e}", cur.display()))?;
if target.is_absolute() {
cur.clear();
} else {
cur.pop();
}
for comp in target.components().rev() {
queue.push_front(PathPart::from(comp));
}
}
Ok(_) => {}
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
) =>
{
cur.pop();
if !cur.as_os_str().is_empty() {
cur = cur.canonicalize().map_err(|ce| {
format!("cannot canonicalize {}: {ce}", cur.display())
})?;
}
cur.push(&name);
missing = true;
}
Err(e) => {
return Err(format!("cannot canonicalize {}: {e}", cur.display()));
}
}
}
}
}
if !missing && !cur.as_os_str().is_empty() {
if let Ok(resolved) = cur.canonicalize() {
return Ok(resolved);
}
}
Ok(cur)
}
fn resolve_protected_prefix(path: &Path) -> Result<PathBuf, String> {
let abs = if path.is_absolute() {
path.to_path_buf()
} else {
std::env::current_dir()
.map_err(|e| format!("cannot determine current directory: {e}"))?
.join(path)
};
let mut probe = abs.as_path();
let mut tail: Vec<std::ffi::OsString> = Vec::new();
loop {
match probe.canonicalize() {
Ok(mut resolved) => {
for part in tail.into_iter().rev() {
resolved.push(part);
}
return Ok(resolved);
}
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::NotFound
| std::io::ErrorKind::NotADirectory
| std::io::ErrorKind::PermissionDenied
) =>
{
let Some(name) = probe.file_name() else {
return Err(format!("cannot canonicalize {}: {e}", probe.display()));
};
tail.push(name.to_os_string());
let Some(parent) = probe.parent() else {
return Err(format!("cannot canonicalize {}: {e}", probe.display()));
};
probe = parent;
}
Err(e) => {
return Err(format!("cannot canonicalize {}: {e}", probe.display()));
}
}
}
}
pub fn protected_read_paths() -> Result<Vec<PathBuf>, String> {
let mut raw = Vec::new();
if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
let home_path = Path::new(&home);
raw.extend(read_denied(home_path));
let blyte_env = home_path.join(".config/blyte/env");
if !raw.contains(&blyte_env) {
raw.push(blyte_env);
}
}
if let Some(dir) = surface_token_dir() {
if !raw.contains(&dir) {
raw.push(dir);
}
}
let mut out = Vec::with_capacity(raw.len());
for path in raw {
let resolved = resolve_protected_prefix(&path)?;
if !out.contains(&resolved) {
out.push(resolved);
}
}
Ok(out)
}
pub(crate) fn is_protected_read_with(path: &Path, protected: &[PathBuf]) -> Result<bool, String> {
let real = resolve_real_path(path)?;
let dot_env = std::ffi::OsStr::new(".env");
if path.file_name() == Some(dot_env) || real.file_name() == Some(dot_env) {
return Ok(true);
}
Ok(protected.iter().any(|p| real.starts_with(p)))
}
pub fn is_protected_read(path: &Path) -> Result<bool, String> {
let protected = protected_read_paths()?;
is_protected_read_with(path, &protected)
}
pub(crate) fn is_in_blyte_own_dir(real_target: &Path) -> Result<bool, String> {
let mut raw = Vec::new();
if let Some(dir) = state_blyte_dir() {
raw.push(dir);
}
if let Some(dir) = std::env::var_os("BLYTE_STATE_DIR").filter(|d| !d.is_empty()) {
raw.push(PathBuf::from(dir));
}
if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
raw.push(PathBuf::from(home).join(".config").join("blyte"));
}
for dir in raw {
let resolved = resolve_protected_prefix(&dir)?;
if real_target.starts_with(&resolved) {
return Ok(true);
}
}
Ok(false)
}
fn canonicalize_existing_prefix(path: &Path) -> PathBuf {
if let Ok(canon) = path.canonicalize() {
return canon;
}
let mut tail = Vec::new();
let mut cur = path;
while let Some(name) = cur.file_name() {
tail.push(name.to_os_string());
match cur.parent() {
Some(parent) => {
cur = parent;
if let Ok(mut canon) = cur.canonicalize() {
for part in tail.into_iter().rev() {
canon.push(part);
}
return canon;
}
}
None => break,
}
}
path.to_path_buf()
}
#[cfg(target_os = "macos")]
fn deny_state_blyte_write(mut profile: String) -> String {
if let Some(dir) = state_blyte_dir() {
let escaped = escape_path(&canonicalize_existing_prefix(&dir));
profile.push_str(&format!(r#"(deny file-write* (subpath "{escaped}"))"#));
}
if let Some(dir) = surface_token_dir() {
let escaped = escape_path(&canonicalize_existing_prefix(&dir));
profile.push_str(&format!(
r#"(deny file-read* (subpath "{escaped}"))(deny file-read-data (subpath "{escaped}"))"#
));
}
if let Some(home) = std::env::var_os("HOME").filter(|h| !h.is_empty()) {
let env_path = PathBuf::from(home).join(".config/blyte/env");
let escaped = escape_path(&canonicalize_existing_prefix(&env_path));
profile.push_str(&format!(
r#"(deny file-read* (subpath "{escaped}"))(deny file-read-data (subpath "{escaped}"))"#
));
}
profile
}
pub fn default_allowed(root: &Path) -> Vec<PathBuf> {
let mut allowed = Vec::new();
allowed.push(root.to_path_buf());
if let Ok(output) = std::process::Command::new("git")
.args(["-C"])
.arg(root)
.args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
.output()
{
if output.status.success() {
let s = String::from_utf8_lossy(&output.stdout);
let path_str = s.trim();
if !path_str.is_empty() {
allowed.push(PathBuf::from(path_str));
}
}
}
allowed.push(PathBuf::from("/private/tmp"));
allowed.push(PathBuf::from("/private/var/folders"));
allowed.push(PathBuf::from("/tmp"));
allowed.push(PathBuf::from("/var/tmp"));
allowed.push(PathBuf::from("/dev"));
if let Some(tmp) = std::env::var_os("TMPDIR") {
if !tmp.is_empty() {
allowed.push(PathBuf::from(tmp));
}
}
if let Some(home) = std::env::var_os("HOME") {
if !home.is_empty() {
let home_path = PathBuf::from(home);
for sub in [
".cargo",
".rustup",
".cache",
".npm",
"Library/Caches",
".gradle",
".m2",
"go",
".docker/buildx",
] {
allowed.push(home_path.join(sub));
}
push_home_local_grants(&home_path, &mut allowed);
}
}
let home = std::env::var_os("HOME")
.filter(|h| !h.is_empty())
.map(PathBuf::from);
let home_canon = home.as_deref().and_then(|h| h.canonicalize().ok());
let is_home = |p: &Path| -> bool {
if let Some(h) = home.as_deref() {
if p == h {
return true;
}
}
if let Some(hc) = home_canon.as_deref() {
if p == hc || p.canonicalize().ok().as_deref() == Some(hc) {
return true;
}
}
false
};
if !is_home(root) {
for a in root.ancestors().skip(1) {
if is_home(a) {
break;
}
let nm = a.join("node_modules");
if nm.is_dir() {
for name in [".vite-temp", ".vite", ".cache"] {
let dir = nm.join(name);
let _ = std::fs::create_dir_all(&dir);
allowed.push(dir);
}
}
}
}
allowed
}
fn git_common_dir(root: &Path) -> Option<PathBuf> {
let output = std::process::Command::new("git")
.args(["-C"])
.arg(root)
.args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let text = String::from_utf8_lossy(&output.stdout);
let line = text.lines().map(str::trim).find(|s| !s.is_empty())?;
Some(PathBuf::from(line))
}
pub fn is_git_repository(root: &Path) -> bool {
git_common_dir(root).is_some()
}
fn canonicalize_or_missing(path: &Path) -> Result<PathBuf, String> {
match path.canonicalize() {
Ok(p) => Ok(p),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(path.to_path_buf()),
Err(e) => Err(format!("cannot canonicalize {}: {e}", path.display())),
}
}
fn main_checkout_root(root: &Path) -> PathBuf {
if let Some(common_dir) = git_common_dir(root) {
if common_dir.file_name() == Some(std::ffi::OsStr::new(".git")) {
if let Some(main_root) = common_dir.parent() {
return main_root
.canonicalize()
.unwrap_or_else(|_| main_root.to_path_buf());
}
}
}
root.canonicalize().unwrap_or_else(|_| root.to_path_buf())
}
fn main_checkout_root_checked(root: &Path) -> Result<PathBuf, String> {
if let Some(common_dir) = git_common_dir(root) {
if common_dir.file_name() == Some(std::ffi::OsStr::new(".git")) {
if let Some(main_root) = common_dir.parent() {
return canonicalize_or_missing(main_root);
}
}
}
canonicalize_or_missing(root)
}
fn create_private_temp_dir(path: &Path) -> Result<bool, String> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| {
format!(
"cannot create private temp directory {}: {e}",
path.display()
)
})?;
}
#[cfg(unix)]
{
use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
let mut builder = std::fs::DirBuilder::new();
builder.mode(0o700);
let created = match builder.create(path) {
Ok(()) => true,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
let meta = std::fs::metadata(path).map_err(|me| {
format!(
"cannot inspect private temp directory {}: {me}",
path.display()
)
})?;
if !meta.is_dir() {
return Err(format!(
"cannot create private temp directory {}: path exists and is not a directory",
path.display()
));
}
false
}
Err(e) => {
return Err(format!(
"cannot create private temp directory {}: {e}",
path.display()
));
}
};
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).map_err(|e| {
format!(
"cannot set permissions on private temp directory {}: {e}",
path.display()
)
})?;
Ok(created)
}
#[cfg(not(unix))]
{
match std::fs::create_dir(path) {
Ok(()) => Ok(true),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
let meta = std::fs::metadata(path).map_err(|me| {
format!(
"cannot inspect private temp directory {}: {me}",
path.display()
)
})?;
if !meta.is_dir() {
return Err(format!(
"cannot create private temp directory {}: path exists and is not a directory",
path.display()
));
}
Ok(false)
}
Err(e) => Err(format!(
"cannot create private temp directory {}: {e}",
path.display()
)),
}
}
}
pub fn conversation_tasks_dir(root: &Path) -> PathBuf {
main_checkout_root(root).join(".wt").join("tasks")
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConversationPaths {
pub allowed: Vec<PathBuf>,
pub tmpdir: Option<PathBuf>,
pub created_tmpdir: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConversationSandbox {
pub profile: Profile,
pub tmpdir: Option<PathBuf>,
}
pub fn conversation_paths(root: &Path) -> Result<ConversationPaths, String> {
let root_cmp = canonicalize_or_missing(root)?;
let common_dir = git_common_dir(root);
let is_repo = common_dir.is_some();
let main_cmp = match common_dir {
Some(ref dir) if dir.file_name() == Some(std::ffi::OsStr::new(".git")) => {
match dir.parent() {
Some(main_root) => canonicalize_or_missing(main_root)?,
None => root_cmp.clone(),
}
}
_ => root_cmp.clone(),
};
let mut raw = vec![
PathBuf::from("/private/tmp"),
PathBuf::from("/private/var/folders"),
PathBuf::from("/tmp"),
PathBuf::from("/var/tmp"),
PathBuf::from("/dev"),
];
if let Some(tmp) = std::env::var_os("TMPDIR") {
if !tmp.is_empty() {
raw.push(PathBuf::from(tmp));
}
}
if let Some(home) = std::env::var_os("HOME") {
if !home.is_empty() {
let home_path = PathBuf::from(home);
for sub in [
".cargo",
".rustup",
".cache",
".npm",
"Library/Caches",
".gradle",
".m2",
"go",
".docker/buildx",
] {
raw.push(home_path.join(sub));
}
push_home_local_grants(&home_path, &mut raw);
}
}
let mut allowed = Vec::with_capacity(raw.len() + 2);
if is_repo {
allowed.push(main_cmp.join(".wt").join("tasks"));
}
let mut removed = false;
for entry in raw {
let entry_cmp = canonicalize_or_missing(&entry)?;
if root_cmp.starts_with(&entry_cmp) || main_cmp.starts_with(&entry_cmp) {
removed = true;
} else {
allowed.push(entry);
}
}
let (tmpdir, created_tmpdir) = if removed {
let private_tmp = if is_repo {
root_cmp
.join(".wt")
.join("tmp")
.join(std::process::id().to_string())
} else {
let mut temp_grants = Vec::new();
if let Some(tmp) = std::env::var_os("TMPDIR") {
if !tmp.is_empty() {
temp_grants.push(PathBuf::from(tmp));
}
}
temp_grants.push(PathBuf::from("/private/tmp"));
temp_grants.push(PathBuf::from("/tmp"));
temp_grants.push(PathBuf::from("/var/tmp"));
let mut chosen = None;
for grant in temp_grants {
let grant_cmp = canonicalize_or_missing(&grant)?;
if root_cmp.starts_with(&grant_cmp) || grant_cmp.starts_with(&root_cmp) {
continue;
}
if grant_cmp.is_dir() {
chosen = Some(grant_cmp);
break;
}
}
let Some(grant) = chosen else {
return Err(format!(
"cannot choose private temp directory for {}: no remaining writable temp directory",
root.display()
));
};
grant.join(format!("blyte-{}", std::process::id()))
};
let created = create_private_temp_dir(&private_tmp)?;
allowed.push(private_tmp.clone());
(Some(private_tmp), created)
} else {
(None, false)
};
Ok(ConversationPaths {
allowed,
tmpdir,
created_tmpdir,
})
}
pub fn conversation_allowed(root: &Path) -> Result<Vec<PathBuf>, String> {
Ok(conversation_paths(root)?.allowed)
}
fn path_exists(path: &Path) -> Result<bool, String> {
match std::fs::metadata(path) {
Ok(_) => Ok(true),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(format!("cannot check {}: {e}", path.display())),
}
}
pub(crate) fn is_open_edit_worktree_id(
wt_dir: &Path,
id: &std::ffi::OsStr,
) -> Result<bool, String> {
let mut edit_name = id.to_os_string();
edit_name.push(".edit.json");
let edit_marker = wt_dir.join(edit_name);
if !path_exists(&edit_marker)? {
return Ok(false);
}
let mut summary_name = id.to_os_string();
summary_name.push(".json");
let summary_marker = wt_dir.join(summary_name);
if path_exists(&summary_marker)? {
return Ok(false);
}
let worktree = wt_dir.join(id);
match std::fs::metadata(&worktree) {
Ok(m) => Ok(m.is_dir()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(format!("cannot check {}: {e}", worktree.display())),
}
}
pub fn open_edit_worktrees(main_checkout: &Path) -> Result<Vec<PathBuf>, String> {
let wt_dir = main_checkout.join(".wt");
let entries = match std::fs::read_dir(&wt_dir) {
Ok(e) => e,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(format!("cannot read {}: {e}", wt_dir.display())),
};
let mut worktrees = Vec::new();
for entry in entries {
let entry = entry.map_err(|e| format!("cannot read {}: {e}", wt_dir.display()))?;
let name = entry.file_name();
let Some(name_str) = name.to_str() else {
continue;
};
let Some(id) = name_str.strip_suffix(".edit.json") else {
continue;
};
if id.is_empty() {
continue;
}
if is_open_edit_worktree_id(&wt_dir, std::ffi::OsStr::new(id))? {
worktrees.push(wt_dir.join(id));
}
}
worktrees.sort();
Ok(worktrees)
}
#[cfg(target_os = "macos")]
fn allow_edit_worktrees(mut base: String, edit_worktrees: &[PathBuf]) -> String {
for wt in edit_worktrees {
let canon = wt.canonicalize().unwrap_or_else(|_| wt.to_path_buf());
let escaped_wt = escape_path(&canon);
let escaped_git = escape_path(&canon.join(".git"));
base.push_str(&format!(
r#"(allow file-write* (subpath "{escaped_wt}"))(deny file-write* (literal "{escaped_git}"))"#
));
}
base
}
pub fn conversation_sandbox(
root: &Path,
allow_read: &[PathBuf],
) -> Result<ConversationSandbox, String> {
conversation_sandbox_net(root, allow_read, true)
}
pub fn conversation_sandbox_net(
root: &Path,
allow_read: &[PathBuf],
network: bool,
) -> Result<ConversationSandbox, String> {
conversation_sandbox_with_edits(root, allow_read, network, &[])
}
pub fn conversation_sandbox_with_edits(
root: &Path,
allow_read: &[PathBuf],
network: bool,
edit_worktrees: &[PathBuf],
) -> Result<ConversationSandbox, String> {
let paths = conversation_paths(root)?;
let profile = {
#[cfg(target_os = "macos")]
{
let deny_read = match std::env::var_os("HOME") {
Some(home) if !home.is_empty() => read_denied(Path::new(&home)),
_ => Vec::new(),
};
let base = deny_state_blyte_write(allow_edit_worktrees(
profile_with(root, &paths.allowed, &deny_read, allow_read),
edit_worktrees,
));
let profiled = if network {
base
} else {
let socks = match std::env::var_os("HOME") {
Some(home) if !home.is_empty() => docker_sockets(Path::new(&home)),
_ => Vec::new(),
};
offline(base, &socks)
};
Profile::Seatbelt(deny_unix_sockets(profiled, ¤t_agent_sockets()))
}
#[cfg(not(target_os = "macos"))]
{
let home = std::env::var_os("HOME");
let home_path = home.as_ref().filter(|h| !h.is_empty()).map(Path::new);
let mut extra_read = vec![root.to_path_buf()];
if let Some(common_dir) = git_common_dir(root) {
extra_read.push(common_dir);
}
let main_wt = main_checkout_root_checked(root)?.join(".wt");
if main_wt.exists() {
extra_read.push(main_wt);
}
extra_read.extend_from_slice(allow_read);
let mut write = paths.allowed;
write.extend(edit_worktrees.iter().cloned());
Profile::LandlockConfined {
write,
read: read_allowed(home_path, &extra_read),
block_tcp: !network,
}
}
};
Ok(ConversationSandbox {
profile,
tmpdir: paths.tmpdir,
})
}
pub fn conversation_sandbox_for_open_edits(
root: &Path,
allow_read: &[PathBuf],
network: bool,
) -> Result<ConversationSandbox, String> {
let main = main_checkout_root_checked(root)?;
let edits = open_edit_worktrees(&main)?;
conversation_sandbox_with_edits(root, allow_read, network, &edits)
}
pub fn conversation_profile(root: &Path, allow_read: &[PathBuf]) -> Result<Profile, String> {
Ok(conversation_sandbox(root, allow_read)?.profile)
}
pub fn conversation_profile_net(
root: &Path,
allow_read: &[PathBuf],
network: bool,
) -> Result<Profile, String> {
Ok(conversation_sandbox_net(root, allow_read, network)?.profile)
}
pub fn conversation_profile_with_edits(
root: &Path,
allow_read: &[PathBuf],
network: bool,
edit_worktrees: &[PathBuf],
) -> Result<Profile, String> {
Ok(conversation_sandbox_with_edits(root, allow_read, network, edit_worktrees)?.profile)
}
pub fn conversation_profile_for_open_edits(
root: &Path,
allow_read: &[PathBuf],
network: bool,
) -> Result<Profile, String> {
Ok(conversation_sandbox_for_open_edits(root, allow_read, network)?.profile)
}
pub fn docker_sockets(home: &Path) -> Vec<PathBuf> {
vec![
PathBuf::from("/var/run/docker.sock"),
home.join(".docker/run/docker.sock"),
home.join(".colima/default/docker.sock"),
home.join(".orbstack/run/docker.sock"),
]
}
pub fn agent_sockets(home: &Path, ssh_auth_sock: Option<&Path>) -> Vec<PathBuf> {
let mut out = Vec::new();
if let Some(sock) = ssh_auth_sock {
if !sock.as_os_str().is_empty() {
out.push(sock.to_path_buf());
}
}
for rel in [
".gnupg/S.gpg-agent.ssh",
".gnupg/S.gpg-agent",
".1password/agent.sock",
"Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock",
] {
let path = home.join(rel);
if !out.contains(&path) {
out.push(path);
}
}
out
}
#[cfg(target_os = "macos")]
fn current_agent_sockets() -> Vec<PathBuf> {
let ssh_auth_sock = if crate::shell::is_pass_env("SSH_AUTH_SOCK") {
None
} else {
std::env::var_os("SSH_AUTH_SOCK")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
};
match std::env::var_os("HOME") {
Some(home) if !home.is_empty() => agent_sockets(Path::new(&home), ssh_auth_sock.as_deref()),
_ => ssh_auth_sock.into_iter().collect(),
}
}
fn deny_unix_sockets(mut profile: String, sockets: &[PathBuf]) -> String {
if sockets.is_empty() {
return profile;
}
let mut paths = Vec::new();
for s in sockets {
if !paths.contains(s) {
paths.push(s.clone());
}
let canon = canonicalize_existing_prefix(s);
if canon != *s && !paths.contains(&canon) {
paths.push(canon);
}
}
profile.push_str("(deny network-outbound");
for p in paths {
let escaped = escape_path(&p);
profile.push_str(&format!(
r#" (remote unix-socket (path-literal "{escaped}"))"#
));
}
profile.push(')');
profile
}
pub fn offline(mut profile: String, docker_sockets: &[PathBuf]) -> String {
profile.push_str(
r#"(deny network-outbound)(allow network-outbound (remote ip "localhost:*"))(allow network-outbound (remote unix-socket))"#,
);
deny_unix_sockets(profile, docker_sockets)
}
#[cfg(target_os = "macos")]
fn default_profile_base(root: &Path, allow_read: &[PathBuf]) -> String {
let deny_read = match std::env::var_os("HOME") {
Some(home) if !home.is_empty() => read_denied(Path::new(&home)),
_ => Vec::new(),
};
deny_state_blyte_write(profile_with(
root,
&default_allowed(root),
&deny_read,
allow_read,
))
}
pub fn default_profile(root: &Path, allow_read: &[PathBuf]) -> Profile {
#[cfg(target_os = "macos")]
{
Profile::Seatbelt(deny_unix_sockets(
default_profile_base(root, allow_read),
¤t_agent_sockets(),
))
}
#[cfg(not(target_os = "macos"))]
{
let home = std::env::var_os("HOME");
let home_path = home.as_ref().filter(|h| !h.is_empty()).map(Path::new);
Profile::LandlockConfined {
write: default_allowed(root),
read: read_allowed(home_path, allow_read),
block_tcp: false,
}
}
}
pub fn default_profile_net(root: &Path, allow_read: &[PathBuf], network: bool) -> Profile {
if network {
return default_profile(root, allow_read);
}
#[cfg(target_os = "macos")]
{
let base = default_profile_base(root, allow_read);
let socks = match std::env::var_os("HOME") {
Some(home) if !home.is_empty() => docker_sockets(Path::new(&home)),
_ => Vec::new(),
};
Profile::Seatbelt(deny_unix_sockets(
offline(base, &socks),
¤t_agent_sockets(),
))
}
#[cfg(not(target_os = "macos"))]
{
let home = std::env::var_os("HOME");
let home_path = home.as_ref().filter(|h| !h.is_empty()).map(Path::new);
Profile::LandlockConfined {
write: default_allowed(root),
read: read_allowed(home_path, allow_read),
block_tcp: true,
}
}
}
#[cfg(target_os = "linux")]
pub(crate) fn landlock_pre_exec(
cmd: &mut std::process::Command,
write: &[PathBuf],
read: Option<&[PathBuf]>,
block_tcp: bool,
) -> std::io::Result<()> {
use landlock::{
path_beneath_rules, Access, AccessFs, AccessNet, Ruleset, RulesetAttr, RulesetCreated,
RulesetCreatedAttr, ABI,
};
use std::os::unix::process::CommandExt;
use std::sync::Mutex;
if block_tcp && landlock_abi() < 4 {
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"needs Linux 6.7 or later",
));
}
let mut ruleset = Ruleset::default()
.handle_access(AccessFs::from_write(ABI::V5))
.map_err(std::io::Error::other)?;
if read.is_some() {
ruleset = ruleset
.handle_access(AccessFs::from_read(ABI::V5))
.map_err(std::io::Error::other)?;
}
if block_tcp {
ruleset = ruleset
.handle_access(AccessNet::ConnectTcp)
.map_err(std::io::Error::other)?;
}
let ruleset: RulesetCreated = ruleset.create().map_err(std::io::Error::other)?;
let ruleset: RulesetCreated = match read {
Some(read_paths) => ruleset
.add_rules(path_beneath_rules(write, AccessFs::from_all(ABI::V5)))
.map_err(std::io::Error::other)?
.add_rules(path_beneath_rules(read_paths, AccessFs::from_read(ABI::V5)))
.map_err(std::io::Error::other)?,
None => ruleset
.add_rules(path_beneath_rules(write, AccessFs::from_write(ABI::V5)))
.map_err(std::io::Error::other)?,
};
let ruleset = Mutex::new(Some(ruleset));
unsafe {
cmd.pre_exec(move || {
let mut guard = ruleset
.lock()
.map_err(|_| std::io::Error::from_raw_os_error(libc::EPERM))?;
let r = guard
.take()
.ok_or_else(|| std::io::Error::from_raw_os_error(libc::EPERM))?;
if r.restrict_self().is_err() {
return Err(std::io::Error::from_raw_os_error(libc::EPERM));
}
Ok(())
});
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn open_edit_worktrees_empty_when_wt_missing() {
let tmp = tempfile::tempdir().unwrap();
assert_eq!(
open_edit_worktrees(tmp.path()).unwrap(),
Vec::<PathBuf>::new()
);
}
#[test]
fn open_edit_worktrees_sorted_and_filtered() {
let tmp = tempfile::tempdir().unwrap();
let wt = tmp.path().join(".wt");
std::fs::create_dir_all(wt.join("B")).unwrap();
std::fs::create_dir_all(wt.join("A")).unwrap();
std::fs::create_dir_all(wt.join("Done")).unwrap();
std::fs::create_dir_all(wt.join("NoMarker")).unwrap();
std::fs::write(wt.join("NotADir"), "file\n").unwrap();
std::fs::write(wt.join("B.edit.json"), "{}\n").unwrap();
std::fs::write(wt.join("A.edit.json"), "{}\n").unwrap();
std::fs::write(wt.join("Done.edit.json"), "{}\n").unwrap();
std::fs::write(wt.join("Done.json"), "{}\n").unwrap();
std::fs::write(wt.join("MissingDir.edit.json"), "{}\n").unwrap();
std::fs::write(wt.join("NotADir.edit.json"), "{}\n").unwrap();
let got = open_edit_worktrees(tmp.path()).unwrap();
assert_eq!(got, vec![wt.join("A"), wt.join("B")]);
}
#[test]
fn open_edit_worktrees_errors_on_unreadable_wt() {
let tmp = tempfile::tempdir().unwrap();
let wt = tmp.path().join(".wt");
std::fs::write(&wt, "not a directory\n").unwrap();
let err = open_edit_worktrees(tmp.path()).unwrap_err();
assert!(err.contains(&wt.display().to_string()), "{err}");
}
#[cfg(target_os = "macos")]
#[test]
fn conversation_profile_with_edits_denies_worktree_git() {
let tmp = tempfile::tempdir().unwrap();
let wt = tmp.path().join(".wt/E1");
std::fs::create_dir_all(&wt).unwrap();
let Profile::Seatbelt(sbpl) =
conversation_profile_with_edits(tmp.path(), &[], false, std::slice::from_ref(&wt))
.unwrap()
else {
panic!("expected Seatbelt profile on macOS");
};
let canon = wt.canonicalize().unwrap();
let escaped_wt = escape_path(&canon);
let escaped_git = escape_path(&canon.join(".git"));
let expected = format!(
r#"(allow file-write* (subpath "{escaped_wt}"))(deny file-write* (literal "{escaped_git}"))"#
);
assert!(sbpl.contains(&expected), "{sbpl}");
}
}