1use crate::{pathctx, sanitize_display};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum ReachReason {
9 Credential,
11 OtherUsersHome,
15 FrozenTrustFile,
21 FrozenTrustRoot,
26 FrozenSystemIntegrity,
29 RawDevice,
34 OutsideWorkspace,
36 Unconfined,
40 ForeignTemp,
45 RepositorySnapshot,
46}
47
48impl ReachReason {
49 pub fn settled(self, command: &str, approved: &dyn Fn(&str) -> bool) -> ReachReason {
52 match self {
53 ReachReason::RepositorySnapshot if !without_snapshot(command).is_some_and(|c| approved(&c)) => ReachReason::FrozenTrustRoot,
54 reason => reason,
55 }
56 }
57
58 pub fn grant_helps(self) -> bool {
70 match self {
71 ReachReason::Credential | ReachReason::OtherUsersHome | ReachReason::RawDevice => true,
73 ReachReason::ForeignTemp | ReachReason::OutsideWorkspace => true,
75 ReachReason::FrozenTrustFile
79 | ReachReason::FrozenTrustRoot
80 | ReachReason::FrozenSystemIntegrity
81 | ReachReason::RepositorySnapshot => false,
82 ReachReason::Unconfined => false,
84 }
85 }
86
87 pub fn message(self, path: &str) -> String {
90 let path = &sanitize_display(path);
91 match self {
92 ReachReason::Credential => format!(
93 "it reaches `{path}`, a credential store. The agent has no ordinary reason to touch \
94 one. If that was not intended, stop it. If you do want to allow it, name that path \
95 in ~/.config/safe-chains.toml. A grant on a parent directory does not reach a \
96 credential store"
97 ),
98 ReachReason::OtherUsersHome => format!(
99 "it reaches `{path}`, inside another user's home folder. safe-chains treats \
100 everything there as that user's private files. If the path came from someone \
101 else's machine, change it to the same place on this one. If you do want to allow \
102 it, name that path in ~/.config/safe-chains.toml"
103 ),
104 ReachReason::RawDevice => format!(
105 "it reaches `{path}`, a raw device. Reading one is not reading a file — a disk \
106 device hands over every file on it and memory hands over every secret in it — and \
107 writing one goes underneath the filesystem entirely. If you do want the read, \
108 name that path in ~/.config/safe-chains.toml; the write stays refused"
109 ),
110 ReachReason::FrozenTrustFile => format!(
111 "it reaches `{path}`. safe-chains reads its permissions from that file, so a write \
112 there is never auto-approved. No grant changes this. Run it yourself if you meant to"
113 ),
114 ReachReason::FrozenTrustRoot => format!(
115 "it reaches `{path}`. safe-chains reads its permissions from a file in that \
116 directory, so removing or replacing it, or writing to a jj repository there, is \
117 never auto-approved. No grant changes this. Run it yourself if you meant to"
118 ),
119 ReachReason::FrozenSystemIntegrity => format!(
120 "it reaches `{path}`. That file decides who may log in, so a write there is never \
121 auto-approved. No grant changes this. Run it yourself if you meant to"
122 ),
123 ReachReason::ForeignTemp => format!(
124 "it runs code from `{path}`, a temporary directory that is not this session's \
125 scratchpad. Reading and writing temp files is fine. Running code from there is \
126 not, because a downloaded script lands in the same place. If this is a working \
127 directory you trust, grant it in ~/.config/safe-chains.toml. A scratchpad the \
128 harness reports for this session is recognized on its own and needs no grant"
129 ),
130 ReachReason::Unconfined => format!(
131 "the path `{path}` is built by an interpolation, so what it names depends on a \
132 value the command does not show. It could be anywhere, which is why it cannot be \
133 auto-approved. If the interpolated part cannot contain a `/`, put literal text \
134 beside it in the same path component. `out/dx_$i.txt` is approved where `out/$i` \
135 is not: the first is a filename whatever `$i` holds, and the second could be `..`"
136 ),
137 ReachReason::RepositorySnapshot => format!(
138 "it uses `{path}` as the jj repository, and jj writes a snapshot there before it \
139 reads. Add --ignore-working-copy after `jj` to read without the snapshot. Edits \
140 since the last snapshot will not show. No grant changes this"
141 ),
142 ReachReason::OutsideWorkspace => match pathctx::display_cwd().map(|c| sanitize_display(&c)) {
143 Some(cwd) => format!(
144 "it reaches `{path}`, outside the working directory `{cwd}`. If the agent is \
145 running from the wrong directory, relaunch it where you meant to be. To allow \
146 it from here, grant that path in ~/.config/safe-chains.toml"
147 ),
148 None => format!(
149 "it reaches `{path}`, outside the working directory. To allow it, grant that \
150 path in ~/.config/safe-chains.toml"
151 ),
152 },
153 }
154 }
155}
156
157enum Tilde {
159 Theirs(String),
162 Ours(String),
164 Stack,
166}
167
168fn tilde_of(path: &str) -> Option<Tilde> {
169 let own = |rest: &str| if rest.is_empty() { "~".to_string() } else { format!("~/{rest}") };
170 if let Some(named) = path.strip_prefix('~').filter(|r| !r.is_empty() && !r.starts_with('/')) {
171 let (user, rest) = named.split_once('/').unwrap_or((named, ""));
172 let home = crate::process_home::var().unwrap_or_default();
173 let ours = home.rsplit_once('/').map(|(_, name)| name).unwrap_or_default();
174 Some(if user == ours {
175 Tilde::Ours(own(rest))
176 } else if user.starts_with(['+', '-']) || user.bytes().all(|b| b.is_ascii_digit()) {
177 Tilde::Stack
178 } else {
179 Tilde::Theirs(own(rest))
180 })
181 } else if crate::engine::resolve::regions::absolute_other_home(path) {
182 Some(Tilde::Theirs(own(path.splitn(4, '/').nth(3).unwrap_or(""))))
183 } else {
184 None
185 }
186}
187
188pub(crate) fn classify(resolved: &str) -> ReachReason {
189 let theirs = match tilde_of(resolved) {
201 Some(Tilde::Ours(own)) => return classify(&own),
202 Some(Tilde::Stack) => return ReachReason::Unconfined,
203 Some(Tilde::Theirs(own)) => Some(own),
204 None => None,
205 };
206 if theirs.as_deref().is_some_and(|own| !crate::engine::resolve::names_credential_store(own)) {
207 ReachReason::OtherUsersHome
208 } else if crate::engine::resolve::names_credential_store(resolved) {
209 ReachReason::Credential
210 } else if let Some(kind) = crate::engine::resolve::frozen_write_kind(resolved) {
211 match kind {
215 crate::engine::resolve::FrozenWrite::TrustFile => ReachReason::FrozenTrustFile,
216 crate::engine::resolve::FrozenWrite::TrustRootDir => ReachReason::FrozenTrustRoot,
217 crate::engine::resolve::FrozenWrite::SystemIntegrity => ReachReason::FrozenSystemIntegrity,
218 crate::engine::resolve::FrozenWrite::RawDevice => ReachReason::RawDevice,
219 }
220 } else if crate::engine::resolve::anchoring_of(resolved) == crate::engine::facet::Anchoring::Opaque {
221 ReachReason::Unconfined
226 } else {
227 ReachReason::OutsideWorkspace
228 }
229}
230
231pub(crate) fn without_snapshot(command: &str) -> Option<String> {
232 let rest = command.trim_start().strip_prefix("jj")?;
233 rest.starts_with([' ', '\t']).then(|| format!("jj --ignore-working-copy{rest}"))
234}
235
236pub(crate) fn repository_snapshot(command: &str) -> Option<(String, ReachReason)> {
237 let rewritten = without_snapshot(command)?;
238 let words = shell_words::split(command).ok()?;
239 let repository = crate::pathgate::handlers::jj::repository_value(&words)?;
240 if classify(crate::pathctx::place(&repository, None).judged()) != ReachReason::FrozenTrustRoot {
241 return None;
242 }
243 (!crate::is_safe_command(command) && crate::is_safe_command(&rewritten)).then_some((repository, ReachReason::RepositorySnapshot))
244}
245
246#[cfg(test)]
247pub(crate) mod tests {
248 use super::ReachReason;
249 use proptest::prelude::*;
250
251 pub(crate) const ALL: &[ReachReason] = &[
252 ReachReason::Credential,
253 ReachReason::OtherUsersHome,
254 ReachReason::FrozenTrustFile,
255 ReachReason::FrozenTrustRoot,
256 ReachReason::FrozenSystemIntegrity,
257 ReachReason::RawDevice,
258 ReachReason::OutsideWorkspace,
259 ReachReason::Unconfined,
260 ReachReason::ForeignTemp,
261 ReachReason::RepositorySnapshot,
262 ];
263
264 proptest! {
265 #[test]
266 fn every_reason_names_the_path_on_one_line(path in "[~/a-z.\n\r\t\u{202e} ]{1,24}") {
267 for reason in ALL {
268 let text = reason.message(&path);
269 prop_assert_eq!(text.lines().count(), 1, "{:?}: {}", reason, text);
270 prop_assert!(text.contains(&crate::sanitize_display(&path)), "{:?}: {}", reason, text);
271 }
272 }
273
274 #[test]
277 fn another_users_home_is_a_credential_store_only_where_ours_would_be(
278 user in "zz[a-z]{1,6}",
279 rest in proptest::sample::select(vec![
280 "", "Source/headmaster", "notes.txt", ".bashrc", ".ssh", ".ssh/id_rsa", ".aws/credentials",
281 ".gnupg/secring.gpg", "Library/Keychains/login.keychain-db", "projects/x/.env",
282 ]),
283 root in proptest::sample::select(vec!["/Users", "/home"]),
284 ) {
285 let tail = if rest.is_empty() { String::new() } else { format!("/{rest}") };
286 let own = if rest.is_empty() { "~".to_string() } else { format!("~/{rest}") };
287 let expected = if crate::engine::resolve::names_credential_store(&own) {
288 ReachReason::Credential
289 } else {
290 ReachReason::OtherUsersHome
291 };
292 for path in [format!("{root}/{user}{tail}"), format!("~{user}{tail}")] {
293 prop_assert_eq!(super::classify(&path), expected, "{}", path);
294 }
295 }
296
297 #[test]
301 fn a_tilde_that_names_us_or_the_directory_stack_is_no_other_users_home(
302 prefix in proptest::sample::select(vec!["ours", "+", "-", "+1", "-2", "3"]),
303 rest in proptest::sample::select(vec!["", "notes.txt", "Source/x", ".ssh/id_rsa"]),
304 ) {
305 let home = crate::process_home::var().unwrap_or_default();
306 let ours = home.rsplit_once('/').map(|(_, name)| name).unwrap_or_default();
307 prop_assume!(!ours.is_empty());
308 let tail = if rest.is_empty() { String::new() } else { format!("/{rest}") };
309 let (path, expected) = if prefix == "ours" {
310 (format!("~{ours}{tail}"), super::classify(&format!("~{tail}")))
311 } else {
312 (format!("~{prefix}{tail}"), ReachReason::Unconfined)
313 };
314 prop_assert_eq!(super::classify(&path), expected, "{}", path);
315 }
316
317 #[test]
318 fn a_trust_root_reason_stays_short_and_plain(path in "[~/a-z.]{1,24}") {
319 let trust = [
320 ReachReason::FrozenTrustFile,
321 ReachReason::FrozenTrustRoot,
322 ReachReason::FrozenSystemIntegrity,
323 ReachReason::RepositorySnapshot,
324 ];
325 for reason in trust {
326 let text = reason.message(&path);
327 let body = text.replacen(&path, "", 1);
328 prop_assert!(body.chars().count() <= 240, "{:?} is {} characters: {}", reason, body.chars().count(), text);
329 prop_assert!(!text.contains('\u{2014}') && !text.contains(':') && !text.contains(';'), "{:?}: {}", reason, text);
330 }
331 }
332 }
333
334 fn in_a_project<T>(body: impl FnOnce(&str) -> T) -> T {
335 use crate::pathctx::{PathCtx, enter};
336 let home = crate::process_home::var().expect("HOME");
337 assert!(home.starts_with('/'), "HOME must be absolute for these tests: {home}");
338 let ws = format!("{home}/projects/scproj");
339 let _g = enter(PathCtx { cwd: Some(ws.clone()), root: Some(ws), ..Default::default() });
340 body(&home)
341 }
342
343 const OBSERVING: &[&str] = &["log", "diff", "show", "status", "st", "bookmark list", "op log", "op show", "file list", "tag list"];
344 const MUTATING: &[&str] = &["new", "describe -m x", "abandon", "bookmark set main", "git fetch", "workspace update-stale"];
345
346 proptest! {
347 #[test]
348 fn a_trust_root_repository_is_explained_by_its_snapshot_only_for_an_observing_sub(
349 observing in any::<bool>(),
350 pick in any::<prop::sample::Index>(),
351 spelling in 0usize..3,
352 root in prop::sample::select(vec![".claude", ".config"]),
353 tail in prop::sample::select(vec!["", " --no-pager", " --quiet"]),
354 ) {
355 in_a_project(|home| {
356 let repo = format!("{home}/{root}");
357 let flag = match spelling {
358 0 => format!("-R {repo}"),
359 1 => format!("--repository {repo}"),
360 _ => format!("--repository={repo}"),
361 };
362 let sub = if observing { pick.get(OBSERVING) } else { pick.get(MUTATING) };
363 let command = format!("jj {flag} {sub}{tail}");
364 let ungranted = crate::workspace_overreach(&command);
365 assert!(!matches!(ungranted, Some((_, ReachReason::RepositorySnapshot))), "{command}: {ungranted:?}");
366 let reach = crate::engine::resolve::regions::with_grants(&[(repo.as_str(), true, true)], || crate::workspace_overreach(&command));
367 if observing {
368 assert_eq!(reach, Some((repo.clone(), ReachReason::RepositorySnapshot)), "{command}");
369 } else {
370 assert!(!matches!(reach, Some((_, ReachReason::RepositorySnapshot))), "{command}: {reach:?}");
371 }
372 });
373 }
374 }
375
376 #[test]
377 fn the_snapshot_reason_is_true_to_the_verdict() {
378 use crate::engine::resolve::regions::with_grants;
379 in_a_project(|home| {
380 let repo = format!("{home}/.claude");
381 let command = format!("jj -R {repo} log");
382 let read = format!("jj --ignore-working-copy -R {repo} log");
383 assert!(!crate::is_safe_command(&command));
384 assert!(!crate::is_safe_command(&read), "a repository outside the project is not opened ungranted");
385 assert!(with_grants(&[(repo.as_str(), true, true)], || crate::is_safe_command(&read)));
386 assert!(!with_grants(&[(repo.as_str(), false, true)], || crate::is_safe_command(&command)));
387 assert!(!ReachReason::RepositorySnapshot.grant_helps());
388 for other in [format!("{home}/.config/safe-chains.toml"), "/etc/sudoers".to_string(), format!("{home}/x")] {
389 let reach = crate::workspace_overreach(&format!("jj -R {other} log"));
390 assert!(!matches!(reach, Some((_, ReachReason::RepositorySnapshot))), "{other}: {reach:?}");
391 }
392 assert_eq!(super::repository_snapshot(&format!("jjx -R {repo} log")), None);
393 let snapshot = ReachReason::RepositorySnapshot;
394 assert_eq!(snapshot.settled(&command, &|c| crate::is_safe_command(c)), ReachReason::FrozenTrustRoot);
395 assert_eq!(
396 with_grants(&[(repo.as_str(), true, true)], || snapshot.settled(&command, &|c| crate::is_safe_command(c))),
397 snapshot
398 );
399 assert_eq!(snapshot.settled(&command, &|_| false), ReachReason::FrozenTrustRoot);
400 assert_eq!(ReachReason::OutsideWorkspace.settled(&command, &|_| false), ReachReason::OutsideWorkspace);
401 });
402 }
403}