codewhale_runtime/
private_log.rs1use std::io::Write as _;
2use std::path::Path;
3
4pub 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
18pub 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
32pub 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
63pub 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)]
70mod 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 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}