Skip to main content

lean_ctx/core/
secure_fs.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Owner-only secret files.
3
4/// Writes a secret file atomically (tmp + rename) with owner-only permissions
5/// (0o600 on Unix), so secrets are never world-readable — not even
6/// transiently between create and chmod.
7pub(crate) fn write_secret_file(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
8    use std::io::Write;
9
10    let parent = path
11        .parent()
12        .ok_or_else(|| std::io::Error::other("secret path has no parent directory"))?;
13    let name = path
14        .file_name()
15        .ok_or_else(|| std::io::Error::other("secret path has no file name"))?
16        .to_string_lossy();
17    // A random part keeps two threads of one process writing the same path
18    // from sharing a temporary file.
19    let mut nonce = [0u8; 8];
20    getrandom::fill(&mut nonce).map_err(std::io::Error::other)?;
21    let tmp = parent.join(format!(
22        ".{name}.tmp.{}.{}",
23        std::process::id(),
24        hex::encode(nonce)
25    ));
26
27    let mut opts = std::fs::OpenOptions::new();
28    opts.write(true).create_new(true);
29    #[cfg(unix)]
30    {
31        use std::os::unix::fs::OpenOptionsExt;
32        opts.mode(0o600);
33    }
34
35    let result = (|| {
36        let mut f = opts.open(&tmp)?;
37        f.write_all(bytes)?;
38        f.sync_all()?;
39        drop(f);
40        // One atomic replace on every platform. Removing the target first on
41        // Windows raced with concurrent writers: a rename onto a target whose
42        // delete is still pending fails with ACCESS_DENIED.
43        crate::core::atomic_fs::replace_file(&tmp, path)
44    })();
45
46    if result.is_err() {
47        let _ = std::fs::remove_file(&tmp);
48    }
49    result
50}
51
52/// Creates `dir` (and its parents) and restricts it to its owner (0700 on Unix). Errors name
53/// the step and the path.
54pub fn private_dir(dir: &std::path::Path) -> std::io::Result<()> {
55    let step = |what: &str, e: std::io::Error| {
56        std::io::Error::new(e.kind(), format!("{what} {}: {e}", dir.display()))
57    };
58    std::fs::create_dir_all(dir).map_err(|e| step("create", e))?;
59    restrict_to_owner(dir).map_err(|e| step("restrict", e))
60}
61
62/// Sets `path` to mode 0700 on Unix, but only when its mode differs (GH #2227).
63/// Lives in `lean-ctx-fs`, so `core::data_dir` reaches it without an edge into
64/// this module.
65pub use lean_ctx_fs::atomic_fs::restrict_to_owner;
66
67/// Writes `dir/name` so that it is never readable by others and never seen half-written:
68/// [`private_dir`] and `write_secret_file`.
69pub fn write_private(dir: &std::path::Path, name: &str, bytes: &[u8]) -> std::io::Result<()> {
70    private_dir(dir)?;
71    write_secret_file(&dir.join(name), bytes).map_err(|e| {
72        std::io::Error::new(e.kind(), format!("write {name} in {}: {e}", dir.display()))
73    })
74}
75
76#[cfg(test)]
77mod tests {
78    use super::write_secret_file;
79
80    #[test]
81    fn concurrent_writers_of_one_path_all_succeed_and_leave_one_whole_file() {
82        let dir = tempfile::tempdir().unwrap();
83        let path = dir.path().join("secret.json");
84        let writers: Vec<_> = (0..8u8)
85            .map(|i| {
86                let path = path.clone();
87                std::thread::spawn(move || write_secret_file(&path, &[i; 64]))
88            })
89            .collect();
90        for writer in writers {
91            writer.join().unwrap().unwrap();
92        }
93        let written = std::fs::read(&path).unwrap();
94        assert_eq!(written.len(), 64);
95        assert!(written.iter().all(|byte| *byte == written[0]));
96        let names: Vec<_> = std::fs::read_dir(dir.path())
97            .unwrap()
98            .map(|entry| entry.unwrap().file_name())
99            .collect();
100        assert_eq!(names, ["secret.json"], "no temporary file is left");
101        #[cfg(unix)]
102        {
103            use std::os::unix::fs::PermissionsExt;
104            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
105            assert_eq!(mode & 0o777, 0o600);
106        }
107    }
108
109    /// GH #2227: a directory that is already 0700 is not chmodded again, so
110    /// its ctime stays put and watchers see no `IN_ATTRIB` event.
111    #[cfg(unix)]
112    #[test]
113    fn restrict_to_owner_leaves_a_private_dir_untouched() {
114        use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
115        let tmp = tempfile::tempdir().unwrap();
116        let dir = tmp.path().join("data");
117        std::fs::create_dir(&dir).unwrap();
118        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap();
119        let ctime = |p: &std::path::Path| {
120            let m = std::fs::metadata(p).unwrap();
121            (m.ctime(), m.ctime_nsec())
122        };
123        let before = ctime(&dir);
124        // Coarse ctime clocks: wait long enough for a chmod to be visible.
125        std::thread::sleep(std::time::Duration::from_millis(1100));
126        super::restrict_to_owner(&dir).unwrap();
127        super::private_dir(&dir).unwrap();
128        crate::core::data_dir::ensure_dir_permissions(&dir);
129        assert_eq!(
130            ctime(&dir),
131            before,
132            "an already private dir is not chmodded"
133        );
134    }
135
136    /// GH #2227: the check does not weaken the guarantee — a 0755 directory
137    /// is still tightened to 0700.
138    #[cfg(unix)]
139    #[test]
140    fn restrict_to_owner_still_tightens_an_open_dir() {
141        use std::os::unix::fs::PermissionsExt as _;
142        let tmp = tempfile::tempdir().unwrap();
143        let mode =
144            |p: &std::path::Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o7777;
145        for (i, restrict) in [
146            (|p: &std::path::Path| super::restrict_to_owner(p).unwrap()) as fn(&std::path::Path),
147            |p| super::private_dir(p).unwrap(),
148            |p| crate::core::data_dir::ensure_dir_permissions(p),
149        ]
150        .into_iter()
151        .enumerate()
152        {
153            let dir = tmp.path().join(format!("open-{i}"));
154            std::fs::create_dir(&dir).unwrap();
155            std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
156            restrict(&dir);
157            assert_eq!(mode(&dir), 0o700);
158        }
159    }
160}