Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(image-map): fetch search URLs through the SSRF-guarded session (#10264)
Rahul selvarajdb4338b858c5
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.pyindex 3ea045f7f4..b26a241527 100644--- a/invokeai/app/api/routers/image_map.py+++ b/invokeai/app/api/routers/image_map.py@@ -45,6 +45,7 @@ from invokeai.app.services.image_index.projection import ()from invokeai.app.services.image_records.image_records_common import ImageRecordNotFoundExceptionfrom invokeai.app.services.video_records.video_records_common import VideoRecordNotFoundException+from invokeai.app.util.ssrf import UnsafeDownloadURLException, build_guarded_session, validate_download_urlfrom invokeai.backend.util.host_platform import is_windows_arm64image_map_router = APIRouter(prefix="/v1/image_map", tags=["image_map"])@@ -742,36 +743,19 @@ _download_slots = asyncio.Semaphore(4)def _assert_url_host_allowed(url: str) -> None:"""Reject URLs whose scheme is not http(s) or whose host resolves to any- non-global address (loopback, RFC1918, link-local, reserved).-- Resolving via getaddrinfo covers hostnames like 'localhost' and the- non-canonical IP notations (decimal, hex, octal, shortened) that a plain- ip_address() literal parse misses. DNS rebinding between this check and- the actual request is accepted residual risk: the endpoint is- authenticated, and nothing about the response is revealed beyond whether- it decoded as an image.- """- import ipaddress- import socket- from urllib.parse import urlparse-- parsed = urlparse(url)- if parsed.scheme not in ("http", "https") or not parsed.hostname:- raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="image_url must be an http(s) URL")+ non-public address (loopback, RFC1918, link-local, reserved, NAT64).- port = parsed.port or (443 if parsed.scheme == "https" else 80)+ This is the cheap up-front check, delegated to the shared SSRF guard. The+ session from build_guarded_session() re-checks the connected peer, which is+ what closes DNS rebinding between this check and the request.+ """try:- infos = socket.getaddrinfo(parsed.hostname, port, proto=socket.IPPROTO_TCP)- except OSError:+ validate_download_url(url)+ except UnsafeDownloadURLException:raise HTTPException(- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="image_url host could not be resolved"+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,+ detail="image_url must be an http(s) URL that does not target a private or loopback address",)- for info in infos:- if not ipaddress.ip_address(info[4][0]).is_global:- raise HTTPException(- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,- detail="image_url must not target a private or loopback address",- )def _download_search_image(url: str) -> bytes:@@ -786,8 +770,6 @@ def _download_search_image(url: str) -> bytes:import timefrom urllib.parse import urljoin- import requests-deadline = time.monotonic() + _URL_TOTAL_DEADLINE_SECONDSdef _remaining() -> float:@@ -810,29 +792,33 @@ def _download_search_image(url: str) -> bytes:return lefttry:- for _ in range(_URL_MAX_REDIRECTS + 1):- _assert_url_host_allowed(url)- hop_timeout = min(_URL_TIMEOUT_SECONDS, _remaining())- with requests.get(url, stream=True, timeout=hop_timeout, allow_redirects=False) as response:- if response.is_redirect:- location = response.headers.get("location")- if not location:- break- url = urljoin(url, location)- continue- response.raise_for_status()- chunks: list[bytes] = []- received = 0- for chunk in response.iter_content(chunk_size=64 * 1024):- received += len(chunk)- if received > MAX_SEARCH_IMAGE_BYTES:- raise HTTPException(- status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,- detail="The reference image is too large",- )- _remaining()- chunks.append(chunk)- return b"".join(chunks)+ # The guarded session ignores HTTP(S)_PROXY/ALL_PROXY and validates the address+ # each socket actually connects to, so neither a proxy nor an address the+ # up-front check misjudges can redirect the fetch to an internal host.+ with build_guarded_session() as session:+ for _ in range(_URL_MAX_REDIRECTS + 1):+ _assert_url_host_allowed(url)+ hop_timeout = min(_URL_TIMEOUT_SECONDS, _remaining())+ with session.get(url, stream=True, timeout=hop_timeout, allow_redirects=False) as response:+ if response.is_redirect:+ location = response.headers.get("location")+ if not location:+ break+ url = urljoin(url, location)+ continue+ response.raise_for_status()+ chunks: list[bytes] = []+ received = 0+ for chunk in response.iter_content(chunk_size=64 * 1024):+ received += len(chunk)+ if received > MAX_SEARCH_IMAGE_BYTES:+ raise HTTPException(+ status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,+ detail="The reference image is too large",+ )+ _remaining()+ chunks.append(chunk)+ return b"".join(chunks)except HTTPException:raiseexcept Exception:diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.pyindex dc6f9ad3a6..bb9b5593ab 100644--- a/tests/app/routers/test_image_map.py+++ b/tests/app/routers/test_image_map.py@@ -9,11 +9,13 @@ from typing import AbstractSetimport numpy as npimport pytest+from fastapi import HTTPExceptionfrom fastapi.testclient import TestClientfrom PIL import Imagefrom sqlalchemy import insertfrom invokeai.app.api.dependencies import ApiDependencies+from invokeai.app.api.routers import image_map as image_map_router_modulefrom invokeai.app.api_app import appfrom invokeai.app.services.board_video_records.board_video_records_default import BoardVideoRecordStoragefrom invokeai.app.services.config.config_default import InvokeAIAppConfig@@ -1355,30 +1357,39 @@ def test_search_by_image_rejects_bad_inputs(client: TestClient) -> None:)-def test_search_by_image_revalidates_redirect_targets(monkeypatch, client: TestClient) -> None:- # A public URL redirecting to a private address must be refused: requests'- # automatic redirect following is disabled and every hop is re-validated.- import requests+class _FakeRedirect:+ status_code = 302+ is_redirect = True+ headers = {"location": "http://127.0.0.1:9090/steal"}- class FakeRedirect:- status_code = 302- is_redirect = True- headers = {"location": "http://127.0.0.1:9090/steal"}+ def __enter__(self):+ return self+ def __exit__(self, *args):+ return False+++def _fake_guarded_session(calls: list[str]):+ class FakeSession:def __enter__(self):return selfdef __exit__(self, *args):return False- calls: list[str] = []+ def get(self, url, **kwargs):+ calls.append(url)+ assert kwargs.get("allow_redirects") is False+ return _FakeRedirect()- def fake_get(url, **kwargs):- calls.append(url)- assert kwargs.get("allow_redirects") is False- return FakeRedirect()+ return FakeSession- monkeypatch.setattr(requests, "get", fake_get)++def test_search_by_image_revalidates_redirect_targets(monkeypatch, client: TestClient) -> None:+ # A public URL redirecting to a private address must be refused: requests'+ # automatic redirect following is disabled and every hop is re-validated.+ calls: list[str] = []+ monkeypatch.setattr(image_map_router_module, "build_guarded_session", _fake_guarded_session(calls))monkeypatch.setattr("socket.getaddrinfo",lambda host, port, **kw: [@@ -1394,6 +1405,47 @@ def test_search_by_image_revalidates_redirect_targets(monkeypatch, client: TestCassert calls == ["http://public.example/a.png"]+def test_search_by_image_rejects_nat64_mapped_loopback(monkeypatch, client: TestClient) -> None:+ # 64:ff9b::/96 can translate to an IPv4 address (here 127.0.0.1); it must be refused both as a+ # literal and as a hostname that resolves to it.+ monkeypatch.setattr(+ "socket.getaddrinfo",+ lambda host, port, **kw: [(None, None, None, None, ("64:ff9b::7f00:1", port, 0, 0))],+ )+ calls: list[str] = []+ monkeypatch.setattr(image_map_router_module, "build_guarded_session", _fake_guarded_session(calls))+ for bad_url in ("http://[64:ff9b::7f00:1]/a.png", "http://nat64.example/a.png"):+ response = client.post("/api/v1/image_map/search_by_image", params={"image_url": bad_url})+ assert response.status_code == 422, bad_url+ # Refused before any request was issued.+ assert calls == []+++def test_search_by_image_download_ignores_proxy_environment(monkeypatch) -> None:+ # With HTTP(S)_PROXY / ALL_PROXY set, the fetch must still connect directly (where the peer+ # address is checked) instead of handing the URL to the proxy.+ import requests++ proxied: list[str] = []++ def fake_send(self, request, **kwargs):+ proxied.append(str(kwargs.get("proxies")))+ raise requests.ConnectionError("stop")++ monkeypatch.setattr(+ "socket.getaddrinfo", lambda host, port, **kw: [(None, None, None, None, ("93.184.216.34", port))]+ )+ for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"):+ monkeypatch.setenv(name, "http://127.0.0.1:3128")+ monkeypatch.setattr(requests.adapters.HTTPAdapter, "send", fake_send)++ with pytest.raises(HTTPException) as exc:+ image_map_router_module._download_search_image("http://public.example/a.png")++ assert exc.value.status_code == 422+ assert proxied and "3128" not in proxied[0]++def test_multiuser_image_search_enforces_read_access_and_user_scope(multiuser, mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient) -> None: