Skip to content

The agent that grows with you

perf(gateway): preflight hosted attachments by source-attested digest, not bytes

teknium142aaae9f8cb1
diff --git a/gateway/hosted_room_attachments.py b/gateway/hosted_room_attachments.py
index 2a3c7137f05..86f704fba91 100644
--- a/gateway/hosted_room_attachments.py
+++ b/gateway/hosted_room_attachments.py
@@ -887,6 +887,28 @@ class HostedRoomAttachmentStore:
)
return AttachmentData(self._metadata(row), data)
+ def describe(
+ self,
+ *,
+ room_id: Any,
+ attachment_id: Any,
+ recipient_member_id: Any,
+ event_id: Any,
+ ) -> dict[str, Any]:
+ """``read`` without bytes: the metadata (including the upload-verified SHA-256) of a
+ committed attachment this recipient may read for this event."""
+ room_id = _identifier(room_id, label="room_id")
+ attachment_id = _attachment_id(attachment_id)
+ recipient_member_id = _identifier(recipient_member_id, label="recipient_member_id")
+ normalized_event = _identifier(event_id, label="event_id")
+ with self._transaction() as conn:
+ row = self._read_committed_row(
+ conn, room_id=room_id, attachment_id=attachment_id,
+ recipient_member_id=recipient_member_id,
+ normalized_event=normalized_event, viewer=False, now=float(self.clock()),
+ )
+ return self._metadata(row)
+
def read_range(
self,
*,
diff --git a/gateway/session_hosted_attachments.py b/gateway/session_hosted_attachments.py
index 698592ddb1b..4978314b385 100644
--- a/gateway/session_hosted_attachments.py
+++ b/gateway/session_hosted_attachments.py
@@ -139,3 +139,34 @@ def committed_submission_payload(rpc, prompt, attachments=None):
from gateway.session_ingress_media import admit_attachments
payload = submission_payload(rpc, prompt, attachments)
return {'text': payload['text'], **admit_attachments(payload.get('attachments'))}
+
+
+def attested_submission_payload(prompt, attachments, digests):
+ """The payload ``committed_submission_payload`` commits for these inputs, derived from
+ source-attested digests alone.
+
+ Retained inputs are content-addressed under ``native-inputs/<sha256>/<name>``, so the
+ durable row is a pure function of prompt, manifest and per-file digest; a source
+ attachment re-pointed at other bytes yields another payload and is refused without
+ transferring anything. ``restore_native_media`` re-verifies the bytes at execution.
+ """
+ if not attachments:
+ return {'text': prompt}
+ from gateway.hosted_room_driver import validate_bound_task_manifest
+ from gateway.hosted_room_attachments import _SHA256_RE
+ from gateway.session_ingress_media import _ATTACHMENT_MIMES, _media_root
+ manifest = validate_bound_task_manifest(attachments)
+ if (not isinstance(digests, list) or len(digests) != len(manifest)
+ or any(not isinstance(d, str) or _SHA256_RE.fullmatch(d) is None for d in digests)):
+ raise RuntimeStoreError('permission_denied')
+ root = _media_root()
+ documents, media, media_types = [], [], []
+ for item, digest in zip(manifest, digests):
+ if item['mime'] in _ATTACHMENT_MIMES:
+ media.append({'path': str(root / digest / (digest + Path(item['name']).suffix)),
+ 'sha256': digest, 'size': item['size']})
+ media_types.append(item['mime'])
+ else:
+ documents.append(str(root / digest / item['name']))
+ text = prompt + ''.join('\n[Shared attachment] file: ' + path + '\n' for path in documents)
+ return {'text': text, **({'attachments_v1': {'media': media, 'media_types': media_types}} if media else {})}
diff --git a/gateway/session_hosted_service.py b/gateway/session_hosted_service.py
index 8343ab35a7c..47a2e7376a3 100644
--- a/gateway/session_hosted_service.py
+++ b/gateway/session_hosted_service.py
@@ -84,7 +84,10 @@ class CanonicalHostedRoomService(HostedControls, HostedRoomService):
from gateway.session_hosted_transport import source_attachment_chunk
result.update(source_attachment_chunk(self, member, room_id, payload.get('attachments', []), params))
else:
- result.update(prompt=payload['prompt'], attachments=payload.get('attachments', []))
+ from gateway.session_hosted_transport import source_attachment_digests
+ manifest = payload.get('attachments', [])
+ result.update(prompt=payload['prompt'], attachments=manifest,
+ attachment_digests=source_attachment_digests(self, member, room_id, manifest))
return result
diff --git a/gateway/session_hosted_transport.py b/gateway/session_hosted_transport.py
index 49d15ee12c3..55ca2d9edf3 100644
--- a/gateway/session_hosted_transport.py
+++ b/gateway/session_hosted_transport.py
@@ -8,7 +8,6 @@ from __future__ import annotations
import asyncio
import base64
from dataclasses import asdict
-from types import SimpleNamespace
import hashlib
import json
import os
@@ -123,6 +122,24 @@ def source_attachment_chunk(service, member, room_id, manifest, params):
'sha256': saved.attachment['sha256']}
+def source_attachment_digests(service, member, room_id, manifest):
+ """Upload-verified SHA-256 of every bound input, read on the source owner's handler.
+
+ Rides on the submit/execute attest result so the target can bind transferred bytes
+ to the attested input and the preflight can verify the durable row without bytes.
+ """
+ from gateway.hosted_room_attachments import HostedRoomAttachmentStore
+ store = HostedRoomAttachmentStore(service.db_path)
+ digests = []
+ for item in manifest:
+ saved = store.describe(room_id=room_id, attachment_id=item['attachment_id'],
+ event_id=item['event_id'], recipient_member_id=member)
+ if any(saved[key] != item[key] for key in ('kind', 'name', 'mime', 'size')):
+ raise RuntimeStoreError('permission_denied')
+ digests.append(saved['sha256'])
+ return digests
+
+
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
@@ -130,20 +147,20 @@ def _attachment_data(binding, attested, params):
if not manifest:
return []
manifest = validate_bound_task_manifest(manifest)
+ digests = attested.get('attachment_digests')
+ if not isinstance(digests, list) or len(digests) != len(manifest):
+ raise RuntimeStoreError('permission_denied')
result = []
- for index, item in enumerate(manifest):
+ for index, (item, digest) in enumerate(zip(manifest, digests)):
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'])):
+ if chunk['owner'] != attested['owner'] or len(raw) != expected or chunk['sha256'] != digest:
raise RuntimeStoreError('permission_denied')
- digest = chunk['sha256']
data.extend(raw)
if hashlib.sha256(data).hexdigest() != digest:
raise RuntimeStoreError('permission_denied')
@@ -269,10 +286,11 @@ def _check_remote_hosted_admission(authority, ref, row):
attested = _attest(binding, 'execute', params)
if attested['owner'] != binding['owner']:
raise ValueError('owner changed')
- from gateway.session_hosted_attachments import committed_submission_payload
- rpc = SimpleNamespace(authority=authority, **binding['selector'],
- hosted_attachment_data=_attachment_data(binding, attested, params))
- if row['payload'] != committed_submission_payload(rpc, attested['prompt'], attested['attachments']):
+ # Bytes are not re-transferred here: the durable row is compared against the
+ # payload the attested prompt, manifest and source-verified digests commit to.
+ from gateway.session_hosted_attachments import attested_submission_payload
+ if row['payload'] != attested_submission_payload(
+ attested['prompt'], attested['attachments'], attested.get('attachment_digests')):
raise ValueError('input changed')
except (ValueError, KeyError, TypeError) as exc:
raise RuntimeStoreError('permission_denied') from exc
diff --git a/tests/gateway/test_session_hosted_transport.py b/tests/gateway/test_session_hosted_transport.py
index e09bf2ef582..95ad38ac4d8 100644
--- a/tests/gateway/test_session_hosted_transport.py
+++ b/tests/gateway/test_session_hosted_transport.py
@@ -255,3 +255,63 @@ def test_attachment_chunks_fill_the_response_line_without_overflowing_it(tmp_pat
assert len(lines) == math.ceil(len(source.data) / _CHUNK_BYTES) == 3
assert max(lines) <= _MAX_RESPONSE_BYTES
assert max(lines) > _MAX_RESPONSE_BYTES * 3 // 4, 'chunks leave most of the response line unused'
+
+
+def test_preflight_verifies_by_attested_digest_and_refuses_changed_source_bytes(owner, tmp_path, monkeypatch):
+ """check_remote_hosted_admission proves the durable row still matches the source's
+ bound input from source-attested digests, transferring no bytes; a source attachment
+ re-pointed at different bytes (same id, name and size) is still refused."""
+ from gateway import session_hosted_transport as transport
+ from gateway.session_hosted_transport import HostedRoomOwnerRPC, check_remote_hosted_admission
+ from gateway.session_contract import SessionRef
+ from hermes_state_runtime import list_session_admissions, RuntimeStoreError
+ authority, loop, _, _ = owner
+ target_home = tmp_path / 'profiles' / 'other'
+ target_home.mkdir(parents=True, mode=0o700)
+ authority.profile_id = str(target_home)
+ source = _SourceTask(tmp_path, monkeypatch, b'document bytes ' * 20000)
+ operations = []
+ real_request = transport.owner_request
+ def counting_request(home, verb, params, **kwargs):
+ operations.append(params.get('operation'))
+ return real_request(home, verb, params, **kwargs)
+ monkeypatch.setattr(transport, 'owner_request', counting_request)
+ servers = [_server(tmp_path), _server(target_home)]
+ 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 = HostedRoomOwnerRPC(home=target_home, source_home=tmp_path, **source.selector)
+ coords = dict(profile='other', source='bot_room')
+ sid = rpc.create(**coords, title='Group: room')['session_id']
+ rpc.submit(**coords, session_id=sid, prompt='frozen', task=source.identity,
+ execution_generation=1, attachments=source.bound, on_terminal=lambda r: None)
+ row, = list_session_admissions(authority.db, session_id=sid, pending_only=False)
+ assert 'attachment' in operations
+ # Quiesce the driver-side history poller before counting the preflight.
+ with rpc._lock:
+ rpc.callbacks.clear()
+ rpc._monitor.join(5)
+ operations.clear()
+ ref = SessionRef(authority.profile_id, sid)
+ assert check_remote_hosted_admission(authority, ref, row) is True
+ assert operations == ['execute'], 'preflight must verify by digest, not re-transfer bytes'
+ # Same name and size, different bytes: re-point the committed row at another blob.
+ changed = source.store.put(room_id='room', upload_id='upload-2', kind='file', name='note.txt',
+ mime='text/plain', data=b'DOCUMENT BYTES ' * 20000)
+ assert changed['size'] == source.bound[0]['size'] and changed['sha256'] != source.store.read(
+ room_id='room', attachment_id=source.bound[0]['attachment_id'], event_id='event',
+ recipient_member_id='two').attachment['sha256']
+ with source.store._transaction() as conn:
+ conn.execute('UPDATE hosted_room_attachments SET sha256=?, blob_id=(SELECT blob_id FROM '
+ 'hosted_room_attachments WHERE attachment_id=?) WHERE attachment_id=?',
+ (changed['sha256'], changed['attachment_id'], source.bound[0]['attachment_id']))
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ check_remote_hosted_admission(authority, ref, row)
+ finally:
+ with rpc._lock:
+ rpc.callbacks.clear()
+ for server in servers:
+ asyncio.run_coroutine_threadsafe(server.stop(), loop).result()