The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: durably admit authenticated Graph notifications before acknowledgement
Tekniume8e17493bad0
diff --git a/gateway/platforms/msgraph_webhook.py b/gateway/platforms/msgraph_webhook.pyindex 326aed18c60..1d28188f74f 100644--- a/gateway/platforms/msgraph_webhook.py+++ b/gateway/platforms/msgraph_webhook.py@@ -181,7 +181,7 @@ class MSGraphWebhookAdapter(BasePlatformAdapter):return web.Response(status=400)return web.Response(text=validation_token, content_type="text/plain")- def _ingest_notification(self, raw_notification: Any) -> str:+ async def _ingest_notification(self, raw_notification: Any) -> str:"""Classify + schedule one notification: 'accepted' | 'duplicate' | 'auth' | 'other'."""if not isinstance(raw_notification, dict):return "other"@@ -193,12 +193,12 @@ class MSGraphWebhookAdapter(BasePlatformAdapter):# retrying; legitimate Graph retries carry a valid clientState → accepted/duplicate paths.return "auth"receipt_key = f"id:{explicit_id}" if (explicit_id := str(notification.get("id") or "").strip()) else None+ if self._notification_scheduler is not None and receipt_key in self._seen_receipts:+ return "duplicate"+ await self._schedule_notification(notification, self._build_message_event(notification, receipt_key))if receipt_key is not None:- if receipt_key in self._seen_receipts:- return "duplicate"self._remember_receipt(receipt_key)self._accepted_count += 1- self._schedule_notification(notification, self._build_message_event(notification, receipt_key))return "accepted"async def _handle_notification(self, request: "web.Request") -> "web.Response":@@ -212,7 +212,11 @@ class MSGraphWebhookAdapter(BasePlatformAdapter):return web.Response(status=status)counts = {"accepted": 0, "duplicate": 0, "auth": 0, "other": 0}for raw_notification in notifications:- counts[self._ingest_notification(raw_notification)] += 1+ try:+ counts[await self._ingest_notification(raw_notification)] += 1+ except Exception:+ logger.exception("[msgraph_webhook] Notification admission failed")+ return web.Response(status=503)self._duplicate_count += counts["duplicate"]# Anything ingested OR deduped → 202 with empty body (Graph acks; no counter leak). Every item# failed auth → 403 so forged POSTs get a clear reject. Otherwise (malformed / not accepted) → 400.@@ -302,14 +306,46 @@ class MSGraphWebhookAdapter(BasePlatformAdapter):rendered = json.dumps(notification, indent=2, sort_keys=True)[:4000]return f"Microsoft Graph change notification:\n\n```json\n{rendered}\n```"- def _schedule_notification(self, notification: Dict[str, Any], event: MessageEvent) -> None:+ async def _schedule_notification(self, notification: Dict[str, Any], event: MessageEvent) -> None:scheduler = self._notification_scheduler- if scheduler is None:- coro = self.handle_message(event)- else:- coro = scheduler(notification, event)- if not asyncio.iscoroutine(coro):- return- task = asyncio.create_task(coro)- self._background_tasks.add(task)- task.add_done_callback(self._background_tasks.discard)+ if scheduler is not None:+ result = scheduler(notification, event)+ if asyncio.iscoroutine(result):+ await result+ return # Plugin-owned pipeline; never also start a gateway inference.+ await self._admit_notification(event)++ @property+ def token(self):+ return self._client_state++ async def _admit_notification(self, event):+ # Only _ingest_notification reaches this after resource + clientState gates;+ # the HTTP handler additionally owns source-IP and body-size authorization.+ # Reuse the existing private automation envelope: public native admission+ # continues to reject internal events and arbitrary metadata.+ from datetime import datetime, timezone+ from gateway.platforms.webhook_ingress import producer_scope+ from gateway.session_ingress_context import capture_provenance+ from hermes_state_runtime import admit_session_input, RuntimeStoreError++ async with producer_scope(self, event) as authority:+ authority._require_admission_open()+ provenance = capture_provenance(authority.runner, event)+ if provenance is None:+ raise RuntimeStoreError('permission_denied')+ ref = authority.register(event.source)+ route = authority.sessions[ref.session_id].route+ source = event.source.to_dict()+ source['is_bot'] = event.source.is_bot+ envelope = {'source': source, 'route': route, 'provenance': provenance,+ 'timestamp': datetime.fromtimestamp(0, timezone.utc).isoformat(),+ 'event': {'message_id': event.message_id},+ 'automation': {'identity': event.message_id, 'owner': ref.session_id}}+ row = admit_session_input(authority.db, epoch=authority.epoch,+ principal_id='msgraph:' + route, session_id=ref.session_id,+ request_id=event.message_id, payload={'text': event.text, 'native_text_v1': envelope})+ event._gateway_accepted = True+ authority._publish_pending(ref)+ authority._schedule(ref)+ return authority._receipt(row)diff --git a/tests/gateway/test_msgraph_authority.py b/tests/gateway/test_msgraph_authority.pynew file mode 100644index 00000000000..92e032f62b1--- /dev/null+++ b/tests/gateway/test_msgraph_authority.py@@ -0,0 +1,97 @@+"""Graph boundary uses the canonical internal queue, not a background ACK."""+import asyncio+import json+import os+from pathlib import Path+import subprocess+import sys+++def test_graph_boundary_commits_only_valid_notifications(tmp_path):+ result = subprocess.run([sys.executable, __file__], env=dict(os.environ, HERMES_HOME=str(tmp_path)),+ capture_output=True, text=True, timeout=90)+ assert result.returncode == 0, result.stdout + result.stderr+ print((tmp_path / 'graph-receipt.json').read_text())+++async def probe(peer):+ import aiohttp+ import ipaddress+ from gateway.config import Platform, PlatformConfig+ from gateway.platforms.msgraph_webhook import MSGraphWebhookAdapter+ from gateway.run import GatewayRunner+ from gateway.session_authority import initialize_session_authority+ from gateway.session_envelope import restore_native+ from hermes_state_runtime import list_session_admissions+ runner = GatewayRunner()+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='graph-test')+ adapter = MSGraphWebhookAdapter(PlatformConfig(enabled=True, extra={+ 'host': '127.0.0.1', 'port': 0, 'client_state': 'owned-state',+ 'accepted_resources': ['users/owned/messages'], 'prompt': 'BLOCK_FIFO'}))+ runner.adapters[Platform.MSGRAPH_WEBHOOK] = adapter+ runner._wire_adapter_handlers(adapter)+ assert await adapter.connect()+ port = next(iter(adapter._runner.sites))._server.sockets[0].getsockname()[1]+ url = f'http://127.0.0.1:{port}{adapter._webhook_path}'+ notification = {'id': 'graph-1', 'subscriptionId': 'owned-sub',+ 'resource': 'users/owned/messages/one', 'clientState': 'owned-state'}+ def rows():+ return [r for sid in authority.sessions for r in list_session_admissions(+ authority.db, session_id=sid, pending_only=False)]+ try:+ async with aiohttp.ClientSession() as client:+ for change, status in [({'clientState': 'wrong'}, 403), ({'resource': 'users/foreign'}, 400)]:+ response = await client.post(url, json={'value': [{**notification, **change}]})+ assert response.status == status and not rows()+ adapter._allowed_source_networks = [ipaddress.ip_network('192.0.2.0/24')]+ denied = await client.post(url, json={'value': [notification]})+ assert denied.status == 403 and not rows()+ adapter._allowed_source_networks = []+ authority.db._execute_write(lambda conn: conn.execute("CREATE TRIGGER fail_graph BEFORE INSERT ON session_admissions BEGIN SELECT RAISE(ABORT, 'owned storage failure'); END"))+ response = await client.post(url, json={'value': [notification]})+ assert response.status == 503, response.status+ assert not rows() and not peer.requests+ authority.db._execute_write(lambda conn: conn.execute('DROP TRIGGER fail_graph'))+ response = await client.post(url, json={'value': [notification]})+ assert response.status == 202 and len(rows()) == 1+ assert restore_native(rows()[0]['payload'], runner).internal is True+ assert await asyncio.to_thread(peer.blocked.wait, 10)+ adapter._seen_receipts.clear()+ duplicate = await client.post(url, json={'value': [notification]})+ assert duplicate.status == 202 and len(rows()) == 1+ peer.release.set()+ async with asyncio.timeout(25):+ while rows()[0]['status'] != 'terminal':+ await asyncio.sleep(.01)+ assert len(peer.requests) == 1+ # A plugin scheduler owns this route exclusively; do not also infer.+ calls = []+ async def scheduler(raw, event):+ calls.append(raw['id'])+ adapter.set_notification_scheduler(scheduler)+ response = await client.post(url, json={'value': [{**notification, 'id': 'plugin-only'}]})+ assert response.status == 202 and calls == ['plugin-only']+ assert len(rows()) == len(peer.requests) == 1+ Path(os.environ['HERMES_HOME'], 'graph-receipt.json').write_text(json.dumps({+ 'admissions': len(rows()), 'inferences': len(peer.requests), 'boundary_controls': True,+ 'internal': True, 'storage_retry': True, 'scheduler_exclusive': True}))+ finally:+ peer.release.set()+ await adapter.disconnect()+++if __name__ == '__main__':+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))+ sys.path.insert(1, str(Path(__file__).parent))+ import test_webhook_authority as harness+ import traceback+ harness.probe = probe+ status = 0+ try:+ harness.main()+ except BaseException:+ traceback.print_exc()+ status = 1+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(status)diff --git a/tests/gateway/test_msgraph_webhook.py b/tests/gateway/test_msgraph_webhook.pyindex 518f431ad23..b9471a1b8bf 100644--- a/tests/gateway/test_msgraph_webhook.py+++ b/tests/gateway/test_msgraph_webhook.py@@ -191,6 +191,7 @@ class TestMSGraphNotifications:@pytest.mark.anyioasync def test_resource_patterns_accept_leading_slash(self):adapter = _make_adapter(accepted_resources=["/communications/onlineMeetings"])+ adapter.set_notification_scheduler(lambda notification, event: None)payload = {"value": [{@@ -230,6 +231,7 @@ class TestMSGraphSourceIPAllowlist:async def test_loopback_bind_without_allowlist_still_accepts_local_requests(self):"""Loopback-only listeners may rely on local proxying/tunnels instead of CIDRs."""adapter = _make_adapter(host="127.0.0.1", allowed_source_cidrs=[])+ adapter.set_notification_scheduler(lambda notification, event: None)payload = {"value": [{