safe-chains 0.243.6

Auto-allow safe bash commands in agentic coding tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use crate::{pathctx, sanitize_display};

/// Why a not-auto-approved command's path reach was flagged — so the nudge can explain the actual
/// reason instead of a one-size-fits-all "outside the working directory". A peer's hidden file and a
/// path genuinely above cwd both deny, but the remedy differs, and conflating them is what reads as
/// "directory parsing is broken".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReachReason {
    /// A known credential store (`.ssh`, `.aws`, keychain…).
    Credential,
    /// A place in another user's home folder that is not a credential store. It is kept as private
    /// as one, but calling a source checkout "a credential store" is false, and the usual cause is
    /// a command copied from someone else's machine.
    OtherUsersHome,
    /// A file safe-chains reads its OWN permissions from (`~/.config/safe-chains.toml`,
    /// `~/.claude/settings.json`). Distinct from `OutsideWorkspace` because the generic remedy
    /// there — grant the path — is not merely unhelpful but FALSE: the write face is frozen, so
    /// following the advice changes nothing. For safe-chains' own config it is also circular,
    /// telling the user to edit the file they are being stopped from editing.
    FrozenTrustFile,
    /// The DIRECTORY a trust file lives in. Distinct from `FrozenTrustFile` because only HALF of
    /// it is refused: writing a file into `~/.config` is ordinary and stays allowed, and only
    /// removing or replacing the directory is not. Copy that said "this is refused" flatly would
    /// misdescribe a directory the user explicitly granted.
    FrozenTrustRoot,
    /// One of the files that decide who may log in (`/etc/passwd`, `/etc/sudoers`, `/etc/pam.d`,
    /// the loader and boot). Same false-remedy problem as `FrozenTrustFile`.
    FrozenSystemIntegrity,
    /// A raw block or character device (`/dev/mem`, `/dev/rdisk0`, `/dev/sda`). Distinct from
    /// `FrozenSystemIntegrity` because the `device` rung outranks `system-integrity`, so without
    /// its own arm every device was explained as a file that "decides who may log in" — which is
    /// both false and unhelpful about the thing that actually makes a device dangerous.
    RawDevice,
    /// Genuinely above/outside the working directory.
    OutsideWorkspace,
    /// A path built by an interpolation that nothing confines (`./out/$i`, `> $(cmd)`). It is not
    /// outside anything — it names WHATEVER the value turns out to be, which is why it cannot be
    /// admitted — so the remedy is to constrain the spelling, not to grant a directory.
    Unconfined,
    /// A temp path that is NOT this session's scratchpad. Reading and writing it is fine; RUNNING
    /// code from it is not, because anonymous `/tmp` is where downloaded/foreign code lands. This
    /// is the one reach whose remedy is usually "that IS my working directory" — so the nudge says
    /// how to bless it rather than implying the agent did something wrong.
    ForeignTemp,
    RepositorySnapshot,
}

impl ReachReason {
    /// The reason as the reader should hear it: a snapshot refusal whose `--ignore-working-copy`
    /// form would not be approved either (a stricter level) is reported as the trust root it is.
    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,
        }
    }

    /// Whether naming this path in `~/.config/safe-chains.toml` actually changes the verdict.
    ///
    /// The refusal copy offers a grant, or explains that granting will not help, and the two must
    /// not diverge: advice that does nothing costs more than silence, because the reader follows
    /// it, sees no change, and stops believing the rest. `a_refusal_offers_a_grant_only_when_one_
    /// would_work` runs the verdict twice — once with the grant applied — and holds this to it.
    ///
    /// `Credential` is `true` as of 2026-09-01 and was `false` before it. A grant naming a store
    /// used to move the locus and leave `reads_secret` set, so the message's "name that path"
    /// advice was FALSE while reading exactly right. That is the failure this pairing exists to
    /// catch, and it went unnoticed because nothing compared the sentence to the behaviour.
    pub fn grant_helps(self) -> bool {
        match self {
            // A grant that NAMES the store clears the shield for reading it.
            ReachReason::Credential | ReachReason::OtherUsersHome | ReachReason::RawDevice => true,
            // "That IS my working directory" is the usual answer here.
            ReachReason::ForeignTemp | ReachReason::OutsideWorkspace => true,
            // Frozen faces stay frozen however specifically they are named: an agent that can edit
            // the trust file decides what is approved next, and one that can write `/etc/sudoers`
            // owns the machine's authorization substrate.
            ReachReason::FrozenTrustFile
            | ReachReason::FrozenTrustRoot
            | ReachReason::FrozenSystemIntegrity
            | ReachReason::RepositorySnapshot => false,
            // There is no path to grant. The remedy is to constrain the spelling.
            ReachReason::Unconfined => false,
        }
    }

    /// The self-contained nudge body ("it reaches `X`, …") including the reason-appropriate remedy.
    /// Callers add their own framing (block / please-confirm) and the docs link.
    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::display_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"
                ),
            },
        }
    }
}

/// What a path's leading `~word` stands for.
enum Tilde {
    /// Another user's home: the same place under ours (`~/rest` for `/Users/someone/rest` or
    /// `~someone/rest`), so a refusal can tell a store of theirs (`.ssh`) from an ordinary folder.
    Theirs(String),
    /// `~ourname/rest`, which is `~/rest`.
    Ours(String),
    /// The directory stack's `~+`, `~-` and `~2`, whose value the line does not show.
    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 = crate::process_home::var().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 {
    // Asked on the LITERAL structure, so an interpolated component cannot strip the credential
    // warning off a path that plainly names one. `cat ~/.ssh/$(id)` was reported as merely
    // "built by an interpolation" — offering to flank it, which can never help, while dropping
    // the one sentence that matters — and the CONFINED spelling fell through to
    // "outside the working directory", whose remedy is to GRANT the path.
    //
    // Granting a credential store IS possible now (a grant covers what it names), so the
    // objection is no longer "that remedy cannot work". It is that the generic wording says
    // "grant that path" while meaning the ordinary parent-directory grant, which is exactly
    // the form a credential store does not accept. The Credential arm spells out the
    // difference instead.
    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) {
        // Ahead of Unconfined and OutsideWorkspace for the same reason Credential is: both of
        // those end in "grant that path", which for a frozen write face is FALSE rather than
        // merely vague, and for safe-chains' own config it is circular as well.
        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 {
        // Ahead of OutsideWorkspace because it is the more specific diagnosis of the SAME
        // refusal, and the generic wording actively misleads here: it names a working-directory
        // problem the user does not have and a remedy (grant the path) that cannot work,
        // since the path is not a fixed path at all.
        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::place(&repository, None).judged()) != 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);
            }
        }

        /// A place in another user's home is a credential store exactly when the same place in ours
        /// would be one, and otherwise it is that user's home, under either spelling of it.
        #[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);
            }
        }

        /// Our own name after `~` is explained as `~` itself, and the directory stack's `~+`, `~-`
        /// and `~N` as a value the line does not show: neither is another user, nor a credential
        /// store merely for being spelt with a tilde.
        #[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 = crate::process_home::var().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 = crate::process_home::var().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", "op show", "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 ungranted = crate::workspace_overreach(&command);
                assert!(!matches!(ungranted, Some((_, ReachReason::RepositorySnapshot))), "{command}: {ungranted:?}");
                let reach = crate::engine::resolve::regions::with_grants(&[(repo.as_str(), true, true)], || 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");
            let read = format!("jj --ignore-working-copy -R {repo} log");
            assert!(!crate::is_safe_command(&command));
            assert!(!crate::is_safe_command(&read), "a repository outside the project is not opened ungranted");
            assert!(with_grants(&[(repo.as_str(), true, true)], || crate::is_safe_command(&read)));
            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)), ReachReason::FrozenTrustRoot);
            assert_eq!(
                with_grants(&[(repo.as_str(), true, true)], || 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);
        });
    }
}