Skip to content

Self-improving AI Employees for everyone

fix(webhook): enforce webhook trigger auth and route by declared path

trohitgdb55d4e9decf
diff --git a/CLAUDE.md b/CLAUDE.md
index 9b4ac4c6..accdc145 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -701,7 +701,7 @@ Node groups (palette categories) are registered in [`server/nodes/groups.py`](./
#### Webhook Router (`server/routers/webhook.py`)
- `ANY /webhook/{path}` - Dynamic webhook endpoint for incoming HTTP requests (GET, POST, PUT, DELETE, PATCH)
-- A path a plugin registered with `register_webhook_source` (Stripe, Dodo Payments, WhatsApp Business) goes to that `WebhookSource`; any other path reaches webhookTrigger nodes through `nodes/trigger/webhook_trigger/_events.broadcast_webhook_received` (`dispatch.emit`)
+- A path a plugin registered with `register_webhook_source` (Stripe, Dodo Payments, WhatsApp Business) goes to that `WebhookSource`; any other path goes to `nodes/trigger/webhook_trigger/_routes.deliver_webhook`, whose route table is the running and paused generations' snapshots: 404 for a path no generation declares, 405 for a method none of its triggers accepts, 401 when the trigger's header check fails (expected value read from the saved node parameters, `hmac.compare_digest`, fail closed). Each matching workflow gets one event scoped to it (`dispatch.emit`, `broadcast=False`), with `authorization`, `cookie`, `proxy-authorization` and the trigger's own header removed. A webhookTrigger with an empty path matches nothing, and Start refuses it (`WEBHOOK_PATH_REQUIRED`)
- A body larger than `WEBHOOK_MAX_BODY_BYTES` (default in `.env.template`) gets 413 before anything is dispatched (`services/events/webhook.read_body_capped`, also used by Discord interactions), because the body rides into a workflow's input
- Returns 200 OK once dispatched (responseNode mode planned for future)
- `GET /webhook/` - Webhook endpoint info and usage documentation
@@ -2749,7 +2749,7 @@ This function:
- `httpRequest` - Make outgoing HTTP requests with httpx async client
- `webhookTrigger` - Receive incoming HTTP requests at `/webhook/{path}`
- `webhookResponse` - Send custom responses back to webhook callers
- - `server/routers/webhook.py` - Dynamic webhook router using broadcaster.send_custom_event()
+ - `server/routers/webhook.py` - Dynamic webhook router; unclaimed paths go to `nodes/trigger/webhook_trigger/_routes.deliver_webhook` (path, method and header checks, one event scoped to each matching workflow)
- Output panel shows clean summaries (method, path, body for webhooks; status code for HTTP)
- **n8n-Pattern Cache System**: Automatic fallback hierarchy for different environments
- Opt-in (`REDIS_ENABLED=true`; no shipped configuration sets it): Redis → SQLite → Memory
diff --git a/client/src/utils/__tests__/parameterSanitizer.test.ts b/client/src/utils/__tests__/parameterSanitizer.test.ts
index 2a67991f..d8dbe7b9 100644
--- a/client/src/utils/__tests__/parameterSanitizer.test.ts
+++ b/client/src/utils/__tests__/parameterSanitizer.test.ts
@@ -103,6 +103,16 @@ describe('sanitizeParameters', () => {
expect(out).toEqual({ keep_me: 'ok' });
});
+ it("strips a webhook trigger's expected header value but keeps its header name", () => {
+ const out = sanitizeParameters({
+ path: 'orders',
+ authentication: 'header',
+ header_name: 'X-API-Key',
+ header_value: 'the-shared-secret',
+ });
+ expect(out).toEqual({ path: 'orders', authentication: 'header', header_name: 'X-API-Key' });
+ });
+
it('keeps cloud_tool_key, which is an identifier and not a credential', () => {
// A blanket `endsWith("key")` rule would discard this identifier
// when exporting legacy workflow configuration.
diff --git a/client/src/utils/parameterSanitizer.ts b/client/src/utils/parameterSanitizer.ts
index 7f4577c4..72bc55f0 100644
--- a/client/src/utils/parameterSanitizer.ts
+++ b/client/src/utils/parameterSanitizer.ts
@@ -41,6 +41,7 @@ const SENSITIVE_EXACT_KEYS = normalizedSet([
'private_key',
'encryption_key',
'oauth_token',
+ 'header_value', // webhookTrigger's expected authentication header
]);
// Legitimate parameter names that contain sensitive substrings but are NOT
diff --git a/docs-internal/event_framework.md b/docs-internal/event_framework.md
index a5253d78..62d877eb 100644
--- a/docs-internal/event_framework.md
+++ b/docs-internal/event_framework.md
@@ -139,6 +139,21 @@ second envelope of the same type and id whose data is only `task_id`,
`status`, `team_id` and `workflow_id`, which is all the Task Manager panel
reads to refresh.
+Third producer: generic webhooks (`nodes/trigger/webhook_trigger/_routes.py`,
+`com.opencompany.webhook.received`). `deliver_webhook` takes its route table
+from the running and paused generations' snapshots and answers 404 for a path
+none declares, 405 for a method none of its triggers accepts, and 401 when
+the trigger's header check fails (expected value read from the saved node
+parameters, never from a snapshot or a Temporal input; compared with
+`hmac.compare_digest`; no configured value refuses). Each workflow with an
+accepting trigger gets one envelope scoped to it, emitted with
+`broadcast=False`; `authorization`, `cookie`, `proxy-authorization` and the
+trigger's own header are removed first. A webhookTrigger with an empty path
+matches nothing, and Start refuses one (`WEBHOOK_PATH_REQUIRED`). Before this
+(RFC-0004 C3) the header check was never made, one webhook fired every
+deployed workflow's trigger, and headers and body were broadcast to every
+socket.
+
Worker is embedded in the FastAPI process (the `main.py` lifespan schedules
`run_temporal_lifecycle` from `services/temporal/lifecycle.py` as one
`asyncio.create_task()` named `temporal-init`; that module owns the connect loop and the
diff --git a/server/nodes/trigger/webhook_trigger/__init__.py b/server/nodes/trigger/webhook_trigger/__init__.py
index 3518f61b..f80c280c 100644
--- a/server/nodes/trigger/webhook_trigger/__init__.py
+++ b/server/nodes/trigger/webhook_trigger/__init__.py
@@ -1,8 +1,10 @@
"""Webhook Trigger — Wave 11.B reference migration (event-based trigger).
-Listens for inbound HTTP requests dispatched into ``services.event_waiter``
-by ``routers/webhook.py``. Filter narrows to a specific ``path``. No
-credentials, no HTTP egress — the routing layer injects the event.
+Listens for inbound HTTP requests on ``/webhook/{path}``.
+``_routes.deliver_webhook`` (called by ``routers/webhook.py``) enforces the
+trigger's path, method and header authentication before anything reaches a
+workflow, and scopes the event to the workflow that declares the path; the
+filter narrows to the ``path``. No credentials, no HTTP egress.
Replaces:
- ``server/nodes/triggers.py:webhookTrigger`` metadata-only registration
@@ -88,16 +90,26 @@ class WebhookTriggerNode(TriggerNode):
Output = WebhookTriggerOutput
def build_filter(self, params: WebhookTriggerParams) -> Callable[[Dict[str, Any]], bool]:
- """Narrow dispatched events to this trigger's path."""
+ """Narrow dispatched events to this trigger's path. A trigger with
+ no path matches nothing: it used to match every webhook."""
expected_path = params.path or ""
def matches(event: Dict[str, Any]) -> bool:
- if expected_path and event.get("path") != expected_path:
- return False
- return True
+ return bool(expected_path) and event.get("path") == expected_path
return matches
+ @classmethod
+ def validate_graph(cls, node_id: str, graph: Dict[str, Any]) -> list[Dict[str, Any]]:
+ """Refuse a Start whose webhook has no path: ``/webhook/`` with no
+ path would reach nothing, and an empty path used to match every
+ webhook sent to the instance."""
+ params = (graph.get("parameters") or {}).get(node_id)
+ if params is None or (params.get("path") or "").strip():
+ return []
+ return [{"code": "WEBHOOK_PATH_REQUIRED", "node_id": node_id,
+ "message": "Give the webhook a path; it is the address callers send to (/webhook/<path>)."}]
+
# Event triggers don't run a body — the base class handles the
# ``event_waiter.register()`` + ``await future`` flow. Declare the
# stub operation so invariants see it.
@@ -108,6 +120,6 @@ class WebhookTriggerNode(TriggerNode):
# Wave 12 C1 canary: opt this trigger type into TriggerListenerWorkflow.
# Gated runtime by Settings.event_framework_enabled in DeploymentManager;
-# the producer side (broadcast_webhook_received calling dispatch.emit) is
+# the producer side (_routes.deliver_webhook calling dispatch.emit) is
# unconditional. See services/deployment/canary_registry.py.
register_canary_trigger_type(WebhookTriggerNode.type, "com.opencompany.webhook.received")
diff --git a/server/nodes/trigger/webhook_trigger/_events.py b/server/nodes/trigger/webhook_trigger/_events.py
index 29cd80e0..0fb4adaa 100644
--- a/server/nodes/trigger/webhook_trigger/_events.py
+++ b/server/nodes/trigger/webhook_trigger/_events.py
@@ -1,13 +1,15 @@
-"""CloudEvents factory + broadcaster wrapper for webhook_trigger.
+"""CloudEvents factory + emit wrapper for webhook_trigger.
Per RFC plugin_authoring_rfc.md §6.4: plugin-specific factories live in
the plugin folder.
-Delivery: single ``dispatch.emit`` call routes events to running
-:class:`TriggerListenerWorkflow` consumers via Temporal Visibility AND
-broadcasts the envelope to FE on the ``webhook_received`` wire key.
-webhookTrigger is canary-registered (see ``nodes/trigger/webhook_trigger/__init__.py``)
-so the deployment manager skips ``setup_event_trigger`` and the legacy
+Delivery: ``_routes.deliver_webhook`` calls :func:`emit_webhook_received`
+once per workflow that declares the path. The envelope is scoped to that
+workflow, so ``dispatch.emit`` signals only its consumers, and it is never
+broadcast: it carries the caller's headers and body, and no client reads
+it. webhookTrigger is canary-registered (see
+``nodes/trigger/webhook_trigger/__init__.py``) so the deployment manager
+skips ``setup_event_trigger`` and the legacy
``broadcaster.send_custom_event`` path (which dispatched to
``event_waiter``) has zero consumers — removed.
"""
@@ -38,17 +40,16 @@ def webhook_received(webhook_data: Mapping[str, Any]) -> WorkflowEvent:
)
-async def broadcast_webhook_received(webhook_data: Mapping[str, Any]) -> None:
- """Broadcast an incoming webhook via the canary CloudEvents path."""
+async def emit_webhook_received(webhook_data: Mapping[str, Any], *, workflow_id: str) -> None:
+ """Deliver an incoming webhook to the triggers of ``workflow_id``."""
from services.events.dispatch import emit
- await emit(
- webhook_received(dict(webhook_data)),
- wire_routing_key=_WIRE_ROUTING_KEY,
- )
+ event = webhook_received(dict(webhook_data))
+ event.workflow_id = workflow_id
+ await emit(event, wire_routing_key=_WIRE_ROUTING_KEY, broadcast=False)
__all__ = [
- "broadcast_webhook_received",
+ "emit_webhook_received",
"webhook_received",
]
diff --git a/server/nodes/trigger/webhook_trigger/_routes.py b/server/nodes/trigger/webhook_trigger/_routes.py
new file mode 100644
index 00000000..77a9aad4
--- /dev/null
+++ b/server/nodes/trigger/webhook_trigger/_routes.py
@@ -0,0 +1,100 @@
+"""Deliver a request on ``/webhook/{path}`` to the deployed webhookTrigger
+nodes that declare its path.
+
+The route table is the graph snapshot of every running or paused generation
+(``list_active_workflow_controls``). A path no generation declares is 404, a
+method none of its triggers accepts is 405, and a request that fails the
+header check of every trigger that has one is 401. Each workflow with an
+accepting trigger gets one event scoped to it, so a webhook never fires
+another workflow's trigger, and its body is never broadcast (RFC-0004 C3).
+"""
+
+from __future__ import annotations
+
+import hmac
+from dataclasses import dataclass
+from typing import Any, List, Mapping
+
+from . import WebhookTriggerParams
+from ._events import emit_webhook_received
+
+#: Request headers never passed on to a workflow, besides each trigger's own
+#: authentication header.
+_PRIVATE_HEADERS = frozenset({"authorization", "cookie", "proxy-authorization"})
+
+
+@dataclass(frozen=True)
+class _Route:
+ workflow_id: str
+ node_id: str
+ params: WebhookTriggerParams
+
+
+async def _routes(database: Any, path: str) -> List[_Route]:
+ routes: List[_Route] = []
+ if not path:
+ return routes
+ for control in await database.list_active_workflow_controls():
+ snapshot = control.graph_snapshot or {}
+ parameters = snapshot.get("parameters") or {}
+ for node in snapshot.get("nodes") or []:
+ if node.get("type") != "webhookTrigger" or (node.get("data") or {}).get("disabled"):
+ continue
+ params = WebhookTriggerParams.model_validate(parameters.get(node.get("id")) or {})
+ if params.path == path:
+ routes.append(_Route(workflow_id=control.workflow_id, node_id=node["id"], params=params))
+ return routes
+
+
+async def _authorized(database: Any, route: _Route, headers: Mapping[str, str]) -> bool:
+ if route.params.authentication != "header":
+ return True
+ # The secret stays out of snapshots and Temporal input; the saved
+ # parameters hold it. With none configured the trigger refuses.
+ saved = await database.get_node_parameters(route.node_id) or {}
+ expected = str(saved.get("header_value") or "")
+ received = str(headers.get(route.params.header_name.lower(), ""))
+ return bool(expected) and hmac.compare_digest(received.encode(), expected.encode())
+
+
+async def deliver_webhook(
+ database: Any,
+ *,
+ method: str,
+ path: str,
+ headers: Mapping[str, str],
+ query: Mapping[str, str],
+ body: str,
+ json_body: Any,
+) -> int:
+ """Deliver the request; returns the HTTP status to answer with.
+
+ ``headers`` must have lowercase names, as Starlette gives them.
+ """
+ routes = await _routes(database, path)
+ if not routes:
+ return 404
+ routes = [route for route in routes if route.params.method in ("ALL", method.upper())]
+ if not routes:
+ return 405
+ accepted = [route for route in routes if await _authorized(database, route, headers)]
+ if not accepted:
+ return 401
+
+ hidden = _PRIVATE_HEADERS | {
+ route.params.header_name.lower() for route in routes if route.params.authentication == "header"
+ }
+ webhook_data = {
+ "method": method,
+ "path": path,
+ "headers": {name: value for name, value in headers.items() if name.lower() not in hidden},
+ "query": dict(query),
+ "body": body,
+ "json": json_body,
+ }
+ for workflow_id in sorted({route.workflow_id for route in accepted}):
+ await emit_webhook_received(webhook_data, workflow_id=workflow_id)
+ return 200
+
+
+__all__ = ["deliver_webhook"]
diff --git a/server/routers/webhook.py b/server/routers/webhook.py
index 7991ca41..f969507d 100644
--- a/server/routers/webhook.py
+++ b/server/routers/webhook.py
@@ -8,7 +8,10 @@ Two dispatch paths:
and wakes a waiting canvas Run; the plugin's override emits the event
to deployed triggers.
2. **Generic webhook.** Paths no plugin claims reach ``webhookTrigger``
- nodes through ``nodes/trigger/webhook_trigger/_events``.
+ nodes through ``nodes/trigger/webhook_trigger/_routes.deliver_webhook``,
+ which answers 404 for a path no running workflow declares, 405 for a
+ method none of its triggers accepts and 401 when the header check
+ fails.
Both read the body through ``read_body_capped``, so a body larger than
``WEBHOOK_MAX_BODY_BYTES`` is refused with 413 before it reaches a
@@ -23,13 +26,17 @@ import logging
from services.events import WEBHOOK_SOURCES
from services.events.webhook import read_body_capped
-# Wave 12 B9: webhook event dispatch moved to
-# ``nodes/trigger/webhook_trigger/_events.broadcast_webhook_received``.
-# The router no longer reaches into the broadcaster directly.
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/webhook", tags=["webhook"])
+# What the generic route answers when ``deliver_webhook`` refuses a request.
+_REFUSALS = {
+ 404: "No running workflow has a webhook at this path.",
+ 405: "No webhook at this path accepts this method.",
+ 401: "Missing or wrong authentication header.",
+}
+
# Pending responses: path -> asyncio.Future (for responseNode mode)
_pending_responses: Dict[str, asyncio.Future] = {}
@@ -89,21 +96,21 @@ async def handle_webhook(path: str, request: Request):
except Exception:
pass
- webhook_data = {
- "method": request.method,
- "path": path,
- "headers": dict(request.headers),
- "query": dict(request.query_params),
- "body": body.decode("utf-8") if isinstance(body, bytes) else (body if body else ""),
- "json": json_body,
- }
-
- logger.info(f"[Webhook] Received: {request.method} /webhook/{path}")
-
- # Wave 12 B9: route through plugin _events.py wrapper.
- from nodes.trigger.webhook_trigger._events import broadcast_webhook_received
-
- await broadcast_webhook_received(webhook_data)
+ from core.container import container
+ from nodes.trigger.webhook_trigger._routes import deliver_webhook
+
+ status = await deliver_webhook(
+ container.database(),
+ method=request.method,
+ path=path,
+ headers=dict(request.headers),
+ query=dict(request.query_params),
+ body=body.decode("utf-8") if body else "",
+ json_body=json_body,
+ )
+ logger.info(f"[Webhook] {request.method} /webhook/{path} -> {status}")
+ if status != 200:
+ return JSONResponse({"status": "refused", "path": path, "error": _REFUSALS[status]}, status_code=status)
return JSONResponse(
content={"status": "received", "path": path, "message": "Webhook received and dispatched to workflow"}, status_code=200
diff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.py
index 77a1ce5b..50f78f69 100644
--- a/server/services/deployment/manager.py
+++ b/server/services/deployment/manager.py
@@ -19,6 +19,7 @@ from constants import POLLING_TRIGGER_TYPES, WORKFLOW_TRIGGER_TYPES
from services import event_waiter
from services.events.envelope import equivalent_event_types
from services.run_graph import collect_downstream_node_ids
+from services.workflow_sanitizer import sanitize_runtime_payload
from .state import DeploymentState, TriggerInfo
from .triggers import TriggerManager
@@ -899,7 +900,9 @@ class DeploymentManager:
"trigger_label": trigger_label,
"node_type": node_type,
"event_type": event_type,
- "filter_params": params,
+ # The listener's input is Temporal history; a secret parameter
+ # (a webhook's expected header value) has no use in a filter.
+ "filter_params": sanitize_runtime_payload(params),
"nodes": state.nodes,
"edges": state.edges,
"parameter_snapshot": state.parameter_snapshot,
diff --git a/server/services/event_waiter.py b/server/services/event_waiter.py
index c48135a5..f6d2abeb 100644
--- a/server/services/event_waiter.py
+++ b/server/services/event_waiter.py
@@ -182,10 +182,9 @@ def build_webhook_filter(params: Dict) -> Callable[[Dict], bool]:
webhook_path = params.get("path", "")
def matches(data: Dict) -> bool:
- event_path = data.get("path", "")
- if webhook_path and event_path != webhook_path:
- return False
- return True
+ # A trigger with no path matches nothing; it used to match every
+ # webhook sent to the instance.
+ return bool(webhook_path) and data.get("path", "") == webhook_path
return matches
diff --git a/server/services/plugin/base.py b/server/services/plugin/base.py
index 423cc785..b2ffed3b 100644
--- a/server/services/plugin/base.py
+++ b/server/services/plugin/base.py
@@ -236,9 +236,11 @@ class BaseNode:
) -> Dict[str, Any]:
return {"reset": False}
- # Wiring this node needs to run, checked before Start and import
- # (services/workflow_validator.py). Returns validator errors,
- # ``{"code", "node_id", "message"}``; none by default.
+ # Wiring and configuration this node needs to run, checked before Start
+ # and import (services/workflow_validator.py). ``graph`` holds ``nodes``,
+ # ``edges`` and the ``parameters`` the caller supplied by node id (a node
+ # may be absent). Returns validator errors, ``{"code", "node_id",
+ # "message"}``; none by default.
@classmethod
def validate_graph(cls, node_id: str, graph: Dict[str, Any]) -> Sequence[Dict[str, Any]]:
return ()
diff --git a/server/services/workflow_sanitizer.py b/server/services/workflow_sanitizer.py
index d96ad2f3..c0843b81 100644
--- a/server/services/workflow_sanitizer.py
+++ b/server/services/workflow_sanitizer.py
@@ -45,6 +45,10 @@ _BLOCKED_EXACT = frozenset(
"reasoningsignature",
"encryptedreasoning",
"encryptedcontent",
+ # webhookTrigger's expected header secret: the router reads it from
+ # the saved parameters, so it never needs to ride a snapshot or a
+ # Temporal input.
+ "headervalue",
}
)
diff --git a/server/services/workflow_validator.py b/server/services/workflow_validator.py
index 788a9ccc..085e4545 100644
--- a/server/services/workflow_validator.py
+++ b/server/services/workflow_validator.py
@@ -295,7 +295,7 @@ async def validate_workflow(
# 4. Missing credentials. Warnings (a workflow can be saved with missing
# credentials and configured later — only at force=True execute does
# it become a runtime error).
- graph = {"nodes": nodes, "edges": edges}
+ graph = {"nodes": nodes, "edges": edges, "parameters": parameters_by_id}
for n in nodes:
node_id = n.get("id")
node_type = n.get("type", "")
diff --git a/server/tests/nodes/test_webhook_trigger_routes.py b/server/tests/nodes/test_webhook_trigger_routes.py
new file mode 100644
index 00000000..62caf7cb
--- /dev/null
+++ b/server/tests/nodes/test_webhook_trigger_routes.py
@@ -0,0 +1,148 @@
+"""Webhook delivery to deployed webhookTrigger nodes (RFC-0004 C3).
+
+``deliver_webhook`` routes by the running and paused generations' snapshots:
+404 for a path none declares, 405 for a method none accepts, 401 when the
+header check fails. Each accepting workflow gets one event scoped to it, with
+authentication headers removed and nothing broadcast.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any, Dict, List
+
+import pytest
+
+from nodes.trigger.webhook_trigger import WebhookTriggerNode, WebhookTriggerParams
+from nodes.trigger.webhook_trigger import _routes
+from services import event_waiter
+from services.events import dispatch as dispatch_mod
+from services.workflow_sanitizer import sanitize_runtime_payload
+
+
+def _control(workflow_id: str, triggers: Dict[str, Dict[str, Any]], *, disabled=()):
+ nodes = [{"id": node_id, "type": "webhookTrigger", "data": {"disabled": node_id in disabled}} for node_id in triggers]
+ return SimpleNamespace(workflow_id=workflow_id, graph_snapshot={"nodes": nodes, "parameters": triggers})
+
+
+class _Database:
+ def __init__(self, controls, saved=None):
+ self.controls = controls
+ self.saved = saved or {}
+
+ async def list_active_workflow_controls(self):
+ return self.controls
+
+ async def get_node_parameters(self, node_id):
+ return self.saved.get(node_id)
+
+
+def emitted(monkeypatch) -> List[Dict[str, Any]]:
+ calls: List[Dict[str, Any]] = []
+
+ async def fake_emit(event, **kwargs):
+ calls.append({"event": event, **kwargs})
+ return event
+
+ monkeypatch.setattr(dispatch_mod, "emit", fake_emit)
+ return calls
+
+
+async def _deliver(database, *, method="POST", path="orders", headers=None):
+ return await _routes.deliver_webhook(
+ database, method=method, path=path, headers=headers or {}, query={}, body="{}", json_body={},
+ )
+
+
+async def test_a_path_no_running_workflow_declares_is_404(emitted):
+ database = _Database([_control("wf-1", {"wf-1:webhookTrigger:1": {"path": "orders"}})])
+
+ assert await _deliver(database, path="refunds") == 404
+ assert await _deliver(database, path="") == 404
+ assert emitted == []
+
+
+async def test_a_method_the_trigger_does_not_accept_is_405(emitted):
+ database = _Database([_control("wf-1", {"wf-1:webhookTrigger:1": {"path": "orders", "method": "POST"}})])
+
+ assert await _deliver(database, method="GET") == 405
+ assert emitted == []
+
+
+async def test_header_authentication_is_enforced_and_fails_closed(emitted):
+ trigger = {"path": "orders", "authentication": "header", "header_name": "X-API-Key"}
+ database = _Database([_control("wf-1", {"t1": trigger})], saved={"t1": {**trigger, "header_value": "s3cret"}})
+
+ assert await _deliver(database) == 401
+ assert await _deliver(database, headers={"x-api-key": "wrong"}) == 401
+ assert emitted == []
+
+ unconfigured = _Database([_control("wf-1", {"t1": trigger})], saved={"t1": trigger})
+ assert await _deliver(unconfigured, headers={"x-api-key": ""}) == 401
+
+
+async def test_an_accepted_request_reaches_only_its_workflow_without_its_secrets(emitted):
+ trigger = {"path": "orders", "authentication": "header", "header_name": "X-API-Key"}
+ database = _Database(
+ [_control("wf-1", {"t1": trigger}), _control("wf-2", {"t2": {"path": "other"}})],
+ saved={"t1": {**trigger, "header_value": "s3cret"}},
+ )
+
+ status = await _deliver(database, headers={
+ "x-api-key": "s3cret", "authorization": "Bearer x", "cookie": "session=1", "x-request-id": "r1",
+ })
+
+ assert status == 200
+ assert len(emitted) == 1
+ event = emitted[0]["event"]
+ assert event.workflow_id == "wf-1"
+ assert emitted[0]["broadcast"] is False
+ assert event.data["headers"] == {"x-request-id": "r1"}
+
+
+async def test_each_workflow_declaring_the_path_gets_its_own_event(emitted):
+ database = _Database([
+ _control("wf-1", {"t1": {"path": "orders"}}),
+ _control("wf-2", {"t2": {"path": "orders", "method": "ALL"}}),
+ _control("wf-3", {"t3": {"path": "orders"}}, disabled={"t3"}),
+ ])
+
+ assert await _deliver(database) == 200
+ assert sorted(call["event"].workflow_id for call in emitted) == ["wf-1", "wf-2"]
+
+
+async def test_a_workflow_whose_header_check_fails_is_left_out(emitted):
+ guarded = {"path": "orders", "authentication": "header", "header_name": "X-API-Key"}
+ database = _Database(
+ [_control("wf-1", {"t1": guarded}), _control("wf-2", {"t2": {"path": "orders"}})],
+ saved={"t1": {**guarded, "header_value": "s3cret"}},
+ )
+
+ assert await _deliver(database) == 200
+ assert [call["event"].workflow_id for call in emitted] == ["wf-2"]
+
+
+def test_a_trigger_without_a_path_matches_nothing():
+ """An empty path used to match every webhook sent to the instance."""
+ node_filter = WebhookTriggerNode().build_filter(WebhookTriggerParams(path=""))
+ waiter_filter = event_waiter.build_webhook_filter({"path": ""})
+
+ assert node_filter({"path": "orders"}) is False
+ assert waiter_filter({"path": "orders"}) is False
+ assert WebhookTriggerNode().build_filter(WebhookTriggerParams(path="orders"))({"path": "orders"}) is True
+
+
+def test_start_refuses_a_webhook_without_a_path():
+ graph = {"nodes": [], "edges": [], "parameters": {"t1": {"path": " "}, "t2": {"path": "orders"}}}
+
+ assert [error["code"] for error in WebhookTriggerNode.validate_graph("t1", graph)] == ["WEBHOOK_PATH_REQUIRED"]
+ assert WebhookTriggerNode.validate_graph("t2", graph) == []
+ # Parameters the caller did not supply are not judged.
+ assert WebhookTriggerNode.validate_graph("t3", graph) == []
+
+
+def test_the_expected_header_value_never_rides_a_snapshot():
+ assert sanitize_runtime_payload({"path": "orders", "header_name": "X-API-Key", "header_value": "s3cret"}) == {
+ "path": "orders", "header_name": "X-API-Key",
+ }
diff --git a/server/tests/routers/test_webhook.py b/server/tests/routers/test_webhook.py
index 84a0e3da..5a094b51 100644
--- a/server/tests/routers/test_webhook.py
+++ b/server/tests/routers/test_webhook.py
@@ -5,7 +5,7 @@ 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
+from unittest.mock import AsyncMock, patch
import pytest
from fastapi import FastAPI
@@ -15,6 +15,10 @@ from fastapi.testclient import TestClient
from routers.webhook import router
from services.events import WEBHOOK_SOURCES, WebhookSource, WorkflowEvent
+# Delivery to deployed webhookTrigger nodes; its own tests are in
+# tests/nodes/test_webhook_trigger_routes.py.
+_DELIVER = "nodes.trigger.webhook_trigger._routes.deliver_webhook"
+
@pytest.fixture
def client():
@@ -129,11 +133,11 @@ class TestBodyCap:
monkeypatch.setenv("WEBHOOK_MAX_BODY_BYTES", "16")
clean_registry.clear()
- with patch("nodes.trigger.webhook_trigger._events.broadcast_webhook_received") as broadcast:
+ with patch(_DELIVER, new=AsyncMock(return_value=200)) as deliver:
resp = client.post("/webhook/unclaimed", content=b"x" * 17)
assert resp.status_code == 413
- broadcast.assert_not_called()
+ deliver.assert_not_awaited()
def test_a_streamed_body_without_a_length_is_capped_by_what_arrives(self, client, clean_registry, monkeypatch):
monkeypatch.setenv("WEBHOOK_MAX_BODY_BYTES", "16")
@@ -143,11 +147,11 @@ class TestBodyCap:
yield b"x" * 10
yield b"x" * 10
- with patch("nodes.trigger.webhook_trigger._events.broadcast_webhook_received") as broadcast:
+ with patch(_DELIVER, new=AsyncMock(return_value=200)) as deliver:
resp = client.post("/webhook/unclaimed", content=chunks())
assert resp.status_code == 413
- broadcast.assert_not_called()
+ deliver.assert_not_awaited()
def test_a_registered_source_is_capped_too(self, client, clean_registry, monkeypatch):
monkeypatch.setenv("WEBHOOK_MAX_BODY_BYTES", "16")
@@ -178,11 +182,20 @@ class TestLegacyFallback:
"""An unregistered path must keep firing webhookTrigger nodes."""
clean_registry.clear()
- with patch("nodes.trigger.webhook_trigger._events.broadcast_webhook_received") as broadcast:
+ with patch(_DELIVER, new=AsyncMock(return_value=200)) as deliver:
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"}
+ deliver.assert_awaited_once()
+ assert deliver.await_args.kwargs["path"] == "unclaimed"
+ assert deliver.await_args.kwargs["json_body"] == {"hello": "world"}
+
+ @pytest.mark.parametrize("status", [401, 404, 405])
+ def test_a_refusal_is_answered_with_its_status(self, client, clean_registry, status):
+ clean_registry.clear()
+
+ with patch(_DELIVER, new=AsyncMock(return_value=status)):
+ resp = client.post("/webhook/unclaimed", json={"hello": "world"})
+
+ assert resp.status_code == status
+ assert resp.json()["status"] == "refused"
diff --git a/server/tests/test_deployment_canary_listener.py b/server/tests/test_deployment_canary_listener.py
index 453a8c6a..74eb20d6 100644
--- a/server/tests/test_deployment_canary_listener.py
+++ b/server/tests/test_deployment_canary_listener.py
@@ -346,7 +346,9 @@ class TestStartCanaryListener:
)
node = _node("wh-1", "webhookTrigger")
- listener_id = await mgr._start_canary_listener(node, "wf-abc", params={"path": "hook"})
+ listener_id = await mgr._start_canary_listener(
+ node, "wf-abc", params={"path": "hook", "authentication": "header", "header_value": "s3cret"},
+ )
# Wave 14: listener id = ``<workflow_slug>-<trigger_label>``.
# Slug falls back to workflow_id ("wf-abc") when no DB row;
@@ -359,6 +361,9 @@ class TestStartCanaryListener:
assert call["id_conflict_policy"] == WorkflowIDConflictPolicy.USE_EXISTING
assert call["task_queue"] == "machina-tasks"
assert call["args"][0]["user_id"] == "account-21"
+ # The listener's input is Temporal history: the webhook's expected
+ # header value stays out of it (the router checks it at the edge).
+ assert call["args"][0]["filter_params"] == {"path": "hook", "authentication": "header"}
# New listeners freeze the Coding runtime before later graph firings.
assert call["args"][0]["_temporal_routing_v1"] == {
"version": 1,