Skip to content

Saleor Core: the high performance, composable, headless commerce API.

reliability: fix and prevent logging exceptions

Mikail Kocak359c1001bdd9
diff --git a/.semgrep/security/logging/exception-object-in-logger-extra.py b/.semgrep/security/logging/exception-object-in-logger-extra.py
new file mode 100644
index 0000000000..cf41fe3d7e
--- /dev/null
+++ b/.semgrep/security/logging/exception-object-in-logger-extra.py
@@ -0,0 +1,33 @@
+# Should match when logging an exception.
+def test_log_info_exception():
+ try:
+ do_something()
+ except Exception as exc:
+ # ruleid: exception-object-in-logger-extra
+ logger.info("Failed", extra={"error": exc})
+
+# Should match when extra contains multiple keys & values.
+def test_log_multiple_extra():
+ try:
+ do_something()
+ except Exception as exc:
+ # ruleid: exception-object-in-logger-extra
+ logger.info("Failed", extra={"other1": 1, "error": exc, "other2": 1})
+
+# Should not match when converting an exception object to string.
+def test_not_logging_exception():
+ try:
+ do_something()
+ except Exception as exc:
+ # ok: exception-object-in-logger-extra
+ logger.info("Failed", extra={"exc": str(exc)})
+
+
+# Should not match when using an attribute from the exception object.
+def test_not_logging_exception():
+ try:
+ do_something()
+ except Exception as exc:
+ # ok: exception-object-in-logger-extra
+ logger.info("Failed", extra={"exc": exc.message})
+
diff --git a/.semgrep/security/logging/exception-object-in-logger-extra.yaml b/.semgrep/security/logging/exception-object-in-logger-extra.yaml
new file mode 100644
index 0000000000..f07f152e40
--- /dev/null
+++ b/.semgrep/security/logging/exception-object-in-logger-extra.yaml
@@ -0,0 +1,23 @@
+rules:
+ - id: exception-object-in-logger-extra
+ patterns:
+ - pattern-inside: |
+ try:
+ ...
+ except ... as $EXC:
+ ...
+ - pattern: |
+ $LOGGER.$LOG_FUNC(..., extra={..., ...: $EXC, ...})
+ - metavariable-regex:
+ metavariable: $LOGGER
+ regex: (?i)(logger|logging)
+ - metavariable-regex:
+ metavariable: $LOG_FUNC
+ regex: (debug|info|warn|warning|error|exception|critical)
+ # e.g., it can cause Sentry to hold the thread reference which leads to threads to not be freed. This is especially true with asgiref as it can spin N threads per HTTP request.
+ message: >-
+ Exception objects should not be put inside a logger's `extra` field, it can lead to high memory usage. Instead, use str(exc) to log the message.
+ languages: [python]
+ severity: WARNING
+ focus-metavariable: $EXC
+
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index 44ab716498..2d5358c266 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -213,7 +213,9 @@ def create_order(payment, checkout, manager):
)
except ValidationError as e:
logger.info(
- "Failed to create order from checkout %s.", checkout.pk, extra={"error": e}
+ "Failed to create order from checkout %s.",
+ checkout.pk,
+ extra={"error": str(e)},
)
return None
# Refresh the payment to assign the newly created order
@@ -292,7 +294,9 @@ def handle_authorization(notification: dict[str, Any], gateway_config: GatewayCo
amount.get("value"), amount.get("currency")
)
except TypeError as e:
- logger.exception("Cannot convert amount from minor unit", extra={"error": e})
+ logger.exception(
+ "Cannot convert amount from minor unit", extra={"error": str(e)}
+ )
return
if notification_payment_amount < payment.total:
diff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.py
index bffef3e525..80262bbf2f 100644
--- a/saleor/payment/gateways/stripe/webhooks.py
+++ b/saleor/payment/gateways/stripe/webhooks.py
@@ -72,12 +72,12 @@ def handle_webhook(
except ValueError as e:
# Invalid payload
logger.warning(
- "Received invalid payload for Stripe webhook", extra={"error": e}
+ "Received invalid payload for Stripe webhook", extra={"error": str(e)}
)
return HttpResponse(status=400)
except SignatureVerificationError as e:
# Invalid signature
- logger.warning("Invalid signature for Stripe webhook", extra={"error": e})
+ logger.warning("Invalid signature for Stripe webhook", extra={"error": str(e)})
return HttpResponse(status=400)
webhook_handlers = {
@@ -218,7 +218,9 @@ def _finalize_checkout(
app=None,
)
except ValidationError as e:
- logger.info("Failed to complete checkout %s.", checkout.pk, extra={"error": e})
+ logger.info(
+ "Failed to complete checkout %s.", checkout.pk, extra={"error": str(e)}
+ )
return None
diff --git a/saleor/plugins/openid_connect/utils.py b/saleor/plugins/openid_connect/utils.py
index 1ab3a8207d..dde3fd5f45 100644
--- a/saleor/plugins/openid_connect/utils.py
+++ b/saleor/plugins/openid_connect/utils.py
@@ -132,19 +132,19 @@ def get_user_info(user_info_url, access_token) -> Optional[dict]:
except requests.exceptions.HTTPError as e:
logger.warning(
"Fetching OIDC user info failed. HTTP error occurred",
- extra={"user_info_url": user_info_url, "error": e},
+ extra={"user_info_url": user_info_url, "error": str(e)},
)
return None
except requests.exceptions.RequestException as e:
logger.warning(
"Fetching OIDC user info failed",
- extra={"user_info_url": user_info_url, "error": e},
+ extra={"user_info_url": user_info_url, "error": str(e)},
)
return None
except json.JSONDecodeError as e:
logger.warning(
"Invalid OIDC user info response",
- extra={"user_info_url": user_info_url, "error": e},
+ extra={"user_info_url": user_info_url, "error": str(e)},
)
return None
@@ -154,7 +154,8 @@ def decode_access_token(token, jwks_url):
return get_decoded_token(token, jwks_url)
except (JoseError, ValueError) as e:
logger.info(
- "Invalid OIDC access token format", extra={"error": e, "jwks_url": jwks_url}
+ "Invalid OIDC access token format",
+ extra={"error": str(e), "jwks_url": jwks_url},
)
return None
@@ -173,7 +174,7 @@ def get_user_from_oauth_access_token_in_jwt_format(
except (JoseError, ValueError) as e:
logger.info(
"OIDC access token validation failed",
- extra={"error": e, "user_info_url": user_info_url},
+ extra={"error": str(e), "user_info_url": user_info_url},
)
return None
@@ -196,7 +197,7 @@ def get_user_from_oauth_access_token_in_jwt_format(
last_login=token_payload.get("iat"),
)
except AuthenticationError as e:
- logger.info("Unable to create a user object", extra={"error": e})
+ logger.info("Unable to create a user object", extra={"error": str(e)})
return None
scope = token_payload.get("scope")