The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): scope webhook delivery identities
FroRaut30f556d094db
diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.pyindex 1aab5959a41..e7d4f6273d9 100644--- a/gateway/platforms/webhook.py+++ b/gateway/platforms/webhook.py@@ -22,6 +22,7 @@ import subprocessimport timefrom collections import dequefrom contextlib import nullcontext, suppress+from dataclasses import dataclassfrom typing import Any, Deque, Dict, List, Optionaltry:@@ -69,6 +70,29 @@ _REPO_RE = re.compile(r"[A-Za-z0-9._-]+/[A-Za-z0-9._-]+")_GH_TOKEN_VARS = ("GH_TOKEN", "GITHUB_TOKEN")+@dataclass(frozen=True)+class _WebhookDeliveryIdentity:+ """Collision-free identity for one provider delivery on one routed webhook route."""++ profile: str+ route: str+ delivery_id: str++ @classmethod+ def from_parts(cls, profile: Optional[str], route: str, delivery_id: str) -> "_WebhookDeliveryIdentity":+ return cls(profile=profile or "default", route=route, delivery_id=delivery_id)++ @property+ def session_chat_id(self) -> str:+ # A versioned canonical JSON tuple avoids delimiter ambiguity while keeping the chat id safe+ # for session-key persistence even when provider-controlled fields contain ':' or '/'.+ payload = json.dumps(+ (self.profile, self.route, self.delivery_id), ensure_ascii=False, separators=(",", ":")+ ).encode("utf-8")+ token = base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=")+ return f"webhook:v2:{token}"++def _is_loopback_host(host: Optional[str]) -> bool:"""True when `host` binds only to the local machine (falsy → non-loopback: usually a public default bind)."""return bool(host) and host.strip().lower() in _LOOPBACK_HOSTS@@ -182,8 +206,9 @@ class WebhookAdapter(BasePlatformAdapter):self._delivery_info_created: Dict[str, float] = {}self._delivery_info_order: Deque[tuple[float, str]] = deque()self.gateway_runner = None # set externally; needed for cross-platform delivery- # Idempotency: TTL cache of recently processed delivery IDs.- self._seen_deliveries: Dict[str, float] = {}+ # Idempotency is scoped to the authenticated route and routed profile: provider delivery+ # IDs are not globally unique across unrelated webhook endpoints.+ self._seen_deliveries: Dict[_WebhookDeliveryIdentity, float] = {}self._idempotency_ttl: int = 3600 # 1 hourself._seen_deliveries_next_prune_at: float = 0.0self._rate_counts: Dict[str, Deque[float]] = {} # per-route hit timestamps in a fixed window@@ -258,8 +283,8 @@ class WebhookAdapter(BasePlatformAdapter):async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None,metadata: Optional[Dict[str, Any]] = None) -> SendResult:- """Deliver the agent's response to the destination stored for ``chat_id``- (``webhook:{route}:{delivery_id}``) — read with ``.get()``, never popped."""+ """Deliver the agent's response to the destination stored for its opaque ``chat_id`` —+ read with ``.get()``, never popped."""# Autonomous lane (no human reader): the loose marker matcher shared with cron (marker on its own# first/last line), because models add a sentence explaining why they stayed quiet, which the# interactive exact-match rule would deliver.@@ -313,13 +338,13 @@ class WebhookAdapter(BasePlatformAdapter):window.append(now)return True- def _record_delivery_id(self, delivery_id: str, now: float) -> bool:- """Return True when this delivery should be processed."""- if (seen_at := self._seen_deliveries.get(delivery_id)) is not None and now - seen_at < self._idempotency_ttl:+ def _record_delivery_id(self, identity: _WebhookDeliveryIdentity, now: float) -> bool:+ """Return True when this route/profile-qualified delivery should be processed."""+ if (seen_at := self._seen_deliveries.get(identity)) is not None and now - seen_at < self._idempotency_ttl:return Falseif seen_at is not None:- self._seen_deliveries.pop(delivery_id, None)- self._seen_deliveries[delivery_id] = now+ self._seen_deliveries.pop(identity, None)+ self._seen_deliveries[identity] = nowif len(self._seen_deliveries) > max(self._rate_limit * 2, 128):self._prune_seen_deliveries(now)return True@@ -618,8 +643,9 @@ class WebhookAdapter(BasePlatformAdapter):delivery_id = headers.get("X-GitHub-Delivery", headers.get("svix-id", headers.get("webhook-id", headers.get("X-Request-ID", str(int(time.time() * 1000))))))now = time.time() # idempotency: skip duplicate deliveries (webhook retries)- if not self._record_delivery_id(delivery_id, now):- logger.info("[webhook] Skipping duplicate delivery %s", delivery_id)+ delivery_identity = _WebhookDeliveryIdentity.from_parts(profile, route_name, delivery_id)+ if not self._record_delivery_id(delivery_identity, now):+ logger.info("[webhook] Skipping duplicate delivery %s on route %s", delivery_id, route_name)return web.json_response({"status": "duplicate", "delivery_id": delivery_id}, status=200)if route_config.get("cron_job"):return self._handle_cron_trigger(prompt, route_config, route_name, event_type, delivery_id, profile)@@ -648,8 +674,8 @@ class WebhookAdapter(BasePlatformAdapter):def _spawn_agent_run(self, payload: Any, prompt: str, delivery_id: str, now: float, *, route_config: dict,route_name: str, profile, event_type: str) -> "asyncio.Task":"""Record delivery info and fire the agent run (shared by the immediate and coalesced paths)."""- # delivery_id in the session key → concurrent webhooks on one route get independent runs.- session_chat_id = f"webhook:{route_name}:{delivery_id}"+ identity = _WebhookDeliveryIdentity.from_parts(profile, route_name, delivery_id)+ session_chat_id = identity.session_chat_id# ``profile`` rides along so the reply leg (``send`` → ``_deliver_cross_platform``) egresses through# THIS profile's adapter, home channel and secrets — not the first profile that has the platform.self._delivery_info[session_chat_id] = {@@ -895,7 +921,7 @@ class WebhookAdapter(BasePlatformAdapter):thread_id: Optional[str]) -> None:"""Best-effort mirror of a delivered response into the TARGET chat's session transcript, so afollow-up there ("so he's out?") sees what the webhook run just told the user. Without this the- text only lives in the ephemeral ``webhook:<route>:<delivery_id>`` session and the target chat's+ text only lives in the ephemeral opaque per-delivery webhook session and the target chat'sagent has no idea it sent anything. Same path and USER-role convention as cron briefs(``cron.scheduler_delivery._maybe_mirror_cron_delivery``, #2221): the text is not the targetsession's agent speaking, and a labelled user turn merges safely on strict-alternation providers.diff --git a/tests/gateway/test_webhook_adapter.py b/tests/gateway/test_webhook_adapter.pyindex 7cb9712f706..04f466acf1b 100644--- a/tests/gateway/test_webhook_adapter.py+++ b/tests/gateway/test_webhook_adapter.py@@ -535,6 +535,32 @@ class TestIdempotency:data = await resp2.json()assert data["status"] == "duplicate"+ @pytest.mark.asyncio+ async def test_delivery_id_is_scoped_to_authenticated_route(self):+ """Provider IDs deduplicate retries for one route, not unrelated authenticated routes."""+ routes = {+ "alpha": {"secret": _INSECURE_NO_AUTH, "prompt": "alpha"},+ "beta": {"secret": _INSECURE_NO_AUTH, "prompt": "beta"},+ }+ adapter = _make_adapter(routes=routes)+ adapter.handle_message = AsyncMock()++ app = _create_app(adapter)+ headers = {"X-GitHub-Delivery": "provider-delivery-1"}+ async with TestClient(TestServer(app)) as cli:+ alpha = await cli.post("/webhooks/alpha", json={"route": "alpha"}, headers=headers)+ beta = await cli.post("/webhooks/beta", json={"route": "beta"}, headers=headers)+ alpha_retry = await cli.post("/webhooks/alpha", json={"route": "alpha"}, headers=headers)++ assert (alpha.status, (await alpha.json())["status"]) == (202, "accepted")+ assert (beta.status, (await beta.json())["status"]) == (202, "accepted")+ assert (alpha_retry.status, (await alpha_retry.json())["status"]) == (200, "duplicate")++ await asyncio.sleep(0)+ assert adapter.handle_message.await_count == 2+ sources = {call.args[0].source.user_id for call in adapter.handle_message.await_args_list}+ assert sources == {"webhook:alpha", "webhook:beta"}+# ===================================================================# Rate limiting@@ -658,6 +684,62 @@ class TestSessionIsolation:ids = {ev.source.chat_id for ev in captured_events}assert len(ids) == 2, "Each delivery must have a unique session chat_id"+ @pytest.mark.asyncio+ async def test_delivery_tuple_is_an_unambiguous_session_identity(self):+ """Route, provider delivery ID, and profile form one collision-free identity."""+ adapter = _make_adapter()+ captured_events = []++ async def _capture(event):+ captured_events.append(event)++ def _spawn(prompt, delivery_id, route, profile, deliver, chat_id, now):+ return adapter._spawn_agent_run(+ {"target": profile},+ prompt,+ delivery_id,+ now,+ route_config={"deliver": deliver, "deliver_extra": {"chat_id": chat_id}},+ route_name=route,+ profile=profile,+ event_type="push",+ )++ adapter.handle_message = _capture+ await asyncio.gather(+ _spawn("high prompt", "external:d1", "build", "shared-profile", "telegram", "high-chat", 100.0),+ _spawn("low prompt", "d1", "build:external", "shared-profile", "discord", "low-chat", 101.0),+ _spawn("other prompt", "external:d1", "build", "other-profile", "slack", "other-chat", 102.0),+ )++ events = {event.text: event for event in captured_events}+ high, low, other = (events[prompt] for prompt in ("high prompt", "low prompt", "other prompt"))+ assert len({high.source.chat_id, low.source.chat_id, other.source.chat_id}) == 3+ assert (high.source.profile, high.source.user_id) == ("shared-profile", "webhook:build")+ assert (low.source.profile, low.source.user_id) == ("shared-profile", "webhook:build:external")+ assert (other.source.profile, other.source.user_id) == ("other-profile", "webhook:build")+ assert adapter._delivery_info[high.source.chat_id] == {+ "deliver": "telegram",+ "profile": "shared-profile",+ "deliver_extra": {"chat_id": "high-chat"},+ "route": "build",+ "mirror": False,+ }+ assert adapter._delivery_info[low.source.chat_id] == {+ "deliver": "discord",+ "profile": "shared-profile",+ "deliver_extra": {"chat_id": "low-chat"},+ "route": "build:external",+ "mirror": False,+ }+ assert adapter._delivery_info[other.source.chat_id] == {+ "deliver": "slack",+ "profile": "other-profile",+ "deliver_extra": {"chat_id": "other-chat"},+ "route": "build",+ "mirror": False,+ }+# ===================================================================# Silence-marker suppression@@ -896,9 +978,9 @@ class TestCrossPlatformDeliveryMirror:resp = await cli.post(f"/webhooks/{route}", json={"a": 1}, headers={"X-Request-ID": route})assert resp.status == 202self._attach_target(adapter)+ deliveries = {delivery["route"]: delivery for delivery in adapter._delivery_info.values()}for route in routes:- delivery = adapter._delivery_info[f"webhook:{route}:{route}"]- assert (await adapter._deliver_cross_platform("telegram", "hi", delivery)).success is True+ assert (await adapter._deliver_cross_platform("telegram", "hi", deliveries[route])).success is Trueassert self._transcript(default_home, "dm-default") == []diff --git a/tests/gateway/test_webhook_integration.py b/tests/gateway/test_webhook_integration.pyindex 4895f4638d6..7e1cccf9310 100644--- a/tests/gateway/test_webhook_integration.py+++ b/tests/gateway/test_webhook_integration.py@@ -138,7 +138,8 @@ class TestGitHubPRWebhook:assert "Add webhook adapter" in event.textassert event.source.chat_type == "webhook"assert event.source.platform == Platform.WEBHOOK- assert "github-pr" in event.source.chat_id+ assert event.source.user_id == "webhook:github-pr"+ assert event.source.chat_id in adapter._delivery_infoassert event.message_id == "gh-delivery-001"@@ -185,9 +186,9 @@ class TestCrossPlatformDelivery:)assert resp.status == 202- # The adapter should have stored delivery info- chat_id = "webhook:alerts:alert-001"- assert chat_id in adapter._delivery_info+ # The adapter should have stored delivery info under the event's opaque session identity.+ assert len(adapter._delivery_info) == 1+ chat_id = next(iter(adapter._delivery_info))# Now call send() as if the agent has finishedresult = await adapter.send(chat_id, "I've acknowledged the alert.")