Skip to main content

safe_chains/
reach.rs

1use crate::{pathctx, sanitize_display};
2
3/// Why a not-auto-approved command's path reach was flagged — so the nudge can explain the actual
4/// reason instead of a one-size-fits-all "outside the working directory". A peer's hidden file and a
5/// path genuinely above cwd both deny, but the remedy differs, and conflating them is what reads as
6/// "directory parsing is broken".
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum ReachReason {
9    /// A known credential store (`.ssh`, `.aws`, keychain…).
10    Credential,
11    /// A place in another user's home folder that is not a credential store. It is kept as private
12    /// as one, but calling a source checkout "a credential store" is false, and the usual cause is
13    /// a command copied from someone else's machine.
14    OtherUsersHome,
15    /// A file safe-chains reads its OWN permissions from (`~/.config/safe-chains.toml`,
16    /// `~/.claude/settings.json`). Distinct from `OutsideWorkspace` because the generic remedy
17    /// there — grant the path — is not merely unhelpful but FALSE: the write face is frozen, so
18    /// following the advice changes nothing. For safe-chains' own config it is also circular,
19    /// telling the user to edit the file they are being stopped from editing.
20    FrozenTrustFile,
21    /// The DIRECTORY a trust file lives in. Distinct from `FrozenTrustFile` because only HALF of
22    /// it is refused: writing a file into `~/.config` is ordinary and stays allowed, and only
23    /// removing or replacing the directory is not. Copy that said "this is refused" flatly would
24    /// misdescribe a directory the user explicitly granted.
25    FrozenTrustRoot,
26    /// One of the files that decide who may log in (`/etc/passwd`, `/etc/sudoers`, `/etc/pam.d`,
27    /// the loader and boot). Same false-remedy problem as `FrozenTrustFile`.
28    FrozenSystemIntegrity,
29    /// A raw block or character device (`/dev/mem`, `/dev/rdisk0`, `/dev/sda`). Distinct from
30    /// `FrozenSystemIntegrity` because the `device` rung outranks `system-integrity`, so without
31    /// its own arm every device was explained as a file that "decides who may log in" — which is
32    /// both false and unhelpful about the thing that actually makes a device dangerous.
33    RawDevice,
34    /// Genuinely above/outside the working directory.
35    OutsideWorkspace,
36    /// A path built by an interpolation that nothing confines (`./out/$i`, `> $(cmd)`). It is not
37    /// outside anything — it names WHATEVER the value turns out to be, which is why it cannot be
38    /// admitted — so the remedy is to constrain the spelling, not to grant a directory.
39    Unconfined,
40    /// A temp path that is NOT this session's scratchpad. Reading and writing it is fine; RUNNING
41    /// code from it is not, because anonymous `/tmp` is where downloaded/foreign code lands. This
42    /// is the one reach whose remedy is usually "that IS my working directory" — so the nudge says
43    /// how to bless it rather than implying the agent did something wrong.
44    ForeignTemp,
45    RepositorySnapshot,
46}
47
48impl ReachReason {
49    /// The reason as the reader should hear it: a snapshot refusal whose `--ignore-working-copy`
50    /// form would not be approved either (a stricter level) is reported as the trust root it is.
51    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    /// Whether naming this path in `~/.config/safe-chains.toml` actually changes the verdict.
59    ///
60    /// The refusal copy offers a grant, or explains that granting will not help, and the two must
61    /// not diverge: advice that does nothing costs more than silence, because the reader follows
62    /// it, sees no change, and stops believing the rest. `a_refusal_offers_a_grant_only_when_one_
63    /// would_work` runs the verdict twice — once with the grant applied — and holds this to it.
64    ///
65    /// `Credential` is `true` as of 2026-09-01 and was `false` before it. A grant naming a store
66    /// used to move the locus and leave `reads_secret` set, so the message's "name that path"
67    /// advice was FALSE while reading exactly right. That is the failure this pairing exists to
68    /// catch, and it went unnoticed because nothing compared the sentence to the behaviour.
69    pub fn grant_helps(self) -> bool {
70        match self {
71            // A grant that NAMES the store clears the shield for reading it.
72            ReachReason::Credential | ReachReason::OtherUsersHome | ReachReason::RawDevice => true,
73            // "That IS my working directory" is the usual answer here.
74            ReachReason::ForeignTemp | ReachReason::OutsideWorkspace => true,
75            // Frozen faces stay frozen however specifically they are named: an agent that can edit
76            // the trust file decides what is approved next, and one that can write `/etc/sudoers`
77            // owns the machine's authorization substrate.
78            ReachReason::FrozenTrustFile
79            | ReachReason::FrozenTrustRoot
80            | ReachReason::FrozenSystemIntegrity
81            | ReachReason::RepositorySnapshot => false,
82            // There is no path to grant. The remedy is to constrain the spelling.
83            ReachReason::Unconfined => false,
84        }
85    }
86
87    /// The self-contained nudge body ("it reaches `X`, …") including the reason-appropriate remedy.
88    /// Callers add their own framing (block / please-confirm) and the docs link.
89    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::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
157/// What a path's leading `~word` stands for.
158enum Tilde {
159    /// Another user's home: the same place under ours (`~/rest` for `/Users/someone/rest` or
160    /// `~someone/rest`), so a refusal can tell a store of theirs (`.ssh`) from an ordinary folder.
161    Theirs(String),
162    /// `~ourname/rest`, which is `~/rest`.
163    Ours(String),
164    /// The directory stack's `~+`, `~-` and `~2`, whose value the line does not show.
165    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 = std::env::var("HOME").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    // Asked on the LITERAL structure, so an interpolated component cannot strip the credential
190    // warning off a path that plainly names one. `cat ~/.ssh/$(id)` was reported as merely
191    // "built by an interpolation" — offering to flank it, which can never help, while dropping
192    // the one sentence that matters — and the CONFINED spelling fell through to
193    // "outside the working directory", whose remedy is to GRANT the path.
194    //
195    // Granting a credential store IS possible now (a grant covers what it names), so the
196    // objection is no longer "that remedy cannot work". It is that the generic wording says
197    // "grant that path" while meaning the ordinary parent-directory grant, which is exactly
198    // the form a credential store does not accept. The Credential arm spells out the
199    // difference instead.
200    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        // Ahead of Unconfined and OutsideWorkspace for the same reason Credential is: both of
212        // those end in "grant that path", which for a frozen write face is FALSE rather than
213        // merely vague, and for safe-chains' own config it is circular as well.
214        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        // Ahead of OutsideWorkspace because it is the more specific diagnosis of the SAME
222        // refusal, and the generic wording actively misleads here: it names a working-directory
223        // problem the user does not have and a remedy (grant the path) that cannot work,
224        // since the path is not a fixed path at all.
225        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::resolve(&repository)) != 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        /// A place in another user's home is a credential store exactly when the same place in ours
275        /// would be one, and otherwise it is that user's home, under either spelling of it.
276        #[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        /// Our own name after `~` is explained as `~` itself, and the directory stack's `~+`, `~-`
298        /// and `~N` as a value the line does not show: neither is another user, nor a credential
299        /// store merely for being spelt with a tilde.
300        #[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 = std::env::var("HOME").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 = std::env::var("HOME").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", "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}