|
| 1 | +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +//! Collector framing, live settings, and whole-line console writes. |
| 5 | +
|
| 6 | +use std::io::Write; |
| 7 | +use std::sync::atomic::{AtomicBool, Ordering}; |
| 8 | +use std::sync::{Arc, Mutex}; |
| 9 | + |
| 10 | +use openshell_ocsf::{ |
| 11 | + EventContext, NetworkActivityBuilder, OcsfJsonlLayer, OcsfShorthandLayer, ocsf_emit, |
| 12 | +}; |
| 13 | +use tracing_subscriber::layer::SubscriberExt; |
| 14 | + |
| 15 | +/// Capture individual writes to verify queue entries are whole lines. |
| 16 | +#[derive(Clone, Default)] |
| 17 | +struct Records(Arc<Mutex<Vec<Vec<u8>>>>); |
| 18 | + |
| 19 | +impl Write for Records { |
| 20 | + fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> { |
| 21 | + self.0.lock().unwrap().push(bytes.to_vec()); |
| 22 | + Ok(bytes.len()) |
| 23 | + } |
| 24 | + |
| 25 | + fn flush(&mut self) -> std::io::Result<()> { |
| 26 | + Ok(()) |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +fn payload(record: &[u8]) -> serde_json::Value { |
| 31 | + let line = std::str::from_utf8(record).unwrap(); |
| 32 | + assert_eq!(line.lines().count(), 1); |
| 33 | + assert!(line.ends_with('\n')); |
| 34 | + assert!(!line.contains('\x1b')); |
| 35 | + let (timestamp, json) = line.trim_end().split_once(" OCSF-JSON ").unwrap(); |
| 36 | + chrono::DateTime::parse_from_rfc3339(timestamp).unwrap(); |
| 37 | + serde_json::from_str(json).unwrap() |
| 38 | +} |
| 39 | + |
| 40 | +fn context() -> EventContext { |
| 41 | + EventContext { |
| 42 | + sandbox_id: "sb-console".to_string(), |
| 43 | + sandbox_name: "console-test".to_string(), |
| 44 | + container_image: "test-image".to_string(), |
| 45 | + hostname: "test-host".to_string(), |
| 46 | + product_version: "test".to_string(), |
| 47 | + proxy_ip: std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), |
| 48 | + proxy_port: 3128, |
| 49 | + origin: openshell_ocsf::EventOrigin::Supervisor, |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +#[test] |
| 54 | +fn console_json_toggles_and_downgrades_without_changing_event_identity() { |
| 55 | + let records = Records::default(); |
| 56 | + let enabled = Arc::new(AtomicBool::new(false)); |
| 57 | + let version = Arc::new(Mutex::new(String::new())); |
| 58 | + let subscriber = tracing_subscriber::registry().with( |
| 59 | + OcsfJsonlLayer::new(records.clone()) |
| 60 | + .with_console_format() |
| 61 | + .with_enabled_flag(enabled.clone()) |
| 62 | + .with_target_version(version.clone()), |
| 63 | + ); |
| 64 | + let event = NetworkActivityBuilder::new(&context()) |
| 65 | + .dst_endpoint(openshell_ocsf::Endpoint::from_domain("example.com", 443)) |
| 66 | + .message("first line\nsecond line") |
| 67 | + .build(); |
| 68 | + let expected = event.to_json().unwrap(); |
| 69 | + tracing::subscriber::with_default(subscriber, || { |
| 70 | + ocsf_emit!(event.clone()); |
| 71 | + tracing::warn!("diagnostics are not JSON audit events"); |
| 72 | + enabled.store(true, Ordering::Relaxed); |
| 73 | + ocsf_emit!(event.clone()); |
| 74 | + *version.lock().unwrap() = "1.3".to_string(); |
| 75 | + ocsf_emit!(event.clone()); |
| 76 | + enabled.store(false, Ordering::Relaxed); |
| 77 | + ocsf_emit!(event); |
| 78 | + }); |
| 79 | + let records = records.0.lock().unwrap(); |
| 80 | + assert_eq!(records.len(), 2); |
| 81 | + assert_eq!(payload(&records[0]), expected); |
| 82 | + let downgraded = payload(&records[1]); |
| 83 | + assert_eq!(downgraded["metadata"]["version"], "1.3"); |
| 84 | + assert_eq!(downgraded["metadata"]["uid"], expected["metadata"]["uid"]); |
| 85 | + assert_eq!(downgraded["message"], expected["message"]); |
| 86 | +} |
| 87 | + |
| 88 | +#[test] |
| 89 | +fn concurrent_console_formats_submit_complete_records() { |
| 90 | + let records = Records::default(); |
| 91 | + let subscriber = tracing_subscriber::registry() |
| 92 | + .with(OcsfShorthandLayer::new(records.clone())) |
| 93 | + .with(OcsfJsonlLayer::new(records.clone()).with_console_format()); |
| 94 | + let dispatch = tracing::Dispatch::new(subscriber); |
| 95 | + std::thread::scope(|scope| { |
| 96 | + for worker in 0..8 { |
| 97 | + let dispatch = dispatch.clone(); |
| 98 | + scope.spawn(move || { |
| 99 | + tracing::dispatcher::with_default(&dispatch, || { |
| 100 | + for index in 0..50 { |
| 101 | + tracing::info!("diagnostic {worker}:{index}"); |
| 102 | + ocsf_emit!( |
| 103 | + NetworkActivityBuilder::new(&context()) |
| 104 | + .dst_endpoint(openshell_ocsf::Endpoint::from_domain( |
| 105 | + "example.com", |
| 106 | + 443 |
| 107 | + )) |
| 108 | + .message(format!("connection {worker}:{index}")) |
| 109 | + .build() |
| 110 | + ); |
| 111 | + } |
| 112 | + }); |
| 113 | + }); |
| 114 | + } |
| 115 | + }); |
| 116 | + let records = records.0.lock().unwrap(); |
| 117 | + assert_eq!(records.len(), 8 * 50 * 3); |
| 118 | + let mut json_count = 0; |
| 119 | + for record in records.iter() { |
| 120 | + let line = std::str::from_utf8(record).unwrap(); |
| 121 | + assert_eq!(line.lines().count(), 1); |
| 122 | + assert!(line.ends_with('\n')); |
| 123 | + if line.contains(" OCSF-JSON ") { |
| 124 | + payload(record); |
| 125 | + json_count += 1; |
| 126 | + } else { |
| 127 | + assert!(line.contains(" OCSF ") || line.contains(" INFO ")); |
| 128 | + } |
| 129 | + } |
| 130 | + assert_eq!(json_count, 8 * 50); |
| 131 | +} |
0 commit comments