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 file safe-chains reads its OWN permissions from (`~/.config/safe-chains.toml`,
12    /// `~/.claude/settings.json`). Distinct from `OutsideWorkspace` because the generic remedy
13    /// there — grant the path — is not merely unhelpful but FALSE: the write face is frozen, so
14    /// following the advice changes nothing. For safe-chains' own config it is also circular,
15    /// telling the user to edit the file they are being stopped from editing.
16    FrozenTrustFile,
17    /// The DIRECTORY a trust file lives in. Distinct from `FrozenTrustFile` because only HALF of
18    /// it is refused: writing a file into `~/.config` is ordinary and stays allowed, and only
19    /// removing or replacing the directory is not. Copy that said "this is refused" flatly would
20    /// misdescribe a directory the user explicitly granted.
21    FrozenTrustRoot,
22    /// One of the files that decide who may log in (`/etc/passwd`, `/etc/sudoers`, `/etc/pam.d`,
23    /// the loader and boot). Same false-remedy problem as `FrozenTrustFile`.
24    FrozenSystemIntegrity,
25    /// A raw block or character device (`/dev/mem`, `/dev/rdisk0`, `/dev/sda`). Distinct from
26    /// `FrozenSystemIntegrity` because the `device` rung outranks `system-integrity`, so without
27    /// its own arm every device was explained as a file that "decides who may log in" — which is
28    /// both false and unhelpful about the thing that actually makes a device dangerous.
29    RawDevice,
30    /// Genuinely above/outside the working directory.
31    OutsideWorkspace,
32    /// A path built by an interpolation that nothing confines (`./out/$i`, `> $(cmd)`). It is not
33    /// outside anything — it names WHATEVER the value turns out to be, which is why it cannot be
34    /// admitted — so the remedy is to constrain the spelling, not to grant a directory.
35    Unconfined,
36    /// A temp path that is NOT this session's scratchpad. Reading and writing it is fine; RUNNING
37    /// code from it is not, because anonymous `/tmp` is where downloaded/foreign code lands. This
38    /// is the one reach whose remedy is usually "that IS my working directory" — so the nudge says
39    /// how to bless it rather than implying the agent did something wrong.
40    ForeignTemp,
41    RepositorySnapshot,
42}
43
44impl ReachReason {
45    /// The reason as the reader should hear it: a snapshot refusal whose `--ignore-working-copy`
46    /// form would not be approved either (a stricter level) is reported as the trust root it is.
47    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    /// Whether naming this path in `~/.config/safe-chains.toml` actually changes the verdict.
55    ///
56    /// The refusal copy offers a grant, or explains that granting will not help, and the two must
57    /// not diverge: advice that does nothing costs more than silence, because the reader follows
58    /// it, sees no change, and stops believing the rest. `a_refusal_offers_a_grant_only_when_one_
59    /// would_work` runs the verdict twice — once with the grant applied — and holds this to it.
60    ///
61    /// `Credential` is `true` as of 2026-09-01 and was `false` before it. A grant naming a store
62    /// used to move the locus and leave `reads_secret` set, so the message's "name that path"
63    /// advice was FALSE while reading exactly right. That is the failure this pairing exists to
64    /// catch, and it went unnoticed because nothing compared the sentence to the behaviour.
65    pub fn grant_helps(self) -> bool {
66        match self {
67            // A grant that NAMES the store clears the shield for reading it.
68            ReachReason::Credential | ReachReason::RawDevice => true,
69            // "That IS my working directory" is the usual answer here.
70            ReachReason::ForeignTemp | ReachReason::OutsideWorkspace => true,
71            // Frozen faces stay frozen however specifically they are named: an agent that can edit
72            // the trust file decides what is approved next, and one that can write `/etc/sudoers`
73            // owns the machine's authorization substrate.
74            ReachReason::FrozenTrustFile
75            | ReachReason::FrozenTrustRoot
76            | ReachReason::FrozenSystemIntegrity
77            | ReachReason::RepositorySnapshot => false,
78            // There is no path to grant. The remedy is to constrain the spelling.
79            ReachReason::Unconfined => false,
80        }
81    }
82
83    /// The self-contained nudge body ("it reaches `X`, …") including the reason-appropriate remedy.
84    /// Callers add their own framing (block / please-confirm) and the docs link.
85    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    // Asked on the LITERAL structure, so an interpolated component cannot strip the credential
149    // warning off a path that plainly names one. `cat ~/.ssh/$(id)` was reported as merely
150    // "built by an interpolation" — offering to flank it, which can never help, while dropping
151    // the one sentence that matters — and the CONFINED spelling fell through to
152    // "outside the working directory", whose remedy is to GRANT the path.
153    //
154    // Granting a credential store IS possible now (a grant covers what it names), so the
155    // objection is no longer "that remedy cannot work". It is that the generic wording says
156    // "grant that path" while meaning the ordinary parent-directory grant, which is exactly
157    // the form a credential store does not accept. The Credential arm spells out the
158    // difference instead.
159    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        // Ahead of Unconfined and OutsideWorkspace for the same reason Credential is: both of
163        // those end in "grant that path", which for a frozen write face is FALSE rather than
164        // merely vague, and for safe-chains' own config it is circular as well.
165        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        // Ahead of OutsideWorkspace because it is the more specific diagnosis of the SAME
173        // refusal, and the generic wording actively misleads here: it names a working-directory
174        // problem the user does not have and a remedy (grant the path) that cannot work,
175        // since the path is not a fixed path at all.
176        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}