use crate::{pathctx, sanitize_display};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReachReason {
Credential,
OtherUsersHome,
FrozenTrustFile,
FrozenTrustRoot,
FrozenSystemIntegrity,
RawDevice,
OutsideWorkspace,
Unconfined,
ForeignTemp,
RepositorySnapshot,
}
impl ReachReason {
pub fn settled(self, command: &str, approved: &dyn Fn(&str) -> bool) -> ReachReason {
match self {
ReachReason::RepositorySnapshot if !without_snapshot(command).is_some_and(|c| approved(&c)) => ReachReason::FrozenTrustRoot,
reason => reason,
}
}
pub fn grant_helps(self) -> bool {
match self {
ReachReason::Credential | ReachReason::OtherUsersHome | ReachReason::RawDevice => true,
ReachReason::ForeignTemp | ReachReason::OutsideWorkspace => true,
ReachReason::FrozenTrustFile
| ReachReason::FrozenTrustRoot
| ReachReason::FrozenSystemIntegrity
| ReachReason::RepositorySnapshot => false,
ReachReason::Unconfined => false,
}
}
pub fn message(self, path: &str) -> String {
let path = &sanitize_display(path);
match self {
ReachReason::Credential => format!(
"it reaches `{path}`, a credential store. The agent has no ordinary reason to touch \
one. If that was not intended, stop it. If you do want to allow it, name that path \
in ~/.config/safe-chains.toml. A grant on a parent directory does not reach a \
credential store"
),
ReachReason::OtherUsersHome => format!(
"it reaches `{path}`, inside another user's home folder. safe-chains treats \
everything there as that user's private files. If the path came from someone \
else's machine, change it to the same place on this one. If you do want to allow \
it, name that path in ~/.config/safe-chains.toml"
),
ReachReason::RawDevice => format!(
"it reaches `{path}`, a raw device. Reading one is not reading a file — a disk \
device hands over every file on it and memory hands over every secret in it — and \
writing one goes underneath the filesystem entirely. If you do want the read, \
name that path in ~/.config/safe-chains.toml; the write stays refused"
),
ReachReason::FrozenTrustFile => format!(
"it reaches `{path}`. safe-chains reads its permissions from that file, so a write \
there is never auto-approved. No grant changes this. Run it yourself if you meant to"
),
ReachReason::FrozenTrustRoot => format!(
"it reaches `{path}`. safe-chains reads its permissions from a file in that \
directory, so removing or replacing it, or writing to a jj repository there, is \
never auto-approved. No grant changes this. Run it yourself if you meant to"
),
ReachReason::FrozenSystemIntegrity => format!(
"it reaches `{path}`. That file decides who may log in, so a write there is never \
auto-approved. No grant changes this. Run it yourself if you meant to"
),
ReachReason::ForeignTemp => format!(
"it runs code from `{path}`, a temporary directory that is not this session's \
scratchpad. Reading and writing temp files is fine. Running code from there is \
not, because a downloaded script lands in the same place. If this is a working \
directory you trust, grant it in ~/.config/safe-chains.toml. A scratchpad the \
harness reports for this session is recognized on its own and needs no grant"
),
ReachReason::Unconfined => format!(
"the path `{path}` is built by an interpolation, so what it names depends on a \
value the command does not show. It could be anywhere, which is why it cannot be \
auto-approved. If the interpolated part cannot contain a `/`, put literal text \
beside it in the same path component. `out/dx_$i.txt` is approved where `out/$i` \
is not: the first is a filename whatever `$i` holds, and the second could be `..`"
),
ReachReason::RepositorySnapshot => format!(
"it uses `{path}` as the jj repository, and jj writes a snapshot there before it \
reads. Add --ignore-working-copy after `jj` to read without the snapshot. Edits \
since the last snapshot will not show. No grant changes this"
),
ReachReason::OutsideWorkspace => match pathctx::cwd().map(|c| sanitize_display(&c)) {
Some(cwd) => format!(
"it reaches `{path}`, outside the working directory `{cwd}`. If the agent is \
running from the wrong directory, relaunch it where you meant to be. To allow \
it from here, grant that path in ~/.config/safe-chains.toml"
),
None => format!(
"it reaches `{path}`, outside the working directory. To allow it, grant that \
path in ~/.config/safe-chains.toml"
),
},
}
}
}
enum Tilde {
Theirs(String),
Ours(String),
Stack,
}
fn tilde_of(path: &str) -> Option<Tilde> {
let own = |rest: &str| if rest.is_empty() { "~".to_string() } else { format!("~/{rest}") };
if let Some(named) = path.strip_prefix('~').filter(|r| !r.is_empty() && !r.starts_with('/')) {
let (user, rest) = named.split_once('/').unwrap_or((named, ""));
let home = std::env::var("HOME").unwrap_or_default();
let ours = home.rsplit_once('/').map(|(_, name)| name).unwrap_or_default();
Some(if user == ours {
Tilde::Ours(own(rest))
} else if user.starts_with(['+', '-']) || user.bytes().all(|b| b.is_ascii_digit()) {
Tilde::Stack
} else {
Tilde::Theirs(own(rest))
})
} else if crate::engine::resolve::regions::absolute_other_home(path) {
Some(Tilde::Theirs(own(path.splitn(4, '/').nth(3).unwrap_or(""))))
} else {
None
}
}
pub(crate) fn classify(resolved: &str) -> ReachReason {
let theirs = match tilde_of(resolved) {
Some(Tilde::Ours(own)) => return classify(&own),
Some(Tilde::Stack) => return ReachReason::Unconfined,
Some(Tilde::Theirs(own)) => Some(own),
None => None,
};
if theirs.as_deref().is_some_and(|own| !crate::engine::resolve::names_credential_store(own)) {
ReachReason::OtherUsersHome
} else if crate::engine::resolve::names_credential_store(resolved) {
ReachReason::Credential
} else if let Some(kind) = crate::engine::resolve::frozen_write_kind(resolved) {
match kind {
crate::engine::resolve::FrozenWrite::TrustFile => ReachReason::FrozenTrustFile,
crate::engine::resolve::FrozenWrite::TrustRootDir => ReachReason::FrozenTrustRoot,
crate::engine::resolve::FrozenWrite::SystemIntegrity => ReachReason::FrozenSystemIntegrity,
crate::engine::resolve::FrozenWrite::RawDevice => ReachReason::RawDevice,
}
} else if crate::engine::resolve::anchoring_of(resolved) == crate::engine::facet::Anchoring::Opaque {
ReachReason::Unconfined
} else {
ReachReason::OutsideWorkspace
}
}
pub(crate) fn without_snapshot(command: &str) -> Option<String> {
let rest = command.trim_start().strip_prefix("jj")?;
rest.starts_with([' ', '\t']).then(|| format!("jj --ignore-working-copy{rest}"))
}
pub(crate) fn repository_snapshot(command: &str) -> Option<(String, ReachReason)> {
let rewritten = without_snapshot(command)?;
let words = shell_words::split(command).ok()?;
let repository = crate::pathgate::handlers::jj::repository_value(&words)?;
if classify(&crate::pathctx::resolve(&repository)) != ReachReason::FrozenTrustRoot {
return None;
}
(!crate::is_safe_command(command) && crate::is_safe_command(&rewritten)).then_some((repository, ReachReason::RepositorySnapshot))
}
#[cfg(test)]
pub(crate) mod tests {
use super::ReachReason;
use proptest::prelude::*;
pub(crate) const ALL: &[ReachReason] = &[
ReachReason::Credential,
ReachReason::OtherUsersHome,
ReachReason::FrozenTrustFile,
ReachReason::FrozenTrustRoot,
ReachReason::FrozenSystemIntegrity,
ReachReason::RawDevice,
ReachReason::OutsideWorkspace,
ReachReason::Unconfined,
ReachReason::ForeignTemp,
ReachReason::RepositorySnapshot,
];
proptest! {
#[test]
fn every_reason_names_the_path_on_one_line(path in "[~/a-z.\n\r\t\u{202e} ]{1,24}") {
for reason in ALL {
let text = reason.message(&path);
prop_assert_eq!(text.lines().count(), 1, "{:?}: {}", reason, text);
prop_assert!(text.contains(&crate::sanitize_display(&path)), "{:?}: {}", reason, text);
}
}
#[test]
fn another_users_home_is_a_credential_store_only_where_ours_would_be(
user in "zz[a-z]{1,6}",
rest in proptest::sample::select(vec![
"", "Source/headmaster", "notes.txt", ".bashrc", ".ssh", ".ssh/id_rsa", ".aws/credentials",
".gnupg/secring.gpg", "Library/Keychains/login.keychain-db", "projects/x/.env",
]),
root in proptest::sample::select(vec!["/Users", "/home"]),
) {
let tail = if rest.is_empty() { String::new() } else { format!("/{rest}") };
let own = if rest.is_empty() { "~".to_string() } else { format!("~/{rest}") };
let expected = if crate::engine::resolve::names_credential_store(&own) {
ReachReason::Credential
} else {
ReachReason::OtherUsersHome
};
for path in [format!("{root}/{user}{tail}"), format!("~{user}{tail}")] {
prop_assert_eq!(super::classify(&path), expected, "{}", path);
}
}
#[test]
fn a_tilde_that_names_us_or_the_directory_stack_is_no_other_users_home(
prefix in proptest::sample::select(vec!["ours", "+", "-", "+1", "-2", "3"]),
rest in proptest::sample::select(vec!["", "notes.txt", "Source/x", ".ssh/id_rsa"]),
) {
let home = std::env::var("HOME").unwrap_or_default();
let ours = home.rsplit_once('/').map(|(_, name)| name).unwrap_or_default();
prop_assume!(!ours.is_empty());
let tail = if rest.is_empty() { String::new() } else { format!("/{rest}") };
let (path, expected) = if prefix == "ours" {
(format!("~{ours}{tail}"), super::classify(&format!("~{tail}")))
} else {
(format!("~{prefix}{tail}"), ReachReason::Unconfined)
};
prop_assert_eq!(super::classify(&path), expected, "{}", path);
}
#[test]
fn a_trust_root_reason_stays_short_and_plain(path in "[~/a-z.]{1,24}") {
let trust = [
ReachReason::FrozenTrustFile,
ReachReason::FrozenTrustRoot,
ReachReason::FrozenSystemIntegrity,
ReachReason::RepositorySnapshot,
];
for reason in trust {
let text = reason.message(&path);
let body = text.replacen(&path, "", 1);
prop_assert!(body.chars().count() <= 240, "{:?} is {} characters: {}", reason, body.chars().count(), text);
prop_assert!(!text.contains('\u{2014}') && !text.contains(':') && !text.contains(';'), "{:?}: {}", reason, text);
}
}
}
fn in_a_project<T>(body: impl FnOnce(&str) -> T) -> T {
use crate::pathctx::{PathCtx, enter};
let home = std::env::var("HOME").expect("HOME");
assert!(home.starts_with('/'), "HOME must be absolute for these tests: {home}");
let ws = format!("{home}/projects/scproj");
let _g = enter(PathCtx { cwd: Some(ws.clone()), root: Some(ws), ..Default::default() });
body(&home)
}
const OBSERVING: &[&str] = &["log", "diff", "show", "status", "st", "bookmark list", "op log", "file list", "tag list"];
const MUTATING: &[&str] = &["new", "describe -m x", "abandon", "bookmark set main", "git fetch", "workspace update-stale"];
proptest! {
#[test]
fn a_trust_root_repository_is_explained_by_its_snapshot_only_for_an_observing_sub(
observing in any::<bool>(),
pick in any::<prop::sample::Index>(),
spelling in 0usize..3,
root in prop::sample::select(vec![".claude", ".config"]),
tail in prop::sample::select(vec!["", " --no-pager", " --quiet"]),
) {
in_a_project(|home| {
let repo = format!("{home}/{root}");
let flag = match spelling {
0 => format!("-R {repo}"),
1 => format!("--repository {repo}"),
_ => format!("--repository={repo}"),
};
let sub = if observing { pick.get(OBSERVING) } else { pick.get(MUTATING) };
let command = format!("jj {flag} {sub}{tail}");
let reach = crate::workspace_overreach(&command);
if observing {
assert_eq!(reach, Some((repo.clone(), ReachReason::RepositorySnapshot)), "{command}");
} else {
assert!(!matches!(reach, Some((_, ReachReason::RepositorySnapshot))), "{command}: {reach:?}");
}
});
}
}
#[test]
fn the_snapshot_reason_is_true_to_the_verdict() {
use crate::engine::resolve::regions::with_grants;
in_a_project(|home| {
let repo = format!("{home}/.claude");
let command = format!("jj -R {repo} log");
assert!(!crate::is_safe_command(&command));
assert!(crate::is_safe_command(&format!("jj --ignore-working-copy -R {repo} log")));
assert!(!with_grants(&[(repo.as_str(), false, true)], || crate::is_safe_command(&command)));
assert!(!ReachReason::RepositorySnapshot.grant_helps());
for other in [format!("{home}/.config/safe-chains.toml"), "/etc/sudoers".to_string(), format!("{home}/x")] {
let reach = crate::workspace_overreach(&format!("jj -R {other} log"));
assert!(!matches!(reach, Some((_, ReachReason::RepositorySnapshot))), "{other}: {reach:?}");
}
assert_eq!(super::repository_snapshot(&format!("jjx -R {repo} log")), None);
let snapshot = ReachReason::RepositorySnapshot;
assert_eq!(snapshot.settled(&command, &|c| crate::is_safe_command(c)), snapshot);
assert_eq!(snapshot.settled(&command, &|_| false), ReachReason::FrozenTrustRoot);
assert_eq!(ReachReason::OutsideWorkspace.settled(&command, &|_| false), ReachReason::OutsideWorkspace);
});
}
}