The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): digest-only hosted preflight verifies retained documents at the destination
teknium167c1e39c2608
diff --git a/gateway/session_hosted_attachments.py b/gateway/session_hosted_attachments.pyindex 4978314b385..df960f6945c 100644--- a/gateway/session_hosted_attachments.py+++ b/gateway/session_hosted_attachments.py@@ -141,17 +141,13 @@ def committed_submission_payload(rpc, prompt, attachments=None):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.+def _attested_inputs(attachments, digests):+ """``(manifest item, retained reference)`` per bound input, from source-attested digests.- 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.+ Retained inputs are content-addressed under ``native-inputs/<sha256>/<name>`` (images+ under their digest-named staging copy), so the destination path of every input is a+ pure function of manifest and digest; nothing is transferred to compute it."""- if not attachments:- return {'text': prompt}from gateway.hosted_room_driver import validate_bound_task_manifestfrom gateway.hosted_room_attachments import _SHA256_REfrom gateway.session_ingress_media import _ATTACHMENT_MIMES, _media_root@@ -160,13 +156,48 @@ def attested_submission_payload(prompt, attachments, digests):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 = [], [], []+ inputs = []for item, digest in zip(manifest, digests):+ name = digest + Path(item['name']).suffix if item['mime'] in _ATTACHMENT_MIMES else item['name']+ inputs.append((item, {'path': str(root / digest / name), 'sha256': digest, 'size': item['size']}))+ return inputs+++def attested_submission_payload(prompt, attachments, digests):+ """The payload ``committed_submission_payload`` commits for these inputs, derived from+ source-attested digests alone.++ 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. Images ride as ``attachments_v1`` references that+ ``restore_native_media`` re-verifies at execution; documents ride in the prompt text as+ paths only, so their retained bytes are checked by ``verify_attested_documents``.+ """+ if not attachments:+ return {'text': prompt}+ from gateway.session_ingress_media import _ATTACHMENT_MIMES+ documents, media, media_types = [], [], []+ for item, reference in _attested_inputs(attachments, digests):if item['mime'] in _ATTACHMENT_MIMES:- media.append({'path': str(root / digest / (digest + Path(item['name']).suffix)),- 'sha256': digest, 'size': item['size']})+ media.append(reference)media_types.append(item['mime'])else:- documents.append(str(root / digest / item['name']))+ documents.append(reference['path'])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 {})}+++def verify_attested_documents(attachments, digests):+ """Refuse ``storage_unavailable`` unless every retained document at the destination+ still hashes to its source-attested digest.++ A document is embedded in the prompt as a content-addressed path, not a structured+ reference, so execution reads whatever bytes sit there; a retained file mutated in+ place or deleted must pause the row here, as ``committed_submission_payload`` did+ before the digest-only preflight. Reads destination bytes only, never the source.+ """+ if not attachments:+ return+ from gateway.session_ingress_media import _ATTACHMENT_MIMES, restore_native_media+ restore_native_media([reference for item, reference in _attested_inputs(attachments, digests)+ if item['mime'] not in _ATTACHMENT_MIMES])diff --git a/gateway/session_hosted_transport.py b/gateway/session_hosted_transport.pyindex 35d7ca2de6b..657fc47f441 100644--- a/gateway/session_hosted_transport.py+++ b/gateway/session_hosted_transport.py@@ -292,12 +292,15 @@ def _check_remote_hosted_admission(authority, ref, row):raise ValueError('owner changed')# 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+ from gateway.session_hosted_attachments import attested_submission_payload, verify_attested_documentsif 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+ # Outside the permission_denied fold: a corrupted or missing retained document is a+ # storage fault of this destination, not a revoked source binding.+ verify_attested_documents(attested['attachments'], attested.get('attachment_digests'))return Truediff --git a/tests/gateway/test_session_hosted_transport.py b/tests/gateway/test_session_hosted_transport.pyindex 95ad38ac4d8..7423f953323 100644--- a/tests/gateway/test_session_hosted_transport.py+++ b/tests/gateway/test_session_hosted_transport.py@@ -315,3 +315,60 @@ def test_preflight_verifies_by_attested_digest_and_refuses_changed_source_bytes(rpc.callbacks.clear()for server in servers:asyncio.run_coroutine_threadsafe(server.stop(), loop).result()+++def test_preflight_refuses_a_retained_document_corrupted_or_missing_at_the_destination(owner, tmp_path, monkeypatch):+ """Documents ride in the prompt as content-addressed paths, so execution never re-hashes+ them: the digest-only preflight must itself refuse ``storage_unavailable`` when the+ destination bytes no longer match the source-attested digest (same-size mutation) or+ are gone, still without transferring bytes from the source. Images are unaffected."""+ 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 ' * 2000)+ 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)+ with rpc._lock:+ rpc.callbacks.clear()+ rpc._monitor.join(5)+ ref = SessionRef(authority.profile_id, sid)+ assert check_remote_hosted_admission(authority, ref, row) is True+ from pathlib import Path+ retained = Path(row['payload']['text'].split('[Shared attachment] file: ')[1].strip())+ assert retained.read_bytes() == source.data+ operations.clear()+ retained.write_bytes(bytes([source.data[0] ^ 1]) + source.data[1:])+ with pytest.raises(RuntimeStoreError, match='storage_unavailable'):+ check_remote_hosted_admission(authority, ref, row)+ retained.unlink()+ with pytest.raises(RuntimeStoreError, match='storage_unavailable'):+ check_remote_hosted_admission(authority, ref, row)+ assert operations == ['execute', 'execute'], 'destination verification must not re-transfer bytes'+ assert row == list_session_admissions(authority.db, session_id=sid, pending_only=False)[0]+ finally:+ with rpc._lock:+ rpc.callbacks.clear()+ for server in servers:+ asyncio.run_coroutine_threadsafe(server.stop(), loop).result()