An open source, non-profit web search engine
Accept Polar webhooks signed with the Standard Webhooks key
Claudee0ca65c843fb
diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.pyindex 0a5979f..1849ac9 100644--- a/mwmbl/platform/api.py+++ b/mwmbl/platform/api.py@@ -15,7 +15,7 @@ from ninja_jwt.authentication import JWTAuthfrom polar_sdk import Polarfrom polar_sdk import models as polar_modelsfrom polar_sdk.models import SubscriptionCancel, SubscriptionStatus-from polar_sdk.webhooks import WebhookVerificationError, validate_event+from polar_sdk.webhooks import WebhookVerificationErrorfrom mwmbl import membership, pricingfrom mwmbl.background import enrich_domain_submission, stats_manager@@ -83,6 +83,7 @@ from mwmbl.platform.schemas import (VoteStats,VoteStatsRequest,)+from mwmbl.polar_webhooks import validate_eventfrom mwmbl.search_auth import invalidate_api_key_cache, invalidate_user_api_key_cachefrom mwmbl.signals import schedule_blacklist_rebuildfrom mwmbl.usernames import generate_usernamediff --git a/mwmbl/polar_webhooks.py b/mwmbl/polar_webhooks.pynew file mode 100644index 0000000..36ae3af--- /dev/null+++ b/mwmbl/polar_webhooks.py@@ -0,0 +1,29 @@+"""Verify Polar webhook deliveries signed with either of Polar's two signing keys."""++from polar_sdk._webhooks import _KNOWN_EVENT_TYPES, WebhookPayloadAdapter+from polar_sdk.webhooks import WebhookUnknownTypeError, WebhookVerificationError, WebhoookPayload+from polar_sdk.webhooks import validate_event as validate_legacy_event+from standardwebhooks.webhooks import Webhook+from standardwebhooks.webhooks import WebhookVerificationError as StandardWebhookVerificationError+++def validate_event(body: str | bytes, headers: dict[str, str], secret: str) -> WebhoookPayload:+ """Verify and parse a Polar webhook delivery.++ Endpoints created before 8 September 2026 sign with the UTF-8 bytes of the whole `whsec_…`+ secret, which is what the pinned SDK's validate_event checks. Later endpoints follow the+ Standard Webhooks spec and sign with the secret as-is. Polar's SDKs from 1.0.0-alpha.19 try+ both; this does the same for the 0.x SDK we pin.+ """+ try:+ return validate_legacy_event(body=body, headers=headers, secret=secret)+ except WebhookVerificationError:+ try:+ data = Webhook(secret).verify(body, headers)+ except (StandardWebhookVerificationError, ValueError) as e:+ # ValueError covers a legacy secret that isn't valid base64 once its prefix is stripped.+ raise WebhookVerificationError(str(e)) from e++ if data.get("type") not in _KNOWN_EVENT_TYPES:+ raise WebhookUnknownTypeError(data.get("type"))+ return WebhookPayloadAdapter.validate_python(data)diff --git a/pyproject.toml b/pyproject.tomlindex 3180b67..bc292f8 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -60,6 +60,7 @@ dependencies = ["beautifulsoup4==4.10.0","onnxruntime>=1.27.0","tokenizers>=0.23.1",+ "standardwebhooks>=1.0.1",][project.optional-dependencies]diff --git a/test/test_polar_webhooks.py b/test/test_polar_webhooks.pynew file mode 100644index 0000000..59f725b--- /dev/null+++ b/test/test_polar_webhooks.py@@ -0,0 +1,72 @@+import base64+import json+from datetime import datetime, timezone++import pytest+from polar_sdk.webhooks import WebhookVerificationError+from standardwebhooks.webhooks import Webhook++from mwmbl.polar_webhooks import validate_event++SECRET = "whsec_" + base64.b64encode(b"a-thirty-two-byte-signing-key!!!").decode()++BODY = json.dumps(+ {+ "type": "customer.deleted",+ "timestamp": "2026-10-02T00:00:00Z",+ "data": {+ "id": "7a6e5b3c-0000-4000-8000-000000000001",+ "type": "individual",+ "created_at": "2026-10-02T00:00:00Z",+ "modified_at": None,+ "metadata": {},+ "email": "[email protected]",+ "email_verified": True,+ "name": None,+ "billing_name": None,+ "billing_address": None,+ "tax_id": None,+ "organization_id": "7a6e5b3c-0000-4000-8000-000000000002",+ "deleted_at": None,+ "external_id": None,+ "avatar_url": "https://example.com/avatar.png",+ },+ }+)+++def _headers(signing_secret):+ timestamp = datetime.now(timezone.utc)+ return {+ "webhook-id": "msg_1",+ "webhook-timestamp": str(int(timestamp.timestamp())),+ "webhook-signature": Webhook(signing_secret).sign("msg_1", timestamp, BODY),+ }+++def test_accepts_legacy_signing():+ # Endpoints created before 8 September 2026: the key is the bytes of the whole whsec_ string.+ headers = _headers(base64.b64encode(SECRET.encode()).decode())++ assert validate_event(body=BODY, headers=headers, secret=SECRET).TYPE == "customer.deleted"+++def test_accepts_standard_webhooks_signing():+ # Endpoints created since 8 September 2026: the whsec_ secret is the Standard Webhooks key.+ headers = _headers(SECRET)++ assert validate_event(body=BODY, headers=headers, secret=SECRET).TYPE == "customer.deleted"+++def test_rejects_wrong_secret():+ headers = _headers("whsec_" + base64.b64encode(b"some-other-key").decode())++ with pytest.raises(WebhookVerificationError):+ validate_event(body=BODY, headers=headers, secret=SECRET)+++def test_rejects_tampered_body():+ headers = _headers(SECRET)++ with pytest.raises(WebhookVerificationError):+ validate_event(body=BODY.replace("member@", "attacker@"), headers=headers, secret=SECRET)diff --git a/uv.lock b/uv.lockindex 013a246..8aee299 100644--- a/uv.lock+++ b/uv.lock@@ -837,6 +837,7 @@ dependencies = [{ name = "scikit-learn" },{ name = "scipy" },{ name = "sentry-sdk" },+ { name = "standardwebhooks" },{ name = "tokenizers" },{ name = "uvicorn" },{ name = "wasmtime" },@@ -916,6 +917,7 @@ requires-dist = [{ name = "scikit-learn", specifier = ">=1.0.2" },{ name = "scipy", specifier = ">=1.8.0" },{ name = "sentry-sdk", specifier = ">=2.13.0" },+ { name = "standardwebhooks", specifier = ">=1.0.1" },{ name = "tokenizers", specifier = ">=0.23.1" },{ name = "ujson", marker = "extra == 'indexer'", specifier = "==4.3.0" },{ name = "uvicorn", specifier = ">=0.16.0" },