Skip to main content

surjection_core/
access.rs

1//! Write access to client files and folders (SPEC 8.2 `read_only_target`,
2//! #4): a folder managed by a separate installer can hold client files
3//! this account may read but not write. Surjection shows them, never plans a
4//! write into them, and reports a write the OS refuses as
5//! `read_only_target` instead of a failure.
6//!
7//! Two layers:
8//! - **The probe** ([`probe`], [`probe_files`]) runs while planning, for the
9//!   views only. It never writes: on Windows it opens the file for writing
10//!   (`CreateFileW` with `GENERIC_WRITE`, `OPEN_EXISTING`, sharing read,
11//!   write and delete, closed at once; never created or truncated) after
12//!   checking the read-only attribute, and opens the folder a temp file or
13//!   a missing file would be created in with `FILE_ADD_FILE` (or
14//!   `FILE_ADD_SUBDIRECTORY` for a missing folder) and backup semantics. On
15//!   Unix it asks `access(W_OK)` of the file (links resolved) and
16//!   `access(W_OK | X_OK)` of that folder. A sharing violation is not read
17//!   only (it stays `file_locked` at write time). Probes run on worker
18//!   threads under a time budget ([`PROBE_BUDGET`] per planner run); one
19//!   that does not answer in time is [`WriteAccess::Unknown`], which counts
20//!   as writable.
21//! - **The write-time mapping** ([`write_error`], [`denied`]) is the real
22//!   protection, since a probe can race: access denied, a read-only
23//!   attribute or a read-only mount at write time becomes
24//!   `read_only_target` for that target, and the run goes on.
25
26use std::collections::HashMap;
27use std::hash::{DefaultHasher, Hash, Hasher};
28use std::io;
29use std::path::{Path, PathBuf};
30use std::sync::{Arc, Mutex, MutexGuard, mpsc};
31use std::thread;
32use std::time::{Duration, Instant};
33
34use crate::error::{CoreError, ErrorCode};
35use crate::fs::Fs;
36
37/// Why this account cannot write a file or folder.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
39#[cfg_attr(feature = "specta", derive(specta::Type))]
40#[serde(rename_all = "snake_case")]
41pub enum ReadOnlyKind {
42    /// Access denied by the permissions (a Windows ACL, a POSIX ACL).
43    Acl,
44    /// The read-only attribute (Windows), or no write bit for the owner
45    /// (Unix).
46    Attribute,
47    /// Unix: owned by another user, with no write permission for this one.
48    Owner,
49    /// A network share that denies writing, a read-only mount or
50    /// write-protected media.
51    Share,
52}
53
54impl ReadOnlyKind {
55    pub const fn as_str(self) -> &'static str {
56        match self {
57            ReadOnlyKind::Acl => "acl",
58            ReadOnlyKind::Attribute => "attribute",
59            ReadOnlyKind::Owner => "owner",
60            ReadOnlyKind::Share => "share",
61        }
62    }
63
64    /// English detail for messages (the views localize from the kind).
65    pub const fn describe(self) -> &'static str {
66        match self {
67            ReadOnlyKind::Acl => "its permissions deny this account writing",
68            ReadOnlyKind::Attribute => "it is marked read only",
69            ReadOnlyKind::Owner => "another user owns it and this account may not write it",
70            ReadOnlyKind::Share => "it is on a read-only share or mount",
71        }
72    }
73}
74
75impl std::fmt::Display for ReadOnlyKind {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        f.write_str(self.as_str())
78    }
79}
80
81/// `--json` form of a read-only state: `{"kind": "acl"}`, or `null`.
82pub fn read_only_json<S: serde::Serializer>(
83    kind: &Option<ReadOnlyKind>,
84    serializer: S,
85) -> Result<S::Ok, S::Error> {
86    #[derive(serde::Serialize)]
87    struct ReadOnly {
88        kind: ReadOnlyKind,
89    }
90    serde::Serialize::serialize(&kind.map(|kind| ReadOnly { kind }), serializer)
91}
92
93/// What a probe found.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
95pub enum WriteAccess {
96    Writable,
97    ReadOnly(ReadOnlyKind),
98    /// The probe could not tell (no answer in time, a sharing violation, a
99    /// view that cannot probe). Counts as writable.
100    Unknown,
101}
102
103impl WriteAccess {
104    pub const fn read_only(self) -> Option<ReadOnlyKind> {
105        match self {
106            WriteAccess::ReadOnly(kind) => Some(kind),
107            _ => None,
108        }
109    }
110}
111
112/// A probe a file system view hands out ([`Fs::write_probe`]). It owns what
113/// it needs, so it can run on a worker thread that may outlive the
114/// planner run waiting for it.
115pub type WriteProbe = Arc<dyn Fn(&Path) -> WriteAccess + Send + Sync>;
116
117/// How long one planner run waits for its probes, together.
118pub const PROBE_BUDGET: Duration = Duration::from_secs(2);
119
120/// Probes `path` on the real file system: the file when it exists, else
121/// the folder it would be created in. Writes nothing.
122pub fn probe(path: &Path) -> WriteAccess {
123    platform::probe(&crate::fs::long(path))
124}
125
126/// The fingerprint of a file's bytes (`None` when it does not exist) that
127/// keys cached probe results: the same content hash the plan cache notes.
128pub fn fingerprint(bytes: Option<&[u8]>) -> Option<u64> {
129    bytes.map(|bytes| {
130        let mut hasher = DefaultHasher::new();
131        bytes.hash(&mut hasher);
132        hasher.finish()
133    })
134}
135
136/// Probe results per file, kept while the file's fingerprint stays the
137/// same (the plan cache, M30). One per process in the app; the CLI probes
138/// afresh each run. A probe still running when its planner run stopped
139/// waiting stores its answer here when it arrives.
140#[derive(Debug)]
141pub struct ProbeCache {
142    budget: Duration,
143    entries: Arc<Mutex<HashMap<PathBuf, Cached>>>,
144}
145
146#[derive(Debug, Clone, Copy)]
147enum Cached {
148    Done(Option<u64>, WriteAccess),
149    Running(Option<u64>),
150}
151
152impl Default for ProbeCache {
153    fn default() -> Self {
154        Self::with_budget(PROBE_BUDGET)
155    }
156}
157
158impl ProbeCache {
159    pub fn new() -> Self {
160        Self::default()
161    }
162
163    /// A cache whose planner runs wait `budget` for their probes.
164    pub fn with_budget(budget: Duration) -> Self {
165        Self {
166            budget,
167            entries: Arc::default(),
168        }
169    }
170
171    /// Forgets every result: the next run probes again. Probes still
172    /// running stay marked, so a stalled share does not get a new thread
173    /// per invalidation, and their late answers are still kept.
174    pub fn clear(&self) {
175        lock(&self.entries).retain(|_, cached| matches!(cached, Cached::Running(_)));
176    }
177}
178
179fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
180    mutex
181        .lock()
182        .unwrap_or_else(std::sync::PoisonError::into_inner)
183}
184
185/// Probes each of `files` (path and [`fingerprint`]) through `fs`'s
186/// [`Fs::write_probe`], in parallel, waiting at most the cache's budget
187/// together; a cached result for the same fingerprint is reused. Every
188/// path gets an answer: [`WriteAccess::Unknown`] when the view cannot
189/// probe or the probe did not answer in time.
190pub fn probe_files(
191    fs: &dyn Fs,
192    files: &[(PathBuf, Option<u64>)],
193    cache: Option<&ProbeCache>,
194) -> HashMap<PathBuf, WriteAccess> {
195    let mut out: HashMap<PathBuf, WriteAccess> = HashMap::new();
196    let Some(probe) = fs.write_probe() else {
197        for (path, _) in files {
198            out.insert(path.clone(), WriteAccess::Unknown);
199        }
200        return out;
201    };
202    let local;
203    let cache = match cache {
204        Some(cache) => cache,
205        None => {
206            local = ProbeCache::new();
207            &local
208        }
209    };
210    let (tx, rx) = mpsc::channel::<(PathBuf, WriteAccess)>();
211    let mut running: Vec<(PathBuf, thread::JoinHandle<()>)> = Vec::new();
212    {
213        let mut entries = lock(&cache.entries);
214        for (path, print) in files {
215            if out.contains_key(path) || running.iter().any(|(p, _)| p == path) {
216                continue;
217            }
218            match entries.get(path) {
219                Some(Cached::Done(seen, access)) if seen == print => {
220                    out.insert(path.clone(), *access);
221                    continue;
222                }
223                Some(Cached::Running(seen)) if seen == print => {
224                    out.insert(path.clone(), WriteAccess::Unknown);
225                    continue;
226                }
227                _ => {}
228            }
229            entries.insert(path.clone(), Cached::Running(*print));
230            let (probe, tx, shared) = (probe.clone(), tx.clone(), cache.entries.clone());
231            let (owned, print) = (path.clone(), *print);
232            let spawned = thread::Builder::new()
233                .name("surjection-probe".to_owned())
234                .spawn(move || {
235                    let access = probe(&owned);
236                    {
237                        let mut entries = lock(&shared);
238                        if matches!(entries.get(&owned), Some(Cached::Running(seen)) if *seen == print)
239                        {
240                            entries.insert(owned.clone(), Cached::Done(print, access));
241                        }
242                    }
243                    let _ = tx.send((owned, access));
244                });
245            match spawned {
246                Ok(handle) => running.push((path.clone(), handle)),
247                Err(_) => {
248                    entries.remove(path);
249                    out.insert(path.clone(), WriteAccess::Unknown);
250                }
251            }
252        }
253    }
254    drop(tx);
255    let deadline = Instant::now() + cache.budget;
256    let mut left = running.len();
257    while left > 0 {
258        let now = Instant::now();
259        if now >= deadline {
260            break;
261        }
262        match rx.recv_timeout(deadline - now) {
263            Ok((path, access)) => {
264                out.insert(path, access);
265                left -= 1;
266            }
267            Err(_) => break,
268        }
269    }
270    for (path, handle) in running {
271        if out.contains_key(&path) {
272            continue;
273        }
274        // A probe that panicked (a confined test view refusing a path)
275        // fails the run as it would without the thread.
276        if handle.is_finished()
277            && let Err(panic) = handle.join()
278        {
279            lock(&cache.entries).remove(&path);
280            std::panic::resume_unwind(panic);
281        }
282        out.insert(path, WriteAccess::Unknown);
283    }
284    out
285}
286
287/// [`probe_files`] for one path, without a cache: the file, or the folder
288/// it would be created in.
289pub fn probe_path(fs: &dyn Fs, path: &Path) -> WriteAccess {
290    probe_files(fs, &[(path.to_path_buf(), None)], None)
291        .remove(path)
292        .unwrap_or(WriteAccess::Unknown)
293}
294
295/// The kind of read-only target `err` reports for a write at `path`, or
296/// `None` when the error says something else (a sharing violation stays
297/// `file_locked`, other errors stay I/O errors). For access denied, the
298/// write probe of `path` through `fs` tells the kind; when it finds `path`
299/// writable the denial was about something else (a privilege, a file being
300/// deleted) and is not read only. A view that cannot probe, or a probe that
301/// cannot tell, gives `acl` (`share` for a UNC path).
302pub fn denied(fs: &dyn Fs, err: &io::Error, path: &Path) -> Option<ReadOnlyKind> {
303    if cfg!(windows) && matches!(err.raw_os_error(), Some(32 | 33)) {
304        return None;
305    }
306    if err.kind() == io::ErrorKind::ReadOnlyFilesystem
307        || (cfg!(windows) && matches!(err.raw_os_error(), Some(19 | 65)))
308    {
309        return Some(ReadOnlyKind::Share);
310    }
311    if err.kind() != io::ErrorKind::PermissionDenied {
312        return None;
313    }
314    let fallback = if is_unc(path) {
315        ReadOnlyKind::Share
316    } else {
317        ReadOnlyKind::Acl
318    };
319    match fs.write_probe().map(|probe| probe(path)) {
320        Some(WriteAccess::ReadOnly(kind)) => Some(kind),
321        Some(WriteAccess::Writable) => None,
322        Some(WriteAccess::Unknown) | None => Some(fallback),
323    }
324}
325
326/// `read_only_target` for `path`, carrying `kind`.
327pub fn read_only_target(kind: ReadOnlyKind, path: &Path) -> CoreError {
328    CoreError::new(
329        ErrorCode::ReadOnlyTarget,
330        format!(
331            "this account cannot write here ({}); Surjection leaves it as it is",
332            kind.describe()
333        ),
334    )
335    .with_path(path)
336    .with_read_only(kind)
337}
338
339/// The error of a failed write at `path`: `read_only_target` when the OS
340/// refused it as read only ([`denied`]), else `io_error` (`what: err`).
341pub fn write_error(fs: &dyn Fs, what: &str, path: &Path, err: &io::Error) -> CoreError {
342    match denied(fs, err, path) {
343        Some(kind) => read_only_target(kind, path),
344        None => CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(path),
345    }
346}
347
348/// Whether `path` names a file on a network share by its UNC name.
349fn is_unc(path: &Path) -> bool {
350    if !cfg!(windows) {
351        return false;
352    }
353    let text = path.as_os_str().to_string_lossy();
354    text.starts_with(r"\\?\UNC\")
355        || (text.starts_with(r"\\") && !text.starts_with(r"\\?\") && !text.starts_with(r"\\.\"))
356}
357
358/// The nearest existing ancestor folder of `path` (a file that does not
359/// exist), and whether it is `path`'s own parent.
360fn existing_parent(path: &Path) -> Option<(&Path, bool)> {
361    let mut direct = true;
362    let mut at = path.parent();
363    while let Some(dir) = at {
364        if dir.is_dir() {
365            return Some((dir, direct));
366        }
367        if dir.exists() {
368            return None;
369        }
370        direct = false;
371        at = dir.parent();
372    }
373    None
374}
375
376#[cfg(windows)]
377mod platform {
378    use std::fs::OpenOptions;
379    use std::io;
380    use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
381    use std::path::Path;
382
383    use super::{ReadOnlyKind, WriteAccess, existing_parent, is_unc};
384
385    const FILE_ATTRIBUTE_READONLY: u32 = 0x1;
386    const FILE_ADD_FILE: u32 = 0x2;
387    const FILE_ADD_SUBDIRECTORY: u32 = 0x4;
388    const FILE_DELETE_CHILD: u32 = 0x40;
389    const DELETE: u32 = 0x0001_0000;
390    const GENERIC_WRITE: u32 = 0x4000_0000;
391    const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
392
393    pub fn probe(path: &Path) -> WriteAccess {
394        match std::fs::metadata(path) {
395            // A folder Surjection makes and removes entries in (skill folders).
396            Ok(meta) if meta.is_dir() => open_dir(
397                path,
398                FILE_ADD_FILE | FILE_ADD_SUBDIRECTORY | FILE_DELETE_CHILD,
399            ),
400            Ok(meta) => {
401                if meta.file_attributes() & FILE_ATTRIBUTE_READONLY != 0 {
402                    return WriteAccess::ReadOnly(ReadOnlyKind::Attribute);
403                }
404                // GENERIC_WRITE and DELETE (the save renames over the file:
405                // DELETE on it, or FILE_DELETE_CHILD on its folder, which
406                // the open check counts too), OPEN_EXISTING, sharing read,
407                // write and delete. Nothing is created, truncated or
408                // written; the handle is closed at once. A handle someone
409                // holds without delete sharing is a sharing violation: a
410                // lock, not read only.
411                if let Err(err) = OpenOptions::new()
412                    .access_mode(GENERIC_WRITE | DELETE)
413                    .open(path)
414                {
415                    return classify(&err, path);
416                }
417                // The atomic replace writes a temp file next to it.
418                match path.parent() {
419                    Some(dir) => open_dir(dir, FILE_ADD_FILE),
420                    None => WriteAccess::Writable,
421                }
422            }
423            Err(err) if err.kind() == io::ErrorKind::NotFound => match existing_parent(path) {
424                Some((dir, true)) => open_dir(dir, FILE_ADD_FILE),
425                Some((dir, false)) => open_dir(dir, FILE_ADD_SUBDIRECTORY),
426                None => WriteAccess::Unknown,
427            },
428            Err(_) => WriteAccess::Unknown,
429        }
430    }
431
432    /// Opens `dir` asking for `access` (backup semantics, needed to open a
433    /// folder); nothing is created in it.
434    fn open_dir(dir: &Path, access: u32) -> WriteAccess {
435        match OpenOptions::new()
436            .access_mode(access)
437            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
438            .open(dir)
439        {
440            Ok(_) => WriteAccess::Writable,
441            Err(err) => classify(&err, dir),
442        }
443    }
444
445    fn classify(err: &io::Error, path: &Path) -> WriteAccess {
446        match err.raw_os_error() {
447            // ERROR_ACCESS_DENIED
448            Some(5) if is_unc(path) => WriteAccess::ReadOnly(ReadOnlyKind::Share),
449            Some(5) => WriteAccess::ReadOnly(ReadOnlyKind::Acl),
450            // ERROR_WRITE_PROTECT, ERROR_NETWORK_ACCESS_DENIED
451            Some(19 | 65) => WriteAccess::ReadOnly(ReadOnlyKind::Share),
452            _ if err.kind() == io::ErrorKind::ReadOnlyFilesystem => {
453                WriteAccess::ReadOnly(ReadOnlyKind::Share)
454            }
455            // A sharing violation (32, 33) is a lock, not read only.
456            _ => WriteAccess::Unknown,
457        }
458    }
459}
460
461#[cfg(unix)]
462mod platform {
463    use std::fs::Metadata;
464    use std::io;
465    use std::os::unix::fs::MetadataExt;
466    use std::path::Path;
467
468    use rustix::fs::{Access, access};
469    use rustix::io::Errno;
470
471    use super::{ReadOnlyKind, WriteAccess, existing_parent};
472
473    pub fn probe(path: &Path) -> WriteAccess {
474        // `metadata` and `access` follow links: the final target counts.
475        match std::fs::metadata(path) {
476            Ok(meta) if meta.is_dir() => check(path, &meta, Access::WRITE_OK | Access::EXEC_OK),
477            Ok(meta) => {
478                let file = check(path, &meta, Access::WRITE_OK);
479                if file != WriteAccess::Writable {
480                    return file;
481                }
482                // The atomic replace writes a temp file next to it.
483                match path.parent() {
484                    Some(dir) => folder(dir),
485                    None => WriteAccess::Writable,
486                }
487            }
488            Err(err) if err.kind() == io::ErrorKind::NotFound => match existing_parent(path) {
489                Some((dir, _)) => folder(dir),
490                None => WriteAccess::Unknown,
491            },
492            Err(_) => WriteAccess::Unknown,
493        }
494    }
495
496    fn folder(dir: &Path) -> WriteAccess {
497        match std::fs::metadata(dir) {
498            Ok(meta) => check(dir, &meta, Access::WRITE_OK | Access::EXEC_OK),
499            Err(_) => WriteAccess::Unknown,
500        }
501    }
502
503    fn check(path: &Path, meta: &Metadata, mode: Access) -> WriteAccess {
504        match access(path, mode) {
505            Ok(()) => WriteAccess::Writable,
506            Err(Errno::ROFS) => WriteAccess::ReadOnly(ReadOnlyKind::Share),
507            Err(Errno::ACCESS | Errno::PERM) => WriteAccess::ReadOnly(kind(meta)),
508            Err(_) => WriteAccess::Unknown,
509        }
510    }
511
512    /// Why the mode bits (or something beyond them) deny writing.
513    fn kind(meta: &Metadata) -> ReadOnlyKind {
514        let mode = meta.mode();
515        if meta.uid() == rustix::process::geteuid().as_raw() {
516            if mode & 0o200 == 0 {
517                ReadOnlyKind::Attribute
518            } else {
519                ReadOnlyKind::Acl
520            }
521        } else if mode & 0o022 == 0 {
522            ReadOnlyKind::Owner
523        } else {
524            ReadOnlyKind::Acl
525        }
526    }
527}
528
529#[cfg(not(any(windows, unix)))]
530mod platform {
531    use std::path::Path;
532
533    use super::WriteAccess;
534
535    pub fn probe(_path: &Path) -> WriteAccess {
536        WriteAccess::Unknown
537    }
538}