Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(events): refuse Standard Webhooks deliveries outside the replay window
trohitg3218f349dd4f
diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.mdindex 8106a76b..f783a77c 100644--- a/docs-internal/plugin_system.md+++ b/docs-internal/plugin_system.md@@ -1322,7 +1322,7 @@ Drop-in HMAC schemes covering the major providers:| Class | Header | Algorithm | Used by ||---|---|---|---|| `StripeVerifier` | `Stripe-Signature: t=…,v1=…` | HMAC-SHA256 over `t.body` | Stripe |-| `StandardWebhooksVerifier` | `webhook-id` / `webhook-timestamp` / `webhook-signature` | HMAC-SHA256 base64 over `id.ts.body` | Svix-backed providers (Resend, Clerk, Loops, …) |+| `StandardWebhooksVerifier` | `webhook-id` / `webhook-timestamp` / `webhook-signature` | HMAC-SHA256 base64 over `id.ts.body`; a `webhook-timestamp` more than 5 minutes from now is refused (the spec's replay window) | Svix-backed providers (Resend, Clerk, Loops, …) || `GitHubVerifier` | `X-Hub-Signature-256: sha256=…` | HMAC-SHA256 over body | GitHub || `HmacVerifier` | configurable header + prefix | HMAC-SHA256 over body | generic fallback |diff --git a/server/services/events/verifiers/standard_webhooks.py b/server/services/events/verifiers/standard_webhooks.pyindex 4925bfd6..00f0e726 100644--- a/server/services/events/verifiers/standard_webhooks.py+++ b/server/services/events/verifiers/standard_webhooks.py@@ -7,6 +7,8 @@ Algorithm: HMAC-SHA256 of the secret (b64-decoded after the ``whsec_`` prefixis stripped) over the signed payload, base64-encoded.``webhook-signature`` may carry multiple space-separated ``v1,<sig>`` entriesto support secret rotation.+A ``webhook-timestamp`` more than five minutes from now is refused, as the+spec requires, so a captured delivery cannot be replayed later."""from __future__ import annotations@@ -14,12 +16,16 @@ from __future__ import annotationsimport base64import hashlibimport hmac+import timefrom typing import Mappingfrom .base import WebhookVerifierclass StandardWebhooksVerifier(WebhookVerifier):+ # The spec's replay window, in seconds, either side of the server clock.+ tolerance_seconds = 5 * 60+@classmethoddef verify(cls, headers: Mapping[str, str], body: bytes, secret: str) -> None:msg_id = cls._header(headers, "webhook-id")@@ -28,6 +34,13 @@ class StandardWebhooksVerifier(WebhookVerifier):if not (msg_id and timestamp and sig_header):raise ValueError("Standard Webhooks headers missing")+ try:+ sent_at = int(timestamp)+ except ValueError:+ raise ValueError("Standard Webhooks timestamp is not a number") from None+ if abs(time.time() - sent_at) > cls.tolerance_seconds:+ raise ValueError("Standard Webhooks timestamp is outside the tolerance window")+if secret.startswith("whsec_"):key = base64.b64decode(secret[len("whsec_") :])else:diff --git a/server/tests/services/test_events.py b/server/tests/services/test_events.pyindex 20a1bc5d..505dbcd7 100644--- a/server/tests/services/test_events.py+++ b/server/tests/services/test_events.py@@ -195,32 +195,69 @@ class TestGitHubVerifier:class TestStandardWebhooksVerifier:- def test_round_trip(self):- from services.events import StandardWebhooksVerifier+ SECRET_RAW = b"super-secret-key-bytes"+ SECRET = "whsec_" + base64.b64encode(SECRET_RAW).decode()- secret_raw = b"super-secret-key-bytes"- secret = "whsec_" + base64.b64encode(secret_raw).decode()- body = b'{"foo":"bar"}'- msg_id = "msg_abc"- ts = "1700000000"+ def _signed(self, body: bytes, ts: int, msg_id: str = "msg_abc") -> dict:signed = f"{msg_id}.{ts}.".encode() + body- sig = base64.b64encode(hmac.new(secret_raw, signed, hashlib.sha256).digest()).decode()- headers = {+ sig = base64.b64encode(hmac.new(self.SECRET_RAW, signed, hashlib.sha256).digest()).decode()+ return {"webhook-id": msg_id,- "webhook-timestamp": ts,+ "webhook-timestamp": str(ts),"webhook-signature": f"v1,{sig}",}- StandardWebhooksVerifier.verify(headers, body, secret)++ def test_round_trip(self):+ from services.events import StandardWebhooksVerifier++ body = b'{"foo":"bar"}'+ StandardWebhooksVerifier.verify(self._signed(body, int(time.time())), body, self.SECRET)++ def test_rotated_secret_list_accepts_any_matching_entry(self):+ from services.events import StandardWebhooksVerifier++ body = b'{"foo":"bar"}'+ headers = self._signed(body, int(time.time()))+ headers["webhook-signature"] = "v1,c3RhbGU= " + headers["webhook-signature"]+ StandardWebhooksVerifier.verify(headers, body, self.SECRET)def test_tampered_rejected(self):from services.events import StandardWebhooksVerifier- with pytest.raises(ValueError):- StandardWebhooksVerifier.verify(- {"webhook-id": "1", "webhook-timestamp": "1", "webhook-signature": "v1,bad"},- b"{}",- "whsec_AAAA",- )+ headers = self._signed(b'{"foo":"bar"}', int(time.time()))+ with pytest.raises(ValueError, match="signature mismatch"):+ StandardWebhooksVerifier.verify(headers, b'{"foo":"baz"}', self.SECRET)++ @pytest.mark.parametrize("offset", [-301, 301])+ def test_timestamp_outside_the_window_is_rejected(self, offset):+ """A correctly signed delivery replayed later (or stamped far ahead)+ fails: the spec bounds the timestamp to five minutes either way."""+ from services.events import StandardWebhooksVerifier++ body = b'{"foo":"bar"}'+ headers = self._signed(body, int(time.time()) + offset)+ with pytest.raises(ValueError, match="tolerance"):+ StandardWebhooksVerifier.verify(headers, body, self.SECRET)++ def test_timestamp_inside_the_window_is_accepted(self):+ from services.events import StandardWebhooksVerifier++ body = b'{"foo":"bar"}'+ StandardWebhooksVerifier.verify(self._signed(body, int(time.time()) - 240), body, self.SECRET)++ def test_non_numeric_timestamp_rejected(self):+ from services.events import StandardWebhooksVerifier++ headers = self._signed(b"{}", int(time.time()))+ headers["webhook-timestamp"] = "yesterday"+ with pytest.raises(ValueError, match="not a number"):+ StandardWebhooksVerifier.verify(headers, b"{}", self.SECRET)++ def test_missing_headers_rejected(self):+ from services.events import StandardWebhooksVerifier++ with pytest.raises(ValueError, match="missing"):+ StandardWebhooksVerifier.verify({}, b"{}", self.SECRET)class TestHmacVerifier: