Skip to main content

devpage_core/folder/
served.rs

1//! The served folder: the one place that decides whether a path is part of
2//! what devpage serves. Every link, chapter, slide, widget folder, logo or URL
3//! that names a file is resolved here — symbolic links followed — and anything
4//! that lands outside the folder is refused. A leaf: it depends on nothing
5//! else in devpage.
6
7use std::path::{Path, PathBuf};
8
9/// The canonical folder devpage serves from, the boundary around it, and the
10/// prefix its addresses are under — its **mount**: empty for a local devpage
11/// and bundled mode, `/d/<id>` or `/d/<id>/v/<n>` for a version in server
12/// mode. It is made once, where devpage starts serving a folder, and passed
13/// to everything loaded from it, so the mount reaches every address.
14#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
15pub struct ServedFolder(PathBuf, String);
16
17impl ServedFolder {
18    /// The served folder at `path`, made canonical; an error when it doesn't
19    /// exist.
20    pub fn new(path: &Path) -> std::io::Result<Self> {
21        path.canonicalize().map(Self::canonical)
22    }
23
24    /// A served folder at a path the caller already made canonical, at `/`.
25    pub fn canonical(path: PathBuf) -> Self {
26        Self(path, String::new())
27    }
28
29    /// The same folder with its addresses under `mount`, which starts with
30    /// `/` and doesn't end with one: `/d/<id>/v/<n>`.
31    pub fn mounted(self, mount: &str) -> Self {
32        debug_assert!(mount.is_empty() || (mount.starts_with('/') && !mount.ends_with('/')));
33        Self(self.0, mount.to_string())
34    }
35
36    /// The prefix its addresses are under: empty at `/`.
37    pub fn mount(&self) -> &str {
38        &self.1
39    }
40
41    /// Its canonical path.
42    pub fn path(&self) -> &Path {
43        &self.0
44    }
45
46    /// `path` with symbolic links followed, when it exists inside the folder.
47    pub fn inside(&self, path: &Path) -> Option<PathBuf> {
48        let real = path.canonicalize().ok()?;
49        real.starts_with(&self.0).then_some(real)
50    }
51
52    /// `path` resolved, when it is a file inside the folder.
53    pub fn file(&self, path: &Path) -> Option<PathBuf> {
54        self.inside(path).filter(|real| real.is_file())
55    }
56
57    /// `path` resolved, when it is a folder inside the folder.
58    pub fn folder(&self, path: &Path) -> Option<PathBuf> {
59        self.inside(path).filter(|real| real.is_dir())
60    }
61
62    /// The file `path` names, as the watcher reports it: resolved, when it
63    /// is a file inside the folder; when nothing is there yet, the path it
64    /// would have — its folder resolved on disk where that folder exists —
65    /// so its arrival can be told apart. `None` for anything else: a path
66    /// outside the folder, or a folder.
67    pub fn named(&self, path: &Path) -> Option<PathBuf> {
68        if let Some(file) = self.file(path) {
69            return Some(file);
70        }
71        let lexical = lexical(path);
72        let would_be = match (lexical.parent(), lexical.file_name()) {
73            (Some(parent), Some(name)) => parent
74                .canonicalize()
75                .map(|parent| parent.join(name))
76                .unwrap_or(lexical),
77            _ => lexical,
78        };
79        (self.contains(&would_be) && std::fs::symlink_metadata(&would_be).is_err())
80            .then_some(would_be)
81    }
82
83    /// What a URL path names — any entry, file or folder — when it lies
84    /// inside the folder.
85    pub fn at(&self, url_path: &str) -> Option<PathBuf> {
86        self.inside(&self.0.join(url_path.trim_start_matches('/')))
87    }
88
89    /// The file a URL path names, when it is a file inside the folder.
90    pub fn file_at(&self, url_path: &str) -> Option<PathBuf> {
91        self.at(url_path).filter(|real| real.is_file())
92    }
93
94    /// Whether an already-resolved path lies inside the folder, without
95    /// touching the disk: for paths that may no longer exist, such as a
96    /// deleted file the watcher reports.
97    pub fn contains(&self, path: &Path) -> bool {
98        path.starts_with(&self.0)
99    }
100
101    /// A resolved path's place in the folder, `None` when it lies outside.
102    pub fn relative<'a>(&self, path: &'a Path) -> Option<&'a Path> {
103        path.strip_prefix(&self.0).ok()
104    }
105
106    /// A file's address: its path from the top of the folder, after `/` and
107    /// the mount prefix. `None` when it lies outside: a path outside the
108    /// folder has no address.
109    pub fn url(&self, file: &Path) -> Option<String> {
110        Some(format!("{}/{}", self.1, self.name(file)?))
111    }
112
113    /// A file's name: its path from the top of the folder, as problems and
114    /// labels show it. `None` when it lies outside: a path outside the
115    /// folder is never named.
116    pub fn name(&self, file: &Path) -> Option<String> {
117        Some(slashed(self.relative(file)?))
118    }
119}
120
121/// A symbolic link at `link` to `target`, on every platform: on Windows a
122/// file's link and a folder's are made differently. For tests that check
123/// nothing is reached through a link out of the folder.
124#[cfg(any(test, feature = "testing"))]
125pub fn symlink(target: &Path, link: &Path) -> std::io::Result<()> {
126    #[cfg(unix)]
127    return std::os::unix::fs::symlink(target, link);
128    #[cfg(windows)]
129    return if target.is_dir() {
130        std::os::windows::fs::symlink_dir(target, link)
131    } else {
132        std::os::windows::fs::symlink_file(target, link)
133    };
134}
135
136/// A path inside the folder as addresses name it: its parts joined with `/`
137/// on every platform, Windows too.
138pub fn slashed(path: &Path) -> String {
139    path.components()
140        .map(|c| c.as_os_str().to_string_lossy())
141        .collect::<Vec<_>>()
142        .join("/")
143}
144
145/// `path` with its `.` and `..` components resolved by name, not on disk:
146/// the path a link or an import names when the file may not exist yet, so it
147/// still gets an address (and a problem). The one rule for it.
148pub(crate) fn lexical(path: &Path) -> PathBuf {
149    use std::path::Component;
150    let mut out = PathBuf::new();
151    for component in path.components() {
152        match component {
153            Component::CurDir => {}
154            Component::ParentDir => {
155                out.pop();
156            }
157            other => out.push(other),
158        }
159    }
160    out
161}
162
163impl AsRef<Path> for ServedFolder {
164    fn as_ref(&self) -> &Path {
165        &self.0
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172    use codespec_rust_macro::spec;
173
174    /// A served folder `served/` beside a secret `outside.txt`, with a
175    /// symbolic link inside pointing out.
176    fn fixture(name: &str) -> (PathBuf, ServedFolder) {
177        let top =
178            std::env::temp_dir().join(format!("devpage-served-{name}-{}", std::process::id()));
179        let _ = std::fs::remove_dir_all(&top);
180        std::fs::create_dir_all(top.join("served/docs")).unwrap();
181        std::fs::write(top.join("outside.txt"), "secret").unwrap();
182        std::fs::write(top.join("served/docs/a.md"), "# A").unwrap();
183        symlink(&top.join("outside.txt"), &top.join("served/link-out")).unwrap();
184        let served = ServedFolder::new(&top.join("served")).unwrap();
185        (top.canonicalize().unwrap(), served)
186    }
187
188    /// A nested file's name and address join its parts with `/` on every
189    /// platform: on Windows the path's own separator is `\`.
190    #[test]
191    fn names_and_addresses_join_with_slashes() {
192        let (top, served) = fixture("slashes");
193        let a = served
194            .file(&top.join("served").join("docs").join("a.md"))
195            .unwrap();
196        assert_eq!(served.name(&a).as_deref(), Some("docs/a.md"));
197        assert_eq!(served.url(&a).as_deref(), Some("/docs/a.md"));
198        std::fs::remove_dir_all(&top).ok();
199    }
200
201    #[test]
202    fn resolves_files_and_folders_inside() {
203        let (top, served) = fixture("inside");
204        let a = top.join("served/docs/a.md");
205        assert_eq!(
206            served.file(&top.join("served/docs/../docs/a.md")),
207            Some(a.clone())
208        );
209        assert_eq!(
210            served.folder(&top.join("served/docs")),
211            Some(top.join("served/docs"))
212        );
213        assert_eq!(
214            served.file(&top.join("served/docs")),
215            None,
216            "a folder is no file"
217        );
218        assert_eq!(served.folder(&a), None, "a file is no folder");
219        assert_eq!(served.at("/docs/a.md"), Some(a.clone()));
220        assert_eq!(served.file_at("/docs/a.md"), Some(a.clone()));
221        assert_eq!(served.file_at("/docs"), None, "a folder is no file");
222        assert_eq!(served.url(&a).as_deref(), Some("/docs/a.md"));
223        assert_eq!(served.name(&a).as_deref(), Some("docs/a.md"));
224        assert_eq!(served.relative(&a), Some(Path::new("docs/a.md")));
225    }
226
227    #[test]
228    fn a_mounted_folder_addresses_its_files_under_the_mount() {
229        let (top, served) = fixture("mounted");
230        let a = top.join("served/docs/a.md");
231        let mounted = served.clone().mounted("/d/x/v/2");
232        assert_eq!(mounted.url(&a).as_deref(), Some("/d/x/v/2/docs/a.md"));
233        assert_eq!(
234            mounted.name(&a).as_deref(),
235            Some("docs/a.md"),
236            "a name is the same anywhere"
237        );
238        assert_eq!(mounted.mount(), "/d/x/v/2");
239        // A folder made from its path is served at `/`.
240        assert_eq!(ServedFolder::new(&top.join("served")).unwrap(), served);
241    }
242
243    #[test]
244    #[spec("devpage-stays-inside-its-folder")]
245    fn refuses_what_climbs_out_or_links_out() {
246        let (top, served) = fixture("outside");
247        assert_eq!(served.at("/../outside.txt"), None);
248        assert_eq!(served.file_at("/../outside.txt"), None);
249        assert_eq!(served.file(&top.join("served/../outside.txt")), None);
250        assert_eq!(served.at("/link-out"), None);
251        assert_eq!(served.file(&top.join("served/link-out")), None);
252        assert_eq!(served.inside(&top.join("served/missing.md")), None);
253        assert!(!served.contains(&top.join("outside.txt")));
254        assert_eq!(served.relative(&top.join("outside.txt")), None);
255        // Neither named nor addressed: no absolute path stands in.
256        assert_eq!(served.name(&top.join("outside.txt")), None);
257        assert_eq!(served.url(&top.join("outside.txt")), None);
258        assert_eq!(
259            served.clone().mounted("/d/x").url(&top.join("outside.txt")),
260            None
261        );
262    }
263
264    #[test]
265    fn a_deleted_file_is_still_inside_by_its_path() {
266        let (top, served) = fixture("deleted");
267        let gone = top.join("served/docs/gone.md");
268        assert!(served.contains(&gone));
269        assert_eq!(served.inside(&gone), None, "it no longer resolves");
270    }
271}