Skip to main content

devpage_core/
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
17/// What a served folder is given as: one already made, which keeps its mount,
18/// or a bare path — at the edges, the command line and tests — served at `/`.
19pub trait Served {
20    fn served(self) -> ServedFolder;
21}
22
23impl Served for ServedFolder {
24    fn served(self) -> ServedFolder {
25        self
26    }
27}
28
29impl Served for &ServedFolder {
30    fn served(self) -> ServedFolder {
31        self.clone()
32    }
33}
34
35impl Served for &Path {
36    /// Made canonical when it exists; a path that doesn't is kept as given,
37    /// and nothing resolves inside it.
38    fn served(self) -> ServedFolder {
39        ServedFolder::canonical(self.canonicalize().unwrap_or_else(|_| self.to_path_buf()))
40    }
41}
42
43impl Served for &PathBuf {
44    fn served(self) -> ServedFolder {
45        self.as_path().served()
46    }
47}
48
49impl Served for PathBuf {
50    fn served(self) -> ServedFolder {
51        self.as_path().served()
52    }
53}
54
55impl ServedFolder {
56    /// The served folder at `path`, made canonical; an error when it doesn't
57    /// exist.
58    pub fn new(path: &Path) -> std::io::Result<Self> {
59        path.canonicalize().map(Self::canonical)
60    }
61
62    /// A served folder at a path the caller already made canonical, at `/`.
63    pub fn canonical(path: PathBuf) -> Self {
64        Self(path, String::new())
65    }
66
67    /// The same folder with its addresses under `mount`, which starts with
68    /// `/` and doesn't end with one: `/d/<id>/v/<n>`.
69    pub fn mounted(self, mount: &str) -> Self {
70        debug_assert!(mount.is_empty() || (mount.starts_with('/') && !mount.ends_with('/')));
71        Self(self.0, mount.to_string())
72    }
73
74    /// The prefix its addresses are under: empty at `/`.
75    pub fn mount(&self) -> &str {
76        &self.1
77    }
78
79    /// Its canonical path.
80    pub fn path(&self) -> &Path {
81        &self.0
82    }
83
84    /// `path` with symbolic links followed, when it exists inside the folder.
85    pub fn inside(&self, path: &Path) -> Option<PathBuf> {
86        let real = path.canonicalize().ok()?;
87        real.starts_with(&self.0).then_some(real)
88    }
89
90    /// `path` resolved, when it is a file inside the folder.
91    pub fn file(&self, path: &Path) -> Option<PathBuf> {
92        self.inside(path).filter(|real| real.is_file())
93    }
94
95    /// `path` resolved, when it is a folder inside the folder.
96    pub fn folder(&self, path: &Path) -> Option<PathBuf> {
97        self.inside(path).filter(|real| real.is_dir())
98    }
99
100    /// What a URL path names — any entry, file or folder — when it lies
101    /// inside the folder.
102    pub fn at(&self, url_path: &str) -> Option<PathBuf> {
103        self.inside(&self.0.join(url_path.trim_start_matches('/')))
104    }
105
106    /// The file a URL path names, when it is a file inside the folder.
107    pub fn file_at(&self, url_path: &str) -> Option<PathBuf> {
108        self.at(url_path).filter(|real| real.is_file())
109    }
110
111    /// Whether an already-resolved path lies inside the folder, without
112    /// touching the disk: for paths that may no longer exist, such as a
113    /// deleted file the watcher reports.
114    pub fn contains(&self, path: &Path) -> bool {
115        path.starts_with(&self.0)
116    }
117
118    /// A resolved path's place in the folder, `None` when it lies outside.
119    pub fn relative<'a>(&self, path: &'a Path) -> Option<&'a Path> {
120        path.strip_prefix(&self.0).ok()
121    }
122
123    /// A file's address: its path from the top of the folder, after `/` and
124    /// the mount prefix.
125    pub fn url(&self, file: &Path) -> String {
126        format!("{}/{}", self.1, self.name(file))
127    }
128
129    /// A file's name: its path from the top of the folder, as problems and
130    /// labels show it.
131    pub fn name(&self, file: &Path) -> String {
132        self.relative(file).unwrap_or(file).display().to_string()
133    }
134}
135
136impl AsRef<Path> for ServedFolder {
137    fn as_ref(&self) -> &Path {
138        &self.0
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    /// A served folder `served/` beside a secret `outside.txt`, with a
147    /// symbolic link inside pointing out.
148    fn fixture(name: &str) -> (PathBuf, ServedFolder) {
149        let top =
150            std::env::temp_dir().join(format!("devpage-served-{name}-{}", std::process::id()));
151        let _ = std::fs::remove_dir_all(&top);
152        std::fs::create_dir_all(top.join("served/docs")).unwrap();
153        std::fs::write(top.join("outside.txt"), "secret").unwrap();
154        std::fs::write(top.join("served/docs/a.md"), "# A").unwrap();
155        #[cfg(unix)]
156        std::os::unix::fs::symlink(top.join("outside.txt"), top.join("served/link-out")).unwrap();
157        let served = ServedFolder::new(&top.join("served")).unwrap();
158        (top.canonicalize().unwrap(), served)
159    }
160
161    #[test]
162    fn resolves_files_and_folders_inside() {
163        let (top, served) = fixture("inside");
164        let a = top.join("served/docs/a.md");
165        assert_eq!(
166            served.file(&top.join("served/docs/../docs/a.md")),
167            Some(a.clone())
168        );
169        assert_eq!(
170            served.folder(&top.join("served/docs")),
171            Some(top.join("served/docs"))
172        );
173        assert_eq!(
174            served.file(&top.join("served/docs")),
175            None,
176            "a folder is no file"
177        );
178        assert_eq!(served.folder(&a), None, "a file is no folder");
179        assert_eq!(served.at("/docs/a.md"), Some(a.clone()));
180        assert_eq!(served.file_at("/docs/a.md"), Some(a.clone()));
181        assert_eq!(served.file_at("/docs"), None, "a folder is no file");
182        assert_eq!(served.url(&a), "/docs/a.md");
183        assert_eq!(served.relative(&a), Some(Path::new("docs/a.md")));
184    }
185
186    #[test]
187    fn a_mounted_folder_addresses_its_files_under_the_mount() {
188        let (top, served) = fixture("mounted");
189        let a = top.join("served/docs/a.md");
190        let mounted = served.clone().mounted("/d/x/v/2");
191        assert_eq!(mounted.url(&a), "/d/x/v/2/docs/a.md");
192        assert_eq!(mounted.name(&a), "docs/a.md", "a name is the same anywhere");
193        assert_eq!(mounted.mount(), "/d/x/v/2");
194        // Passed on, it keeps the mount; a bare path is served at `/`.
195        assert_eq!((&mounted).served().mount(), "/d/x/v/2");
196        assert_eq!(top.join("served").served(), served);
197    }
198
199    #[test]
200    fn refuses_what_climbs_out_or_links_out() {
201        let (top, served) = fixture("outside");
202        assert_eq!(served.at("/../outside.txt"), None);
203        assert_eq!(served.file_at("/../outside.txt"), None);
204        assert_eq!(served.file(&top.join("served/../outside.txt")), None);
205        #[cfg(unix)]
206        {
207            assert_eq!(served.at("/link-out"), None);
208            assert_eq!(served.file(&top.join("served/link-out")), None);
209        }
210        assert_eq!(served.inside(&top.join("served/missing.md")), None);
211        assert!(!served.contains(&top.join("outside.txt")));
212        assert_eq!(served.relative(&top.join("outside.txt")), None);
213    }
214
215    #[test]
216    fn a_deleted_file_is_still_inside_by_its_path() {
217        let (top, served) = fixture("deleted");
218        let gone = top.join("served/docs/gone.md");
219        assert!(served.contains(&gone));
220        assert_eq!(served.inside(&gone), None, "it no longer resolves");
221    }
222}