Skip to main content

xet_runtime/file_utils/
safe_file_creator.rs

1use std::fs::{self, File, Metadata};
2use std::io::{self, BufWriter, Seek, SeekFrom, Write};
3use std::path::{Path, PathBuf};
4
5use rand::distr::Alphanumeric;
6use rand::{RngExt, rng};
7
8use super::create_file;
9use super::file_metadata::set_file_metadata;
10
11pub struct SafeFileCreator {
12    dest_path: Option<PathBuf>,
13    temp_path: PathBuf,
14    original_metadata: Option<Metadata>,
15    writer: Option<BufWriter<File>>,
16}
17
18impl SafeFileCreator {
19    /// Safely creates a new file at a specific location.  Ensures the file is not created with elevated privileges,
20    /// and a temporary file is created then renamed on close.
21    ///
22    /// Calling close() explicitly is required to rename.
23    pub fn new<P: AsRef<Path>>(dest_path: P) -> io::Result<Self> {
24        let dest_path = dest_path.as_ref().to_path_buf();
25
26        let parent = dest_path
27            .parent()
28            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path doesn't have a valid parent directory"))?;
29        let file_name = parent
30            .file_name()
31            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path doesn't have a valid file name"))?
32            .to_str();
33
34        let temp_path = Self::temp_file_path(parent, file_name);
35
36        // This matches the permissions and ownership of the parent directory
37        let file = create_file(&temp_path)?;
38        let writer = BufWriter::new(file);
39
40        Ok(SafeFileCreator {
41            dest_path: Some(dest_path),
42            temp_path,
43            original_metadata: None,
44            writer: Some(writer),
45        })
46    }
47
48    /// Safely creates a new file while a destination name can't be decided now. Users need to call
49    /// ```ignore
50    /// pub fn set_dest_path<P: AsRef<Path>>(dest_path: P)
51    /// ```
52    /// to set the destination before closing the file.
53    ///
54    /// Calling close() explicitly is required to rename.
55    pub fn new_unnamed(temp_root: impl AsRef<Path>) -> io::Result<Self> {
56        let temp_path = Self::temp_file_path(temp_root, None);
57
58        // This matches the permissions and ownership of the parent directory
59        let file = create_file(&temp_path)?;
60        let writer = BufWriter::new(file);
61
62        Ok(SafeFileCreator {
63            dest_path: None,
64            temp_path,
65            original_metadata: None,
66            writer: Some(writer),
67        })
68    }
69
70    /// Safely replaces a new file at a specific location.  Ensures the file is not created with elevated privileges,
71    /// and additionally the metadata of the old one will match the new metadata.
72    ///
73    /// Calling close() explicitly is required to rename.
74    pub fn replace_existing<P: AsRef<Path>>(dest_path: P) -> io::Result<Self> {
75        let mut s = Self::new(&dest_path)?;
76        s.original_metadata = fs::metadata(dest_path).ok();
77        Ok(s)
78    }
79
80    /// Generates a temporary file path in the same directory as the destination file
81    fn temp_file_path(dest_dir: impl AsRef<Path>, file: Option<&str>) -> PathBuf {
82        let mut rng = rng();
83        let random_hash: String = (0..10).map(|_| rng.sample(Alphanumeric)).map(char::from).collect();
84        let temp_file_name = if let Some(filename) = file {
85            format!(".{filename}.{random_hash}.tmp")
86        } else {
87            format!(".{random_hash}.tmp")
88        };
89        dest_dir.as_ref().join(temp_file_name)
90    }
91
92    pub fn set_dest_path<P: AsRef<Path>>(&mut self, dest_path: P) {
93        let dest_path = dest_path.as_ref().to_path_buf();
94        self.dest_path = Some(dest_path);
95    }
96
97    // abort the writing process and delete the temporary file
98    pub fn abort(&mut self) -> io::Result<()> {
99        if self.writer.is_none() {
100            return Ok(());
101        }
102        self.writer = None;
103        if self.temp_path.exists() {
104            fs::remove_file(&self.temp_path)?;
105        }
106        Ok(())
107    }
108
109    /// Closes the writer and replaces the original file with the temporary file
110    pub fn close(&mut self) -> io::Result<()> {
111        let Some(dest_path) = &self.dest_path else {
112            return Err(io::Error::new(io::ErrorKind::InvalidInput, "destination file name not set"));
113        };
114
115        match &mut self.writer {
116            Some(writer) => writer.flush()?,
117            None => return Ok(()),
118        }
119        self.writer = None;
120
121        // Replace the original file with the new file
122        fs::rename(&self.temp_path, dest_path)?;
123
124        if let Some(metadata) = self.original_metadata.as_ref() {
125            set_file_metadata(dest_path, metadata, false)?;
126        }
127        let original_permissions = if dest_path.exists() {
128            Some(fs::metadata(dest_path)?.permissions())
129        } else {
130            None
131        };
132
133        // Set the original file's permissions to the new file if they exist
134        if let Some(permissions) = original_permissions {
135            fs::set_permissions(dest_path, permissions.clone())?;
136        }
137
138        Ok(())
139    }
140
141    fn writer(&mut self) -> io::Result<&mut BufWriter<File>> {
142        match &mut self.writer {
143            Some(wr) => Ok(wr),
144            None => Err(io::Error::new(
145                io::ErrorKind::BrokenPipe,
146                format!("Writing to {:?} already completed.", self.dest_path),
147            )),
148        }
149    }
150}
151
152impl Write for SafeFileCreator {
153    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
154        self.writer()?.write(buf)
155    }
156
157    fn flush(&mut self) -> io::Result<()> {
158        self.writer()?.flush()
159    }
160}
161
162impl Seek for SafeFileCreator {
163    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
164        self.writer()?.seek(pos)
165    }
166}
167
168impl Drop for SafeFileCreator {
169    fn drop(&mut self) {
170        let _ = self.abort();
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use std::fs::File;
177    use std::io::Read;
178    #[cfg(unix)]
179    use std::os::unix::fs::PermissionsExt;
180
181    use tempfile::tempdir;
182
183    use super::*;
184
185    #[test]
186    fn test_safe_file_creator_new() {
187        let dir = tempdir().unwrap();
188        let dest_path = dir.path().join("new_file.txt");
189
190        let mut safe_file_creator = SafeFileCreator::new(&dest_path).unwrap();
191        writeln!(safe_file_creator, "Hello, world!").unwrap();
192        safe_file_creator.close().unwrap();
193
194        // Verify file contents
195        let mut contents = String::new();
196        File::open(&dest_path).unwrap().read_to_string(&mut contents).unwrap();
197        assert_eq!(contents.trim(), "Hello, world!");
198
199        // Verify file permissions: owner should have read/write.
200        // Group/other bits depend on host umask and may vary (e.g. 0o600 vs 0o644).
201        #[cfg(unix)]
202        {
203            let metadata = std::fs::metadata(&dest_path).unwrap();
204            let permissions = metadata.permissions();
205            let mode = permissions.mode() & 0o777;
206            // Default creation mode is 0o666 masked by umask.
207            assert!(mode & 0o600 == 0o600, "Owner should have rw permissions, got {mode:#o}");
208        }
209    }
210
211    #[test]
212    fn test_safe_file_creator_new_unnamed() {
213        let _dir = tempdir().unwrap();
214        let mut safe_file_creator = SafeFileCreator::new_unnamed(_dir.path()).unwrap();
215        writeln!(safe_file_creator, "Hello, world!").unwrap();
216
217        // Test error checking
218        let ret = safe_file_creator.close();
219        assert!(ret.is_err());
220
221        let dir = tempdir().unwrap();
222        let dest_path = dir.path().join("new_file.txt");
223        safe_file_creator.set_dest_path(&dest_path);
224        safe_file_creator.close().unwrap();
225
226        // Verify file contents
227        let mut contents = String::new();
228        File::open(&dest_path).unwrap().read_to_string(&mut contents).unwrap();
229        assert_eq!(contents.trim(), "Hello, world!");
230
231        // Verify file permissions: owner should have read/write.
232        // Group/other bits depend on host umask and may vary (e.g. 0o600 vs 0o644).
233        #[cfg(unix)]
234        {
235            let metadata = std::fs::metadata(&dest_path).unwrap();
236            let permissions = metadata.permissions();
237            let mode = permissions.mode() & 0o777;
238            // Default creation mode is 0o666 masked by umask.
239            assert!(mode & 0o600 == 0o600, "Owner should have rw permissions, got {mode:#o}");
240        }
241    }
242
243    #[test]
244    fn test_safe_file_creator_replace_existing() {
245        let dir = tempdir().unwrap();
246        let dest_path = dir.path().join("existing_file.txt");
247
248        // Create the existing file
249        {
250            let mut file = File::create(&dest_path).unwrap();
251            file.write_all(b"Old content").unwrap();
252            #[cfg(unix)]
253            {
254                let mut perms = file.metadata().unwrap().permissions();
255                perms.set_mode(0o600);
256                std::fs::set_permissions(&dest_path, perms).unwrap();
257            }
258        }
259
260        let mut safe_file_creator = SafeFileCreator::replace_existing(&dest_path).unwrap();
261        writeln!(safe_file_creator, "New content").unwrap();
262        safe_file_creator.close().unwrap();
263
264        // Verify file contents
265        let mut contents = String::new();
266        File::open(&dest_path).unwrap().read_to_string(&mut contents).unwrap();
267        assert_eq!(contents.trim(), "New content");
268
269        // Verify file permissions
270        #[cfg(unix)]
271        {
272            let metadata = std::fs::metadata(&dest_path).unwrap();
273            let permissions = metadata.permissions();
274            assert_eq!(permissions.mode() & 0o777, 0o600); // Original file mode
275        }
276    }
277
278    #[test]
279    fn test_safe_file_creator_drop() {
280        let dir = tempdir().unwrap();
281        let dest_path = dir.path().join("drop_file.txt");
282        fs::write(&dest_path, "Old content").unwrap();
283        let temp_path;
284
285        {
286            let mut safe_file_creator = SafeFileCreator::replace_existing(&dest_path).unwrap();
287            temp_path = safe_file_creator.temp_path.clone();
288            writeln!(safe_file_creator, "Hello, world!").unwrap();
289            // safe_file_creator is dropped here without calling close()
290        }
291
292        assert_eq!(
293            fs::read_to_string(&dest_path).unwrap(),
294            "Old content",
295            "dest file should be unchanged when dropped without close()"
296        );
297        assert!(!temp_path.exists(), "temp file should be cleaned up on drop");
298    }
299
300    #[test]
301    fn test_safe_file_creator_double_close() {
302        let dir = tempdir().unwrap();
303        let dest_path = dir.path().join("double_close_file.txt");
304
305        let mut safe_file_creator = SafeFileCreator::new(&dest_path).unwrap();
306        writeln!(safe_file_creator, "Hello, world!").unwrap();
307        safe_file_creator.close().unwrap();
308        safe_file_creator.close().unwrap(); // Should be a no-op
309
310        // Verify file contents
311        let mut contents = String::new();
312        File::open(&dest_path).unwrap().read_to_string(&mut contents).unwrap();
313        assert_eq!(contents.trim(), "Hello, world!");
314    }
315
316    #[test]
317    #[cfg(unix)]
318    fn test_safe_file_creator_set_metadata() {
319        let dir = tempdir().unwrap();
320        let dest_path = dir.path().join("metadata_file.txt");
321
322        // Create the existing file
323        {
324            let mut file = File::create(&dest_path).unwrap();
325            file.write_all(b"Old content").unwrap();
326            let mut perms = file.metadata().unwrap().permissions();
327            perms.set_mode(0o600);
328            fs::set_permissions(&dest_path, perms).unwrap();
329        }
330
331        let mut safe_file_creator = SafeFileCreator::replace_existing(&dest_path).unwrap();
332        writeln!(safe_file_creator, "New content").unwrap();
333        safe_file_creator.close().unwrap();
334
335        // Verify file contents
336        let mut contents = String::new();
337        File::open(&dest_path).unwrap().read_to_string(&mut contents).unwrap();
338        assert_eq!(contents.trim(), "New content");
339
340        // Verify file permissions
341        let metadata = fs::metadata(&dest_path).unwrap();
342        let permissions = metadata.permissions();
343        #[cfg(unix)]
344        assert_eq!(permissions.mode() & 0o777, 0o600); // Original file mode
345    }
346}