diff --git a/spec/Http/HttpSensitiveDataHelperSpec.php b/spec/Http/HttpSensitiveDataHelperSpec.php new file mode 100644 index 0000000..65bfd9e --- /dev/null +++ b/spec/Http/HttpSensitiveDataHelperSpec.php @@ -0,0 +1,29 @@ + + */ + +namespace spec\Instrumentation\Http; + +use PhpSpec\ObjectBehavior; + +class HttpSensitiveDataHelperSpec extends ObjectBehavior +{ + public function it_removes_credentials_from_url(): void + { + $this::filterUrl('https://root:p4ssw0rd@example.com?foo=bar#baz')->shouldReturn('https://example.com?foo=bar#baz'); + } + + public function it_removes_credentials_from_headers(): void + { + $this::filterHeaders([ + 'Content-Type' => 'application/json', + 'Authorization' => 'Bearer kjfdhsfkjshgskjq', + 'proxy-authorization' => 'Basic gperfbshkdbfzdzl', + ])->shouldReturn([ + 'Content-Type' => 'application/json', + ]); + } +} diff --git a/src/Http/HttpMessageHelper.php b/src/Http/HttpMessageHelper.php index 92ddf4e..dc4ad4a 100644 --- a/src/Http/HttpMessageHelper.php +++ b/src/Http/HttpMessageHelper.php @@ -16,6 +16,8 @@ class HttpMessageHelper */ public static function formatHeadersForSpanAttribute(array $headers): string { + $headers = HttpSensitiveDataHelper::filterHeaders($headers); + $lines = []; foreach ($headers as $name => $values) { foreach ($values as $value) { diff --git a/src/Http/HttpSensitiveDataHelper.php b/src/Http/HttpSensitiveDataHelper.php new file mode 100644 index 0000000..0a25d67 --- /dev/null +++ b/src/Http/HttpSensitiveDataHelper.php @@ -0,0 +1,40 @@ + + */ + +namespace Instrumentation\Http; + +use Nyholm\Psr7\Uri; + +class HttpSensitiveDataHelper +{ + private const SENSITIVE_HEADERS = [ + 'authorization', + 'Authorization', + 'proxy-authorization', + 'Proxy-Authorization', + ]; + + public static function filterUrl(string $url): string + { + $url = new Uri($url); + $url = $url->withUserInfo(''); + + return (string) $url; + } + + /** + * @param array $headers + * + * @return array + */ + public static function filterHeaders(array $headers): array + { + return array_diff_key($headers, array_flip(self::SENSITIVE_HEADERS)); + } +} diff --git a/src/Semantics/Attribute/ClientRequestAttributeProvider.php b/src/Semantics/Attribute/ClientRequestAttributeProvider.php index c4d24bb..1f3c73e 100644 --- a/src/Semantics/Attribute/ClientRequestAttributeProvider.php +++ b/src/Semantics/Attribute/ClientRequestAttributeProvider.php @@ -9,6 +9,7 @@ namespace Instrumentation\Semantics\Attribute; +use Instrumentation\Http\HttpSensitiveDataHelper; use OpenTelemetry\SemConv\TraceAttributes; class ClientRequestAttributeProvider implements ClientRequestAttributeProviderInterface @@ -24,7 +25,7 @@ public function getAttributes(string $method, string $url, array $headers = []): { $attributes = [ TraceAttributes::HTTP_METHOD => strtoupper($method), - TraceAttributes::HTTP_URL => $url, + TraceAttributes::HTTP_URL => HttpSensitiveDataHelper::filterUrl($url), ]; foreach ($this->capturedHeaders as $header) {