Skip to content

The agent that grows with you

fix(runtime): reauthorize same-home hosted admission in the writer transaction

David Dudok de Wit835aac9c4850
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 3f14cebf3da..da77c44ae55 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -290,7 +290,7 @@ class SessionAuthority:
results[sid] = exc.reason
return results
- async def submit(self, actor: Principal, request: Submission):
+ async def submit(self, actor: Principal, request: Submission, *, _authorize_write=None):
self.authorize(actor, request.ref, 'session:submit')
self._require_admission_open()
if (request.intent != 'queue' or not {'text'} <= set(request.payload) <= {
@@ -314,7 +314,8 @@ class SessionAuthority:
'principal_id': actor.subject}
row = admit_session_input(self.db, epoch=self.epoch, principal_id=actor.subject,
session_id=request.ref.session_id, request_id=request.request_id,
- payload=payload, intent=request.intent)
+ payload=payload, intent=request.intent,
+ _authorize_write=_authorize_write)
self._publish_pending(request.ref)
self._schedule(request.ref)
return self._receipt(row)
diff --git a/gateway/session_hosted_rpc.py b/gateway/session_hosted_rpc.py
index 057785c5732..d21d68988c3 100644
--- a/gateway/session_hosted_rpc.py
+++ b/gateway/session_hosted_rpc.py
@@ -19,10 +19,11 @@ _RESULTLESS_OUTCOMES = frozenset({'interrupted', 'cancelled'})
class HostedRoomAuthorityRPC:
def __init__(self, authority, loop, *, room_id, member_id, profile, principal,
- authorize, timeout=30):
+ authorize, authorize_write=None, timeout=30):
self.authority, self.loop = authority, loop
self.room_id, self.member_id, self.profile = room_id, member_id, profile
self.principal, self.authorizer, self.timeout = principal, authorize, timeout
+ self.authorize_write = authorize_write
self.callbacks = {}
binding = json.dumps([room_id, member_id, profile], separators=(',', ':'))
self.creation_id = 'hosted:' + hashlib.sha256(binding.encode()).hexdigest()
@@ -137,8 +138,11 @@ class HostedRoomAuthorityRPC:
from gateway.session_hosted_attachments import submission_payload
payload = await asyncio.to_thread(
submission_payload, self, params['prompt'], params.get('attachments'))
+ authorize_write = self.authorize_write
receipt = await self.authority.submit(self.principal, Submission(
- request_id, self.ref, payload, 'queue'))
+ request_id, self.ref, payload, 'queue'),
+ _authorize_write=(lambda conn: authorize_write(conn, task, generation))
+ if authorize_write is not None else None)
self.callbacks[receipt.admission_id] = params['on_terminal']
if receipt.status in {'queued', 'started'}:
waiter = self.authority.waiters.get(receipt.admission_id)
diff --git a/gateway/session_hosted_service.py b/gateway/session_hosted_service.py
index 47a2e7376a3..e43e0dd1a1b 100644
--- a/gateway/session_hosted_service.py
+++ b/gateway/session_hosted_service.py
@@ -149,28 +149,59 @@ class CanonicalHostedRoomService(HostedControls, HostedRoomService):
source_home=self.authority.profile_id, room_id=binding.room_id,
member_id=member, profile=profile)
return self.member_rpcs[key]
- def authorize(operation, identity, generation):
- self.authorize_room(owner, binding.room_id)
- room = self._room(binding.room_id)
+ def authorized(conn, operation, identity, generation):
+ # Admission checks must share the FIFO writer's snapshot. Opening
+ # another transaction here would reintroduce the revocation race.
+ from gateway.hosted_rooms import _room_from_row
+ from gateway.hosted_room_driver import _task_from_row
+ _epoch(conn, self.authority.epoch)
+ owned = conn.execute('SELECT value FROM state_meta WHERE key=?',
+ (_OWNER + binding.room_id,)).fetchone()
+ if owned is None or owned[0] != owner:
+ return False
+ stored = conn.execute('SELECT * FROM hosted_rooms WHERE room_id=?',
+ (binding.room_id,)).fetchone()
+ if stored is None or stored['disbanded_at'] is not None:
+ return False
+ room = _room_from_row(stored)
if (room['authority_gateway_id'], room['authority_epoch']) != (binding.gateway_id, binding.authority_epoch):
return False
members = room['members']
- if not any(m.get('member_id') == member and m.get('profile') == profile for m in members):
+ if not any(m.get('member_id') == member and m.get('profile') == profile
+ and (m.get('target') is None or (
+ isinstance(m.get('target'), dict)
+ and m['target'].get('kind', 'local') == 'local'))
+ for m in members):
return False
if self.profile_homes().get(profile) != home:
return False
if identity is not None:
- from gateway.hosted_room_driver import list_tasks
- return any(t['identity'] == identity and t['execution_generation'] == generation
- and t['payload'].get('target_profile') == profile
- and t['status'] in {'running', 'stopping'}
- for t in list_tasks(self.db_path, room_id=binding.room_id))
+ stored = conn.execute('SELECT * FROM hosted_room_driver_tasks WHERE room_id=? AND task_id=?',
+ (binding.room_id, identity.task_id)).fetchone()
+ if stored is None:
+ return False
+ current = _task_from_row(stored)
+ return (current['identity'] == identity and current['execution_generation'] == generation
+ and current['payload'].get('target_profile') == profile
+ and current['payload'].get('target_member_id', profile) == member
+ and current['status'] in ({'running'} if operation in {'submit', 'execute'}
+ else {'running', 'stopping'}))
+ return True
+ def authorize(operation, identity, generation):
+ with self.authority.db._read_ctx() as conn:
+ return authorized(conn, operation, identity, generation)
+ def authorize_write(conn, identity, generation):
+ # Raise to refuse rather than return False: a guard that only returns False
+ # is ignored wherever the admission hook signals refusal by raising.
+ if not authorized(conn, 'submit', identity, generation):
+ raise RuntimeStoreError('permission_denied')
return True
principal = Principal(owner, self.authority.profile_id,
frozenset({'session:create', 'session:read', 'session:submit', 'session:control', 'session:approve'}),
'hosted:' + binding.room_id + ':' + member)
self.member_rpcs[key] = HostedRoomAuthorityRPC(self.authority, self.loop,
- room_id=binding.room_id, member_id=member, profile=profile, principal=principal, authorize=authorize)
+ room_id=binding.room_id, member_id=member, profile=profile, principal=principal, authorize=authorize,
+ authorize_write=authorize_write)
return self.member_rpcs[key]
def check_admission(self, ref, row):
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index 48960a91fb2..6237b14888b 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -85,7 +85,14 @@ def begin_runtime_epoch(db, *, instance_id: str) -> int:
def admit_session_input(db, *, epoch: int, principal_id: str, session_id: str,
- request_id: str, payload: dict, intent: str = 'queue') -> dict:
+ request_id: str, payload: dict, intent: str = 'queue',
+ _authorize_write=None) -> dict:
+ """Admit input; the trusted private guard raises to refuse a NEW write.
+
+ The guard receives the owning transaction connection, must not commit it or
+ perform external effects, and may run again on SQLite retry. Exact existing
+ and terminal replays bypass it: they cannot create or change accepted work.
+ """
for value in (principal_id, session_id, request_id):
_text(value)
if intent not in ('queue', 'steer', 'redirect'):
@@ -106,6 +113,8 @@ def admit_session_input(db, *, epoch: int, principal_id: str, session_id: str,
if old['payload_digest'] != digest:
raise RuntimeStoreError('admission_conflict')
return _row(old)
+ if _authorize_write is not None:
+ _authorize_write(conn)
admission_id = uuid.uuid4().hex
conn.execute('''INSERT INTO session_admissions(admission_id,request_id,principal_id,
target_session_id,lineage_json,payload_json,payload_digest,intent,status,owner_epoch)
diff --git a/tests/gateway/test_session_hosted_rpc.py b/tests/gateway/test_session_hosted_rpc.py
index 726b1b7d96b..9ff6a645a24 100644
--- a/tests/gateway/test_session_hosted_rpc.py
+++ b/tests/gateway/test_session_hosted_rpc.py
@@ -6,6 +6,90 @@ from types import SimpleNamespace
import pytest
[email protected]('member_target', [{}, {'target': None}], ids=['missing-target', 'null-target'])
[email protected]('revocation', [None, 'member', 'room_epoch', 'owner', 'task_generation', 'stopping', 'disbanded', 'malformed_target'])
+def test_local_hosted_member_revoked_during_preparation_is_not_admitted(owner, monkeypatch, revocation, member_target):
+ """Revocation must fence admission, not merely pause execution afterward."""
+ import concurrent.futures
+ import json
+ from pathlib import Path
+ import time
+
+ from gateway import hosted_room_driver as tasks, session_hosted_attachments
+ from gateway.hosted_rooms import create_room, local_authority_gateway_id
+ from gateway.session_hosted_service import CanonicalHostedRoomService
+ from hermes_state_runtime import RuntimeStoreError, list_session_admissions
+ from tui_gateway.hosted_room_driver import HostedRoomBinding
+
+ authority, loop, _, _ = owner
+ service = CanonicalHostedRoomService(authority, loop)
+ # The component fixture uses a synthetic profile identifier, not a daemon home.
+ monkeypatch.setattr(service, 'profile_homes', lambda: {'default': Path(authority.profile_id)})
+ service.authorize_room('alice', 'room', create=True)
+ gateway = local_authority_gateway_id()
+ members = [
+ {'member_id': 'one', 'profile': 'default', 'handle': 'one', **member_target},
+ {'member_id': 'two', 'profile': 'other', 'handle': 'two'},
+ ]
+ create_room(authority.db.db_path, room_id='room', name='Room',
+ authority_gateway_id=gateway, members=members)
+ identity = tasks.TaskIdentity('room', 'task', 'thread', 'turn')
+ payload = {'target_profile': 'default', 'target_member_id': 'one',
+ 'source_event_seq': 1, 'prompt': 'frozen'}
+ tasks.admit_task(authority.db.db_path, identity, payload=payload, clock=time.time)
+ lease = tasks.acquire_lease(authority.db.db_path, room_id='room', gateway_id=gateway,
+ authority_epoch=1, process_generation='test', ttl_seconds=120, clock=time.time)
+ tasks.start_task(authority.db.db_path, identity, lease,
+ expected_cancel_generation=0, clock=time.time)
+ task, = tasks.list_tasks(authority.db.db_path, room_id='room')
+ rpc = service._resolve_member_transport(HostedRoomBinding('room', gateway, 1), task)
+ coords = {'profile': 'default', 'source': 'bot_room'}
+ sid = rpc.create(**coords, title='Group: room')['session_id']
+ preparing, release = threading.Event(), threading.Event()
+ original = session_hosted_attachments.submission_payload
+
+ def paused_preparation(*args, **kwargs):
+ preparing.set()
+ assert release.wait(10), 'test did not release preparation'
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(session_hosted_attachments, 'submission_payload', paused_preparation)
+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
+ submitted = executor.submit(rpc.submit, **coords, session_id=sid, prompt='frozen',
+ task=identity, execution_generation=task['execution_generation'],
+ on_terminal=lambda receipt: None)
+ try:
+ assert preparing.wait(10), 'producer never reached preparation'
+ if revocation is not None:
+ if revocation == 'malformed_target':
+ members[0]['target'] = []
+ else:
+ members[0] = {'member_id': 'replacement', 'profile': 'default', 'handle': 'replacement'}
+ mutations = {
+ 'member': ('UPDATE hosted_rooms SET members_json=? WHERE room_id=?', (json.dumps(members), 'room')),
+ 'room_epoch': ('UPDATE hosted_rooms SET authority_epoch=2 WHERE room_id=?', ('room',)),
+ 'owner': ('UPDATE state_meta SET value=? WHERE key=?', ('bob', 'gateway.hosted.owner.v1:room')),
+ 'task_generation': ('UPDATE hosted_room_driver_tasks SET execution_generation=2 WHERE room_id=?', ('room',)),
+ 'stopping': ("UPDATE hosted_room_driver_tasks SET status='stopping' WHERE room_id=?", ('room',)),
+ 'disbanded': ('UPDATE hosted_rooms SET disbanded_at=? WHERE room_id=?', (time.time(), 'room')),
+ 'malformed_target': ('UPDATE hosted_rooms SET members_json=? WHERE room_id=?', (json.dumps(members), 'room')),
+ }
+ sql, args = mutations[revocation]
+ authority.db._execute_write(lambda conn: conn.execute(sql, args))
+ finally:
+ release.set()
+ if revocation is None:
+ receipt = submitted.result(timeout=10)
+ retry = rpc.submit(**coords, session_id=sid, prompt='frozen', task=identity,
+ execution_generation=task['execution_generation'], on_terminal=lambda receipt: None)
+ assert retry['admission_id'] == receipt['admission_id']
+ else:
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ submitted.result(timeout=10)
+ rows = list_session_admissions(authority.db, session_id=sid, pending_only=False)
+ assert len(rows) == (1 if revocation is None else 0)
+
+
@pytest.fixture
def owner(tmp_path, monkeypatch):
from gateway.config import GatewayConfig