Skip to main content

reddb_server/runtime/
audit_query.rs

1//! Audit log query / replay helpers.
2//!
3//! Backs the `GET /admin/audit` endpoint. Reads the active
4//! `.audit.log` plus rotated siblings (`.audit.log.<ms>.zst`),
5//! parses each line into [`AuditEvent`], and applies the request
6//! filters in memory. The audit volume on a typical RedDB deploy is
7//! orders of magnitude smaller than the data plane (admin actions,
8//! auth events, lease transitions) so a linear scan over the rotated
9//! tail is acceptable. If the volume ever justifies it, a real index
10//! lives one refactor away — slot a sled / parquet sidecar in here
11//! without touching the public surface.
12
13use std::path::Path;
14
15use crate::runtime::audit_log::{AuditEvent, Outcome};
16
17/// Query filters. All fields are optional; an empty `Query` returns
18/// the entire window up to `limit`.
19#[derive(Debug, Clone, Default)]
20pub struct AuditQuery {
21    pub since_ms: Option<u128>,
22    pub until_ms: Option<u128>,
23    pub principal: Option<String>,
24    pub tenant: Option<String>,
25    /// Prefix match on `action` (e.g. `auth/`, `admin/`,
26    /// `lease/acquire`). Empty string matches everything.
27    pub action_prefix: Option<String>,
28    pub outcome: Option<Outcome>,
29    /// Hard cap on the number of returned events. Server should clamp
30    /// this to a sensible maximum (e.g. 1000) before passing through.
31    pub limit: usize,
32}
33
34impl AuditQuery {
35    pub fn new() -> Self {
36        Self {
37            limit: 100,
38            ..Default::default()
39        }
40    }
41
42    fn matches(&self, ev: &AuditEvent) -> bool {
43        if let Some(since) = self.since_ms {
44            if ev.ts < since {
45                return false;
46            }
47        }
48        if let Some(until) = self.until_ms {
49            if ev.ts > until {
50                return false;
51            }
52        }
53        if let Some(principal) = &self.principal {
54            match &ev.principal {
55                Some(p) if p == principal => {}
56                _ => return false,
57            }
58        }
59        if let Some(tenant) = &self.tenant {
60            match &ev.tenant {
61                Some(t) if t == tenant => {}
62                _ => return false,
63            }
64        }
65        if let Some(prefix) = &self.action_prefix {
66            if !ev.action.starts_with(prefix) {
67                return false;
68            }
69        }
70        if let Some(outcome) = self.outcome {
71            if ev.outcome != outcome {
72                return false;
73            }
74        }
75        true
76    }
77}
78
79/// Run `query` against the audit log rooted at `active_path` (the
80/// current `.audit.log`). Walks the active file plus every sibling
81/// rotated archive (`.audit.log.<ms>.zst`), oldest-first by filename.
82/// Returns the matching events in chronological order, capped at
83/// `query.limit`.
84pub fn run_query(active_path: &Path, query: &AuditQuery) -> Vec<AuditEvent> {
85    if active_path.as_os_str().is_empty() {
86        return Vec::new();
87    }
88    let mut events: Vec<AuditEvent> = Vec::new();
89    let parent = active_path.parent().unwrap_or_else(|| Path::new("."));
90
91    let mut rotated: Vec<(u128, std::path::PathBuf)> = Vec::new();
92    if let Ok(rd) = std::fs::read_dir(parent) {
93        for entry in rd.flatten() {
94            let name = entry.file_name();
95            let Some(name_s) = name.to_str() else {
96                continue;
97            };
98            if let Some(ts) =
99                reddb_file::layout::parse_audit_log_rotated_timestamp(active_path, name_s)
100            {
101                rotated.push((ts, entry.path()));
102            }
103        }
104    }
105    rotated.sort_by_key(|(ts, _)| *ts);
106
107    for (_, path) in &rotated {
108        let bytes = match std::fs::read(path) {
109            Ok(b) => b,
110            Err(_) => continue,
111        };
112        let plain = if path
113            .extension()
114            .and_then(|e| e.to_str())
115            .map(|e| e == reddb_file::layout::AUDIT_LOG_ROTATED_COMPRESSED_EXTENSION)
116            .unwrap_or(false)
117        {
118            match zstd::bulk::decompress(&bytes, 256 * 1024 * 1024) {
119                Ok(p) => p,
120                Err(_) => continue,
121            }
122        } else {
123            bytes
124        };
125        ingest_buffer(&plain, query, &mut events);
126    }
127
128    if let Ok(active_bytes) = std::fs::read(active_path) {
129        ingest_buffer(&active_bytes, query, &mut events);
130    }
131
132    if events.len() > query.limit {
133        let take = query.limit;
134        let drop = events.len() - take;
135        events.drain(0..drop);
136    }
137    events
138}
139
140fn ingest_buffer(bytes: &[u8], query: &AuditQuery, out: &mut Vec<AuditEvent>) {
141    let Ok(text) = std::str::from_utf8(bytes) else {
142        return;
143    };
144    for line in text.lines() {
145        if line.is_empty() {
146            continue;
147        }
148        let Some(ev) = AuditEvent::parse_line(line) else {
149            continue;
150        };
151        if query.matches(&ev) {
152            out.push(ev);
153        }
154    }
155}
156
157/// Render a list of events as a JSON array (returned by the HTTP
158/// query handler). Stable field set so dashboards stay locked.
159pub fn events_to_json_array(events: &[AuditEvent]) -> crate::json::Value {
160    use crate::json::{Map, Value};
161    let mut arr: Vec<Value> = Vec::with_capacity(events.len());
162    for ev in events {
163        let line = ev.to_json_line(None);
164        if let Ok(v) = crate::json::from_str::<Value>(&line) {
165            arr.push(v);
166        }
167    }
168    let mut obj = Map::new();
169    obj.insert("count".to_string(), Value::Number(events.len() as f64));
170    obj.insert("events".to_string(), Value::Array(arr));
171    Value::Object(obj)
172}
173
174// ---------------------------------------------------------------------------
175// Param parsing
176// ---------------------------------------------------------------------------
177
178/// Parse RFC-3339 with second precision OR an integer ms epoch. The
179/// query endpoint accepts either form per the spec; we keep the
180/// parser tiny so we don't pull `chrono`.
181pub fn parse_time_arg(raw: &str) -> Option<u128> {
182    let trimmed = raw.trim();
183    if trimmed.is_empty() {
184        return None;
185    }
186    if let Ok(ms) = trimmed.parse::<u128>() {
187        return Some(ms);
188    }
189    parse_rfc3339_ms(trimmed)
190}
191
192/// Tiny RFC 3339 -> ms parser. Accepts `YYYY-MM-DDTHH:MM:SSZ` and
193/// `YYYY-MM-DDTHH:MM:SS.mmmZ`. Rejects anything with a non-Z offset
194/// — the audit log writes UTC and we want callers to pass UTC too.
195pub fn parse_rfc3339_ms(s: &str) -> Option<u128> {
196    let bytes = s.as_bytes();
197    if bytes.len() < 20 {
198        return None;
199    }
200    if !s.ends_with('Z') {
201        return None;
202    }
203    let year: i64 = s.get(0..4)?.parse().ok()?;
204    let month: u32 = s.get(5..7)?.parse().ok()?;
205    let day: u32 = s.get(8..10)?.parse().ok()?;
206    if &bytes[4..5] != b"-" || &bytes[7..8] != b"-" || &bytes[10..11] != b"T" {
207        return None;
208    }
209    let hour: u64 = s.get(11..13)?.parse().ok()?;
210    let minute: u64 = s.get(14..16)?.parse().ok()?;
211    let second: u64 = s.get(17..19)?.parse().ok()?;
212    if &bytes[13..14] != b":" || &bytes[16..17] != b":" {
213        return None;
214    }
215    let mut ms_extra: u64 = 0;
216    if bytes.len() > 20 {
217        // Either `.mmm` then `Z`, or some other suffix.
218        if &bytes[19..20] == b"." {
219            // Up to the `Z`.
220            let dot_end = s.len() - 1; // skip Z
221            let frac = s.get(20..dot_end)?;
222            if frac.len() > 9 || frac.is_empty() {
223                return None;
224            }
225            // pad / truncate to 3 digits for ms.
226            let mut digits = String::with_capacity(3);
227            for c in frac.chars().take(3) {
228                if !c.is_ascii_digit() {
229                    return None;
230                }
231                digits.push(c);
232            }
233            while digits.len() < 3 {
234                digits.push('0');
235            }
236            ms_extra = digits.parse().ok()?;
237        } else if &bytes[19..20] != b"Z" {
238            return None;
239        }
240    }
241    let days = days_from_civil(year, month, day);
242    let secs =
243        (days as i128) * 86_400 + (hour as i128) * 3600 + (minute as i128) * 60 + second as i128;
244    let ms = secs * 1000 + ms_extra as i128;
245    if ms < 0 {
246        return None;
247    }
248    Some(ms as u128)
249}
250
251/// Howard Hinnant's days_from_civil algorithm. Mirrors the inverse
252/// `civil_from_days` already in `audit_log.rs`.
253fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
254    let y = if m <= 2 { y - 1 } else { y };
255    let era = if y >= 0 { y } else { y - 399 } / 400;
256    let yoe = (y - era * 400) as u64;
257    let m = m as u64;
258    let d = d as u64;
259    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
260    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
261    era * 146_097 + (doe as i64) - 719_468
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267    use crate::runtime::audit_log::{AuditAuthSource, AuditEvent, AuditLogger, Outcome};
268    use std::path::PathBuf;
269    use std::time::Duration;
270
271    fn temp_path(tag: &str) -> PathBuf {
272        let mut p = std::env::temp_dir();
273        p.push(format!(
274            "reddb-audit-query-{}-{}-{}",
275            tag,
276            std::process::id(),
277            crate::utils::now_unix_nanos()
278        ));
279        std::fs::create_dir_all(&p).unwrap();
280        p.push("data.rdb");
281        p
282    }
283
284    #[test]
285    fn filters_by_principal_and_action_prefix() {
286        let data = temp_path("filter");
287        let logger = AuditLogger::for_data_path(&data);
288        for who in ["alice", "bob", "alice", "carol"] {
289            logger.record_event(
290                AuditEvent::builder("auth/login.ok")
291                    .principal(who)
292                    .source(AuditAuthSource::Password)
293                    .build(),
294            );
295        }
296        logger.record_event(
297            AuditEvent::builder("admin/shutdown")
298                .principal("alice")
299                .source(AuditAuthSource::Session)
300                .outcome(Outcome::Success)
301                .build(),
302        );
303        assert!(logger.wait_idle(Duration::from_secs(2)));
304
305        let q = AuditQuery {
306            principal: Some("alice".to_string()),
307            action_prefix: Some("auth/".to_string()),
308            limit: 100,
309            ..Default::default()
310        };
311        let hits = run_query(logger.path(), &q);
312        assert_eq!(hits.len(), 2, "expected two alice/auth lines");
313        assert!(hits.iter().all(|e| e.principal.as_deref() == Some("alice")));
314        assert!(hits.iter().all(|e| e.action.starts_with("auth/")));
315    }
316
317    #[test]
318    fn parse_time_accepts_rfc3339_and_ms() {
319        assert_eq!(
320            parse_time_arg("2024-02-29T12:34:56.789Z"),
321            Some(1_709_210_096_789)
322        );
323        assert_eq!(parse_time_arg("1709210096789"), Some(1_709_210_096_789));
324        assert_eq!(parse_time_arg("not a time"), None);
325    }
326
327    #[test]
328    fn limit_caps_oldest_off() {
329        let data = temp_path("limit");
330        let logger = AuditLogger::for_data_path(&data);
331        for i in 0..10 {
332            logger.record_event(AuditEvent::builder(format!("test/n/{i}")).build());
333        }
334        assert!(logger.wait_idle(Duration::from_secs(2)));
335        let q = AuditQuery {
336            limit: 3,
337            ..Default::default()
338        };
339        let hits = run_query(logger.path(), &q);
340        assert_eq!(hits.len(), 3);
341        // Newest 3 are kept.
342        assert_eq!(hits[0].action, "test/n/7");
343        assert_eq!(hits[2].action, "test/n/9");
344    }
345}