Skip to content

The agent that grows with you

fix(security): route remote-party-supplied URL fetches through the SSRF guard

beardthelion3933fdf63b48
diff --git a/agent/pet/manifest.py b/agent/pet/manifest.py
index ebd76f68bad..60ff176848a 100644
--- a/agent/pet/manifest.py
+++ b/agent/pet/manifest.py
@@ -104,7 +104,12 @@ def fetch_manifest(*, timeout: float = _DEFAULT_TIMEOUT, force: bool = False) ->
except ImportError as exc: # pragma: no cover - httpx is a core dep
raise ManifestError("httpx is required to fetch the petdex manifest") from exc
try:
- resp = httpx.get(MANIFEST_URL, timeout=timeout, follow_redirects=True, headers={"User-Agent": "hermes-agent-petdex"})
+ from tools.url_safety import create_ssrf_safe_client, is_safe_url
+
+ if not is_safe_url(MANIFEST_URL):
+ raise ManifestError(f"Pet manifest URL failed the SSRF safety check: {MANIFEST_URL}")
+ with create_ssrf_safe_client(timeout=timeout, follow_redirects=True) as client:
+ resp = client.get(MANIFEST_URL, headers={"User-Agent": "hermes-agent-petdex"})
resp.raise_for_status()
payload = resp.json()
except Exception as exc: # noqa: BLE001 - normalize to one error type
diff --git a/agent/pet/store.py b/agent/pet/store.py
index afc4f0f7fbe..fb0d88f00c0 100644
--- a/agent/pet/store.py
+++ b/agent/pet/store.py
@@ -304,10 +304,14 @@ def rename_pet(slug: str, display_name: str) -> str | None:
def _http_get(url: str, timeout: float):
- """GET *url* with the petdex UA, following redirects; raises on HTTP errors."""
- import httpx
-
- resp = httpx.get(url, timeout=timeout, follow_redirects=True, headers=_HTTP_HEADERS)
+ """GET *url* with the petdex UA, following redirects; raises on HTTP errors.
+ Manifest-derived URLs are remote-party-controlled — SSRF-checked first."""
+ from tools.url_safety import create_ssrf_safe_client, is_safe_url
+
+ if not is_safe_url(url):
+ raise ValueError(f"Pet store URL failed the SSRF safety check: {url}")
+ with create_ssrf_safe_client(timeout=timeout, follow_redirects=True) as client:
+ resp = client.get(url, headers=_HTTP_HEADERS)
resp.raise_for_status()
return resp
@@ -317,7 +321,12 @@ def _download(url: str, dest: Path, *, timeout: float) -> None:
import httpx
try:
- with httpx.stream("GET", url, timeout=timeout, follow_redirects=True, headers=_HTTP_HEADERS) as resp:
+ from tools.url_safety import create_ssrf_safe_client, is_safe_url
+
+ if not is_safe_url(url):
+ raise ValueError(f"Pet store URL failed the SSRF safety check: {url}")
+ with create_ssrf_safe_client(timeout=timeout, follow_redirects=True) as client, \
+ client.stream("GET", url, headers=_HTTP_HEADERS) as resp:
resp.raise_for_status()
tmp = dest.with_suffix(dest.suffix + ".part")
with tmp.open("wb") as fh:
diff --git a/agent/provider_media.py b/agent/provider_media.py
index 1db99e9f9a7..bdad62f4f6e 100644
--- a/agent/provider_media.py
+++ b/agent/provider_media.py
@@ -14,6 +14,10 @@ import datetime
import uuid
from pathlib import Path
from typing import Dict, Optional, Tuple
+from urllib.parse import urljoin
+
+_REDIRECT_STATUS_CODES = {301, 302, 303, 307, 308}
+_MAX_SAVE_URL_REDIRECTS = 5
def cache_dir(kind: str) -> Path:
@@ -55,43 +59,64 @@ def save_url(
the URL suffix (some CDNs return ``application/octet-stream``), then
*default_extension*. Raises on any network / HTTP / oversize / empty error so
callers can fall back to the bare URL; a partial file is never left behind.
- """
- import requests
- response = requests.get(url, headers=headers, timeout=timeout, stream=True)
- response.raise_for_status()
-
- content_type = (response.headers.get("Content-Type") or "").split(";", 1)[0].strip().lower()
- extension = content_types.get(content_type)
- if require_known_content_type and extension is None:
- raise ValueError(
- f"{label} download returned unexpected Content-Type {content_type or '(missing)'}"
- )
- if extension is None:
- url_path = url.split("?", 1)[0].lower()
- extension = next(
- ("jpg" if ext == "jpeg" else ext for ext in url_extensions if url_path.endswith(f".{ext}")),
- default_extension,
- )
- path = cache_path(kind, prefix, extension)
- bytes_written = 0
- with path.open("wb") as fh:
- for chunk in response.iter_content(chunk_size=chunk_size):
- if not chunk:
- continue
- bytes_written += len(chunk)
- if bytes_written > max_bytes:
- fh.close()
- _unlink_quiet(path)
- raise ValueError(
- f"{label} at {url} exceeds {max_bytes // (1024 * 1024)}MB cap; refusing to cache."
- )
- fh.write(chunk)
-
- if bytes_written == 0:
- _unlink_quiet(path)
- raise ValueError(empty_error.format(url=url))
- return path
+ The URL is provider-supplied, so every hop is validated with
+ ``tools.url_safety`` before a socket opens (and again at TCP connect by the
+ guarded transport, closing DNS-rebinding TOCTOU). Caller-supplied *headers*
+ (e.g. provider auth) go to the first hop only — a redirect target never
+ receives them.
+ """
+ from tools.url_safety import create_ssrf_safe_client, is_safe_url
+
+ current_url, hop_headers = url, headers
+ for _ in range(_MAX_SAVE_URL_REDIRECTS + 1):
+ if not is_safe_url(current_url):
+ raise ValueError(f"{label} URL failed the SSRF safety check: {current_url}")
+ with create_ssrf_safe_client(timeout=timeout, follow_redirects=False) as client:
+ with client.stream("GET", current_url, headers=hop_headers) as response:
+ if response.status_code in _REDIRECT_STATUS_CODES:
+ location = response.headers.get("location")
+ if not location:
+ raise ValueError(f"{label} download redirected without a Location: {current_url}")
+ current_url, hop_headers = urljoin(current_url, location), None
+ continue
+ if not response.is_success:
+ response.read()
+ response.raise_for_status()
+
+ content_type = (response.headers.get("Content-Type") or "").split(";", 1)[0].strip().lower()
+ extension = content_types.get(content_type)
+ if require_known_content_type and extension is None:
+ raise ValueError(
+ f"{label} download returned unexpected Content-Type {content_type or '(missing)'}"
+ )
+ if extension is None:
+ url_path = current_url.split("?", 1)[0].lower()
+ extension = next(
+ ("jpg" if ext == "jpeg" else ext for ext in url_extensions if url_path.endswith(f".{ext}")),
+ default_extension,
+ )
+ path = cache_path(kind, prefix, extension)
+ bytes_written = 0
+ with path.open("wb") as fh:
+ for chunk in response.iter_bytes(chunk_size=chunk_size):
+ if not chunk:
+ continue
+ bytes_written += len(chunk)
+ if bytes_written > max_bytes:
+ fh.close()
+ _unlink_quiet(path)
+ raise ValueError(
+ f"{label} at {url} exceeds {max_bytes // (1024 * 1024)}MB cap; refusing to cache."
+ )
+ fh.write(chunk)
+
+ if bytes_written == 0:
+ _unlink_quiet(path)
+ raise ValueError(empty_error.format(url=url))
+
+ return path
+ raise ValueError(f"{label} download exceeded {_MAX_SAVE_URL_REDIRECTS} redirects: {url}")
def _unlink_quiet(path: Path) -> None:
diff --git a/plugins/image_gen/openai-codex/__init__.py b/plugins/image_gen/openai-codex/__init__.py
index f84dcc433d4..6063fef8c46 100644
--- a/plugins/image_gen/openai-codex/__init__.py
+++ b/plugins/image_gen/openai-codex/__init__.py
@@ -117,9 +117,12 @@ def _data_url_to_input_image_url(value: str) -> str:
def _remote_image_to_data_url(value: str) -> str:
"""The edit endpoint takes inline data URLs only (as the official client sends), so fetch."""
- import httpx
+ from tools.url_safety import create_ssrf_safe_client, is_safe_url
- response = httpx.get(value, timeout=60.0, follow_redirects=True)
+ if not is_safe_url(value):
+ raise ValueError(f"Image URL failed the SSRF safety check: {value}")
+ with create_ssrf_safe_client(timeout=60.0, follow_redirects=True) as client:
+ response = client.get(value)
response.raise_for_status()
return _encode_input_image(
response.content,
diff --git a/plugins/image_gen/openai/__init__.py b/plugins/image_gen/openai/__init__.py
index 80e495d4094..2c0742ee8a4 100644
--- a/plugins/image_gen/openai/__init__.py
+++ b/plugins/image_gen/openai/__init__.py
@@ -48,9 +48,12 @@ def _load_image_bytes(ref: str) -> Tuple[bytes, str]:
ref = ref.strip()
lower = ref.lower()
if lower.startswith(("http://", "https://")):
- import requests
+ from tools.url_safety import create_ssrf_safe_client, is_safe_url
- resp = requests.get(ref, timeout=60)
+ if not is_safe_url(ref):
+ raise ValueError(f"Image reference URL failed the SSRF safety check: {ref}")
+ with create_ssrf_safe_client(timeout=60, follow_redirects=True) as client:
+ resp = client.get(ref)
resp.raise_for_status()
name = ref.split("?", 1)[0].rsplit("/", 1)[-1] or "image.png"
return resp.content, name
diff --git a/tests/agent/test_pet_engine.py b/tests/agent/test_pet_engine.py
index 4a6a0c8dab5..4782cb49231 100644
--- a/tests/agent/test_pet_engine.py
+++ b/tests/agent/test_pet_engine.py
@@ -282,3 +282,26 @@ def test_wezterm_is_not_placeholder_capable(monkeypatch):
monkeypatch.setenv("WEZTERM_PANE", "1")
assert render.supports_kitty_placeholders() is False
+
+
+def test_http_get_refuses_ssrf_url():
+ """Manifest-derived URLs are remote-party-controlled — metadata endpoints
+ must be refused before a socket opens."""
+ with pytest.raises(ValueError, match="SSRF"):
+ store._http_get("http://169.254.169.254/latest/meta-data", timeout=5)
+
+
+def test_download_refuses_ssrf_url(tmp_path):
+ dest = tmp_path / "sheet.png"
+ with pytest.raises(store.PetStoreError, match="SSRF"):
+ store._download("http://169.254.169.254/x.png", dest, timeout=5)
+ assert not dest.exists()
+ assert not dest.with_suffix(".png.part").exists()
+
+
+def test_fetch_manifest_refuses_ssrf_url(monkeypatch):
+ """The manifest URL is validated by the SSRF guard before any fetch."""
+ from agent.pet import manifest
+ monkeypatch.setattr(manifest, "MANIFEST_URL", "http://169.254.169.254/api/manifest")
+ with pytest.raises(manifest.ManifestError, match="could not fetch"):
+ manifest.fetch_manifest(force=True)
diff --git a/tests/agent/test_provider_media.py b/tests/agent/test_provider_media.py
index 47f517c78d8..8910278cea4 100644
--- a/tests/agent/test_provider_media.py
+++ b/tests/agent/test_provider_media.py
@@ -5,19 +5,6 @@ import pytest
from agent import provider_media
-class _Response:
- def __init__(self, content_type: str, chunks: list[bytes]):
- self.headers = {"Content-Type": content_type}
- self._chunks = chunks
-
- def raise_for_status(self):
- return None
-
- def iter_content(self, chunk_size: int):
- del chunk_size
- return iter(self._chunks)
-
-
def _save_video(url: str, **kwargs):
return provider_media.save_url(
"videos",
@@ -35,15 +22,30 @@ def _save_video(url: str, **kwargs):
)
+def _stub_fetch(monkeypatch, handler):
+ """Route save_url's fetch through an httpx MockTransport and stub the URL
+ policy check — SSRF behavior has dedicated tests in test_save_url_image.py;
+ these pin the streaming/content-type/headers contract."""
+ import httpx
+
+ monkeypatch.setattr("tools.url_safety.is_safe_url", lambda url: True)
+ monkeypatch.setattr(
+ "tools.url_safety.create_ssrf_safe_client",
+ lambda **kw: httpx.Client(transport=httpx.MockTransport(handler), **kw),
+ )
+
+
def test_save_url_forwards_headers_and_streams_to_cache(monkeypatch, tmp_path):
monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
calls = []
- def fake_get(url, **kwargs):
- calls.append((url, kwargs))
- return _Response("video/mp4", [b"clip"])
+ import httpx
- monkeypatch.setattr("requests.get", fake_get)
+ def handler(request):
+ calls.append(request)
+ return httpx.Response(200, headers={"Content-Type": "video/mp4"}, content=b"clip")
+
+ _stub_fetch(monkeypatch, handler)
path = _save_video(
"https://api.example/videos/job/content",
@@ -53,23 +55,18 @@ def test_save_url_forwards_headers_and_streams_to_cache(monkeypatch, tmp_path):
assert path.read_bytes() == b"clip"
assert path.suffix == ".mp4"
- assert calls == [
- (
- "https://api.example/videos/job/content",
- {
- "headers": {"Authorization": "Bearer test"},
- "timeout": 30,
- "stream": True,
- },
- )
- ]
+ assert len(calls) == 1
+ assert str(calls[0].url) == "https://api.example/videos/job/content"
+ assert calls[0].headers["Authorization"] == "Bearer test"
def test_save_url_strict_content_type_rejects_non_video(monkeypatch, tmp_path):
monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
- monkeypatch.setattr(
- "requests.get",
- lambda *_args, **_kwargs: _Response("text/html", [b"not a video"]),
+ import httpx
+
+ _stub_fetch(
+ monkeypatch,
+ lambda request: httpx.Response(200, headers={"Content-Type": "text/html"}, content=b"not a video"),
)
with pytest.raises(ValueError, match="unexpected Content-Type text/html"):
@@ -79,3 +76,31 @@ def test_save_url_strict_content_type_rejects_non_video(monkeypatch, tmp_path):
)
assert not list(provider_media.cache_dir("videos").iterdir())
+
+
+def test_save_url_redirect_does_not_forward_caller_headers(monkeypatch, tmp_path):
+ """Caller auth headers (provider base_url fetches) go to the first hop only —
+ a redirect target must never receive them."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ calls = []
+
+ import httpx
+
+ def handler(request):
+ calls.append(request)
+ if request.url.path == "/start":
+ return httpx.Response(302, headers={"Location": "/final"})
+ return httpx.Response(200, headers={"Content-Type": "video/mp4"}, content=b"clip")
+
+ _stub_fetch(monkeypatch, handler)
+
+ path = _save_video(
+ "https://api.example/start",
+ headers={"Authorization": "Bearer test"},
+ require_known_content_type=True,
+ )
+
+ assert path.read_bytes() == b"clip"
+ assert len(calls) == 2
+ assert calls[0].headers.get("Authorization") == "Bearer test"
+ assert calls[1].headers.get("Authorization") is None
diff --git a/tests/agent/test_save_url_image.py b/tests/agent/test_save_url_image.py
index 086182331ad..a4f3f883e70 100644
--- a/tests/agent/test_save_url_image.py
+++ b/tests/agent/test_save_url_image.py
@@ -56,6 +56,14 @@ class _TinyImageHandler(http.server.BaseHTTPRequestHandler):
elif self.path == "/404":
self.send_response(404)
self.end_headers()
+ elif self.path == "/redirect-metadata":
+ self.send_response(302)
+ self.send_header("Location", "http://169.254.169.254/latest/meta-data/")
+ self.end_headers()
+ elif self.path == "/redirect-loop":
+ self.send_response(302)
+ self.send_header("Location", "/redirect-loop")
+ self.end_headers()
elif self.path == "/no-type-with-url-ext.jpg":
self.send_response(200)
self.send_header("Content-Type", "application/octet-stream")
@@ -75,8 +83,16 @@ class _TinyImageHandler(http.server.BaseHTTPRequestHandler):
@pytest.fixture
def http_server(tmp_path, monkeypatch):
- """Spin up a localhost HTTP server and isolate HERMES_HOME under tmp_path."""
+ """Spin up a localhost HTTP server and isolate HERMES_HOME under tmp_path.
+
+ ``HERMES_ALLOW_PRIVATE_URLS`` opts the test server into private-IP reach
+ (the same toggle a LAN-hosted provider would set); the cloud-metadata
+ floor stays blocked regardless, which is what the SSRF tests pin.
+ """
monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ monkeypatch.setenv("HERMES_ALLOW_PRIVATE_URLS", "1")
+ from tools import url_safety
+ url_safety._reset_allow_private_cache()
(tmp_path / ".hermes").mkdir()
# Force the constants/image cache helpers to re-read HERMES_HOME.
@@ -91,6 +107,8 @@ def http_server(tmp_path, monkeypatch):
thread.start()
yield f"http://127.0.0.1:{port}", httpd
httpd.shutdown()
+ monkeypatch.delenv("HERMES_ALLOW_PRIVATE_URLS", raising=False)
+ url_safety._reset_allow_private_cache()
class TestSaveUrlImage:
@@ -114,11 +132,38 @@ class TestSaveUrlImage:
"""HTTP errors must propagate — caller decides whether to fall back."""
base, _ = http_server
from agent.image_gen_provider import save_url_image
- import requests as req_lib
+ import httpx
- with pytest.raises(req_lib.HTTPError):
+ with pytest.raises(httpx.HTTPStatusError):
save_url_image(f"{base}/404")
+ def test_metadata_url_refused_before_any_fetch(self, http_server):
+ """The provider-supplied URL must pass the SSRF check before a socket
+ opens — cloud metadata is always blocked, even under
+ allow_private_urls."""
+ from agent.image_gen_provider import save_url_image
+
+ with pytest.raises(ValueError, match="SSRF"):
+ save_url_image("http://169.254.169.254/latest/meta-data/", timeout=2)
+ with pytest.raises(ValueError, match="SSRF"):
+ save_url_image("file:///etc/passwd", timeout=2)
+
+ def test_redirect_to_metadata_aborts_mid_chain(self, http_server):
+ """A safe first hop must not launder an unsafe redirect target —
+ each hop is re-validated."""
+ base, _ = http_server
+ from agent.image_gen_provider import save_url_image
+
+ with pytest.raises(ValueError, match="SSRF"):
+ save_url_image(f"{base}/redirect-metadata", timeout=2)
+
+ def test_redirect_loop_is_bounded(self, http_server):
+ base, _ = http_server
+ from agent.image_gen_provider import save_url_image
+
+ with pytest.raises(ValueError, match="redirect"):
+ save_url_image(f"{base}/redirect-loop")
+
def test_oversize_raises_and_cleans_up(self, http_server, tmp_path):
"""Oversize downloads must NOT leak a partial file into the cache."""
diff --git a/tests/plugins/image_gen/test_openai_codex_provider.py b/tests/plugins/image_gen/test_openai_codex_provider.py
index 89a7832bbfa..2c3cab50b4e 100644
--- a/tests/plugins/image_gen/test_openai_codex_provider.py
+++ b/tests/plugins/image_gen/test_openai_codex_provider.py
@@ -174,9 +174,16 @@ class TestGenerate:
def test_remote_source_url_is_fetched_and_inlined(self, provider, codex_backend, monkeypatch):
# The backend's own URL downloader 400s on ordinary public images; we fetch client-side.
+ monkeypatch.setattr("tools.url_safety.is_safe_url", lambda url: True)
+ # codex_backend monkeypatches httpx.Client; build the fetch client from
+ # the unpatched class so the ref-image download gets the PNG responder.
+ real_client = httpx._client.Client
monkeypatch.setattr(
- httpx, "get",
- lambda url, **kw: httpx.Response(200, content=_png_bytes(), request=httpx.Request("GET", url)))
+ "tools.url_safety.create_ssrf_safe_client",
+ lambda **kw: real_client(
+ transport=httpx.MockTransport(
+ lambda request: httpx.Response(200, content=_png_bytes(), request=request)),
+ **kw))
result = provider.generate("edit", image_url="https://example.com/ref.png")
@@ -184,6 +191,14 @@ class TestGenerate:
body = json.loads(codex_backend["requests"][0].content)
assert body["images"] == [{"image_url": "data:image/png;base64," + _b64_png()}]
+ def test_remote_source_url_refused_by_ssrf_guard(self, provider, codex_backend):
+ """A model-supplied image_url pointing at a metadata endpoint must be
+ refused before any fetch."""
+ result = provider.generate("edit", image_url="http://169.254.169.254/latest/meta-data")
+
+ assert result["success"] is False
+ assert codex_backend["requests"] == []
+
def test_capabilities_advertise_image_inputs(self, provider):
caps = provider.capabilities()
assert caps["modalities"] == ["text", "image"]
diff --git a/tests/plugins/image_gen/test_openai_provider.py b/tests/plugins/image_gen/test_openai_provider.py
index 93ad4013213..caba14a6eb6 100644
--- a/tests/plugins/image_gen/test_openai_provider.py
+++ b/tests/plugins/image_gen/test_openai_provider.py
@@ -119,6 +119,15 @@ class TestSourceImageLoading:
openai_plugin._load_image_bytes(str(auth_json))
+ def test_load_image_bytes_refuses_ssrf_url(self, tmp_path, monkeypatch):
+ """A model-supplied remote image ref pointing at a metadata endpoint must be
+ refused before any fetch."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ (tmp_path / ".hermes").mkdir()
+
+ with pytest.raises(ValueError, match="SSRF"):
+ openai_plugin._load_image_bytes("http://169.254.169.254/latest/meta-data")
+
def test_load_image_bytes_allows_legit_local_image(self, tmp_path, monkeypatch):
"""Negative control: a legitimate local image path is NOT blocked and
loads normally — proves the guard doesn't over-fire on everything."""
diff --git a/tests/tools/test_skills_hub.py b/tests/tools/test_skills_hub.py
index a7d0e14b42d..8244ad7fa81 100644
--- a/tests/tools/test_skills_hub.py
+++ b/tests/tools/test_skills_hub.py
@@ -228,6 +228,41 @@ class TestSkillsShSource:
assert results[0].path == "vercel-react-best-practices"
assert results[0].extra["installs"] == 207679
+ def test_sitemap_skips_metadata_loc_entries(self, monkeypatch):
+ """A hostile sitemap index advertising an internal <loc> must not be fetched."""
+ index_xml = (
+ "<urlset>"
+ "<url><loc>https://www.skills.sh/sitemap-skills-1.xml</loc></url>"
+ "<url><loc>http://169.254.169.254/sitemap-skills-2.xml</loc></url>"
+ "</urlset>"
+ )
+ monkeypatch.setattr("tools.skills_hub_skillssh._cached_metas", lambda key: None)
+ monkeypatch.setattr("tools.skills_hub_skillssh._cache_metas", lambda key, m: None)
+ fetched = []
+
+ def _fake_get_text(url, **kw):
+ fetched.append(url)
+ return index_xml if "sitemap.xml" in url else None
+
+ monkeypatch.setattr("tools.skills_hub_skillssh._get_text", _fake_get_text)
+
+ class _Client:
+ def __enter__(self): return self
+ def __exit__(self, *a): return False
+ def get(self, url, **kw):
+ fetched.append(url)
+ body = "<urlset><url><loc>https://skills.sh/acme/tools/my-skill</loc></url></urlset>"
+ return httpx.Response(200, text=body, request=httpx.Request("GET", url))
+
+ monkeypatch.setattr("tools.url_safety.create_ssrf_safe_client", lambda **kw: _Client())
+
+ self._source()._sitemap_catalog(limit=5)
+
+ assert "http://169.254.169.254/sitemap-skills-2.xml" not in fetched
+ assert fetched == [
+ "https://www.skills.sh/sitemap.xml",
+ "https://www.skills.sh/sitemap-skills-1.xml",
+ ]
@patch("tools.skills_hub._write_index_cache")
@patch("tools.skills_hub._read_index_cache", return_value=None)
@@ -2042,3 +2077,4 @@ class TestUrlSourceFetchMissingReferencedFile:
assert bundle is not None
assert bundle.name == "demo"
assert "references/missing.md" not in bundle.files
+
diff --git a/tests/tui_gateway/test_methods_images.py b/tests/tui_gateway/test_methods_images.py
new file mode 100644
index 00000000000..c6dbc4d9f30
--- /dev/null
+++ b/tests/tui_gateway/test_methods_images.py
@@ -0,0 +1,99 @@
+"""``image.generate`` RPC: the provider-result ``image`` field may be a bare remote
+URL (cache_url_best_effort falls back to it), so ``_image_to_data_url`` fetches it
+server-side — it must route through the SSRF guard like provider_media.save_url.
+"""
+
+import http.server
+import socketserver
+import threading
+
+import httpx
+import pytest
+
+from tui_gateway import methods_images
+
+_PNG = bytes.fromhex(
+ "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4"
+ "890000000d49444154789c6300010000000500010d0a2db40000000049454e44"
+ "ae426082"
+)
+
+
+def test_image_to_data_url_refuses_metadata_url():
+ assert methods_images._image_to_data_url("http://169.254.169.254/latest/meta-data", 1024) is None
+
+
+def test_image_to_data_url_refuses_file_scheme():
+ assert methods_images._image_to_data_url("file:///etc/passwd", 1024) is None
+
+
+def test_image_to_data_url_fetches_safe_url(monkeypatch):
+ monkeypatch.setattr("tools.url_safety.is_safe_url", lambda url: True)
+ monkeypatch.setattr(
+ "tools.url_safety.create_ssrf_safe_client",
+ lambda **kw: httpx.Client(
+ transport=httpx.MockTransport(
+ lambda request: httpx.Response(
+ 200, content=_PNG, headers={"content-type": "image/png"}, request=request)),
+ **kw))
+
+ data_url = methods_images._image_to_data_url("https://example.com/i.png", 1024)
+
+ assert data_url is not None
+ assert data_url.startswith("data:image/png;base64,")
+
+
+def test_image_to_data_url_caps_remote_body(monkeypatch):
+ monkeypatch.setattr("tools.url_safety.is_safe_url", lambda url: True)
+ monkeypatch.setattr(
+ "tools.url_safety.create_ssrf_safe_client",
+ lambda **kw: httpx.Client(
+ transport=httpx.MockTransport(
+ lambda request: httpx.Response(
+ 200, content=_PNG * 8, headers={"content-type": "image/png"}, request=request)),
+ **kw))
+
+ assert methods_images._image_to_data_url("https://example.com/i.png", 64) is None
+
+
+class _ImageHandler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self): # noqa: N802
+ if self.path == "/ok.png":
+ self.send_response(200)
+ self.send_header("Content-Type", "image/png")
+ self.end_headers()
+ self.wfile.write(_PNG)
+ elif self.path == "/redirect-metadata":
+ self.send_response(302)
+ self.send_header("Location", "http://169.254.169.254/latest/meta-data/")
+ self.end_headers()
+ else:
+ self.send_response(404)
+ self.end_headers()
+
+ def log_message(self, *args, **kw):
+ return
+
+
+def image_server(monkeypatch):
+ """Real local HTTP server — same e2e shape as tests/agent/test_save_url_image."""
+ monkeypatch.setenv("HERMES_ALLOW_PRIVATE_URLS", "1")
+ from tools import url_safety
+ url_safety._reset_allow_private_cache()
+ httpd = socketserver.TCPServer(("127.0.0.1", 0), _ImageHandler)
+ threading.Thread(target=httpd.serve_forever, daemon=True).start()
+ yield f"http://127.0.0.1:{httpd.server_address[1]}"
+ httpd.shutdown()
+ monkeypatch.delenv("HERMES_ALLOW_PRIVATE_URLS", raising=False)
+ url_safety._reset_allow_private_cache()
+
+
+def test_image_to_data_url_e2e_real_fetch(image_server):
+ """End-to-end: real guarded client, real socket, real cache path."""
+ data_url = methods_images._image_to_data_url(f"{image_server}/ok.png", 1 << 20)
+ assert data_url is not None and data_url.startswith("data:image/png;base64,")
+
+
+def test_image_to_data_url_e2e_redirect_to_metadata_blocked(image_server):
+ assert methods_images._image_to_data_url(f"{image_server}/redirect-metadata", 1 << 20) is None
diff --git a/tools/skills_hub_skillssh.py b/tools/skills_hub_skillssh.py
index 606aa701b90..634b0965ed1 100644
--- a/tools/skills_hub_skillssh.py
+++ b/tools/skills_hub_skillssh.py
@@ -125,15 +125,26 @@ class SkillsShSource(SkillSource):
# Step 1: sitemap index -> per-skill sitemap URLs.
index_xml = _get_text(self.SITEMAP_INDEX_URL, follow_redirects=True, headers=self._SITEMAP_HEADERS)
+ # <loc> targets are remote-party-controlled — a hostile index could point a
+ # sitemap at an internal address; skip anything the SSRF guard rejects.
+ from tools.url_safety import is_safe_url
skill_sitemap_urls = [m.group(1).strip() for m in self._SITEMAP_LOC_RE.finditer(index_xml or "")
- if "sitemap-skills" in m.group(1)]
+ if "sitemap-skills" in m.group(1) and is_safe_url(m.group(1).strip())]
if not skill_sitemap_urls:
return self._featured_skills(limit)
# Step 2: collect canonical "owner/repo/skill" IDs from each sitemap.
+ # The guarded client re-validates every redirect hop at connect time, so a
+ # safe-looking <loc> can't 302 to an internal target.
+ from tools.url_safety import create_ssrf_safe_client
seen, results = set(), []
for sitemap_url in skill_sitemap_urls:
- xml = _get_text(sitemap_url, timeout=30, follow_redirects=True, headers=self._SITEMAP_HEADERS)
+ with create_ssrf_safe_client(timeout=30, follow_redirects=True) as client:
+ try:
+ resp = client.get(sitemap_url, headers=self._SITEMAP_HEADERS)
+ except Exception:
+ continue
+ xml = resp.text if resp.status_code == 200 else None
for loc_match in self._SITEMAP_LOC_RE.finditer(xml or ""):
m = self._SITEMAP_SKILL_RE.match(loc_match.group(1).strip())
if not m:
diff --git a/tui_gateway/methods_images.py b/tui_gateway/methods_images.py
index 595f089d8fc..84df312ba12 100644
--- a/tui_gateway/methods_images.py
+++ b/tui_gateway/methods_images.py
@@ -17,13 +17,24 @@ def _image_to_data_url(ref: str, cap: int):
import os
try:
if ref.startswith(("http://", "https://")):
- import urllib.request
- req = urllib.request.Request(ref, headers={"User-Agent": "hermes-agent"})
- with urllib.request.urlopen(req, timeout=60) as resp:
- if resp.length is not None and resp.length > cap:
+ # Provider-result URLs are remote-party-controlled — same SSRF guard as
+ # agent/provider_media.save_url (which may have fallen back to the bare URL).
+ from tools.url_safety import create_ssrf_safe_client, is_safe_url
+ if not is_safe_url(ref):
+ return None
+ with create_ssrf_safe_client(timeout=60, follow_redirects=True) as client, \
+ client.stream("GET", ref, headers={"User-Agent": "hermes-agent"}) as resp:
+ resp.raise_for_status()
+ if resp.headers.get("content-length") and int(resp.headers["content-length"]) > cap:
return None
- data = resp.read(cap + 1)
- mime = resp.headers.get_content_type() or "image/png"
+ chunks, total = [], 0
+ for chunk in resp.iter_bytes():
+ total += len(chunk)
+ if total > cap:
+ return None
+ chunks.append(chunk)
+ data = b"".join(chunks)
+ mime = (resp.headers.get("content-type") or "image/png").split(";", 1)[0].strip()
elif os.path.isfile(ref):
if os.path.getsize(ref) > cap:
return None