Skip to main content

safe_chains/pathctx/
folder.rs

1//! The unknown-folder mode of one evaluation: which folder level is in force, where each relative
2//! path is placed, and which command leaves wrote without naming a path
3//! (docs/design/unknown-folder-writes.md).
4//!
5//! Engaged only when a harness does not say which folder the command runs in, and the command
6//! is classified at `targets::UNKNOWN_WORKDIR`. At `reads` nothing here changes a verdict. Above it:
7//!
8//! - a relative path is placed in the workspace when its anchor value and use are ones the level
9//!   approves (`anchor::placement`), and left in the unknown folder otherwise, where no write lands
10//!   inside anything;
11//! - a command leaf whose verdict is a write is approved only when that write is accounted for: it
12//!   wrote a path it named (and that path was placed or refused on its own), it declares what it
13//!   writes in its folder (`writes_cwd`, `executor = "project"`), or a command nested in it was
14//!   accounted for. Anything else is refused, so a writer nobody has labelled fails closed.
15
16use std::cell::{Cell, RefCell};
17
18use super::anchor::{self, Anchor, FolderLevel, Use};
19use crate::parse::Token;
20use crate::verdict::{SafetyLevel, Verdict};
21
22/// What the mode decided about one path or one command, for `--explain`.
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub enum Note {
25    Path { path: String, anchor: Anchor, use_: Use, placed: bool },
26    Leaf { command: String, anchor: Option<Anchor>, admitted: bool },
27}
28
29#[derive(Default)]
30struct Frame {
31    named_write: bool,
32    nested_accounted: bool,
33    declared: Option<Anchor>,
34}
35
36thread_local! {
37    static LEVEL: Cell<Option<FolderLevel>> = const { Cell::new(None) };
38    static FRAMES: RefCell<Vec<Frame>> = const { RefCell::new(Vec::new()) };
39    static NOTES: RefCell<Vec<Note>> = const { RefCell::new(Vec::new()) };
40}
41
42/// Put `level` in force for the guard's lifetime and start a fresh record. Restored on drop.
43#[must_use]
44pub fn enter(level: FolderLevel) -> Guard {
45    NOTES.with(|n| n.borrow_mut().clear());
46    Guard(LEVEL.with(|l| l.replace(Some(level))))
47}
48
49pub struct Guard(Option<FolderLevel>);
50
51impl Drop for Guard {
52    fn drop(&mut self) {
53        LEVEL.with(|l| l.set(self.0));
54    }
55}
56
57/// The folder level in force, or `None` outside the mode.
58pub fn level() -> Option<FolderLevel> {
59    LEVEL.with(Cell::get)
60}
61
62/// Whether writes are being judged at all: a level above `reads` is in force.
63pub fn judges_writes() -> bool {
64    level().is_some_and(|l| l > FolderLevel::Reads)
65}
66
67/// What this evaluation decided, in order, for `--explain`.
68pub fn notes() -> Vec<Note> {
69    NOTES.with(|n| n.borrow().clone())
70}
71
72/// Whether `cwd` is the unknown folder or a directory below it (`cd sub` from there).
73pub fn is_unknown(cwd: &str) -> bool {
74    let base = crate::targets::UNKNOWN_WORKDIR;
75    cwd.strip_prefix(base).is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
76}
77
78/// The workspace-relative path to classify `path` as, when it is relative to an unknown `cwd` and
79/// the level places it; `None` leaves it in the unknown folder.
80///
81/// A path that climbs out of the folder, or cannot be read, is placed NOWHERE at every level, even
82/// for a read: joined onto the unknown folder it would name an ordinary directory, while the real
83/// parent of an unknown folder can be anything, another user's home included.
84fn has_workspace() -> bool {
85    matches!(super::root(), super::Root::Known(root) if !root.is_empty())
86}
87
88pub(super) fn place(cwd: &str, path: &str, stated: Option<Use>) -> Option<String> {
89    let use_ = stated.unwrap_or(Use::Read);
90    let level = level()?;
91    if path.starts_with('/') || path.starts_with('~') || !is_unknown(cwd) {
92        return None;
93    }
94    if !use_.mutates() && super::reported_is_secret() {
95        return Some(NOWHERE.to_string());
96    }
97    let below = cwd[crate::targets::UNKNOWN_WORKDIR.len()..].trim_start_matches('/');
98    let relative = if below.is_empty() { path.to_string() } else { format!("{below}/{path}") };
99    let anchor = anchor::of_path(&relative);
100    let placed = anchor::placement(&relative, use_, level)
101        .filter(|p| !use_.mutates() || (has_workspace() && (p != "." || declares_writes_in_its_folder()) && !items_in_scope()));
102    if level > FolderLevel::Reads && stated.is_some_and(Use::mutates) {
103        record(Note::Path { path: relative.clone(), anchor, use_, placed: placed.is_some() });
104    }
105    match placed {
106        None if anchor == Anchor::RelativeUnplaced || use_ == Use::Read => Some(NOWHERE.to_string()),
107        other => other,
108    }
109}
110
111/// Whether the command leaf being judged says what it writes in its folder (`writes_cwd` source or
112/// output). Only such a tool may write to the folder ITSELF (`gofmt -w .`): a copy or a sync into
113/// `.` writes names it brings with it (`cp /tmp/.zshrc .`), and the folder could be `~`.
114fn declares_writes_in_its_folder() -> bool {
115    FRAMES.with(|f| {
116        f.borrow()
117            .last()
118            .and_then(|t| t.declared)
119            .is_some_and(|a| matches!(a, Anchor::ImplicitSource | Anchor::ImplicitOutput))
120    })
121}
122
123/// Whether a write may be naming an item that arrives at run time: an `xargs` item on stdin, or a
124/// loop variable (`while read f`, `for f in …`). The classifier sees a stand-in for it, an ordinary
125/// name, while the real item can be `.zshrc` (`ls -A | xargs -I{} sh -c 'echo x >> {}'`).
126fn items_in_scope() -> bool {
127    super::stdin_item_repr().is_some() || super::vars::any_loop()
128}
129
130/// The command leaf being judged wrote to a path it named.
131pub(super) fn note_named_write() {
132    FRAMES.with(|f| {
133        if let Some(top) = f.borrow_mut().last_mut() {
134            top.named_write = true;
135        }
136    });
137}
138
139/// A leaf classifier that judges each leaf it classifies, for a caller that hands one on.
140pub(crate) fn judging(with_env: bool, classify: fn(&[Token]) -> Verdict) -> impl Fn(&[Token]) -> Verdict {
141    move |tokens| judge_leaf(tokens, with_env, || classify(tokens))
142}
143
144/// Judge one command leaf: run `classify`, and when its verdict is a write made in the unknown
145/// folder that nothing accounts for, refuse it.
146pub(crate) fn judge_leaf(tokens: &[Token], with_env: bool, classify: impl FnOnce() -> Verdict) -> Verdict {
147    // A relative path is classified as `bash` of that path. Account for it as that command, so the
148    // shell's `writes_cwd = "code"` covers the project's own script. The classifier rewrites too.
149    let rewritten = crate::handlers::direct_script::as_interpreter(tokens);
150    let tokens = rewritten.as_ref();
151    let declared = crate::registry::cwd_writes(tokens);
152    let frame = FrameGuard::push(declared);
153    let verdict = classify();
154    let frame = frame.pop();
155    let verdict = if verdict.is_allowed() { verdict.combine(folder_code_verdict(declared)) } else { verdict };
156    let writes = matches!(verdict, Verdict::Allowed(l) if l > SafetyLevel::SafeRead);
157    if !writes {
158        return verdict;
159    }
160    let here_unknown = super::cwd().is_some_and(|c| is_unknown(&c));
161    let Some(level) = level().filter(|l| *l > FolderLevel::Reads && here_unknown) else {
162        let verdict = verdict.combine(cwd_write_verdict(declared, frame.named_write));
163        if verdict.is_allowed() {
164            mark_parent_accounted();
165        }
166        return verdict;
167    };
168    let names_its_writes = declared == Some(Anchor::NamesItsWrites) && frame.named_write;
169    let implicit = !with_env && has_workspace() && declared.is_some_and(|a| level.admits_implicit(a));
170    let accounted = implicit || names_its_writes || frame.nested_accounted;
171    let command = tokens.iter().take(4).map(Token::as_str).collect::<Vec<_>>().join(" ");
172    record(Note::Leaf { command, anchor: declared, admitted: accounted });
173    if accounted {
174        mark_parent_accounted();
175        verdict
176    } else {
177        Verdict::Denied
178    }
179}
180
181/// The verdict for the write a leaf makes in the folder it runs in without naming a path (`cargo
182/// fmt`, `git commit`, `mise set`): that folder judged as a write target, so a `cd` earlier on the
183/// line moves the write with it, exactly as it moves a relative operand. A leaf that declares a
184/// fixed target (`writes_cwd = "none"`), or that named what it wrote and declares no folder write,
185/// writes nothing here. The folder the harness reported is the session's own when it lies in the
186/// project root, and is not judged, nor is an unknown one (the unknown-folder mode's), nor a missing
187/// one, as for a relative path.
188fn cwd_write_verdict(declared: Option<Anchor>, named_write: bool) -> Verdict {
189    let in_folder = matches!(declared, Some(Anchor::ImplicitOutput | Anchor::ImplicitSource | Anchor::RunsFolderCode));
190    let judged = super::cwd().is_some_and(|cwd| !is_unknown(&cwd) && (super::moved_by_cd() || !within_root(&cwd)));
191    if declared == Some(Anchor::Free) || (named_write && !in_folder) || !judged {
192        return Verdict::Allowed(SafetyLevel::Inert);
193    }
194    let frame = FrameGuard::push(None);
195    let verdict = crate::engine::resolve::write_target_verdict(".");
196    frame.pop();
197    verdict
198}
199
200/// The verdict for the code a leaf runs from the folder it runs in (`cargo run`, a `rake` task) or
201/// builds there (`cargo build` runs build scripts): once a `cd` has moved the line, that folder is
202/// judged as the place code is loaded from, so a temporary folder asks as `/tmp/x.py` would, though
203/// writing there would be approved.
204fn folder_code_verdict(declared: Option<Anchor>) -> Verdict {
205    let runs = matches!(declared, Some(Anchor::ImplicitOutput | Anchor::RunsFolderCode));
206    if !runs {
207        return Verdict::Allowed(SafetyLevel::Inert);
208    }
209    if super::cwd().is_none_or(|cwd| is_unknown(&cwd)) {
210        return match super::root() {
211            super::Root::Known(_) => Verdict::Allowed(SafetyLevel::Inert),
212            super::Root::Unknown => Verdict::Denied,
213        };
214    }
215    if crate::engine::resolve::frozen_reach::is_unreviewed_folder(".") {
216        return Verdict::Denied;
217    }
218    if !super::moved_by_cd() && has_workspace() {
219        return Verdict::Allowed(SafetyLevel::Inert);
220    }
221    let frame = FrameGuard::push(None);
222    let trusted = crate::engine::resolve::execute_file_verdict(".").is_allowed();
223    frame.pop();
224    if trusted { Verdict::Allowed(SafetyLevel::Inert) } else { Verdict::Denied }
225}
226
227fn within_root(cwd: &str) -> bool {
228    match super::root() {
229        super::Root::Known(root) if !root.is_empty() => {
230            let root = root.trim_end_matches('/');
231            cwd.trim_end_matches('/') == root || cwd.starts_with(&format!("{root}/"))
232        }
233        super::Root::Known(_) | super::Root::Unknown => false,
234    }
235}
236
237fn mark_parent_accounted() {
238    FRAMES.with(|f| {
239        if let Some(top) = f.borrow_mut().last_mut() {
240            top.nested_accounted = true;
241        }
242    });
243}
244
245fn record(note: Note) {
246    NOTES.with(|n| {
247        let mut notes = n.borrow_mut();
248        if notes.len() < MAX_NOTES && !notes.contains(&note) {
249            notes.push(note);
250        }
251    });
252}
253
254/// What a path placed nowhere is classified as: a component the locus guard treats as unpinnable,
255/// so a read of it is one the shield cannot clear and a write of it lands nowhere approvable.
256const NOWHERE: &str = "__SAFE_CHAINS_CMDSUB__/outside-an-unknown-folder";
257
258/// A long chain still explains its first writes; past this the record stops growing.
259const MAX_NOTES: usize = 64;
260
261/// Pops its frame even when the classification inside unwinds, so a later evaluation on the thread
262/// does not inherit it.
263struct FrameGuard(bool);
264
265impl FrameGuard {
266    fn push(declared: Option<Anchor>) -> FrameGuard {
267        FRAMES.with(|f| f.borrow_mut().push(Frame { declared, ..Frame::default() }));
268        FrameGuard(true)
269    }
270
271    fn pop(mut self) -> Frame {
272        self.0 = false;
273        FRAMES.with(|f| f.borrow_mut().pop()).unwrap_or_default()
274    }
275}
276
277impl Drop for FrameGuard {
278    fn drop(&mut self) {
279        if self.0 {
280            FRAMES.with(|f| f.borrow_mut().pop());
281        }
282    }
283}
284
285#[cfg(test)]
286#[path = "folder_tests.rs"]
287mod tests;
288
289#[cfg(test)]
290#[path = "folder_soundness_tests.rs"]
291mod soundness;