cm-email-webhook-verification 1.0.0__tar.gz

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,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,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,110 @@
1
+ # CM Email Webhook Verification SDK (Python)
2
+
3
+ SDK for verifying the authenticity of webhooks sent by CM Email services.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install cm-email-webhook-verification
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```python
14
+ from cm_email_webhook_verification import WebhookValidator, WebhookVerificationError
15
+
16
+ # Initialize with your webhook secret key
17
+ validator = WebhookValidator("your-secret-key")
18
+
19
+ # Extract headers and payload from incoming request
20
+ headers = {
21
+ "svix-id": request.headers["svix-id"],
22
+ "svix-timestamp": request.headers["svix-timestamp"],
23
+ "svix-signature": request.headers["svix-signature"],
24
+ }
25
+ payload = request.body.decode("utf-8")
26
+
27
+ try:
28
+ data = validator.verify(payload, headers)
29
+ # Process verified webhook data
30
+ print(f"Received event: {data}")
31
+ except WebhookVerificationError as e:
32
+ # Handle verification failure
33
+ print(f"Webhook verification failed: {e}")
34
+ ```
35
+
36
+ ## Flask Example
37
+
38
+ ```python
39
+ from flask import Flask, request, jsonify
40
+ from cm_email_webhook_verification import WebhookValidator, WebhookVerificationError
41
+
42
+ app = Flask(__name__)
43
+ validator = WebhookValidator("your-secret-key")
44
+
45
+ @app.route("/webhook", methods=["POST"])
46
+ def webhook():
47
+ headers = {
48
+ "svix-id": request.headers.get("svix-id"),
49
+ "svix-timestamp": request.headers.get("svix-timestamp"),
50
+ "svix-signature": request.headers.get("svix-signature"),
51
+ }
52
+ payload = request.get_data(as_text=True)
53
+
54
+ try:
55
+ data = validator.verify(payload, headers)
56
+ return jsonify({"status": "ok"}), 200
57
+ except WebhookVerificationError:
58
+ return jsonify({"error": "Invalid webhook"}), 401
59
+ ```
60
+
61
+ ## FastAPI Example
62
+
63
+ ```python
64
+ from fastapi import FastAPI, Request, HTTPException
65
+ from cm_email_webhook_verification import WebhookValidator, WebhookVerificationError
66
+
67
+ app = FastAPI()
68
+ validator = WebhookValidator("your-secret-key")
69
+
70
+ @app.post("/webhook")
71
+ async def webhook(request: Request):
72
+ headers = {
73
+ "svix-id": request.headers.get("svix-id"),
74
+ "svix-timestamp": request.headers.get("svix-timestamp"),
75
+ "svix-signature": request.headers.get("svix-signature"),
76
+ }
77
+ payload = (await request.body()).decode("utf-8")
78
+
79
+ try:
80
+ data = validator.verify(payload, headers)
81
+ return {"status": "ok"}
82
+ except WebhookVerificationError:
83
+ raise HTTPException(status_code=401, detail="Invalid webhook")
84
+ ```
85
+
86
+ ## Custom Tolerance
87
+
88
+ By default, webhooks are valid for 5 minutes. You can customize this:
89
+
90
+ ```python
91
+ # Accept webhooks up to 10 minutes old
92
+ validator = WebhookValidator("your-secret-key", tolerance_in_seconds=600)
93
+ ```
94
+
95
+ ## Exceptions
96
+
97
+ | Exception | Description |
98
+ |-----------|-------------|
99
+ | `WebhookVerificationError` | Base exception for all verification errors |
100
+ | `InvalidSignatureError` | Signature does not match |
101
+ | `TimestampExpiredError` | Timestamp outside tolerance window |
102
+ | `MissingHeaderError` | Required headers missing |
103
+
104
+ ## Security
105
+
106
+ This SDK uses:
107
+ - **HMAC-SHA512** for signature generation
108
+ - **Constant-time comparison** to prevent timing attacks
109
+ - **Timestamp validation** to prevent replay attacks
110
+
@@ -0,0 +1,60 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "cm-email-webhook-verification"
7
+ version = "1.0.0"
8
+ description = "SDK for verifying CM Email webhook signatures"
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.9"
12
+ authors = [ {name = "email-team"} ]
13
+ classifiers = [
14
+ "Development Status :: 5 - Production/Stable",
15
+ "Intended Audience :: Developers",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.9",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Security :: Cryptography",
24
+ "Typing :: Typed",
25
+ ]
26
+
27
+ keywords = ["webhook", "verification", "hmac", "signature", "cm", "email"]
28
+ dependencies = []
29
+
30
+ [project.urls]
31
+ Documentation = "https://github.com/cmdotcom/email-webhook-verification-sdks#readme"
32
+ Repository = "https://github.com/cmdotcom/email-webhook-verification-sdks"
33
+
34
+ [project.optional-dependencies]
35
+ dev = [
36
+ "pytest>=7.0",
37
+ "pytest-cov>=4.0",
38
+ "mypy>=1.0",
39
+ "ruff>=0.1.0",
40
+ ]
41
+
42
+ [tool.setuptools.packages.find]
43
+ where = ["src"]
44
+
45
+ [tool.pytest.ini_options]
46
+ testpaths = ["tests"]
47
+ pythonpath = ["src"]
48
+
49
+ [tool.mypy]
50
+ python_version = "3.9"
51
+ warn_return_any = true
52
+ warn_unused_configs = true
53
+ strict = true
54
+
55
+ [tool.ruff]
56
+ target-version = "py39"
57
+ line-length = 120
58
+
59
+ [tool.ruff.lint]
60
+ select = ["E", "F", "W", "I", "N", "UP", "B", "C4", "SIM"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/cm_email_webhook_verification/__init__.py
5
+ src/cm_email_webhook_verification/exceptions.py
6
+ src/cm_email_webhook_verification/signer.py
7
+ src/cm_email_webhook_verification/validator.py
8
+ src/cm_email_webhook_verification.egg-info/PKG-INFO
9
+ src/cm_email_webhook_verification.egg-info/SOURCES.txt
10
+ src/cm_email_webhook_verification.egg-info/dependency_links.txt
11
+ src/cm_email_webhook_verification.egg-info/requires.txt
12
+ src/cm_email_webhook_verification.egg-info/top_level.txt
13
+ tests/test_validator.py
@@ -0,0 +1,6 @@
1
+
2
+ [dev]
3
+ pytest>=7.0
4
+ pytest-cov>=4.0
5
+ mypy>=1.0
6
+ ruff>=0.1.0
@@ -0,0 +1,177 @@
1
+ import json
2
+ import time
3
+
4
+ import pytest
5
+
6
+ from cm_email_webhook_verification import (
7
+ InvalidSignatureError,
8
+ MissingHeaderError,
9
+ TimestampExpiredError,
10
+ WebhookValidator,
11
+ )
12
+ from cm_email_webhook_verification.signer import generate_signature
13
+
14
+
15
+ class TestWebhookValidator:
16
+
17
+ def setup_method(self) -> None:
18
+ self.secret_key = "test-secret-key"
19
+ self.validator = WebhookValidator(self.secret_key)
20
+
21
+ def _create_valid_headers(self, payload: str) -> dict[str, str]:
22
+ message_id = "msg-123"
23
+ timestamp_ms = int(time.time() * 1000)
24
+ signature_payload = f"{message_id}.{timestamp_ms}.{payload}"
25
+ signature = generate_signature(self.secret_key, signature_payload)
26
+
27
+ return {
28
+ "svix-id": message_id,
29
+ "svix-timestamp": str(timestamp_ms),
30
+ "svix-signature": signature,
31
+ }
32
+
33
+ def test_verify_valid_webhook(self) -> None:
34
+ payload = json.dumps({"event": "test", "data": {"id": 123}})
35
+ headers = self._create_valid_headers(payload)
36
+
37
+ result = self.validator.verify(payload, headers)
38
+
39
+ assert result["event"] == "test"
40
+ assert result["data"]["id"] == 123
41
+
42
+ def test_verify_invalid_signature(self) -> None:
43
+ payload = json.dumps({"event": "test"})
44
+ headers = self._create_valid_headers(payload)
45
+ headers["svix-signature"] = "invalid-signature"
46
+
47
+ with pytest.raises(InvalidSignatureError):
48
+ self.validator.verify(payload, headers)
49
+
50
+ def test_verify_missing_headers(self) -> None:
51
+ payload = json.dumps({"event": "test"})
52
+
53
+ with pytest.raises(MissingHeaderError):
54
+ self.validator.verify(payload, {})
55
+
56
+ def test_verify_missing_single_header(self) -> None:
57
+ payload = json.dumps({"event": "test"})
58
+ headers = self._create_valid_headers(payload)
59
+ del headers["svix-id"]
60
+
61
+ with pytest.raises(MissingHeaderError) as exc_info:
62
+ self.validator.verify(payload, headers)
63
+
64
+ assert "svix-id" in str(exc_info.value)
65
+
66
+ def test_verify_expired_timestamp(self) -> None:
67
+ payload = json.dumps({"event": "test"})
68
+ message_id = "msg-123"
69
+ # Timestamp from 10 minutes ago
70
+ timestamp_ms = int((time.time() - 600) * 1000)
71
+ signature_payload = f"{message_id}.{timestamp_ms}.{payload}"
72
+ signature = generate_signature(self.secret_key, signature_payload)
73
+
74
+ headers = {
75
+ "svix-id": message_id,
76
+ "svix-timestamp": str(timestamp_ms),
77
+ "svix-signature": signature,
78
+ }
79
+
80
+ with pytest.raises(TimestampExpiredError):
81
+ self.validator.verify(payload, headers)
82
+
83
+ def test_verify_future_timestamp_within_tolerance(self) -> None:
84
+ payload = json.dumps({"event": "test"})
85
+ message_id = "msg-123"
86
+ # Timestamp 1 minute in the future
87
+ timestamp_ms = int((time.time() + 60) * 1000)
88
+ signature_payload = f"{message_id}.{timestamp_ms}.{payload}"
89
+ signature = generate_signature(self.secret_key, signature_payload)
90
+
91
+ headers = {
92
+ "svix-id": message_id,
93
+ "svix-timestamp": str(timestamp_ms),
94
+ "svix-signature": signature,
95
+ }
96
+
97
+ result = self.validator.verify(payload, headers)
98
+ assert result["event"] == "test"
99
+
100
+ def test_verify_empty_payload(self) -> None:
101
+ headers = {"svix-id": "123", "svix-timestamp": "123", "svix-signature": "sig"}
102
+
103
+ with pytest.raises(ValueError):
104
+ self.validator.verify("", headers)
105
+
106
+ def test_verify_none_headers(self) -> None:
107
+ with pytest.raises(ValueError):
108
+ self.validator.verify('{"event": "test"}', None) # type: ignore
109
+
110
+ def test_constructor_empty_secret(self) -> None:
111
+ with pytest.raises(ValueError):
112
+ WebhookValidator("")
113
+
114
+ def test_constructor_whitespace_secret(self) -> None:
115
+ with pytest.raises(ValueError):
116
+ WebhookValidator(" ")
117
+
118
+ def test_custom_tolerance(self) -> None:
119
+ # Create validator with 1 second tolerance
120
+ validator = WebhookValidator(self.secret_key, tolerance_in_seconds=1)
121
+
122
+ payload = json.dumps({"event": "test"})
123
+ message_id = "msg-123"
124
+ # Timestamp from 5 seconds ago
125
+ timestamp_ms = int((time.time() - 5) * 1000)
126
+ signature_payload = f"{message_id}.{timestamp_ms}.{payload}"
127
+ signature = generate_signature(self.secret_key, signature_payload)
128
+
129
+ headers = {
130
+ "svix-id": message_id,
131
+ "svix-timestamp": str(timestamp_ms),
132
+ "svix-signature": signature,
133
+ }
134
+
135
+ with pytest.raises(TimestampExpiredError):
136
+ validator.verify(payload, headers)
137
+
138
+ def test_invalid_timestamp_format(self) -> None:
139
+ payload = json.dumps({"event": "test"})
140
+ headers = {
141
+ "svix-id": "msg-123",
142
+ "svix-timestamp": "not-a-number",
143
+ "svix-signature": "signature",
144
+ }
145
+
146
+ with pytest.raises(ValueError) as exc_info:
147
+ self.validator.verify(payload, headers)
148
+
149
+ assert "timestamp" in str(exc_info.value).lower()
150
+
151
+
152
+ class TestGenerateSignature:
153
+
154
+ def test_generate_signature_deterministic(self) -> None:
155
+ secret = "test-secret"
156
+ payload = "test-payload"
157
+
158
+ sig1 = generate_signature(secret, payload)
159
+ sig2 = generate_signature(secret, payload)
160
+
161
+ assert sig1 == sig2
162
+
163
+ def test_generate_signature_different_secrets(self) -> None:
164
+ payload = "test-payload"
165
+
166
+ sig1 = generate_signature("secret1", payload)
167
+ sig2 = generate_signature("secret2", payload)
168
+
169
+ assert sig1 != sig2
170
+
171
+ def test_generate_signature_different_payloads(self) -> None:
172
+ secret = "test-secret"
173
+
174
+ sig1 = generate_signature(secret, "payload1")
175
+ sig2 = generate_signature(secret, "payload2")
176
+
177
+ assert sig1 != sig2