diff --git a/Cargo.lock b/Cargo.lock index 08333b3..9f5a8b6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3947,6 +3947,7 @@ dependencies = [ "opentelemetry", "tracing", "tracing-core", + "tracing-opentelemetry", "tracing-subscriber", ] diff --git a/compliance-agent/src/api/mod.rs b/compliance-agent/src/api/mod.rs index be386da..cc22552 100644 --- a/compliance-agent/src/api/mod.rs +++ b/compliance-agent/src/api/mod.rs @@ -3,5 +3,6 @@ pub mod handlers; pub mod role_gate; pub mod routes; pub mod server; +pub mod trace; pub use server::start_api_server; diff --git a/compliance-agent/src/api/server.rs b/compliance-agent/src/api/server.rs index 51dbb55..c69a011 100644 --- a/compliance-agent/src/api/server.rs +++ b/compliance-agent/src/api/server.rs @@ -444,7 +444,11 @@ pub async fn start_api_server( &agent.config.cors_allowed_origins, agent.config.app_env, )) - .layer(TraceLayer::new_for_http()) + .layer( + TraceLayer::new_for_http() + .make_span_with(crate::api::trace::make_span) + .on_response(crate::api::trace::on_response), + ) // Security headers (defense-in-depth, primary enforcement via Traefik) .layer(SetResponseHeaderLayer::overriding( axum::http::header::STRICT_TRANSPORT_SECURITY, diff --git a/compliance-agent/src/api/trace.rs b/compliance-agent/src/api/trace.rs new file mode 100644 index 0000000..d91958f --- /dev/null +++ b/compliance-agent/src/api/trace.rs @@ -0,0 +1,146 @@ +//! One server span per HTTP request, for `TraceLayer` (instrumentation plan, +//! research/observability/2026-10-28-instrumentation-portal-registry-db.md). +//! +//! The default `TraceLayer` span is DEBUG (so the INFO filter drops it) and +//! records the full URI. This one is INFO, named after the route template +//! (`GET /api/v1/targets/{id}`), continues an incoming `traceparent` (portal, +//! registry) and records no path, query or client address. + +use std::time::Duration; + +use axum::extract::{MatchedPath, Request}; +use axum::response::Response; +use tracing::Span; + +/// The health route is polled every few seconds and gets no span. +const UNTRACED: &[&str] = &["/api/v1/health"]; + +pub fn make_span(req: &Request) -> Span { + let route = req + .extensions() + .get::() + .map(MatchedPath::as_str); + if route.is_some_and(|r| UNTRACED.contains(&r)) { + return Span::none(); + } + let method = req.method().as_str(); + let span = tracing::info_span!( + "http", + otel.name = %format!("{method} {}", route.unwrap_or("unmatched")), + otel.kind = "server", + otel.status_code = tracing::field::Empty, + http.request.method = %method, + http.route = route.unwrap_or(""), + http.response.status_code = tracing::field::Empty, + ); + let header = |name: &str| req.headers().get(name).and_then(|v| v.to_str().ok()); + compliance_core::telemetry::continue_trace(&span, header("traceparent"), header("tracestate")); + span +} + +pub fn on_response(res: &Response, _latency: Duration, span: &Span) { + span.record("http.response.status_code", res.status().as_u16()); + if res.status().is_server_error() { + span.record("otel.status_code", "ERROR"); + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::*; + use axum::body::Body; + use axum::routing::get; + use axum::Router; + use std::sync::{Arc, Mutex}; + use tower::ServiceExt as _; + use tower_http::trace::TraceLayer; + use tracing::field::{Field, Visit}; + use tracing::span::{Attributes, Id, Record}; + use tracing_subscriber::layer::{Context, SubscriberExt as _}; + use tracing_subscriber::Layer; + + /// Every field recorded on any span, as "name=value". + #[derive(Clone, Default)] + struct Fields(Arc>>); + struct Collect<'a>(&'a Mutex>); + impl Visit for Collect<'_> { + fn record_debug(&mut self, f: &Field, v: &dyn std::fmt::Debug) { + self.0.lock().unwrap().push(format!("{}={v:?}", f.name())); + } + fn record_str(&mut self, f: &Field, v: &str) { + self.0.lock().unwrap().push(format!("{}={v}", f.name())); + } + } + impl Layer for Fields { + fn on_new_span(&self, a: &Attributes<'_>, _: &Id, _: Context<'_, S>) { + a.record(&mut Collect(&self.0)); + } + fn on_record(&self, _: &Id, r: &Record<'_>, _: Context<'_, S>) { + r.record(&mut Collect(&self.0)); + } + } + + async fn call(path: &str, status: u16) -> Vec { + let fields = Fields::default(); + let sub = tracing_subscriber::registry().with(fields.clone()); + let _guard = tracing::subscriber::set_default(sub); + let app = Router::new() + .route("/api/v1/health", get(|| async { "ok" })) + .route( + "/api/v1/targets/{id}", + get(move || async move { axum::http::StatusCode::from_u16(status).unwrap() }), + ) + .layer( + TraceLayer::new_for_http() + .make_span_with(make_span) + .on_response(on_response), + ); + let req = Request::builder().uri(path).body(Body::empty()).unwrap(); + app.oneshot(req).await.unwrap(); + let out = fields.0.lock().unwrap().clone(); + out + } + + #[tokio::test] + async fn names_the_span_after_the_route_and_keeps_the_path_out() { + let f = call("/api/v1/targets/acme-firmware?token=x", 200).await; + assert!( + f.contains(&"otel.name=GET /api/v1/targets/{id}".to_string()), + "{f:?}" + ); + assert!( + f.contains(&"http.route=/api/v1/targets/{id}".to_string()), + "{f:?}" + ); + assert!( + f.contains(&"http.response.status_code=200".to_string()), + "{f:?}" + ); + assert!( + f.iter() + .all(|x| !x.contains("acme") && !x.contains("token")), + "{f:?}" + ); + assert!( + !f.iter().any(|x| x.starts_with("otel.status_code")), + "{f:?}" + ); + } + + #[tokio::test] + async fn a_server_error_marks_the_span() { + let f = call("/api/v1/targets/1", 503).await; + assert!(f.contains(&"otel.status_code=ERROR".to_string()), "{f:?}"); + } + + #[tokio::test] + async fn health_and_unmatched() { + assert!( + call("/api/v1/health", 200).await.is_empty(), + "health gets no span" + ); + let f = call("/nope/acme", 200).await; + assert!(f.contains(&"otel.name=GET unmatched".to_string()), "{f:?}"); + } +} diff --git a/compliance-agent/src/registry.rs b/compliance-agent/src/registry.rs index c7207cc..339fae5 100644 --- a/compliance-agent/src/registry.rs +++ b/compliance-agent/src/registry.rs @@ -328,6 +328,10 @@ impl RegistryClient { if let Some(tok) = self.bearer().await? { rb = rb.bearer_auth(tok); } + // traceparent: the registry's spans join this request's trace. + for (name, value) in compliance_core::telemetry::trace_context_headers() { + rb = rb.header(name, value); + } Ok(rb) } diff --git a/compliance-core/Cargo.toml b/compliance-core/Cargo.toml index 338d236..3945761 100644 --- a/compliance-core/Cargo.toml +++ b/compliance-core/Cargo.toml @@ -54,7 +54,9 @@ mongodb = { workspace = true, optional = true } opentelemetry = { version = "0.29", optional = true } opentelemetry_sdk = { version = "0.29", features = ["rt-tokio"], optional = true } opentelemetry-otlp = { version = "0.29", features = ["http", "reqwest-rustls"], optional = true } -opentelemetry-appender-tracing = { version = "0.29", optional = true } +# experimental_use_tracing_span_context: an OTLP log record carries the +# trace_id/span_id of the span it was logged in, so SigNoz links logs and traces. +opentelemetry-appender-tracing = { version = "0.29", optional = true, features = ["experimental_use_tracing_span_context"] } tracing-opentelemetry = { version = "0.30", optional = true } tracing-subscriber = { workspace = true, optional = true } tracing = { workspace = true, optional = true } diff --git a/compliance-core/src/telemetry.rs b/compliance-core/src/telemetry.rs index 5e933fc..17d26f1 100644 --- a/compliance-core/src/telemetry.rs +++ b/compliance-core/src/telemetry.rs @@ -19,8 +19,11 @@ use opentelemetry::trace::TracerProvider as _; use opentelemetry::KeyValue; use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge; use opentelemetry_otlp::{LogExporter, SpanExporter, WithExportConfig}; -use opentelemetry_sdk::{logs::SdkLoggerProvider, trace::SdkTracerProvider, Resource}; -use tracing_opentelemetry::OpenTelemetryLayer; +use opentelemetry_sdk::{ + logs::SdkLoggerProvider, propagation::TraceContextPropagator, trace::SdkTracerProvider, + Resource, +}; +use tracing_opentelemetry::{OpenTelemetryLayer, OpenTelemetrySpanExt as _}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer as _}; /// Guard that shuts down OTel providers on drop. @@ -68,6 +71,9 @@ fn build_resource(service_name: &str) -> Resource { /// Panics if the tracing subscriber cannot be initialized (e.g. called twice). pub fn init_telemetry(service_name: &str) -> TelemetryGuard { let otel_endpoint = std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT").ok(); + // W3C trace context in and out (traceparent), so a call from the portal or + // the registry and Prüfwerk's own calls to the registry stay one trace. + global::set_text_map_propagator(TraceContextPropagator::new()); let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); let fmt_layer = tracing_subscriber::fmt::layer(); @@ -150,3 +156,103 @@ pub fn init_telemetry(service_name: &str) -> TelemetryGuard { } } } + +/// The W3C headers (`traceparent`, `tracestate`) for an outbound request made +/// inside the current span; empty outside a trace or with telemetry off. +pub fn trace_context_headers() -> Vec<(String, String)> { + struct Headers(Vec<(String, String)>); + impl opentelemetry::propagation::Injector for Headers { + fn set(&mut self, key: &str, value: String) { + self.0.push((key.to_string(), value)); + } + } + let cx = tracing::Span::current().context(); + let mut headers = Headers(Vec::new()); + global::get_text_map_propagator(|p| p.inject_context(&cx, &mut headers)); + headers.0 +} + +/// Makes `span` a child of the caller's trace when the request carried a +/// `traceparent` (and optionally `tracestate`); without one it stays a root. +pub fn continue_trace(span: &tracing::Span, traceparent: Option<&str>, tracestate: Option<&str>) { + let Some(traceparent) = traceparent else { + return; + }; + struct Carrier<'a>(&'a str, Option<&'a str>); + impl opentelemetry::propagation::Extractor for Carrier<'_> { + fn get(&self, key: &str) -> Option<&str> { + match key { + "traceparent" => Some(self.0), + "tracestate" => self.1, + _ => None, + } + } + fn keys(&self) -> Vec<&str> { + vec!["traceparent", "tracestate"] + } + } + let parent = global::get_text_map_propagator(|p| p.extract(&Carrier(traceparent, tracestate))); + span.set_parent(parent); +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod propagation_tests { + use super::*; + use opentelemetry::trace::TraceContextExt as _; + + const PARENT: &str = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"; + + fn subscriber() -> impl tracing::Subscriber { + let tracer = SdkTracerProvider::builder().build().tracer("test"); + tracing_subscriber::registry().with(OpenTelemetryLayer::new(tracer)) + } + + #[test] + fn a_traceparent_is_continued_and_passed_on() { + global::set_text_map_propagator(TraceContextPropagator::new()); + tracing::subscriber::with_default(subscriber(), || { + let span = tracing::info_span!("request"); + continue_trace(&span, Some(PARENT), None); + let trace_id = span.context().span().span_context().trace_id().to_string(); + assert_eq!(trace_id, "0af7651916cd43dd8448eb211c80319c"); + + let _entered = span.enter(); + let headers = trace_context_headers(); + let (_, value) = headers + .iter() + .find(|(k, _)| k == "traceparent") + .expect("traceparent"); + assert!( + value.starts_with("00-0af7651916cd43dd8448eb211c80319c-"), + "{value}" + ); + assert!( + !value.contains("b7ad6b7169203331"), + "the child passes its own span id" + ); + }); + } + + #[test] + fn without_a_traceparent_the_span_stays_a_root() { + global::set_text_map_propagator(TraceContextPropagator::new()); + tracing::subscriber::with_default(subscriber(), || { + let span = tracing::info_span!("request"); + continue_trace(&span, None, None); + let ctx = span.context(); + let sc = ctx.span().span_context().clone(); + assert!(sc.is_valid(), "a root span of its own"); + assert_ne!( + sc.trace_id().to_string(), + "0af7651916cd43dd8448eb211c80319c" + ); + }); + } + + #[test] + fn outside_a_trace_no_headers_are_sent() { + global::set_text_map_propagator(TraceContextPropagator::new()); + assert!(trace_context_headers().is_empty()); + } +}