Skip to content

Commit bf99144

Browse files
marcbachmannvmarchauddyladan
authored
chore(http-propagation): reduce complexity of traceparent parsing (#1837)
Co-authored-by: Valentin Marchaud <[email protected]> Co-authored-by: Daniel Dyla <[email protected]>
1 parent 31ab012 commit bf99144

File tree

1 file changed

+16
-30
lines changed

1 file changed

+16
-30
lines changed

packages/opentelemetry-core/src/context/propagation/HttpTraceContext.ts

Lines changed: 16 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,13 @@ export const TRACE_PARENT_HEADER = 'traceparent';
3030
export const TRACE_STATE_HEADER = 'tracestate';
3131

3232
const VERSION = '00';
33-
const VERSION_PART_COUNT = 4; // Version 00 only allows the specific 4 fields.
34-
35-
const VERSION_REGEX = /^(?!ff)[\da-f]{2}$/;
36-
const TRACE_ID_REGEX = /^(?![0]{32})[\da-f]{32}$/;
37-
const PARENT_ID_REGEX = /^(?![0]{16})[\da-f]{16}$/;
38-
const FLAGS_REGEX = /^[\da-f]{2}$/;
33+
const VERSION_PART = '(?!ff)[\\da-f]{2}';
34+
const TRACE_ID_PART = '(?![0]{32})[\\da-f]{32}';
35+
const PARENT_ID_PART = '(?![0]{16})[\\da-f]{16}';
36+
const FLAGS_PART = '[\\da-f]{2}';
37+
const TRACE_PARENT_REGEX = new RegExp(
38+
`^\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\s?$`
39+
);
3940

4041
/**
4142
* Parses information from the [traceparent] span tag and converts it into {@link SpanContext}
@@ -48,33 +49,18 @@ const FLAGS_REGEX = /^[\da-f]{2}$/;
4849
* For more information see {@link https://www.w3.org/TR/trace-context/}
4950
*/
5051
export function parseTraceParent(traceParent: string): SpanContext | null {
51-
const trimmed = traceParent.trim();
52-
const traceParentParts = trimmed.split('-');
53-
54-
// Current version must be structured correctly.
55-
// For future versions, we can grab just the parts we do support.
56-
if (
57-
traceParentParts[0] === VERSION &&
58-
traceParentParts.length !== VERSION_PART_COUNT
59-
) {
60-
return null;
61-
}
52+
const match = TRACE_PARENT_REGEX.exec(traceParent);
53+
if (!match) return null;
6254

63-
const [version, traceId, parentId, flags] = traceParentParts;
64-
const isValidParent =
65-
VERSION_REGEX.test(version) &&
66-
TRACE_ID_REGEX.test(traceId) &&
67-
PARENT_ID_REGEX.test(parentId) &&
68-
FLAGS_REGEX.test(flags);
69-
70-
if (!isValidParent) {
71-
return null;
72-
}
55+
// According to the specification the implementation should be compatible
56+
// with future versions. If there are more parts, we only reject it if it's using version 00
57+
// See https://www.w3.org/TR/trace-context/#versioning-of-traceparent
58+
if (match[1] === '00' && match[5]) return null;
7359

7460
return {
75-
traceId: traceId,
76-
spanId: parentId,
77-
traceFlags: parseInt(flags, 16),
61+
traceId: match[2],
62+
spanId: match[3],
63+
traceFlags: parseInt(match[4], 16),
7864
};
7965
}
8066

0 commit comments

Comments
 (0)