Skip to content
Merged
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
22 changes: 15 additions & 7 deletions src/openai/lib/_webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import hmac
import time
import base64
import codecs
import hashlib

from .._types import HeadersLike
Expand Down Expand Up @@ -55,13 +56,20 @@ def webhook_signature_matches(
if not decoded_secret:
raise ValueError("The webhook secret must not be empty after decoding")

body = payload.decode("utf-8") if isinstance(payload, bytes) else payload

# Prepare the signed payload (OpenAI uses webhookId.timestamp.payload format)
signed_payload = f"{webhook_id}.{timestamp}.{body}"
expected_signature = base64.b64encode(
hmac.new(decoded_secret, signed_payload.encode(), hashlib.sha256).digest()
).decode()
mac = hmac.new(decoded_secret, f"{webhook_id}.{timestamp}.".encode(), hashlib.sha256)
chunk_size = 64 * 1024
if isinstance(payload, bytes):
# Validate UTF-8 across chunk boundaries while signing the original bytes.
decoder = codecs.getincrementaldecoder("utf-8")()
for start in range(0, len(payload), chunk_size):
chunk = payload[start : start + chunk_size]
decoder.decode(chunk)
mac.update(chunk)
decoder.decode(b"", final=True)
else:
for start in range(0, len(payload), chunk_size):
mac.update(payload[start : start + chunk_size].encode())
expected_signature = base64.b64encode(mac.digest()).decode()

# Accept if any signature matches
return any(hmac.compare_digest(expected_signature, sig) for sig in signatures)
21 changes: 19 additions & 2 deletions tests/lib/test_webhook_signature.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import base64
import hashlib
import binascii
import tracemalloc
from typing import Iterator, cast
from unittest import mock

Expand Down Expand Up @@ -180,9 +181,25 @@ def test_malformed_secret_keeps_base64_error(webhook_resource: Webhooks | AsyncW
webhook_resource.verify_signature(PAYLOAD, signed_headers(), secret="whsec_a")


def test_invalid_utf8_payload_keeps_decode_error(webhook_resource: Webhooks | AsyncWebhooks) -> None:
@pytest.mark.parametrize("payload", [b"\xff", b"\xc3"])
def test_invalid_utf8_payload_keeps_decode_error(webhook_resource: Webhooks | AsyncWebhooks, payload: bytes) -> None:
with pytest.raises(UnicodeDecodeError):
webhook_resource.verify_signature(b"\xff", signed_headers(), secret=RAW_SECRET)
webhook_resource.verify_signature(payload, signed_headers(), secret=RAW_SECRET)


@pytest.mark.parametrize("as_bytes", [False, True], ids=["text", "bytes"])
def test_large_signature_without_full_body_copies(webhook_resource: Webhooks | AsyncWebhooks, as_bytes: bool) -> None:
# The leading ASCII byte splits a UTF-8 character across each even byte boundary.
text = "a" + "é" * (2 * 1024 * 1024)
payload = text.encode() if as_bytes else text
headers = signed_headers(payload)
tracemalloc.start()
try:
webhook_resource.verify_signature(payload, headers, secret=RAW_SECRET)
_, peak = tracemalloc.get_traced_memory()
finally:
tracemalloc.stop()
assert peak < len(payload)


def test_non_ascii_signature_keeps_compare_error(webhook_resource: Webhooks | AsyncWebhooks) -> None:
Expand Down
Loading