diff --git a/packages/dd-trace/src/opentracing/propagation/text_map.js b/packages/dd-trace/src/opentracing/propagation/text_map.js index 1346f85de72..42a482853ee 100644 --- a/packages/dd-trace/src/opentracing/propagation/text_map.js +++ b/packages/dd-trace/src/opentracing/propagation/text_map.js @@ -53,6 +53,8 @@ class TextMapPropagator { } inject (spanContext, carrier) { + if (!spanContext || !carrier) return + this._injectBaggageItems(spanContext, carrier) this._injectDatadog(spanContext, carrier) this._injectB3MultipleHeaders(spanContext, carrier) @@ -383,7 +385,7 @@ class TextMapPropagator { return null } const matches = headerValue.trim().match(traceparentExpr) - if (matches.length) { + if (matches?.length) { const [version, traceId, spanId, flags, tail] = matches.slice(1) const traceparent = { version } const tracestate = TraceState.fromString(carrier.tracestate) diff --git a/packages/dd-trace/test/opentracing/propagation/text_map.spec.js b/packages/dd-trace/test/opentracing/propagation/text_map.spec.js index 58ee69047ba..5b7fef68092 100644 --- a/packages/dd-trace/test/opentracing/propagation/text_map.spec.js +++ b/packages/dd-trace/test/opentracing/propagation/text_map.spec.js @@ -58,6 +58,16 @@ describe('TextMapPropagator', () => { } }) + it('should not crash without spanContext', () => { + const carrier = {} + propagator.inject(null, carrier) + }) + + it('should not crash without carrier', () => { + const spanContext = createContext() + propagator.inject(spanContext, null) + }) + it('should inject the span context into the carrier', () => { const carrier = {} const spanContext = createContext() @@ -492,6 +502,12 @@ describe('TextMapPropagator', () => { expect(first._spanId.toString(16)).to.equal(spanId) }) + it('should not crash with invalid traceparent', () => { + textMap.traceparent = 'invalid' + + propagator.extract(textMap) + }) + it('should always extract tracestate from tracecontext when trace IDs match', () => { textMap.traceparent = '00-0000000000000000000000000000007B-0000000000000456-01' textMap.tracestate = 'other=bleh,dd=t.foo_bar_baz_:abc_!@#$%^&*()_+`-~;s:2;o:foo;t.dm:-4'