|
| 1 | +from typing import Any, Dict, Union, Optional |
| 2 | +from sinch.domains.authentication.webhooks.v1.authentication_validation import ( |
| 3 | + validate_webhook_signature_with_nonce, |
| 4 | +) |
| 5 | +from sinch.domains.authentication.webhooks.v1.webhook_utils import ( |
| 6 | + parse_json, |
| 7 | + normalize_iso_timestamp, |
| 8 | +) |
| 9 | +from sinch.domains.conversation.webhooks.v1.events import ( |
| 10 | + ConversationWebhookEventBase, |
| 11 | + MessageDeliveryReceiptEvent, |
| 12 | + MessageInboundEvent, |
| 13 | + MessageSubmitEvent, |
| 14 | +) |
| 15 | + |
| 16 | + |
| 17 | +ConversationWebhookCallback = Union[ |
| 18 | + MessageDeliveryReceiptEvent, |
| 19 | + MessageInboundEvent, |
| 20 | + MessageSubmitEvent, |
| 21 | + ConversationWebhookEventBase, |
| 22 | +] |
| 23 | + |
| 24 | + |
| 25 | +class ConversationWebhooks: |
| 26 | + """ |
| 27 | + Handler for Conversation API webhooks: validate signature and parse events. |
| 28 | + """ |
| 29 | + |
| 30 | + def __init__(self, webhook_secret: Optional[str] = None): |
| 31 | + """ |
| 32 | + :param webhook_secret: Secret configured for the webhook (used for HMAC validation). |
| 33 | + """ |
| 34 | + self.webhook_secret = webhook_secret |
| 35 | + |
| 36 | + def validate_signature( |
| 37 | + self, |
| 38 | + payload: Union[str, bytes], |
| 39 | + headers: Dict[str, str], |
| 40 | + webhook_secret: Optional[str] = None, |
| 41 | + ) -> bool: |
| 42 | + """ |
| 43 | + Validate the webhook signature using the request body and headers. |
| 44 | +
|
| 45 | + Uses x-sinch-webhook-signature, x-sinch-webhook-signature-nonce, and |
| 46 | + x-sinch-webhook-signature-timestamp. Returns True only if the signature |
| 47 | + is valid. |
| 48 | +
|
| 49 | + :param payload: Raw request body (string or bytes). |
| 50 | + :param headers: Incoming request headers (key case is normalized to lower). |
| 51 | + :param webhook_secret: Secret for this webhook; defaults to the secret passed to __init__. |
| 52 | + :returns: True if the signature is valid, False otherwise. |
| 53 | + """ |
| 54 | + secret = ( |
| 55 | + webhook_secret |
| 56 | + if webhook_secret is not None |
| 57 | + else self.webhook_secret |
| 58 | + ) |
| 59 | + if not secret: |
| 60 | + return False |
| 61 | + if isinstance(payload, bytes): |
| 62 | + payload = payload.decode("utf-8") |
| 63 | + return validate_webhook_signature_with_nonce(secret, headers, payload) |
| 64 | + |
| 65 | + def validate_authentication_header( |
| 66 | + self, headers: Dict[str, str], json_payload: str |
| 67 | + ) -> bool: |
| 68 | + """ |
| 69 | + Validate the webhook signature (convenience alias for validate_signature). |
| 70 | +
|
| 71 | + :param headers: Incoming request's headers. |
| 72 | + :param json_payload: Incoming request's raw body. |
| 73 | + :returns: True if the X-Sinch-Webhook-Signature header is valid. |
| 74 | + """ |
| 75 | + return self.validate_signature(json_payload, headers) |
| 76 | + |
| 77 | + def parse_event( |
| 78 | + self, event_body: Union[str, Dict[str, Any]] |
| 79 | + ) -> ConversationWebhookCallback: |
| 80 | + """ |
| 81 | + Parse the webhook payload into a typed event. |
| 82 | +
|
| 83 | + Parses by key: message_delivery_report → MessageDeliveryReceiptEvent, |
| 84 | + message → MessageInboundEvent, message_submit_notification → MessageSubmitEvent. |
| 85 | + Normalizes accepted_time and event_time. Injects trigger on the returned event. |
| 86 | +
|
| 87 | + :param event_body: JSON string or dict of the webhook body. |
| 88 | + :returns: Parsed event model. |
| 89 | + :raises ValueError: If JSON parsing fails or the payload is invalid. |
| 90 | + """ |
| 91 | + if isinstance(event_body, str): |
| 92 | + event_body = parse_json(event_body) |
| 93 | + |
| 94 | + # Normalize timestamp fields |
| 95 | + for key in ("accepted_time", "event_time"): |
| 96 | + if key in event_body and isinstance(event_body[key], str): |
| 97 | + event_body[key] = normalize_iso_timestamp(event_body[key]) |
| 98 | + |
| 99 | + # Type is determined by which key is present (message_delivery_report, message, |
| 100 | + # message_submit_notification). Inject trigger so callers can use event.trigger. |
| 101 | + trigger = event_body.get("trigger") |
| 102 | + if not trigger and "message_delivery_report" in event_body: |
| 103 | + trigger = "MESSAGE_DELIVERY" |
| 104 | + if not trigger and "message" in event_body: |
| 105 | + trigger = "MESSAGE_INBOUND" |
| 106 | + if not trigger and "message_submit_notification" in event_body: |
| 107 | + trigger = "MESSAGE_SUBMIT" |
| 108 | + |
| 109 | + if trigger == "MESSAGE_DELIVERY": |
| 110 | + event_body = {**event_body, "trigger": "MESSAGE_DELIVERY"} |
| 111 | + return MessageDeliveryReceiptEvent(**event_body) |
| 112 | + if trigger == "MESSAGE_INBOUND": |
| 113 | + event_body = {**event_body, "trigger": "MESSAGE_INBOUND"} |
| 114 | + return MessageInboundEvent(**event_body) |
| 115 | + if trigger == "MESSAGE_SUBMIT": |
| 116 | + event_body = {**event_body, "trigger": "MESSAGE_SUBMIT"} |
| 117 | + return MessageSubmitEvent(**event_body) |
| 118 | + |
| 119 | + return ConversationWebhookEventBase(**event_body) |
0 commit comments