webhookd-sdk 0.1.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.
- webhookd_sdk-0.1.0/.gitignore +25 -0
- webhookd_sdk-0.1.0/LICENSE +21 -0
- webhookd_sdk-0.1.0/PKG-INFO +82 -0
- webhookd_sdk-0.1.0/README.md +54 -0
- webhookd_sdk-0.1.0/pyproject.toml +53 -0
- webhookd_sdk-0.1.0/tests/test_client.py +86 -0
- webhookd_sdk-0.1.0/tests/test_e2e_webhookd.py +102 -0
- webhookd_sdk-0.1.0/tests/test_signature.py +72 -0
- webhookd_sdk-0.1.0/tests/test_vectors.py +35 -0
- webhookd_sdk-0.1.0/webhookd_sdk/__init__.py +24 -0
- webhookd_sdk-0.1.0/webhookd_sdk/client.py +147 -0
- webhookd_sdk-0.1.0/webhookd_sdk/errors.py +21 -0
- webhookd_sdk-0.1.0/webhookd_sdk/signature.py +81 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.egg-info/
|
|
5
|
+
build/
|
|
6
|
+
dist/
|
|
7
|
+
.venv/
|
|
8
|
+
venv/
|
|
9
|
+
.env
|
|
10
|
+
.pytest_cache/
|
|
11
|
+
.mypy_cache/
|
|
12
|
+
.ruff_cache/
|
|
13
|
+
.coverage
|
|
14
|
+
htmlcov/
|
|
15
|
+
|
|
16
|
+
# Node / TypeScript
|
|
17
|
+
node_modules/
|
|
18
|
+
typescript/dist/
|
|
19
|
+
*.tsbuildinfo
|
|
20
|
+
coverage/
|
|
21
|
+
|
|
22
|
+
# OS / editor
|
|
23
|
+
.DS_Store
|
|
24
|
+
.idea/
|
|
25
|
+
.vscode/
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 NimbusNexus
|
|
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,82 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: webhookd-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for NimbusNexus Webhooks — publish events + verify webhook signatures.
|
|
5
|
+
Project-URL: Homepage, https://github.com/NimbusNexus/Webhooks-sdks/tree/develop/python#readme
|
|
6
|
+
Project-URL: Repository, https://github.com/NimbusNexus/Webhooks-sdks
|
|
7
|
+
Project-URL: Issues, https://github.com/NimbusNexus/Webhooks-sdks/issues
|
|
8
|
+
Author: NimbusNexus
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: hmac,nimbusnexus,sdk,signature,verify,webhook,webhooks
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Requires-Dist: httpx>=0.27
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: mypy; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
26
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# webhookd-sdk (Python)
|
|
30
|
+
|
|
31
|
+
Official Python SDK for **NimbusNexus Webhooks** — publish events, and verify the webhooks you receive.
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
pip install webhookd-sdk
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Verify an incoming webhook (subscribers)
|
|
38
|
+
|
|
39
|
+
When webhookd delivers a webhook it signs the body with your endpoint's signing secret. **Always
|
|
40
|
+
verify the signature** before trusting the payload — it proves the request really came from webhookd
|
|
41
|
+
and wasn't tampered with or replayed.
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from webhookd_sdk import verify
|
|
45
|
+
|
|
46
|
+
# In your webhook handler — pass the RAW request body bytes (do not re-serialize the JSON):
|
|
47
|
+
ok = verify(
|
|
48
|
+
secret=ENDPOINT_SIGNING_SECRET,
|
|
49
|
+
raw_body=request.body,
|
|
50
|
+
signature=request.headers["X-Webhook-Signature"],
|
|
51
|
+
timestamp=request.headers["X-Webhook-Timestamp"],
|
|
52
|
+
)
|
|
53
|
+
if not ok:
|
|
54
|
+
return Response(status_code=400) # forged, tampered, or outside the 300s replay window
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Publish an event (producers)
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from webhookd_sdk import Client, WebhookdAPIError
|
|
61
|
+
|
|
62
|
+
with Client("https://webhooks.example.com", api_key="whsk_…") as wh:
|
|
63
|
+
try:
|
|
64
|
+
event = wh.publish(
|
|
65
|
+
"order.created",
|
|
66
|
+
{"order_id": "ord_123", "total": 4200},
|
|
67
|
+
idempotency_key="order-123", # makes the publish safe to retry
|
|
68
|
+
)
|
|
69
|
+
print(event.event_uid, event.deliveries_created)
|
|
70
|
+
except WebhookdAPIError as e:
|
|
71
|
+
print(e.status_code, e.code, e.message) # the stable {error:{code,message}} envelope
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Transient failures (connection errors, `429`, `5xx`) are retried with backoff (a `429` honours
|
|
75
|
+
`Retry-After`); other `4xx` raise `WebhookdAPIError`.
|
|
76
|
+
|
|
77
|
+
## Develop
|
|
78
|
+
|
|
79
|
+
```sh
|
|
80
|
+
pip install -e '.[dev]'
|
|
81
|
+
pytest && ruff check . && mypy webhookd_sdk
|
|
82
|
+
```
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# webhookd-sdk (Python)
|
|
2
|
+
|
|
3
|
+
Official Python SDK for **NimbusNexus Webhooks** — publish events, and verify the webhooks you receive.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install webhookd-sdk
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Verify an incoming webhook (subscribers)
|
|
10
|
+
|
|
11
|
+
When webhookd delivers a webhook it signs the body with your endpoint's signing secret. **Always
|
|
12
|
+
verify the signature** before trusting the payload — it proves the request really came from webhookd
|
|
13
|
+
and wasn't tampered with or replayed.
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from webhookd_sdk import verify
|
|
17
|
+
|
|
18
|
+
# In your webhook handler — pass the RAW request body bytes (do not re-serialize the JSON):
|
|
19
|
+
ok = verify(
|
|
20
|
+
secret=ENDPOINT_SIGNING_SECRET,
|
|
21
|
+
raw_body=request.body,
|
|
22
|
+
signature=request.headers["X-Webhook-Signature"],
|
|
23
|
+
timestamp=request.headers["X-Webhook-Timestamp"],
|
|
24
|
+
)
|
|
25
|
+
if not ok:
|
|
26
|
+
return Response(status_code=400) # forged, tampered, or outside the 300s replay window
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Publish an event (producers)
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from webhookd_sdk import Client, WebhookdAPIError
|
|
33
|
+
|
|
34
|
+
with Client("https://webhooks.example.com", api_key="whsk_…") as wh:
|
|
35
|
+
try:
|
|
36
|
+
event = wh.publish(
|
|
37
|
+
"order.created",
|
|
38
|
+
{"order_id": "ord_123", "total": 4200},
|
|
39
|
+
idempotency_key="order-123", # makes the publish safe to retry
|
|
40
|
+
)
|
|
41
|
+
print(event.event_uid, event.deliveries_created)
|
|
42
|
+
except WebhookdAPIError as e:
|
|
43
|
+
print(e.status_code, e.code, e.message) # the stable {error:{code,message}} envelope
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Transient failures (connection errors, `429`, `5xx`) are retried with backoff (a `429` honours
|
|
47
|
+
`Retry-After`); other `4xx` raise `WebhookdAPIError`.
|
|
48
|
+
|
|
49
|
+
## Develop
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
pip install -e '.[dev]'
|
|
53
|
+
pytest && ruff check . && mypy webhookd_sdk
|
|
54
|
+
```
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "webhookd-sdk"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Official Python SDK for NimbusNexus Webhooks — publish events + verify webhook signatures."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "NimbusNexus" }]
|
|
13
|
+
keywords = ["webhook", "webhooks", "hmac", "signature", "verify", "nimbusnexus", "sdk"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Topic :: Software Development :: Libraries",
|
|
24
|
+
]
|
|
25
|
+
dependencies = ["httpx>=0.27"]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://github.com/NimbusNexus/Webhooks-sdks/tree/develop/python#readme"
|
|
29
|
+
Repository = "https://github.com/NimbusNexus/Webhooks-sdks"
|
|
30
|
+
Issues = "https://github.com/NimbusNexus/Webhooks-sdks/issues"
|
|
31
|
+
|
|
32
|
+
[project.optional-dependencies]
|
|
33
|
+
dev = ["pytest", "ruff", "mypy"]
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.wheel]
|
|
36
|
+
packages = ["webhookd_sdk"]
|
|
37
|
+
|
|
38
|
+
[tool.pytest.ini_options]
|
|
39
|
+
testpaths = ["tests"]
|
|
40
|
+
addopts = "-q"
|
|
41
|
+
pythonpath = ["."]
|
|
42
|
+
|
|
43
|
+
[tool.ruff]
|
|
44
|
+
line-length = 100
|
|
45
|
+
target-version = "py311"
|
|
46
|
+
|
|
47
|
+
[tool.ruff.lint]
|
|
48
|
+
select = ["E", "F", "I", "W", "B", "UP"]
|
|
49
|
+
|
|
50
|
+
[tool.mypy]
|
|
51
|
+
python_version = "3.11"
|
|
52
|
+
warn_unused_ignores = true
|
|
53
|
+
ignore_missing_imports = true
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Publish client — exercised against an httpx MockTransport (no network)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
import pytest
|
|
9
|
+
|
|
10
|
+
from webhookd_sdk import Client, WebhookdAPIError
|
|
11
|
+
|
|
12
|
+
_OK = {
|
|
13
|
+
"id": "evt_db",
|
|
14
|
+
"event_uid": "u1",
|
|
15
|
+
"event_type": "order.created",
|
|
16
|
+
"application": "default",
|
|
17
|
+
"environment": "prod",
|
|
18
|
+
"deliveries_created": 2,
|
|
19
|
+
"source": None,
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _client(handler, **kw) -> Client:
|
|
24
|
+
return Client("https://wh.example.com", "whsk_x", transport=httpx.MockTransport(handler), **kw)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_publish_success_and_request_shape():
|
|
28
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
29
|
+
assert request.url.path == "/v1/events"
|
|
30
|
+
assert request.headers["Authorization"] == "Bearer whsk_x"
|
|
31
|
+
body = json.loads(request.content)
|
|
32
|
+
assert body["event_type"] == "order.created"
|
|
33
|
+
assert body["payload"] == {"id": 1} and body["environment"] == "prod"
|
|
34
|
+
return httpx.Response(201, json=_OK)
|
|
35
|
+
|
|
36
|
+
with _client(handler) as c:
|
|
37
|
+
ev = c.publish("order.created", {"id": 1})
|
|
38
|
+
assert ev.event_uid == "u1" and ev.deliveries_created == 2
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_idempotency_key_header():
|
|
42
|
+
seen: dict[str, str | None] = {}
|
|
43
|
+
|
|
44
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
45
|
+
seen["idem"] = request.headers.get("Idempotency-Key")
|
|
46
|
+
return httpx.Response(201, json=_OK)
|
|
47
|
+
|
|
48
|
+
with _client(handler) as c:
|
|
49
|
+
c.publish("order.created", {"id": 1}, idempotency_key="order-123")
|
|
50
|
+
assert seen["idem"] == "order-123"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_api_error_carries_envelope():
|
|
54
|
+
def handler(_request: httpx.Request) -> httpx.Response:
|
|
55
|
+
return httpx.Response(422, json={"error": {"code": "validation_error", "message": "bad"}})
|
|
56
|
+
|
|
57
|
+
with _client(handler) as c, pytest.raises(WebhookdAPIError) as ei:
|
|
58
|
+
c.publish("order.created", {})
|
|
59
|
+
assert ei.value.status_code == 422 and ei.value.code == "validation_error"
|
|
60
|
+
assert ei.value.message == "bad"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_retries_on_503_then_succeeds():
|
|
64
|
+
calls = {"n": 0}
|
|
65
|
+
|
|
66
|
+
def handler(_request: httpx.Request) -> httpx.Response:
|
|
67
|
+
calls["n"] += 1
|
|
68
|
+
if calls["n"] == 1:
|
|
69
|
+
return httpx.Response(503, json={"error": {"code": "unavailable", "message": "x"}})
|
|
70
|
+
return httpx.Response(201, json=_OK)
|
|
71
|
+
|
|
72
|
+
with _client(handler, max_retries=2) as c:
|
|
73
|
+
ev = c.publish("order.created", {})
|
|
74
|
+
assert calls["n"] == 2 and ev.event_uid == "u1"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def test_does_not_retry_4xx():
|
|
78
|
+
calls = {"n": 0}
|
|
79
|
+
|
|
80
|
+
def handler(_request: httpx.Request) -> httpx.Response:
|
|
81
|
+
calls["n"] += 1
|
|
82
|
+
return httpx.Response(404, json={"error": {"code": "not_found", "message": "no app"}})
|
|
83
|
+
|
|
84
|
+
with _client(handler, max_retries=2) as c, pytest.raises(WebhookdAPIError):
|
|
85
|
+
c.publish("order.created", {})
|
|
86
|
+
assert calls["n"] == 1 # a 404 is terminal — not retried
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""End-to-end: the SDK ``Client`` publishing against a REAL in-process webhookd, driven through
|
|
2
|
+
FastAPI's ``TestClient`` ASGI bridge (no network, no server). This goes beyond the mocked-transport
|
|
3
|
+
unit tests — it proves the client authenticates and shapes ``POST /v1/events`` correctly and parses
|
|
4
|
+
webhookd's real ``EventOut`` (incl. fan-out counting + idempotent replay).
|
|
5
|
+
|
|
6
|
+
webhookd is NOT a PyPI package, so this is SKIPPED unless it's importable — it runs locally (or in a
|
|
7
|
+
combined lane where webhookd is on the path), not in the pure-SDK CI. The signature *verify* path is
|
|
8
|
+
covered independently by the server-generated vector fixture (``test_vectors.py``) + the live
|
|
9
|
+
delivery-core parity check (``test_signature.py``).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import base64
|
|
15
|
+
import os
|
|
16
|
+
import tempfile
|
|
17
|
+
|
|
18
|
+
import httpx
|
|
19
|
+
import pytest
|
|
20
|
+
|
|
21
|
+
# webhookd reads its Settings (and builds its engine) at import time, so configure BEFORE importing
|
|
22
|
+
# it — mirrors webhookd's own conftest. A file-backed sqlite (not :memory:) so every connection sees
|
|
23
|
+
# the same DB; a 32-byte test KEK so endpoint-secret envelope encryption works offline.
|
|
24
|
+
_DB = os.path.join(tempfile.gettempdir(), "sdk_e2e_webhookd.db")
|
|
25
|
+
os.environ.setdefault("WEBHOOKD_DATABASE_URL", f"sqlite:///{_DB}")
|
|
26
|
+
os.environ.setdefault("WEBHOOKD_SERVICE_TOKEN", "e2e-token")
|
|
27
|
+
os.environ.setdefault(
|
|
28
|
+
"WEBHOOKD_KEK", base64.urlsafe_b64encode(b"webhookd-e2e-kek-0123456789abcde").decode()
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
pytest.importorskip(
|
|
32
|
+
"webhookd", reason="webhookd not installed — e2e runs only where it's available"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
import webhookd.models # noqa: E402,F401 — register tables on Base.metadata
|
|
36
|
+
from fastapi.testclient import TestClient # noqa: E402
|
|
37
|
+
from webhookd import service # noqa: E402
|
|
38
|
+
from webhookd.app import app # noqa: E402
|
|
39
|
+
from webhookd.db import Base, SessionLocal, engine # noqa: E402
|
|
40
|
+
|
|
41
|
+
from webhookd_sdk import Client # noqa: E402
|
|
42
|
+
|
|
43
|
+
BASE = "http://testserver" # httpx's ASGI convention
|
|
44
|
+
TOKEN = os.environ["WEBHOOKD_SERVICE_TOKEN"]
|
|
45
|
+
AUTH = {"Authorization": f"Bearer {TOKEN}"}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@pytest.fixture
|
|
49
|
+
def transport():
|
|
50
|
+
"""A fresh-DB sync transport bridged to the real webhookd ASGI app. Drop/create + seed the
|
|
51
|
+
default tenant per test (TestClient's lifespan also seeds idempotently), then hand the SDK its
|
|
52
|
+
own httpx transport so the SDK's sync Client can drive the real app in-process."""
|
|
53
|
+
Base.metadata.drop_all(bind=engine)
|
|
54
|
+
Base.metadata.create_all(bind=engine)
|
|
55
|
+
with SessionLocal() as s:
|
|
56
|
+
service.ensure_seed(s)
|
|
57
|
+
with TestClient(app) as tc: # keeps the ASGI bridge (portal) alive for the test body
|
|
58
|
+
yield tc._transport
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _register_endpoint(transport, event_type: str) -> None:
|
|
62
|
+
"""Register an endpoint subscribed EXACTLY to `event_type` via the real API, so each test's
|
|
63
|
+
fan-out count is independent of any other endpoints in the DB."""
|
|
64
|
+
with httpx.Client(base_url=BASE, transport=transport, headers=AUTH) as raw:
|
|
65
|
+
r = raw.post(
|
|
66
|
+
"/v1/endpoints",
|
|
67
|
+
json={
|
|
68
|
+
"url": "https://sub.example.com/hook",
|
|
69
|
+
"environment": "prod",
|
|
70
|
+
"subscriptions": [{"match_kind": "exact", "pattern": event_type}],
|
|
71
|
+
},
|
|
72
|
+
)
|
|
73
|
+
assert r.status_code == 201, r.text
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_sdk_publishes_against_real_webhookd(transport):
|
|
77
|
+
"""The SDK publishes a real event; webhookd persists it and returns a real EventOut."""
|
|
78
|
+
with Client(BASE, TOKEN, transport=transport) as c:
|
|
79
|
+
ev = c.publish("order.created", {"id": 1})
|
|
80
|
+
assert ev.event_uid and ev.event_type == "order.created"
|
|
81
|
+
assert ev.application == "default" and ev.environment == "prod"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_sdk_publish_fans_out_to_a_real_endpoint(transport):
|
|
85
|
+
"""With a matching endpoint registered (via the real API — endpoint mgmt isn't the SDK's job),
|
|
86
|
+
the SDK publish fans out to exactly it."""
|
|
87
|
+
_register_endpoint(transport, "e2e.fanout")
|
|
88
|
+
with Client(BASE, TOKEN, transport=transport) as c:
|
|
89
|
+
ev = c.publish("e2e.fanout", {"id": 2})
|
|
90
|
+
assert ev.deliveries_created == 1
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_sdk_idempotent_publish_replays_not_refans(transport):
|
|
94
|
+
"""A retried publish with the same Idempotency-Key returns the ORIGINAL event with no new
|
|
95
|
+
fan-out — the safety property the client's retries rely on."""
|
|
96
|
+
_register_endpoint(transport, "e2e.idem")
|
|
97
|
+
with Client(BASE, TOKEN, transport=transport) as c:
|
|
98
|
+
first = c.publish("e2e.idem", {"id": 3}, idempotency_key="dedupe-1")
|
|
99
|
+
again = c.publish("e2e.idem", {"id": 3}, idempotency_key="dedupe-1")
|
|
100
|
+
assert first.deliveries_created == 1
|
|
101
|
+
assert again.event_uid == first.event_uid
|
|
102
|
+
assert again.deliveries_created == 0 # replay: no re-fan-out
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Signature verification — the crown jewel. Includes an independent known-answer vector and a
|
|
2
|
+
byte-for-byte cross-check against the server's own signer (delivery-core) when it's importable."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import hashlib
|
|
7
|
+
import hmac
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from webhookd_sdk import sign, verify
|
|
12
|
+
|
|
13
|
+
SECRET = "whsec_test_value"
|
|
14
|
+
BODY = b'{"data":{"id":1},"id":"evt_1","type":"order.created","version":"1"}'
|
|
15
|
+
TS = 1_700_000_000
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def test_verify_known_vector():
|
|
19
|
+
# Independently construct the signed bytes (timestamp + "." + body) + HMAC — no SDK helper used.
|
|
20
|
+
expected = (
|
|
21
|
+
"sha256="
|
|
22
|
+
+ hmac.new(SECRET.encode(), f"{TS}.".encode("ascii") + BODY, hashlib.sha256).hexdigest()
|
|
23
|
+
)
|
|
24
|
+
assert verify(SECRET, BODY, expected, timestamp=TS, now=TS)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_sign_verify_roundtrip():
|
|
28
|
+
sig = sign(SECRET, BODY, TS)
|
|
29
|
+
assert sig.startswith("sha256=")
|
|
30
|
+
assert verify(SECRET, BODY, sig, timestamp=TS, now=TS)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_signature_prefix_is_optional():
|
|
34
|
+
bare = sign(SECRET, BODY, TS).removeprefix("sha256=")
|
|
35
|
+
assert verify(SECRET, BODY, bare, timestamp=TS, now=TS)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_rejects_tampered_body():
|
|
39
|
+
sig = sign(SECRET, BODY, TS)
|
|
40
|
+
assert not verify(SECRET, BODY + b" ", sig, timestamp=TS, now=TS)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_rejects_wrong_secret():
|
|
44
|
+
sig = sign(SECRET, BODY, TS)
|
|
45
|
+
assert not verify("whsec_other", BODY, sig, timestamp=TS, now=TS)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_rejects_stale_timestamp_replay():
|
|
49
|
+
sig = sign(SECRET, BODY, TS)
|
|
50
|
+
# 301s in the future of the signed timestamp -> outside the 300s window.
|
|
51
|
+
assert not verify(SECRET, BODY, sig, timestamp=TS, now=TS + 301)
|
|
52
|
+
assert verify(SECRET, BODY, sig, timestamp=TS, now=TS + 299)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_accepts_str_timestamp_header():
|
|
56
|
+
# Subscribers pass the raw X-Webhook-Timestamp header (a string) straight through.
|
|
57
|
+
sig = sign(SECRET, BODY, TS)
|
|
58
|
+
assert verify(SECRET, BODY, sig, timestamp=str(TS), now=TS)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def test_str_body_accepted():
|
|
62
|
+
sig = sign(SECRET, BODY.decode(), TS)
|
|
63
|
+
assert verify(SECRET, BODY.decode(), sig, timestamp=TS, now=TS)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_matches_delivery_core_server_signer():
|
|
67
|
+
# The real proof: a signature produced by the SERVER's signer must verify with the SDK.
|
|
68
|
+
server_sign = pytest.importorskip("delivery_core.webhook_outbox").sign
|
|
69
|
+
server_sig = server_sign(SECRET, BODY, TS)
|
|
70
|
+
assert verify(SECRET, BODY, server_sig, timestamp=TS, now=TS)
|
|
71
|
+
# ... and our sign matches theirs exactly.
|
|
72
|
+
assert sign(SECRET, BODY, TS) == server_sig
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Cross-implementation signing-contract check. Every signature in fixtures/signature-vectors.json
|
|
2
|
+
was produced by delivery-core — the SERVER's signer — so the SDK must reproduce AND verify each one.
|
|
3
|
+
This pins the Python SDK to the exact wire contract without importing delivery_core — the guarantee
|
|
4
|
+
holds even in a CI lane with no server installed (and the TS SDK checks the same file)."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import pathlib
|
|
10
|
+
|
|
11
|
+
import pytest
|
|
12
|
+
|
|
13
|
+
from webhookd_sdk import sign, verify
|
|
14
|
+
|
|
15
|
+
_FIXTURE = pathlib.Path(__file__).resolve().parents[2] / "fixtures" / "signature-vectors.json"
|
|
16
|
+
VECTORS = json.loads(_FIXTURE.read_text(encoding="utf-8"))["vectors"]
|
|
17
|
+
IDS = [v["name"] for v in VECTORS]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@pytest.mark.parametrize("v", VECTORS, ids=IDS)
|
|
21
|
+
def test_sdk_reproduces_server_signature(v):
|
|
22
|
+
"""sign() must produce the EXACT bytes the server produced (a divergence in encoding / the
|
|
23
|
+
'<ts>.' join / hex casing fails here, not silently in production)."""
|
|
24
|
+
assert sign(v["secret"], v["body"], v["timestamp"]) == v["signature"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@pytest.mark.parametrize("v", VECTORS, ids=IDS)
|
|
28
|
+
def test_sdk_verifies_server_signature(v):
|
|
29
|
+
ts = v["timestamp"]
|
|
30
|
+
assert verify(v["secret"], v["body"], v["signature"], timestamp=ts, now=ts)
|
|
31
|
+
# the bare hex (no 'sha256=' prefix) must also verify
|
|
32
|
+
bare = v["signature"].removeprefix("sha256=")
|
|
33
|
+
assert verify(v["secret"], v["body"], bare, timestamp=ts, now=ts)
|
|
34
|
+
# a one-byte tamper must be rejected
|
|
35
|
+
assert not verify(v["secret"], v["body"] + " ", v["signature"], timestamp=ts, now=ts)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""webhookd-sdk — the official Python client for NimbusNexus Webhooks.
|
|
2
|
+
|
|
3
|
+
- :func:`verify` — verify an incoming webhook's HMAC signature (for subscribers).
|
|
4
|
+
- :class:`Client` — publish events to webhookd (for producers).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from webhookd_sdk.client import Client, Event
|
|
10
|
+
from webhookd_sdk.errors import WebhookdAPIError, WebhookdError
|
|
11
|
+
from webhookd_sdk.signature import DEFAULT_TOLERANCE_SECONDS, sign, verify
|
|
12
|
+
|
|
13
|
+
__version__ = "0.1.0"
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Client",
|
|
17
|
+
"Event",
|
|
18
|
+
"WebhookdAPIError",
|
|
19
|
+
"WebhookdError",
|
|
20
|
+
"DEFAULT_TOLERANCE_SECONDS",
|
|
21
|
+
"sign",
|
|
22
|
+
"verify",
|
|
23
|
+
"__version__",
|
|
24
|
+
]
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Typed publish client for the webhookd API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from webhookd_sdk.errors import WebhookdAPIError, WebhookdError
|
|
12
|
+
|
|
13
|
+
_RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Event:
|
|
18
|
+
"""The published event, as returned by ``POST /v1/events`` (webhookd's ``EventOut``)."""
|
|
19
|
+
|
|
20
|
+
id: str
|
|
21
|
+
event_uid: str
|
|
22
|
+
event_type: str
|
|
23
|
+
application: str
|
|
24
|
+
environment: str
|
|
25
|
+
deliveries_created: int
|
|
26
|
+
source: str | None = None
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def _from_json(cls, d: dict[str, Any]) -> Event:
|
|
30
|
+
return cls(
|
|
31
|
+
id=d["id"],
|
|
32
|
+
event_uid=d["event_uid"],
|
|
33
|
+
event_type=d["event_type"],
|
|
34
|
+
application=d.get("application", "default"),
|
|
35
|
+
environment=d.get("environment", "prod"),
|
|
36
|
+
deliveries_created=d.get("deliveries_created", 0),
|
|
37
|
+
source=d.get("source"),
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Client:
|
|
42
|
+
"""Publish events to webhookd.
|
|
43
|
+
|
|
44
|
+
Authenticate with a per-tenant API key (``whsk_…``) or a service token::
|
|
45
|
+
|
|
46
|
+
with Client("https://webhooks.example.com", api_key="whsk_…") as wh:
|
|
47
|
+
event = wh.publish("order.created", {"id": 123}, idempotency_key="order-123")
|
|
48
|
+
|
|
49
|
+
Transient failures (connection errors, 429, 5xx) are retried with exponential backoff; a 429
|
|
50
|
+
honours its ``Retry-After`` header. Other 4xx raise :class:`WebhookdAPIError` carrying the
|
|
51
|
+
server's ``{error: {code, message}}`` envelope.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
base_url: str,
|
|
57
|
+
api_key: str,
|
|
58
|
+
*,
|
|
59
|
+
timeout: float = 10.0,
|
|
60
|
+
max_retries: int = 2,
|
|
61
|
+
transport: httpx.BaseTransport | None = None,
|
|
62
|
+
):
|
|
63
|
+
self._base = base_url.rstrip("/")
|
|
64
|
+
self._key = api_key
|
|
65
|
+
self._max_retries = max_retries
|
|
66
|
+
self._client = httpx.Client(timeout=timeout, transport=transport)
|
|
67
|
+
|
|
68
|
+
def publish(
|
|
69
|
+
self,
|
|
70
|
+
event_type: str,
|
|
71
|
+
payload: dict[str, Any],
|
|
72
|
+
*,
|
|
73
|
+
environment: str = "prod",
|
|
74
|
+
application: str = "default",
|
|
75
|
+
source: str | None = None,
|
|
76
|
+
idempotency_key: str | None = None,
|
|
77
|
+
) -> Event:
|
|
78
|
+
"""Publish one event. ``idempotency_key`` makes the publish safe to retry (a replay returns
|
|
79
|
+
the original event without re-fanning-out)."""
|
|
80
|
+
body: dict[str, Any] = {
|
|
81
|
+
"event_type": event_type,
|
|
82
|
+
"payload": payload,
|
|
83
|
+
"environment": environment,
|
|
84
|
+
"application": application,
|
|
85
|
+
}
|
|
86
|
+
if source is not None:
|
|
87
|
+
body["source"] = source
|
|
88
|
+
headers = {"Authorization": f"Bearer {self._key}"}
|
|
89
|
+
if idempotency_key is not None:
|
|
90
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
91
|
+
resp = self._post("/v1/events", body, headers)
|
|
92
|
+
return Event._from_json(resp.json())
|
|
93
|
+
|
|
94
|
+
def close(self) -> None:
|
|
95
|
+
self._client.close()
|
|
96
|
+
|
|
97
|
+
def __enter__(self) -> Client:
|
|
98
|
+
return self
|
|
99
|
+
|
|
100
|
+
def __exit__(self, *_exc: object) -> None:
|
|
101
|
+
self.close()
|
|
102
|
+
|
|
103
|
+
# -- internals -------------------------------------------------------------
|
|
104
|
+
def _post(
|
|
105
|
+
self, path: str, json_body: dict[str, Any], headers: dict[str, str]
|
|
106
|
+
) -> httpx.Response:
|
|
107
|
+
url = f"{self._base}{path}"
|
|
108
|
+
last_exc: Exception | None = None
|
|
109
|
+
for attempt in range(self._max_retries + 1):
|
|
110
|
+
try:
|
|
111
|
+
resp = self._client.post(url, json=json_body, headers=headers)
|
|
112
|
+
except httpx.HTTPError as exc:
|
|
113
|
+
last_exc = exc
|
|
114
|
+
if attempt < self._max_retries:
|
|
115
|
+
time.sleep(_backoff(attempt))
|
|
116
|
+
continue
|
|
117
|
+
raise WebhookdError(f"request failed: {exc}") from exc
|
|
118
|
+
|
|
119
|
+
if resp.status_code in _RETRY_STATUSES and attempt < self._max_retries:
|
|
120
|
+
time.sleep(_retry_after(resp) or _backoff(attempt))
|
|
121
|
+
continue
|
|
122
|
+
if resp.status_code >= 400:
|
|
123
|
+
raise _api_error(resp)
|
|
124
|
+
return resp
|
|
125
|
+
raise WebhookdError(f"request failed after retries: {last_exc}")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _backoff(attempt: int) -> float:
|
|
129
|
+
return min(2.0, 0.2 * (2**attempt))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _retry_after(resp: httpx.Response) -> float | None:
|
|
133
|
+
raw = resp.headers.get("Retry-After")
|
|
134
|
+
if raw and raw.isdigit():
|
|
135
|
+
return float(raw)
|
|
136
|
+
return None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _api_error(resp: httpx.Response) -> WebhookdAPIError:
|
|
140
|
+
code, message = "error", resp.text
|
|
141
|
+
try:
|
|
142
|
+
err = resp.json().get("error") or {}
|
|
143
|
+
code = err.get("code", code)
|
|
144
|
+
message = err.get("message", message)
|
|
145
|
+
except Exception: # noqa: BLE001 - a non-JSON error body falls back to the raw text
|
|
146
|
+
pass
|
|
147
|
+
return WebhookdAPIError(resp.status_code, code, message)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""SDK exceptions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class WebhookdError(Exception):
|
|
7
|
+
"""Base class for all webhookd SDK errors (network failures, etc.)."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class WebhookdAPIError(WebhookdError):
|
|
11
|
+
"""A non-2xx response from the webhookd API.
|
|
12
|
+
|
|
13
|
+
Carries the M5a error envelope: a stable machine ``code`` (e.g. ``"rate_limited"``,
|
|
14
|
+
``"not_found"``, ``"validation_error"``) and a human ``message``, plus the HTTP ``status_code``.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, status_code: int, code: str, message: str):
|
|
18
|
+
self.status_code = status_code
|
|
19
|
+
self.code = code
|
|
20
|
+
self.message = message
|
|
21
|
+
super().__init__(f"[{status_code} {code}] {message}")
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Verify webhookd webhook signatures.
|
|
2
|
+
|
|
3
|
+
webhookd signs every delivery as ``HMAC_SHA256(secret, f"{timestamp}.".encode() + raw_body)`` (its
|
|
4
|
+
default timestamped mode) and sends:
|
|
5
|
+
|
|
6
|
+
- ``X-Webhook-Signature: sha256=<hex>``
|
|
7
|
+
- ``X-Webhook-Timestamp: <unix-seconds>``
|
|
8
|
+
|
|
9
|
+
A subscriber MUST verify the signature to prove the request genuinely came from webhookd and was not
|
|
10
|
+
tampered with in transit. ``verify`` does it correctly: it rebuilds the signed bytes, enforces the
|
|
11
|
+
replay window against the timestamp, and compares in constant time. This mirrors
|
|
12
|
+
``delivery_core.webhook_outbox.{sign,verify}`` byte-for-byte.
|
|
13
|
+
|
|
14
|
+
from webhookd_sdk import verify
|
|
15
|
+
|
|
16
|
+
if not verify(secret, request.body, request.headers["X-Webhook-Signature"],
|
|
17
|
+
timestamp=request.headers["X-Webhook-Timestamp"]):
|
|
18
|
+
return 400 # reject — forged, tampered, or replayed
|
|
19
|
+
|
|
20
|
+
Pass the EXACT bytes you received as ``raw_body`` — do not re-serialize the JSON, or the signature
|
|
21
|
+
won't match (webhookd signs the bytes on the wire).
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import hashlib
|
|
27
|
+
import hmac
|
|
28
|
+
import time
|
|
29
|
+
|
|
30
|
+
_PREFIX = "sha256="
|
|
31
|
+
DEFAULT_TOLERANCE_SECONDS = 300
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _as_bytes(value: str | bytes) -> bytes:
|
|
35
|
+
return value if isinstance(value, bytes) else value.encode("utf-8")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _signed_bytes(raw_body: bytes, timestamp: int | None) -> bytes:
|
|
39
|
+
if timestamp is None:
|
|
40
|
+
return raw_body
|
|
41
|
+
return f"{timestamp}.".encode("ascii") + raw_body
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def sign(secret: str | bytes, raw_body: str | bytes, timestamp: int | None = None) -> str:
|
|
45
|
+
"""The ``sha256=<hex>`` signature webhookd would send for ``raw_body`` (+ optional timestamp).
|
|
46
|
+
|
|
47
|
+
Mainly useful for tests; subscribers call :func:`verify`.
|
|
48
|
+
"""
|
|
49
|
+
digest = hmac.new(
|
|
50
|
+
_as_bytes(secret), _signed_bytes(_as_bytes(raw_body), timestamp), hashlib.sha256
|
|
51
|
+
).hexdigest()
|
|
52
|
+
return f"{_PREFIX}{digest}"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def verify(
|
|
56
|
+
secret: str | bytes,
|
|
57
|
+
raw_body: str | bytes,
|
|
58
|
+
signature: str,
|
|
59
|
+
*,
|
|
60
|
+
timestamp: int | str | None = None,
|
|
61
|
+
tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS,
|
|
62
|
+
now: int | None = None,
|
|
63
|
+
) -> bool:
|
|
64
|
+
"""Return ``True`` iff ``signature`` is a valid webhookd signature for ``raw_body``.
|
|
65
|
+
|
|
66
|
+
:param secret: the endpoint's signing secret (shown once at endpoint creation).
|
|
67
|
+
:param raw_body: the exact request body bytes received (do not re-serialize).
|
|
68
|
+
:param signature: the ``X-Webhook-Signature`` header (``sha256=…``; the prefix is optional).
|
|
69
|
+
:param timestamp: the ``X-Webhook-Timestamp`` header. When given, the signature is rejected if
|
|
70
|
+
it is older/newer than ``tolerance_seconds`` (replay protection) — always pass it.
|
|
71
|
+
:param tolerance_seconds: replay window; webhookd's default is 300s.
|
|
72
|
+
:param now: override the current unix time (for tests).
|
|
73
|
+
"""
|
|
74
|
+
ts = int(timestamp) if timestamp is not None else None
|
|
75
|
+
if ts is not None:
|
|
76
|
+
current = int(time.time()) if now is None else now
|
|
77
|
+
if abs(current - ts) > tolerance_seconds:
|
|
78
|
+
return False
|
|
79
|
+
expected = sign(secret, raw_body, ts)
|
|
80
|
+
candidate = signature if signature.startswith(_PREFIX) else f"{_PREFIX}{signature}"
|
|
81
|
+
return hmac.compare_digest(expected, candidate)
|