Skip to main content
← rust.krizaka.comkrizaka.com

krizaka_rust/
scope.rs

1//! The folder scope — the heart of the app's least-privilege file access.
2//!
3//! The app can read a path **only** when it lies inside a folder the user granted with the native
4//! picker. Grants are persisted (a JSON file in the app's data directory), listed in the UI and
5//! revocable. Every path is canonicalised before it is compared, so `..` segments and symlinks that
6//! leave a granted folder are refused; broad or sensitive locations can never be granted.
7
8use serde::{Deserialize, Serialize};
9use std::fs;
10use std::io;
11use std::path::{Path, PathBuf};
12
13#[derive(Debug, PartialEq, Eq)]
14pub enum ScopeError {
15    /// The folder is too broad or too sensitive to be granted (home, `/`, `~/.ssh`, `/System`…).
16    Forbidden(String),
17    /// The path does not exist or is not a directory / file as expected.
18    NotFound(String),
19    /// The path is outside every granted folder.
20    OutsideScope(String),
21    Io(String),
22}
23
24impl ScopeError {
25    /// The stable code the page reads.
26    pub fn code(&self) -> &'static str {
27        match self {
28            ScopeError::Forbidden(_) => "scope_forbidden",
29            ScopeError::NotFound(_) => "scope_not_found",
30            ScopeError::OutsideScope(_) => "scope_outside",
31            ScopeError::Io(_) => "scope_io",
32        }
33    }
34}
35
36impl std::fmt::Display for ScopeError {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        match self {
39            ScopeError::Forbidden(p) => write!(f, "forbidden: {p}"),
40            ScopeError::NotFound(p) => write!(f, "not found: {p}"),
41            ScopeError::OutsideScope(p) => write!(f, "outside the granted folders: {p}"),
42            ScopeError::Io(e) => write!(f, "io: {e}"),
43        }
44    }
45}
46
47impl std::error::Error for ScopeError {}
48
49/// A path the scope let through: canonical, inside a granted folder (or a file dropped this session), not sensitive.
50///
51/// Only [`ScopeStore::resolve`] and [`crate::access::Access::resolve`] make one, so a function that takes a `ScopedPath`
52/// can never be handed a path the scope did not see. A read goes through [`ScopedPath::open`], which confirms that the
53/// opened file is still this one.
54///
55/// ```
56/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
57/// use krizaka_rust::scope::ScopeStore;
58/// let dir = tempfile::tempdir()?;
59/// let home = dir.path().canonicalize()?;
60/// std::fs::create_dir(home.join("docs"))?;
61/// std::fs::write(home.join("docs/a.txt"), "hello")?;
62/// let mut scope = ScopeStore::default();
63/// scope.grant_with_home(&home.join("docs"), Some(&home))?;
64/// let file = scope.resolve_with_home(&home.join("docs/a.txt"), Some(&home))?;
65/// assert_eq!(krizaka_rust::files::preview(&file, &Default::default())?.text.as_deref(), Some("hello"));
66/// # Ok(())
67/// # }
68/// ```
69///
70/// It cannot be made from a bare path:
71///
72/// ```compile_fail
73/// let _ = krizaka_rust::scope::ScopedPath(std::path::PathBuf::from("/etc/hosts"));
74/// ```
75#[derive(Debug, Clone, PartialEq, Eq, Hash)]
76pub struct ScopedPath(PathBuf);
77
78impl ScopedPath {
79    /// `canon` has passed the scope's checks: only the scope's gates call this.
80    pub(crate) fn new(canon: PathBuf) -> Self {
81        ScopedPath(canon)
82    }
83
84    pub fn as_path(&self) -> &Path {
85        &self.0
86    }
87
88    pub fn into_path_buf(self) -> PathBuf {
89        self.0
90    }
91
92    /// Opens the file once, read only, and confirms the descriptor is the file the scope let through.
93    ///
94    /// The path may have changed since it was resolved: the file, or one of its parent folders, swapped for a link out
95    /// of the grant. The last component is opened without following a link, and the system is asked where the opened
96    /// file really is; anything but the resolved path is refused. Read the metadata and the content from the returned
97    /// file, never from the path again.
98    pub fn open(&self) -> Result<fs::File, ScopeError> {
99        let file = open_no_follow(&self.0).map_err(|e| match e.kind() {
100            io::ErrorKind::NotFound => ScopeError::NotFound(self.0.display().to_string()),
101            _ => ScopeError::Io(e.to_string()),
102        })?;
103        let opened = opened_path(&file).map_err(|e| ScopeError::Io(e.to_string()))?;
104        if opened != self.0 {
105            return Err(ScopeError::OutsideScope(self.0.display().to_string()));
106        }
107        Ok(file)
108    }
109}
110
111impl AsRef<Path> for ScopedPath {
112    fn as_ref(&self) -> &Path {
113        &self.0
114    }
115}
116
117/// Read only, the last component never followed if it is a link, never blocking on a pipe swapped in.
118#[cfg(unix)]
119fn open_no_follow(path: &Path) -> io::Result<fs::File> {
120    use rustix::fs::{Mode, OFlags};
121    let flags = OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC;
122    Ok(fs::File::from(rustix::fs::open(
123        path,
124        flags,
125        Mode::empty(),
126    )?))
127}
128
129#[cfg(not(unix))]
130fn open_no_follow(path: &Path) -> io::Result<fs::File> {
131    fs::File::open(path)
132}
133
134/// Where the system says the opened file is (`F_GETPATH`), whatever path was used to open it.
135#[cfg(target_os = "macos")]
136fn opened_path(file: &fs::File) -> io::Result<PathBuf> {
137    use std::os::unix::ffi::OsStringExt;
138    let path = rustix::fs::getpath(file)?;
139    Ok(PathBuf::from(std::ffi::OsString::from_vec(
140        path.into_bytes(),
141    )))
142}
143
144#[cfg(target_os = "linux")]
145fn opened_path(file: &fs::File) -> io::Result<PathBuf> {
146    use std::os::fd::AsRawFd;
147    fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd()))
148}
149
150/// Elsewhere the opened file cannot be located, so nothing is read.
151#[cfg(not(any(target_os = "macos", target_os = "linux")))]
152fn opened_path(_file: &fs::File) -> io::Result<PathBuf> {
153    Err(io::Error::new(
154        io::ErrorKind::Unsupported,
155        "the opened file cannot be located on this system",
156    ))
157}
158
159/// Directories (relative to the user's home) that can never be granted, nor read through a grant.
160const SENSITIVE_HOME_DIRS: &[&str] = &[
161    ".ssh",
162    ".gnupg",
163    ".aws",
164    ".kube",
165    ".docker",
166    ".config",
167    ".npmrc",
168    "Library",
169    ".claude",
170    ".cargo",
171    ".krizaka-worktrees",
172];
173
174/// System locations that can never be granted (they are broad, or hold other programs' data).
175const FORBIDDEN_ABSOLUTE: &[&str] = &[
176    "/",
177    "/System",
178    "/Library",
179    "/Users",
180    "/Volumes",
181    "/private",
182    "/etc",
183    "/usr",
184    "/bin",
185    "/sbin",
186    "/var",
187    "/opt",
188    "/Applications",
189    "/dev",
190    "/cores",
191    "/tmp",
192];
193
194#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
195pub struct ScopeStore {
196    roots: Vec<PathBuf>,
197}
198
199impl ScopeStore {
200    pub fn roots(&self) -> &[PathBuf] {
201        &self.roots
202    }
203
204    pub fn load(file: &Path) -> Self {
205        Self::load_with_home(file, home_dir().as_deref())
206    }
207
208    pub fn load_with_home(file: &Path, home: Option<&Path>) -> Self {
209        let Ok(raw) = fs::read_to_string(file) else {
210            return Self::default();
211        };
212        let mut store: ScopeStore = serde_json::from_str(&raw).unwrap_or_default();
213        // A folder that has vanished, or that became forbidden, silently drops out of the scope.
214        store
215            .roots
216            .retain(|r| r.is_dir() && check_grantable(r, home).is_ok());
217        store
218    }
219
220    /// Written atomically: a crash mid-write never loses the grants.
221    pub fn save(&self, file: &Path) -> Result<(), ScopeError> {
222        crate::settings::save(file, self).map_err(|e| ScopeError::Io(e.to_string()))
223    }
224
225    /// Grants a folder (idempotent). Returns the canonical path stored.
226    pub fn grant(&mut self, folder: &Path) -> Result<PathBuf, ScopeError> {
227        self.grant_with_home(folder, home_dir().as_deref())
228    }
229
230    pub fn grant_with_home(
231        &mut self,
232        folder: &Path,
233        home: Option<&Path>,
234    ) -> Result<PathBuf, ScopeError> {
235        let canon = folder
236            .canonicalize()
237            .map_err(|_| ScopeError::NotFound(folder.display().to_string()))?;
238        if !canon.is_dir() {
239            return Err(ScopeError::NotFound(canon.display().to_string()));
240        }
241        check_grantable(&canon, home)?;
242        // A child of an already granted folder adds nothing; a parent replaces its children.
243        if self.roots.iter().any(|r| canon.starts_with(r)) {
244            return Ok(canon);
245        }
246        self.roots.retain(|r| !r.starts_with(&canon));
247        self.roots.push(canon.clone());
248        self.roots.sort();
249        Ok(canon)
250    }
251
252    pub fn revoke(&mut self, folder: &Path) -> bool {
253        let before = self.roots.len();
254        self.roots.retain(|r| r != folder);
255        self.roots.len() != before
256    }
257
258    pub fn revoke_all(&mut self) {
259        self.roots.clear();
260    }
261
262    /// Resolves `path` to its canonical form **iff** it lies inside a granted folder and is not a
263    /// sensitive location. This is the one gate every read goes through.
264    pub fn resolve(&self, path: &Path) -> Result<ScopedPath, ScopeError> {
265        self.resolve_with_home(path, home_dir().as_deref())
266    }
267
268    pub fn resolve_with_home(
269        &self,
270        path: &Path,
271        home: Option<&Path>,
272    ) -> Result<ScopedPath, ScopeError> {
273        let canon = path
274            .canonicalize()
275            .map_err(|_| ScopeError::NotFound(path.display().to_string()))?;
276        if !self.roots.iter().any(|r| canon.starts_with(r)) {
277            return Err(ScopeError::OutsideScope(path.display().to_string()));
278        }
279        if is_sensitive(&canon, home) {
280            return Err(ScopeError::Forbidden(canon.display().to_string()));
281        }
282        Ok(ScopedPath::new(canon))
283    }
284}
285
286pub fn home_dir() -> Option<PathBuf> {
287    std::env::var_os("HOME")
288        .map(PathBuf::from)
289        .and_then(|p| p.canonicalize().ok())
290}
291
292fn is_sensitive(canon: &Path, home: Option<&Path>) -> bool {
293    if let Some(home) = home {
294        for d in SENSITIVE_HOME_DIRS {
295            if canon.starts_with(home.join(d)) {
296                return true;
297            }
298        }
299    }
300    false
301}
302
303fn check_grantable(canon: &Path, home: Option<&Path>) -> Result<(), ScopeError> {
304    let shown = canon.display().to_string();
305    for f in FORBIDDEN_ABSOLUTE {
306        // The folder itself, never what is under it (`/Users/me/Documents` is fine).
307        if canon == Path::new(f) {
308            return Err(ScopeError::Forbidden(shown));
309        }
310    }
311    // macOS volumes' roots and `/Users/<name>` — a whole home is too broad.
312    if let Some(home) = home {
313        if canon == home {
314            return Err(ScopeError::Forbidden(shown));
315        }
316        if is_sensitive(canon, Some(home)) {
317            return Err(ScopeError::Forbidden(shown));
318        }
319        // Also refuse a folder that *contains* the home (e.g. `/Users`).
320        if home.starts_with(canon) {
321            return Err(ScopeError::Forbidden(shown));
322        }
323    }
324    for f in [
325        "/System",
326        "/Library",
327        "/usr",
328        "/bin",
329        "/sbin",
330        "/etc",
331        "/private/etc",
332    ] {
333        if canon.starts_with(f) {
334            return Err(ScopeError::Forbidden(shown));
335        }
336    }
337    Ok(())
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343    use tempfile::tempdir;
344
345    fn fake_home() -> tempfile::TempDir {
346        let h = tempdir().unwrap();
347        fs::create_dir_all(h.path().join("Documents/clients")).unwrap();
348        fs::create_dir_all(h.path().join(".ssh")).unwrap();
349        fs::write(h.path().join(".ssh/id_ed25519"), "secret").unwrap();
350        fs::write(h.path().join("Documents/clients/a.pdf"), "%PDF").unwrap();
351        h
352    }
353
354    #[test]
355    fn grants_a_normal_folder_and_resolves_inside_it() {
356        let h = fake_home();
357        let home = h.path().canonicalize().unwrap();
358        let mut s = ScopeStore::default();
359        let root = s
360            .grant_with_home(&home.join("Documents"), Some(&home))
361            .unwrap();
362        assert!(s
363            .resolve_with_home(&root.join("clients/a.pdf"), Some(&home))
364            .is_ok());
365    }
366
367    #[test]
368    fn refuses_the_home_itself_root_and_sensitive_folders() {
369        let h = fake_home();
370        let home = h.path().canonicalize().unwrap();
371        let mut s = ScopeStore::default();
372        assert!(matches!(
373            s.grant_with_home(&home, Some(&home)),
374            Err(ScopeError::Forbidden(_))
375        ));
376        assert!(matches!(
377            s.grant_with_home(Path::new("/"), Some(&home)),
378            Err(ScopeError::Forbidden(_))
379        ));
380        assert!(matches!(
381            s.grant_with_home(&home.join(".ssh"), Some(&home)),
382            Err(ScopeError::Forbidden(_))
383        ));
384        assert!(matches!(
385            s.grant_with_home(Path::new("/System"), Some(&home)),
386            Err(ScopeError::Forbidden(_))
387        ));
388        assert!(s.roots().is_empty());
389    }
390
391    #[test]
392    fn refuses_a_parent_of_home() {
393        let h = fake_home();
394        let home = h.path().canonicalize().unwrap();
395        let parent = home.parent().unwrap().to_path_buf();
396        let mut s = ScopeStore::default();
397        assert!(matches!(
398            s.grant_with_home(&parent, Some(&home)),
399            Err(ScopeError::Forbidden(_))
400        ));
401    }
402
403    #[test]
404    fn refuses_paths_outside_the_scope_and_dotdot_escapes() {
405        let h = fake_home();
406        let home = h.path().canonicalize().unwrap();
407        let mut s = ScopeStore::default();
408        let root = s
409            .grant_with_home(&home.join("Documents"), Some(&home))
410            .unwrap();
411        let escape = root.join("clients/../../.ssh/id_ed25519");
412        assert!(matches!(
413            s.resolve_with_home(&escape, Some(&home)),
414            Err(ScopeError::OutsideScope(_))
415        ));
416        assert!(matches!(
417            s.resolve_with_home(Path::new("/etc/hosts"), Some(&home)),
418            Err(ScopeError::OutsideScope(_))
419        ));
420    }
421
422    #[cfg(unix)]
423    #[test]
424    fn refuses_a_symlink_that_leaves_the_granted_folder() {
425        let h = fake_home();
426        let home = h.path().canonicalize().unwrap();
427        let mut s = ScopeStore::default();
428        let root = s
429            .grant_with_home(&home.join("Documents"), Some(&home))
430            .unwrap();
431        std::os::unix::fs::symlink(home.join(".ssh/id_ed25519"), root.join("innocent.txt"))
432            .unwrap();
433        assert!(matches!(
434            s.resolve_with_home(&root.join("innocent.txt"), Some(&home)),
435            Err(ScopeError::OutsideScope(_))
436        ));
437    }
438
439    #[test]
440    fn revoking_removes_access_and_a_parent_grant_absorbs_children() {
441        let h = fake_home();
442        let home = h.path().canonicalize().unwrap();
443        let mut s = ScopeStore::default();
444        let child = s
445            .grant_with_home(&home.join("Documents/clients"), Some(&home))
446            .unwrap();
447        let parent = s
448            .grant_with_home(&home.join("Documents"), Some(&home))
449            .unwrap();
450        assert_eq!(s.roots(), std::slice::from_ref(&parent));
451        assert!(s
452            .resolve_with_home(&child.join("a.pdf"), Some(&home))
453            .is_ok());
454        assert!(s.revoke(&parent));
455        assert!(matches!(
456            s.resolve_with_home(&child.join("a.pdf"), Some(&home)),
457            Err(ScopeError::OutsideScope(_))
458        ));
459        assert!(!s.revoke(&parent));
460    }
461
462    #[test]
463    fn grants_persist_and_vanished_folders_drop_out() {
464        let h = fake_home();
465        let home = h.path().canonicalize().unwrap();
466        let file = h.path().join("data/scope.json");
467        let mut s = ScopeStore::default();
468        s.grant_with_home(&home.join("Documents"), Some(&home))
469            .unwrap();
470        s.save(&file).unwrap();
471        let loaded = ScopeStore::load_with_home(&file, Some(&home));
472        assert_eq!(loaded.roots().len(), 1);
473        fs::remove_dir_all(home.join("Documents")).unwrap();
474        assert!(ScopeStore::load_with_home(&file, Some(&home))
475            .roots()
476            .is_empty());
477    }
478}