#![deny(missing_docs)]
#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::module_name_repetitions)]
mod async_backend;
mod backends;
mod context;
mod error;
mod file;
mod filter;
#[cfg(feature = "hlc")]
mod hlc;
mod integrity;
mod logger;
mod macros;
mod processor;
mod provenance;
mod redact;
#[cfg(feature = "tracing")]
mod tracing_bridge;
#[cfg(feature = "hmac-chain")]
mod hmac_chain;
#[cfg(feature = "ocsf")]
pub mod ocsf;
pub use async_backend::*;
pub use backends::*;
pub use context::*;
pub use error::*;
pub use file::*;
pub use filter::*;
#[cfg(feature = "hlc")]
pub use hlc::*;
#[cfg(feature = "hmac-chain")]
pub use hmac_chain::*;
pub use integrity::*;
pub use logger::*;
pub use processor::*;
pub use provenance::*;
pub use redact::*;
#[cfg(feature = "tracing")]
pub use tracing_bridge::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::time::SystemTime;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEvent {
#[serde(with = "system_time_format")]
pub timestamp: SystemTime,
pub event_type: AuditEventType,
pub correlation_id: Option<String>,
pub remote_addr: Option<SocketAddr>,
pub principal: Option<String>,
pub method: Option<String>,
pub result: AuditResult,
pub severity: AuditSeverity,
pub metadata: HashMap<String, serde_json::Value>,
pub params: Option<serde_json::Value>,
pub error: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
#[serde(default, skip_serializing_if = "Provenance::is_empty")]
pub provenance: Provenance,
#[cfg(feature = "hlc")]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hlc: Option<EventClock>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AuditEventType {
ConnectionEstablished,
ConnectionClosed,
AuthenticationAttempt,
AuthorizationCheck,
MethodInvocation,
ErrorOccurred,
SecurityViolation,
ConfigurationChange,
AdminAction,
Diagnostic,
}
impl AuditEventType {
#[must_use]
pub const fn is_security_relevant(self) -> bool {
match self {
Self::ConnectionEstablished
| Self::ConnectionClosed
| Self::AuthenticationAttempt
| Self::AuthorizationCheck
| Self::MethodInvocation
| Self::ErrorOccurred
| Self::SecurityViolation
| Self::ConfigurationChange
| Self::AdminAction => true,
Self::Diagnostic => false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AuditResult {
Success,
Failure,
Denied,
Violation,
NotApplicable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AuditSeverity {
Trace,
Debug,
Info,
Warning,
Error,
Critical,
}
impl AuditSeverity {
pub const MIN: Self = Self::Trace;
pub const MAX: Self = Self::Critical;
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Trace => "trace",
Self::Debug => "debug",
Self::Info => "info",
Self::Warning => "warning",
Self::Error => "error",
Self::Critical => "critical",
}
}
}
impl std::fmt::Display for AuditSeverity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl std::str::FromStr for AuditSeverity {
type Err = ParseSeverityError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_ascii_lowercase().as_str() {
"trace" => Ok(Self::Trace),
"debug" => Ok(Self::Debug),
"info" => Ok(Self::Info),
"warn" | "warning" => Ok(Self::Warning),
"error" => Ok(Self::Error),
"crit" | "critical" => Ok(Self::Critical),
_ => Err(ParseSeverityError(s.to_string())),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseSeverityError(String);
impl std::fmt::Display for ParseSeverityError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"unknown severity {:?}; expected one of trace, debug, info, warning, error, critical",
self.0
)
}
}
impl std::error::Error for ParseSeverityError {}
impl AuditEvent {
#[must_use]
#[track_caller]
pub fn diagnostic<S: Into<String>>(message: S) -> AuditEventBuilder {
AuditEventBuilder::default()
.event_type(AuditEventType::Diagnostic)
.result(AuditResult::NotApplicable)
.message(message)
.provenance(Provenance::capture())
}
#[must_use]
pub fn builder() -> AuditEventBuilder {
AuditEventBuilder::default()
}
pub fn add_metadata<K: Into<String>, V: Into<serde_json::Value>>(&mut self, key: K, value: V) {
self.metadata.insert(key.into(), value.into());
}
#[must_use]
pub fn with_correlation_id(mut self, correlation_id: Option<String>) -> Self {
self.correlation_id = correlation_id;
self
}
#[must_use]
pub fn with_principal<S: Into<String>>(mut self, principal: S) -> Self {
self.principal = Some(principal.into());
self
}
#[must_use]
pub fn with_remote_addr(mut self, addr: SocketAddr) -> Self {
self.remote_addr = Some(addr);
self
}
}
#[derive(Debug, Default)]
pub struct AuditEventBuilder {
event_type: Option<AuditEventType>,
correlation_id: Option<String>,
remote_addr: Option<SocketAddr>,
principal: Option<String>,
method: Option<String>,
result: Option<AuditResult>,
severity: Option<AuditSeverity>,
metadata: HashMap<String, serde_json::Value>,
params: Option<serde_json::Value>,
error: Option<String>,
message: Option<String>,
provenance: Provenance,
#[cfg(feature = "hlc")]
hlc: Option<EventClock>,
}
impl AuditEventBuilder {
#[must_use]
pub fn event_type(mut self, event_type: AuditEventType) -> Self {
self.event_type = Some(event_type);
self
}
#[must_use]
pub fn correlation_id<S: Into<String>>(mut self, id: S) -> Self {
self.correlation_id = Some(id.into());
self
}
#[must_use]
pub fn remote_addr(mut self, addr: SocketAddr) -> Self {
self.remote_addr = Some(addr);
self
}
#[must_use]
pub fn principal<S: Into<String>>(mut self, principal: S) -> Self {
self.principal = Some(principal.into());
self
}
#[must_use]
pub fn method<S: Into<String>>(mut self, method: S) -> Self {
self.method = Some(method.into());
self
}
#[must_use]
pub fn result(mut self, result: AuditResult) -> Self {
self.result = Some(result);
self
}
#[must_use]
pub fn severity(mut self, severity: AuditSeverity) -> Self {
self.severity = Some(severity);
self
}
#[must_use]
pub fn metadata<K: Into<String>, V: Into<serde_json::Value>>(
mut self,
key: K,
value: V,
) -> Self {
self.metadata.insert(key.into(), value.into());
self
}
#[must_use]
pub fn params(mut self, params: serde_json::Value) -> Self {
self.params = Some(params);
self
}
#[must_use]
pub fn provenance(mut self, provenance: Provenance) -> Self {
self.provenance = provenance;
self
}
#[cfg(feature = "hlc")]
#[must_use]
pub fn hlc(mut self, hlc: EventClock) -> Self {
self.hlc = Some(hlc);
self
}
#[must_use]
pub fn message<S: Into<String>>(mut self, message: S) -> Self {
self.message = Some(message.into());
self
}
#[must_use]
pub fn error<S: Into<String>>(mut self, error: S) -> Self {
self.error = Some(error.into());
self
}
#[must_use]
#[allow(clippy::panic)]
pub fn build(self) -> AuditEvent {
let event_type = self
.event_type
.unwrap_or_else(|| panic!("event_type is required for AuditEvent"));
let result = self
.result
.unwrap_or_else(|| panic!("result is required for AuditEvent"));
let severity = self.severity.unwrap_or(match result {
AuditResult::Success | AuditResult::NotApplicable => AuditSeverity::Info,
AuditResult::Failure => AuditSeverity::Warning,
AuditResult::Denied | AuditResult::Violation => AuditSeverity::Critical,
});
AuditEvent {
timestamp: SystemTime::now(),
event_type,
correlation_id: self.correlation_id,
remote_addr: self.remote_addr,
principal: self.principal,
method: self.method,
result,
severity,
metadata: self.metadata,
params: self.params,
error: self.error,
message: self.message,
provenance: self.provenance,
#[cfg(feature = "hlc")]
hlc: self.hlc,
}
}
}
mod system_time_format {
use serde::{Deserialize, Deserializer, Serializer};
use std::time::{SystemTime, UNIX_EPOCH};
pub fn serialize<S>(time: &SystemTime, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let duration = time
.duration_since(UNIX_EPOCH)
.map_err(serde::ser::Error::custom)?;
#[allow(clippy::arithmetic_side_effects)] let nanos = duration.as_secs() * 1_000_000_000 + u64::from(duration.subsec_nanos());
serializer.serialize_u64(nanos)
}
#[allow(clippy::arithmetic_side_effects, clippy::as_conversions)] pub fn deserialize<'de, D>(deserializer: D) -> Result<SystemTime, D::Error>
where
D: Deserializer<'de>,
{
let nanos = u64::deserialize(deserializer)?;
let secs = nanos / 1_000_000_000;
let subsec_nanos = (nanos % 1_000_000_000) as u32;
Ok(UNIX_EPOCH + std::time::Duration::new(secs, subsec_nanos))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_audit_event_builder() {
let event = AuditEvent::builder()
.event_type(AuditEventType::AuthenticationAttempt)
.principal("user@example.com")
.method("login")
.result(AuditResult::Success)
.build();
assert_eq!(event.event_type, AuditEventType::AuthenticationAttempt);
assert_eq!(event.principal, Some("user@example.com".to_string()));
assert_eq!(event.result, AuditResult::Success);
assert_eq!(event.severity, AuditSeverity::Info);
}
#[test]
fn test_audit_event_serialization() {
let event = AuditEvent::builder()
.event_type(AuditEventType::MethodInvocation)
.principal("test_user")
.method("get_balance")
.result(AuditResult::Success)
.build();
let json = serde_json::to_string(&event).unwrap();
assert!(json.contains("method_invocation"));
assert!(json.contains("test_user"));
assert!(json.contains("success"));
}
#[test]
fn test_diagnostic_is_not_security_relevant() {
assert!(!AuditEventType::Diagnostic.is_security_relevant());
}
#[test]
fn test_diagnostic_builder_sets_a_truthful_classification() {
let event = AuditEvent::diagnostic("cache warm complete").build();
assert_eq!(event.event_type, AuditEventType::Diagnostic);
assert_eq!(event.result, AuditResult::NotApplicable);
assert_eq!(event.message.as_deref(), Some("cache warm complete"));
assert_eq!(event.severity, AuditSeverity::Info);
}
#[test]
fn test_diagnostic_accepts_an_explicit_level() {
let event = AuditEvent::diagnostic("connection retry")
.severity(AuditSeverity::Warning)
.build();
assert_eq!(event.severity, AuditSeverity::Warning);
}
#[test]
fn test_message_is_omitted_when_absent() {
let event = AuditEvent::builder()
.event_type(AuditEventType::AuthenticationAttempt)
.result(AuditResult::Success)
.build();
let json = serde_json::to_string(&event).expect("serializes");
assert!(
!json.contains("message"),
"absent message must not appear in the log line: {json}"
);
}
#[test]
fn test_message_round_trips() {
let event = AuditEvent::diagnostic("disk usage 91%").build();
let json = serde_json::to_string(&event).expect("serializes");
let parsed: AuditEvent = serde_json::from_str(&json).expect("deserializes");
assert_eq!(parsed.message.as_deref(), Some("disk usage 91%"));
}
#[test]
fn test_events_without_message_still_deserialize() {
let line = r#"{"timestamp":0,"event_type":"method_invocation","correlation_id":null,
"remote_addr":null,"principal":null,"method":null,"result":"success",
"severity":"info","metadata":{},"params":null,"error":null}"#;
let parsed: AuditEvent = serde_json::from_str(line).expect("deserializes");
assert_eq!(parsed.message, None);
}
#[test]
fn test_severity_is_ordered_ascending() {
use AuditSeverity as S;
let ascending = [
S::Trace,
S::Debug,
S::Info,
S::Warning,
S::Error,
S::Critical,
];
for pair in ascending.windows(2) {
assert!(
pair[0] < pair[1],
"{:?} must sort below {:?}; level filtering depends on this",
pair[0],
pair[1]
);
}
assert_eq!(S::MIN, S::Trace);
assert_eq!(S::MAX, S::Critical);
}
#[test]
fn test_severity_round_trips_through_its_name() {
use std::str::FromStr as _;
for level in [
AuditSeverity::Trace,
AuditSeverity::Debug,
AuditSeverity::Info,
AuditSeverity::Warning,
AuditSeverity::Error,
AuditSeverity::Critical,
] {
assert_eq!(AuditSeverity::from_str(level.as_str()), Ok(level));
assert_eq!(level.to_string(), level.as_str());
let json = serde_json::to_string(&level).expect("serializes");
assert_eq!(json, format!("\"{}\"", level.as_str()));
}
}
#[test]
fn test_severity_parsing_is_lenient_about_case_and_aliases() {
use std::str::FromStr as _;
assert_eq!(AuditSeverity::from_str("WARN"), Ok(AuditSeverity::Warning));
assert_eq!(
AuditSeverity::from_str(" Critical "),
Ok(AuditSeverity::Critical)
);
assert_eq!(AuditSeverity::from_str("crit"), Ok(AuditSeverity::Critical));
assert!(AuditSeverity::from_str("verbose").is_err());
}
#[test]
fn test_new_levels_deserialize_from_logs() {
for name in ["trace", "debug", "info", "warning", "error", "critical"] {
let parsed: AuditSeverity =
serde_json::from_str(&format!("\"{name}\"")).expect("deserializes");
assert_eq!(parsed.as_str(), name);
}
}
#[test]
fn test_security_relevance_classification() {
for event_type in [
AuditEventType::ConnectionEstablished,
AuditEventType::ConnectionClosed,
AuditEventType::AuthenticationAttempt,
AuditEventType::AuthorizationCheck,
AuditEventType::MethodInvocation,
AuditEventType::ErrorOccurred,
AuditEventType::SecurityViolation,
AuditEventType::ConfigurationChange,
AuditEventType::AdminAction,
] {
assert!(
event_type.is_security_relevant(),
"{event_type:?} must always be admitted to the audit chain"
);
}
}
#[test]
fn test_severity_defaults() {
let success = AuditEvent::builder()
.event_type(AuditEventType::MethodInvocation)
.result(AuditResult::Success)
.build();
assert_eq!(success.severity, AuditSeverity::Info);
let denied = AuditEvent::builder()
.event_type(AuditEventType::AuthorizationCheck)
.result(AuditResult::Denied)
.build();
assert_eq!(denied.severity, AuditSeverity::Critical);
}
}