1use serde::Serialize;
6use std::time::{SystemTime, UNIX_EPOCH};
7
8const FEZ_MUTATION_MESSAGE_ID: &str = "fe2c0ffee0000400a8b1mutati0naud1";
10
11#[derive(Serialize, Clone, Debug)]
13pub struct AuditRecord {
14 pub actor: String,
16 pub target_host: String,
18 pub operation: String,
20 pub unit: String,
22 pub result: String,
24 #[serde(skip_serializing_if = "Option::is_none")]
26 pub error: Option<String>,
27 pub correlation_id: String,
29 pub timestamp_unix_ms: u128,
31}
32
33impl AuditRecord {
34 fn priority(&self) -> &'static str {
35 match self.result.as_str() {
36 "error" => "3", "attempt" => "5", _ => "6", }
40 }
41}
42
43#[derive(Clone, Debug)]
47pub enum Outcome {
48 Attempt,
50 Ok,
52 Error(String),
54}
55
56impl Outcome {
57 fn result(&self) -> &'static str {
59 match self {
60 Outcome::Attempt => "attempt",
61 Outcome::Ok => "ok",
62 Outcome::Error(_) => "error",
63 }
64 }
65
66 fn into_error(self) -> Option<String> {
68 match self {
69 Outcome::Error(e) => Some(e),
70 _ => None,
71 }
72 }
73}
74
75#[derive(Clone, Debug)]
80pub struct AuditContext {
81 actor: String,
82 target_host: String,
83 operation: String,
84 unit: String,
85 correlation_id: String,
86}
87
88impl AuditContext {
89 pub fn new(
91 actor: &str,
92 target_host: &str,
93 operation: &str,
94 unit: &str,
95 correlation_id: &str,
96 ) -> Self {
97 AuditContext {
98 actor: actor.into(),
99 target_host: target_host.into(),
100 operation: operation.into(),
101 unit: unit.into(),
102 correlation_id: correlation_id.into(),
103 }
104 }
105
106 #[must_use]
108 pub fn record(&self, outcome: Outcome) -> AuditRecord {
109 let timestamp_unix_ms = SystemTime::now()
110 .duration_since(UNIX_EPOCH)
111 .map(|d| d.as_millis())
112 .unwrap_or(0);
113 let result = outcome.result().to_string();
114 AuditRecord {
115 actor: self.actor.clone(),
116 target_host: self.target_host.clone(),
117 operation: self.operation.clone(),
118 unit: self.unit.clone(),
119 result,
120 error: outcome.into_error(),
121 correlation_id: self.correlation_id.clone(),
122 timestamp_unix_ms,
123 }
124 }
125}
126
127pub fn actor() -> String {
129 std::env::var("USER")
130 .or_else(|_| std::env::var("LOGNAME"))
131 .unwrap_or_else(|_| "unknown".into())
132}
133
134pub fn correlation_id() -> String {
136 use std::sync::atomic::{AtomicU64, Ordering};
137 static SEQ: AtomicU64 = AtomicU64::new(0);
138 let nanos = SystemTime::now()
139 .duration_since(UNIX_EPOCH)
140 .map(|d| d.as_nanos())
141 .unwrap_or(0);
142 let pid = std::process::id();
143 let seq = SEQ.fetch_add(1, Ordering::Relaxed);
144 format!("{nanos:x}-{pid:x}-{seq:x}")
145}
146
147fn push_field(out: &mut Vec<u8>, key: &str, value: &str) {
151 out.extend_from_slice(key.as_bytes());
152 if value.contains('\n') {
153 out.push(b'\n');
155 out.extend_from_slice(&(value.len() as u64).to_le_bytes());
156 } else {
157 out.push(b'=');
159 }
160 out.extend_from_slice(value.as_bytes());
161 out.push(b'\n');
162}
163
164pub fn encode_journal_fields(rec: &AuditRecord) -> Vec<u8> {
166 let mut out = Vec::new();
167 let message = format!(
168 "fez {} {} on {}: {}",
169 rec.operation, rec.unit, rec.target_host, rec.result
170 );
171 push_field(&mut out, "MESSAGE", &message);
172 push_field(&mut out, "MESSAGE_ID", FEZ_MUTATION_MESSAGE_ID);
173 push_field(&mut out, "SYSLOG_IDENTIFIER", "fez");
174 push_field(&mut out, "PRIORITY", rec.priority());
175 push_field(&mut out, "FEZ_ACTOR", &rec.actor);
176 push_field(&mut out, "FEZ_TARGET_HOST", &rec.target_host);
177 push_field(&mut out, "FEZ_OPERATION", &rec.operation);
178 push_field(&mut out, "FEZ_UNIT", &rec.unit);
179 push_field(&mut out, "FEZ_RESULT", &rec.result);
180 push_field(&mut out, "FEZ_CORRELATION_ID", &rec.correlation_id);
181 if let Some(err) = &rec.error {
182 push_field(&mut out, "FEZ_ERROR", err);
183 }
184 out
185}
186
187pub trait AuditSink {
189 fn write(&self, rec: &AuditRecord);
191}
192
193pub struct NoopSink;
195impl AuditSink for NoopSink {
196 fn write(&self, _rec: &AuditRecord) {}
197}
198
199pub struct FileSink {
201 pub path: std::path::PathBuf,
203}
204impl AuditSink for FileSink {
205 fn write(&self, rec: &AuditRecord) {
206 use std::io::Write;
207 if let Ok(mut f) = std::fs::OpenOptions::new()
208 .create(true)
209 .append(true)
210 .open(&self.path)
211 {
212 if let Ok(line) = serde_json::to_string(rec) {
213 let _ = writeln!(f, "{line}");
214 }
215 }
216 }
217}
218
219pub struct JournalSink;
222impl AuditSink for JournalSink {
223 fn write(&self, rec: &AuditRecord) {
224 let buf = encode_journal_fields(rec);
225 if let Ok(sock) = std::os::unix::net::UnixDatagram::unbound() {
226 let _ = sock.send_to(&buf, "/run/systemd/journal/socket");
227 }
228 }
229}
230
231pub fn sink_from_env() -> Box<dyn AuditSink> {
233 match std::env::var("FEZ_AUDIT").ok().as_deref() {
234 Some("off") | Some("0") => Box::new(NoopSink),
235 Some(v) if v.starts_with("file:") => Box::new(FileSink {
236 path: std::path::PathBuf::from(&v["file:".len()..]),
237 }),
238 _ => Box::new(JournalSink),
239 }
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245
246 fn ctx() -> AuditContext {
247 AuditContext::new("alice", "localhost", "stop", "chronyd.service", "abc-1-0")
248 }
249
250 fn rec(result: &str, error: Option<String>) -> AuditRecord {
251 let outcome = match (result, error) {
252 ("attempt", _) => Outcome::Attempt,
253 ("ok", _) => Outcome::Ok,
254 ("error", Some(e)) => Outcome::Error(e),
255 ("error", None) => Outcome::Error(String::new()),
256 (other, _) => panic!("unexpected result {other}"),
257 };
258 ctx().record(outcome)
259 }
260
261 #[test]
262 fn context_records_share_invocation_fields() {
263 let c = ctx();
264 let attempt = c.record(Outcome::Attempt);
265 let ok = c.record(Outcome::Ok);
266 assert_eq!(attempt.actor, "alice");
267 assert_eq!(attempt.target_host, "localhost");
268 assert_eq!(attempt.operation, "stop");
269 assert_eq!(attempt.unit, "chronyd.service");
270 assert_eq!(attempt.correlation_id, "abc-1-0");
271 assert_eq!(attempt.operation, ok.operation);
273 assert_eq!(attempt.correlation_id, ok.correlation_id);
274 }
275
276 #[test]
277 fn outcome_maps_to_result_and_error() {
278 assert_eq!(ctx().record(Outcome::Attempt).result, "attempt");
279 assert_eq!(ctx().record(Outcome::Attempt).error, None);
280 assert_eq!(ctx().record(Outcome::Ok).result, "ok");
281 assert_eq!(ctx().record(Outcome::Ok).error, None);
282 let err = ctx().record(Outcome::Error("boom".into()));
283 assert_eq!(err.result, "error");
284 assert_eq!(err.error.as_deref(), Some("boom"));
285 }
286
287 #[test]
288 fn encodes_plain_fields() {
289 let bytes = encode_journal_fields(&rec("ok", None));
290 let text = String::from_utf8_lossy(&bytes);
291 assert!(text.contains("SYSLOG_IDENTIFIER=fez\n"));
292 assert!(text.contains("FEZ_UNIT=chronyd.service\n"));
293 assert!(text.contains("FEZ_OPERATION=stop\n"));
294 assert!(text.contains("FEZ_RESULT=ok\n"));
295 assert!(text.contains("PRIORITY=6\n"));
296 assert!(!text.contains("FEZ_ERROR"));
298 }
299
300 #[test]
301 fn encodes_newline_value_in_binary_form() {
302 let bytes = encode_journal_fields(&rec("error", Some("line one\nline two".into())));
303 let needle = b"FEZ_ERROR\n";
305 let pos = bytes
306 .windows(needle.len())
307 .position(|w| w == needle)
308 .expect("FEZ_ERROR key present in binary form");
309 let len_start = pos + needle.len();
310 let len_bytes: [u8; 8] = bytes[len_start..len_start + 8].try_into().unwrap();
311 assert_eq!(
312 u64::from_le_bytes(len_bytes) as usize,
313 "line one\nline two".len()
314 );
315 }
316
317 #[test]
318 fn file_sink_appends_json_lines() {
319 let path =
320 std::env::temp_dir().join(format!("fez-audit-test-{}.jsonl", std::process::id()));
321 let _ = std::fs::remove_file(&path);
322 let sink = FileSink { path: path.clone() };
323 sink.write(&rec("attempt", None));
324 sink.write(&rec("ok", None));
325 let body = std::fs::read_to_string(&path).unwrap();
326 let lines: Vec<&str> = body.lines().collect();
327 assert_eq!(lines.len(), 2);
328 assert!(lines[0].contains("\"result\":\"attempt\""));
329 assert!(lines[1].contains("\"result\":\"ok\""));
330 let _ = std::fs::remove_file(&path);
331 }
332
333 #[test]
334 fn priority_varies_by_result() {
335 assert_eq!(rec("error", Some("x".into())).priority(), "3");
336 assert_eq!(rec("attempt", None).priority(), "5");
337 assert_eq!(rec("ok", None).priority(), "6");
338 }
339}