Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: left pad short b3 trace identifiers #1021

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { getParentSpanContext, setExtractedSpanContext } from '../context';
export const X_B3_TRACE_ID = 'x-b3-traceid';
export const X_B3_SPAN_ID = 'x-b3-spanid';
export const X_B3_SAMPLED = 'x-b3-sampled';
const VALID_TRACEID_REGEX = /^[0-9a-f]{32}$/i;
const VALID_TRACEID_REGEX = /^([0-9a-f]{16}){1,2}$/i;
const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
const INVALID_ID_REGEX = /^0+$/i;

Expand Down Expand Up @@ -72,16 +72,21 @@ export class B3Propagator implements HttpTextPropagator {
const traceIdHeader = getter(carrier, X_B3_TRACE_ID);
const spanIdHeader = getter(carrier, X_B3_SPAN_ID);
const sampledHeader = getter(carrier, X_B3_SAMPLED);
const traceId = Array.isArray(traceIdHeader)

const traceIdHeaderValue = Array.isArray(traceIdHeader)
? traceIdHeader[0]
: traceIdHeader;
const spanId = Array.isArray(spanIdHeader) ? spanIdHeader[0] : spanIdHeader;

const options = Array.isArray(sampledHeader)
? sampledHeader[0]
: sampledHeader;

if (typeof traceId !== 'string' || typeof spanId !== 'string')
if (typeof traceIdHeaderValue !== 'string' || typeof spanId !== 'string') {
return context;
}

const traceId = traceIdHeaderValue.padStart(32, '0');

if (isValidTraceId(traceId) && isValidSpanId(spanId)) {
return setExtractedSpanContext(context, {
Expand Down
16 changes: 16 additions & 0 deletions packages/opentelemetry-core/test/context/B3Propagator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,5 +289,21 @@ describe('B3Propagator', () => {
assert.ok(ctx2 === Context.ROOT_CONTEXT);
assert.ok(ctx3 === Context.ROOT_CONTEXT);
});

it('should left-pad 64 bit trace ids with 0', () => {
carrier[X_B3_TRACE_ID] = '8448eb211c80319c';
carrier[X_B3_SPAN_ID] = 'b7ad6b7169203331';
carrier[X_B3_SAMPLED] = '1';
const extractedSpanContext = getExtractedSpanContext(
b3Propagator.extract(Context.ROOT_CONTEXT, carrier, defaultGetter)
);

assert.deepStrictEqual(extractedSpanContext, {
spanId: 'b7ad6b7169203331',
traceId: '00000000000000008448eb211c80319c',
isRemote: true,
traceFlags: TraceFlags.SAMPLED,
});
});
});
});