返回 CodeWhale
private_log.rs
根目录 / crates / runtime / src / private_log.rs
1 use std::io::Write as _;
2 use std::path::Path;
3
4 /// Open or create a file for appending at `path`, optionally syncing after
5 /// every write. Use this for append-only logs like `audit.log`.
6 ///
7 /// The returned `BufWriter<fs::File>` wraps the append handle. Call
8 /// `.flush()` followed by `.get_ref().sync_all()` after each batch.
9 pub fn open_append(path: &Path) -> std::io::Result<std::io::BufWriter<std::fs::File>> {
10 if let Some(parent) = path.parent() {
11 std::fs::create_dir_all(parent)?;
12 }
13 let file = private_log_options().append(true).open(path)?;
14 restrict_to_owner(&file)?;
15 Ok(std::io::BufWriter::new(file))
16 }
17
18 /// Open options for an owner-only log or lock file: created 0600 and never
19 /// opened through a link at the final component (Unix). Callers add the
20 /// access mode they need.
21 pub fn private_log_options() -> std::fs::OpenOptions {
22 let mut options = std::fs::OpenOptions::new();
23 options.create(true);
24 #[cfg(unix)]
25 {
26 use std::os::unix::fs::OpenOptionsExt;
27 options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
28 }
29 options
30 }
31
32 /// Tighten a log created by an earlier version at the default mode. No-op
33 /// outside Unix.
34 ///
35 /// Best effort on purpose. The file was created `0600`, so this only narrows a
36 /// log left wider by an earlier version or a different umask — and a mount that
37 /// assigns modes itself (HarmonyOS hmdfs answers `EPERM` to every `chmod`) will
38 /// refuse it for every object it holds. Failing here would turn a write that
39 /// already succeeded into "permission denied"; a log left wide is reported
40 /// instead, so an operator can still see it.
41 pub fn restrict_to_owner(file: &std::fs::File) -> std::io::Result<()> {
42 #[cfg(unix)]
43 {
44 use std::os::unix::fs::PermissionsExt as _;
45 if file
46 .set_permissions(std::fs::Permissions::from_mode(0o600))
47 .is_err()
48 && file
49 .metadata()
50 .is_ok_and(|metadata| metadata.permissions().mode() & 0o077 != 0)
51 {
52 tracing::warn!(
53 "a private log could not be narrowed to 0600 and is still readable by group or \
54 other; this filesystem does not apply Unix mode bits"
55 );
56 }
57 }
58 #[cfg(not(unix))]
59 let _ = file;
60 Ok(())
61 }
62
63 /// Flush a `BufWriter` wrapping a `File`, then `fsync` the underlying file.
64 pub fn flush_and_sync(writer: &mut std::io::BufWriter<std::fs::File>) -> std::io::Result<()> {
65 writer.flush()?;
66 writer.get_ref().sync_all()
67 }
68
69 #[cfg(test)]
70 mod tests {
71 use super::{flush_and_sync, open_append};
72
73 #[test]
74 fn flush_and_sync_writes_and_syncs() {
75 use std::io::Write as _;
76 let tmp = tempfile::tempdir().expect("tempdir");
77 let path = tmp.path().join("append.log");
78 {
79 let mut writer = open_append(&path).expect("open_append");
80 writeln!(writer, "line 1").expect("write");
81 flush_and_sync(&mut writer).expect("flush_and_sync");
82 writeln!(writer, "line 2").expect("write");
83 flush_and_sync(&mut writer).expect("flush_and_sync");
84 }
85 let content = std::fs::read_to_string(&path).expect("read");
86 assert_eq!(content, "line 1\nline 2\n");
87 }
88
89 #[cfg(unix)]
90 #[test]
91 fn append_logs_are_owner_only_and_not_opened_through_links() {
92 use std::os::unix::fs::PermissionsExt;
93 let dir = tempfile::tempdir().expect("tempdir");
94
95 let log = dir.path().join("audit.log");
96 drop(open_append(&log).expect("open"));
97 let mode = std::fs::metadata(&log).unwrap().permissions().mode() & 0o777;
98 assert_eq!(mode, 0o600);
99
100 // A log left world-readable by an earlier version is tightened.
101 std::fs::set_permissions(&log, std::fs::Permissions::from_mode(0o644)).unwrap();
102 drop(open_append(&log).expect("reopen"));
103 let mode = std::fs::metadata(&log).unwrap().permissions().mode() & 0o777;
104 assert_eq!(mode, 0o600);
105
106 let target = dir.path().join("elsewhere");
107 std::fs::write(&target, "").unwrap();
108 let link = dir.path().join("linked.log");
109 std::os::unix::fs::symlink(&target, &link).unwrap();
110 assert!(open_append(&link).is_err());
111 }
112 }
113
113 lines RUST