Skip to main content

fallow_engine/
saved_file.rs

1//! Read back the files that fallow saves, such as baselines, snapshots and
2//! setup state.
3//!
4//! A flag or a default names each file. A cloned repository can commit a
5//! symlink at that path, so a path below the project root or the working
6//! directory must resolve inside that directory. A path outside both is a
7//! plain path that the user names, and it stays allowed. Each file must be a
8//! regular file of at most [`DEFAULT_MAX_READ_BYTES`] bytes.
9//!
10//! A parse error names the position only, because the serde text can quote a
11//! value of the file.
12
13use std::path::{Path, PathBuf};
14
15use fallow_types::path_guard::lexically_normalized;
16use fallow_types::read_guard::{
17    DEFAULT_MAX_READ_BYTES, ReadRefusal, is_inside_root, read_to_string_bounded,
18    read_to_string_inside,
19};
20
21/// Read the saved file at `path`, with `root` and the working directory as
22/// bases. A relative `path` is taken relative to the working directory.
23///
24/// # Errors
25///
26/// Returns a [`ReadRefusal`] when the path below `root` or the working
27/// directory resolves outside it, the file is not a regular file, is too
28/// large, is not UTF-8, or cannot be read. When the working directory cannot
29/// be read, a relative path is refused.
30pub fn read_saved_file(root: &Path, path: &Path) -> Result<String, ReadRefusal> {
31    read_saved_text(Some(root), path, DEFAULT_MAX_READ_BYTES)
32}
33
34/// True when `path`, with `..` and `.` applied by text, is `base` or below
35/// it. See [`base_in_path_spelling`].
36#[must_use]
37pub fn lies_below(base: &Path, path: &Path) -> bool {
38    base_in_path_spelling(base, path).is_some()
39}
40
41/// The ancestor of `path`, with `..` and `.` applied by text, that is
42/// `base`. A base can have another spelling through a link, such as `/tmp`
43/// for `/private/tmp` on macOS, so an ancestor that resolves to `base` also
44/// counts. A link below that ancestor does not move `path` out of `base`:
45/// the caller then checks where that link resolves. `None` when `path` is
46/// not below `base`.
47#[must_use]
48pub fn base_in_path_spelling(base: &Path, path: &Path) -> Option<PathBuf> {
49    let normalized = lexically_normalized(path);
50    if normalized.starts_with(base) {
51        return Some(base.to_path_buf());
52    }
53    let canonical_base = std::fs::canonicalize(base).ok()?;
54    normalized
55        .ancestors()
56        .find(|ancestor| {
57            *ancestor == canonical_base
58                || std::fs::canonicalize(ancestor).is_ok_and(|resolved| resolved == canonical_base)
59        })
60        .map(Path::to_path_buf)
61}
62
63/// [`read_saved_file`] for a caller that has no project root. Only the
64/// working directory is a base.
65///
66/// # Errors
67///
68/// Returns a [`ReadRefusal`] as [`read_saved_file`] does.
69pub fn read_saved_file_in_cwd(path: &Path) -> Result<String, ReadRefusal> {
70    read_saved_text(None, path, DEFAULT_MAX_READ_BYTES)
71}
72
73/// [`read_saved_file`] with an optional `root` and the limit `max_bytes`.
74///
75/// # Errors
76///
77/// Returns a [`ReadRefusal`] as [`read_saved_file`] does.
78pub fn read_saved_text(
79    root: Option<&Path>,
80    path: &Path,
81    max_bytes: u64,
82) -> Result<String, ReadRefusal> {
83    let cwd = std::env::current_dir();
84    let absolute = match (&cwd, path.is_absolute()) {
85        (_, true) => path.to_path_buf(),
86        (Ok(cwd), false) => cwd.join(path),
87        (Err(error), false) => {
88            return Err(ReadRefusal::Io {
89                path: path.to_path_buf(),
90                source: std::io::Error::new(error.kind(), error.to_string()),
91            });
92        }
93    };
94    read_saved_file_from(root, cwd.ok().as_deref(), &absolute, max_bytes)
95}
96
97fn read_saved_file_from(
98    root: Option<&Path>,
99    cwd: Option<&Path>,
100    absolute: &Path,
101    max_bytes: u64,
102) -> Result<String, ReadRefusal> {
103    let base = [root, cwd]
104        .into_iter()
105        .flatten()
106        .find(|base| lies_below(base, absolute));
107    match base {
108        Some(base) => read_to_string_inside(base, absolute, max_bytes),
109        None => read_to_string_bounded(absolute, max_bytes),
110    }
111}
112
113/// List the saved-file directory `dir` below `root`, when it resolves inside
114/// `root`. Read each entry with [`read_saved_file`].
115///
116/// # Errors
117///
118/// Returns a `PermissionDenied` error when `dir` resolves outside `root`, and
119/// the error of `read_dir` otherwise.
120pub(crate) fn read_saved_dir(root: &Path, dir: &Path) -> std::io::Result<std::fs::ReadDir> {
121    let entries = std::fs::read_dir(dir)?;
122    if is_inside_root(root, dir) {
123        Ok(entries)
124    } else {
125        Err(std::io::Error::new(
126            std::io::ErrorKind::PermissionDenied,
127            format!(
128                "refusing to list {}: it resolves outside {}",
129                dir.display(),
130                root.display()
131            ),
132        ))
133    }
134}
135
136/// The position of a JSON error, for a message that must not quote the file.
137/// An error of a typed conversion has no position, so it gets a fixed text.
138#[must_use]
139pub fn json_error_position(error: &serde_json::Error) -> String {
140    if error.line() == 0 {
141        "the content does not have the expected structure".to_owned()
142    } else {
143        format!(
144            "parse error at line {}, column {}",
145            error.line(),
146            error.column()
147        )
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    #[test]
156    #[cfg(unix)]
157    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
158    fn refuses_a_link_below_the_root_or_the_working_directory() {
159        let dir = tempfile::tempdir().expect("temp dir");
160        let base = dunce::canonicalize(dir.path()).expect("canonical");
161        let root = base.join("cwd").join("project");
162        std::fs::create_dir_all(&root).expect("mkdir");
163        let cwd = base.join("cwd");
164        let outside = base.join("other.json");
165        std::fs::write(&outside, r#"{"value": "outside"}"#).expect("write");
166        std::os::unix::fs::symlink(&outside, root.join("baseline.json")).expect("link");
167        std::os::unix::fs::symlink(&outside, cwd.join("baseline.json")).expect("link");
168        std::fs::write(root.join("own.json"), "{}").expect("write");
169
170        for linked in [root.join("baseline.json"), cwd.join("baseline.json")] {
171            let refusal = read_saved_file_from(Some(&root), Some(&cwd), &linked, 1024).unwrap_err();
172            assert!(
173                matches!(refusal, ReadRefusal::OutsideRoot { .. }),
174                "{refusal}"
175            );
176        }
177        assert_eq!(
178            read_saved_file_from(Some(&root), Some(&cwd), &root.join("own.json"), 1024)
179                .expect("own"),
180            "{}"
181        );
182        assert!(
183            read_saved_file_from(Some(&root), Some(&cwd), &outside, 1024).is_ok(),
184            "a plain path outside both directories stays allowed"
185        );
186        assert!(matches!(
187            read_saved_file_from(Some(&root), Some(&cwd), &root, 1024).unwrap_err(),
188            ReadRefusal::NotRegularFile { .. }
189        ));
190    }
191
192    #[test]
193    #[cfg(unix)]
194    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
195    fn refuses_to_list_a_directory_link_out_of_the_root() {
196        let dir = tempfile::tempdir().expect("temp dir");
197        let root = dir.path().join("project");
198        let outside = dir.path().join("elsewhere");
199        std::fs::create_dir_all(&root).expect("mkdir");
200        std::fs::create_dir_all(&outside).expect("mkdir");
201        std::os::unix::fs::symlink(&outside, root.join("snapshots")).expect("link");
202        std::fs::create_dir(root.join("own")).expect("mkdir");
203
204        assert!(read_saved_dir(&root, &root.join("snapshots")).is_err());
205        assert!(read_saved_dir(&root, &root.join("own")).is_ok());
206    }
207
208    #[test]
209    #[cfg(unix)]
210    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
211    fn a_base_spelled_through_a_link_still_counts() {
212        let dir = tempfile::tempdir().expect("temp dir");
213        let real = dunce::canonicalize(dir.path())
214            .expect("canonical")
215            .join("project");
216        std::fs::create_dir_all(&real).expect("mkdir");
217        let alias = real.parent().expect("parent").join("alias");
218        std::os::unix::fs::symlink(&real, &alias).expect("link");
219
220        assert_eq!(
221            base_in_path_spelling(&real, &alias.join("a/b.json")),
222            Some(alias.clone())
223        );
224        assert!(lies_below(&real, &real.join("a/../b.json")));
225        assert!(!lies_below(&real, &real.join("../b.json")));
226    }
227
228    #[test]
229    fn json_errors_name_the_position_only() {
230        let error = serde_json::from_str::<u32>("\"hidden-value\"").unwrap_err();
231        let message = json_error_position(&error);
232        assert!(!message.contains("hidden-value"), "{message}");
233        assert!(message.contains("line 1"), "{message}");
234    }
235}