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)]
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(self.relative(file)?.display().to_string())
118    }
119}
120
121/// `path` with its `.` and `..` components resolved by name, not on disk:
122/// the path a link or an import names when the file may not exist yet, so it
123/// still gets an address (and a problem). The one rule for it.
124pub(crate) fn lexical(path: &Path) -> PathBuf {
125    use std::path::Component;
126    let mut out = PathBuf::new();
127    for component in path.components() {
128        match component {
129            Component::CurDir => {}
130            Component::ParentDir => {
131                out.pop();
132            }
133            other => out.push(other),
134        }
135    }
136    out
137}
138
139impl AsRef<Path> for ServedFolder {
140    fn as_ref(&self) -> &Path {
141        &self.0
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    /// A served folder `served/` beside a secret `outside.txt`, with a
150    /// symbolic link inside pointing out.
151    fn fixture(name: &str) -> (PathBuf, ServedFolder) {
152        let top =
153            std::env::temp_dir().join(format!("devpage-served-{name}-{}", std::process::id()));
154        let _ = std::fs::remove_dir_all(&top);
155        std::fs::create_dir_all(top.join("served/docs")).unwrap();
156        std::fs::write(top.join("outside.txt"), "secret").unwrap();
157        std::fs::write(top.join("served/docs/a.md"), "# A").unwrap();
158        #[cfg(unix)]
159        std::os::unix::fs::symlink(top.join("outside.txt"), top.join("served/link-out")).unwrap();
160        let served = ServedFolder::new(&top.join("served")).unwrap();
161        (top.canonicalize().unwrap(), served)
162    }
163
164    #[test]
165    fn resolves_files_and_folders_inside() {
166        let (top, served) = fixture("inside");
167        let a = top.join("served/docs/a.md");
168        assert_eq!(
169            served.file(&top.join("served/docs/../docs/a.md")),
170            Some(a.clone())
171        );
172        assert_eq!(
173            served.folder(&top.join("served/docs")),
174            Some(top.join("served/docs"))
175        );
176        assert_eq!(
177            served.file(&top.join("served/docs")),
178            None,
179            "a folder is no file"
180        );
181        assert_eq!(served.folder(&a), None, "a file is no folder");
182        assert_eq!(served.at("/docs/a.md"), Some(a.clone()));
183        assert_eq!(served.file_at("/docs/a.md"), Some(a.clone()));
184        assert_eq!(served.file_at("/docs"), None, "a folder is no file");
185        assert_eq!(served.url(&a).as_deref(), Some("/docs/a.md"));
186        assert_eq!(served.name(&a).as_deref(), Some("docs/a.md"));
187        assert_eq!(served.relative(&a), Some(Path::new("docs/a.md")));
188    }
189
190    #[test]
191    fn a_mounted_folder_addresses_its_files_under_the_mount() {
192        let (top, served) = fixture("mounted");
193        let a = top.join("served/docs/a.md");
194        let mounted = served.clone().mounted("/d/x/v/2");
195        assert_eq!(mounted.url(&a).as_deref(), Some("/d/x/v/2/docs/a.md"));
196        assert_eq!(
197            mounted.name(&a).as_deref(),
198            Some("docs/a.md"),
199            "a name is the same anywhere"
200        );
201        assert_eq!(mounted.mount(), "/d/x/v/2");
202        // A folder made from its path is served at `/`.
203        assert_eq!(ServedFolder::new(&top.join("served")).unwrap(), served);
204    }
205
206    #[test]
207    fn refuses_what_climbs_out_or_links_out() {
208        let (top, served) = fixture("outside");
209        assert_eq!(served.at("/../outside.txt"), None);
210        assert_eq!(served.file_at("/../outside.txt"), None);
211        assert_eq!(served.file(&top.join("served/../outside.txt")), None);
212        #[cfg(unix)]
213        {
214            assert_eq!(served.at("/link-out"), None);
215            assert_eq!(served.file(&top.join("served/link-out")), None);
216        }
217        assert_eq!(served.inside(&top.join("served/missing.md")), None);
218        assert!(!served.contains(&top.join("outside.txt")));
219        assert_eq!(served.relative(&top.join("outside.txt")), None);
220        // Neither named nor addressed: no absolute path stands in.
221        assert_eq!(served.name(&top.join("outside.txt")), None);
222        assert_eq!(served.url(&top.join("outside.txt")), None);
223        assert_eq!(
224            served.clone().mounted("/d/x").url(&top.join("outside.txt")),
225            None
226        );
227    }
228
229    #[test]
230    fn a_deleted_file_is_still_inside_by_its_path() {
231        let (top, served) = fixture("deleted");
232        let gone = top.join("served/docs/gone.md");
233        assert!(served.contains(&gone));
234        assert_eq!(served.inside(&gone), None, "it no longer resolves");
235    }
236}