Skip to main content

safe_chains/pathctx/
anchor.rs

1//! How much a write depends on the folder it runs in, for a harness that does not say which folder
2//! that is (docs/design/unknown-folder-writes.md §4–§6).
3//!
4//! Pure: a path and a level in, an answer out. The ambient state (which level is in force, what a
5//! command wrote) lives in `folder`.
6
7/// How much one write depends on the folder the command runs in.
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum Anchor {
10    /// The target is pinned without the folder: absolute, `~`, a stream; or, declared on a command
11    /// (`writes_cwd = "none"`), whatever it writes is somewhere fixed (`pkill`, `rustup target add`).
12    Free,
13    /// A relative path that stays below the folder and names nothing sensitive.
14    RelativePlain,
15    /// A relative path whose name means something wherever it lands: a hidden segment, a git hook,
16    /// a credential file name, a region the table names under the workspace or under `~`.
17    RelativeSensitive,
18    /// A relative path that climbs out of the folder, or whose spelling cannot be read (`$VAR`, a
19    /// glob, a substitution).
20    RelativeUnplaced,
21    /// The tool writes, without naming a path, only into a subtree of the folder it owns and
22    /// regenerates (`cargo build` → `target/`).
23    ImplicitOutput,
24    /// The tool rewrites existing files of its own kind of project in the folder (`cargo fmt`,
25    /// `git commit -am x`).
26    ImplicitSource,
27    /// The command runs code the folder holds (`cargo run`, `swift build`).
28    RunsFolderCode,
29    /// Declared on a command (`writes_cwd = "named"`): it writes only the paths it names, each
30    /// judged by its own anchor value (`touch`, `tee`, `sed -i`). Not a decompressor, whose output
31    /// name is derived from its input, nor a sync that brings the source's names.
32    NamesItsWrites,
33}
34
35impl Anchor {
36    pub const ALL: [Anchor; 8] = [
37        Anchor::Free,
38        Anchor::RelativePlain,
39        Anchor::RelativeSensitive,
40        Anchor::RelativeUnplaced,
41        Anchor::ImplicitOutput,
42        Anchor::ImplicitSource,
43        Anchor::RunsFolderCode,
44        Anchor::NamesItsWrites,
45    ];
46
47    pub fn name(self) -> &'static str {
48        match self {
49            Anchor::Free => "anchor-free",
50            Anchor::RelativePlain => "relative-plain",
51            Anchor::RelativeSensitive => "relative-sensitive",
52            Anchor::RelativeUnplaced => "relative-unplaced",
53            Anchor::ImplicitOutput => "implicit-output",
54            Anchor::ImplicitSource => "implicit-source",
55            Anchor::RunsFolderCode => "runs-folder-code",
56            Anchor::NamesItsWrites => "names-its-writes",
57        }
58    }
59}
60
61/// How far writes are approved when the folder is unknown. A second dial beside `--level`: a
62/// command passes when it passes both, and this one never loosens what `--level` refuses.
63#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
64pub enum FolderLevel {
65    /// Reads only; every write goes to the harness's prompt.
66    Reads,
67    /// What a developer approves in a known project, except deletion and paths that climb out.
68    Developer,
69    /// The folder is treated as the workspace: deletion and `../sibling` paths too.
70    Workspace,
71}
72
73impl FolderLevel {
74    pub const DEFAULT: FolderLevel = FolderLevel::Developer;
75    pub const NAMES: [&'static str; 3] = ["reads", "developer", "workspace"];
76
77    pub fn parse(name: &str) -> Option<FolderLevel> {
78        match name {
79            "reads" => Some(FolderLevel::Reads),
80            "developer" => Some(FolderLevel::Developer),
81            "workspace" => Some(FolderLevel::Workspace),
82            _ => None,
83        }
84    }
85
86    pub fn name(self) -> &'static str {
87        match self {
88            FolderLevel::Reads => "reads",
89            FolderLevel::Developer => "developer",
90            FolderLevel::Workspace => "workspace",
91        }
92    }
93
94    /// Whether a write the command makes without naming a path is approved at this level.
95    pub fn admits_implicit(self, anchor: Anchor) -> bool {
96        self >= FolderLevel::Developer
97            && matches!(anchor, Anchor::Free | Anchor::ImplicitOutput | Anchor::ImplicitSource | Anchor::RunsFolderCode)
98    }
99}
100
101/// What a resolved path is used for, which is also the face of a region role it reads.
102#[derive(Clone, Copy, Debug, PartialEq, Eq)]
103pub enum Use {
104    Read,
105    Write,
106    /// Changes what the NAME refers to, rather than the bytes underneath it: `rm` unbinds it, `ln`
107    /// points it elsewhere, `mv` takes it away. Identical to `Write` for almost every path; the two
108    /// diverge where a role says a directory may be written INTO but not replaced, and in an
109    /// unknown folder, where it is the deletion the `developer` level leaves to the prompt.
110    Rebind,
111}
112
113impl Use {
114    /// Whether this use changes state, which is what `expand_vars` needs to pick a loop variable's
115    /// representative item. A rebind is a write for that purpose.
116    pub(crate) fn mutates(self) -> bool {
117        self != Use::Read
118    }
119}
120
121/// The anchor value of `path` as written, relative to the folder the command runs in.
122pub fn of_path(path: &str) -> Anchor {
123    if path.starts_with('/') || path.starts_with('~') {
124        return Anchor::Free;
125    }
126    match normalize(path) {
127        Some(segments) if !is_sensitive(&segments) => Anchor::RelativePlain,
128        Some(_) => Anchor::RelativeSensitive,
129        None => Anchor::RelativeUnplaced,
130    }
131}
132
133/// Where `path`, relative to the unknown folder, is classified for `use_` at `level`: a path
134/// relative to the workspace root, which the ordinary classifier then judges, or `None` to leave it
135/// in the unknown folder, where no write lands inside anything.
136///
137/// A read of a relative path is placed at every level, `reads` included: if the agent runs it in
138/// `~`, reading there is the user's choice (the owner, 2026-10-08). A sensitive name, a climb out of
139/// the folder, and a glob anywhere but the last segment are still not placed. `developer` places a
140/// plain path for a write, never a rebind. `workspace` also places a rebind (but not of the folder
141/// itself) and a path that climbs exactly one level into a sibling.
142pub fn placement(path: &str, use_: Use, level: FolderLevel) -> Option<String> {
143    if path.starts_with('/') || path.starts_with('~') {
144        return None;
145    }
146    if use_ == Use::Read {
147        return read_placement(path);
148    }
149    if level == FolderLevel::Reads {
150        return None;
151    }
152    if let Some(segments) = normalize(path) {
153        if is_sensitive(&segments) {
154            return None;
155        }
156        let rebinds_the_folder = segments.is_empty();
157        let allowed = use_ == Use::Write || (level == FolderLevel::Workspace && !rebinds_the_folder);
158        return allowed.then(|| if segments.is_empty() { ".".to_string() } else { segments.join("/") });
159    }
160    if level < FolderLevel::Workspace {
161        return None;
162    }
163    let rest = sibling_hop(path)?;
164    if rest.len() < 2 && use_ == Use::Rebind {
165        return None;
166    }
167    Some(format!("../{}", rest.join("/")))
168}
169
170/// A read's placement. A glob is allowed in the last segment only (`tests/*.rs`): there it names
171/// files in one directory it shows, and a shell glob never matches a leading dot. One that could
172/// match a sensitive file name (`id_*`, `hooks/pre-*`) is not placed.
173fn read_placement(path: &str) -> Option<String> {
174    let (dir, last) = path.rsplit_once('/').unwrap_or(("", path));
175    let globbed = last.contains(['*', '?', '[']);
176    let literal = if globbed { dir } else { path };
177    let mut segments = if literal.is_empty() { Vec::new() } else { normalize(literal)? };
178    if read_is_secret(&segments) {
179        return None;
180    }
181    if globbed {
182        let pattern = last.replace('[', "?");
183        if last.starts_with('.') || unreadable(&last.replace(['*', '?', '[', ']'], "")) || last.contains("..") {
184            return None;
185        }
186        if KEY_FILES.iter().copied().chain(pinned_names(true)).any(|name| glob_matches(&pattern, name)) {
187            return None;
188        }
189        segments.push(last);
190    }
191    Some(if segments.is_empty() { ".".to_string() } else { segments.join("/") })
192}
193
194/// Whether `pattern` (`*` any run, `?` one character, case-folded) matches `name` in full.
195fn glob_matches(pattern: &str, name: &str) -> bool {
196    let (p, n): (Vec<char>, Vec<char>) = (pattern.to_ascii_lowercase().chars().collect(), name.to_ascii_lowercase().chars().collect());
197    let (mut pi, mut ni, mut star, mut mark) = (0, 0, None, 0);
198    while ni < n.len() {
199        if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) {
200            pi += 1;
201            ni += 1;
202        } else if pi < p.len() && p[pi] == '*' {
203            star = Some(pi);
204            mark = ni;
205            pi += 1;
206        } else if let Some(s) = star {
207            pi = s + 1;
208            mark += 1;
209            ni = mark;
210        } else {
211            return false;
212        }
213    }
214    p[pi..].iter().all(|c| *c == '*')
215}
216
217/// The segments of `path` once `.` and empty segments are dropped and `..` folded, or `None` when
218/// it climbs above the folder or cannot be read off the command line.
219fn normalize(path: &str) -> Option<Vec<&str>> {
220    if path.is_empty() || unreadable(path) {
221        return None;
222    }
223    let mut out = Vec::new();
224    for segment in path.split('/') {
225        match segment {
226            "" | "." => {}
227            ".." => {
228                out.pop()?;
229            }
230            s => out.push(s),
231        }
232    }
233    Some(out)
234}
235
236/// `../name/…` that climbs exactly one level and then stays down: the segments below the parent.
237/// A sibling is a plain, non-sensitive name; the folder's own name is unknown, so `../same` is as
238/// much a sibling as anything else.
239fn sibling_hop(path: &str) -> Option<Vec<&str>> {
240    if unreadable(path) {
241        return None;
242    }
243    let rest = path.trim_start_matches("./").strip_prefix("../")?;
244    let segments = normalize(rest)?;
245    (!segments.is_empty() && !is_sensitive(&segments)).then_some(segments)
246}
247
248fn unreadable(path: &str) -> bool {
249    path.contains(['$', '*', '?', '[', '{', '}', '`', '\\']) || path.contains("__SAFE_CHAINS_") || path.contains("://")
250}
251
252/// Whether the segments name something sensitive under any folder: a hidden segment anywhere, a git
253/// hook, a credential file name, or a region the table names as written or placed under `~`.
254fn is_sensitive(segments: &[&str]) -> bool {
255    if segments.is_empty() {
256        return false;
257    }
258    if segments.iter().any(|s| s.starts_with('.')) {
259        return true;
260    }
261    let same = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
262    if segments.windows(2).any(|w| same(w[0], "hooks") && GIT_HOOKS.iter().any(|h| same(h, w[1]))) {
263        return true;
264    }
265    let last = segments[segments.len() - 1];
266    if NAMED_FILES.iter().any(|n| same(n, last))
267        || pinned_names(false).any(|n| same(n, last))
268        || starts_with_the_end_of_a_home_node(segments, false)
269    {
270        return true;
271    }
272    let joined = segments.join("/");
273    use crate::engine::resolve::regions::names_a_region;
274    names_a_region(&joined) || names_a_region(&format!("~/{joined}"))
275}
276
277/// Whether a READ of the segments could be a secret under any folder: a node of the credential
278/// shield as written or under `~`, the end of one (`Keychains/login.keychain-db` from
279/// `~/Library`), a key file (`id_rsa`) or a file a shield node pins (`credentials`). Reads of other
280/// sensitive names (`.gitignore`, `.github/`) are ordinary, so only these stay refused.
281pub fn read_is_secret(segments: &[&str]) -> bool {
282    use crate::engine::resolve::regions::names_a_secret;
283    let same = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
284    let Some(last) = segments.last() else { return false };
285    let joined = segments.join("/");
286    KEY_FILES.iter().any(|n| same(n, last))
287        || pinned_names(true).any(|n| same(n, last))
288        || starts_with_the_end_of_a_home_node(segments, true)
289        || names_a_secret(&joined)
290        || names_a_secret(&format!("~/{joined}"))
291}
292
293/// Private keys, by OpenSSH's default names (ssh(1) FILES).
294const KEY_FILES: &[&str] = &["id_rsa", "id_dsa", "id_ecdsa", "id_ecdsa_sk", "id_ed25519", "id_ed25519_sk"];
295
296/// The file names exact home nodes pin (`credentials` from `~/.cargo/credentials`), hidden ones left
297/// out because a hidden segment is sensitive on its own.
298fn pinned_names(secret_only: bool) -> impl Iterator<Item = &'static str> {
299    crate::engine::resolve::regions::home_nodes()
300        .iter()
301        .filter(move |n| n.exact && (n.secret || !secret_only))
302        .filter_map(|n| n.segments.last().map(String::as_str))
303        .filter(|name| !name.starts_with('.'))
304}
305
306/// Whether the segments start with the end of a home node, so they can be that place whichever
307/// folder under `~` the command runs in.
308fn starts_with_the_end_of_a_home_node(segments: &[&str], secret_only: bool) -> bool {
309    let same = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
310    crate::engine::resolve::regions::home_nodes()
311        .iter()
312        .filter(|n| n.secret || !secret_only)
313        .any(|node| {
314            let node = &node.segments;
315            (1..node.len()).any(|k| node[k..].len() <= segments.len() && node[k..].iter().zip(segments).all(|(a, b)| same(a, b)))
316        })
317}
318
319/// Files whose name means the same thing in whichever folder they sit, beyond what the region table
320/// pins: OpenSSH's per-user files (ssh(1) and sshd(8) FILES, OpenSSH 10.2, researched 2026-10-08)
321/// other than `config`, GnuPG's (gpg(1) FILES, 2.4), fish's startup file, and the hook and
322/// permission files Claude Code and Codex read from their own folders (`hooks.json`,
323/// `settings.local.json`, Codex's `rules/default.rules`). `config` and `config.toml` are left out on
324/// purpose: they are the accepted risk §6 names, since names that common cannot be refused
325/// everywhere.
326pub const NAMED_FILES: &[&str] = &[
327    "authorized_keys", "authorized_keys2", "known_hosts", "id_rsa", "id_dsa", "id_ecdsa", "id_ecdsa_sk", "id_ed25519", "id_ed25519_sk",
328    "rc", "environment", "gpg.conf", "gpg-agent.conf", "dirmngr.conf", "pubring.kbx", "trustdb.gpg", "config.fish", "hooks.json",
329    "settings.local.json", "default.rules",
330];
331
332/// githooks(5) as of Git 2.51 (researched 2026-10-08). Matched only below a `hooks` segment, so the
333/// command runs in `.git` and writes `hooks/pre-commit`.
334pub const GIT_HOOKS: &[&str] = &[
335    "applypatch-msg", "pre-applypatch", "post-applypatch", "pre-commit", "pre-merge-commit", "prepare-commit-msg", "commit-msg",
336    "post-commit", "pre-rebase", "post-checkout", "post-merge", "pre-push", "pre-receive", "update", "proc-receive", "post-receive",
337    "post-update", "reference-transaction", "push-to-checkout", "pre-auto-gc", "post-rewrite", "sendemail-validate", "fsmonitor-watchman",
338    "p4-changelist", "p4-prepare-changelist", "p4-post-changelist", "p4-pre-submit", "post-index-change",
339];
340
341#[cfg(test)]
342#[path = "anchor_tests.rs"]
343mod tests;