The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: ACP image staging takes its type from the bytes; staging refuses hardlinks
Tekniume746794aaf34
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex 9f4150e86b1..4525716fd4f 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -27,7 +27,9 @@ def _stage_user_content(content):if isinstance(content, str):return content, []import base64+ import binasciifrom gateway.platforms.base import cache_image_from_bytes+ from gateway.session_ingress_media import _ATTACHMENT_LIMIT, _IMAGE_EXT, sniff_image_mimetexts, attachments = [], []for part in content:if part.get('type') == 'text':@@ -38,9 +40,20 @@ def _stage_user_content(content):texts.append(f"[Image attached: {url}]")continueheader, _, data = url.partition(',')- mime = header[len('data:'):].split(';', 1)[0] or 'image/png'+ declared = header[len('data:'):].split(';', 1)[0].strip().lower()+ if len(attachments) >= _ATTACHMENT_LIMIT:+ raise GatewayClientError('acp_content_invalid')try:- path = cache_image_from_bytes(base64.b64decode(data), '.' + mime.split('/', 1)[1])+ raw = base64.b64decode(data, validate=True)+ except (binascii.Error, ValueError) as exc:+ raise GatewayClientError('acp_content_invalid') from exc+ # The staged extension and admitted type come from the sniffed bytes, never the client's+ # text (``text/html`` -> .html, ``image/svg+xml``, or a path-shaped subtype on Windows).+ mime = sniff_image_mime(raw)+ if mime is None or (declared and {'image/jpg': 'image/jpeg'}.get(declared, declared) != mime):+ raise GatewayClientError('acp_content_invalid')+ try:+ path = cache_image_from_bytes(raw, _IMAGE_EXT[mime])except ValueError as exc:raise GatewayClientError('acp_content_invalid') from excattachments.append({'path': path, 'mime': mime})diff --git a/gateway/session_api_media.py b/gateway/session_api_media.pyindex 0391350ee69..0438a5f6652 100644--- a/gateway/session_api_media.py+++ b/gateway/session_api_media.py@@ -9,18 +9,6 @@ _MIME_EXT = {'image/png': '.png', 'image/jpeg': '.jpg', 'image/gif': '.gif', 'im_IMAGE_LIMIT = 10-def _sniffed_mime(data):- if data.startswith(b'\x89PNG\r\n\x1a\n'):- return 'image/png'- if data.startswith(b'\xff\xd8\xff'):- return 'image/jpeg'- if data[:6] in (b'GIF87a', b'GIF89a'):- return 'image/gif'- if data[:4] == b'RIFF' and data[8:12] == b'WEBP':- return 'image/webp'- return None--def _data_url_bytes(url):"""``(mime, bytes)`` for a committable ``data:image/...;base64,`` URL, else ``None``."""header, _, encoded = url.partition(',')@@ -43,15 +31,15 @@ def commit_api_images(content):"""Stage every inline ``data:`` image deterministically (same bytes -> same path, so anexact retry keeps its admission digest) and commit the bytes as immutable media."""from gateway.platforms.base import get_image_cache_dir- from gateway.session_ingress_media import capture_native_mediafrom gateway.platforms.base import get_inbound_media_max_bytes+ from gateway.session_ingress_media import capture_native_media, sniff_image_mimefrom hermes_state_runtime import RuntimeStoreErrorimages = [decoded for decoded in map(_data_url_bytes, _image_urls(content)) if decoded is not None]# Validate the whole batch before one byte lands on disk: a refused request must not# leave staged or committed bytes behind, and the declared type must be the real one.limit = max(0, get_inbound_media_max_bytes())if (len(images) > _IMAGE_LIMIT or (limit and sum(len(data) for _, data in images) > limit)- or any(_sniffed_mime(data) != mime for mime, data in images)):+ or any(sniff_image_mime(data) != mime for mime, data in images)):raise RuntimeStoreError('invalid_params')staged = []for mime, data in images:diff --git a/gateway/session_ingress_media.py b/gateway/session_ingress_media.pyindex 4e21ce64dfd..86c7fb8e52b 100644--- a/gateway/session_ingress_media.py+++ b/gateway/session_ingress_media.py@@ -26,6 +26,20 @@ def _media_root():# cleanup of the staging file can change what executes._ATTACHMENT_MIMES = frozenset({'image/png', 'image/jpeg', 'image/gif', 'image/webp'})_ATTACHMENT_LIMIT = 10+_IMAGE_EXT = {'image/png': '.png', 'image/jpeg': '.jpg', 'image/gif': '.gif', 'image/webp': '.webp'}+++def sniff_image_mime(data):+ """The admission image type the bytes really are (png/jpeg/gif/webp), else ``None``."""+ if data.startswith(b'\x89PNG\r\n\x1a\n'):+ return 'image/png'+ if data.startswith(b'\xff\xd8\xff'):+ return 'image/jpeg'+ if data[:6] in (b'GIF87a', b'GIF89a'):+ return 'image/gif'+ if data[:4] == b'RIFF' and data[8:12] == b'WEBP':+ return 'image/webp'+ return Nonedef admit_attachments(attachments):@@ -42,6 +56,12 @@ def admit_attachments(attachments):paths = [Path(item['path']) for item in attachments]if any(not path.is_absolute() or path.resolve().parent != staging for path in paths):raise RuntimeStoreError('invalid_params')+ # A hardlink placed in staging is a second name for a file outside it (~/.ssh/id_rsa).+ try:+ if any(path.lstat().st_nlink != 1 for path in paths):+ raise RuntimeStoreError('invalid_params')+ except OSError as exc:+ raise RuntimeStoreError('invalid_params') from excreturn {'attachments_v1': {'media': capture_native_media(paths),'media_types': [item['mime'] for item in attachments]}}diff --git a/tests/acp_adapter/test_acp_image_staging_boundary.py b/tests/acp_adapter/test_acp_image_staging_boundary.pynew file mode 100644index 00000000000..6952f6b186f--- /dev/null+++ b/tests/acp_adapter/test_acp_image_staging_boundary.py@@ -0,0 +1,45 @@+"""prompt.submit attachments and ACP image staging stay inside the profile image cache (PR #106742 security lane)."""+import base64+import os+from pathlib import Path++import pytest++from hermes_state_runtime import RuntimeStoreError++PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 32+++def test_hardlink_in_staging_to_outside_file_is_refused(tmp_path, monkeypatch):+ from gateway.platforms import base+ from gateway.session_ingress_media import admit_attachments+ staging = tmp_path / "home" / "cache" / "images"+ staging.mkdir(parents=True)+ monkeypatch.setattr(base, "get_image_cache_dir", lambda: staging)+ monkeypatch.setattr(base, "get_document_cache_dir", lambda: tmp_path / "home" / "cache" / "documents")+ secret = tmp_path / "id_rsa"+ secret.write_bytes(PNG + b"PRIVATE")+ (staging / "own.png").write_bytes(PNG)+ assert admit_attachments([{"path": str(staging / "own.png"), "mime": "image/png"}]) # control+ os.link(secret, staging / "planted.png")+ with pytest.raises(RuntimeStoreError):+ admit_attachments([{"path": str(staging / "planted.png"), "mime": "image/png"}])++[email protected]("mime", ["image/png/../../../../escape", "image/svg+xml", "text/html", "image/gif"])+def test_acp_image_mime_never_chooses_the_staged_extension(tmp_path, monkeypatch, mime):+ """The extension comes from the sniffed bytes (png/jpeg/gif/webp), never the client's text;+ a declared type that disagrees with the bytes (PNG bytes as image/gif) is refused too."""+ from acp.schema import ImageContentBlock+ from acp_adapter.content import _content_blocks_to_openai_user_content+ from acp_adapter.gateway_server import _stage_user_content+ from gateway.platforms import base+ from hermes_cli.gateway_client import GatewayClientError+ staging = tmp_path / "home" / "cache" / "images"+ staging.mkdir(parents=True)+ monkeypatch.setattr(base, "get_image_cache_dir", lambda: staging)+ block = ImageContentBlock(type="image", data=base64.b64encode(PNG).decode(), mime_type=mime)+ with pytest.raises(GatewayClientError):+ _stage_user_content(_content_blocks_to_openai_user_content([block]))+ assert list(staging.iterdir()) == []+