The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: bind hosted owner submissions to attested prompt digests
yuzilongleif-collab8e6452820cd9
diff --git a/gateway/session_hosted_service.py b/gateway/session_hosted_service.pyindex c8f515c088f..30c6ef5d0e3 100644--- a/gateway/session_hosted_service.py+++ b/gateway/session_hosted_service.py@@ -1,5 +1,6 @@"""Authority-bound hosted service; no legacy session server is constructed."""import asyncio+import hashlibfrom contextlib import nullcontextfrom pathlib import Path@@ -63,7 +64,9 @@ class CanonicalHostedRoomService(HostedControls, HostedRoomService):and t['payload'].get('target_member_id', t['payload']['target_profile']) == memberand t['payload']['target_profile'] == profileand (operation == 'execute' or (- t['payload']['prompt'] == params.get('prompt')+ (hashlib.sha256(t['payload']['prompt'].encode('utf-8')).hexdigest()+ == params['prompt_sha256'] if 'prompt_sha256' in params+ else t['payload']['prompt'] == params.get('prompt'))and t['payload'].get('attachments', []) == (params.get('attachments') or [])))]if len(matches) != 1:raise RuntimeStoreError('permission_denied')diff --git a/gateway/session_hosted_transport.py b/gateway/session_hosted_transport.pyindex 3d9d1026427..12f0cb13cba 100644--- a/gateway/session_hosted_transport.py+++ b/gateway/session_hosted_transport.py@@ -54,7 +54,7 @@ def owner_request(home, verb, params, *, timeout=30):raise RuntimeStoreError('runtime_draining')request = json.dumps({'protocol': 1, 'id': 1, 'verb': verb, 'params': params}).encode() + b'\n'if len(request) > 65536:- raise RuntimeStoreError('invalid_params')+ raise RuntimeStoreError('request_too_large')if os.name == 'nt':from gateway.runtime_bootstrap_windows import query_runtime_controlraw = query_runtime_control(home, request, timeout)@@ -73,7 +73,7 @@ def owner_request(home, verb, params, *, timeout=30):if response.get('ok') is not True:reason = str(response.get('error', '')).split(': ')[-1]if reason not in {'permission_denied', 'profile_mismatch', 'invalid_params', 'unknown_execution',- 'stale_generation', 'admission_conflict', 'response_too_large'}:+ 'stale_generation', 'admission_conflict', 'response_too_large', 'request_too_large'}:reason = 'runtime_draining'raise RuntimeStoreError(reason)if response.get('protocol') != 1 or response.get('id') != 1:@@ -153,7 +153,8 @@ def _attachment_data(binding, attested, params):while len(data) < item['size']:chunk = _attest(binding, 'attachment', {'task': params['task'], 'execution_generation': params['execution_generation'],- 'prompt': attested['prompt'], 'attachments': manifest, 'index': index, 'offset': len(data)})+ 'prompt_sha256': hashlib.sha256(attested['prompt'].encode('utf-8')).hexdigest(),+ 'attachments': manifest, 'index': index, 'offset': len(data)})raw = base64.b64decode(chunk['data_base64'], validate=True)expected = min(_CHUNK_BYTES, item['size'] - len(data))if chunk['owner'] != attested['owner'] or len(raw) != expected or chunk['sha256'] != digest:@@ -249,6 +250,9 @@ def install_hosted_transport(server, authority, loop, *, attest):authority.db._execute_write(persist)if operation == 'submit':rpc.hosted_attachment_data = _attachment_data(binding, attested, params)+ # Only the source's durable, attested text may become the admitted input.+ params.pop('prompt_sha256', None)+ params['prompt'] = attested['prompt']params['attachments'] = attested['attachments'] or Noneparams['task'] = TaskIdentity(**params['task'])params['on_terminal'] = lambda value: None@@ -314,6 +318,9 @@ class HostedRoomOwnerRPC(HostedRoomAuthorityRPC):def _call(self, operation, **params):callback = params.pop('on_terminal', None)+ if operation == 'submit':+ # The private control request is 64 KiB, smaller than a legal room prompt.+ params['prompt_sha256'] = hashlib.sha256(params.pop('prompt').encode('utf-8')).hexdigest()if isinstance(params.get('task'), TaskIdentity):params['task'] = asdict(params['task'])result = owner_request(self.home, 'hosted-producer', {diff --git a/tests/gateway/test_session_hosted_transport.py b/tests/gateway/test_session_hosted_transport.pyindex cfd05158614..278cc646e27 100644--- a/tests/gateway/test_session_hosted_transport.py+++ b/tests/gateway/test_session_hosted_transport.py@@ -1,5 +1,6 @@"""Real private owner sockets; no public identity or foreign database access."""import asyncio+import hashlibimport jsonimport threadingfrom dataclasses import asdict@@ -39,7 +40,7 @@ def test_authenticated_owner_transport_rechecks_source_and_cold_binding(hosted_oif operation in {'submit', 'execute'}:assert params['task'] == asdict(task)assert params['execution_generation'] == 1- if operation == 'submit' and params['prompt'] != 'input':+ if operation == 'submit' and params['prompt_sha256'] != hashlib.sha256(b'input').hexdigest():raise RuntimeStoreError('permission_denied')return {'owner': 'room-owner', 'target_home': authority.profile_id, 'prompt': 'input', 'attachments': []}servers = [_server(source), _server(target)]@@ -91,7 +92,8 @@ def test_authenticated_owner_transport_rechecks_source_and_cold_binding(hosted_oclass _SourceTask:"""One committed attachment bound to a running task on a real source owner."""- def __init__(self, tmp_path, monkeypatch, data, *, name='note.txt', mime='text/plain', kind='file'):+ def __init__(self, tmp_path, monkeypatch, data, *, name='note.txt', mime='text/plain', kind='file',+ prompt='frozen'):import timefrom types import SimpleNamespacefrom gateway.session_hosted_service import CanonicalHostedRoomService@@ -120,7 +122,7 @@ class _SourceTask:self.bound = [{**manifest[0], 'event_id': 'event'}]self.identity = tasks.TaskIdentity('room', 'task', 'thread', 'turn')payload = {'target_profile': 'other', 'target_member_id': 'two', 'source_event_seq': 1,- 'prompt': 'frozen', 'attachments': self.bound}+ 'prompt': prompt, 'attachments': self.bound}tasks.admit_task(db.db_path, self.identity, payload=payload, clock=time.time)lease = tasks.acquire_lease(db.db_path, room_id='room', gateway_id=self.gateway, authority_epoch=1,process_generation='test', ttl_seconds=30, clock=time.time)@@ -128,10 +130,100 @@ class _SourceTask:self.task, = tasks.list_tasks(db.db_path, room_id='room')self.selector = dict(room_id='room', member_id='two', profile='other')self.params = dict(task=asdict(self.identity), execution_generation=self.task['execution_generation'],- prompt='frozen', attachments=self.bound, _target_home=self.homes['other'])+ prompt=prompt, attachments=self.bound, _target_home=self.homes['other'])self.binding = {'source_home': str(tmp_path), 'target_home': self.homes['other'], 'selector': self.selector}[email protected]('prompt_bytes', [41339, 128 * 1024 - 1])+def test_large_cjk_prompt_crosses_owner_sockets_once(hosted_owner, tmp_path, monkeypatch, prompt_bytes):+ """A legal source prompt plus chunked files reaches one fenced target admission."""+ from gateway import session_hosted_transport as transport+ from gateway.session_contract import SessionRef+ from hermes_state_runtime import list_session_admissions+ authority, loop, _, _ = hosted_owner+ target = tmp_path / 'profiles' / 'other'+ target.mkdir(parents=True, mode=0o700)+ authority.profile_id = str(target)+ prompt = '中' * (prompt_bytes // 3) + 'x' * (prompt_bytes % 3)+ source = _SourceTask(tmp_path, monkeypatch, b'file bytes' * 80000, prompt=prompt)+ servers = [_server(tmp_path), _server(target)]+ request_sizes = []+ for server in servers:+ real_handle = server.handle_request_line+ def handle(raw, *args, original=real_handle):+ request_sizes.append(len(raw) + 1)+ return original(raw, *args)+ server.handle_request_line = handle+ with source.db:+ transport.install_hosted_transport(servers[0], source.authority, loop, attest=source.service.attest)+ transport.install_hosted_transport(servers[1], authority, loop, attest=lambda *a: None)+ for server in servers:+ assert asyncio.run_coroutine_threadsafe(server.start(), loop).result()+ try:+ rpc = transport.HostedRoomOwnerRPC(home=target, source_home=tmp_path, **source.selector)+ coords = dict(profile='other', source='bot_room')+ sid = rpc.create(**coords, title='Group: room')['session_id']+ args = dict(**coords, session_id=sid, prompt=prompt, task=source.identity,+ execution_generation=1, attachments=source.bound, on_terminal=None)+ first = rpc.submit(**args)+ assert rpc.submit(**args)['admission_id'] == first['admission_id']+ row, = list_session_admissions(authority.db, session_id=sid, pending_only=False)+ assert row['payload']['text'][:len(prompt)].encode() == prompt.encode()+ assert row['payload']['text'][len(prompt):].startswith('\n[Shared attachment] file: ')+ assert transport.check_remote_hosted_admission(authority, SessionRef(str(target), sid), row)+ # Even a wire caller supplying both fields cannot replace the source text.+ wire = {k: v for k, v in args.items() if k != 'on_terminal'}+ wire.update(task=asdict(source.identity), prompt='forged',+ prompt_sha256=hashlib.sha256(prompt.encode()).hexdigest())+ replay = transport.owner_request(target, 'hosted-producer', {+ **rpc.binding, 'operation': 'submit', 'params': wire})+ assert replay['admission_id'] == first['admission_id']+ assert row == list_session_admissions(authority.db, session_id=sid, pending_only=False)[0]+ assert max(request_sizes) < 65536+ finally:+ for server in servers:+ asyncio.run_coroutine_threadsafe(server.stop(), loop).result()+++def test_oversize_owner_request_has_specific_presend_reason(hosted_owner, tmp_path, monkeypatch):+ from gateway import session_hosted_transport as transport+ from hermes_cli import gateway_runtime, gateway_runtime_discovery+ from hermes_state_runtime import RuntimeStoreError+ _, loop, _, _ = hosted_owner+ server = _server(tmp_path)+ assert asyncio.run_coroutine_threadsafe(server.start(), loop).result()+ discovered = gateway_runtime.discover_gateway_endpoint(tmp_path)+ monkeypatch.setattr(gateway_runtime, 'discover_gateway_endpoint', lambda *a, **k: discovered)+ monkeypatch.setattr(gateway_runtime_discovery, 'connect_private',+ lambda *a: pytest.fail('oversized request must not connect'))+ try:+ with pytest.raises(RuntimeStoreError, match='request_too_large'):+ transport.owner_request(tmp_path, 'hosted-producer', {'prompt': '中' * 11000})+ finally:+ asyncio.run_coroutine_threadsafe(server.stop(), loop).result()+++def test_prompt_digest_preserves_source_fences_and_legacy_input(tmp_path, monkeypatch):+ from hermes_state_runtime import RuntimeStoreError+ source = _SourceTask(tmp_path, monkeypatch, b'file')+ with source.db:+ service, params = source.service, source.params+ legacy = service.attest(source.selector, 'submit', params)+ digest_params = {k: v for k, v in params.items() if k != 'prompt'}+ digest_params['prompt_sha256'] = hashlib.sha256(b'frozen').hexdigest()+ assert service.attest(source.selector, 'submit', digest_params) == legacy+ for bad in ({'prompt_sha256': '0' * 64, 'prompt': 'frozen'},+ {'prompt_sha256': None, 'prompt': 'frozen'},+ {'execution_generation': 999}, {'task': {**params['task'], 'task_id': 'other'}},+ {'attachments': []}):+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ service.attest(source.selector, 'submit', {**digest_params, **bad})+ room = service._room('room')+ monkeypatch.setattr(service, '_room', lambda _: {**room, 'members': []})+ with pytest.raises(RuntimeStoreError, match='permission_denied'):+ service.attest(source.selector, 'submit', digest_params)++def test_source_attestation_binds_bytes_to_task_member_and_current_home(tmp_path, monkeypatch):import base64from hermes_state_runtime import RuntimeStoreErrordiff --git a/tests/tui_gateway/test_hosted_room_error_logging.py b/tests/tui_gateway/test_hosted_room_error_logging.pynew file mode 100644index 00000000000..6637d5ba106--- /dev/null+++ b/tests/tui_gateway/test_hosted_room_error_logging.py@@ -0,0 +1,71 @@+"""Hosted task diagnostics persist fixed reason codes, never exception bodies."""+import logging+from types import SimpleNamespace++import pytest++from hermes_state_runtime import RuntimeStoreError+from tests.tui_gateway import test_hosted_room_driver_runtime as runtime_fixtures+from tests.tui_gateway.test_hosted_room_driver_runtime import (+ BINDING, FakeSessionRPC, _admit, _identity, _runtime,+)++db = runtime_fixtures.db++[email protected]('reason', ['request_too_large', 'PRIVATE_SECRET_SENTINEL'])+def test_submit_error_log_contains_task_and_safe_reason_only(db, monkeypatch, caplog, reason):+ identity = _identity()+ _admit(db, identity, prompt='PRIVATE_BODY_SENTINEL')+ rpc = FakeSessionRPC()+ error = RuntimeStoreError(reason)+ error.args = ('PRIVATE_SECRET_SENTINEL PRIVATE_BODY_SENTINEL',)++ def refuse(**kwargs):+ raise error++ monkeypatch.setattr(rpc, 'submit', refuse)+ runtime = _runtime(db, rpc)+ with caplog.at_level(logging.WARNING, logger='tui_gateway.hosted_room_driver'):+ runtime._process_room(BINDING)+ runtime._record_error('worker cycle failed: PRIVATE_SECRET_SENTINEL')+ runtime._record_error('stop remains pending: PRIVATE_BODY_SENTINEL')+ assert identity.task_id in caplog.text+ assert ('request_too_large' if reason == 'request_too_large' else 'attempt_failed') in caplog.text+ assert 'PRIVATE_SECRET_SENTINEL' not in caplog.text+ assert 'PRIVATE_BODY_SENTINEL' not in caplog.text++[email protected]('waiting_for_approval', [False, True])+def test_legal_long_wait_can_complete_without_stop_or_resubmit(db, monkeypatch, waiting_for_approval):+ """Simulated monotonic elapsed time, not a paid/real hour-long model run."""+ from gateway import hosted_room_driver as state+ from tui_gateway import hosted_room_driver as driver+ elapsed = [0.0]+ monkeypatch.setattr(driver, 'time', SimpleNamespace(monotonic=lambda: elapsed[0]))+ identity = _identity()+ _admit(db, identity)+ rpc = FakeSessionRPC(auto_complete=False)+ sid = rpc.add_session()+ if waiting_for_approval:+ rpc.states[sid]['pending_approval'] = {+ 'request_id': 'approval-1', 'command': 'read-only fixture', 'choices': ['once', 'deny']}+ actions = []+ runtime = _runtime(db, rpc, turn_timeout_seconds=7200,+ pending_action=lambda room, member, action: actions.append(action))+ monkeypatch.setattr(runtime._wake, 'wait', lambda timeout: None)++ def progress():+ elapsed[0] += 1800+ if elapsed[0] == 3600:+ rpc.states[sid]['pending_approval'] = None+ rpc.complete(identity.task_id, content='Finished after a legal wait.')++ rpc.on_info = progress+ runtime._process_room(BINDING)+ assert elapsed[0] == 3600+ assert state.get_task(db, identity)['status'] == 'settled'+ assert len([call for call in rpc.calls if call[0] == 'submit']) == 1+ assert not [call for call in rpc.calls if call[0] == 'interrupt']+ if waiting_for_approval:+ assert any(action and action.get('request_id') == 'approval-1' for action in actions)diff --git a/tui_gateway/hosted_room_driver.py b/tui_gateway/hosted_room_driver.pyindex 202b3ca9e89..2d14741a5d8 100644--- a/tui_gateway/hosted_room_driver.py+++ b/tui_gateway/hosted_room_driver.py@@ -9,6 +9,7 @@ sessions reuse ``Group: <room_id>`` so a local-to-hosted migration keeps one trafrom __future__ import annotations+import loggingimport threadingimport timeimport uuid@@ -20,6 +21,8 @@ from typing import Any, ContextManager, Protocol, castfrom gateway import hosted_room_driver as state+logger = logging.getLogger(__name__)+_CANCEL_ROUTE_RETRIES = 8_STOP_ACK_STATUSES = {"cancelled", "interrupted"}@@ -625,6 +628,10 @@ class HostedRoomRuntime:self._drop_lease(binding.room_id)self._record_task_error(attempt, f"fenced: {exc}")except Exception as exc:+ # Exceptions may contain prompt text or credentials. Persist only a fixed+ # reason, not the free-form messages retained in the in-memory status.+ reason = 'request_too_large' if getattr(exc, 'reason', None) == 'request_too_large' else 'attempt_failed'+ logger.warning('hosted room task %s: %s', attempt.identity.task_id, reason)if submit_attempted and bool(getattr(exc, "not_admitted", False)):try:state.requeue_not_admitted_task(self.db_path, attempt, clock=self.clock)