The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: boot authenticated session authority in ordinary gateway
Tekniumc3bf62ebd392
diff --git a/gateway/run_api.py b/gateway/run_api.pyindex c1474dd06da..9f8d477af6a 100644--- a/gateway/run_api.py+++ b/gateway/run_api.py@@ -24,7 +24,7 @@ async def start_gateway_api(runner, *, host: str = "127.0.0.1", port: int = 0) -from hermes_cli import web_server as web# Existing routers/auth helpers share one process-local app. Never rebind it- # underneath another listener. Multiplex profiles use this same authority.+ # underneath another listener. Each authority is bound to its own profile DB.if getattr(web.app.state, "gateway_runner", None) is not None:raise RuntimeError("gateway API already started")web._configure_auth_gate(host, False, None, None)@@ -41,6 +41,10 @@ async def start_gateway_api(runner, *, host: str = "127.0.0.1", port: int = 0) -listener.close()raise+ # Wrap this server's ASGI graph, never the module-global app/router.+ if not config.loaded:+ config.load()+ config.loaded_app = GatewayRuntimeAPI(config.loaded_app, runner, web.app)web.app.state.gateway_runner = runnerweb.app.state.session_authority = getattr(runner, "session_authority", None)web.app.state.bound_host = host@@ -83,3 +87,53 @@ async def stop_gateway_api(handle: GatewayAPIHandle) -> None:"""Drain sockets without stopping the session authority or taking signals."""handle.server.should_exit = Trueawait asyncio.shield(handle.task)+++class GatewayRuntimeAPI:+ """Redeem private local tickets at the existing WS subprotocol boundary.++ Other credentials and HTTP routes retain the complete dashboard gate. Local+ bootstrap never grants an exposure/worker ticket interactive permissions.+ """+ def __init__(self, app, runner, web_app):+ self.app, self.runner, self.web_app = app, runner, web_app++ async def __call__(self, scope, receive, send):+ descriptor = getattr(self.runner, 'session_runtime_descriptor', None)+ if scope['type'] not in {'http', 'websocket'} or descriptor is None:+ return await self.app(scope, receive, send)+ if descriptor['state'] != 'ready' or self.runner._draining:+ if scope['type'] == 'websocket':+ await send({'type': 'websocket.close', 'code': 1013})+ else:+ from starlette.responses import JSONResponse+ await JSONResponse({'error': 'gateway_not_ready', 'state': descriptor['state']},+ status_code=503)(scope, receive, send)+ return+ if scope['type'] != 'websocket' or scope['path'] != '/api/ws':+ return await self.app(scope, receive, send)+ from starlette.websockets import WebSocket+ from hermes_cli.web_server_chat import (+ _gateway_ws_ticket_from_subprotocol, _ws_request_is_allowed,+ )+ scope['app'] = self.web_app+ ws = WebSocket(scope, receive, send)+ ticket, reason = _gateway_ws_ticket_from_subprotocol(ws)+ if reason == 'none':+ return await self.app(scope, receive, send)+ from hermes_cli import web_server as web+ if (reason != 'ok' or not web._DASHBOARD_EMBEDDED_CHAT_ENABLED+ or not _ws_request_is_allowed(ws) or ws.headers.get('origin')+ or not ws.client or ws.client.host not in {'127.0.0.1', '::1'}):+ await ws.close(code=4403)+ return+ try:+ grant = self.runner.session_ticket_store.redeem(+ ticket, profile_id=self.runner.session_authority.profile_id,+ purpose='interactive')+ except PermissionError:+ await ws.close(code=4401)+ return+ from tui_gateway.ws import handle_ws+ await handle_ws(ws, auth_identity={'user_id': grant['subject'], 'provider': 'local'},+ subprotocol='hermes-gateway-v1')diff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.pyindex 944b1953f72..da15c382c47 100644--- a/gateway/run_bootstrap.py+++ b/gateway/run_bootstrap.py@@ -224,19 +224,7 @@ async def _start_gateway_start_control_socket(runner):# failure only means consumers fall back to the process-scan/state-file layer, exactly as before# this feature. See #92091.from gateway.control_socket import GatewayControlServer, build_identify_payload- from gateway.runtime_bootstrap import TicketStore- from gateway.runtime_ownership import process_ownership- import uuid- descriptor = {- "instance_id": uuid.uuid4().hex, "runtime_protocol": 1,- "state": "starting", "capabilities": [],- "served_profiles": [{"profile_id": str(home), "home": str(home)}- for home in process_ownership.homes],- }- runner.session_runtime_descriptor = descriptor- runner.session_ticket_store = TicketStore(- descriptor["instance_id"],- frozenset(item["profile_id"] for item in descriptor["served_profiles"]))+ descriptor = runner.session_runtime_descriptordef _identify_runtime():payload = build_identify_payload()@@ -464,11 +452,14 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =return False_control_server = None+ runner = None_planned_stop_watcher_stop = Nonetry:_start_gateway_configure_logging(verbosity)runner = GatewayRunner(resolved_config)+ from gateway.run_runtime import initialize_gateway_runtime+ await initialize_gateway_runtime(runner)# Multiplex: swap the launch-home file handlers for per-profile routers so each profile's records# land in its own logs/. Must run after the runner resolved (possibly None) config and setup_logging.# See #82936.@@ -527,6 +518,10 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =# Right after the PID claim (which makes us authoritative); non-fatal — consumers fall back to scan._control_server = await _start_gateway_start_control_socket(runner)+ if _control_server is None:+ raise RuntimeError("gateway session bootstrap control listener unavailable")+ from gateway.run_runtime import start_gateway_runtime_api+ await start_gateway_runtime_api(runner)def _lifecycle_record_startup() -> None:# Report if the previous life died uncleanly (SIGKILL / OOM / VM death), then claim the@@ -590,6 +585,8 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =_start_gateway_start_cron_and_housekeeping(runner))# READY only once adapters, cron and housekeeping run; missing systemd state just disables watchdog.+ from gateway.run_runtime import publish_gateway_runtime_ready+ publish_gateway_runtime_ready(runner)runner._start_systemd_watchdog()await runner.wait_for_shutdown()@@ -599,6 +596,12 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =_planned_stop_watcher_stop, _planned_stop_watcher_thread, _signal_initiated_shutdown)finally:+ if runner is not None:+ from gateway.run_runtime import drain_gateway_runtime+ await drain_gateway_runtime(runner)+ # Startup may have opened adapters before an exception. The same+ # stop path owns their writers and DB handles on every exit.+ await runner.stop()if _planned_stop_watcher_stop is not None:_planned_stop_watcher_stop.set()if _control_server is not None:diff --git a/gateway/run_runtime.py b/gateway/run_runtime.pynew file mode 100644index 00000000000..7b8620ed7b4--- /dev/null+++ b/gateway/run_runtime.py@@ -0,0 +1,73 @@+"""Session-runtime lifecycle owned by the ordinary gateway bootstrap."""+from __future__ import annotations++import asyncio+from pathlib import Path+import uuid+++async def initialize_gateway_runtime(runner):+ from gateway.runtime_bootstrap import TicketStore+ from gateway.runtime_ownership import process_ownership+ from gateway.session_authority import initialize_session_authority+ from hermes_constants import get_hermes_home++ home = get_hermes_home().resolve()+ # One SessionAuthority currently binds exactly one DB. Never give a+ # secondary home's principal access to the launch home's authority.+ if getattr(runner.config, 'multiplex_profiles', False):+ raise RuntimeError('shared gateway bootstrap does not yet support multiplex profile authorities')+ if not process_ownership.owns(home):+ raise RuntimeError('session authority requires reserved profile ownership')+ db = getattr(runner._session_db, '_db', runner._session_db)+ if db is None or Path(db.db_path).resolve().parent != home:+ raise RuntimeError('session authority database does not belong to the reserved profile')+ descriptor = {+ 'instance_id': uuid.uuid4().hex, 'runtime_protocol': 1,+ 'state': 'starting', 'capabilities': [],+ 'served_profiles': [{'profile_id': str(home), 'home': str(home)}],+ }+ runner.session_runtime_descriptor = descriptor+ authority = await initialize_session_authority(+ runner, profile_id=str(home), instance_id=descriptor['instance_id'])+ descriptor['authority_epoch'] = authority.epoch+ runner.session_ticket_store = TicketStore(descriptor['instance_id'], frozenset({str(home)}))+++async def start_gateway_runtime_api(runner):+ from gateway.run_api import start_gateway_api+ runner.session_api = await start_gateway_api(runner)+ runner.session_runtime_descriptor['api_origin'] = runner.session_api.api_origin+++def publish_gateway_runtime_ready(runner):+ descriptor = runner.session_runtime_descriptor+ if runner.session_api.task.done() or not runner._running or runner._draining:+ raise RuntimeError('gateway stopped before session API readiness')+ descriptor.update(state='ready', capabilities=[+ 'session-authority-v1', 'durable-admission-v1', 'event-replay-v1'])+++async def drain_gateway_runtime(runner):+ """Withdraw admission before any await; close sockets before DB teardown."""+ from gateway.run_api import stop_gateway_api+ descriptor = getattr(runner, 'session_runtime_descriptor', None)+ if descriptor is None:+ return+ descriptor.update(state='draining', capabilities=[])+ store = getattr(runner, 'session_ticket_store', None)+ if store is not None:+ store.revoke()+ handle = getattr(runner, 'session_api', None)+ if handle is not None:+ await stop_gateway_api(handle)+++async def settle_gateway_runtime(runner):+ """Keep authority tasks alive until their last durable settlement write."""+ authority = getattr(runner, 'session_authority', None)+ if authority is None:+ return+ tasks = [live.task for live in authority.sessions.values() if live.task is not None]+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex 3b16f92be14..dc19b2dbaf4 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -1552,6 +1552,8 @@ class GatewayShutdownMixin:self._running = Falseself._clear_plugin_message_injector()self._draining = True+ from gateway.run_runtime import drain_gateway_runtime+ await drain_gateway_runtime(self)# getattr-guards: shutdown-path test doubles may lack the room worker / systemd watchdog.stop_room_worker = getattr(self, "_stop_hosted_room_worker", None)if callable(stop_room_worker):@@ -1887,6 +1889,8 @@ class GatewayShutdownMixin:await GatewayRunner._stop_drain_active_work(self, timeout, ctx)if ctx.timed_out:await GatewayRunner._stop_interrupt_remaining_work(self, ctx)+ from gateway.run_runtime import settle_gateway_runtime+ await settle_gateway_runtime(self)await GatewayRunner._stop_finalize_agents_and_adapters(self, ctx)GatewayRunner._stop_release_runtime_state(self, ctx)GatewayRunner._stop_quiesce_and_close_session_dbs(self, timeout, ctx)diff --git a/tests/gateway/test_normal_runtime_boot.py b/tests/gateway/test_normal_runtime_boot.pynew file mode 100644index 00000000000..4189cb51da2--- /dev/null+++ b/tests/gateway/test_normal_runtime_boot.py@@ -0,0 +1,98 @@+"""The ordinary no-platform process must earn its bootstrap readiness."""+import asyncio+import json+import os+from pathlib import Path+import signal+import socket+import subprocess+import sys+import time++import pytest+from websockets.asyncio.client import connect+from websockets.exceptions import InvalidStatus+++def control(home, verb, params=None):+ pointer = home / 'gateway.sock.path'+ path = pointer.read_text().strip() if pointer.exists() else str(home / 'gateway.sock')+ with socket.socket(socket.AF_UNIX) as peer:+ peer.settimeout(2)+ peer.connect(path)+ peer.sendall(json.dumps({'protocol': 1, 'id': 1, 'verb': verb,+ 'params': params or {}}).encode() + b'\n')+ with peer.makefile('rb') as stream:+ reply = json.loads(stream.readline())+ assert reply['ok'], reply+ return reply['result']+++async def handshake(home, descriptor):+ url = descriptor['api_origin'].replace('http:', 'ws:') + '/api/ws'+ with pytest.raises(InvalidStatus):+ async with connect(url):+ pass+ binding = {'profile_id': str(home.resolve()), 'instance_id': descriptor['instance_id'],+ 'purpose': 'interactive'}+ grant = control(home, 'session-ticket', binding)+ protocols = ['hermes-gateway-v1', 'hermes-gateway-ticket.' + grant['ticket']]+ async with connect(url, subprotocols=protocols) as ws:+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': 7, 'method': 'session.resume',+ 'params': {'session_id': 'not-registered'}}))+ while True:+ reply = json.loads(await asyncio.wait_for(ws.recv(), 10))+ if reply.get('id') == 7:+ break+ assert reply['error']['message'] == 'not_found', reply+ assert ws.subprotocol == 'hermes-gateway-v1'+ with pytest.raises(InvalidStatus):+ async with connect(url, subprotocols=protocols):+ pass++[email protected]_only+def test_normal_entrypoint_earns_authenticated_authority_readiness(tmp_path):+ home = tmp_path / 'state'+ home.mkdir(mode=0o700)+ user = tmp_path / 'user'+ user.mkdir()+ (home / 'config.yaml').write_text('gateway:\n multiplex_profiles: false\nauxiliary:\n title_generation:\n enabled: false\n')+ root = Path(__file__).resolve().parents[2]+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ PYTHONPATH=str(root), PYTHONUNBUFFERED='1')+ with (tmp_path / 'gateway.log').open('w+') as log:+ process = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=root, env=env,+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)+ descriptor = {}+ try:+ deadline = time.monotonic() + 35+ while process.poll() is None and time.monotonic() < deadline:+ try:+ descriptor = control(home, 'identify')+ if descriptor.get('state') == 'ready':+ break+ except (OSError, ValueError):+ pass+ time.sleep(.1)+ log.flush()+ log.seek(0)+ assert descriptor.get('state') == 'ready', (descriptor, log.read())+ assert descriptor['authority_epoch'] > 0+ assert descriptor['served_profiles'] == [{'profile_id': str(home), 'home': str(home)}]+ assert 'session-authority-v1' in descriptor['capabilities']+ asyncio.run(handshake(home, descriptor))+ process.send_signal(signal.SIGINT)+ assert process.wait(timeout=20) == 0+ assert not (home / 'gateway.pid').exists()+ assert not (home / 'gateway.sock').exists()+ print(json.dumps({k: descriptor[k] for k in ('instance_id', 'authority_epoch', 'state', 'capabilities')}))+ finally:+ if process.poll() is None:+ process.terminate()+ try:+ process.wait(timeout=15)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)