Skip to content

Commit cab7290

Browse files
committed
Add validation for Trace ID
1 parent c6a0e3e commit cab7290

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

opentelemetry-api/src/opentelemetry/trace/span.py

+19-1
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,24 @@ def values(self) -> typing.ValuesView[str]:
390390

391391
DEFAULT_TRACE_STATE = TraceState.get_default()
392392

393+
_TRACE_ID_BYTES = 16
394+
_TRACE_ID_HEX_LENGTH = 2 * _TRACE_ID_BYTES
395+
396+
def _validate_trace_id(trace_id: int) -> bool:
397+
"""Validates a trace_id.
398+
399+
Args:
400+
trace_id: An int that is expected to corresponds to 16-bytes hexdecimal value
401+
402+
Returns:
403+
True if trace_id is valid, False otherwise.
404+
"""
405+
if not trace_id:
406+
return False
407+
if len(format(trace_id, "032x")) != _TRACE_ID_HEX_LENGTH:
408+
return False
409+
410+
return True
393411

394412
class SpanContext(
395413
typing.Tuple[int, int, bool, "TraceFlags", "TraceState", bool]
@@ -420,7 +438,7 @@ def __new__(
420438
if trace_state is None:
421439
trace_state = DEFAULT_TRACE_STATE
422440

423-
is_valid = trace_id != INVALID_TRACE_ID and span_id != INVALID_SPAN_ID
441+
is_valid = trace_id != INVALID_TRACE_ID and span_id != INVALID_SPAN_ID and _validate_trace_id(trace_id)
424442

425443
return tuple.__new__(
426444
cls,

opentelemetry-api/tests/trace/test_span_context.py

+9
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,12 @@ def test_span_context_pickle(self):
3434
pickle_sc = pickle.loads(pickle.dumps(sc))
3535
self.assertEqual(sc.trace_id, pickle_sc.trace_id)
3636
self.assertEqual(sc.span_id, pickle_sc.span_id)
37+
38+
invalid_sc = trace.SpanContext(
39+
9999999999999999999999999999999999999999999999999999999999999999999999999999,
40+
9,
41+
is_remote=False,
42+
trace_flags=trace.DEFAULT_TRACE_OPTIONS,
43+
trace_state=trace.DEFAULT_TRACE_STATE,
44+
)
45+
self.assertFalse(invalid_sc.is_valid)

0 commit comments

Comments
 (0)