Skip to content

The agent that grows with you

fix: transfer hosted input bytes through task-scoped owner attestation

Teknium519e11011d63
diff --git a/gateway/session_hosted_service.py b/gateway/session_hosted_service.py
index 37f28a42c1d..0a026446bde 100644
--- a/gateway/session_hosted_service.py
+++ b/gateway/session_hosted_service.py
@@ -60,17 +60,25 @@ class CanonicalHostedRoomService(HostedControls, HostedRoomService):
target_home = self.profile_homes().get(profile)
if target_home is None or params.get('_target_home') != str(target_home):
raise RuntimeStoreError('permission_denied')
- if operation in {'submit', 'execute'}:
+ result = {'owner': owner, 'target_home': str(target_home)}
+ if operation in {'submit', 'execute', 'attachment'}:
matches = [t for t in list_tasks(self.db_path, room_id=room_id)
if asdict(t['identity']) == params.get('task')
and t['execution_generation'] == params.get('execution_generation')
and t['status'] == 'running'
and t['payload'].get('target_member_id', t['payload']['target_profile']) == member
and t['payload']['target_profile'] == profile
- and t['payload']['prompt'] == params.get('prompt')]
+ and (operation == 'execute' or (
+ t['payload']['prompt'] == params.get('prompt')
+ and t['payload'].get('attachments', []) == (params.get('attachments') or [])))]
if len(matches) != 1:
raise RuntimeStoreError('permission_denied')
- return {'owner': owner, 'target_home': str(target_home)}
+ payload = matches[0]['payload']
+ result.update(prompt=payload['prompt'], attachments=payload.get('attachments', []))
+ if operation == 'attachment':
+ from gateway.session_hosted_transport import source_attachment_chunk
+ result.update(source_attachment_chunk(self, member, room_id, result['attachments'], params))
+ return result
def bindings(self):
diff --git a/gateway/session_hosted_transport.py b/gateway/session_hosted_transport.py
index 49e07a94ee5..a7b70cbe0ee 100644
--- a/gateway/session_hosted_transport.py
+++ b/gateway/session_hosted_transport.py
@@ -6,7 +6,9 @@ owner attests durable membership/task state; the target never opens its database
from __future__ import annotations
import asyncio
+import base64
from dataclasses import asdict
+from types import SimpleNamespace
import hashlib
import json
import os
@@ -23,6 +25,7 @@ from hermes_state_runtime import RuntimeStoreError, _epoch
_BINDING = 'gateway.hosted.transport.v1:'
_OPERATIONS = frozenset({'resolve_exact', 'create', 'resume', 'submit', 'history',
'info', 'interrupt', 'discard', 'approve'})
+_CHUNK_BYTES = 24576
_CAPS = frozenset({'session:create', 'session:read', 'session:submit',
'session:control', 'session:approve'})
@@ -80,6 +83,51 @@ def _attest(binding, operation, params):
return result
+def source_attachment_chunk(service, member, room_id, manifest, params):
+ """Read scoped source bytes only on the source owner's authenticated handler."""
+ index, offset = params.get('index'), params.get('offset')
+ if (type(index) is not int or not 0 <= index < len(manifest)
+ or type(offset) is not int or not 0 <= offset < manifest[index]['size']):
+ raise RuntimeStoreError('permission_denied')
+ from gateway.hosted_room_attachments import HostedRoomAttachmentStore
+ item = manifest[index]
+ saved = HostedRoomAttachmentStore(service.db_path).read(room_id=room_id,
+ attachment_id=item['attachment_id'], event_id=item['event_id'], recipient_member_id=member)
+ if any(saved.attachment[key] != item[key] for key in ('kind', 'name', 'mime', 'size')):
+ raise RuntimeStoreError('permission_denied')
+ data = saved.data
+ return {'data_base64': base64.b64encode(data[offset:offset + _CHUNK_BYTES]).decode('ascii'),
+ 'sha256': hashlib.sha256(data).hexdigest()}
+
+
+def _attachment_data(binding, attested, params):
+ """Transfer bytes, not foreign filenames, with a task fence on every chunk."""
+ from gateway.hosted_room_driver import validate_bound_task_manifest
+ manifest = attested.get('attachments', [])
+ if not manifest:
+ return []
+ manifest = validate_bound_task_manifest(manifest)
+ result = []
+ for index, item in enumerate(manifest):
+ data = bytearray()
+ digest = None
+ 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)})
+ 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 (digest is not None and digest != chunk['sha256'])):
+ raise RuntimeStoreError('permission_denied')
+ digest = chunk['sha256']
+ data.extend(raw)
+ if hashlib.sha256(data).hexdigest() != digest:
+ raise RuntimeStoreError('permission_denied')
+ result.append((item, bytes(data)))
+ return result
+
+
def _principal(authority, binding):
# Source-profile namespace prevents equal room owner strings on other owners
# from aliasing a target's principal. Never widen Principal.profile_id.
@@ -98,7 +146,7 @@ def install_hosted_transport(server, authority, loop, *, attest):
def source(params, peer):
if set(params) != {'selector', 'operation', 'params'}:
raise RuntimeStoreError('invalid_params')
- if params['operation'] not in _OPERATIONS | {'execute'}:
+ if params['operation'] not in _OPERATIONS | {'execute', 'attachment'}:
raise RuntimeStoreError('invalid_params')
return attest(params['selector'], params['operation'], params['params'])
@@ -130,6 +178,8 @@ def install_hosted_transport(server, authority, loop, *, attest):
conn.execute('INSERT OR IGNORE INTO state_meta(key,value) VALUES(?,?)', (key, encoded))
authority.db._execute_write(persist)
if operation == 'submit':
+ rpc.hosted_attachment_data = _attachment_data(binding, attested, params)
+ params['attachments'] = attested['attachments'] or None
params['task'] = TaskIdentity(**params['task'])
params['on_terminal'] = lambda value: None
result = rpc._call(operation, **params)
@@ -158,10 +208,15 @@ def check_remote_hosted_admission(authority, ref, row):
or ref.profile_id != authority.profile_id
or binding.get('target_home') != authority.profile_id):
raise ValueError('binding mismatch')
- owner = _attest(binding, 'execute', {'task': identity,
- 'execution_generation': generation, 'prompt': row['payload']['text']})
- if owner['owner'] != binding['owner']:
+ params = {'task': identity, 'execution_generation': generation}
+ attested = _attest(binding, 'execute', params)
+ if attested['owner'] != binding['owner']:
raise ValueError('owner changed')
+ from gateway.session_hosted_attachments import submission_payload
+ rpc = SimpleNamespace(authority=authority, **binding['selector'],
+ hosted_attachment_data=_attachment_data(binding, attested, params))
+ if row['payload'] != submission_payload(rpc, attested['prompt'], attested['attachments']):
+ raise ValueError('input changed')
except (ValueError, KeyError, TypeError) as exc:
raise RuntimeStoreError('permission_denied') from exc
return True
diff --git a/tests/gateway/test_session_hosted_transport.py b/tests/gateway/test_session_hosted_transport.py
index ef70d8301a0..4b72204b331 100644
--- a/tests/gateway/test_session_hosted_transport.py
+++ b/tests/gateway/test_session_hosted_transport.py
@@ -74,3 +74,85 @@ def test_authenticated_owner_transport_rechecks_source_and_cold_binding(owner, t
finally:
for server in servers:
asyncio.run_coroutine_threadsafe(server.stop(), loop).result()
+
+
+def test_source_attestation_binds_bytes_to_task_member_and_current_home(tmp_path, monkeypatch):
+ import base64
+ import time
+ from types import SimpleNamespace
+ from gateway.session_hosted_service import CanonicalHostedRoomService
+ from gateway import hosted_room_driver as tasks
+ from gateway.hosted_rooms import create_room, local_authority_gateway_id
+ from gateway.hosted_room_attachments import HostedRoomAttachmentStore
+ from hermes_state import SessionDB
+ from hermes_state_runtime import begin_runtime_epoch, RuntimeStoreError
+ from tui_gateway.hosted_room_driver import HostedRoomBinding
+ import gateway.run
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ homes = {'other': str(tmp_path / 'profiles' / 'other')}
+ monkeypatch.setattr(gateway.run, '_load_gateway_config', lambda: {'hosted_rooms': {'profiles': homes}})
+ with SessionDB(tmp_path / 'state.db') as db:
+ authority = SimpleNamespace(db=db, profile_id=str(tmp_path), epoch=begin_runtime_epoch(db, instance_id='test'))
+ service = CanonicalHostedRoomService(authority, None)
+ service.authorize_room('alice', 'room', create=True)
+ gateway = local_authority_gateway_id()
+ create_room(db.db_path, room_id='room', name='Room', authority_gateway_id=gateway, members=[
+ {'member_id': 'one', 'profile': 'default', 'handle': 'one'},
+ {'member_id': 'two', 'profile': 'other', 'handle': 'two'}])
+ data = b'owned source bytes' * 4000
+ store = HostedRoomAttachmentStore(db.db_path)
+ saved = store.put(room_id='room', upload_id='upload', kind='file', name='note.txt', mime='text/plain', data=data)
+ manifest = [{k: saved[k] for k in ('attachment_id', 'kind', 'name', 'size', 'mime')}]
+ store.commit_message(room_id='room', event_id='event', manifest=manifest, recipient_member_ids=['two'])
+ bound = [{**manifest[0], 'event_id': 'event'}]
+ identity = tasks.TaskIdentity('room', 'task', 'thread', 'turn')
+ payload = {'target_profile': 'other', 'target_member_id': 'two', 'source_event_seq': 1,
+ 'prompt': 'frozen', 'attachments': bound}
+ tasks.admit_task(db.db_path, identity, payload=payload, clock=time.time)
+ lease = tasks.acquire_lease(db.db_path, room_id='room', gateway_id=gateway, authority_epoch=1,
+ process_generation='test', ttl_seconds=30, clock=time.time)
+ tasks.start_task(db.db_path, identity, lease, expected_cancel_generation=0, clock=time.time)
+ task, = tasks.list_tasks(db.db_path, room_id='room')
+ selector = dict(room_id='room', member_id='two', profile='other')
+ params = dict(task=asdict(identity), execution_generation=task['execution_generation'],
+ prompt='frozen', attachments=bound, _target_home=homes['other'])
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ service.attest(selector, 'submit', {**params, 'attachments': []})
+ assert service.attest(selector, 'submit', params)['attachments'] == bound
+ chunks = []
+ for offset in range(0, len(data), 24576):
+ result = service.attest(selector, 'attachment', {**params, 'index': 0, 'offset': offset})
+ chunks.append(base64.b64decode(result['data_base64']))
+ assert b''.join(chunks) == data
+ from gateway.control_socket import GatewayControlServer
+ from gateway.session_hosted_transport import install_hosted_transport, _attachment_data
+ # The same chunk protocol crosses a real private socket; the target never
+ # receives a filesystem path or opens the source database.
+ loop = asyncio.new_event_loop()
+ thread = threading.Thread(target=loop.run_forever)
+ thread.start()
+ server = GatewayControlServer(tmp_path)
+ install_hosted_transport(server, authority, loop, attest=service.attest)
+ assert asyncio.run_coroutine_threadsafe(server.start(), loop).result()
+ try:
+ transport_binding = {'source_home': str(tmp_path), 'target_home': homes['other'], 'selector': selector}
+ attested = service.attest(selector, 'submit', params)
+ assert _attachment_data(transport_binding, attested, params) == [(bound[0], data)]
+ finally:
+ asyncio.run_coroutine_threadsafe(server.stop(), loop).result()
+ loop.call_soon_threadsafe(loop.stop)
+ thread.join()
+ loop.close()
+ for bad in ({'execution_generation': 999}, {'_target_home': str(tmp_path / 'wrong')},
+ {'attachments': [{**bound[0], 'event_id': 'other'}]}, {'index': 1}, {'offset': -1}):
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ service.attest(selector, 'attachment', {**params, 'index': 0, 'offset': 0, **bad})
+ binding = HostedRoomBinding('room', gateway, 1)
+ old_rpc = service._resolve_member_transport(binding, task)
+ homes['other'] = str(tmp_path / 'replacement' / 'profiles' / 'other')
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ service.attest(selector, 'history', params)
+ assert service._resolve_member_transport(binding, task) is not old_rpc
+ homes.clear()
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ service._resolve_member_transport(binding, task)