From f77550a864c613cd817685fbfef26ca4ce6d5b7b Mon Sep 17 00:00:00 2001 From: nlathia Date: Fri, 13 Nov 2026 22:53:25 +0000 Subject: [PATCH] Raise SignatureVerificationError for unrepresentable timestamps and non-ASCII signatures parse_signature_header converted the timestamp to a datetime outside its try/except, so out-of-range timestamps raised ValueError/OverflowError, and non-ASCII signatures raised TypeError from hmac.compare_digest. Treat all of these as invalid signatures. Co-Authored-By: Claude Sonnet 5.5 --- src/gradient_labs/webhook.py | 11 +++++++++-- tests/test_webhook.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/gradient_labs/webhook.py b/src/gradient_labs/webhook.py index dfe42ca..d9a2606 100644 --- a/src/gradient_labs/webhook.py +++ b/src/gradient_labs/webhook.py @@ -77,15 +77,22 @@ def parse_signature_header( timestamp, signatures = cls._get_timestamp_and_signatures( header, cls.SCHEME ) + # Not every integer is a representable datetime (e.g. year 10000). + parsed_timestamp = datetime.fromtimestamp(timestamp, UTC) except Exception: return WebhookSignature(valid=False, timestamp=None) signed_payload = "%d.%s" % (timestamp, payload) expected_sig = cls._compute_signature(signed_payload, signing_key) - valid = any(hmac.compare_digest(expected_sig, s) for s in signatures) + try: + valid = any(hmac.compare_digest(expected_sig, s) for s in signatures) + except TypeError: + # e.g. a signature containing non-ASCII characters. + return WebhookSignature(valid=False, timestamp=None) + return WebhookSignature( - timestamp=datetime.fromtimestamp(timestamp, UTC), + timestamp=parsed_timestamp, valid=valid, ) diff --git a/tests/test_webhook.py b/tests/test_webhook.py index 77a4ea7..2a38ed1 100644 --- a/tests/test_webhook.py +++ b/tests/test_webhook.py @@ -269,3 +269,36 @@ def test_action_execute(self): }, ), ) + + +class TestMalformedSignatureHeaders: + @pytest.mark.parametrize( + "header", + [ + "t=253402300800,v1=00", # start of year 10000 + "t=" + "1" + "0" * 30 + ",v1=00", # overflows time_t + "t=-99999999999,v1=00", # before year 1 + "t=1699291314,v1=é", # non-ASCII signature + ], + ) + def test_parse_signature_header_is_invalid(self, header): + signature = Webhook.parse_signature_header( + payload="{}", header=header, signing_key=WEBHOOK_KEY + ) + assert not signature.valid + assert signature.timestamp is None + + @pytest.mark.parametrize( + "header", + [ + "t=253402300800,v1=00", + "t=" + "1" + "0" * 30 + ",v1=00", + "t=-99999999999,v1=00", + "t=1699291314,v1=é", + ], + ) + def test_parse_event_raises_signature_error(self, header): + with pytest.raises(SignatureVerificationError): + Webhook.parse_event( + payload="{}", signature_header=header, signing_key=WEBHOOK_KEY + )