Skip to content

Commit 3f17b08

Browse files
committed
fix(cli): normalize trace-context env reading and cover interceptor composition
Review follow-ups on the trace-context forwarding feature: - Normalize each TRACEPARENT/TRACESTATE spelling (trim, drop blanks) before the lower-case fallback so a blank upper-case value no longer shadows a valid lower-case one - Share one env-reading helper between EnvTraceContextInterceptor and set_parent_from_environment so both paths agree on what counts as set - Pass the TRACEPARENT_ENV/TRACESTATE_ENV constants instead of duplicated string literals - Log at debug level when a present TRACEPARENT is invalid, keeping the passive no-op behavior but leaving a grep-able signal - Cover EnvTraceContext::from_env (both spellings, padding, blanks) and the GatewayInterceptor auth+trace composition with tests - Drop tracestate when traceparent is invalid, and assert it in tests - Narrow the traces.mdx claim to standard CLI commands, since term and completions build clients without the trace interceptor Signed-off-by: Chris Moore <cmoore@redhat.com>
1 parent 1f7bd68 commit 3f17b08

3 files changed

Lines changed: 151 additions & 16 deletions

File tree

‎crates/openshell-cli/src/tls.rs‎

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ pub type GrpcClient = openshell_sdk::raw::GrpcClient<
1919
tonic::service::interceptor::InterceptedService<Channel, GatewayInterceptor>,
2020
>;
2121

22-
/// Interceptor stack applied to every gateway gRPC request.
22+
/// Interceptor stack applied to gateway requests from clients built by
23+
/// [`grpc_client`].
2324
///
2425
/// Runs authentication header injection first, then passive W3C trace-context
2526
/// forwarding so a CI pipeline's `TRACEPARENT` extends into the gateway's
@@ -401,13 +402,61 @@ pub fn retry_unrouted(replica: Option<&AsciiMetadataValue>, status: &tonic::Stat
401402
#[cfg(test)]
402403
mod tests {
403404
use super::{
404-
TlsOptions, owner_replica, retry_unrouted, routed_to, sdk_client_config, with_owner_hint,
405+
GatewayInterceptor, TlsOptions, owner_replica, retry_unrouted, routed_to,
406+
sdk_client_config, with_owner_hint,
405407
};
408+
use crate::TEST_ENV_LOCK;
406409
use openshell_core::replica_routing::{
407410
OWNER_REPLICA_HEADER, OWNER_REQUEST_HEADER, ROUTE_REPLICA_HEADER,
408411
};
409-
use openshell_sdk::AuthConfig;
412+
use openshell_otel::EnvTraceContextInterceptor;
413+
use openshell_sdk::{AuthConfig, EdgeAuthInterceptor};
410414
use std::io::Write;
415+
use tonic::service::Interceptor as _;
416+
417+
#[test]
418+
fn gateway_interceptor_composes_auth_and_trace_forwarding() {
419+
let _guard = TEST_ENV_LOCK
420+
.lock()
421+
.unwrap_or_else(std::sync::PoisonError::into_inner);
422+
let traceparent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
423+
temp_env::with_vars(
424+
[
425+
("TRACEPARENT", Some(traceparent)),
426+
("TRACESTATE", Some("vendor=value")),
427+
],
428+
|| {
429+
let mut interceptor = GatewayInterceptor {
430+
auth: EdgeAuthInterceptor::new(Some("test-token"), None).unwrap(),
431+
trace: EnvTraceContextInterceptor::from_env(),
432+
};
433+
434+
let request = interceptor.call(tonic::Request::new(())).unwrap();
435+
436+
assert_eq!(
437+
request
438+
.metadata()
439+
.get("authorization")
440+
.and_then(|value| value.to_str().ok()),
441+
Some("Bearer test-token")
442+
);
443+
assert_eq!(
444+
request
445+
.metadata()
446+
.get("traceparent")
447+
.and_then(|value| value.to_str().ok()),
448+
Some(traceparent)
449+
);
450+
assert_eq!(
451+
request
452+
.metadata()
453+
.get("tracestate")
454+
.and_then(|value| value.to_str().ok()),
455+
Some("vendor=value")
456+
);
457+
},
458+
);
459+
}
411460

412461
#[test]
413462
fn owner_hint_is_requested_explicitly() {

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

Lines changed: 98 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -113,12 +113,16 @@ pub fn current_trace_context_environment() -> Vec<(&'static str, String)> {
113113

114114
/// Parent `span` under the trace context in `TRACEPARENT` and `TRACESTATE`.
115115
///
116+
/// Reads the environment the same way [`EnvTraceContextInterceptor`] does:
117+
/// both spellings are accepted, whitespace is trimmed, and blank values are
118+
/// treated as unset.
119+
///
116120
/// Leaves `span` unchanged when the environment carries no valid context.
117121
pub fn set_parent_from_environment(span: &tracing::Span) {
118122
set_parent_from_trace_context(
119123
span,
120-
std::env::var(TRACEPARENT_ENV).ok().as_deref(),
121-
std::env::var(TRACESTATE_ENV).ok().as_deref(),
124+
read_env(TRACEPARENT_ENV).as_deref(),
125+
read_env(TRACESTATE_ENV).as_deref(),
122126
);
123127
}
124128

@@ -194,22 +198,29 @@ struct EnvTraceContext {
194198
impl EnvTraceContext {
195199
fn from_env() -> Self {
196200
Self {
197-
traceparent: read_env("TRACEPARENT"),
198-
tracestate: read_env("TRACESTATE"),
201+
traceparent: read_env(TRACEPARENT_ENV),
202+
tracestate: read_env(TRACESTATE_ENV),
199203
}
200204
}
201205
}
202206

203-
/// Read an environment variable by its upper-case name, falling back to the
204-
/// lower-case spelling, trimming whitespace and discarding blank values.
205-
fn read_env(upper: &str) -> Option<String> {
206-
std::env::var(upper)
207+
/// Read one environment variable, trimming whitespace and discarding blanks.
208+
fn read_one(name: &str) -> Option<String> {
209+
std::env::var(name)
207210
.ok()
208-
.or_else(|| std::env::var(upper.to_ascii_lowercase()).ok())
209211
.map(|value| value.trim().to_string())
210212
.filter(|value| !value.is_empty())
211213
}
212214

215+
/// Read an environment variable by its upper-case name, falling back to the
216+
/// lower-case spelling, trimming whitespace and discarding blank values.
217+
///
218+
/// Each spelling is normalized before the fallback, so a blank upper-case
219+
/// value never shadows a valid lower-case one.
220+
fn read_env(upper: &str) -> Option<String> {
221+
read_one(upper).or_else(|| read_one(&upper.to_ascii_lowercase()))
222+
}
223+
213224
impl Extractor for EnvTraceContext {
214225
fn get(&self, key: &str) -> Option<&str> {
215226
match key {
@@ -251,9 +262,12 @@ impl EnvTraceContextInterceptor {
251262
/// Capture the W3C trace context from the process environment.
252263
#[must_use]
253264
pub fn from_env() -> Self {
254-
Self {
255-
context: context_from(&EnvTraceContext::from_env()),
265+
let env = EnvTraceContext::from_env();
266+
let context = context_from(&env);
267+
if env.traceparent.is_some() && !span_context_is_valid(&context) {
268+
tracing::debug!("TRACEPARENT is set but invalid; not forwarding trace context");
256269
}
270+
Self { context }
257271
}
258272
}
259273

@@ -263,6 +277,12 @@ fn context_from(extractor: &impl Extractor) -> Context {
263277
TraceContextPropagator::new().extract_with_context(&Context::new(), extractor)
264278
}
265279

280+
fn span_context_is_valid(context: &Context) -> bool {
281+
use opentelemetry::trace::TraceContextExt as _;
282+
283+
context.span().span_context().is_valid()
284+
}
285+
266286
impl tonic::service::Interceptor for EnvTraceContextInterceptor {
267287
fn call(
268288
&mut self,
@@ -437,6 +457,71 @@ mod tests {
437457
}
438458
}
439459

460+
fn snapshot_env(names: &[&'static str]) -> Vec<(&'static str, Option<String>)> {
461+
names
462+
.iter()
463+
.map(|name| (*name, std::env::var(name).ok()))
464+
.collect()
465+
}
466+
467+
#[allow(unsafe_code)]
468+
fn restore_env(saved: &[(&'static str, Option<String>)]) {
469+
for (name, value) in saved {
470+
unsafe {
471+
match value {
472+
Some(value) => std::env::set_var(name, value),
473+
None => std::env::remove_var(name),
474+
}
475+
}
476+
}
477+
}
478+
479+
#[test]
480+
#[allow(unsafe_code)]
481+
fn env_trace_context_from_env_reads_both_spellings_and_skips_blanks() {
482+
let _tracing_lock = crate::test_lock();
483+
let saved = snapshot_env(&[TRACEPARENT_ENV, "traceparent", TRACESTATE_ENV, "tracestate"]);
484+
let traceparent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
485+
486+
// Upper-case spelling with surrounding whitespace.
487+
unsafe {
488+
std::env::set_var(TRACEPARENT_ENV, format!(" {traceparent} "));
489+
std::env::set_var(TRACESTATE_ENV, " vendor=value ");
490+
}
491+
let padded = EnvTraceContext::from_env();
492+
assert_eq!(padded.traceparent.as_deref(), Some(traceparent));
493+
assert_eq!(padded.tracestate.as_deref(), Some("vendor=value"));
494+
495+
// Lower-case-only spelling.
496+
unsafe {
497+
std::env::remove_var(TRACEPARENT_ENV);
498+
std::env::remove_var(TRACESTATE_ENV);
499+
std::env::set_var("traceparent", traceparent);
500+
std::env::set_var("tracestate", "vendor=value");
501+
}
502+
let lower = EnvTraceContext::from_env();
503+
assert_eq!(lower.traceparent.as_deref(), Some(traceparent));
504+
assert_eq!(lower.tracestate.as_deref(), Some("vendor=value"));
505+
506+
// A blank upper-case value must not shadow a valid lower-case one.
507+
unsafe {
508+
std::env::set_var(TRACEPARENT_ENV, " ");
509+
std::env::remove_var("tracestate");
510+
}
511+
let shadowed = EnvTraceContext::from_env();
512+
assert_eq!(shadowed.traceparent.as_deref(), Some(traceparent));
513+
assert_eq!(shadowed.tracestate, None);
514+
515+
// Blank values in both spellings are treated as unset.
516+
unsafe {
517+
std::env::set_var("traceparent", "");
518+
}
519+
let blank = EnvTraceContext::from_env();
520+
assert_eq!(blank.traceparent, None);
521+
522+
restore_env(&saved);
523+
}
524+
440525
#[test]
441526
fn env_interceptor_forwards_valid_traceparent() {
442527
let traceparent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
@@ -477,11 +562,12 @@ mod tests {
477562
fn env_interceptor_is_noop_for_invalid_traceparent() {
478563
let mut interceptor = interceptor_with(EnvTraceContext {
479564
traceparent: Some("not-a-valid-traceparent".to_string()),
480-
tracestate: None,
565+
tracestate: Some("vendor=value".to_string()),
481566
});
482567

483568
let request = interceptor.call(tonic::Request::new(())).unwrap();
484569

485570
assert!(request.metadata().get("traceparent").is_none());
571+
assert!(request.metadata().get("tracestate").is_none());
486572
}
487573
}

‎docs/observability/traces.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ Give each installation that reports to the same collector its own name, includin
6969

7070
The gateway continues a valid W3C `traceparent` sent by the caller, so a client's trace can include the gateway's spans for its requests. Without one, the gateway starts a new trace.
7171

72-
The CLI forwards `TRACEPARENT` and `TRACESTATE` from its environment on every gateway request. A CI system that exports these variables (GitHub Actions, GitLab CI, Jenkins OpenTelemetry plugins) therefore parents the gateway's spans for the commands it runs, with no collector or provider configuration on the CI runner.
72+
The CLI forwards `TRACEPARENT` and `TRACESTATE` from its environment on gateway requests from its standard commands. A CI system that exports these variables (GitHub Actions, GitLab CI, Jenkins OpenTelemetry plugins) therefore parents the gateway's spans for the commands it runs, with no collector or provider configuration on the CI runner.
7373

7474
The gateway also passes its trace context to compute drivers, so driver spans appear in the same trace as the gateway request that caused them. Built-in drivers export their spans through the gateway's process. Managed external drivers receive the trace endpoint, gateway name, and compute driver from the gateway. Drivers that you run yourself own their telemetry configuration.
7575

0 commit comments

Comments
 (0)