Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Make sure we never log URL credentials (#16897)
Patryk Zawadzki15d39085ad76
diff --git a/saleor/core/utils/tests/test_url.py b/saleor/core/utils/tests/test_url.pyindex 6dd5e3e7ed..65d987d714 100644--- a/saleor/core/utils/tests/test_url.py+++ b/saleor/core/utils/tests/test_url.py@@ -1,9 +1,10 @@from collections import OrderedDictfrom urllib.parse import urlencode+import pytestfrom django.conf import settings-from ..url import get_default_storage_root_url, prepare_url+from ..url import get_default_storage_root_url, prepare_url, sanitize_url_for_loggingdef test_prepare_url():@@ -26,3 +27,27 @@ def test_get_default_storage_root_url(site_settings):# thenassert root_url == f"http://{site_settings.site.domain}{settings.MEDIA_URL}"+++ ("url", "expected"),+ [+ ("http://example.com/test", "http://example.com/test"),+ (+ "https://example.com:8000/test/path?q=val&k=val",+ "https://example.com:8000/test/path?q=val&k=val",+ ),+ ("https://[email protected]/test", "https://***:***@example.com/test"),+ ("https://:[email protected]/test", "https://***:***@example.com/test"),+ (+ "http://user:[email protected]:8000/test",+ "http://***:***@example.com:8000/test",+ ),+ (+ "awssqs://key:[email protected]/xxxx/myqueue.fifo",+ "awssqs://***:***@sqs.us-east-2.amazonaws.com/xxxx/myqueue.fifo",+ ),+ ],+)+def test_sanitize_url_for_logging(url, expected):+ assert sanitize_url_for_logging(url) == expecteddiff --git a/saleor/core/utils/url.py b/saleor/core/utils/url.pyindex 7eade00ae2..a36dccb4c8 100644--- a/saleor/core/utils/url.py+++ b/saleor/core/utils/url.py@@ -49,3 +49,15 @@ def get_default_storage_root_url():# `path` is stripped to get the actual root URLtmp_path = "path"return build_absolute_uri(default_storage.url(tmp_path)).rstrip(tmp_path)+++def sanitize_url_for_logging(url: str) -> str:+ """Remove sensitive data from a URL to make it safe for logging."""+ url_parts = urlparse(url)+ if url_parts.username or url_parts.password:+ url_parts = url_parts._replace(+ netloc=f"***:***@{url_parts.hostname}:{url_parts.port}"+ if url_parts.port+ else f"***:***@{url_parts.hostname}"+ )+ return url_parts.geturl()diff --git a/saleor/webhook/observability/obfuscation.py b/saleor/webhook/observability/obfuscation.pyindex 93c7540064..f0f30c38ff 100644--- a/saleor/webhook/observability/obfuscation.py+++ b/saleor/webhook/observability/obfuscation.py@@ -1,5 +1,4 @@from typing import TYPE_CHECKING, Any, Optional, Union, cast-from urllib.parse import urlparse, urlunparsefrom graphql import (GraphQLError,@@ -55,17 +54,6 @@ def filter_and_hide_headers(return filtered_headers-def obfuscate_url(url: str) -> str:- parts = urlparse(url)- # If parts.username returns None there are no credentials in the URL- if parts.username is None:- return url- password = "" if parts.password is None else f":{MASK}"- port = "" if parts.port is None else f":{parts.port}"- netloc = f"{parts.username}{password}@{parts.hostname}{port}"- return urlunparse([parts[0], netloc, *parts[2:]])--class SensitiveFieldError(GraphQLError):passdiff --git a/saleor/webhook/observability/payloads.py b/saleor/webhook/observability/payloads.pyindex 4cae585e52..c2d2a89cdb 100644--- a/saleor/webhook/observability/payloads.py+++ b/saleor/webhook/observability/payloads.py@@ -12,6 +12,7 @@ from graphene.utils.str_converters import to_camel_case as str_to_camel_casefrom graphql import get_operation_astfrom ...core.utils import build_absolute_uri+from ...core.utils.url import sanitize_url_for_loggingfrom .. import traced_payload_generatorfrom ..event_types import WebhookEventSyncTypefrom .exceptions import ApiCallTruncationError, EventDeliveryAttemptTruncationError@@ -19,7 +20,6 @@ from .obfuscation import (anonymize_event_payload,anonymize_gql_operation_response,filter_and_hide_headers,- obfuscate_url,)from .payload_schema import (ApiCallPayload,@@ -237,7 +237,7 @@ def generate_event_delivery_attempt_payload(webhook=Webhook(id=graphene.Node.to_global_id("Webhook", attempt.delivery.webhook.pk),name=attempt.delivery.webhook.name or "",- target_url=obfuscate_url(attempt.delivery.webhook.target_url),+ target_url=sanitize_url_for_logging(attempt.delivery.webhook.target_url),subscription_query=TRUNC_PLACEHOLDER,),app=App(diff --git a/saleor/webhook/observability/tests/test_obfuscation.py b/saleor/webhook/observability/tests/test_obfuscation.pyindex 7cb4470ae4..3879dd0627 100644--- a/saleor/webhook/observability/tests/test_obfuscation.py+++ b/saleor/webhook/observability/tests/test_obfuscation.py@@ -7,7 +7,6 @@ from ..obfuscation import (anonymize_event_payload,anonymize_gql_operation_response,filter_and_hide_headers,- obfuscate_url,validate_sensitive_fields_map,)@@ -39,30 +38,6 @@ def test_filter_and_hide_headers(headers, allowed, sensitive, expected):)- ("url", "expected"),- [- ("http://example.com/test", "http://example.com/test"),- (- "https://example.com:8000/test/path?q=val&k=val",- "https://example.com:8000/test/path?q=val&k=val",- ),- ("https://[email protected]/test", "https://[email protected]/test"),- ("https://:[email protected]/test", f"https://:{MASK}@example.com/test"),- (- "http://user:[email protected]:8000/test",- f"http://user:{MASK}@example.com:8000/test",- ),- (- "awssqs://key:[email protected]/xxxx/myqueue.fifo",- f"awssqs://key:{MASK}@sqs.us-east-2.amazonaws.com/xxxx/myqueue.fifo",- ),- ],-)-def test_obfuscate_url(url, expected):- assert obfuscate_url(url) == expected--def test_anonymize_gql_operation_response(gql_operation_factory):query = "query FirstQuery { shop { name } }"result = {"data": "result"}diff --git a/saleor/webhook/observability/tests/test_payloads.py b/saleor/webhook/observability/tests/test_payloads.pyindex d269bcf672..15960b7332 100644--- a/saleor/webhook/observability/tests/test_payloads.py+++ b/saleor/webhook/observability/tests/test_payloads.py@@ -488,4 +488,4 @@ def test_generate_event_delivery_attempt_payload_target_url_obfuscated(payload = generate_event_delivery_attempt_payload(event_attempt, None, 1024)payload = json.loads(payload)- assert payload["webhook"]["targetUrl"] == f"http://user:{MASK}@example.com/webhooks"+ assert payload["webhook"]["targetUrl"] == "http://***:***@example.com/webhooks"diff --git a/saleor/webhook/transport/asynchronous/transport.py b/saleor/webhook/transport/asynchronous/transport.pyindex 6addf92fe5..a652d6dfb3 100644--- a/saleor/webhook/transport/asynchronous/transport.py+++ b/saleor/webhook/transport/asynchronous/transport.py@@ -17,6 +17,7 @@ from ....core.db.connection import allow_writerfrom ....core.models import EventDelivery, EventPayloadfrom ....core.tracing import webhooks_opentracing_tracefrom ....core.utils import get_domain+from ....core.utils.url import sanitize_url_for_loggingfrom ....graphql.core.dataloaders import DataLoaderfrom ....graphql.webhook.subscription_payload import (generate_payload_from_subscription,@@ -136,7 +137,7 @@ def create_deliveries_for_multiple_subscription_objects("[Webhook ID:%r] No data changes for event %r, skip delivery to %r",webhook.id,event_type,- webhook.target_url,+ sanitize_url_for_logging(webhook.target_url),)continue@@ -404,7 +405,7 @@ def send_webhook_request_async(self, event_delivery_id) -> None:task_logger.info("[Webhook ID:%r] Payload sent to %r for event %r. Delivery id: %r",webhook.id,- webhook.target_url,+ sanitize_url_for_logging(webhook.target_url),delivery.event_type,delivery.id,)@@ -461,7 +462,7 @@ def send_observability_events(webhooks: list[WebhookData], events: list[bytes]):logger.info("Webhook ID: %r failed request to %r (%s/%s events dropped): %r.",webhook.id,- webhook.target_url,+ sanitize_url_for_logging(webhook.target_url),failed,len(events),response.content,@@ -471,7 +472,7 @@ def send_observability_events(webhooks: list[WebhookData], events: list[bytes]):logger.debug("Successful delivered %s events to %r.",len(events),- webhook.target_url,+ sanitize_url_for_logging(webhook.target_url),extra={**extra, "dropped_events_count": 0},)diff --git a/saleor/webhook/transport/synchronous/transport.py b/saleor/webhook/transport/synchronous/transport.pyindex 5610507412..0fe9a1d7b4 100644--- a/saleor/webhook/transport/synchronous/transport.py+++ b/saleor/webhook/transport/synchronous/transport.py@@ -14,6 +14,7 @@ from ....core.db.connection import allow_writerfrom ....core.models import EventDelivery, EventPayloadfrom ....core.tracing import webhooks_opentracing_tracefrom ....core.utils import get_domain+from ....core.utils.url import sanitize_url_for_loggingfrom ....graphql.webhook.subscription_payload import (generate_payload_from_subscription,initialize_request,@@ -104,7 +105,7 @@ def _send_webhook_request_sync(logger.debug("[Webhook] Sending payload to %r for event %r.",- webhook.target_url,+ sanitize_url_for_logging(webhook.target_url),delivery.event_type,)if attempt is None:@@ -131,7 +132,7 @@ def _send_webhook_request_sync(logger.info("[Webhook] Failed parsing JSON response from %r: %r.""ID of failed DeliveryAttempt: %r . ",- webhook.target_url,+ sanitize_url_for_logging(webhook.target_url),e,attempt.id,)@@ -141,7 +142,7 @@ def _send_webhook_request_sync(logger.info("[Webhook] Failed request to %r: %r. ""ID of failed DeliveryAttempt: %r . ",- webhook.target_url,+ sanitize_url_for_logging(webhook.target_url),response.content,attempt.id,)@@ -149,7 +150,7 @@ def _send_webhook_request_sync(logger.debug("[Webhook] Success response from %r.""Successful DeliveryAttempt id: %r",- webhook.target_url,+ sanitize_url_for_logging(webhook.target_url),attempt.id,)diff --git a/saleor/webhook/transport/utils.py b/saleor/webhook/transport/utils.pyindex 9b3386057f..171b6e9b50 100644--- a/saleor/webhook/transport/utils.py+++ b/saleor/webhook/transport/utils.py@@ -35,6 +35,7 @@ from ...core.tasks import delete_files_from_private_storage_taskfrom ...core.taxes import TaxData, TaxLineDatafrom ...core.utils import build_absolute_urifrom ...core.utils.events import call_event+from ...core.utils.url import sanitize_url_for_loggingfrom ...payment import PaymentErrorfrom ...payment.interface import (GatewayResponse,@@ -312,7 +313,7 @@ def handle_webhook_retry(log_extra_details = {"webhook": {"id": webhook.id,- "target_url": webhook.target_url,+ "target_url": sanitize_url_for_logging(webhook.target_url),"event": delivery.event_type,"execution_mode": "async","duration": response.duration,@@ -323,7 +324,7 @@ def handle_webhook_retry("[Webhook ID: %r] Failed request to %r: %r for event: %r."" Delivery attempt id: %r",webhook.id,- webhook.target_url,+ sanitize_url_for_logging(webhook.target_url),response.content,delivery.event_type,delivery_attempt.id,@@ -334,7 +335,7 @@ def handle_webhook_retry(task_logger.info("[Webhook ID: %r] Failed request to %r: received HTTP %d. Delivery ID: %r",webhook.id,- webhook.target_url,+ sanitize_url_for_logging(webhook.target_url),response.response_status_code,delivery.id,extra=log_extra_details,@@ -352,7 +353,7 @@ def handle_webhook_retry(task_logger.info("[Webhook ID: %r] Failed request to %r: exceeded retry limit. Delivery ID: %r",webhook.id,- webhook.target_url,+ sanitize_url_for_logging(webhook.target_url),delivery.id,extra=log_extra_details,)