Skip to content

Commit

Permalink
Add regexes to check keys and values
Browse files Browse the repository at this point in the history
  • Loading branch information
ocelotl committed Aug 5, 2021
1 parent e2eb73c commit fddef97
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,19 @@
#
import typing
import urllib.parse
from re import compile as compile_

from opentelemetry import baggage
from opentelemetry.context import get_current
from opentelemetry.context.context import Context
from opentelemetry.propagators import textmap

_key = r"[!#-'*+-.0-9A-Z^-z|~]+"
_key_regex = compile_(_key)
_value = r"[!#-+.-:<-\[\]-~-]*"
_value_regex = compile_(_value)
_key_value_regex = compile_(r"\s*{}\s*=\s*{}\s*".format(_key, _value))


class W3CBaggagePropagator(textmap.TextMapPropagator):
"""Extracts and injects Baggage which is used to annotate telemetry."""
Expand Down Expand Up @@ -54,7 +61,10 @@ def extract(
baggage_entries = header.split(",")
total_baggage_entries = self._MAX_PAIRS
for entry in baggage_entries:
if total_baggage_entries <= 0:

if _key_value_regex.match(entry) is None or (
total_baggage_entries <= 0
):
return context
total_baggage_entries -= 1
if len(entry) > self._MAX_PAIR_LENGTH:
Expand Down Expand Up @@ -96,10 +106,17 @@ def fields(self) -> typing.Set[str]:


def _format_baggage(baggage_entries: typing.Mapping[str, object]) -> str:
return ",".join(
key + "=" + urllib.parse.quote_plus(str(value))
for key, value in baggage_entries.items()
)

key_values = []

for key, value in baggage_entries.items():
# type: ignore
if _key_regex.match(key) is None or _value_regex.match(value) is None:
continue

key_values.append(key + "=" + urllib.parse.quote(str(value)))

return ",".join(key_values)


def _extract_first_element(
Expand Down
8 changes: 5 additions & 3 deletions opentelemetry-api/tests/baggage/test_baggage_propagation.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,8 @@ def test_valid_header_with_empty_value(self):
self.assertEqual(self._extract(header), expected)

def test_invalid_header(self):
header = "header1"
expected = {}
self.assertEqual(self._extract(header), expected)
self.assertEqual(self._extract("header1"), {})
self.assertEqual(self._extract(" = "), {})

def test_header_too_long(self):
long_value = "s" * (W3CBaggagePropagator._MAX_HEADER_LENGTH + 1)
Expand Down Expand Up @@ -111,6 +110,9 @@ def test_inject_no_baggage_entries(self):
output = self._inject(values)
self.assertEqual(None, output)

def test_inject_invalid_entries(self):
self.assertEqual(None, self._inject({"key": "val ue"}))

def test_inject(self):
values = {
"key1": "val1",
Expand Down

0 comments on commit fddef97

Please sign in to comment.