Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 9 additions & 1 deletion stripe/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
29 changes: 29 additions & 0 deletions tests/test_webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import stripe
from stripe._error import SignatureVerificationError
from stripe._util import secure_compare
from stripe._webhook import WebhookSignature


Expand Down Expand Up @@ -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 = [
Expand Down