Skip to content

Commit 8a20212

Browse files
authored
feat(observability): correlate HTTP receipts, OCSF and request traces (#5214)
* feat(observability): correlate HTTP receipts, audit records and traces Closes #5393 Refs #5210 Signed-off-by: Alex Fournier <afournier@nvidia.com> * fix(observability): narrow receipt validation and simplify tests Signed-off-by: Alex Fournier <afournier@nvidia.com> * refactor(observability): preserve per-control HTTP audit records Correlate original control records at emission with a request-scoped ID and sequence. Remove primary-record aggregation and broad response-head validation while retaining protected receipts and request tracing. Signed-off-by: Alex Fournier <afournier@nvidia.com> * fix(observability): preserve HTTP correlation through relay failures Avoid parsing queries solely for correlation. Carry request attribution through terminal errors and policy reloads, and clear HTTP scope at WebSocket upgrade. Preserve per-control audit records while reporting bounded stage outcomes and filtering receipt trailers consistently. Remove JSON receipt additions and the unused correlation setter. Signed-off-by: Alex Fournier <afournier@nvidia.com> * fix(observability): finish stage results and isolate correlation fixtures Signed-off-by: Alex Fournier <afournier@nvidia.com> * fix(observability): report handled middleware stage failures Signed-off-by: Alex Fournier <afournier@nvidia.com> * fix(observability): complete proxy request correlation paths Signed-off-by: Alex Fournier <afournier@nvidia.com> --------- Signed-off-by: Alex Fournier <afournier@nvidia.com>
1 parent e7d2dc7 commit 8a20212

36 files changed

Lines changed: 9596 additions & 859 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ ocsf_emit!(event);
153153

154154
- `crate::ocsf_ctx()` returns the process-wide `EventContext`. It is always available (falls back to defaults in tests).
155155
- `ocsf_emit!()` is non-blocking and cannot panic. It stores the event in a thread-local and emits via `tracing::info!()`.
156-
- In `openshell-supervisor-network`, emit with `crate::telemetry::egress_emit!` instead, or `crate::telemetry::emit_decision` for the records of one decision, so denied HTTP decisions get a deny span. Clippy rejects `ocsf_emit!` there.
156+
- In `openshell-supervisor-network`, the inspected request scope automatically correlates all OCSF records at emission, including findings, and uses the request span without creating a denial-only span. Emit through `crate::telemetry::egress_emit!` or `crate::telemetry::emit_decision`; Clippy rejects direct `ocsf_emit!` calls there.
157157
- The shorthand layer and JSONL layer extract the event from the thread-local. The shorthand format is derived automatically from the builder fields.
158158
- For security findings, **dual-emit**: one domain event (e.g., `SshActivityBuilder`) AND one `DetectionFindingBuilder` for the same incident.
159159
- Never log secrets, credentials, or query parameters in OCSF messages. The OCSF JSONL file may be shipped to external systems.

‎Cargo.lock‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/openshell-ocsf/src/events/mod.rs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,29 @@ mod tests {
281281
assert_eq!(deserialized.class_uid(), 2004);
282282
}
283283

284+
#[test]
285+
fn correlation_uid_can_be_set_on_any_event_class() {
286+
let ctx = test_sandbox_context();
287+
let mut event = AuthenticationBuilder::new(
288+
&ctx,
289+
User::other("user-1", "User"),
290+
Service::new("gateway"),
291+
)
292+
.status(StatusId::Success)
293+
.build();
294+
295+
event.base_mut().metadata.correlation_uid = Some("request-123".into());
296+
297+
assert_eq!(
298+
event.base().metadata.correlation_uid.as_deref(),
299+
Some("request-123")
300+
);
301+
assert_eq!(
302+
serde_json::to_value(&event).unwrap()["metadata"]["correlation_uid"],
303+
"request-123"
304+
);
305+
}
306+
284307
#[test]
285308
fn test_roundtrip_application_lifecycle() {
286309
let ctx = test_sandbox_context();

‎crates/openshell-ocsf/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,5 +74,5 @@ pub use builders::{
7474
pub use tracing_layers::{
7575
OCSF_TARGET, OcsfJsonSettings, OcsfJsonlLayer, OcsfShorthandLayer, bind_thread_json_settings,
7676
clear_current_event, clone_current_event, emit_ocsf_event, emit_ocsf_event_routed,
77-
set_current_event,
77+
register_event_enricher, set_current_event,
7878
};

‎crates/openshell-ocsf/src/tracing_layers/event_bridge.rs‎

Lines changed: 118 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,11 @@
88
//! layers intercept this target, clone the event, and format it.
99
//! After dispatch, `emit_ocsf_event` clears the thread-local.
1010
11-
use crate::events::OcsfEvent;
11+
use std::sync::OnceLock;
12+
13+
use crate::events::{BaseEventData, OcsfEvent};
14+
15+
static EVENT_ENRICHER: OnceLock<fn(&mut BaseEventData)> = OnceLock::new();
1216

1317
std::thread_local! {
1418
// Thread-local storage for the current OCSF event being emitted.
@@ -19,6 +23,27 @@ std::thread_local! {
1923
/// Target string used to identify OCSF tracing events.
2024
pub const OCSF_TARGET: &str = "ocsf";
2125

26+
/// Register optional process-wide event enrichment at startup.
27+
///
28+
/// The callback runs once per emission, before any output layer receives the
29+
/// record, independently of trace sampling or export. It receives the common
30+
/// base fields for every event class and should add only contextual fields,
31+
/// preserving the record's content, classification, and timestamp. It must not
32+
/// block, panic, or emit another OCSF event.
33+
///
34+
/// Returns `false` if an enricher is already registered. Without an enricher,
35+
/// emission does not add application-specific context.
36+
pub fn register_event_enricher(enricher: fn(&mut BaseEventData)) -> bool {
37+
EVENT_ENRICHER.set(enricher).is_ok()
38+
}
39+
40+
fn enrich(event: &mut OcsfEvent) {
41+
crate::trace::enrich(event);
42+
if let Some(enrich) = EVENT_ENRICHER.get() {
43+
enrich(event.base_mut());
44+
}
45+
}
46+
2247
/// Clone the current thread-local OCSF event, if any.
2348
///
2449
/// Multiple layers can call this for the same event — each receives
@@ -35,7 +60,7 @@ pub fn clone_current_event() -> Option<OcsfEvent> {
3560
///
3661
/// Both layers receive the event — `clone_current_event()` is non-consuming.
3762
pub fn emit_ocsf_event(mut event: OcsfEvent) {
38-
crate::trace::enrich(&mut event);
63+
enrich(&mut event);
3964
// Store the event in thread-local so layers can access it
4065
set_current_event(event);
4166

@@ -83,7 +108,7 @@ pub fn clear_current_event() {
83108
/// per-event `sandbox_id` field here instead. One tracing event feeds both the
84109
/// JSONL audit file and the routing bus.
85110
pub fn emit_ocsf_event_routed(sandbox_id: &str, mut event: OcsfEvent) {
86-
crate::trace::enrich(&mut event);
111+
enrich(&mut event);
87112
let message = event.format_shorthand();
88113
set_current_event(event);
89114
tracing::info!(target: "ocsf", sandbox_id = %sandbox_id, message = %message);
@@ -111,6 +136,22 @@ mod tests {
111136
use crate::events::{BaseEvent, OcsfEvent};
112137
use crate::objects::{Metadata, Product};
113138

139+
std::thread_local! {
140+
// Registration is process-wide, but this test's callback must be inert
141+
// for unrelated tests running in parallel or reusing this thread later.
142+
static TEST_ENRICHER_SEQUENCE: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
143+
}
144+
145+
fn test_enricher(event: &mut BaseEventData) {
146+
TEST_ENRICHER_SEQUENCE.with(|sequence| {
147+
if let Some(next) = sequence.get() {
148+
sequence.set(Some(next + 1));
149+
event.metadata.correlation_uid = Some("emit-time-request".into());
150+
event.add_unmapped("request_sequence", next);
151+
}
152+
});
153+
}
154+
114155
fn test_event() -> OcsfEvent {
115156
OcsfEvent::Base(BaseEvent {
116157
base: BaseEventData::new(
@@ -238,4 +279,78 @@ mod tests {
238279
"routed emit must match the bare path JSON"
239280
);
240281
}
282+
283+
#[test]
284+
fn event_enrichment_runs_once_for_every_class_and_output_path() {
285+
use crate::test_support::OcsfCapture;
286+
use crate::tracing_layers::OcsfJsonlLayer;
287+
use tracing_subscriber::prelude::*;
288+
289+
assert!(register_event_enricher(test_enricher));
290+
assert!(!register_event_enricher(test_enricher));
291+
let capture = OcsfCapture::default();
292+
let bytes = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
293+
let subscriber = tracing_subscriber::registry()
294+
.with(capture.clone())
295+
.with(OcsfJsonlLayer::new(SharedWriter(bytes.clone())));
296+
let context = crate::builders::test_sandbox_context();
297+
let mut expected = Vec::new();
298+
299+
tracing::subscriber::with_default(subscriber, || {
300+
struct ResetEnricher;
301+
impl Drop for ResetEnricher {
302+
fn drop(&mut self) {
303+
TEST_ENRICHER_SEQUENCE.with(|sequence| sequence.set(None));
304+
}
305+
}
306+
let plain = test_event();
307+
expected.push(plain.clone());
308+
emit_ocsf_event(plain);
309+
310+
{
311+
let _reset = ResetEnricher;
312+
TEST_ENRICHER_SEQUENCE.with(|sequence| sequence.set(Some(1)));
313+
let mut sequence = 1;
314+
for routed in [false, true] {
315+
for (_, mut event) in crate::builders::sample_events(&context) {
316+
event.base_mut().add_unmapped("source_detail", "keep");
317+
event
318+
.base_mut()
319+
.add_unmapped("http_event_kind", "original_kind");
320+
let mut enriched = event.clone();
321+
enriched.base_mut().metadata.correlation_uid =
322+
Some("emit-time-request".into());
323+
enriched
324+
.base_mut()
325+
.add_unmapped("request_sequence", sequence);
326+
expected.push(enriched);
327+
if routed {
328+
emit_ocsf_event_routed("test-sandbox", event);
329+
} else {
330+
emit_ocsf_event(event);
331+
}
332+
assert!(clone_current_event().is_none());
333+
sequence += 1;
334+
}
335+
}
336+
TEST_ENRICHER_SEQUENCE.with(|next| assert_eq!(next.get(), Some(sequence)));
337+
}
338+
339+
let plain = test_event();
340+
expected.push(plain.clone());
341+
emit_ocsf_event_routed("test-sandbox", plain);
342+
});
343+
344+
assert_eq!(capture.events(), expected);
345+
let expected_json: Vec<_> = expected
346+
.iter()
347+
.map(|event| event.to_json().unwrap())
348+
.collect();
349+
let output = String::from_utf8(bytes.lock().unwrap().clone()).unwrap();
350+
let json: Vec<serde_json::Value> = output
351+
.lines()
352+
.map(|line| serde_json::from_str(line).unwrap())
353+
.collect();
354+
assert_eq!(json, expected_json);
355+
}
241356
}

‎crates/openshell-ocsf/src/tracing_layers/mod.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ mod shorthand_layer;
1313

1414
pub use event_bridge::{
1515
OCSF_TARGET, clear_current_event, clone_current_event, emit_ocsf_event, emit_ocsf_event_routed,
16-
set_current_event,
16+
register_event_enricher, set_current_event,
1717
};
1818
pub use jsonl_layer::{OcsfJsonSettings, OcsfJsonlLayer, bind_thread_json_settings};
1919
pub use shorthand_layer::OcsfShorthandLayer;

‎crates/openshell-otel/src/ocsf.rs‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ const MAX_EXPORT_ATTEMPTS: usize = 4;
3434
const INITIAL_BACKOFF: Duration = Duration::from_millis(250);
3535
const MAX_BACKOFF: Duration = Duration::from_secs(2);
3636
const GAP_EVENT: &str = "openshell.ocsf.gap";
37+
const CORRELATION_UID_ATTRIBUTE: &str = "ocsf.metadata.correlation_uid";
3738

3839
/// Exports OCSF events to an OTLP collector as log records.
3940
pub struct OcsfOtlp {
@@ -391,6 +392,9 @@ fn log_record(
391392
if let Some(uid) = &base.metadata.uid {
392393
record.add_attribute("ocsf.metadata.uid", uid.clone());
393394
}
395+
if let Some(uid) = &base.metadata.correlation_uid {
396+
record.add_attribute(CORRELATION_UID_ATTRIBUTE, uid.clone());
397+
}
394398
if let Some(sandbox_id) = event.sandbox_id() {
395399
record.add_attribute("openshell.sandbox.id", sandbox_id.to_string());
396400
}
@@ -629,6 +633,19 @@ mod tests {
629633
assert_eq!(native(&event)["resources"][0]["uid"], "requested-sandbox");
630634
}
631635

636+
#[test]
637+
fn correlation_uid_is_a_stable_otlp_attribute() {
638+
let mut event = event("sandbox-1", SeverityId::Informational);
639+
let OcsfEvent::DeviceConfigStateChange(config) = &mut event else {
640+
unreachable!("event fixture returns a configuration event");
641+
};
642+
config.base.metadata.correlation_uid = Some("request-123".into());
643+
assert_eq!(
644+
attribute(&record(&event), CORRELATION_UID_ATTRIBUTE),
645+
Some(AnyValue::String("request-123".into()))
646+
);
647+
}
648+
632649
#[test]
633650
fn events_without_a_sandbox_carry_no_sandbox_attribute() {
634651
let record = record(&event("", SeverityId::Informational));
@@ -788,12 +805,27 @@ mod tests {
788805
.with(otlp.layer());
789806
let span_context = tracing::subscriber::with_default(subscriber, || {
790807
let span = tracing::info_span!("decision");
791-
span.in_scope(|| ocsf_emit!(event("sandbox-1", SeverityId::Medium)));
808+
let mut event = event("sandbox-1", SeverityId::Medium);
809+
let OcsfEvent::DeviceConfigStateChange(config) = &mut event else {
810+
unreachable!("event fixture returns a configuration event");
811+
};
812+
config.base.metadata.correlation_uid =
813+
Some("request-with-or-without-sampling".into());
814+
span.in_scope(|| ocsf_emit!(event));
792815
span.context().span().span_context().clone()
793816
});
794817
otlp.shutdown().await;
795818

796819
let records = exporter.exported();
820+
assert_eq!(records.len(), 1);
821+
assert_eq!(
822+
attribute(&records[0].record, CORRELATION_UID_ATTRIBUTE),
823+
Some(AnyValue::String("request-with-or-without-sampling".into()))
824+
);
825+
assert_eq!(
826+
body(&records[0].record)["metadata"]["correlation_uid"],
827+
"request-with-or-without-sampling"
828+
);
797829
let trace = records[0].record.trace_context();
798830
if span_context.is_sampled() {
799831
let trace = trace.expect("sampled span context is attached");

‎crates/openshell-supervisor-middleware/src/headers.rs‎

Lines changed: 60 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -366,25 +366,31 @@ fn is_safe_value(value: &str) -> bool {
366366
}
367367

368368
fn is_request_protected(name: &str) -> bool {
369-
matches!(
370-
name,
371-
"authorization"
372-
| "proxy-authorization"
373-
| "proxy-authenticate"
374-
| "cookie"
375-
| "host"
376-
| "content-length"
377-
| "transfer-encoding"
378-
| "connection"
379-
| "proxy-connection"
380-
| "keep-alive"
381-
| "te"
382-
| "trailer"
383-
| "upgrade"
384-
) || name.starts_with("x-amz-")
369+
is_platform_correlation_header(name)
370+
|| matches!(
371+
name,
372+
"authorization"
373+
| "proxy-authorization"
374+
| "proxy-authenticate"
375+
| "cookie"
376+
| "host"
377+
| "content-length"
378+
| "transfer-encoding"
379+
| "connection"
380+
| "proxy-connection"
381+
| "keep-alive"
382+
| "te"
383+
| "trailer"
384+
| "upgrade"
385+
)
386+
|| name.starts_with("x-amz-")
385387
|| name.starts_with("x-openshell-credential")
386388
}
387389

390+
fn is_platform_correlation_header(name: &str) -> bool {
391+
name == "x-openshell-request-id"
392+
}
393+
388394
/// Return whether a response header can carry authentication material and must
389395
/// never be exposed to middleware.
390396
#[must_use]
@@ -402,7 +408,8 @@ pub fn is_response_credential_header(name: &str) -> bool {
402408
}
403409

404410
fn is_response_protected(name: &str) -> bool {
405-
is_response_credential_header(name)
411+
is_platform_correlation_header(name)
412+
|| is_response_credential_header(name)
406413
|| matches!(
407414
name,
408415
"connection"
@@ -488,6 +495,42 @@ mod tests {
488495
);
489496
}
490497

498+
#[test]
499+
fn platform_request_id_is_immutable_for_all_http_phases() {
500+
for authority in [
501+
HeaderAuthority::Request,
502+
HeaderAuthority::HookRequest,
503+
HeaderAuthority::RequestTrailers,
504+
HeaderAuthority::Response,
505+
HeaderAuthority::HookResponse,
506+
HeaderAuthority::ResponseTrailers,
507+
] {
508+
let name = "X-OpenShell-Request-ID";
509+
let write_error = apply(
510+
authority,
511+
&[],
512+
&[],
513+
&[write(name, "forged", ExistingHeaderAction::Overwrite)],
514+
)
515+
.expect_err("platform request ID write");
516+
assert_eq!(
517+
write_error,
518+
HeaderMutationError::Protected {
519+
name: name.to_string()
520+
}
521+
);
522+
523+
let remove_error = apply(authority, &[], &[], &[remove(name)])
524+
.expect_err("platform request ID removal");
525+
assert_eq!(
526+
remove_error,
527+
HeaderMutationError::Protected {
528+
name: name.to_string()
529+
}
530+
);
531+
}
532+
}
533+
491534
#[test]
492535
fn unsafe_header_value_is_rejected() {
493536
let error = apply(

0 commit comments

Comments
 (0)