1use crate::scope::{ScopeError, ScopeStore, ScopedPath};
4use std::collections::HashSet;
5use std::path::{Path, PathBuf};
6
7#[derive(Default)]
8pub struct Access {
9 scope: ScopeStore,
10 dropped: HashSet<PathBuf>,
12}
13
14impl Access {
15 pub fn new(scope: ScopeStore) -> Self {
16 Access {
17 scope,
18 dropped: HashSet::new(),
19 }
20 }
21
22 pub fn scope(&self) -> &ScopeStore {
23 &self.scope
24 }
25
26 pub fn scope_mut(&mut self) -> &mut ScopeStore {
27 &mut self.scope
28 }
29
30 pub fn allow_dropped(&mut self, path: &Path) -> Option<PathBuf> {
32 let canon = path.canonicalize().ok()?;
33 if !canon.is_file() {
34 return None;
35 }
36 self.dropped.insert(canon.clone());
37 Some(canon)
38 }
39
40 pub fn resolve(&self, path: &Path) -> Result<ScopedPath, ScopeError> {
42 match self.scope.resolve(path) {
43 Ok(p) => Ok(p),
44 Err(error) => match path.canonicalize() {
45 Ok(canon) if self.dropped.contains(&canon) => Ok(ScopedPath::new(canon)),
46 _ => Err(error),
47 },
48 }
49 }
50}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55 use std::fs;
56 use tempfile::tempdir;
57
58 #[test]
59 fn a_dropped_file_is_readable_and_its_neighbours_are_not() {
60 let d = tempdir().unwrap();
61 fs::write(d.path().join("bail.pdf"), "%PDF").unwrap();
62 fs::write(d.path().join("secret.pdf"), "%PDF").unwrap();
63 let mut access = Access::default();
64 assert!(access.resolve(&d.path().join("bail.pdf")).is_err());
65 access.allow_dropped(&d.path().join("bail.pdf")).unwrap();
66 assert!(access.resolve(&d.path().join("bail.pdf")).is_ok());
67 assert!(access.resolve(&d.path().join("secret.pdf")).is_err());
68 }
69
70 #[test]
71 fn a_dropped_folder_or_a_path_that_does_not_exist_grants_nothing() {
72 let d = tempdir().unwrap();
73 let mut access = Access::default();
74 assert!(access.allow_dropped(d.path()).is_none());
75 assert!(access
76 .allow_dropped(&d.path().join("missing.pdf"))
77 .is_none());
78 }
79
80 #[cfg(unix)]
81 #[test]
82 fn a_link_to_a_file_that_was_not_dropped_is_not_a_way_in() {
83 let d = tempdir().unwrap();
84 fs::write(d.path().join("secret.pdf"), "%PDF").unwrap();
85 fs::write(d.path().join("bail.pdf"), "%PDF").unwrap();
86 std::os::unix::fs::symlink(d.path().join("secret.pdf"), d.path().join("innocent.pdf"))
87 .unwrap();
88 let mut access = Access::default();
89 access.allow_dropped(&d.path().join("bail.pdf")).unwrap();
90 assert!(access.resolve(&d.path().join("innocent.pdf")).is_err());
91 }
92}