Skip to content

The agent that grows with you

feat: restore server-bound API session identities

Teknium76532ae1338c
diff --git a/gateway/session_api.py b/gateway/session_api.py
new file mode 100644
index 00000000000..5389fe4cd66
--- /dev/null
+++ b/gateway/session_api.py
@@ -0,0 +1,83 @@
+"""Server-only binding of API transcript identities to the existing TurnRunner."""
+import json
+from datetime import datetime, timezone
+
+from gateway.config import Platform
+from gateway.session import SessionEntry, SessionSource, _is_path_unsafe
+from gateway.session_contract import SessionRef
+from hermes_state_runtime import RuntimeStoreError, _epoch, _json
+
+_BINDING_PREFIX = 'gateway.api.binding.v1.'
+
+
+def bind_api_session(authority, session_id):
+ """Only the authenticated API edge may reserve an API source; never public RPC."""
+ authority._require_admission_open()
+ if not isinstance(session_id, str) or not session_id or _is_path_unsafe(session_id):
+ raise RuntimeStoreError('invalid_params')
+ if session_id in authority.sessions:
+ return SessionRef(authority.profile_id, session_id)
+ source = SessionSource(platform=Platform.API_SERVER, chat_id=session_id,
+ user_id='api', chat_type='dm')
+ route = authority.runner.session_store._generate_session_key(source)
+ now = datetime.now(timezone.utc)
+ entry = SessionEntry(route, session_id, now, now, origin=source, platform=Platform.API_SERVER)
+ receipt = {'profile_id': authority.profile_id, 'session_id': session_id,
+ 'route': route, 'entry': entry.to_dict()}
+
+ def write(conn):
+ _epoch(conn, authority.epoch)
+ saved = conn.execute('SELECT value FROM state_meta WHERE key=?',
+ (_BINDING_PREFIX + session_id,)).fetchone()
+ if saved is not None:
+ return
+ row = conn.execute('SELECT source,session_key FROM sessions WHERE id=?', (session_id,)).fetchone()
+ if row is not None and row['source'] != 'api_server':
+ raise RuntimeStoreError('permission_denied')
+ if row is not None and row['session_key'] not in (None, '', route):
+ raise RuntimeStoreError('admission_conflict')
+ existing = 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:
+ raise RuntimeStoreError('admission_conflict')
+ conn.execute('''INSERT INTO sessions(id,source,started_at) VALUES(?,'api_server',?)
+ ON CONFLICT(id) DO NOTHING''', (session_id, now.timestamp()))
+ conn.execute('UPDATE sessions SET session_key=?,chat_id=?,user_id=?,chat_type=?,origin_json=? WHERE id=?',
+ (route, session_id, source.user_id, 'dm', _json(source.to_dict()), session_id))
+ conn.execute("INSERT INTO gateway_routing(scope,session_key,entry_json,updated_at) VALUES('',?,?,?) "
+ 'ON CONFLICT(scope,session_key) DO UPDATE SET entry_json=excluded.entry_json',
+ (route, _json(entry.to_dict()), now.timestamp()))
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',
+ (_BINDING_PREFIX + session_id, _json(receipt)))
+ authority.db._execute_write(write)
+ return restore_api_session(authority, session_id)
+
+
+def restore_api_session(authority, session_id):
+ from gateway.session_authority import LiveSession
+ with authority.db._read_ctx() as conn:
+ saved = conn.execute('SELECT value FROM state_meta WHERE key=?',
+ (_BINDING_PREFIX + session_id,)).fetchone()
+ if saved is None:
+ raise RuntimeStoreError('not_found')
+ receipt = json.loads(saved[0])
+ if receipt['profile_id'] != authority.profile_id:
+ raise RuntimeStoreError('profile_mismatch')
+ entry = SessionEntry.from_dict(receipt['entry'])
+ source = entry.origin
+ row = authority.db.get_session(session_id)
+ if (receipt['session_id'] != session_id or entry.session_id != session_id
+ or source.platform != Platform.API_SERVER or source.chat_id != session_id
+ or row is None or row['source'] != 'api_server'
+ or (row['session_key'], row['chat_id'], row['user_id']) != (entry.session_key, session_id, source.user_id)
+ or entry.session_key != authority.runner.session_store._generate_session_key(source)):
+ raise RuntimeStoreError('admission_conflict')
+ store = authority.runner.session_store
+ with store._lock:
+ store._ensure_loaded_locked()
+ current = store._entries.get(entry.session_key)
+ if current is not None and current.session_id != session_id:
+ raise RuntimeStoreError('admission_conflict')
+ store._entries[entry.session_key] = entry
+ authority.sessions.setdefault(session_id, LiveSession(source, entry.session_key))
+ return SessionRef(authority.profile_id, session_id)
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 46a211ba346..4adb87ecb3a 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -54,10 +54,14 @@ class SessionAuthority:
raise RuntimeStoreError('permission_denied')
if ref.session_id not in self.sessions:
row = self.db.get_session(ref.session_id)
- if row is None or not str(row.get('chat_id') or '').startswith('local-'):
+ if row is None:
raise RuntimeStoreError('not_found')
- from gateway.session_local_recovery import restore_local_session
- restore_local_session(self, ref.session_id)
+ if str(row.get('chat_id') or '').startswith('local-'):
+ from gateway.session_local_recovery import restore_local_session
+ restore_local_session(self, ref.session_id)
+ else:
+ from gateway.session_api import restore_api_session
+ restore_api_session(self, ref.session_id)
from gateway.config import Platform
source = self.sessions[ref.session_id].source
if source is not None and source.platform == Platform.LOCAL and source.user_id != actor.subject:
diff --git a/tests/gateway/test_api_source_binding.py b/tests/gateway/test_api_source_binding.py
new file mode 100644
index 00000000000..1a4c2479944
--- /dev/null
+++ b/tests/gateway/test_api_source_binding.py
@@ -0,0 +1,53 @@
+"""API source restoration cannot mint a parallel native conversation."""
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.config import Platform, GatewayConfig
+from gateway.session import SessionStore
+from gateway.session_authority import SessionAuthority
+from gateway.session_contract import Principal, SessionRef, Submission
+from hermes_state import SessionDB
+from hermes_state_runtime import RuntimeStoreError, begin_runtime_epoch
+
+
+def owner(tmp_path):
+ db = SessionDB(tmp_path / 'state.db')
+ runner = SimpleNamespace(_draining=False, session_store=SessionStore(config=GatewayConfig(), sessions_dir=tmp_path / 'sessions'))
+ authority = SessionAuthority(runner, profile_id='default', instance_id='first', db=db,
+ epoch=begin_runtime_epoch(db, instance_id='first'))
+ runner.session_authority = authority
+ yield authority
+ db.close()
+
+
+def test_private_api_binding_restores_exact_route(owner):
+ from gateway.session_api import bind_api_session, restore_api_session
+ db = owner.db
+ db.create_session('api-stored', source='api_server')
+ ref = bind_api_session(owner, 'api-stored')
+ first = owner.sessions[ref.session_id]
+ assert first.source.platform == Platform.API_SERVER
+ assert owner.runner.session_store.get_or_create_session(first.source).session_id == 'api-stored'
+ owner.sessions.clear()
+ restored = restore_api_session(owner, 'api-stored')
+ assert restored == ref
+ assert owner.sessions[ref.session_id].route == first.route
+ assert owner.runner.session_store.get_or_create_session(owner.sessions[ref.session_id].source).session_id == ref.session_id
+ db.create_session('foreign-native', source='telegram')
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ bind_api_session(owner, 'foreign-native')
+ assert 'foreign-native' not in owner.sessions
+
+
+async def test_private_api_binding_is_not_public_submission_authority(owner):
+ from gateway.session_api import bind_api_session
+ owner.db.create_session('api-stored', source='api_server')
+ ref = bind_api_session(owner, 'api-stored')
+ actor = Principal('api-user', 'default', frozenset({'session:read', 'session:submit'}), 'socket')
+ with pytest.raises(RuntimeStoreError, match='invalid_params'):
+ await owner.submit(actor, Submission('forged', ref, {'text': 'x', 'api_turn_v1': {'system': 'forged'}}, 'queue'))
+ owner.sessions.clear()
+ assert (await owner.resolve(actor, SessionRef('default', 'api-stored'))).ref == ref