cm-email-webhook-verification 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ from typing import Any
2
+
3
+ from cm_email_webhook_verification.exceptions import (
4
+ InvalidSignatureError,
5
+ MissingHeaderError,
6
+ TimestampExpiredError,
7
+ WebhookVerificationError,
8
+ )
9
+ from cm_email_webhook_verification.validator import WebhookValidator
10
+
11
+ __version__ = "1.0.0"
12
+ __all__ = [
13
+ "verify",
14
+ "WebhookValidator",
15
+ "WebhookVerificationError",
16
+ "InvalidSignatureError",
17
+ "TimestampExpiredError",
18
+ "MissingHeaderError",
19
+ ]
20
+
21
+
22
+ def verify(secret_key: str, payload: str, headers: dict[str, str]) -> Any:
23
+ return WebhookValidator(secret_key).verify(payload, headers)
@@ -0,0 +1,14 @@
1
+ class WebhookVerificationError(Exception):
2
+ pass
3
+
4
+
5
+ class InvalidSignatureError(WebhookVerificationError):
6
+ pass
7
+
8
+
9
+ class TimestampExpiredError(WebhookVerificationError):
10
+ pass
11
+
12
+
13
+ class MissingHeaderError(WebhookVerificationError):
14
+ pass
@@ -0,0 +1,11 @@
1
+ import base64
2
+ import hashlib
3
+ import hmac
4
+
5
+
6
+ def generate_signature(secret: str, payload: str) -> str:
7
+ key_bytes = secret.encode("utf-8")
8
+ payload_bytes = payload.encode("utf-8")
9
+
10
+ signature = hmac.new(key_bytes, payload_bytes, hashlib.sha512)
11
+ return base64.b64encode(signature.digest()).decode("utf-8")
@@ -0,0 +1,69 @@
1
+ import hmac
2
+ import json
3
+ import time
4
+ from typing import Any
5
+
6
+ from cm_email_webhook_verification.exceptions import (
7
+ InvalidSignatureError,
8
+ MissingHeaderError,
9
+ TimestampExpiredError,
10
+ )
11
+ from cm_email_webhook_verification.signer import generate_signature
12
+
13
+
14
+ class WebhookValidator:
15
+ HEADER_ID = "svix-id"
16
+ HEADER_TIMESTAMP = "svix-timestamp"
17
+ HEADER_SIGNATURE = "svix-signature"
18
+
19
+ def __init__(self, secret_key: str, tolerance_in_seconds: int = 300) -> None:
20
+ if not secret_key or not secret_key.strip():
21
+ raise ValueError("secret_key cannot be empty")
22
+
23
+ self._secret_key = secret_key
24
+ self._tolerance_ms = tolerance_in_seconds * 1000
25
+
26
+ def verify(self, payload: str, headers: dict[str, str]) -> Any:
27
+ if not payload or not payload.strip():
28
+ raise ValueError("payload cannot be empty")
29
+
30
+ if headers is None:
31
+ raise ValueError("headers cannot be None")
32
+
33
+ message_id = headers.get(self.HEADER_ID)
34
+ timestamp_str = headers.get(self.HEADER_TIMESTAMP)
35
+ signature = headers.get(self.HEADER_SIGNATURE)
36
+
37
+ if not message_id or not timestamp_str or not signature:
38
+ missing = []
39
+ if not message_id:
40
+ missing.append(self.HEADER_ID)
41
+ if not timestamp_str:
42
+ missing.append(self.HEADER_TIMESTAMP)
43
+ if not signature:
44
+ missing.append(self.HEADER_SIGNATURE)
45
+ raise MissingHeaderError(f"Missing required headers: {', '.join(missing)}")
46
+
47
+ try:
48
+ timestamp_ms = int(timestamp_str)
49
+ except ValueError as e:
50
+ raise ValueError("Invalid timestamp format") from e
51
+
52
+ self._validate_timestamp(timestamp_ms)
53
+
54
+ signature_payload = f"{message_id}.{timestamp_ms}.{payload}"
55
+ expected_signature = generate_signature(self._secret_key, signature_payload)
56
+
57
+ if not hmac.compare_digest(signature, expected_signature):
58
+ raise InvalidSignatureError("Invalid signature")
59
+
60
+ return json.loads(payload)
61
+
62
+ def _validate_timestamp(self, timestamp_ms: int) -> None:
63
+ current_time_ms = int(time.time() * 1000)
64
+ difference = abs(current_time_ms - timestamp_ms)
65
+
66
+ if difference > self._tolerance_ms:
67
+ raise TimestampExpiredError(
68
+ "Webhook timestamp is outside the allowed tolerance window"
69
+ )
@@ -0,0 +1,140 @@
1
+ Metadata-Version: 2.4
2
+ Name: cm-email-webhook-verification
3
+ Version: 1.0.0
4
+ Summary: SDK for verifying CM Email webhook signatures
5
+ Author: email-team
6
+ License: MIT
7
+ Project-URL: Documentation, https://github.com/cmdotcom/email-webhook-verification-sdks#readme
8
+ Project-URL: Repository, https://github.com/cmdotcom/email-webhook-verification-sdks
9
+ Keywords: webhook,verification,hmac,signature,cm,email
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Security :: Cryptography
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=7.0; extra == "dev"
26
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
27
+ Requires-Dist: mypy>=1.0; extra == "dev"
28
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # CM Email Webhook Verification SDK (Python)
32
+
33
+ SDK for verifying the authenticity of webhooks sent by CM Email services.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install cm-email-webhook-verification
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ ```python
44
+ from cm_email_webhook_verification import WebhookValidator, WebhookVerificationError
45
+
46
+ # Initialize with your webhook secret key
47
+ validator = WebhookValidator("your-secret-key")
48
+
49
+ # Extract headers and payload from incoming request
50
+ headers = {
51
+ "svix-id": request.headers["svix-id"],
52
+ "svix-timestamp": request.headers["svix-timestamp"],
53
+ "svix-signature": request.headers["svix-signature"],
54
+ }
55
+ payload = request.body.decode("utf-8")
56
+
57
+ try:
58
+ data = validator.verify(payload, headers)
59
+ # Process verified webhook data
60
+ print(f"Received event: {data}")
61
+ except WebhookVerificationError as e:
62
+ # Handle verification failure
63
+ print(f"Webhook verification failed: {e}")
64
+ ```
65
+
66
+ ## Flask Example
67
+
68
+ ```python
69
+ from flask import Flask, request, jsonify
70
+ from cm_email_webhook_verification import WebhookValidator, WebhookVerificationError
71
+
72
+ app = Flask(__name__)
73
+ validator = WebhookValidator("your-secret-key")
74
+
75
+ @app.route("/webhook", methods=["POST"])
76
+ def webhook():
77
+ headers = {
78
+ "svix-id": request.headers.get("svix-id"),
79
+ "svix-timestamp": request.headers.get("svix-timestamp"),
80
+ "svix-signature": request.headers.get("svix-signature"),
81
+ }
82
+ payload = request.get_data(as_text=True)
83
+
84
+ try:
85
+ data = validator.verify(payload, headers)
86
+ return jsonify({"status": "ok"}), 200
87
+ except WebhookVerificationError:
88
+ return jsonify({"error": "Invalid webhook"}), 401
89
+ ```
90
+
91
+ ## FastAPI Example
92
+
93
+ ```python
94
+ from fastapi import FastAPI, Request, HTTPException
95
+ from cm_email_webhook_verification import WebhookValidator, WebhookVerificationError
96
+
97
+ app = FastAPI()
98
+ validator = WebhookValidator("your-secret-key")
99
+
100
+ @app.post("/webhook")
101
+ async def webhook(request: Request):
102
+ headers = {
103
+ "svix-id": request.headers.get("svix-id"),
104
+ "svix-timestamp": request.headers.get("svix-timestamp"),
105
+ "svix-signature": request.headers.get("svix-signature"),
106
+ }
107
+ payload = (await request.body()).decode("utf-8")
108
+
109
+ try:
110
+ data = validator.verify(payload, headers)
111
+ return {"status": "ok"}
112
+ except WebhookVerificationError:
113
+ raise HTTPException(status_code=401, detail="Invalid webhook")
114
+ ```
115
+
116
+ ## Custom Tolerance
117
+
118
+ By default, webhooks are valid for 5 minutes. You can customize this:
119
+
120
+ ```python
121
+ # Accept webhooks up to 10 minutes old
122
+ validator = WebhookValidator("your-secret-key", tolerance_in_seconds=600)
123
+ ```
124
+
125
+ ## Exceptions
126
+
127
+ | Exception | Description |
128
+ |-----------|-------------|
129
+ | `WebhookVerificationError` | Base exception for all verification errors |
130
+ | `InvalidSignatureError` | Signature does not match |
131
+ | `TimestampExpiredError` | Timestamp outside tolerance window |
132
+ | `MissingHeaderError` | Required headers missing |
133
+
134
+ ## Security
135
+
136
+ This SDK uses:
137
+ - **HMAC-SHA512** for signature generation
138
+ - **Constant-time comparison** to prevent timing attacks
139
+ - **Timestamp validation** to prevent replay attacks
140
+
@@ -0,0 +1,9 @@
1
+ cm_email_webhook_verification/__init__.py,sha256=W0gSf2AufxRoBnXl4sIA7l448IsqEueQa4BGW5DTb44,591
2
+ cm_email_webhook_verification/exceptions.py,sha256=nExmfRR__P9ODzgTbVFA90v7tmmPDFK70ZOwVlGF1MQ,247
3
+ cm_email_webhook_verification/signer.py,sha256=6MhOEk23zkK2bN3cUF_w8vrqhVJbqT_BzcKTHwgCcxU,316
4
+ cm_email_webhook_verification/validator.py,sha256=70uB8xRr0Zwl_Ge-AEYKrckmooZnmv5jXldGIOS-7-I,2405
5
+ cm_email_webhook_verification-1.0.0.dist-info/licenses/LICENSE,sha256=pTszkBQD8rzyUTf4JC1iC3p7yKrc1xDPdCnIONbeuyM,1063
6
+ cm_email_webhook_verification-1.0.0.dist-info/METADATA,sha256=9hVg6_W38Fh1c38sgDpTglR1RIAcXXTMO6u5fXwX_xA,4337
7
+ cm_email_webhook_verification-1.0.0.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
8
+ cm_email_webhook_verification-1.0.0.dist-info/top_level.txt,sha256=BxP-GPplUBGRu3S7Gkf0yNCATNbnGL_uut8eYfXmQWo,30
9
+ cm_email_webhook_verification-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 CM.com
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ cm_email_webhook_verification