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
11 changes: 9 additions & 2 deletions src/gradient_labs/webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)

Expand Down
33 changes: 33 additions & 0 deletions tests/test_webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Loading