Skip to main content

graphrt_core/
private_fs.rs

1//! Owner-only files and directories for hosts that write run data to disk.
2//!
3//! Run stores, scores, replay cassettes and evaluation reports hold prompts,
4//! model answers and user data. Written with the default umask (often `022`)
5//! they are readable by every local user, so hosts create them through these
6//! helpers instead: `0600` files and `0700` directories on Unix. Other
7//! platforms rely on the per-user ACLs of the parent directory.
8//!
9//! Modes only apply to what these functions create: an existing file or
10//! directory keeps its permissions, so an operator's deliberate `chmod` is
11//! respected. Atomic replaces (write a new temporary file, then rename) always
12//! end up owner-only.
13
14use std::fs::{DirBuilder, File, OpenOptions};
15use std::io::{self, Write};
16use std::path::{Path, PathBuf};
17use std::sync::atomic::{AtomicU64, Ordering};
18
19/// Mode of directories created here (Unix).
20pub const PRIVATE_DIR_MODE: u32 = 0o700;
21/// Mode of files created here (Unix).
22pub const PRIVATE_FILE_MODE: u32 = 0o600;
23
24/// Create `path` and its missing parents, each new one owner-only.
25///
26/// @param path - Directory to create; existing directories are left as they are.
27/// @throws io::Error - When a directory cannot be created.
28///
29/// @example
30/// graphrt_core::private_fs::create_dir_all(Path::new("store/runs/r1"))?;
31pub fn create_dir_all(path: &Path) -> io::Result<()> {
32    private_dir_builder().recursive(true).create(path)
33}
34
35/// Create a new, owner-only directory under the system temp directory, named
36/// `<prefix>-<pid>-<counter>-<nanos>`.
37///
38/// Creation fails if the path already exists, so another local user cannot
39/// pre-create it (or a symlink in its place) to read or swap what the caller
40/// writes there. The caller removes it.
41///
42/// @param prefix - Name prefix, e.g. `graphrt-bundle-config`.
43/// @returns The new directory's path.
44/// @throws io::Error - When the directory cannot be created.
45pub fn create_fresh_temp_dir(prefix: &str) -> io::Result<PathBuf> {
46    static COUNTER: AtomicU64 = AtomicU64::new(0);
47    let nanos =
48        std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
49    let unique = format!("{}-{}-{nanos}", std::process::id(), COUNTER.fetch_add(1, Ordering::Relaxed));
50    let dir = std::env::temp_dir().join(format!("{prefix}-{unique}"));
51    private_dir_builder().create(&dir)?;
52    Ok(dir)
53}
54
55/// Open `path` for writing, truncating it, creating it owner-only when missing.
56///
57/// @throws io::Error - When the file cannot be opened.
58pub fn create_file(path: &Path) -> io::Result<File> {
59    private_open_options().write(true).create(true).truncate(true).open(path)
60}
61
62/// Open `path` for appending, creating it owner-only when missing.
63///
64/// @throws io::Error - When the file cannot be opened.
65pub fn append_file(path: &Path) -> io::Result<File> {
66    private_open_options().append(true).create(true).open(path)
67}
68
69/// Write `bytes` to `path` (like [`std::fs::write`]), creating it owner-only.
70///
71/// @throws io::Error - When the file cannot be written.
72pub fn write(path: &Path, bytes: impl AsRef<[u8]>) -> io::Result<()> {
73    create_file(path)?.write_all(bytes.as_ref())
74}
75
76fn private_dir_builder() -> DirBuilder {
77    #[cfg_attr(not(unix), allow(unused_mut))] // only mutated by the Unix mode below
78    let mut builder = DirBuilder::new();
79    #[cfg(unix)]
80    std::os::unix::fs::DirBuilderExt::mode(&mut builder, PRIVATE_DIR_MODE);
81    builder
82}
83
84fn private_open_options() -> OpenOptions {
85    #[cfg_attr(not(unix), allow(unused_mut))] // only mutated by the Unix mode below
86    let mut options = OpenOptions::new();
87    #[cfg(unix)]
88    std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE_FILE_MODE);
89    options
90}
91
92#[cfg(test)]
93#[allow(clippy::unwrap_used)]
94mod tests {
95    use super::*;
96
97    #[cfg(unix)]
98    fn mode_of(path: &Path) -> u32 {
99        use std::os::unix::fs::PermissionsExt;
100        std::fs::metadata(path).unwrap().permissions().mode() & 0o777
101    }
102
103    #[test]
104    fn fresh_temp_dirs_are_new_and_owner_only() {
105        let first = create_fresh_temp_dir("graphrt-private-fs-test").unwrap();
106        let second = create_fresh_temp_dir("graphrt-private-fs-test").unwrap();
107        assert_ne!(first, second);
108        #[cfg(unix)]
109        assert_eq!(mode_of(&first), PRIVATE_DIR_MODE);
110        for dir in [first, second] {
111            std::fs::remove_dir_all(dir).unwrap();
112        }
113    }
114
115    #[test]
116    fn files_and_nested_dirs_are_owner_only() {
117        let root = create_fresh_temp_dir("graphrt-private-fs-test").unwrap();
118        let nested = root.join("a/b");
119        create_dir_all(&nested).unwrap();
120        let file = nested.join("data.json");
121        write(&file, b"{}").unwrap();
122        append_file(&nested.join("log.jsonl")).unwrap().write_all(b"x\n").unwrap();
123        assert_eq!(std::fs::read(&file).unwrap(), b"{}");
124        #[cfg(unix)]
125        {
126            assert_eq!(mode_of(&root.join("a")), PRIVATE_DIR_MODE);
127            assert_eq!(mode_of(&nested), PRIVATE_DIR_MODE);
128            assert_eq!(mode_of(&file), PRIVATE_FILE_MODE);
129            assert_eq!(mode_of(&nested.join("log.jsonl")), PRIVATE_FILE_MODE);
130        }
131        std::fs::remove_dir_all(root).unwrap();
132    }
133}