Skip to main content

rigspark_runtime/
secure_fs.rs

1use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt};
2use cap_std::fs::{Dir, OpenOptions};
3use std::{
4    fs,
5    io::{self, Read, Write},
6    path::{Component, Path, PathBuf},
7};
8
9#[derive(Debug)]
10pub struct Directory {
11    directory: Dir,
12    path: PathBuf,
13    identity: same_file::Handle,
14}
15impl Directory {
16    pub fn open(path: &Path) -> io::Result<Self> {
17        if fs::symlink_metadata(path)?.file_type().is_symlink() {
18            return Err(io::Error::other("symlinked directory"));
19        }
20        let directory = Dir::open_ambient_dir(path, cap_std::ambient_authority())?;
21        let identity = same_file::Handle::from_file(directory.try_clone()?.into_std_file())?;
22        let result = Self {
23            directory,
24            path: path.into(),
25            identity,
26        };
27        result.check()?;
28        Ok(result)
29    }
30    pub fn check(&self) -> io::Result<()> {
31        if fs::symlink_metadata(&self.path)?.file_type().is_symlink()
32            || same_file::Handle::from_path(&self.path)? != self.identity
33        {
34            return Err(io::Error::other("directory identity changed"));
35        }
36        Ok(())
37    }
38    pub fn dir(&self) -> io::Result<&Dir> {
39        self.check()?;
40        Ok(&self.directory)
41    }
42    pub fn subdir(&self, path: &Path) -> io::Result<Dir> {
43        self.parent(&path.join(".unused")).map(|(parent, _)| parent)
44    }
45    pub fn ensure_dir(&self, path: &Path) -> io::Result<()> {
46        self.check()?;
47        let mut parent = self.directory.try_clone()?;
48        for component in path.components() {
49            let Component::Normal(part) = component else {
50                return Err(io::Error::other("invalid directory path"));
51            };
52            match parent.symlink_metadata(part) {
53                Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => (),
54                Err(error) if error.kind() == io::ErrorKind::NotFound => {
55                    let builder = cap_std::fs::DirBuilder::new();
56                    #[cfg(unix)]
57                    let mut builder = builder;
58                    #[cfg(unix)]
59                    {
60                        use cap_std::fs::DirBuilderExt;
61                        builder.mode(0o700);
62                    }
63                    parent.create_dir_with(part, &builder)?;
64                }
65                _ => return Err(io::Error::other("unsafe directory")),
66            }
67            parent = parent.open_dir_nofollow(part)?;
68        }
69        Ok(())
70    }
71    fn parent(&self, path: &Path) -> io::Result<(Dir, std::ffi::OsString)> {
72        self.check()?;
73        let mut parts = Vec::new();
74        for component in path.components() {
75            if let Component::Normal(part) = component {
76                parts.push(part);
77            } else {
78                return Err(io::Error::other("invalid capability path"));
79            }
80        }
81        let name = parts
82            .pop()
83            .ok_or_else(|| io::Error::other("file name required"))?;
84        let mut parent = self.directory.try_clone()?;
85        for part in parts {
86            if parent.symlink_metadata(part)?.file_type().is_symlink() {
87                return Err(io::Error::other("symlinked ancestor"));
88            }
89            parent = parent.open_dir_nofollow(part)?;
90        }
91        Ok((parent, name.into()))
92    }
93    pub fn read(&self, path: &Path, maximum: u64, secret: bool) -> io::Result<Vec<u8>> {
94        let (parent, name) = self.parent(path)?;
95        if parent.symlink_metadata(&name)?.file_type().is_symlink() {
96            return Err(io::Error::other("symlinked file"));
97        }
98        let mut options = OpenOptions::new();
99        options.read(true).follow(FollowSymlinks::No);
100        #[cfg(unix)]
101        {
102            use cap_std::fs::OpenOptionsExt;
103            options.custom_flags(
104                (rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK).bits() as i32,
105            );
106        }
107        let file = parent.open_with(&name, &options)?.into_std();
108        let metadata = file.metadata()?;
109        if !metadata.is_file() || metadata.len() > maximum {
110            return Err(io::Error::other("invalid or oversized file"));
111        }
112        #[cfg(unix)]
113        {
114            use std::os::unix::fs::PermissionsExt;
115            if metadata.permissions().mode() & if secret { 0o077 } else { 0o022 } != 0 {
116                return Err(io::Error::other("unsafe file permissions"));
117            }
118        }
119        #[cfg(not(unix))]
120        let _ = secret;
121        let mut bytes = Vec::new();
122        file.take(maximum + 1).read_to_end(&mut bytes)?;
123        if bytes.len() as u64 > maximum {
124            return Err(io::Error::other("file exceeds limit"));
125        }
126        self.check()?;
127        Ok(bytes)
128    }
129    pub fn write(
130        &self,
131        path: &Path,
132        bytes: &[u8],
133        create: bool,
134        preserve_mode: bool,
135    ) -> io::Result<()> {
136        let (parent, name) = self.parent(path)?;
137        let permissions = if preserve_mode {
138            let mut options = OpenOptions::new();
139            options.read(true).follow(FollowSymlinks::No);
140            #[cfg(unix)]
141            {
142                use cap_std::fs::OpenOptionsExt;
143                options.custom_flags(rustix::fs::OFlags::NONBLOCK.bits() as i32);
144            }
145            let metadata = parent.open_with(&name, &options)?.into_std().metadata()?;
146            if !metadata.is_file() {
147                return Err(io::Error::other("replace target is not a regular file"));
148            }
149            Some(metadata.permissions())
150        } else {
151            None
152        };
153        let temporary = format!(".llmup-{}.tmp", uuid::Uuid::new_v4());
154        let result = (|| {
155            let mut options = OpenOptions::new();
156            options.write(true).create_new(true);
157            #[cfg(unix)]
158            {
159                use cap_std::fs::OpenOptionsExt;
160                options.mode(0o600);
161            }
162            let mut file = parent.open_with(&temporary, &options)?.into_std();
163            file.write_all(bytes)?;
164            if let Some(permissions) = permissions {
165                file.set_permissions(permissions)?;
166            }
167            file.sync_all()?;
168            self.check()?;
169            if create {
170                parent.hard_link(&temporary, &parent, &name)?;
171                parent.remove_file(&temporary)?;
172            } else {
173                parent.rename(&temporary, &parent, &name)?;
174            }
175            #[cfg(unix)]
176            parent.open(".")?.sync_all()?;
177            Ok(())
178        })();
179        if result.is_err() {
180            let _ = parent.remove_file(&temporary);
181        }
182        result
183    }
184    pub fn remove(&self, path: &Path) -> io::Result<()> {
185        let (parent, name) = self.parent(path)?;
186        parent.remove_file(name)
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    #[cfg(unix)]
194    #[test]
195    fn directory_handles_cannot_be_redirected_to_another_root() {
196        let home = tempfile::tempdir().unwrap();
197        let outside = tempfile::tempdir().unwrap();
198        fs::create_dir(home.path().join("root")).unwrap();
199        fs::write(outside.path().join("secret"), "outside").unwrap();
200        let directory = Directory::open(&home.path().join("root")).unwrap();
201        fs::rename(home.path().join("root"), home.path().join("original")).unwrap();
202        std::os::unix::fs::symlink(outside.path(), home.path().join("root")).unwrap();
203        assert!(directory.read(Path::new("secret"), 1024, false).is_err());
204        assert!(
205            directory
206                .write(Path::new("secret"), b"changed", false, false)
207                .is_err()
208        );
209        assert_eq!(
210            fs::read_to_string(outside.path().join("secret")).unwrap(),
211            "outside"
212        );
213    }
214    #[test]
215    fn writes_are_atomic_and_create_never_clobbers() {
216        let home = tempfile::tempdir().unwrap();
217        let directory = Directory::open(home.path()).unwrap();
218        directory
219            .write(Path::new("file"), b"first", true, false)
220            .unwrap();
221        assert!(
222            directory
223                .write(Path::new("file"), b"second", true, false)
224                .is_err()
225        );
226        assert_eq!(
227            directory.read(Path::new("file"), 10, true).unwrap(),
228            b"first"
229        );
230        directory
231            .write(Path::new("file"), b"second", false, true)
232            .unwrap();
233        assert_eq!(
234            directory.read(Path::new("file"), 10, true).unwrap(),
235            b"second"
236        );
237    }
238}