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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Which region nodes protect something, whether a workspace root sits above one of them, and what
//! the table can say about a name with no folder to place it in.

use std::sync::LazyLock;

use super::{Frozen, Matcher, REGIONS, Role, absolute_other_home, current_os, secret_node};
use crate::engine::facet::LocalLocus;

#[path = "workspace_roots.rs"]
mod workspace_roots;

/// Whether a role is a PROTECTION (a credential/secret shield, the pinned config, or a
/// write-freeze) rather than an admit — it makes some face stricter than an ordinary worktree.
/// Only protection nodes are matched case-insensitively on a case-insensitive filesystem: folding
/// an ADMIT (`/tmp`, worktree) could admit a case-variant that is a DIFFERENT path on a
/// case-sensitive volume (fail-open), whereas folding a protection only ever denies more.
pub(super) fn role_is_protective(role: &Role) -> bool {
    role.reads_secret
        || role.frozen != Frozen::Nothing
        || role.write_locus > LocalLocus::Worktree
        || role.read_locus > LocalLocus::WorktreeTrusted
}

/// Whether absolute `abs`, inside the workspace `root`, must keep its absolute spelling instead of
/// becoming a root-relative worktree path.
///
/// A root that contains a place protected at a fixed location (`/etc/shadow`,
/// `~/.config/safe-chains.toml`, `/boot/`) would otherwise turn that place, and every directory
/// above it, into ordinary worktree files. So a path at, inside or above such a place stays
/// absolute (a glob counts as its literal directory), and classifies as from any other workspace.
/// A root at or above a home directory (`/`, `/Users`, `$HOME`, and `/private`) keeps EVERY path absolute: the
/// whole home is the protection there, read but never written. A root that sits INSIDE a protected
/// place (`/root/app`) contains none and is unaffected.
///
/// The root comes from the harness as spelled, so paths are compared in a normal form: `.` and
/// `..` collapsed, macOS's `/private` firmlinks folded (a session started in `/etc` reports
/// `/private/etc`), a leading `/System/Volumes/Data` removed, and, on macOS, Unicode composed to
/// NFC and case folded. A folded comparison only ever finds more.
pub(crate) fn keeps_absolute(abs: &str, root: &str) -> bool {
    if crate::pathctx::folder::is_unknown(root) {
        return true;
    }
    let root_cmp = comparable(root);
    let home = crate::pathctx::home_dir();
    if holds_a_home(&root_cmp, home.as_deref()) || protection_or_ancestor_covers(root) {
        return true;
    }
    let path = comparable(&literal_dir(abs));
    REGIONS
        .nodes
        .iter()
        .filter(|n| n.applies_here() && role_is_protective(&n.role))
        .filter_map(|n| {
            let (place, sub) = fixed_place(&n.matcher)?;
            Some((place, sub || n.role.frozen == Frozen::Rebind))
        })
        .any(|(place, subtree)| {
            let place = match (place.strip_prefix('~'), home.as_deref()) {
                (Some(rest), Some(h)) => comparable(&format!("{h}{rest}")),
                (Some(_), None) => return true,
                (None, _) => comparable(&place),
            };
            (under(&place, &root_cmp) || (subtree && under(&root_cmp, &place)))
                && ((subtree && under(&path, &place)) || under(&place, &path))
        })
}

fn region_node_covers(path: &str) -> bool {
    let path = super::super::locus::canonicalize(path);
    let fold_shields = current_os() == "macos";
    REGIONS
        .nodes
        .iter()
        .filter(|n| n.applies_here() && role_is_protective(&n.role))
        .any(|n| n.matcher.specificity(&path, n.fold && fold_shields).is_some())
}

fn protection_or_ancestor_covers(path: &str) -> bool {
    let Some(norm) = crate::pathctx::join_cwd(None, path).filter(|p| p.starts_with('/')) else {
        return region_node_covers(path);
    };
    let mut cur = norm.as_str();
    loop {
        if region_node_covers(cur) {
            return true;
        }
        let Some((parent, _)) = cur.rsplit_once('/') else {
            return false;
        };
        if parent.is_empty() {
            return region_node_covers("/");
        }
        cur = parent;
    }
}

fn has_disallowed_dot_component(path: &str, home: Option<&str>) -> bool {
    let Some(norm) = crate::pathctx::join_cwd(None, path).filter(|p| p.starts_with('/')) else {
        return true;
    };
    if let Some(disqualified) = workspace_roots::dot_disqualifies(&norm, home) {
        return disqualified;
    }
    if let Some(h) = home.map(|h| h.trim_end_matches('/')).filter(|h| !h.is_empty())
        && let Some(rel) = norm.strip_prefix(h).and_then(|r| r.strip_prefix('/'))
    {
        if let Some(wt_rel) = rel.strip_prefix(".worktrees/") {
            return wt_rel.is_empty() || wt_rel.split('/').any(|c| c.starts_with('.'));
        }
        return rel.split('/').any(|c| c.starts_with('.'));
    }
    norm.rsplit('/').next().unwrap_or("").starts_with('.')
}

pub(crate) fn is_workspace_root(dir: &str) -> bool {
    if !dir.starts_with('/')
        || dir == crate::targets::UNKNOWN_WORKDIR
        || dir == crate::pathctx::UNRESOLVED_CWD
        || dir.contains('$')
        || dir.contains("__SAFE_CHAINS_")
    {
        return false;
    }
    let Some(lex) = crate::pathctx::join_cwd(None, dir).filter(|p| p.starts_with('/')) else {
        return false;
    };
    let phys = crate::pathctx::physical_directory(&lex);
    if phys == crate::pathctx::UNRESOLVED_CWD {
        return false;
    }
    let home = crate::process_home::var().ok().filter(|h| h.starts_with('/') && h.len() > 1);
    let phys_home = home.as_deref().map(crate::pathctx::physical_directory);
    let clean = |p: &str, h: Option<&str>| {
        !holds_a_home(&comparable(p), h)
            && !protection_or_ancestor_covers(p)
            && !has_disallowed_dot_component(p, h)
            && in_known_workspace(p, h)
    };
    clean(&lex, home.as_deref()) && clean(&phys, phys_home.as_deref().or(home.as_deref()))
}

fn in_known_workspace(path: &str, home: Option<&str>) -> bool {
    if let Some(h) = home.map(|h| h.trim_end_matches('/')).filter(|h| !h.is_empty())
        && let Some(rel) = path.strip_prefix(h).and_then(|r| r.strip_prefix('/'))
        && (rel == "projects" || rel.starts_with("projects/") || (rel.starts_with(".worktrees/") && !rel[".worktrees/".len()..].is_empty()))
    {
        return true;
    }
    if workspace_roots::listed(path, home) {
        return true;
    }
    (granted_in_user_config(path) && granted_for_writing(path))
        || path
            .strip_prefix("/private")
            .filter(|rest| rest.starts_with("/var/") || rest.starts_with("/tmp/") || rest.starts_with("/etc/"))
            .is_some_and(|rest| granted_in_user_config(rest) && granted_for_writing(rest))
}

fn granted_in_user_config(path: &str) -> bool {
    let canon = super::super::locus::canonicalize(path);
    let matches = |grants: &mut dyn Iterator<Item = &super::Grant>| {
        for g in grants {
            if g.source == super::GrantSource::UserConfig
                && g.write
                && g.matcher.specificity(&canon, false).is_some()
                && !super::has_hidden_component(g.matcher.remainder(&canon))
            {
                return true;
            }
        }
        false
    };
    #[cfg(test)]
    {
        super::TEST_GRANTS.with(|g| super::hypothetical::with_extra(|extra| matches(&mut g.borrow().iter().chain(extra))))
    }
    #[cfg(not(test))]
    {
        super::hypothetical::with_extra(|extra| matches(&mut super::USER_GRANTS.iter().chain(extra)))
    }
}

fn under(inner: &str, outer: &str) -> bool {
    outer == "/" || inner == outer || inner.strip_prefix(outer).is_some_and(|r| r.starts_with('/'))
}

pub(super) fn holds_a_home(root: &str, home: Option<&str>) -> bool {
    ["/Users", "/home", "/private"].into_iter().chain(home).map(comparable).any(|h| under(&h, root))
}

/// Whether a grant hands `path` over for writing: the user named the folder as one they work in,
/// so a repository there is theirs as the project's is.
pub(crate) fn granted_for_writing(path: &str) -> bool {
    super::best_grant(&super::super::locus::canonicalize(path), None).is_some_and(|(_, write)| write)
}

/// Whether the absolute `abs` lies at or below the project root, which `keeps_absolute` does not
/// say for a project that is itself a protected place (a session working in `~/.claude`). A root
/// at or above a home directory contains nothing, as there.
pub(crate) fn lies_in_root(placed: &crate::pathctx::Placed, root: &str) -> bool {
    let root = comparable(root);
    let home = crate::pathctx::home_dir();
    root != "/" && !holds_a_home(&root, home.as_deref()) && under(&comparable(placed.judged()), &root)
}

/// `path` up to its first component holding a glob character: the directory a glob can reach into.
fn literal_dir(path: &str) -> String {
    path.split('/').take_while(|c| !c.contains(['*', '?', '['])).collect::<Vec<_>>().join("/")
}

/// An absolute path in the form `keeps_absolute` compares: lexically collapsed, the
/// `/private/{etc,var,tmp}` firmlinks folded, a leading `/System/Volumes/Data` removed (any ASCII
/// case on macOS), and on macOS Unicode in NFC and lowercased. No trailing slash but `/`.
pub(super) fn comparable(path: &str) -> String {
    // Composition is a property of the default macOS volume. Off macOS the two forms are different
    // directories, and folding them would treat a path outside the project as inside it.
    let path = if current_os() == "macos" { super::unicode_spelling::nfc(path) } else { path.to_string() };
    let mut parts: Vec<&str> = Vec::new();
    for seg in path.split('/') {
        match seg {
            "" | "." => {}
            ".." => {
                parts.pop();
            }
            s => parts.push(s),
        }
    }
    let mut out = format!("/{}", parts.join("/"));
    if current_os() == "macos" {
        out = out.to_ascii_lowercase();
    }
    out = strip_data_volume(out);
    for firm in ["/etc", "/var", "/tmp"] {
        let private = format!("/private{firm}");
        if out == private || out.starts_with(&format!("{private}/")) {
            out = out["/private".len()..].to_string();
        }
    }
    out
}

/// Remove a leading `/System/Volumes/Data`. On macOS the path is already lowercased, so every
/// ASCII case of the prefix goes; elsewhere only the exact spelling does.
fn strip_data_volume(path: String) -> String {
    let prefix = if current_os() == "macos" { "/system/volumes/data" } else { "/System/Volumes/Data" };
    let mut rest = path.as_str();
    while rest == prefix || rest.strip_prefix(prefix).is_some_and(|tail| tail.starts_with('/')) {
        rest = &rest[prefix.len()..];
        if rest.is_empty() {
            return "/".to_string();
        }
    }
    if rest.len() == path.len() { path } else { rest.to_string() }
}

/// The literal directory or file a node is anchored at, and whether it covers what is below it
/// (an exact node names one path only), or `None` for an anchorless segment node.
fn fixed_place(matcher: &Matcher) -> Option<(String, bool)> {
    match matcher {
        Matcher::Exact(s) => Some((s.clone(), false)),
        Matcher::Prefix(s) => Some((s.clone(), true)),
        Matcher::StringPrefix(s) => Some((s.rsplit_once('/').map_or_else(String::new, |(dir, _)| dir.to_string()), true)),
        Matcher::Glob(parts) => Some((parts.iter().take_while(|p| !p.contains('*')).cloned().collect::<Vec<_>>().join("/"), true)),
        Matcher::Segment(_) => None,
    }
}

/// Whether any protection, anchored or not, covers absolute `path`: a workspace rooted inside one
/// (`~/.ssh`) is where the user chose to work, but a `~/` spelling is not resolved into it.
pub(crate) fn protection_covers(path: &str) -> bool {
    let path = super::super::locus::canonicalize(path);
    let fold_shields = current_os() == "macos";
    absolute_other_home(&path)
        || REGIONS
            .nodes
            .iter()
            .filter(|n| n.applies_here() && role_is_protective(&n.role))
            .any(|n| n.matcher.specificity(&path, n.fold && fold_shields).is_some())
}

/// Every declared region path at a fixed place that a protection node applying on this platform
/// covers: the witnesses for the root-above-a-protection property.
#[cfg(test)]
pub(crate) fn anchored_protected_paths_here() -> Vec<String> {
    super::declared_region_paths()
        .into_iter()
        .filter(|p| p.starts_with('/') || p.starts_with('~'))
        .filter(|p| {
            REGIONS
                .nodes
                .iter()
                .any(|n| n.applies_here() && role_is_protective(&n.role) && n.matcher.specificity(p, false).is_some())
        })
        .collect()
}

/// Whether `path` falls under any node of the region table, whatever its role, ignoring grants.
///
/// The unknown-folder classifier asks this of a relative path twice, once as written (a segment
/// node such as `.git` or `.ssh` bites at any depth) and once placed under `~`, so a node added to
/// the table later is a sensitive name without anyone extending a list.
pub(crate) fn names_a_region(path: &str) -> bool {
    let path = &super::super::locus::canonicalize(path);
    let fold = current_os() == "macos";
    secret_node(path).is_some()
        || REGIONS
            .nodes
            .iter()
            .any(|n| n.applies_here() && n.matcher.specificity(path, n.fold && fold).is_some())
}

/// A node under `~`, for the unknown-folder classifier, which has a relative path and no folder to
/// put it in: its segments, whether it pins one file, and whether it shields a secret.
pub(crate) struct HomeNode {
    pub segments: Vec<String>,
    pub exact: bool,
    pub secret: bool,
}

/// Every node under `~`. A relative path that starts with the end of one (`LaunchAgents/x` for
/// `~/Library/LaunchAgents/`, `git/config` for `~/.config/git/`) can be that place whichever folder
/// under home the command runs in, and an exact node's file name (`credentials` from
/// `~/.cargo/credentials`) can be that file.
pub(crate) fn home_nodes() -> &'static [HomeNode] {
    static NODES: LazyLock<Vec<HomeNode>> = LazyLock::new(|| {
        REGIONS
            .nodes
            .iter()
            .filter_map(|n| match &n.matcher {
                Matcher::Exact(p) => p.strip_prefix("~/").map(|p| (p, true, n.role.reads_secret)),
                Matcher::Prefix(p) => p.strip_prefix("~/").map(|p| (p, false, n.role.reads_secret)),
                _ => None,
            })
            .map(|(p, exact, secret)| HomeNode {
                segments: p.split('/').filter(|s| !s.is_empty()).map(str::to_string).collect(),
                exact,
                secret,
            })
            .filter(|n| !n.segments.is_empty())
            .collect()
    });
    &NODES
}

/// Whether `path` falls under a node that shields a secret (`.ssh`, `~/.aws/`).
/// Whether a bare name or spelling falls under a node that shields a secret: for a name no path
/// stands behind (a reported folder, an anchor's relative name). A path that was placed goes to
/// `classify_region`, which asks the same of both its readings.
pub(crate) fn names_a_secret_text(path: &str) -> bool {
    secret_node(&super::super::locus::canonicalize(path)).is_some()
}

#[cfg(test)]
mod names_tests {
    use super::*;

    #[test]
    fn segment_nodes_name_a_relative_path_and_home_nodes_a_home_one() {
        for named in
            [".git/hooks/pre-commit", "a/.ssh/id_rsa", ".envrc", "~/.ssh/config", "~/.config", "~/Library/LaunchAgents/x.plist", "~/bin/ls"]
        {
            assert!(names_a_region(named), "{named}");
        }
        for unnamed in ["src/main.rs", "notes.md", "~/notes.md", "~/projects/app/src/x.rs", "bin/ls"] {
            assert!(!names_a_region(unnamed), "{unnamed}");
        }
    }

    #[test]
    fn home_nodes_carry_their_segments_and_whether_they_shield_a_secret() {
        let find = |p: &[&str]| home_nodes().iter().find(|n| n.segments.iter().map(String::as_str).eq(p.iter().copied()));
        let creds = find(&[".cargo", "credentials"]).expect("~/.cargo/credentials");
        assert!(creds.exact && creds.secret);
        let agents = find(&["Library", "LaunchAgents"]).expect("~/Library/LaunchAgents/");
        assert!(!agents.exact && !agents.secret);
        assert!(home_nodes().iter().all(|n| !n.segments.is_empty() && n.segments.iter().all(|s| !s.is_empty())));
    }
}

#[cfg(test)]
mod tests {
    use super::super::with_os;
    use super::*;

    fn role(read: LocalLocus, write: LocalLocus, reads_secret: bool, frozen: Frozen) -> Role {
        Role { read_locus: read, write_locus: write, rebind_locus: write, reads_secret, frozen }
    }

    #[test]
    fn each_stricter_face_alone_makes_a_role_protective() {
        let w = LocalLocus::Worktree;
        assert!(!role_is_protective(&role(w, w, false, Frozen::Nothing)), "the worktree itself");
        assert!(!role_is_protective(&role(LocalLocus::WorktreeTrusted, w, false, Frozen::Nothing)), "a trusted read at the bound");
        assert!(role_is_protective(&role(w, w, true, Frozen::Nothing)), "a secret alone");
        assert!(role_is_protective(&role(w, w, false, Frozen::Rebind)), "a freeze alone");
        assert!(role_is_protective(&role(w, LocalLocus::WorktreeTrusted, false, Frozen::Nothing)), "a write past the worktree alone");
        assert!(role_is_protective(&role(LocalLocus::Machine, w, false, Frozen::Nothing)), "a read past the trusted rung alone");
    }

    #[test]
    fn a_root_holding_only_admitted_places_still_resolves_relative() {
        assert!(!keeps_absolute("/tmp/x", "/tmp"), "the scratch node admits, it does not protect");
    }

    #[test]
    fn a_glob_node_is_anchored_at_its_literal_directory() {
        assert!(keeps_absolute("/proc/1/environ", "/proc"));
        assert!(keeps_absolute("/proc", "/proc"), "the root itself is above the protected place");
    }

    #[test]
    fn protection_covers_only_protections_and_folds_case_only_on_macos() {
        assert!(!protection_covers("/tmp/x"), "an admit node is not a protection");
        assert!(!protection_covers("/srv/app/src"));
        assert!(protection_covers("/srv/app/.ssh/id_rsa"));
        assert!(with_os("macos", || protection_covers("/srv/app/.SSH/id_rsa")), "one file on a case-insensitive volume");
        assert!(!with_os("linux", || protection_covers("/srv/app/.SSH/id_rsa")), "a different directory on Linux");
    }
}