Skip to content

Commit adc0a88

Browse files
author
Daniel Rogers
committed
Add support for regular expression matching and sanitizing of headers in ASGI.
Next part of #1184 Details: Add test cases for regular expression matching. Add test cases for "all" keyword. Add test cases for header sanitizing. Add documentation for regular expression matching and header sanitation. Various documentation cleanups and standardization. Fix keys() in class ASGIGetter so it returns the HTTP header keys instead of a list of available request data. This makes it consistent with the WSGIGetter keys() method. Make ASGIGetter.get() compare all keys in a case insensitive manner.
1 parent 273ae3c commit adc0a88

File tree

6 files changed

+440
-54
lines changed

6 files changed

+440
-54
lines changed

CHANGELOG.md

+6
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1616
([#1242](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1242))
1717
- `opentelemetry-util-http` Add support for sanitizing HTTP header values.
1818
([#1253](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1253))
19+
- `opentelemetry-instrumentation-asgi` Add support for regular expression matching of HTTP headers.
20+
([#1333](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1333))
1921

2022
### Fixed
2123

@@ -29,6 +31,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2931
- ([#1246](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1246))
3032
- Add _is_openetlemetry_instrumented check in _InstrumentedFastAPI class
3133
([#1313](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1313))
34+
- `opentelemetry-instrumentation-asgi` Fix keys() in class ASGIGetter so it returns the HTTP header keys instead of a list of available request data.
35+
([#1333](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1333))
36+
- `opentelemetry-instrumentation-asgi` Make ASGIGetter.get() compare all keys in a case insensitive manner.
37+
([#1333](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1333))
3238

3339
## [1.12.0-0.33b0](https://github.com/open-telemetry/opentelemetry-python/releases/tag/v1.12.0-0.33b0) - 2022-08-08
3440

instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py

+134-42
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,7 @@
1515

1616
"""
1717
The opentelemetry-instrumentation-asgi package provides an ASGI middleware that can be used
18-
on any ASGI framework (such as Django-channels / Quart) to track requests
19-
timing through OpenTelemetry.
18+
on any ASGI framework (such as Django-channels / Quart) to track request timing through OpenTelemetry.
2019
2120
Usage (Quart)
2221
-------------
@@ -71,9 +70,14 @@ async def hello():
7170
Request/Response hooks
7271
**********************
7372
74-
Utilize request/response hooks to execute custom logic to be performed before/after performing a request. The server request hook takes in a server span and ASGI
75-
scope object for every incoming request. The client request hook is called with the internal span and an ASGI scope which is sent as a dictionary for when the method receive is called.
76-
The client response hook is called with the internal span and an ASGI event which is sent as a dictionary for when the method send is called.
73+
This instrumentation supports request and response hooks. These are functions that get called
74+
right after a span is created for a request and right before the span is finished for the response.
75+
76+
- The server request hook is passed a server span and ASGI scope object for every incoming request.
77+
- The client request hook is called with the internal span and an ASGI scope when the method ``receive`` is called.
78+
- The client response hook is called with the internal span and an ASGI event when the method ``send`` is called.
79+
80+
For example,
7781
7882
.. code-block:: python
7983
@@ -93,59 +97,99 @@ def client_response_hook(span: Span, message: dict):
9397
9498
Capture HTTP request and response headers
9599
*****************************************
96-
You can configure the agent to capture predefined HTTP headers as span attributes, according to the `semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_.
100+
You can configure the agent to capture specified HTTP headers as span attributes, according to the
101+
`semantic convention <https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers>`_.
97102
98103
Request headers
99104
***************
100-
To capture predefined HTTP request headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST``
101-
to a comma-separated list of HTTP header names.
105+
To capture HTTP request headers as span attributes, set the environment variable
106+
``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST`` to a comma delimited list of HTTP header names.
102107
103108
For example,
104-
105109
::
106110
107111
export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="content-type,custom_request_header"
108112
109-
will extract ``content-type`` and ``custom_request_header`` from request headers and add them as span attributes.
113+
will extract ``content-type`` and ``custom_request_header`` from the request headers and add them as span attributes.
114+
115+
Request header names in ASGI are case-insensitive. So, giving the header name as ``CUStom-Header`` in the environment
116+
variable will capture the header named ``custom-header``.
117+
118+
Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example:
119+
::
120+
121+
export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="Accept.*,X-.*"
122+
123+
Would match all request headers that start with ``Accept`` and ``X-``.
124+
125+
Additionally, the special keyword ``all`` can be used to capture all request headers.
126+
::
110127
111-
It is recommended that you should give the correct names of the headers to be captured in the environment variable.
112-
Request header names in ASGI are case insensitive. So, giving header name as ``CUStom-Header`` in environment variable will be able capture header with name ``custom-header``.
128+
export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST="all"
113129
114-
The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ).
115-
The value of the attribute will be single item list containing all the header values.
130+
The name of the added span attribute will follow the format ``http.request.header.<header_name>`` where ``<header_name>``
131+
is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a
132+
single item list containing all the header values.
116133
117-
Example of the added span attribute,
134+
For example:
118135
``http.request.header.custom_request_header = ["<value1>,<value2>"]``
119136
120137
Response headers
121138
****************
122-
To capture predefined HTTP response headers as span attributes, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE``
123-
to a comma-separated list of HTTP header names.
139+
To capture HTTP response headers as span attributes, set the environment variable
140+
``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE`` to a comma delimited list of HTTP header names.
124141
125142
For example,
126-
127143
::
128144
129145
export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="content-type,custom_response_header"
130146
131-
will extract ``content-type`` and ``custom_response_header`` from response headers and add them as span attributes.
147+
will extract ``content-type`` and ``custom_response_header`` from the response headers and add them as span attributes.
148+
149+
Response header names in ASGI are case-insensitive. So, giving the header name as ``CUStom-Header`` in the environment
150+
variable will capture the header named ``custom-header``.
151+
152+
Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example:
153+
::
154+
155+
export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="Content.*,X-.*"
132156
133-
It is recommended that you should give the correct names of the headers to be captured in the environment variable.
134-
Response header names captured in ASGI are case insensitive. So, giving header name as ``CUStomHeader`` in environment variable will be able capture header with name ``customheader``.
157+
Would match all response headers that start with ``Content`` and ``X-``.
135158
136-
The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>`` being the normalized HTTP header name (lowercase, with - characters replaced by _ ).
137-
The value of the attribute will be single item list containing all the header values.
159+
Additionally, the special keyword ``all`` can be used to capture all response headers.
160+
::
161+
162+
export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE="all"
163+
164+
The name of the added span attribute will follow the format ``http.response.header.<header_name>`` where ``<header_name>``
165+
is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a
166+
single item list containing all the header values.
138167
139-
Example of the added span attribute,
168+
For example:
140169
``http.response.header.custom_response_header = ["<value1>,<value2>"]``
141170
171+
Sanitizing headers
172+
******************
173+
In order to prevent storing sensitive data such as personally identifiable information (PII), session keys, passwords,
174+
etc, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS``
175+
to a comma delimited list of HTTP header names to be sanitized. Regexes may be used, and all header names will be
176+
matched in a case-insensitive manner.
177+
178+
For example,
179+
::
180+
181+
export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS=".*session.*,set-cookie"
182+
183+
will replace the value of headers such as ``session-id`` and ``set-cookie`` with ``[REDACTED]`` in the span.
184+
142185
Note:
143-
Environment variable names to capture http headers are still experimental, and thus are subject to change.
186+
The environment variable names used to capture HTTP headers are still experimental, and thus are subject to change.
144187
145188
API
146189
---
147190
"""
148191

192+
import re
149193
import typing
150194
import urllib
151195
from functools import wraps
@@ -169,8 +213,10 @@ def client_response_hook(span: Span, message: dict):
169213
from opentelemetry.trace import Span, set_span_in_context
170214
from opentelemetry.trace.status import Status, StatusCode
171215
from opentelemetry.util.http import (
216+
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS,
172217
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST,
173218
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE,
219+
SanitizeValue,
174220
_parse_active_request_count_attrs,
175221
_parse_duration_attrs,
176222
get_custom_headers,
@@ -202,19 +248,21 @@ def get(
202248
if not headers:
203249
return None
204250

205-
# asgi header keys are in lower case
251+
# ASGI header keys are in lower case
206252
key = key.lower()
207253
decoded = [
208254
_value.decode("utf8")
209255
for (_key, _value) in headers
210-
if _key.decode("utf8") == key
256+
if _key.decode("utf8").lower() == key
211257
]
212258
if not decoded:
213259
return None
214260
return decoded
215261

216262
def keys(self, carrier: dict) -> typing.List[str]:
217-
return list(carrier.keys())
263+
return [
264+
_key.decode("utf8") for (_key, _value) in carrier.get("headers")
265+
]
218266

219267

220268
asgi_getter = ASGIGetter()
@@ -290,15 +338,37 @@ def collect_custom_request_headers_attributes(scope):
290338
Refer specification https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers"""
291339

292340
attributes = {}
293-
custom_request_headers = get_custom_headers(
341+
342+
sanitized_fields = get_custom_headers(
343+
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS
344+
)
345+
346+
sanitize = SanitizeValue(sanitized_fields)
347+
348+
custom_request_headers_name = get_custom_headers(
294349
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_REQUEST
295350
)
296351

297-
for header in custom_request_headers:
298-
values = asgi_getter.get(scope, header)
299-
if values:
300-
key = normalise_request_header_name(header)
301-
attributes.setdefault(key, []).extend(values)
352+
if custom_request_headers_name:
353+
custom_request_headers_regex_compiled = re.compile(
354+
"|".join("^" + i + "$" for i in custom_request_headers_name),
355+
re.IGNORECASE,
356+
)
357+
358+
for header_name in list(
359+
filter(
360+
custom_request_headers_regex_compiled.match,
361+
asgi_getter.keys(scope),
362+
)
363+
):
364+
header_values = asgi_getter.get(scope, header_name.lower())
365+
if header_values:
366+
key = normalise_request_header_name(header_name.lower())
367+
attributes[key] = [
368+
sanitize.sanitize_header_value(
369+
header=header_name, value=header_values[0]
370+
)
371+
]
302372

303373
return attributes
304374

@@ -307,15 +377,37 @@ def collect_custom_response_headers_attributes(message):
307377
"""returns custom HTTP response headers to be added into SERVER span as span attributes
308378
Refer specification https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/http.md#http-request-and-response-headers"""
309379
attributes = {}
310-
custom_response_headers = get_custom_headers(
380+
381+
sanitized_fields = get_custom_headers(
382+
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS
383+
)
384+
385+
sanitize = SanitizeValue(sanitized_fields)
386+
387+
custom_response_headers_name = get_custom_headers(
311388
OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE
312389
)
313390

314-
for header in custom_response_headers:
315-
values = asgi_getter.get(message, header)
316-
if values:
317-
key = normalise_response_header_name(header)
318-
attributes.setdefault(key, []).extend(values)
391+
if custom_response_headers_name:
392+
custom_response_headers_regex_compiled = re.compile(
393+
"|".join("^" + i + "$" for i in custom_response_headers_name),
394+
re.IGNORECASE,
395+
)
396+
397+
for header_name in list(
398+
filter(
399+
custom_response_headers_regex_compiled.match,
400+
asgi_getter.keys(message),
401+
)
402+
):
403+
header_values = asgi_getter.get(message, header_name.lower())
404+
if header_values:
405+
key = normalise_response_header_name(header_name.lower())
406+
attributes[key] = [
407+
sanitize.sanitize_header_value(
408+
header=header_name, value=header_values[0]
409+
)
410+
]
319411

320412
return attributes
321413

@@ -353,7 +445,7 @@ def set_status_code(span, status_code):
353445
def get_default_span_details(scope: dict) -> Tuple[str, dict]:
354446
"""Default implementation for get_default_span_details
355447
Args:
356-
scope: the asgi scope dictionary
448+
scope: the ASGI scope dictionary
357449
Returns:
358450
a tuple of the span name, and any attributes to attach to the span.
359451
"""
@@ -427,7 +519,7 @@ async def __call__(self, scope, receive, send):
427519
"""The ASGI application
428520
429521
Args:
430-
scope: A ASGI environment.
522+
scope: An ASGI environment.
431523
receive: An awaitable callable yielding dictionaries
432524
send: An awaitable callable taking a single dictionary as argument.
433525
"""

0 commit comments

Comments
 (0)