diff --git a/.hark/changes/2026-11-15_jaideepkrishna2008-ui_webhook-non-ascii-signature.change.md b/.hark/changes/2026-11-15_jaideepkrishna2008-ui_webhook-non-ascii-signature.change.md new file mode 100644 index 000000000..ad646d843 --- /dev/null +++ b/.hark/changes/2026-11-15_jaideepkrishna2008-ui_webhook-non-ascii-signature.change.md @@ -0,0 +1,8 @@ +--- +title: Handle non-ASCII signatures gracefully in WebhookSignature.verify_header +semver_level: patch +github_issues_resolved: +- https://github.com/stripe/stripe-python/issues/1991 +--- + +Fix `WebhookSignature.verify_header` raising an unhandled `TypeError` when a signature contains non-ASCII characters, properly raising `SignatureVerificationError` instead. diff --git a/stripe/_util.py b/stripe/_util.py index 995967aa5..c2be3ad13 100644 --- a/stripe/_util.py +++ b/stripe/_util.py @@ -105,7 +105,15 @@ def fmt(key, val): if hasattr(hmac, "compare_digest"): # Prefer the stdlib implementation, when available. def secure_compare(val1, val2): - return hmac.compare_digest(val1, val2) + try: + return hmac.compare_digest(val1, val2) + except TypeError: + if isinstance(val1, str) and isinstance(val2, str): + return hmac.compare_digest( + val1.encode("utf-8", "surrogatepass"), + val2.encode("utf-8", "surrogatepass"), + ) + raise else: diff --git a/tests/test_webhook.py b/tests/test_webhook.py index 7248ef01e..499c8a561 100644 --- a/tests/test_webhook.py +++ b/tests/test_webhook.py @@ -5,6 +5,7 @@ import stripe from stripe._error import SignatureVerificationError +from stripe._util import secure_compare from stripe._webhook import WebhookSignature @@ -222,6 +223,34 @@ def test_raise_on_no_valid_signatures_for_payload(self): DUMMY_WEBHOOK_PAYLOAD, header, DUMMY_WEBHOOK_SECRET ) + def test_raise_on_non_ascii_signature_in_header(self): + for header in ["t=1,v1=é", "t=1,v1=\udcff"]: + with pytest.raises( + SignatureVerificationError, + match="No signatures found matching the expected signature for payload", + ): + stripe.WebhookSignature.verify_header( + DUMMY_WEBHOOK_PAYLOAD, header, DUMMY_WEBHOOK_SECRET + ) + + def test_header_with_non_ascii_v1_before_valid_v1(self): + header = generate_header() + # Prepend a non-ASCII v1 before the valid v1 + header_with_bad_v1 = header.replace("v1=", "v1=é,v1=") + assert stripe.WebhookSignature.verify_header( + DUMMY_WEBHOOK_PAYLOAD, header_with_bad_v1, DUMMY_WEBHOOK_SECRET + ) + + def test_secure_compare_non_ascii_strings(self): + assert secure_compare("é", "é") + assert not secure_compare("é", "è") + + def test_secure_compare_raises_type_error_on_invalid_types(self): + with pytest.raises(TypeError): + secure_compare(None, "signature") + with pytest.raises(TypeError): + secure_compare(b"bytes", "str") + def test_diagnose_secret_mismatch(self): dashboard_url_base = "https://dashboard.stripe.com/webhooks" cases = [