1use crate::{pathctx, sanitize_display};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum ReachReason {
9 Credential,
11 FrozenTrustFile,
17 FrozenTrustRoot,
22 FrozenSystemIntegrity,
25 RawDevice,
30 OutsideWorkspace,
32 Unconfined,
36 ForeignTemp,
41 RepositorySnapshot,
42}
43
44impl ReachReason {
45 pub fn settled(self, command: &str, approved: &dyn Fn(&str) -> bool) -> ReachReason {
48 match self {
49 ReachReason::RepositorySnapshot if !without_snapshot(command).is_some_and(|c| approved(&c)) => ReachReason::FrozenTrustRoot,
50 reason => reason,
51 }
52 }
53
54 pub fn grant_helps(self) -> bool {
66 match self {
67 ReachReason::Credential | ReachReason::RawDevice => true,
69 ReachReason::ForeignTemp | ReachReason::OutsideWorkspace => true,
71 ReachReason::FrozenTrustFile
75 | ReachReason::FrozenTrustRoot
76 | ReachReason::FrozenSystemIntegrity
77 | ReachReason::RepositorySnapshot => false,
78 ReachReason::Unconfined => false,
80 }
81 }
82
83 pub fn message(self, path: &str) -> String {
86 let path = &sanitize_display(path);
87 match self {
88 ReachReason::Credential => format!(
89 "it reaches `{path}`, a credential store. The agent has no ordinary reason to touch \
90 one. If that was not intended, stop it. If you do want to allow it, name that path \
91 in ~/.config/safe-chains.toml. A grant on a parent directory does not reach a \
92 credential store"
93 ),
94 ReachReason::RawDevice => format!(
95 "it reaches `{path}`, a raw device. Reading one is not reading a file — a disk \
96 device hands over every file on it and memory hands over every secret in it — and \
97 writing one goes underneath the filesystem entirely. If you do want the read, \
98 name that path in ~/.config/safe-chains.toml; the write stays refused"
99 ),
100 ReachReason::FrozenTrustFile => format!(
101 "it reaches `{path}`. safe-chains reads its permissions from that file, so a write \
102 there is never auto-approved. No grant changes this. Run it yourself if you meant to"
103 ),
104 ReachReason::FrozenTrustRoot => format!(
105 "it reaches `{path}`. safe-chains reads its permissions from a file in that \
106 directory, so removing or replacing it, or writing to a jj repository there, is \
107 never auto-approved. No grant changes this. Run it yourself if you meant to"
108 ),
109 ReachReason::FrozenSystemIntegrity => format!(
110 "it reaches `{path}`. That file decides who may log in, so a write there is never \
111 auto-approved. No grant changes this. Run it yourself if you meant to"
112 ),
113 ReachReason::ForeignTemp => format!(
114 "it runs code from `{path}`, a temporary directory that is not this session's \
115 scratchpad. Reading and writing temp files is fine. Running code from there is \
116 not, because a downloaded script lands in the same place. If this is a working \
117 directory you trust, grant it in ~/.config/safe-chains.toml. A scratchpad the \
118 harness reports for this session is recognized on its own and needs no grant"
119 ),
120 ReachReason::Unconfined => format!(
121 "the path `{path}` is built by an interpolation, so what it names depends on a \
122 value the command does not show. It could be anywhere, which is why it cannot be \
123 auto-approved. If the interpolated part cannot contain a `/`, put literal text \
124 beside it in the same path component. `out/dx_$i.txt` is approved where `out/$i` \
125 is not: the first is a filename whatever `$i` holds, and the second could be `..`"
126 ),
127 ReachReason::RepositorySnapshot => format!(
128 "it uses `{path}` as the jj repository, and jj writes a snapshot there before it \
129 reads. Add --ignore-working-copy after `jj` to read without the snapshot. Edits \
130 since the last snapshot will not show. No grant changes this"
131 ),
132 ReachReason::OutsideWorkspace => match pathctx::cwd().map(|c| sanitize_display(&c)) {
133 Some(cwd) => format!(
134 "it reaches `{path}`, outside the working directory `{cwd}`. If the agent is \
135 running from the wrong directory, relaunch it where you meant to be. To allow \
136 it from here, grant that path in ~/.config/safe-chains.toml"
137 ),
138 None => format!(
139 "it reaches `{path}`, outside the working directory. To allow it, grant that \
140 path in ~/.config/safe-chains.toml"
141 ),
142 },
143 }
144 }
145}
146
147pub(crate) fn classify(resolved: &str) -> ReachReason {
148 if crate::engine::resolve::names_credential_store(resolved) {
160 ReachReason::Credential
161 } else if let Some(kind) = crate::engine::resolve::frozen_write_kind(resolved) {
162 match kind {
166 crate::engine::resolve::FrozenWrite::TrustFile => ReachReason::FrozenTrustFile,
167 crate::engine::resolve::FrozenWrite::TrustRootDir => ReachReason::FrozenTrustRoot,
168 crate::engine::resolve::FrozenWrite::SystemIntegrity => ReachReason::FrozenSystemIntegrity,
169 crate::engine::resolve::FrozenWrite::RawDevice => ReachReason::RawDevice,
170 }
171 } else if crate::engine::resolve::anchoring_of(resolved) == crate::engine::facet::Anchoring::Opaque {
172 ReachReason::Unconfined
177 } else {
178 ReachReason::OutsideWorkspace
179 }
180}
181
182pub(crate) fn without_snapshot(command: &str) -> Option<String> {
183 let rest = command.trim_start().strip_prefix("jj")?;
184 rest.starts_with([' ', '\t']).then(|| format!("jj --ignore-working-copy{rest}"))
185}
186
187pub(crate) fn repository_snapshot(command: &str) -> Option<(String, ReachReason)> {
188 let rewritten = without_snapshot(command)?;
189 let words = shell_words::split(command).ok()?;
190 let repository = crate::pathgate::handlers::jj::repository_value(&words)?;
191 if classify(&crate::pathctx::resolve(&repository)) != ReachReason::FrozenTrustRoot {
192 return None;
193 }
194 (!crate::is_safe_command(command) && crate::is_safe_command(&rewritten)).then_some((repository, ReachReason::RepositorySnapshot))
195}
196
197#[cfg(test)]
198pub(crate) mod tests {
199 use super::ReachReason;
200 use proptest::prelude::*;
201
202 pub(crate) const ALL: &[ReachReason] = &[
203 ReachReason::Credential,
204 ReachReason::FrozenTrustFile,
205 ReachReason::FrozenTrustRoot,
206 ReachReason::FrozenSystemIntegrity,
207 ReachReason::RawDevice,
208 ReachReason::OutsideWorkspace,
209 ReachReason::Unconfined,
210 ReachReason::ForeignTemp,
211 ReachReason::RepositorySnapshot,
212 ];
213
214 proptest! {
215 #[test]
216 fn every_reason_names_the_path_on_one_line(path in "[~/a-z.\n\r\t\u{202e} ]{1,24}") {
217 for reason in ALL {
218 let text = reason.message(&path);
219 prop_assert_eq!(text.lines().count(), 1, "{:?}: {}", reason, text);
220 prop_assert!(text.contains(&crate::sanitize_display(&path)), "{:?}: {}", reason, text);
221 }
222 }
223
224 #[test]
225 fn a_trust_root_reason_stays_short_and_plain(path in "[~/a-z.]{1,24}") {
226 let trust = [
227 ReachReason::FrozenTrustFile,
228 ReachReason::FrozenTrustRoot,
229 ReachReason::FrozenSystemIntegrity,
230 ReachReason::RepositorySnapshot,
231 ];
232 for reason in trust {
233 let text = reason.message(&path);
234 let body = text.replacen(&path, "", 1);
235 prop_assert!(body.chars().count() <= 240, "{:?} is {} characters: {}", reason, body.chars().count(), text);
236 prop_assert!(!text.contains('\u{2014}') && !text.contains(':') && !text.contains(';'), "{:?}: {}", reason, text);
237 }
238 }
239 }
240
241 fn in_a_project<T>(body: impl FnOnce(&str) -> T) -> T {
242 use crate::pathctx::{PathCtx, enter};
243 let home = std::env::var("HOME").expect("HOME");
244 assert!(home.starts_with('/'), "HOME must be absolute for these tests: {home}");
245 let ws = format!("{home}/projects/scproj");
246 let _g = enter(PathCtx { cwd: Some(ws.clone()), root: Some(ws), ..Default::default() });
247 body(&home)
248 }
249
250 const OBSERVING: &[&str] = &["log", "diff", "show", "status", "st", "bookmark list", "op log", "file list", "tag list"];
251 const MUTATING: &[&str] = &["new", "describe -m x", "abandon", "bookmark set main", "git fetch", "workspace update-stale"];
252
253 proptest! {
254 #[test]
255 fn a_trust_root_repository_is_explained_by_its_snapshot_only_for_an_observing_sub(
256 observing in any::<bool>(),
257 pick in any::<prop::sample::Index>(),
258 spelling in 0usize..3,
259 root in prop::sample::select(vec![".claude", ".config"]),
260 tail in prop::sample::select(vec!["", " --no-pager", " --quiet"]),
261 ) {
262 in_a_project(|home| {
263 let repo = format!("{home}/{root}");
264 let flag = match spelling {
265 0 => format!("-R {repo}"),
266 1 => format!("--repository {repo}"),
267 _ => format!("--repository={repo}"),
268 };
269 let sub = if observing { pick.get(OBSERVING) } else { pick.get(MUTATING) };
270 let command = format!("jj {flag} {sub}{tail}");
271 let reach = crate::workspace_overreach(&command);
272 if observing {
273 assert_eq!(reach, Some((repo.clone(), ReachReason::RepositorySnapshot)), "{command}");
274 } else {
275 assert!(!matches!(reach, Some((_, ReachReason::RepositorySnapshot))), "{command}: {reach:?}");
276 }
277 });
278 }
279 }
280
281 #[test]
282 fn the_snapshot_reason_is_true_to_the_verdict() {
283 use crate::engine::resolve::regions::with_grants;
284 in_a_project(|home| {
285 let repo = format!("{home}/.claude");
286 let command = format!("jj -R {repo} log");
287 assert!(!crate::is_safe_command(&command));
288 assert!(crate::is_safe_command(&format!("jj --ignore-working-copy -R {repo} log")));
289 assert!(!with_grants(&[(repo.as_str(), false, true)], || crate::is_safe_command(&command)));
290 assert!(!ReachReason::RepositorySnapshot.grant_helps());
291 for other in [format!("{home}/.config/safe-chains.toml"), "/etc/sudoers".to_string(), format!("{home}/x")] {
292 let reach = crate::workspace_overreach(&format!("jj -R {other} log"));
293 assert!(!matches!(reach, Some((_, ReachReason::RepositorySnapshot))), "{other}: {reach:?}");
294 }
295 assert_eq!(super::repository_snapshot(&format!("jjx -R {repo} log")), None);
296 let snapshot = ReachReason::RepositorySnapshot;
297 assert_eq!(snapshot.settled(&command, &|c| crate::is_safe_command(c)), snapshot);
298 assert_eq!(snapshot.settled(&command, &|_| false), ReachReason::FrozenTrustRoot);
299 assert_eq!(ReachReason::OutsideWorkspace.settled(&command, &|_| false), ReachReason::OutsideWorkspace);
300 });
301 }
302}