Skip to main content

sysknife_daemon/
audit_forward.rs

1//! External audit log forwarding (RFC 5424 syslog over UDP).
2//!
3//! After each `transactions` row is recorded, the daemon hands a structured
4//! `AuditEvent` to a per-sink forwarder task over a bounded
5//! [`tokio::sync::mpsc::channel`]. The forwarder formats the event per the
6//! configured wire protocol and emits it. **Forwarding is fire-and-forget**:
7//! channel send failures (`try_send` returning `Full`/`Closed`) increment a
8//! drop counter and emit an `eprintln!` warning after `DROP_WARN_THRESHOLD`
9//! consecutive drops; the audit-log INSERT path itself never awaits or fails.
10//!
11//! ## Wire protocols
12//!
13//! Phase 1 ships **RFC 5424 syslog over UDP**, the de-facto on-host
14//! log-forwarding format. Direct ingestion works with Splunk, Elastic,
15//! IBM QRadar, and rsyslog; vendors that require a forwarder agent
16//! (Microsoft Sentinel via the Azure Monitor Agent on a Linux VM,
17//! Datadog/Chronicle via their own collectors) consume the same stream
18//! through that agent. CEF and NDJSON-over-TCP are designed-for in
19//! [`AuditSinkSpec`] and arrive in follow-up PRs.
20//!
21//! ## Reliability vs durability
22//!
23//! - **Local audit-log INSERT** (Ed25519-signed hash-chained, see
24//!   [`audit_chain`](crate::audit_chain)) is the durable record.
25//! - **External forwarding** is best-effort. A SIEM outage, a routing flap, or
26//!   a misconfigured collector must NEVER block daemon execution.
27//! - We do not retry the *send* in-process: a frame that the kernel could not
28//!   hand to the SIEM is dropped and the next event continues.  Bind failures
29//!   *are* retried with exponential backoff (1s → 60s) so a transient outage
30//!   does not poison the socket forever, but neither path tries to replay the
31//!   missed event — the SIEM is the long-lived accumulator and the local
32//!   hash-chained log will catch up the operator on the next ingest.  (A
33//!   future "tail watermark + replay" Phase 2 bridge can reconcile gaps from
34//!   the local log.)
35
36use std::net::SocketAddr;
37use std::sync::atomic::{AtomicU64, Ordering};
38use std::sync::Arc;
39use std::time::Duration;
40
41use sysknife_types::RiskLevel;
42use tokio::sync::mpsc;
43
44/// Bounded queue depth between daemon and forwarder. Sized for ~5 minutes of
45/// audit events at the daemon's sustainable record rate (well below SIEM
46/// ingest); a sustained burst that overflows is a SIEM outage and we drop
47/// (with counter + WARN) rather than back-pressure the audit-log writer.
48pub const FORWARDER_QUEUE_DEPTH: usize = 4096;
49
50/// Emit a single WARN to stderr after this many consecutive `try_send` drops.
51/// Counter resets on a successful send.
52pub const DROP_WARN_THRESHOLD: u64 = 8;
53
54/// Configuration for one forwarding sink.
55#[derive(Clone, Debug)]
56pub enum AuditSinkSpec {
57    /// RFC 5424 syslog over UDP. Sends each event as a single datagram.
58    SyslogUdp {
59        /// Host:port of the receiver, e.g. `"siem.internal:514"`.
60        host: SocketAddr,
61        /// Syslog facility (default `1` = user-level messages).
62        facility: u8,
63    },
64}
65
66/// One audit event handed to the forwarder. Mirrors the chain content
67/// captured at INSERT time so SIEM rules can correlate by `transaction_id`
68/// and `request_hash` against the local hash-chained log.
69///
70/// `final_status` is `None` for the preview-time event (no terminal state yet)
71/// and `Some` for the execute-time event emitted after `update_status`. SOC
72/// analysts watching the SIEM can therefore tell from the same event stream
73/// whether an action ran, succeeded, failed, or was rolled back.
74#[derive(Clone, Debug)]
75pub struct AuditEvent {
76    pub seq: u64,
77    pub transaction_id: String,
78    pub action_name: String,
79    pub risk_level: RiskLevel,
80    pub summary: String,
81    pub approval_id: Option<String>,
82    pub created_at: String,
83    pub chain_hash: String,
84    pub key_id: String,
85    pub caller_role: Option<String>,
86    pub final_status: Option<String>,
87}
88
89/// A handle the daemon writes to. Cheap to clone (Arc-wrapped sender +
90/// counter). Returns immediately on `submit`.
91#[derive(Clone)]
92pub struct AuditForwarder {
93    sender: mpsc::Sender<AuditEvent>,
94    drops: Arc<AtomicU64>,
95}
96
97impl std::fmt::Debug for AuditForwarder {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        f.debug_struct("AuditForwarder")
100            .field("queue_capacity", &self.sender.capacity())
101            .field("queue_max", &self.sender.max_capacity())
102            .field("drops", &self.drops.load(Ordering::Relaxed))
103            .finish()
104    }
105}
106
107impl AuditForwarder {
108    /// Submit an event for forwarding. Never blocks. Drops the event if the
109    /// channel is full or closed; consecutive drops emit a WARN after
110    /// [`DROP_WARN_THRESHOLD`].
111    pub fn submit(&self, event: AuditEvent) {
112        match self.sender.try_send(event) {
113            Ok(()) => {
114                // Reset drop counter on a successful submit so the next
115                // outage emits a fresh WARN.
116                self.drops.store(0, Ordering::Relaxed);
117            }
118            Err(mpsc::error::TrySendError::Full(_)) => {
119                let prev = self.drops.fetch_add(1, Ordering::Relaxed);
120                if (prev + 1) == DROP_WARN_THRESHOLD {
121                    eprintln!(
122                        "[sysknife-daemon] audit-forward: queue full, dropping events \
123                         (>= {DROP_WARN_THRESHOLD} consecutive); is the SIEM reachable?"
124                    );
125                }
126            }
127            Err(mpsc::error::TrySendError::Closed(_)) => {
128                // The forwarder task has shut down. One-time WARN to stderr;
129                // subsequent submits silently no-op.
130                let prev = self.drops.fetch_add(1, Ordering::Relaxed);
131                if prev == 0 {
132                    eprintln!(
133                        "[sysknife-daemon] audit-forward: forwarder task is gone; \
134                         further submits will be dropped silently"
135                    );
136                }
137            }
138        }
139    }
140
141    /// Total events dropped since the last successful submit. Test-only.
142    #[cfg(test)]
143    pub fn drop_count(&self) -> u64 {
144        self.drops.load(Ordering::Relaxed)
145    }
146}
147
148/// Spawn a forwarder task that consumes events from `rx` and sends them to
149/// `spec`. Returns the [`AuditForwarder`] handle the daemon writes to.
150///
151/// On task exit (channel closed by all senders dropping), the task returns
152/// silently. There is no graceful drain — pending events in the channel are
153/// dropped at shutdown. Audit durability is guaranteed by the local
154/// hash-chained log, not by the forwarder.
155pub fn spawn(spec: AuditSinkSpec) -> AuditForwarder {
156    let (tx, rx) = mpsc::channel(FORWARDER_QUEUE_DEPTH);
157    let drops = Arc::new(AtomicU64::new(0));
158    tokio::spawn(forwarder_task(spec, rx));
159    AuditForwarder { sender: tx, drops }
160}
161
162async fn forwarder_task(spec: AuditSinkSpec, mut rx: mpsc::Receiver<AuditEvent>) {
163    match spec {
164        AuditSinkSpec::SyslogUdp { host, facility } => {
165            let mut socket = open_udp(host).await;
166            // Exponential backoff on consecutive bind failures so a transient
167            // outage does not produce a tight retry loop that pegs a CPU.
168            // See `next_backoff_secs` for the doubling sequence and
169            // `MAX_BACKOFF_SECS` for why the cap lives where it does.  Reset
170            // to `INITIAL_BACKOFF_SECS` on the first successful bind.
171            let mut backoff_secs: u64 = INITIAL_BACKOFF_SECS;
172            while let Some(event) = rx.recv().await {
173                let frame = format_rfc5424(&event, facility);
174                // **Event-drop semantics:** if the socket is `None` (bind has
175                // never succeeded, or a previous send failed and we have not
176                // yet rebound) the formatted frame is computed and then
177                // dropped. The local hash-chained audit log already has a
178                // durable copy of the same row, so the SIEM gap is by
179                // design — a future "tail watermark + replay" Phase 2 bridge
180                // can backfill from the local log.
181                if let Some(s) = &socket {
182                    if let Err(e) = s.send_to(frame.as_bytes(), host).await {
183                        eprintln!(
184                            "[sysknife-daemon] audit-forward: UDP send to {host} failed: {e} \
185                             — dropping socket and reopening (current event is lost)"
186                        );
187                        socket = None;
188                    }
189                }
190                if socket.is_none() {
191                    socket = open_udp(host).await;
192                    if socket.is_none() {
193                        // Bind failure: sleep with exponential backoff before
194                        // we attempt again on the next event. Without this,
195                        // a misconfigured host with a packed channel would
196                        // pin a CPU at 100% on `eprintln!` syscalls.
197                        tokio::time::sleep(Duration::from_secs(backoff_secs)).await;
198                        backoff_secs = next_backoff_secs(backoff_secs);
199                    } else {
200                        backoff_secs = 1;
201                    }
202                }
203            }
204        }
205    }
206}
207
208/// Maximum wait between consecutive bind-failure retries, in seconds.
209///
210/// Once the exponential backoff hits this ceiling it stays there.  Without a
211/// cap, a long-running SIEM outage would silently grow the retry interval
212/// into hours (1h ≈ 3600s, the doubling sequence reaches that after only a
213/// few minutes) — operators would think forwarding had quietly stopped
214/// rather than seeing minute-by-minute reattempts. 60s is the smallest
215/// value where:
216///
217///   1. The retry rate is well below the threshold that pegs a CPU on
218///      bind/`eprintln!` syscalls in a tight loop, and
219///   2. A normally-functioning SIEM coming back online recovers within one
220///      ingest interval (most SIEMs ingest at ≤ 60s granularity already).
221const MAX_BACKOFF_SECS: u64 = 60;
222
223/// Initial wait after the first bind failure, in seconds.  The doubling
224/// sequence resets to this value after every successful bind.
225const INITIAL_BACKOFF_SECS: u64 = 1;
226
227/// Compute the next exponential-backoff wait, capped at [`MAX_BACKOFF_SECS`].
228///
229/// Sequence: `1 → 2 → 4 → 8 → 16 → 32 → MAX → MAX → …`.  Extracted from
230/// `forwarder_task` so the math can be unit-tested without driving a real
231/// tokio runtime.
232fn next_backoff_secs(prev: u64) -> u64 {
233    prev.saturating_mul(2).min(MAX_BACKOFF_SECS)
234}
235
236/// Bind a fresh ephemeral UDP socket whose address family matches `host`.
237///
238/// IPv4 host → bind on `0.0.0.0:0`; IPv6 host → bind on `[::]:0`. Without
239/// this, an operator with an IPv6-only SIEM (e.g. Sentinel at
240/// `[2001:db8::5]:514`) would never receive any events because every send
241/// would fail with `AddrNotAvailable`.
242///
243/// Returns `None` on bind failure — caller retries with backoff.
244async fn open_udp(host: SocketAddr) -> Option<tokio::net::UdpSocket> {
245    let bind_addr = if host.is_ipv6() {
246        "[::]:0"
247    } else {
248        "0.0.0.0:0"
249    };
250    match tokio::net::UdpSocket::bind(bind_addr).await {
251        Ok(s) => Some(s),
252        Err(e) => {
253            eprintln!("[sysknife-daemon] audit-forward: UDP bind on {bind_addr} failed: {e}");
254            None
255        }
256    }
257}
258
259/// Format `event` as a single RFC 5424 syslog message.
260///
261/// Layout (one line, no trailing newline — UDP datagrams don't need one):
262/// ```text
263/// <PRI>1 TIMESTAMP HOSTNAME APP-NAME PROCID MSGID [SD@32473 ...] MSG
264/// ```
265///
266/// We hold to the spec's printable-USASCII rule for the structured-data
267/// (SD) section by escaping `]`, `"`, and `\` per §6.3.3.
268pub fn format_rfc5424(event: &AuditEvent, facility: u8) -> String {
269    // Severity 5 = NOTICE for audit events. PRI = facility * 8 + severity.
270    let severity = 5u8;
271    let pri = (facility as u32) * 8 + severity as u32;
272
273    let hostname = read_hostname();
274    let app_name = "sysknife-daemon";
275    let procid = std::process::id();
276    let msgid = "AUDIT";
277
278    let risk = match event.risk_level {
279        RiskLevel::Low => "low",
280        RiskLevel::Medium => "medium",
281        RiskLevel::High => "high",
282    };
283
284    // RFC 5424 §6.3 structured data.
285    //
286    // **PEN 32473 is RFC 5612's documentation/test PEN — it MUST be replaced
287    // before production deployment.** RFC 5424 §7.2.2 requires an
288    // IANA-assigned Private Enterprise Number on `SD-ID`s emitted in
289    // production frames. The SysKnife project does not yet hold a PEN; the
290    // 32473 reservation is used here only so the formatter is bytewise
291    // testable. Operators running a SIEM under a regulated framework should
292    // either patch `SD@32473` to their own PEN at build time or treat this
293    // as a known gap (see issue tracker).
294    //
295    // `terminal_status` is appended ONLY for the execute-time forward, so
296    // preview frames remain byte-for-byte unchanged.
297    let terminal_status_param = match &event.final_status {
298        Some(s) => format!(" terminal_status=\"{}\"", sd_escape(s)),
299        None => String::new(),
300    };
301    let sd = format!(
302        "[sysknife@32473 \
303         seq=\"{}\" \
304         tx=\"{}\" \
305         action=\"{}\" \
306         risk=\"{}\" \
307         approval=\"{}\" \
308         role=\"{}\" \
309         chain_hash=\"{}\" \
310         key_id=\"{}\"{terminal_status_param}]",
311        event.seq,
312        sd_escape(&event.transaction_id),
313        sd_escape(&event.action_name),
314        risk,
315        sd_escape(event.approval_id.as_deref().unwrap_or("")),
316        sd_escape(event.caller_role.as_deref().unwrap_or("")),
317        sd_escape(&event.chain_hash),
318        sd_escape(&event.key_id),
319    );
320
321    let msg = format!("[{}] {}", event.action_name, event.summary);
322
323    format!(
324        "<{pri}>1 {ts} {host} {app} {pid} {msgid} {sd} {msg}",
325        ts = event.created_at,
326        host = hostname,
327        app = app_name,
328        pid = procid,
329    )
330}
331
332/// Escape a value for inclusion inside a RFC 5424 SD-PARAM-VALUE per §6.3.3.
333///
334/// RFC 5424 §6 names PRINTUSASCII (`0x21..=0x7E`) as the preferred SD form;
335/// UTF-8 is technically allowed but every strict SIEM ingest pipeline we
336/// have surveyed (Splunk in strict mode, IBM QRadar, Microsoft Sentinel via
337/// the Azure Monitor Agent) rejects non-ASCII bytes inside SD-VALUE. We
338/// therefore drop **every** byte outside the printable-ASCII range and
339/// escape the three characters
340/// `]`, `"`, `\` per §6.3.3.
341///
342/// This also covers DEL (`0x7F`) and C1 controls (`0x80..=0x9F`).
343fn sd_escape(value: &str) -> String {
344    let mut out = String::with_capacity(value.len());
345    for ch in value.chars() {
346        match ch {
347            '"' => out.push_str("\\\""),
348            '\\' => out.push_str("\\\\"),
349            ']' => out.push_str("\\]"),
350            c if (0x20..=0x7E).contains(&(c as u32)) => out.push(c),
351            // Drop everything else (C0, DEL, C1, all non-ASCII Unicode).
352            _ => {}
353        }
354    }
355    out
356}
357
358/// Read the kernel hostname and validate it against RFC 5424 §6.2.4.
359///
360/// HOSTNAME must be a single token: 1..=255 bytes, all `PRINTUSASCII`
361/// (`0x21..=0x7E`), no embedded whitespace. Anything else (empty,
362/// embedded space, non-ASCII, control char) returns the NILVALUE `"-"`
363/// so the datagram remains parseable. Without this, a sysctl-set
364/// hostname containing a space (e.g. `"edge node"`) would corrupt every
365/// emitted frame and silently drop in strict SIEMs.
366fn read_hostname() -> String {
367    let raw = std::fs::read_to_string("/proc/sys/kernel/hostname")
368        .map(|s| s.trim().to_string())
369        .unwrap_or_default();
370    if raw.is_empty() || raw.len() > 255 || !raw.bytes().all(|b| (0x21..=0x7E).contains(&b)) {
371        return "-".to_string();
372    }
373    raw
374}
375
376/// Test-only hostname validator that accepts an externally-provided string,
377/// applies the same RFC 5424 §6.2.4 rule, and returns either the input or
378/// `"-"`. Lets tests cover the validation path without mutating
379/// `/proc/sys/kernel/hostname`.
380#[cfg(test)]
381fn validate_hostname_for_test(raw: &str) -> String {
382    if raw.is_empty() || raw.len() > 255 || !raw.bytes().all(|b| (0x21..=0x7E).contains(&b)) {
383        return "-".to_string();
384    }
385    raw.to_string()
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391
392    fn sample_event() -> AuditEvent {
393        AuditEvent {
394            seq: 42,
395            transaction_id: "tx-abc".to_string(),
396            action_name: "InstallFlatpak".to_string(),
397            risk_level: RiskLevel::Medium,
398            summary: "Install Firefox".to_string(),
399            approval_id: Some("appr-xyz".to_string()),
400            created_at: "2026-04-25T08:30:00Z".to_string(),
401            chain_hash: "deadbeef".to_string(),
402            key_id: "v1".to_string(),
403            caller_role: Some("Dev".to_string()),
404            final_status: None,
405        }
406    }
407
408    // ── Hostname validation ──────────────────────────────────────────────
409
410    #[test]
411    fn hostname_with_space_is_rejected() {
412        assert_eq!(validate_hostname_for_test("edge node 7"), "-");
413    }
414
415    #[test]
416    fn hostname_with_control_byte_is_rejected() {
417        assert_eq!(validate_hostname_for_test("edge\x01node"), "-");
418    }
419
420    #[test]
421    fn hostname_with_non_ascii_is_rejected() {
422        assert_eq!(validate_hostname_for_test("ëdge"), "-");
423    }
424
425    #[test]
426    fn empty_hostname_falls_back_to_nilvalue() {
427        assert_eq!(validate_hostname_for_test(""), "-");
428    }
429
430    #[test]
431    fn legitimate_hostname_passes_through() {
432        assert_eq!(
433            validate_hostname_for_test("edge-node-7.example.com"),
434            "edge-node-7.example.com"
435        );
436    }
437
438    #[test]
439    fn hostname_over_255_bytes_is_rejected() {
440        let long = "a".repeat(256);
441        assert_eq!(validate_hostname_for_test(&long), "-");
442    }
443
444    // ── SD-VALUE strict ASCII ────────────────────────────────────────────
445
446    #[test]
447    fn sd_escape_strips_del_and_c1_controls() {
448        let raw = "before\x7Fafter\u{0085}";
449        assert_eq!(sd_escape(raw), "beforeafter");
450    }
451
452    #[test]
453    fn sd_escape_strips_non_ascii_to_avoid_strict_siem_rejection() {
454        // Splunk/QRadar in strict mode reject non-ASCII inside SD-VALUE.
455        let raw = "café";
456        let escaped = sd_escape(raw);
457        assert!(escaped.bytes().all(|b| (0x20..=0x7E).contains(&b)));
458    }
459
460    // ── RFC 5424 framing ──────────────────────────────────────────────────
461
462    #[test]
463    fn rfc5424_starts_with_pri_and_version() {
464        let frame = format_rfc5424(&sample_event(), 1);
465        // facility=1, severity=5 → PRI = 13. Version = 1.
466        assert!(frame.starts_with("<13>1 "));
467    }
468
469    #[test]
470    fn rfc5424_contains_sd_with_chain_hash_and_seq() {
471        let frame = format_rfc5424(&sample_event(), 1);
472        assert!(frame.contains("[sysknife@32473"));
473        assert!(frame.contains("seq=\"42\""));
474        assert!(frame.contains("chain_hash=\"deadbeef\""));
475        assert!(frame.contains("key_id=\"v1\""));
476        assert!(frame.contains("risk=\"medium\""));
477        assert!(frame.contains("role=\"Dev\""));
478    }
479
480    #[test]
481    fn rfc5424_message_section_contains_summary_and_action_tag() {
482        let frame = format_rfc5424(&sample_event(), 1);
483        assert!(frame.ends_with("[InstallFlatpak] Install Firefox"));
484    }
485
486    #[test]
487    fn sd_escape_handles_dquote_backslash_bracket() {
488        let raw = r#"name with "quotes", a \ backslash, and ] bracket"#;
489        let escaped = sd_escape(raw);
490        assert!(escaped.contains("\\\""));
491        assert!(escaped.contains("\\\\"));
492        assert!(escaped.contains("\\]"));
493    }
494
495    #[test]
496    fn sd_escape_strips_control_characters() {
497        // Control bytes must not appear inside SD-VALUE.
498        let raw = "before\x01\x02\x1fafter";
499        let escaped = sd_escape(raw);
500        assert_eq!(escaped, "beforeafter");
501    }
502
503    #[test]
504    fn rfc5424_missing_approval_renders_empty_string() {
505        let mut e = sample_event();
506        e.approval_id = None;
507        let frame = format_rfc5424(&e, 1);
508        assert!(frame.contains("approval=\"\""));
509    }
510
511    #[test]
512    fn rfc5424_caller_role_with_quote_is_escaped() {
513        let mut e = sample_event();
514        e.caller_role = Some(r#"Dev"name"#.to_string());
515        let frame = format_rfc5424(&e, 1);
516        assert!(frame.contains("role=\"Dev\\\"name\""));
517    }
518
519    #[test]
520    fn rfc5424_facility_changes_pri() {
521        // facility=23 (local7), severity=5 → PRI = 189.
522        let frame = format_rfc5424(&sample_event(), 23);
523        assert!(frame.starts_with("<189>1 "));
524    }
525
526    #[test]
527    fn terminal_status_emitted_when_present() {
528        // Execute-time forward carries the terminal JobState. SOC analysts
529        // need the SD-PARAM in the same frame as the chain hash so they can
530        // pivot from "did the action run?" to "what happened?" without
531        // joining against a second log source.
532        let mut e = sample_event();
533        e.final_status = Some("succeeded".to_string());
534        let frame = format_rfc5424(&e, 1);
535        assert!(
536            frame.contains("terminal_status=\"succeeded\""),
537            "frame missing terminal_status: {frame}"
538        );
539    }
540
541    // ── AuditForwarder behaviour ─────────────────────────────────────────
542
543    #[tokio::test(flavor = "current_thread")]
544    async fn forwarder_drops_on_closed_channel() {
545        let (tx, rx) = mpsc::channel::<AuditEvent>(1);
546        // Drop the receiver to simulate a forwarder task that has exited.
547        drop(rx);
548        let forwarder = AuditForwarder {
549            sender: tx,
550            drops: Arc::new(AtomicU64::new(0)),
551        };
552        forwarder.submit(sample_event());
553        assert_eq!(forwarder.drop_count(), 1);
554    }
555
556    #[tokio::test(flavor = "current_thread")]
557    async fn forwarder_drops_when_full_and_warns_at_threshold() {
558        // Build a channel of capacity 1 so the second submit overflows.
559        let (tx, _rx) = mpsc::channel::<AuditEvent>(1);
560        let forwarder = AuditForwarder {
561            sender: tx,
562            drops: Arc::new(AtomicU64::new(0)),
563        };
564
565        // Fill the channel.
566        forwarder.submit(sample_event()); // queued — drop_count stays 0
567        assert_eq!(forwarder.drop_count(), 0);
568
569        // Now overflow DROP_WARN_THRESHOLD times.
570        for _ in 0..DROP_WARN_THRESHOLD {
571            forwarder.submit(sample_event());
572        }
573        assert_eq!(forwarder.drop_count(), DROP_WARN_THRESHOLD);
574    }
575
576    #[tokio::test(flavor = "current_thread")]
577    async fn forwarder_resets_drop_counter_after_successful_submit() {
578        let (tx, mut rx) = mpsc::channel::<AuditEvent>(1);
579        let forwarder = AuditForwarder {
580            sender: tx,
581            drops: Arc::new(AtomicU64::new(0)),
582        };
583        // First submit lands; second drops (full).
584        forwarder.submit(sample_event());
585        forwarder.submit(sample_event());
586        assert_eq!(forwarder.drop_count(), 1);
587        // Drain — frees a slot.
588        let _ = rx.recv().await;
589        // Next submit succeeds and resets the counter.
590        forwarder.submit(sample_event());
591        assert_eq!(forwarder.drop_count(), 0);
592    }
593
594    // ── End-to-end: spawn() actually emits over a UDP loopback ───────────
595
596    #[tokio::test(flavor = "current_thread")]
597    async fn spawn_sends_udp_datagrams_to_listener() {
598        // Bind a loopback listener first to learn the assigned port.
599        let listener = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
600        let port = listener.local_addr().unwrap().port();
601        let host: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
602
603        let forwarder = spawn(AuditSinkSpec::SyslogUdp { host, facility: 1 });
604        forwarder.submit(sample_event());
605
606        // Receive with a generous timeout.
607        let mut buf = [0u8; 2048];
608        let len = tokio::time::timeout(Duration::from_secs(2), listener.recv(&mut buf))
609            .await
610            .expect("UDP recv timed out — forwarder did not emit")
611            .expect("UDP recv succeeded");
612        let frame = std::str::from_utf8(&buf[..len]).expect("frame is UTF-8");
613        assert!(frame.starts_with("<13>1 "), "unexpected frame: {frame}");
614        assert!(frame.contains("seq=\"42\""));
615        assert!(frame.contains("[InstallFlatpak] Install Firefox"));
616    }
617
618    /// Backoff sequence regression: every consecutive bind failure must
619    /// double the wait, capped at [`MAX_BACKOFF_SECS`].  The dispatcher does
620    /// not currently expose a hook to drive the live `forwarder_task`
621    /// deterministically (it loops on real `recv().await`), but the
622    /// backoff math is extracted to `next_backoff_secs` so we can pin the
623    /// sequence as a pure-function test.  A regression that turns the cap
624    /// off would silently grow retry intervals into hours during a long
625    /// SIEM outage; a regression that breaks doubling would peg a CPU on
626    /// a tight retry loop.  Either way, this test fails first.
627    #[test]
628    fn next_backoff_secs_doubles_then_caps() {
629        // Walk the sequence from the documented start until it has saturated
630        // at the cap for two consecutive steps, so a future increase to
631        // MAX_BACKOFF_SECS doesn't silently make this assertion looser.
632        let mut seen = vec![INITIAL_BACKOFF_SECS];
633        let mut b = INITIAL_BACKOFF_SECS;
634        for _ in 0..32 {
635            b = next_backoff_secs(b);
636            seen.push(b);
637            if seen.len() >= 2
638                && seen[seen.len() - 1] == MAX_BACKOFF_SECS
639                && seen[seen.len() - 2] == MAX_BACKOFF_SECS
640            {
641                break;
642            }
643        }
644
645        // Doubling phase: every value before the cap is exactly 2× its
646        // predecessor.
647        for w in seen.windows(2) {
648            let (prev, next) = (w[0], w[1]);
649            if next == MAX_BACKOFF_SECS {
650                // Either we hit the cap by doubling (prev * 2 >= cap) or we
651                // are saturating (prev == cap). Both are valid.
652                assert!(
653                    prev.saturating_mul(2) >= MAX_BACKOFF_SECS,
654                    "first cap step jumped from {prev} → {next} without doubling"
655                );
656            } else {
657                assert_eq!(next, prev * 2, "non-cap step must double: {prev} → {next}");
658            }
659        }
660
661        // Cap is reached and held — the final two entries are both at the cap.
662        let n = seen.len();
663        assert!(n >= 2);
664        assert_eq!(seen[n - 1], MAX_BACKOFF_SECS);
665        assert_eq!(seen[n - 2], MAX_BACKOFF_SECS);
666        assert_eq!(seen[0], INITIAL_BACKOFF_SECS);
667    }
668
669    /// T8 — RFC 5424 round-trip through a real syslog parser.
670    ///
671    /// Substring `assert!(frame.contains("..."))` checks accept malformed
672    /// frames as long as they happen to contain the expected substring.
673    /// Round-trip the formatter's output through `syslog_loose`, which
674    /// implements RFC 5424's grammar, and assert each parsed field
675    /// matches the input event.  A regression that breaks PRI / VERSION /
676    /// MSGID / SD-ID structure fails parsing here, not in production.
677    #[test]
678    fn rfc5424_round_trip_through_syslog_loose() {
679        let event = sample_event();
680        let facility = 1u8; // user-level
681        let frame = format_rfc5424(&event, facility);
682
683        let parsed = syslog_loose::parse_message(&frame, syslog_loose::Variant::RFC5424);
684
685        // PRI = facility * 8 + severity. Severity for audit events is 5
686        // (NOTICE) — pin both halves through the parser.
687        assert_eq!(
688            parsed.facility.expect("frame has a facility"),
689            syslog_loose::SyslogFacility::LOG_USER,
690            "facility should round-trip as user-level (1)"
691        );
692        assert_eq!(
693            parsed.severity.expect("frame has a severity"),
694            syslog_loose::SyslogSeverity::SEV_NOTICE,
695            "audit events must be NOTICE-severity"
696        );
697        assert!(
698            matches!(parsed.protocol, syslog_loose::Protocol::RFC5424(1)),
699            "RFC 5424 frames carry version=1; got protocol={:?}",
700            parsed.protocol
701        );
702        assert_eq!(parsed.msgid, Some("AUDIT"));
703        assert_eq!(parsed.appname, Some("sysknife-daemon"));
704
705        // Structured-data block: one SD element with id "sysknife@32473"
706        // and the audit fields as params.
707        let sd = parsed
708            .structured_data
709            .iter()
710            .find(|s| s.id == "sysknife@32473")
711            .expect("frame has the sysknife@32473 SD element");
712
713        let get = |key: &str| -> String {
714            sd.params
715                .iter()
716                .find(|(k, _)| *k == key)
717                .map(|(_, v)| (*v).to_string())
718                .unwrap_or_else(|| panic!("SD element missing param {key}: {sd:?}"))
719        };
720        assert_eq!(get("seq"), event.seq.to_string());
721        assert_eq!(get("tx"), event.transaction_id);
722        assert_eq!(get("action"), event.action_name);
723        assert_eq!(get("risk"), "medium");
724        assert_eq!(get("approval"), event.approval_id.unwrap());
725        assert_eq!(get("role"), event.caller_role.unwrap());
726        assert_eq!(get("chain_hash"), event.chain_hash);
727        assert_eq!(get("key_id"), event.key_id);
728    }
729
730    /// IPv6 bind path: `open_udp` must select `[::]:0` for an IPv6 host so
731    /// an IPv6-only SIEM (e.g. Sentinel at `[2001:db8::5]:514`) is reachable.
732    /// Skipped when the kernel has IPv6 disabled (e.g. some hardened CI
733    /// images with `net.ipv6.conf.all.disable_ipv6=1`); the assertion path
734    /// only runs when bind genuinely succeeds.
735    #[tokio::test(flavor = "current_thread")]
736    async fn open_udp_ipv6_host_binds_ipv6_local_socket() {
737        let host: SocketAddr = "[::1]:514".parse().unwrap();
738        let Some(socket) = open_udp(host).await else {
739            // IPv6 disabled in this environment — bind unavailable. The
740            // production guard is exercised by the IPv4 test above.
741            return;
742        };
743        let local = socket.local_addr().expect("bound socket has a local addr");
744        assert!(
745            local.is_ipv6(),
746            "open_udp(IPv6 host) bound to non-IPv6 socket {local}"
747        );
748    }
749}