diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cf8b6d504..a3d12ae211 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ([#3938](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3938)) - `opentelemetry-instrumentation-aiohttp-server`: Support passing `TracerProvider` when instrumenting. ([#3819](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/3819)) +- `opentelemetry-instrumentation-urllib3`: add ability to capture custom headers + ([#4050](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/4050)) ### Fixed diff --git a/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py b/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py index 6598971931..c37415f802 100644 --- a/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py +++ b/instrumentation/opentelemetry-instrumentation-urllib3/src/opentelemetry/instrumentation/urllib3/__init__.py @@ -88,6 +88,97 @@ def response_hook( will exclude requests such as ``https://site/client/123/info`` and ``https://site/xyz/healthcheck``. +Capture HTTP request and response headers +***************************************** +You can configure the agent to capture specified HTTP headers as span attributes, according to the +`semantic conventions `_. + +Request headers +*************** +To capture HTTP request headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_REQUEST`` to a comma delimited list of HTTP header names. + +For example using the environment variable, +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_REQUEST="content-type,custom_request_header" + +will extract ``content-type`` and ``custom_request_header`` from the request headers and add them as span attributes. + +Request header names in urllib3 are case-insensitive. So, giving the header name as ``CUStom-Header`` in the environment +variable will capture the header named ``custom-header``. + +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_REQUEST="Accept.*,X-.*" + +Would match all request headers that start with ``Accept`` and ``X-``. + +To capture all request headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_REQUEST`` to ``".*"``. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_REQUEST=".*" + +The name of the added span attribute will follow the format ``http.request.header.`` where ```` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +single item list containing all the header values. + +For example: +``http.request.header.custom_request_header = ["", ""]`` + +Response headers +**************** +To capture HTTP response headers as span attributes, set the environment variable +``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_RESPONSE`` to a comma delimited list of HTTP header names. + +For example using the environment variable, +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_RESPONSE="content-type,custom_response_header" + +will extract ``content-type`` and ``custom_response_header`` from the response headers and add them as span attributes. + +Response header names in urllib3 are case-insensitive. So, giving the header name as ``CUStom-Header`` in the environment +variable will capture the header named ``custom-header``. + +Regular expressions may also be used to match multiple headers that correspond to the given pattern. For example: +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_RESPONSE="Content.*,X-.*" + +Would match all response headers that start with ``Content`` and ``X-``. + +To capture all response headers, set ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_RESPONSE`` to ``".*"``. +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_RESPONSE=".*" + +The name of the added span attribute will follow the format ``http.response.header.`` where ```` +is the normalized HTTP header name (lowercase, with ``-`` replaced by ``_``). The value of the attribute will be a +list containing the header values. + +For example: +``http.response.header.custom_response_header = ["", ""]`` + +Sanitizing headers +****************** +In order to prevent storing sensitive data such as personally identifiable information (PII), session keys, passwords, +etc, set the environment variable ``OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS`` +to a comma delimited list of HTTP header names to be sanitized. + +Regexes may be used, and all header names will be matched in a case-insensitive manner. + +For example using the environment variable, +:: + + export OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS=".*session.*,set-cookie" + +will replace the value of headers such as ``session-id`` and ``set-cookie`` with ``[REDACTED]`` in the span. + +Note: + The environment variable names used to capture HTTP headers are still experimental, and thus are subject to change. + API --- """ @@ -142,8 +233,15 @@ def response_hook( ) from opentelemetry.trace import Span, SpanKind, Tracer, get_tracer from opentelemetry.util.http import ( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_REQUEST, + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_RESPONSE, + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS, ExcludeList, + get_custom_header_attributes, + get_custom_headers, get_excluded_urls, + normalise_request_header_name, + normalise_response_header_name, parse_excluded_urls, sanitize_method, ) @@ -278,6 +376,7 @@ def _instrument(self, **kwargs): response_size_histogram_new = ( create_http_client_response_body_size(meter) ) + _instrument( tracer, duration_histogram_old, @@ -295,6 +394,24 @@ def _instrument(self, **kwargs): else parse_excluded_urls(excluded_urls) ), sem_conv_opt_in_mode=sem_conv_opt_in_mode, + captured_request_headers=kwargs.get( + "captured_request_headers", + get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_REQUEST + ), + ), + captured_response_headers=kwargs.get( + "captured_response_headers", + get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_RESPONSE + ), + ), + sensitive_headers=kwargs.get( + "sensitive_headers", + get_custom_headers( + OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS + ), + ), ) def _uninstrument(self, **kwargs): @@ -321,7 +438,11 @@ def _instrument( url_filter: _UrlFilterT = None, excluded_urls: ExcludeList = None, sem_conv_opt_in_mode: _StabilityMode = _StabilityMode.DEFAULT, + captured_request_headers: typing.Optional[list[str]] = None, + captured_response_headers: typing.Optional[list[str]] = None, + sensitive_headers: typing.Optional[list[str]] = None, ): + # pylint: disable=too-many-locals def instrumented_urlopen(wrapped, instance, args, kwargs): if not is_http_instrumentation_enabled(): return wrapped(*args, **kwargs) @@ -345,6 +466,15 @@ def instrumented_urlopen(wrapped, instance, args, kwargs): ) _set_http_url(span_attributes, url, sem_conv_opt_in_mode) + span_attributes.update( + get_custom_header_attributes( + headers, + captured_request_headers, + sensitive_headers, + normalise_request_header_name, + ) + ) + with ( tracer.start_as_current_span( span_name, kind=SpanKind.CLIENT, attributes=span_attributes @@ -402,6 +532,16 @@ def instrumented_urlopen(wrapped, instance, args, kwargs): sem_conv_opt_in_mode, ) + if span.is_recording(): + span.set_attributes( + get_custom_header_attributes( + response.headers, + captured_response_headers, + sensitive_headers, + normalise_response_header_name, + ) + ) + return response wrapt.wrap_function_wrapper( diff --git a/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py b/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py index e5a9f3b7e1..8bba46affb 100644 --- a/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py +++ b/instrumentation/opentelemetry-instrumentation-urllib3/tests/test_urllib3_integration.py @@ -11,6 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + import json import typing from unittest import mock @@ -609,3 +610,344 @@ def test_no_op_tracer_provider(self): response = self.perform_request(self.HTTP_URL) self.assertEqual(b"Hello!", response.data) self.assert_span(num_spans=0) + + def test_custom_response_headers_captured(self): + URLLib3Instrumentor().uninstrument() + URLLib3Instrumentor().instrument( + captured_response_headers=["X-Custom-Header", "X-Another-Header"] + ) + + response_headers = { + "X-Custom-Header": "custom-value", + "X-Another-Header": "another-value", + } + url = "http://mock//capture_headers" + httpretty.register_uri( + httpretty.GET, url, body="Hello!", adding_headers=response_headers + ) + self.perform_request(url) + + span = self.assert_span(num_spans=1) + self.assertEqual( + span.attributes["http.response.header.x_custom_header"], + ("custom-value",), + ) + self.assertEqual( + span.attributes["http.response.header.x_another_header"], + ("another-value",), + ) + self.assertNotIn( + "http.response.header.x_excluded_header", span.attributes + ) + + def test_custom_headers_not_captured_when_not_configured(self): + """Test that headers are not captured when env vars are not set.""" + URLLib3Instrumentor().uninstrument() + URLLib3Instrumentor().instrument() + + self.perform_request( + self.HTTP_URL, + headers={"X-Request-Header": "request-value"}, + ) + + span = self.assert_span(num_spans=1) + self.assertNotIn( + "http.request.header.x_request_header", span.attributes + ) + self.assertNotIn( + "http.response.header.x_response_header", span.attributes + ) + + def test_sensitive_headers_sanitized(self): + """Test that sensitive header values are redacted.""" + URLLib3Instrumentor().uninstrument() + URLLib3Instrumentor().instrument( + captured_request_headers=["Authorization", "X-Api-Key"], + captured_response_headers=["Set-Cookie", "X-Secret"], + sensitive_headers=[ + "Authorization", + "X-Api-Key", + "Set-Cookie", + "X-Secret", + ], + ) + + response_headers = { + "Set-Cookie": "session=abc123", + "X-Secret": "secret", + } + url = "http://mock//capture_headers" + httpretty.register_uri( + httpretty.GET, url, body="Hello!", adding_headers=response_headers + ) + self.perform_request( + url, + headers={ + "Authorization": "Bearer secret-token", + "X-Api-Key": "secret-key", + }, + ) + + span = self.assert_span(num_spans=1) + self.assertEqual( + span.attributes["http.request.header.authorization"], + ("[REDACTED]",), + ) + self.assertEqual( + span.attributes["http.request.header.x_api_key"], + ("[REDACTED]",), + ) + self.assertEqual( + span.attributes["http.response.header.set_cookie"], + ("[REDACTED]",), + ) + self.assertEqual( + span.attributes["http.response.header.x_secret"], + ("[REDACTED]",), + ) + + def test_custom_headers_with_regex(self): + """Test that header capture works with regex patterns.""" + URLLib3Instrumentor().uninstrument() + URLLib3Instrumentor().instrument( + captured_request_headers=["X-Custom-Request-.*"], + captured_response_headers=["X-Custom-Response-.*"], + ) + + response_headers = { + "X-Custom-Response-A": "value-A", + "X-Custom-Response-B": "value-B", + "X-Other-Response-Header": "other-value", + } + url = "http://mock//capture_headers" + httpretty.register_uri( + httpretty.GET, url, body="Hello!", adding_headers=response_headers + ) + self.perform_request( + url, + headers={ + "X-Custom-Request-One": "value-one", + "X-Custom-Request-Two": "value-two", + "X-Other-Request-Header": "other-value", + }, + ) + + span = self.assert_span(num_spans=1) + self.assertEqual( + span.attributes["http.request.header.x_custom_request_one"], + ("value-one",), + ) + self.assertEqual( + span.attributes["http.request.header.x_custom_request_two"], + ("value-two",), + ) + self.assertNotIn( + "http.request.header.x_other_request_header", span.attributes + ) + self.assertEqual( + span.attributes["http.response.header.x_custom_response_a"], + ("value-A",), + ) + self.assertEqual( + span.attributes["http.response.header.x_custom_response_b"], + ("value-B",), + ) + self.assertNotIn( + "http.response.header.x_other_response_header", span.attributes + ) + + def test_custom_headers_case_insensitive(self): + """Test that header capture is case-insensitive.""" + URLLib3Instrumentor().uninstrument() + URLLib3Instrumentor().instrument( + captured_request_headers=["x-request-header"], + captured_response_headers=["x-response-header"], + ) + + response_headers = {"X-ReSPoNse-HeaDER": "custom-value"} + url = "http://mock//capture_headers" + httpretty.register_uri( + httpretty.GET, url, body="Hello!", adding_headers=response_headers + ) + self.perform_request( + url, + headers={"X-ReQuESt-HeaDER": "custom-value"}, + ) + + span = self.assert_span(num_spans=1) + self.assertEqual( + span.attributes["http.request.header.x_request_header"], + ("custom-value",), + ) + self.assertEqual( + span.attributes["http.response.header.x_response_header"], + ("custom-value",), + ) + + def test_standard_http_headers_captured(self): + """Test that standard HTTP headers can be captured.""" + URLLib3Instrumentor().uninstrument() + URLLib3Instrumentor().instrument( + captured_request_headers=["Content-Type", "Accept"], + captured_response_headers=["Content-Type", "Server"], + ) + + response_headers = { + "Content-Type": "text/plain", + "Server": "TestServer/1.0", + } + url = "http://mock//capture_headers" + httpretty.register_uri( + httpretty.GET, url, body="Hello!", adding_headers=response_headers + ) + self.perform_request( + url, + headers={ + "Content-Type": "application/json", + "Accept": "application/json", + }, + ) + + span = self.assert_span(num_spans=1) + self.assertEqual( + span.attributes["http.request.header.content_type"], + ("application/json",), + ) + self.assertEqual( + span.attributes["http.request.header.accept"], + ("application/json",), + ) + self.assertEqual( + span.attributes["http.response.header.content_type"], + ("text/plain",), + ) + self.assertEqual( + span.attributes["http.response.header.server"], + ("TestServer/1.0",), + ) + + def test_capture_all_request_headers(self): + """Test that all request headers can be captured with .* pattern.""" + URLLib3Instrumentor().uninstrument() + URLLib3Instrumentor().instrument(captured_request_headers=[".*"]) + + self.perform_request( + self.HTTP_URL, + headers={ + "X-Header-One": "value1", + "X-Header-Two": "value2", + "X-Header-Three": "value3", + }, + ) + + span = self.assert_span(num_spans=1) + self.assertEqual( + span.attributes["http.request.header.x_header_one"], + ("value1",), + ) + self.assertEqual( + span.attributes["http.request.header.x_header_two"], + ("value2",), + ) + self.assertEqual( + span.attributes["http.request.header.x_header_three"], + ("value3",), + ) + + def test_capture_all_response_headers(self): + """Test that all response headers can be captured with .* pattern.""" + URLLib3Instrumentor().uninstrument() + URLLib3Instrumentor().instrument(captured_response_headers=[".*"]) + + response_headers = { + "X-Response-One": "value1", + "X-Response-Two": "value2", + "X-Response-Three": "value3", + } + url = "http://mock//capture_headers" + httpretty.register_uri( + httpretty.GET, url, body="Hello!", adding_headers=response_headers + ) + self.perform_request(url) + + span = self.assert_span(num_spans=1) + self.assertEqual( + span.attributes["http.response.header.x_response_one"], + ("value1",), + ) + self.assertEqual( + span.attributes["http.response.header.x_response_two"], + ("value2",), + ) + self.assertEqual( + span.attributes["http.response.header.x_response_three"], + ("value3",), + ) + + def test_sanitize_with_regex_pattern(self): + """Test that sanitization works with regex patterns.""" + URLLib3Instrumentor().uninstrument() + URLLib3Instrumentor().instrument( + captured_request_headers=["X-Test.*"], + sensitive_headers=[".*secret.*"], + ) + + self.perform_request( + self.HTTP_URL, + headers={ + "X-Test": "normal-value", + "X-Test-Secret": "secret-value", + }, + ) + + span = self.assert_span(num_spans=1) + self.assertEqual( + span.attributes["http.request.header.x_test"], + ("normal-value",), + ) + self.assertEqual( + span.attributes["http.request.header.x_test_secret"], + ("[REDACTED]",), + ) + + @mock.patch.dict( + "os.environ", + { + "OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_REQUEST": "x-request-one,x-request-two", + "OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_CLIENT_RESPONSE": "x-response-one", + "OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SANITIZE_FIELDS": "x-request-two", + }, + ) + def test_capture_and_sanitize_environment_variables(self): + URLLib3Instrumentor().uninstrument() + URLLib3Instrumentor().instrument() + + response_headers = { + "X-Response-One": "value1", + "X-Response-Two": "value2", + } + url = "http://mock//capture_headers" + httpretty.register_uri( + httpretty.GET, url, body="Hello!", adding_headers=response_headers + ) + self.perform_request( + url, headers={"x-request-one": "one", "x-request-two": "two"} + ) + + span = self.assert_span(num_spans=1) + self.assertEqual( + span.attributes["http.request.header.x_request_one"], + ("one",), + ) + self.assertEqual( + span.attributes["http.request.header.x_request_two"], + ("[REDACTED]",), + ) + self.assertEqual( + span.attributes["http.response.header.x_response_one"], + ("value1",), + ) + self.assertNotIn( + "http.response.header.x_response_two", + span.attributes, + )