1#![deny(missing_docs)]
34#![warn(clippy::all, clippy::pedantic)]
35#![allow(clippy::module_name_repetitions)]
36
37mod async_backend;
38mod backends;
39mod context;
40mod error;
41mod file;
42mod filter;
43#[cfg(feature = "hlc")]
44mod hlc;
45mod integrity;
46mod logger;
47mod macros;
48mod processor;
49mod provenance;
50mod redact;
51
52#[cfg(feature = "tracing")]
53mod tracing_bridge;
54
55#[cfg(feature = "hmac-chain")]
56mod hmac_chain;
57
58#[cfg(feature = "ocsf")]
59pub mod ocsf;
60
61pub use async_backend::*;
62pub use backends::*;
63pub use context::*;
64pub use error::*;
65pub use file::*;
66pub use filter::*;
67#[cfg(feature = "hlc")]
68pub use hlc::*;
69#[cfg(feature = "hmac-chain")]
70pub use hmac_chain::*;
71pub use integrity::*;
72pub use logger::*;
73pub use processor::*;
74pub use provenance::*;
75pub use redact::*;
76#[cfg(feature = "tracing")]
77pub use tracing_bridge::*;
78
79use serde::{Deserialize, Serialize};
80use std::collections::HashMap;
81use std::net::SocketAddr;
82use std::time::SystemTime;
83
84#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct AuditEvent {
87 #[serde(with = "system_time_format")]
89 pub timestamp: SystemTime,
90
91 pub event_type: AuditEventType,
93
94 pub correlation_id: Option<String>,
96
97 pub remote_addr: Option<SocketAddr>,
99
100 pub principal: Option<String>,
102
103 pub method: Option<String>,
105
106 pub result: AuditResult,
108
109 pub severity: AuditSeverity,
111
112 pub metadata: HashMap<String, serde_json::Value>,
114
115 pub params: Option<serde_json::Value>,
117
118 pub error: Option<String>,
120
121 #[serde(default, skip_serializing_if = "Option::is_none")]
126 pub message: Option<String>,
127
128 #[serde(default, skip_serializing_if = "Provenance::is_empty")]
133 pub provenance: Provenance,
134
135 #[cfg(feature = "hlc")]
143 #[serde(default, skip_serializing_if = "Option::is_none")]
144 pub hlc: Option<EventClock>,
145}
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
153#[serde(rename_all = "snake_case")]
154#[non_exhaustive]
155pub enum AuditEventType {
156 ConnectionEstablished,
158
159 ConnectionClosed,
161
162 AuthenticationAttempt,
164
165 AuthorizationCheck,
167
168 MethodInvocation,
170
171 ErrorOccurred,
173
174 SecurityViolation,
176
177 ConfigurationChange,
179
180 AdminAction,
182
183 Diagnostic,
191}
192
193impl AuditEventType {
194 #[must_use]
211 pub const fn is_security_relevant(self) -> bool {
212 match self {
213 Self::ConnectionEstablished
214 | Self::ConnectionClosed
215 | Self::AuthenticationAttempt
216 | Self::AuthorizationCheck
217 | Self::MethodInvocation
218 | Self::ErrorOccurred
219 | Self::SecurityViolation
220 | Self::ConfigurationChange
221 | Self::AdminAction => true,
222 Self::Diagnostic => false,
223 }
224 }
225}
226
227#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
229#[serde(rename_all = "snake_case")]
230#[non_exhaustive]
231pub enum AuditResult {
232 Success,
234
235 Failure,
237
238 Denied,
240
241 Violation,
243
244 NotApplicable,
249}
250
251#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
268#[serde(rename_all = "snake_case")]
269#[non_exhaustive]
270pub enum AuditSeverity {
271 Trace,
273
274 Debug,
276
277 Info,
279
280 Warning,
282
283 Error,
285
286 Critical,
288}
289
290impl AuditSeverity {
291 pub const MIN: Self = Self::Trace;
293
294 pub const MAX: Self = Self::Critical;
296
297 #[must_use]
299 pub const fn as_str(self) -> &'static str {
300 match self {
301 Self::Trace => "trace",
302 Self::Debug => "debug",
303 Self::Info => "info",
304 Self::Warning => "warning",
305 Self::Error => "error",
306 Self::Critical => "critical",
307 }
308 }
309}
310
311impl std::fmt::Display for AuditSeverity {
312 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313 f.write_str(self.as_str())
314 }
315}
316
317impl std::str::FromStr for AuditSeverity {
318 type Err = ParseSeverityError;
319
320 fn from_str(s: &str) -> Result<Self, Self::Err> {
325 match s.trim().to_ascii_lowercase().as_str() {
326 "trace" => Ok(Self::Trace),
327 "debug" => Ok(Self::Debug),
328 "info" => Ok(Self::Info),
329 "warn" | "warning" => Ok(Self::Warning),
330 "error" => Ok(Self::Error),
331 "crit" | "critical" => Ok(Self::Critical),
332 _ => Err(ParseSeverityError(s.to_string())),
333 }
334 }
335}
336
337#[derive(Debug, Clone, PartialEq, Eq)]
339pub struct ParseSeverityError(String);
340
341impl std::fmt::Display for ParseSeverityError {
342 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
343 write!(
344 f,
345 "unknown severity {:?}; expected one of trace, debug, info, warning, error, critical",
346 self.0
347 )
348 }
349}
350
351impl std::error::Error for ParseSeverityError {}
352
353impl AuditEvent {
354 #[must_use]
376 #[track_caller]
377 pub fn diagnostic<S: Into<String>>(message: S) -> AuditEventBuilder {
378 AuditEventBuilder::default()
379 .event_type(AuditEventType::Diagnostic)
380 .result(AuditResult::NotApplicable)
381 .message(message)
382 .provenance(Provenance::capture())
383 }
384
385 #[must_use]
387 pub fn builder() -> AuditEventBuilder {
388 AuditEventBuilder::default()
389 }
390
391 pub fn add_metadata<K: Into<String>, V: Into<serde_json::Value>>(&mut self, key: K, value: V) {
393 self.metadata.insert(key.into(), value.into());
394 }
395
396 #[must_use]
398 pub fn with_correlation_id(mut self, correlation_id: Option<String>) -> Self {
399 self.correlation_id = correlation_id;
400 self
401 }
402
403 #[must_use]
405 pub fn with_principal<S: Into<String>>(mut self, principal: S) -> Self {
406 self.principal = Some(principal.into());
407 self
408 }
409
410 #[must_use]
412 pub fn with_remote_addr(mut self, addr: SocketAddr) -> Self {
413 self.remote_addr = Some(addr);
414 self
415 }
416}
417
418#[derive(Debug, Default)]
420pub struct AuditEventBuilder {
421 event_type: Option<AuditEventType>,
422 correlation_id: Option<String>,
423 remote_addr: Option<SocketAddr>,
424 principal: Option<String>,
425 method: Option<String>,
426 result: Option<AuditResult>,
427 severity: Option<AuditSeverity>,
428 metadata: HashMap<String, serde_json::Value>,
429 params: Option<serde_json::Value>,
430 error: Option<String>,
431 message: Option<String>,
432 provenance: Provenance,
433 #[cfg(feature = "hlc")]
434 hlc: Option<EventClock>,
435}
436
437impl AuditEventBuilder {
438 #[must_use]
440 pub fn event_type(mut self, event_type: AuditEventType) -> Self {
441 self.event_type = Some(event_type);
442 self
443 }
444
445 #[must_use]
447 pub fn correlation_id<S: Into<String>>(mut self, id: S) -> Self {
448 self.correlation_id = Some(id.into());
449 self
450 }
451
452 #[must_use]
454 pub fn remote_addr(mut self, addr: SocketAddr) -> Self {
455 self.remote_addr = Some(addr);
456 self
457 }
458
459 #[must_use]
461 pub fn principal<S: Into<String>>(mut self, principal: S) -> Self {
462 self.principal = Some(principal.into());
463 self
464 }
465
466 #[must_use]
468 pub fn method<S: Into<String>>(mut self, method: S) -> Self {
469 self.method = Some(method.into());
470 self
471 }
472
473 #[must_use]
475 pub fn result(mut self, result: AuditResult) -> Self {
476 self.result = Some(result);
477 self
478 }
479
480 #[must_use]
482 pub fn severity(mut self, severity: AuditSeverity) -> Self {
483 self.severity = Some(severity);
484 self
485 }
486
487 #[must_use]
489 pub fn metadata<K: Into<String>, V: Into<serde_json::Value>>(
490 mut self,
491 key: K,
492 value: V,
493 ) -> Self {
494 self.metadata.insert(key.into(), value.into());
495 self
496 }
497
498 #[must_use]
500 pub fn params(mut self, params: serde_json::Value) -> Self {
501 self.params = Some(params);
502 self
503 }
504
505 #[must_use]
507 pub fn provenance(mut self, provenance: Provenance) -> Self {
508 self.provenance = provenance;
509 self
510 }
511
512 #[cfg(feature = "hlc")]
517 #[must_use]
518 pub fn hlc(mut self, hlc: EventClock) -> Self {
519 self.hlc = Some(hlc);
520 self
521 }
522
523 #[must_use]
525 pub fn message<S: Into<String>>(mut self, message: S) -> Self {
526 self.message = Some(message.into());
527 self
528 }
529
530 #[must_use]
532 pub fn error<S: Into<String>>(mut self, error: S) -> Self {
533 self.error = Some(error.into());
534 self
535 }
536
537 #[must_use]
542 #[allow(clippy::panic)]
543 pub fn build(self) -> AuditEvent {
544 let event_type = self
545 .event_type
546 .unwrap_or_else(|| panic!("event_type is required for AuditEvent"));
547 let result = self
548 .result
549 .unwrap_or_else(|| panic!("result is required for AuditEvent"));
550
551 let severity = self.severity.unwrap_or(match result {
555 AuditResult::Success | AuditResult::NotApplicable => AuditSeverity::Info,
556 AuditResult::Failure => AuditSeverity::Warning,
557 AuditResult::Denied | AuditResult::Violation => AuditSeverity::Critical,
558 });
559
560 AuditEvent {
561 timestamp: SystemTime::now(),
562 event_type,
563 correlation_id: self.correlation_id,
564 remote_addr: self.remote_addr,
565 principal: self.principal,
566 method: self.method,
567 result,
568 severity,
569 metadata: self.metadata,
570 params: self.params,
571 error: self.error,
572 message: self.message,
573 provenance: self.provenance,
574 #[cfg(feature = "hlc")]
575 hlc: self.hlc,
576 }
577 }
578}
579
580mod system_time_format {
582 use serde::{Deserialize, Deserializer, Serializer};
583 use std::time::{SystemTime, UNIX_EPOCH};
584
585 pub fn serialize<S>(time: &SystemTime, serializer: S) -> Result<S::Ok, S::Error>
586 where
587 S: Serializer,
588 {
589 let duration = time
590 .duration_since(UNIX_EPOCH)
591 .map_err(serde::ser::Error::custom)?;
592 #[allow(clippy::arithmetic_side_effects)] let nanos = duration.as_secs() * 1_000_000_000 + u64::from(duration.subsec_nanos());
594 serializer.serialize_u64(nanos)
595 }
596
597 #[allow(clippy::arithmetic_side_effects, clippy::as_conversions)] pub fn deserialize<'de, D>(deserializer: D) -> Result<SystemTime, D::Error>
599 where
600 D: Deserializer<'de>,
601 {
602 let nanos = u64::deserialize(deserializer)?;
603 let secs = nanos / 1_000_000_000;
604 let subsec_nanos = (nanos % 1_000_000_000) as u32;
606 Ok(UNIX_EPOCH + std::time::Duration::new(secs, subsec_nanos))
607 }
608}
609
610#[cfg(test)]
611mod tests {
612 use super::*;
613
614 #[test]
615 fn test_audit_event_builder() {
616 let event = AuditEvent::builder()
617 .event_type(AuditEventType::AuthenticationAttempt)
618 .principal("user@example.com")
619 .method("login")
620 .result(AuditResult::Success)
621 .build();
622
623 assert_eq!(event.event_type, AuditEventType::AuthenticationAttempt);
624 assert_eq!(event.principal, Some("user@example.com".to_string()));
625 assert_eq!(event.result, AuditResult::Success);
626 assert_eq!(event.severity, AuditSeverity::Info);
627 }
628
629 #[test]
630 fn test_audit_event_serialization() {
631 let event = AuditEvent::builder()
632 .event_type(AuditEventType::MethodInvocation)
633 .principal("test_user")
634 .method("get_balance")
635 .result(AuditResult::Success)
636 .build();
637
638 let json = serde_json::to_string(&event).unwrap();
639 assert!(json.contains("method_invocation"));
640 assert!(json.contains("test_user"));
641 assert!(json.contains("success"));
642 }
643
644 #[test]
645 fn test_diagnostic_is_not_security_relevant() {
646 assert!(!AuditEventType::Diagnostic.is_security_relevant());
647 }
648
649 #[test]
650 fn test_diagnostic_builder_sets_a_truthful_classification() {
651 let event = AuditEvent::diagnostic("cache warm complete").build();
652
653 assert_eq!(event.event_type, AuditEventType::Diagnostic);
654 assert_eq!(event.result, AuditResult::NotApplicable);
655 assert_eq!(event.message.as_deref(), Some("cache warm complete"));
656 assert_eq!(event.severity, AuditSeverity::Info);
659 }
660
661 #[test]
662 fn test_diagnostic_accepts_an_explicit_level() {
663 let event = AuditEvent::diagnostic("connection retry")
664 .severity(AuditSeverity::Warning)
665 .build();
666
667 assert_eq!(event.severity, AuditSeverity::Warning);
668 }
669
670 #[test]
671 fn test_message_is_omitted_when_absent() {
672 let event = AuditEvent::builder()
674 .event_type(AuditEventType::AuthenticationAttempt)
675 .result(AuditResult::Success)
676 .build();
677
678 let json = serde_json::to_string(&event).expect("serializes");
679 assert!(
680 !json.contains("message"),
681 "absent message must not appear in the log line: {json}"
682 );
683 }
684
685 #[test]
686 fn test_message_round_trips() {
687 let event = AuditEvent::diagnostic("disk usage 91%").build();
688 let json = serde_json::to_string(&event).expect("serializes");
689 let parsed: AuditEvent = serde_json::from_str(&json).expect("deserializes");
690
691 assert_eq!(parsed.message.as_deref(), Some("disk usage 91%"));
692 }
693
694 #[test]
695 fn test_events_without_message_still_deserialize() {
696 let line = r#"{"timestamp":0,"event_type":"method_invocation","correlation_id":null,
698 "remote_addr":null,"principal":null,"method":null,"result":"success",
699 "severity":"info","metadata":{},"params":null,"error":null}"#;
700 let parsed: AuditEvent = serde_json::from_str(line).expect("deserializes");
701
702 assert_eq!(parsed.message, None);
703 }
704
705 #[test]
706 fn test_severity_is_ordered_ascending() {
707 use AuditSeverity as S;
708 let ascending = [
709 S::Trace,
710 S::Debug,
711 S::Info,
712 S::Warning,
713 S::Error,
714 S::Critical,
715 ];
716 for pair in ascending.windows(2) {
717 assert!(
718 pair[0] < pair[1],
719 "{:?} must sort below {:?}; level filtering depends on this",
720 pair[0],
721 pair[1]
722 );
723 }
724 assert_eq!(S::MIN, S::Trace);
725 assert_eq!(S::MAX, S::Critical);
726 }
727
728 #[test]
729 fn test_severity_round_trips_through_its_name() {
730 use std::str::FromStr as _;
731 for level in [
732 AuditSeverity::Trace,
733 AuditSeverity::Debug,
734 AuditSeverity::Info,
735 AuditSeverity::Warning,
736 AuditSeverity::Error,
737 AuditSeverity::Critical,
738 ] {
739 assert_eq!(AuditSeverity::from_str(level.as_str()), Ok(level));
740 assert_eq!(level.to_string(), level.as_str());
741
742 let json = serde_json::to_string(&level).expect("serializes");
745 assert_eq!(json, format!("\"{}\"", level.as_str()));
746 }
747 }
748
749 #[test]
750 fn test_severity_parsing_is_lenient_about_case_and_aliases() {
751 use std::str::FromStr as _;
752 assert_eq!(AuditSeverity::from_str("WARN"), Ok(AuditSeverity::Warning));
753 assert_eq!(
754 AuditSeverity::from_str(" Critical "),
755 Ok(AuditSeverity::Critical)
756 );
757 assert_eq!(AuditSeverity::from_str("crit"), Ok(AuditSeverity::Critical));
758 assert!(AuditSeverity::from_str("verbose").is_err());
759 }
760
761 #[test]
762 fn test_new_levels_deserialize_from_logs() {
763 for name in ["trace", "debug", "info", "warning", "error", "critical"] {
766 let parsed: AuditSeverity =
767 serde_json::from_str(&format!("\"{name}\"")).expect("deserializes");
768 assert_eq!(parsed.as_str(), name);
769 }
770 }
771
772 #[test]
773 fn test_security_relevance_classification() {
774 for event_type in [
776 AuditEventType::ConnectionEstablished,
777 AuditEventType::ConnectionClosed,
778 AuditEventType::AuthenticationAttempt,
779 AuditEventType::AuthorizationCheck,
780 AuditEventType::MethodInvocation,
781 AuditEventType::ErrorOccurred,
782 AuditEventType::SecurityViolation,
783 AuditEventType::ConfigurationChange,
784 AuditEventType::AdminAction,
785 ] {
786 assert!(
787 event_type.is_security_relevant(),
788 "{event_type:?} must always be admitted to the audit chain"
789 );
790 }
791 }
792
793 #[test]
794 fn test_severity_defaults() {
795 let success = AuditEvent::builder()
796 .event_type(AuditEventType::MethodInvocation)
797 .result(AuditResult::Success)
798 .build();
799 assert_eq!(success.severity, AuditSeverity::Info);
800
801 let denied = AuditEvent::builder()
802 .event_type(AuditEventType::AuthorizationCheck)
803 .result(AuditResult::Denied)
804 .build();
805 assert_eq!(denied.severity, AuditSeverity::Critical);
806 }
807}