Skip to content

Commit

Permalink
Add latin-1 fallback decoding for asgi headers
Browse files Browse the repository at this point in the history
  • Loading branch information
nkhitrov committed May 4, 2023
1 parent 135280e commit a381c2e
Showing 1 changed file with 20 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -251,17 +251,15 @@ def get(
# ASGI header keys are in lower case
key = key.lower()
decoded = [
_value.decode("utf8")
_decode_header_item(_value)
for (_key, _value) in headers
if _key.decode("utf8").lower() == key
if _decode_header_item(_key).lower() == key
]
if not decoded:
return None
return decoded
return decoded or None

def keys(self, carrier: dict) -> typing.List[str]:
headers = carrier.get("headers") or []
return [_key.decode("utf8") for (_key, _value) in headers]
return [_decode_header_item(_key) for (_key, _value) in headers]


asgi_getter = ASGIGetter()
Expand Down Expand Up @@ -344,10 +342,7 @@ def collect_custom_request_headers_attributes(scope):
)

# Decode headers before processing.
headers = {
_key.decode("utf8"): _value.decode("utf8")
for (_key, _value) in scope.get("headers")
}
headers = _decode_headers(scope.get("headers"))

return sanitize.sanitize_header_values(
headers,
Expand All @@ -370,10 +365,7 @@ def collect_custom_response_headers_attributes(message):
)

# Decode headers before processing.
headers = {
_key.decode("utf8"): _value.decode("utf8")
for (_key, _value) in message.get("headers")
}
headers = _decode_headers(message.get("headers"))

return sanitize.sanitize_header_values(
headers,
Expand Down Expand Up @@ -657,3 +649,17 @@ async def otel_send(message):
await send(message)

return otel_send


def _decode_headers(headers):
return {
_decode_header_item(key): _decode_header_item(value)
for key, value in headers
}


def _decode_header_item(value):
try:
return value.decode("utf-8")
except ValueError:
return value.decode("latin-1")

0 comments on commit a381c2e

Please sign in to comment.