diff --git a/packages/opentelemetry-core/src/context/propagation/HttpTraceContext.ts b/packages/opentelemetry-core/src/context/propagation/HttpTraceContext.ts index 735e8d2e44..8b4dac8216 100644 --- a/packages/opentelemetry-core/src/context/propagation/HttpTraceContext.ts +++ b/packages/opentelemetry-core/src/context/propagation/HttpTraceContext.ts @@ -17,6 +17,7 @@ import { Context, getSpanContext, + isSpanContextValid, setSpanContext, SpanContext, TextMapGetter, @@ -73,7 +74,7 @@ export function parseTraceParent(traceParent: string): SpanContext | null { export class HttpTraceContext implements TextMapPropagator { inject(context: Context, carrier: unknown, setter: TextMapSetter) { const spanContext = getSpanContext(context); - if (!spanContext) return; + if (!spanContext || !isSpanContextValid(spanContext)) return; const traceParent = `${VERSION}-${spanContext.traceId}-${ spanContext.spanId diff --git a/packages/opentelemetry-core/test/context/HttpTraceContext.test.ts b/packages/opentelemetry-core/test/context/HttpTraceContext.test.ts index a732a471f9..831a3899df 100644 --- a/packages/opentelemetry-core/test/context/HttpTraceContext.test.ts +++ b/packages/opentelemetry-core/test/context/HttpTraceContext.test.ts @@ -21,6 +21,8 @@ import { TraceFlags, getSpanContext, setSpanContext, + INVALID_TRACEID, + INVALID_SPANID, } from '@opentelemetry/api'; import { ROOT_CONTEXT } from '@opentelemetry/api'; import * as assert from 'assert'; @@ -78,6 +80,23 @@ describe('HttpTraceContext', () => { ); assert.deepStrictEqual(carrier[TRACE_STATE_HEADER], 'foo=bar,baz=qux'); }); + + it('should ignore invalid span context', () => { + const spanContext: SpanContext = { + traceId: INVALID_TRACEID, + spanId: INVALID_SPANID, + traceFlags: TraceFlags.NONE, + traceState: new TraceState('foo=bar,baz=qux'), + }; + + httpTraceContext.inject( + setSpanContext(ROOT_CONTEXT, spanContext), + carrier, + defaultTextMapSetter + ); + assert.strictEqual(carrier[TRACE_PARENT_HEADER], undefined); + assert.strictEqual(carrier[TRACE_STATE_HEADER], undefined); + }); }); describe('.extract()', () => {