Skip to main content

kumo_server_common/
acct.rs

1use crate::authn_authz::{Access, AuditRecord, AuthInfo, Identity};
2use crate::disk_space::{MinFree, MonitoredPath};
3use crate::log::{mark_existing_logs_as_done_in_dir, OpenedFile};
4use anyhow::Context;
5use chrono::Utc;
6use kumo_chrono_helper::{DateTime, Instant};
7use parking_lot::Mutex;
8use serde::{Deserialize, Serialize};
9use std::io::Write;
10use std::path::PathBuf;
11use std::sync::OnceLock;
12use std::time::Duration;
13use tokio::sync::mpsc::{channel, Receiver, Sender};
14use tokio::task::JoinHandle;
15use zstd::Encoder;
16
17static LOGGER: OnceLock<AcctLogger> = OnceLock::new();
18
19#[derive(Debug)]
20enum AcctCommand {
21    Record(AcctLogRecord),
22    /// Stop after writing every record queued ahead of this command.
23    Terminate,
24}
25
26struct AcctLogger {
27    tx: Sender<AcctCommand>,
28    /// Present until `shutdown` takes it to join the logger task.
29    task: Mutex<Option<JoinHandle<()>>>,
30}
31
32#[derive(Deserialize, Clone, Debug)]
33#[serde(deny_unknown_fields)]
34pub struct AuditLogParams {
35    /// Where to place the log files
36    pub log_dir: PathBuf,
37    /// How many uncompressed bytes to allow per file segment
38    #[serde(default = "AuditLogParams::default_max_file_size")]
39    pub max_file_size: u64,
40    /// Maximum number of outstanding items to be logged before
41    /// the submission will block; helps to avoid runaway issues
42    /// spiralling out of control.
43    #[serde(default = "AuditLogParams::default_back_pressure")]
44    pub back_pressure: usize,
45
46    /// The level of compression.
47    /// 0 - use the zstd default level (probably 3).
48    /// 1-21 are the explicitly configurable levels
49    #[serde(default = "AuditLogParams::default_compression_level")]
50    pub compression_level: i32,
51
52    #[serde(default, with = "duration_serde")]
53    pub max_segment_duration: Option<Duration>,
54
55    #[serde(default)]
56    pub min_free_space: MinFree,
57    #[serde(default)]
58    pub min_free_inodes: MinFree,
59
60    /// Log records for successfully granted authz
61    #[serde(default = "AuditLogParams::default_true")]
62    pub log_authz_allow: bool,
63
64    /// Log records for denied authz
65    #[serde(default = "AuditLogParams::default_true")]
66    pub log_authz_deny: bool,
67
68    /// Log records for successful authn
69    #[serde(default = "AuditLogParams::default_true")]
70    pub log_authn_ok: bool,
71
72    /// Log records for failed authn
73    #[serde(default = "AuditLogParams::default_true")]
74    pub log_authn_fail: bool,
75}
76
77impl AuditLogParams {
78    pub fn default_max_file_size() -> u64 {
79        1_000_000_000
80    }
81    pub fn default_back_pressure() -> usize {
82        128_000
83    }
84    pub fn default_compression_level() -> i32 {
85        0 // use the zstd default
86    }
87
88    pub fn default_true() -> bool {
89        true
90    }
91
92    pub async fn init(&self) -> anyhow::Result<()> {
93        let (tx, rx) = channel(self.back_pressure);
94        let params = self.clone();
95        let task = kumo_server_runtime::spawn_on_main("acct logger", async move {
96            if let Err(err) = params.acct_logger(rx).await {
97                tracing::error!(
98                    "AuditLogParams::acct_logger returned with error: {err}, \
99                    audit logging will cease to function until the next restart!"
100                );
101            }
102        })?;
103
104        let logger = AcctLogger {
105            tx,
106            task: Mutex::new(Some(task)),
107        };
108        if LOGGER.set(logger).is_err() {
109            anyhow::bail!("AuditLogParams::init must not be called more than once");
110        }
111
112        Ok(())
113    }
114
115    async fn acct_logger(self, mut rx: Receiver<AcctCommand>) -> anyhow::Result<()> {
116        if !config::is_validating() {
117            if let Err(err) = mark_existing_logs_as_done_in_dir(&self.log_dir) {
118                tracing::error!("{err}");
119            }
120            std::fs::create_dir_all(&self.log_dir).ok();
121            MonitoredPath {
122                name: format!("log dir {}", self.log_dir.display()),
123                path: self.log_dir.clone(),
124                min_free_space: self.min_free_space,
125                min_free_inodes: self.min_free_inodes,
126            }
127            .register();
128        }
129
130        let mut expire_counter = 0u16;
131        let mut current_file: Option<OpenedFile> = None;
132
133        loop {
134            let deadline = current_file.as_ref().and_then(|f| f.expires);
135
136            let mut check_expire = false;
137            let record = match deadline {
138                Some(deadline) => tokio::select! {
139                    cmd = rx.recv() => {
140                        match cmd {
141                            Some(AcctCommand::Record(r)) => Some(r),
142                            Some(AcctCommand::Terminate) | None => return Ok(()),
143                        }
144                    }
145                    _ = tokio::time::sleep_until(deadline.into()) => {
146                        check_expire = true;
147                        None
148                    }
149                },
150                None => match rx.recv().await {
151                    Some(AcctCommand::Record(r)) => Some(r),
152                    Some(AcctCommand::Terminate) | None => return Ok(()),
153                },
154            };
155
156            expire_counter = expire_counter.wrapping_add(1);
157            if expire_counter == 10_000 {
158                check_expire = true;
159            }
160
161            if check_expire {
162                let now = Instant::now();
163                let do_expire = current_file
164                    .as_ref()
165                    .and_then(|f| f.expires.map(|exp| exp <= now))
166                    .unwrap_or(false);
167
168                if do_expire {
169                    current_file.take();
170                }
171                expire_counter = 0;
172            }
173
174            if let Some(record) = record {
175                let should_log = match &record {
176                    AcctLogRecord::Authentication(authn) => {
177                        if authn.success {
178                            self.log_authn_ok
179                        } else {
180                            self.log_authn_fail
181                        }
182                    }
183                    AcctLogRecord::Authorization(authz) => match authz.access {
184                        Access::Allow => self.log_authz_allow,
185                        Access::Deny => self.log_authz_deny,
186                    },
187                };
188
189                if !should_log {
190                    continue;
191                }
192
193                if let Err(err) = self.open_file_if_needed(&mut current_file) {
194                    tracing::error!("{err}");
195                    continue;
196                }
197
198                if let Err(err) = self.do_record(&mut current_file, record) {
199                    tracing::error!("{err}");
200                    continue;
201                }
202            }
203        }
204    }
205
206    fn open_file_if_needed(&self, current_file: &mut Option<OpenedFile>) -> anyhow::Result<()> {
207        if current_file.is_some() {
208            return Ok(());
209        }
210        let now = DateTime::now();
211
212        let base_name = now.format("acct-%Y%m%d-%H%M%S%.f").to_string();
213
214        let name = self.log_dir.join(base_name);
215        // They might be trying to use multiple directories below
216        // the configured log_dir, so adjust our idea of its parent
217        // dir
218        let log_dir = name
219            .parent()
220            .expect("log_dir.join ensures we always have a parent");
221
222        let f = match std::fs::OpenOptions::new()
223            .append(true)
224            .create(true)
225            .open(&name)
226        {
227            Ok(f) => f,
228            Err(err) => {
229                if err.kind() == std::io::ErrorKind::NotFound {
230                    match std::fs::create_dir_all(log_dir) {
231                        Ok(_) => {
232                            // Try opening it again now
233                            std::fs::OpenOptions::new()
234                                .append(true)
235                                .create(true)
236                                .open(&name)
237                                .with_context(|| format!("open log file {name:?}"))?
238                        }
239                        Err(dir_err) => {
240                            anyhow::bail!(
241                                "open log file {name:?}: failed: {err:#?}. \
242                                    Additionally, attempting to create dir {} failed: {dir_err:#?}",
243                                log_dir.display()
244                            );
245                        }
246                    }
247                } else {
248                    anyhow::bail!("open log file {name:?}: failed: {err:#?}");
249                }
250            }
251        };
252
253        let file = OpenedFile {
254            file: Encoder::new(f, self.compression_level).context("set up zstd encoder")?,
255            name,
256            written: 0,
257            expires: self
258                .max_segment_duration
259                .map(|duration| Instant::now().saturating_add(duration)),
260        };
261
262        current_file.replace(file);
263        Ok(())
264    }
265
266    fn do_record(
267        &self,
268        current_file: &mut Option<OpenedFile>,
269        record: AcctLogRecord,
270    ) -> anyhow::Result<()> {
271        if let Some(file) = current_file {
272            let mut record_text = Vec::new();
273            serde_json::to_writer(&mut record_text, &record).context("serializing record")?;
274            record_text.push(b'\n');
275
276            file.file
277                .write_all(&record_text)
278                .with_context(|| format!("writing record to {}", file.name.display()))?;
279            file.written += record_text.len() as u64;
280
281            let need_rotate = file.written >= self.max_file_size
282                || file
283                    .expires
284                    .map(|exp| exp <= Instant::now())
285                    .unwrap_or(false);
286
287            if need_rotate {
288                current_file.take();
289            }
290        }
291        Ok(())
292    }
293}
294
295#[derive(Serialize, Deserialize, Debug)]
296#[serde(tag = "type")]
297pub enum AcctLogRecord {
298    Authentication(AuthnAuditRecord),
299    Authorization(AuditRecord),
300}
301
302impl AcctLogRecord {
303    pub fn timestamp(&self) -> &DateTime<Utc> {
304        match self {
305            Self::Authentication(authn) => &authn.timestamp,
306            Self::Authorization(authz) => &authz.timestamp,
307        }
308    }
309
310    pub fn is_allow(&self) -> bool {
311        match self {
312            Self::Authentication(authn) => authn.success,
313            Self::Authorization(authz) => authz.access == Access::Allow,
314        }
315    }
316}
317
318async fn log_acct(record: AcctLogRecord) -> anyhow::Result<()> {
319    tracing::trace!("Audit: {record:?}");
320    if let Some(logger) = LOGGER.get() {
321        logger.tx.send(AcctCommand::Record(record)).await?;
322    }
323    Ok(())
324}
325
326/// Stop the audit logger and finalize its open log segment. Records
327/// submitted before this call are written first. Blocks until the
328/// logger task has exited. Does nothing if the logger was never
329/// configured.
330pub async fn shutdown() {
331    let Some(logger) = LOGGER.get() else {
332        return;
333    };
334    logger.tx.send(AcctCommand::Terminate).await.ok();
335    let task = logger.task.lock().take();
336    if let Some(task) = task {
337        if let Err(err) = task.await {
338            tracing::error!("acct logger task failed: {err:#}");
339        }
340    }
341}
342
343pub async fn log_authz(record: AuditRecord) -> anyhow::Result<()> {
344    log_acct(AcctLogRecord::Authorization(record)).await
345}
346
347#[derive(Serialize, Deserialize, Debug)]
348pub struct AuthnAuditRecord {
349    /// When the event occurred
350    pub timestamp: DateTime<Utc>,
351    /// Who they were attempting to authenticate as
352    pub attempted_identity: Identity,
353    /// Whether the attempt was successful
354    pub success: bool,
355    /// The resulting authentication info
356    pub auth_info: AuthInfo,
357}
358
359pub async fn log_authn(record: AuthnAuditRecord) -> anyhow::Result<()> {
360    log_acct(AcctLogRecord::Authentication(record)).await
361}
362
363#[cfg(test)]
364mod test {
365    use super::*;
366    use crate::authn_authz::IdentityContext;
367
368    /// Builds params that log everything into `log_dir`, with no time based
369    /// rotation and the given size limit.
370    fn params(log_dir: &std::path::Path, max_file_size: u64) -> AuditLogParams {
371        AuditLogParams {
372            log_dir: log_dir.to_path_buf(),
373            max_file_size,
374            back_pressure: 16,
375            compression_level: AuditLogParams::default_compression_level(),
376            max_segment_duration: None,
377            min_free_space: MinFree::default(),
378            min_free_inodes: MinFree::default(),
379            log_authz_allow: true,
380            log_authz_deny: true,
381            log_authn_ok: true,
382            log_authn_fail: true,
383        }
384    }
385
386    fn authn_record(identity: &str) -> AcctLogRecord {
387        AcctLogRecord::Authentication(AuthnAuditRecord {
388            timestamp: DateTime::now(),
389            attempted_identity: Identity {
390                identity: identity.to_string(),
391                context: IdentityContext::SmtpAuthPlainAuthentication,
392            },
393            success: true,
394            auth_info: AuthInfo::default(),
395        })
396    }
397
398    /// Decode every segment in `dir`, returning the identity from each
399    /// record in filename order.
400    fn read_identities(dir: &std::path::Path) -> anyhow::Result<Vec<Vec<String>>> {
401        let mut paths: Vec<_> = std::fs::read_dir(dir)?
402            .map(|entry| entry.map(|e| e.path()))
403            .collect::<Result<_, _>>()?;
404        paths.sort();
405        paths
406            .iter()
407            .map(|path| {
408                let data = zstd::stream::decode_all(std::fs::File::open(path)?)?;
409                String::from_utf8(data)?
410                    .lines()
411                    .map(|line| match serde_json::from_str(line)? {
412                        AcctLogRecord::Authentication(authn) => {
413                            Ok(authn.attempted_identity.identity)
414                        }
415                        other => anyhow::bail!("unexpected record {other:?}"),
416                    })
417                    .collect()
418            })
419            .collect()
420    }
421
422    /// With no size or time based rotation, shutdown is required to complete
423    /// the zstd frame.
424    #[tokio::test]
425    async fn shutdown_finalizes_open_segment() -> anyhow::Result<()> {
426        let dir = tempfile::tempdir()?;
427        params(dir.path(), AuditLogParams::default_max_file_size())
428            .init()
429            .await?;
430
431        let AcctLogRecord::Authentication(record) = authn_record("daniel") else {
432            unreachable!()
433        };
434        log_authn(record).await?;
435
436        shutdown().await;
437
438        k9::assert_equal!(
439            read_identities(dir.path())?,
440            vec![vec!["daniel".to_string()]]
441        );
442        Ok(())
443    }
444
445    #[test]
446    fn size_limit_rotates_segment() -> anyhow::Result<()> {
447        let dir = tempfile::tempdir()?;
448        let params = params(dir.path(), 1);
449        let mut current_file = None;
450
451        for identity in ["first", "second"] {
452            params.open_file_if_needed(&mut current_file)?;
453            params.do_record(&mut current_file, authn_record(identity))?;
454            assert!(
455                current_file.is_none(),
456                "segment must rotate after {identity}"
457            );
458        }
459
460        k9::assert_equal!(
461            read_identities(dir.path())?,
462            vec![vec!["first".to_string()], vec!["second".to_string()]]
463        );
464        Ok(())
465    }
466}