The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api): adopt pre-binding API sessions under the caller's declared key
Teknium42bee65cec84
diff --git a/gateway/session_api.py b/gateway/session_api.pyindex 5f945f1ff15..ce7320f4bdf 100644--- a/gateway/session_api.py+++ b/gateway/session_api.py@@ -16,7 +16,13 @@ def declared_api_session(db, key):with db._read_ctx() as conn:row = conn.execute('SELECT value FROM state_meta WHERE key=?',(_DECLARED_PREFIX + key,)).fetchone()- return row[0] if row else None+ if row:+ return row[0]+ # Earlier releases kept no declared-key registry: the declared key itself sat in+ # ``sessions.session_key`` (#139835). The pre-binding lookup finds that conversation, and+ # ``bind_api_steps`` adopts it under the same key, so later requests hit the registry.+ legacy = db.find_latest_gateway_session_for_peer(source='api_server', session_key=key)+ return legacy['id'] if legacy else Nonedef _served_profile(authority):@@ -86,14 +92,19 @@ async def run_steps_off_loop(authority, steps, *, orphaned=None):raise-def bind_api_session(authority, session_id, *, hosted_dispatch=None, declared_key=None):+def bind_api_session(authority, session_id, *, hosted_dispatch=None, declared_key=None, caller_key=None):"""Only the authenticated API edge may reserve an API source; never public RPC."""return run_steps(bind_api_steps(authority, session_id, hosted_dispatch=hosted_dispatch,- declared_key=declared_key))+ declared_key=declared_key, caller_key=caller_key))-def bind_api_steps(authority, session_id, *, hosted_dispatch=None, declared_key=None):- """``bind_api_session`` as write steps (``run_steps``): the binding transaction is yielded."""+def bind_api_steps(authority, session_id, *, hosted_dispatch=None, declared_key=None, caller_key=None):+ """``bind_api_session`` as write steps (``run_steps``): the binding transaction is yielded.++ ``caller_key`` is this request's validated ``X-Hermes-Session-Key`` even when an explicit+ session id selected the conversation (``declared_key`` is set only when the key selected it).+ It is used solely to adopt a row an earlier release stamped with that same key; it is never+ registered as the conversation's declared key."""authority._require_admission_open()if not isinstance(session_id, str) or not session_id or _is_path_unsafe(session_id):raise RuntimeStoreError('invalid_params')@@ -160,10 +171,23 @@ def bind_api_steps(authority, session_id, *, hosted_dispatch=None, declared_key=raise RuntimeStoreError('admission_conflict')if conn.execute('SELECT 1 FROM sessions WHERE title=? AND id!=?', (title, session_id)).fetchone():raise RuntimeStoreError('admission_conflict')- # Earlier API releases stored the caller-declared key directly on the session row.- # The declared-key registry above proves that this caller still owns that legacy value.- if row is not None and row['session_key'] not in (None, '', route, declared_key):- raise RuntimeStoreError('admission_conflict')+ # Earlier API releases stored the caller-declared key directly on the session row+ # (#139835). A caller presenting that exact key adopts the row onto the canonical route;+ # the declared-key registry above already refused a key owned by another session, and any+ # other stored key (another conversation's, a foreign route) still conflicts.+ legacy_key = declared_key or caller_key+ if row is not None and row['session_key'] not in (None, '', route):+ if not legacy_key or row['session_key'] != legacy_key:+ raise RuntimeStoreError('admission_conflict')+ # The rewrite below replaces the stamped key with the route: the registry keeps it,+ # so a later request selecting the conversation by that key still finds this row.+ owner = conn.execute('SELECT value FROM state_meta WHERE key=?',+ (_DECLARED_PREFIX + legacy_key,)).fetchone()+ if owner is not None and owner[0] != session_id:+ raise RuntimeStoreError('admission_conflict')+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?) ON CONFLICT(key) DO NOTHING',+ (_DECLARED_PREFIX + legacy_key, session_id))+ receipt['declared_key'] = legacy_keyexisting = conn.execute("SELECT entry_json FROM gateway_routing WHERE scope='' AND session_key=?",(route,)).fetchone()if existing is not None and json.loads(existing[0])['session_id'] != session_id:diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.pyindex c0e22a66f91..c3587cf5962 100644--- a/gateway/session_api_turn.py+++ b/gateway/session_api_turn.py@@ -257,7 +257,8 @@ def _admit_api_payload(authority, adapter, sid, request_id, payload, settings, dcheck_api_settings(adapter, settings)from gateway.session_contract import SessionRefreturn authority, SessionRef(authority.profile_id, sid), row- ref = yield from bind_api_steps(authority, sid, hosted_dispatch=kwargs.get("room_dispatch"), declared_key=declared_key)+ ref = yield from bind_api_steps(authority, sid, hosted_dispatch=kwargs.get("room_dispatch"), declared_key=declared_key,+ caller_key=kwargs.get('gateway_session_key'))check_api_turn(authority, ref, payload)row = yield partial(admit_session_input, authority.db, epoch=authority.epoch, principal_id='api',session_id=sid, request_id=request_id, payload=payload,diff --git a/tests/gateway/test_api_runs_legacy_declared_key.py b/tests/gateway/test_api_runs_legacy_declared_key.pynew file mode 100644index 00000000000..b955e476237--- /dev/null+++ b/tests/gateway/test_api_runs_legacy_declared_key.py@@ -0,0 +1,81 @@+"""#139835 (LC-13): an API session written by an earlier release stored the client's declared+``X-Hermes-Session-Key`` in ``sessions.session_key``; the caller that declares that same key is+adopted onto the canonical route, never 409'd forever. A different key still conflicts."""+import json+import os+import subprocess+import sys+from pathlib import Path+++def test_runs_adopt_legacy_declared_session_key(tmp_path):+ result = subprocess.run([sys.executable, __file__], cwd=Path(__file__).resolve().parents[2],+ env=dict(os.environ, HERMES_HOME=str(tmp_path)), capture_output=True, text=True, timeout=90, check=False)+ assert result.returncode == 0, result.stdout + result.stderr+ print((tmp_path / 'legacy-receipt.json').read_text(encoding='utf-8'))+++async def probe():+ import aiohttp+ from gateway.config import Platform, PlatformConfig+ from gateway.platforms.api_server import APIServerAdapter+ from gateway.run import GatewayRunner+ from gateway.session_authority import initialize_session_authority++ runner = GatewayRunner()+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='legacy-test')+ db = authority.db+ # Rows exactly as earlier releases left them: the declared key verbatim, no binding receipt.+ for sid in ('legacy1', 'legacy2', 'legacy3'):+ db.create_session(sid, source='api_server')+ db.record_gateway_session_peer(sid, source='api_server', session_key='webui:' + sid)+ adapter = APIServerAdapter(PlatformConfig(enabled=True, extra={'key': 'legacy-probe-secret', 'port': 0}))+ adapter.gateway_runner = runner+ adapter.set_message_handler(runner._handle_message)+ runner.adapters[Platform.API_SERVER] = adapter+ assert await adapter.connect()+ port = adapter._site._server.sockets[0].getsockname()[1]+ out = {}++ async def post(client, name, body, key):+ headers = {'Authorization': 'Bearer legacy-probe-secret', 'Idempotency-Key': name}+ if key:+ headers['X-Hermes-Session-Key'] = key+ async with client.post(f'http://127.0.0.1:{port}/v1/runs', json=body, headers=headers) as response:+ text = await response.text()+ out[name] = [response.status, json.loads(text) if response.content_type == 'application/json' else text]+ return response.status, out[name][1]+ try:+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=20)) as client:+ # The report's request: explicit session id plus the same declared key.+ status, body = await post(client, 'explicit', {'session_id': 'legacy1', 'input': 'hi'}, 'webui:legacy1')+ assert status == 202, (status, body)+ # Adoption kept the key: selecting the conversation by it alone reaches the same row.+ status, body = await post(client, 'explicit-then-declared', {'input': 'again'}, 'webui:legacy1')+ assert status == 202, (status, body)+ assert adapter._run_statuses[body['run_id']]['session_id'] == 'legacy1', adapter._run_statuses[body['run_id']]+ # A caller declaring a DIFFERENT key never adopts a row stamped with another key.+ status, body = await post(client, 'foreign', {'session_id': 'legacy2', 'input': 'hi'}, 'webui:intruder')+ assert status == 409 and body['error']['code'] == 'admission_conflict', (status, body)+ status, body = await post(client, 'keyless', {'session_id': 'legacy2', 'input': 'hi'}, None)+ assert status == 409 and body['error']['code'] == 'admission_conflict', (status, body)+ # Declared key alone (no session id) resolves the legacy conversation, not a new one.+ status, body = await post(client, 'declared', {'input': 'hi'}, 'webui:legacy3')+ assert status == 202, (status, body)+ route = lambda sid: db.get_session(sid)['session_key']+ assert route('legacy1') == 'agent:main:api_server:dm:legacy1', route('legacy1')+ assert route('legacy2') == 'webui:legacy2', 'a refused caller must not rewrite the row'+ assert route('legacy3') == 'agent:main:api_server:dm:legacy3', route('legacy3')+ Path(os.environ['HERMES_HOME'], 'legacy-receipt.json').write_text(encoding='utf-8', data=json.dumps(out))+ finally:+ await adapter.disconnect()+++if __name__ == '__main__':+ import asyncio+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))+ os.environ.update(OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL='http://127.0.0.1:9/v1')+ Path(os.environ['HERMES_HOME'], 'config.yaml').write_text(+ 'model:\n default: local-wire-stub\n provider: custom\n base_url: http://127.0.0.1:9/v1\n'+ 'auxiliary:\n title_generation:\n enabled: false\n')+ asyncio.run(probe())