Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/sendgrid/helpers/eventwebhook/__init__.py: 62%
14 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1from ellipticcurve.ecdsa import Ecdsa
2from ellipticcurve.publicKey import PublicKey
3from ellipticcurve.signature import Signature
5from .eventwebhook_header import EventWebhookHeader
7class EventWebhook:
8 """
9 This class allows you to use the Event Webhook feature. Read the docs for
10 more details: https://sendgrid.com/docs/for-developers/tracking-events/event
11 """
13 def __init__(self, public_key=None):
14 """
15 Construct the Event Webhook verifier object
16 :param public_key: verification key under Mail Settings
17 :type public_key: string
18 """
19 self.public_key = self.convert_public_key_to_ecdsa(public_key) if public_key else public_key
21 def convert_public_key_to_ecdsa(self, public_key):
22 """
23 Convert the public key string to a ECPublicKey.
25 :param public_key: verification key under Mail Settings
26 :type public_key string
27 :return: public key using the ECDSA algorithm
28 :rtype PublicKey
29 """
30 return PublicKey.fromPem('\n-----BEGIN PUBLIC KEY-----\n'+public_key+'\n-----END PUBLIC KEY-----\n')
32 def verify_signature(self, payload, signature, timestamp, public_key=None):
33 """
34 Verify signed event webhook requests.
36 :param payload: event payload in the request body
37 :type payload: string
38 :param signature: value obtained from the 'X-Twilio-Email-Event-Webhook-Signature' header
39 :type signature: string
40 :param timestamp: value obtained from the 'X-Twilio-Email-Event-Webhook-Timestamp' header
41 :type timestamp: string
42 :param public_key: elliptic curve public key
43 :type public_key: PublicKey
44 :return: true or false if signature is valid
45 """
46 timestamped_payload = timestamp + payload
47 decoded_signature = Signature.fromBase64(signature)
49 key = public_key or self.public_key
50 return Ecdsa.verify(timestamped_payload, decoded_signature, key)