Skip to main content

ash_log/
lib.rs

1//! # ash-log
2//!
3//! Security audit logging for Rust applications.
4//!
5//! Provides structured audit logging for security events including authentication,
6//! authorization, method invocations, and policy violations.
7//!
8//! For logs that must resist deliberate modification, enable the `hmac-chain`
9//! feature and use [`HmacChainIntegrity`]. The default [`ChecksumIntegrity`] uses
10//! an unkeyed hash and detects only accidental corruption.
11//!
12//! **Features**: append-only logs, integrity verification, pluggable backends.
13//!
14//! ## Quick start
15//!
16//! ```rust
17//! use ash_log::*;
18//! use std::sync::Arc;
19//!
20//! let backend = Arc::new(StdoutAuditBackend);
21//! let integrity = SequenceIntegrity::new();
22//!
23//! let mut event = AuditEvent::builder()
24//!     .event_type(AuditEventType::AuthenticationAttempt)
25//!     .principal("alice@example.com")
26//!     .result(AuditResult::Success)
27//!     .build();
28//!
29//! integrity.add_integrity(&mut event);
30//! backend.log_audit(&event);
31//! ```
32
33#![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/// A security audit event representing a significant action or decision
85#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct AuditEvent {
87    /// Precise timestamp with nanosecond precision
88    #[serde(with = "system_time_format")]
89    pub timestamp: SystemTime,
90
91    /// Type of audit event
92    pub event_type: AuditEventType,
93
94    /// Unique correlation ID spanning the request chain
95    pub correlation_id: Option<String>,
96
97    /// Remote address of the client
98    pub remote_addr: Option<SocketAddr>,
99
100    /// Principal identifier (user ID, API key, certificate DN, etc.)
101    pub principal: Option<String>,
102
103    /// Method or action being performed
104    pub method: Option<String>,
105
106    /// Result of the action
107    pub result: AuditResult,
108
109    /// Event severity level
110    pub severity: AuditSeverity,
111
112    /// Additional context and metadata
113    pub metadata: HashMap<String, serde_json::Value>,
114
115    /// Request parameters (sanitized)
116    pub params: Option<serde_json::Value>,
117
118    /// Error message if result is Failure or Denied
119    pub error: Option<String>,
120
121    /// Human-readable message.
122    ///
123    /// Primarily carried by [`AuditEventType::Diagnostic`] records. It is part
124    /// of the canonical form, so it is covered by any integrity mechanism.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub message: Option<String>,
127
128    /// Where the event was emitted from.
129    ///
130    /// Part of the canonical form, so provenance is covered by any integrity
131    /// mechanism: it can be proved, not merely recorded.
132    #[serde(default, skip_serializing_if = "Provenance::is_empty")]
133    pub provenance: Provenance,
134
135    /// Monotonic causal timestamp, when the logger was given a clock.
136    ///
137    /// [`timestamp`](Self::timestamp) comes from the system clock and can move
138    /// backwards; this cannot. It is part of the canonical form, so the causal
139    /// ordering is covered by the integrity mechanism. Absent unless the `hlc`
140    /// feature is enabled and a clock is configured, and skipped when absent,
141    /// so events written without it canonicalize exactly as before.
142    #[cfg(feature = "hlc")]
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub hlc: Option<EventClock>,
145}
146
147/// Types of recorded events.
148///
149/// Every variant except [`Diagnostic`](Self::Diagnostic) is security-relevant
150/// and is always admitted to the audit chain regardless of level filtering; see
151/// [`is_security_relevant`](Self::is_security_relevant).
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
153#[serde(rename_all = "snake_case")]
154#[non_exhaustive]
155pub enum AuditEventType {
156    /// Connection established
157    ConnectionEstablished,
158
159    /// Connection closed
160    ConnectionClosed,
161
162    /// Authentication attempt (login, certificate validation, etc.)
163    AuthenticationAttempt,
164
165    /// Authorization check (access control decision)
166    AuthorizationCheck,
167
168    /// RPC method invocation
169    MethodInvocation,
170
171    /// Error occurred during processing
172    ErrorOccurred,
173
174    /// Security policy violation (rate limit, size limit, banned IP, etc.)
175    SecurityViolation,
176
177    /// Configuration change (admin action)
178    ConfigurationChange,
179
180    /// System administrative action
181    AdminAction,
182
183    /// A diagnostic or operational log record carrying a human-readable
184    /// message rather than a security decision.
185    ///
186    /// Unlike every other variant, this one is **not** security-relevant, so it
187    /// is subject to level filtering and may legitimately be dropped. Use it for
188    /// application logging; use a specific variant for anything that belongs in
189    /// the compliance record.
190    Diagnostic,
191}
192
193impl AuditEventType {
194    /// Whether this event type is security-relevant and must therefore always
195    /// reach the audit chain, regardless of any level filtering.
196    ///
197    /// This is the admission policy for the crate's two tiers: security events
198    /// are recorded unconditionally, so an operational log level cannot shrink
199    /// the compliance record, while diagnostic events are subject to the
200    /// configured minimum level.
201    ///
202    /// The `match` below is deliberately exhaustive with no wildcard arm: a new
203    /// variant will fail to compile until its tier is stated explicitly, rather
204    /// than silently defaulting into one.
205    ///
206    /// ```rust
207    /// # use ash_log::AuditEventType;
208    /// assert!(AuditEventType::SecurityViolation.is_security_relevant());
209    /// ```
210    #[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/// Result of an audited action
228#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
229#[serde(rename_all = "snake_case")]
230#[non_exhaustive]
231pub enum AuditResult {
232    /// Action succeeded
233    Success,
234
235    /// Action failed due to error
236    Failure,
237
238    /// Action denied by policy
239    Denied,
240
241    /// Action resulted in security violation
242    Violation,
243
244    /// No pass/fail outcome applies.
245    ///
246    /// Used by [`AuditEventType::Diagnostic`] records, which report something
247    /// that happened rather than the outcome of a security decision.
248    NotApplicable,
249}
250
251/// Severity level of an audit event, ordered from least to most severe.
252///
253/// Variants are declared in ascending order of severity, and `Ord` is derived
254/// from that order, so `severity >= min_level` is a valid level filter.
255///
256/// ```rust
257/// # use ash_log::AuditSeverity;
258/// assert!(AuditSeverity::Critical > AuditSeverity::Info);
259/// assert!(AuditSeverity::Error > AuditSeverity::Warning);
260/// ```
261///
262/// # Compatibility
263///
264/// The enum is `#[non_exhaustive]`, and adding a variant is asymmetric: new
265/// code reads old logs, but an older verifier rejects a level it does not know.
266/// Roll verifiers out before the producers that write new levels.
267#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
268#[serde(rename_all = "snake_case")]
269#[non_exhaustive]
270pub enum AuditSeverity {
271    /// Fine-grained diagnostic detail. Noisy; normally filtered out.
272    Trace,
273
274    /// Diagnostic detail useful when developing or debugging.
275    Debug,
276
277    /// Normal operation worth recording.
278    Info,
279
280    /// An anomaly that did not cause a failure.
281    Warning,
282
283    /// An operation failed.
284    Error,
285
286    /// A security-significant event.
287    Critical,
288}
289
290impl AuditSeverity {
291    /// The lowest severity, useful as a permissive filter threshold.
292    pub const MIN: Self = Self::Trace;
293
294    /// The highest severity, useful as a restrictive filter threshold.
295    pub const MAX: Self = Self::Critical;
296
297    /// The lower-case name of this level, as it appears in serialized events.
298    #[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    /// Parse a level from its name, case-insensitively.
321    ///
322    /// Accepts the serialized names, plus `warn` for `Warning` and `crit` for
323    /// `Critical`, since both are common in configuration files.
324    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/// Returned when a string does not name an [`AuditSeverity`].
338#[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    /// Start building a diagnostic log record.
355    ///
356    /// Pre-sets [`AuditEventType::Diagnostic`],
357    /// [`AuditResult::NotApplicable`], and the message, so a message-shaped log
358    /// line does not have to invent a security classification it does not have.
359    /// The default severity is [`AuditSeverity::Info`]; set an explicit level
360    /// with [`severity`](AuditEventBuilder::severity).
361    ///
362    /// Diagnostic records are subject to level filtering, unlike every other
363    /// event type.
364    ///
365    /// ```rust
366    /// # use ash_log::*;
367    /// let event = AuditEvent::diagnostic("cache warm complete")
368    ///     .severity(AuditSeverity::Debug)
369    ///     .build();
370    ///
371    /// assert_eq!(event.event_type, AuditEventType::Diagnostic);
372    /// assert!(!event.event_type.is_security_relevant());
373    /// assert_eq!(event.message.as_deref(), Some("cache warm complete"));
374    /// ```
375    #[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    /// Create a new audit event builder
386    #[must_use]
387    pub fn builder() -> AuditEventBuilder {
388        AuditEventBuilder::default()
389    }
390
391    /// Add a metadata entry
392    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    /// Set the correlation ID from a request
397    #[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    /// Set the principal from connection context
404    #[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    /// Set the remote address
411    #[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/// Builder for creating audit events
419#[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    /// Set event type
439    #[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    /// Set correlation ID
446    #[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    /// Set remote address
453    #[must_use]
454    pub fn remote_addr(mut self, addr: SocketAddr) -> Self {
455        self.remote_addr = Some(addr);
456        self
457    }
458
459    /// Set principal
460    #[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    /// Set method name
467    #[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    /// Set result
474    #[must_use]
475    pub fn result(mut self, result: AuditResult) -> Self {
476        self.result = Some(result);
477        self
478    }
479
480    /// Set severity
481    #[must_use]
482    pub fn severity(mut self, severity: AuditSeverity) -> Self {
483        self.severity = Some(severity);
484        self
485    }
486
487    /// Add metadata entry
488    #[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    /// Set sanitized parameters
499    #[must_use]
500    pub fn params(mut self, params: serde_json::Value) -> Self {
501        self.params = Some(params);
502        self
503    }
504
505    /// Set where the event was emitted from.
506    #[must_use]
507    pub fn provenance(mut self, provenance: Provenance) -> Self {
508        self.provenance = provenance;
509        self
510    }
511
512    /// Set the monotonic causal timestamp.
513    ///
514    /// Normally supplied by the [`Logger`] from its configured clock rather
515    /// than set here; this exists for events built by hand.
516    #[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    /// Set the human-readable message.
524    #[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    /// Set error message
531    #[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    /// Build the audit event
538    ///
539    /// # Panics
540    /// Panics if `event_type` or `result` were not set
541    #[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        // Determine default severity based on result. `NotApplicable` carries no
552        // outcome, so it defaults to `Info` and callers are expected to set an
553        // explicit level on diagnostic records.
554        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
580/// Custom serialization for `SystemTime` to include nanosecond precision
581mod 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)] // Nanosecond calculation for timestamp
593        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)] // Timestamp serialization math
598    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        // Safe: modulo operation ensures value < 1_000_000_000, fits in u32
605        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        // No outcome was claimed, so the level defaults to Info rather than
657        // implying success.
658        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        // Existing security events gain no empty field in their serialized form.
673        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        // A 0.1.0 log line has no `message` key at all.
697        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            // The name must match the serialized form, or configuration files
743            // and log lines would disagree about what a level is called.
744            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        // A verifier must read every level a producer of the same version can
764        // write, or a log would fail to deserialize rather than to verify.
765        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        // Every existing variant is security-relevant; only diagnostics are not.
775        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}