Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add HTTP headers filtering to observability reporter (#11285)
Przemysław Łada7ae893782a50
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 84974a37eb..ec40aebb6e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -40,6 +40,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add metadata on order line payload notifications. #10954 by @CarlesLopezMagem- Make email authentication case-insensitive. #11284 by @zedzior- Fix the observability reporter to obfuscate URLs. #11282 by @przlada+- Add HTTP headers filtering to observability reporter. #11285 by @przlada# 3.8.0diff --git a/saleor/webhook/observability/obfuscation.py b/saleor/webhook/observability/obfuscation.pyindex 1e10634aa7..80efcfc841 100644--- a/saleor/webhook/observability/obfuscation.py+++ b/saleor/webhook/observability/obfuscation.py@@ -1,4 +1,4 @@-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union, cast+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, Union, castfrom urllib.parse import urlparse, urlunparsefrom graphql import (@@ -22,7 +22,7 @@ from graphql.validation.rules.base import ValidationRulefrom graphql.validation.validation import ValidationContextfrom ...graphql.api import schema-from .sensitive_data import SENSITIVE_HEADERS, SensitiveFieldsMap+from .sensitive_data import ALLOWED_HEADERS, SENSITIVE_HEADERS, SensitiveFieldsMapif TYPE_CHECKING:from graphql import GraphQLDocument@@ -39,13 +39,20 @@ GraphQLNode = Union[MASK = "***"-def hide_sensitive_headers(- headers: Dict[str, str], sensitive_headers: Tuple[str, ...] = SENSITIVE_HEADERS+def filter_and_hide_headers(+ headers: Dict[str, str],+ allowed=ALLOWED_HEADERS,+ sensitive=SENSITIVE_HEADERS,) -> Dict[str, str]:- return {- key: val if key.upper().replace("-", "_") not in sensitive_headers else MASK- for key, val in headers.items()- }+ filtered_headers = {}+ for key, val in headers.items():+ lowered = key.lower()+ if lowered in allowed:+ if lowered in sensitive:+ filtered_headers[key] = MASK+ else:+ filtered_headers[key] = val+ return filtered_headersdef obfuscate_url(url: str) -> str:diff --git a/saleor/webhook/observability/payloads.py b/saleor/webhook/observability/payloads.pyindex b6b065f7ac..9f1a8bbab4 100644--- a/saleor/webhook/observability/payloads.py+++ b/saleor/webhook/observability/payloads.py@@ -17,7 +17,7 @@ from .exceptions import ApiCallTruncationError, EventDeliveryAttemptTruncationErfrom .obfuscation import (anonymize_event_payload,anonymize_gql_operation_response,- hide_sensitive_headers,+ filter_and_hide_headers,obfuscate_url,)from .payload_schema import (@@ -85,7 +85,7 @@ GQL_OPERATION_PLACEHOLDER_SIZE = len(dump_payload(GQL_OPERATION_PLACEHOLDER))def serialize_headers(headers: Optional[Dict[str, str]]) -> HttpHeaders:if headers:- return list(hide_sensitive_headers(headers).items())+ return list(filter_and_hide_headers(headers).items())return []diff --git a/saleor/webhook/observability/sensitive_data.py b/saleor/webhook/observability/sensitive_data.pyindex 25dfd6e290..f8f68fb07a 100644--- a/saleor/webhook/observability/sensitive_data.py+++ b/saleor/webhook/observability/sensitive_data.py@@ -1,6 +1,8 @@"""Definitions of sensitive data for observability obfuscation methods.-SENSITIVE_HEADERS is a tuple of sensitive HTTP headers to anonymize before reporting.+ALLOWED_HEADERS is a set of lowercase HTTP headers allowed for reporting.++SENSITIVE_HEADERS is a set of lowercase HTTP headers to anonymize before reporting.SENSITIVE_GQL_FIELDS is a dict of sets representing fields of GraphGL types to anonymize- Type@@ -8,16 +10,38 @@ SENSITIVE_GQL_FIELDS is a dict of sets representing fields of GraphGL types to a"""from typing import Dict, Set-from ...core.auth import DEFAULT_AUTH_HEADER, SALEOR_AUTH_HEADER+from ...app.headers import AppHeaders, DeprecatedAppHeaders-SENSITIVE_HEADERS = (- SALEOR_AUTH_HEADER,- DEFAULT_AUTH_HEADER,- "COOKIE",-)-SENSITIVE_HEADERS = tuple(- x[5:] if x.startswith("HTTP_") else x for x in SENSITIVE_HEADERS-)+ALLOWED_HEADERS = {+ header.lower()+ for header in {+ "Content-Length",+ "Content-Type",+ "Host",+ "Origin",+ "Referer",+ "Content-Encoding",+ "User-Agent",+ "Cookie",+ "Authorization",+ "Authorization-Bearer",+ DeprecatedAppHeaders.DOMAIN,+ DeprecatedAppHeaders.EVENT_TYPE,+ DeprecatedAppHeaders.SIGNATURE,+ AppHeaders.DOMAIN,+ AppHeaders.EVENT_TYPE,+ AppHeaders.SIGNATURE,+ AppHeaders.API_URL,+ }+}+SENSITIVE_HEADERS = {+ header.lower()+ for header in {+ "Cookie",+ "Authorization",+ "Authorization-Bearer",+ }+}SensitiveFieldsMap = Dict[str, Set[str]]SENSITIVE_GQL_FIELDS: SensitiveFieldsMap = {diff --git a/saleor/webhook/observability/tests/test_obfuscation.py b/saleor/webhook/observability/tests/test_obfuscation.pyindex 1ed503f386..370affbc92 100644--- a/saleor/webhook/observability/tests/test_obfuscation.py+++ b/saleor/webhook/observability/tests/test_obfuscation.py@@ -6,34 +6,37 @@ from ..obfuscation import (MASK,anonymize_event_payload,anonymize_gql_operation_response,- hide_sensitive_headers,+ filter_and_hide_headers,obfuscate_url,validate_sensitive_fields_map,)@pytest.mark.parametrize(- "headers,sensitive,expected",+ "headers,allowed,sensitive,expected",[+ ({}, {"header"}, {"header"}, {}),+ ({"Header": "val"}, {}, {}, {}),+ ({"HeAdEr": "val"}, {"header"}, {}, {"HeAdEr": "val"}),(- {"header1": "text", "header2": "text"},- ("AUTHORIZATION", "AUTHORIZATION_BEARER"),- {"header1": "text", "header2": "text"},+ {"Header": "val", "AuThOrIzAtIoN": "secret"},+ {"header"},+ {"authorization"},+ {"Header": "val"},),(- {"header1": "text", "authorization": "secret"},- ("AUTHORIZATION", "AUTHORIZATION_BEARER"),- {"header1": "text", "authorization": MASK},- ),- (- {"HEADER1": "text", "authorization-bearer": "secret"},- ("AUTHORIZATION", "AUTHORIZATION_BEARER"),- {"HEADER1": "text", "authorization-bearer": MASK},+ {"Content-Length": "10", "AuThOrIzAtIoN": "secret", "Not-Allowed": "val"},+ {"content-length", "authorization"},+ {"authorization"},+ {"Content-Length": "10", "AuThOrIzAtIoN": MASK},),],)-def test_hide_sensitive_headers(headers, sensitive, expected):- assert hide_sensitive_headers(headers, sensitive_headers=sensitive) == expected+def test_filter_and_hide_headers(headers, allowed, sensitive, expected):+ assert (+ filter_and_hide_headers(headers, allowed=allowed, sensitive=sensitive)+ == expected+ )@pytest.mark.parametrize(diff --git a/saleor/webhook/observability/tests/test_payloads.py b/saleor/webhook/observability/tests/test_payloads.pyindex e03f26323d..c993aa7fa7 100644--- a/saleor/webhook/observability/tests/test_payloads.py+++ b/saleor/webhook/observability/tests/test_payloads.py@@ -219,8 +219,16 @@ def test_serialize_gql_operation_results_when_too_low_bytes_limit(({}, []),(None, []),(- {"Content-Length": "19", "Content-Type": "application/json"},- [("Content-Length", "19"), ("Content-Type", "application/json")],+ {+ "Authorization": "secret",+ "Content-Length": "19",+ "Content-Type": "application/json",+ },+ [+ ("Authorization", MASK),+ ("Content-Length", "19"),+ ("Content-Type", "application/json"),+ ],),],)