Skip to content

Self-improving AI Employees for everyone

feat(events): add WebhookSource.handle_get for subscription handshakes

trohitg39450b3804ef
diff --git a/server/routers/webhook.py b/server/routers/webhook.py
index 659390e4..45f360a5 100644
--- a/server/routers/webhook.py
+++ b/server/routers/webhook.py
@@ -56,6 +56,16 @@ async def handle_webhook(path: str, request: Request):
source = WEBHOOK_SOURCES.get(path)
if source is not None:
try:
+ if request.method == "GET":
+ # Subscription handshakes (Meta's hub.challenge echo, and
+ # equivalents) need a provider-specific body that is not
+ # this router's fixed JSON. A source that declines returns
+ # None and falls through to the normal handle() path, so
+ # sources without an override are unaffected.
+ handshake = await source.handle_get(request)
+ if handshake is not None:
+ logger.info("[Webhook] GET %s -> %s handshake", path, type(source).__name__)
+ return handshake
await source.handle(request)
except HTTPException:
raise
diff --git a/server/services/events/webhook.py b/server/services/events/webhook.py
index c15ce3d4..73cc8cec 100644
--- a/server/services/events/webhook.py
+++ b/server/services/events/webhook.py
@@ -19,7 +19,7 @@ from __future__ import annotations
import json
from typing import ClassVar, Dict, Optional, Type
-from fastapi import HTTPException, Request
+from fastapi import HTTPException, Request, Response
from core.logging import get_logger
@@ -72,6 +72,21 @@ class WebhookSource(PushEventSource):
data=payload,
)
+ async def handle_get(self, request: Request) -> Optional[Response]:
+ """Answer a provider's subscription handshake.
+
+ Several providers verify webhook ownership with a ``GET`` before
+ they will deliver anything: Meta echoes ``hub.challenge`` as
+ ``text/plain``, and others use their own challenge shapes. Those
+ responses are not the router's fixed JSON body, so the source has
+ to own them.
+
+ Return ``None`` (the default) to decline, in which case the router
+ falls through to the normal :meth:`handle` path — so every source
+ that does not override this behaves exactly as before.
+ """
+ return None
+
async def handle(self, request: Request) -> WorkflowEvent:
"""Called by the webhook router. Verifies signature, parses the
body, shapes the event, dispatches into ``event_waiter``, and
@@ -107,5 +122,11 @@ class WebhookSource(PushEventSource):
from services import event_waiter
- event_waiter.dispatch(self.type, event)
+ # Pass the envelope alone. The two-argument form is
+ # ``(event_type: str, data: Dict)``, so handing a WorkflowEvent as
+ # the second argument made ``data`` the envelope itself and every
+ # ``data.get(...)`` in the dispatcher raised AttributeError as soon
+ # as a waiter was active. ``_unpack_event`` already unwraps a
+ # WorkflowEvent into ``(type, data)`` on its own.
+ event_waiter.dispatch(event)
return event
diff --git a/server/tests/nodes/test_stripe_plugin.py b/server/tests/nodes/test_stripe_plugin.py
index dc7e8e63..0b810892 100644
--- a/server/tests/nodes/test_stripe_plugin.py
+++ b/server/tests/nodes/test_stripe_plugin.py
@@ -96,9 +96,13 @@ class TestStripeWebhookShape:
ev = _run(src.handle(req))
assert ev.type == "stripe.charge.succeeded"
dispatch.assert_called_once()
- ev_type, dispatched = dispatch.call_args[0]
- assert ev_type == "stripe.webhook"
+ # Dispatched as a lone envelope: the two-argument form means
+ # ``(event_type, data)``, so passing the event second made ``data``
+ # the envelope and the dispatcher's ``data.get(...)`` calls raised
+ # AttributeError once a waiter was active.
+ (dispatched,) = dispatch.call_args[0]
assert dispatched.id == "evt_2"
+ assert dispatched.type == "stripe.charge.succeeded"
def test_handle_rejects_tampered_signature(self):
from fastapi import HTTPException
diff --git a/server/tests/routers/test_webhook.py b/server/tests/routers/test_webhook.py
new file mode 100644
index 00000000..7b03ee17
--- /dev/null
+++ b/server/tests/routers/test_webhook.py
@@ -0,0 +1,135 @@
+"""Webhook router dispatch — registered sources vs the legacy fallback.
+
+The router owns one decision that the sources cannot make for themselves:
+whether a GET is a provider subscription handshake (answered by the source
+with its own Response) or ordinary traffic (handled by ``handle()``).
+"""
+
+from unittest.mock import patch
+
+import pytest
+from fastapi import FastAPI
+from fastapi.responses import PlainTextResponse
+from fastapi.testclient import TestClient
+
+from routers.webhook import router
+from services.events import WEBHOOK_SOURCES, WebhookSource, WorkflowEvent
+
+
+def client():
+ app = FastAPI()
+ app.include_router(router)
+ return TestClient(app)
+
+
+def clean_registry():
+ """Restore WEBHOOK_SOURCES so tests cannot leak paths into each other."""
+ original = dict(WEBHOOK_SOURCES)
+ try:
+ yield WEBHOOK_SOURCES
+ finally:
+ WEBHOOK_SOURCES.clear()
+ WEBHOOK_SOURCES.update(original)
+
+
+class _RecordingSource(WebhookSource):
+ """Unverified source that records whether handle() ran."""
+
+ type = "recording.hook"
+ path = "recording"
+
+ def __init__(self):
+ super().__init__()
+ self.handled = 0
+
+ async def shape(self, request, body, payload):
+ return WorkflowEvent(source="rec://x", type="recording.event", data=payload)
+
+ async def handle(self, request):
+ self.handled += 1
+ return await super().handle(request)
+
+
+class _HandshakeSource(_RecordingSource):
+ """Answers a GET carrying hub.challenge, declines every other GET."""
+
+ type = "handshake.hook"
+ path = "handshake"
+
+ async def handle_get(self, request):
+ challenge = request.query_params.get("hub.challenge")
+ if challenge is None:
+ return None
+ return PlainTextResponse(challenge)
+
+
+class TestGetHandshake:
+ def test_handshake_response_is_returned_verbatim(self, client, clean_registry):
+ """The source's body reaches the caller unwrapped.
+
+ Meta rejects a JSON envelope here -- it wants the bare challenge.
+ """
+ source = _HandshakeSource()
+ clean_registry[source.path] = source
+
+ resp = client.get("/webhook/handshake?hub.mode=subscribe&hub.challenge=1158201444")
+
+ assert resp.status_code == 200
+ assert resp.text == "1158201444"
+ assert resp.headers["content-type"].startswith("text/plain")
+ # A handshake is not an event -- handle() must not run.
+ assert source.handled == 0
+
+ def test_declining_falls_through_to_handle(self, client, clean_registry):
+ """Returning None keeps the pre-existing behaviour exactly."""
+ source = _HandshakeSource()
+ clean_registry[source.path] = source
+
+ with patch("services.event_waiter.dispatch"):
+ resp = client.get("/webhook/handshake")
+
+ assert resp.status_code == 200
+ assert resp.json() == {"status": "received", "path": "handshake"}
+ assert source.handled == 1
+
+ def test_source_without_override_is_unaffected(self, client, clean_registry):
+ """Every existing source predates this hook and must behave as before."""
+ source = _RecordingSource()
+ clean_registry[source.path] = source
+
+ with patch("services.event_waiter.dispatch"):
+ resp = client.get("/webhook/recording")
+
+ assert resp.status_code == 200
+ assert resp.json() == {"status": "received", "path": "recording"}
+ assert source.handled == 1
+
+ def test_post_never_consults_handle_get(self, client, clean_registry):
+ """The hook is GET-only; a POST carrying the query params still
+ goes through handle()."""
+ source = _HandshakeSource()
+ clean_registry[source.path] = source
+
+ with patch("services.event_waiter.dispatch"):
+ resp = client.post("/webhook/handshake?hub.challenge=123", json={"a": 1})
+
+ assert resp.status_code == 200
+ assert resp.json() == {"status": "received", "path": "handshake"}
+ assert source.handled == 1
+
+
+class TestLegacyFallback:
+ def test_unclaimed_path_still_reaches_the_generic_handler(self, client, clean_registry):
+ """An unregistered path must keep firing webhookTrigger nodes."""
+ clean_registry.clear()
+
+ with patch("nodes.trigger.webhook_trigger._events.broadcast_webhook_received") as broadcast:
+ resp = client.post("/webhook/unclaimed", json={"hello": "world"})
+
+ assert resp.status_code == 200
+ broadcast.assert_called_once()
+ payload = broadcast.call_args[0][0]
+ assert payload["path"] == "unclaimed"
+ assert payload["json"] == {"hello": "world"}
diff --git a/server/tests/services/test_events.py b/server/tests/services/test_events.py
index 0fdb739d..20a1bc5d 100644
--- a/server/tests/services/test_events.py
+++ b/server/tests/services/test_events.py
@@ -320,9 +320,54 @@ class TestWebhookSourceHandle:
ev = _run(src.handle(req))
assert ev.type == "fake.event"
dispatch.assert_called_once()
- called_type, called_event = dispatch.call_args[0]
- assert called_type == "fake.hook"
- assert called_event is ev
+ # The envelope is passed alone. The two-argument form means
+ # ``(event_type: str, data: Dict)``, so passing the event as the
+ # second argument made ``data`` the envelope itself -- see
+ # test_dispatch_with_live_waiter_does_not_crash below.
+ assert dispatch.call_args[0] == (ev,)
+
+ def test_dispatch_with_live_waiter_does_not_crash(self):
+ """Regression: the dispatcher must receive an unpackable envelope.
+
+ ``handle`` used to call ``dispatch(self.type, event)``. The
+ two-argument form is ``(event_type, data)``, so ``data`` became the
+ WorkflowEvent and every ``data.get(...)`` inside the dispatcher
+ raised AttributeError -- but only once a waiter was actually
+ registered, which is why no existing test caught it. This registers
+ a real waiter and dispatches for real.
+ """
+ import asyncio as _asyncio
+
+ from services import event_waiter
+
+ src = self._build_source(secret_value="whsec_test")
+ body = b'{"event":"payload","from_id":"alice"}'
+ req = self._signed_request(body, "whsec_test")
+
+ async def _scenario():
+ # Built inline rather than via event_waiter.register(), which
+ # requires a TRIGGER_REGISTRY entry this fake type has no
+ # business adding. The future must be created on the loop that
+ # runs handle(), so it cannot be set up outside the coroutine.
+ waiter = event_waiter.Waiter(
+ node_id="n1",
+ node_type="fakeTrigger",
+ event_type="fake.event",
+ filter_fn=lambda _data: True,
+ future=_asyncio.get_running_loop().create_future(),
+ )
+ event_waiter._waiters[waiter.id] = waiter
+ try:
+ event = await src.handle(req)
+ return event, waiter.future
+ finally:
+ event_waiter.cancel_for_node("n1")
+
+ ev, future = _run(_scenario())
+ assert future.done()
+ # The waiter resolves with the envelope's *data*, not the envelope.
+ assert future.result() == ev.data
+ assert future.result()["from_id"] == "alice"
def test_tampered_signature_raises_400(self):
from fastapi import HTTPException
@@ -390,6 +435,85 @@ class TestWebhookSourceHandle:
dispatch.assert_not_called()
+# ============================================================================
+# WebhookSource.handle_get — provider subscription handshakes
+# ============================================================================
+
+
+class TestWebhookSourceHandleGet:
+ """A source may answer a GET handshake with its own Response body.
+
+ Providers verify webhook ownership before delivering anything, and the
+ expected reply is provider-specific (Meta echoes ``hub.challenge`` as
+ text/plain). The router's fixed JSON body cannot express that, so the
+ source owns the response.
+ """
+
+ def test_default_declines(self):
+ """The base implementation returns None so existing sources are
+ untouched -- the router then falls through to handle()."""
+ from services.events import WebhookSource
+
+ class Bare(WebhookSource):
+ type = "bare.hook"
+ path = "bare"
+
+ class FakeReq:
+ method = "GET"
+ headers = {}
+ query_params = {}
+
+ assert _run(Bare().handle_get(FakeReq())) is None
+
+ def test_override_can_return_plain_text(self):
+ """A source that overrides it controls status, body and media type."""
+ from fastapi.responses import PlainTextResponse
+
+ from services.events import WebhookSource
+
+ class Echoing(WebhookSource):
+ type = "echo.hook"
+ path = "echo"
+
+ async def handle_get(self, request):
+ challenge = request.query_params.get("hub.challenge")
+ if challenge is None:
+ return None
+ return PlainTextResponse(challenge)
+
+ class FakeReq:
+ method = "GET"
+ headers = {}
+ query_params = {"hub.challenge": "1158201444"}
+
+ resp = _run(Echoing().handle_get(FakeReq()))
+ assert resp.status_code == 200
+ # Meta requires the bare challenge value, not a JSON wrapper.
+ assert resp.body == b"1158201444"
+ assert resp.media_type == "text/plain"
+
+ def test_override_may_still_decline(self):
+ """Returning None from an override falls through to handle()."""
+ from fastapi.responses import PlainTextResponse
+
+ from services.events import WebhookSource
+
+ class Echoing(WebhookSource):
+ type = "echo.hook"
+ path = "echo"
+
+ async def handle_get(self, request):
+ challenge = request.query_params.get("hub.challenge")
+ return PlainTextResponse(challenge) if challenge else None
+
+ class FakeReq:
+ method = "GET"
+ headers = {}
+ query_params = {}
+
+ assert _run(Echoing().handle_get(FakeReq())) is None
+
+
# ============================================================================
# DaemonEventSource lifecycle (mocked ProcessService)
# ============================================================================