|
14 | 14 | #
|
15 | 15 | import typing
|
16 | 16 | import urllib.parse
|
| 17 | +from re import compile as compile_ |
17 | 18 |
|
18 | 19 | from opentelemetry import baggage
|
19 | 20 | from opentelemetry.context import get_current
|
20 | 21 | from opentelemetry.context.context import Context
|
21 | 22 | from opentelemetry.propagators import textmap
|
22 | 23 |
|
| 24 | +_key = r"[!#-'*+-.0-9A-Z^-z|~]+" |
| 25 | +_key_regex = compile_(_key) |
| 26 | +_value = r"[!#-+.-:<-\[\]-~-]*" |
| 27 | +_value_regex = compile_(_value) |
| 28 | +_key_value_regex = compile_(r"\s*{}\s*=\s*{}\s*".format(_key, _value)) |
| 29 | + |
23 | 30 |
|
24 | 31 | class W3CBaggagePropagator(textmap.TextMapPropagator):
|
25 | 32 | """Extracts and injects Baggage which is used to annotate telemetry."""
|
@@ -54,7 +61,10 @@ def extract(
|
54 | 61 | baggage_entries = header.split(",")
|
55 | 62 | total_baggage_entries = self._MAX_PAIRS
|
56 | 63 | for entry in baggage_entries:
|
57 |
| - if total_baggage_entries <= 0: |
| 64 | + |
| 65 | + if _key_value_regex.match(entry) is None or ( |
| 66 | + total_baggage_entries <= 0 |
| 67 | + ): |
58 | 68 | return context
|
59 | 69 | total_baggage_entries -= 1
|
60 | 70 | if len(entry) > self._MAX_PAIR_LENGTH:
|
@@ -95,11 +105,18 @@ def fields(self) -> typing.Set[str]:
|
95 | 105 | return {self._BAGGAGE_HEADER_NAME}
|
96 | 106 |
|
97 | 107 |
|
98 |
| -def _format_baggage(baggage_entries: typing.Mapping[str, object]) -> str: |
99 |
| - return ",".join( |
100 |
| - key + "=" + urllib.parse.quote_plus(str(value)) |
101 |
| - for key, value in baggage_entries.items() |
102 |
| - ) |
| 108 | +def _format_baggage(baggage_entries: typing.Mapping[str, str]) -> str: |
| 109 | + |
| 110 | + key_values = [] |
| 111 | + |
| 112 | + for key, value in baggage_entries.items(): |
| 113 | + |
| 114 | + if _key_regex.match(key) is None or _value_regex.match(value) is None: |
| 115 | + continue |
| 116 | + |
| 117 | + key_values.append(key + "=" + urllib.parse.quote(str(value))) |
| 118 | + |
| 119 | + return ",".join(key_values) |
103 | 120 |
|
104 | 121 |
|
105 | 122 | def _extract_first_element(
|
|
0 commit comments