Skip to content

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.

fix(download): remove the download_queue REST API; block non-public URLs for server-side downloads (#9492)

Lincoln Stein1f64b0b03286
diff --git a/docs/src/content/docs/features/Multi-User Mode/admin-guide.mdx b/docs/src/content/docs/features/Multi-User Mode/admin-guide.mdx
index d5fac328a7..f3222ac95b 100644
--- a/docs/src/content/docs/features/Multi-User Mode/admin-guide.mdx
+++ b/docs/src/content/docs/features/Multi-User Mode/admin-guide.mdx
@@ -249,6 +249,35 @@ view the models previously installed, but cannot add or modify them.
## Security
+### Download URL Restrictions
+
+These restrictions apply to every download the server performs on your behalf —
+model installs from URLs are the main case. (The old general-purpose
+`/api/v1/download_queue` REST endpoint, which accepted an arbitrary URL and
+destination path, has been removed.)
+
+Downloads are refused when the URL resolves to a loopback, link-local or
+private-network address. This stops a download URL from being used to reach
+services that only the server can see, such as an admin interface bound to
+`127.0.0.1` or a cloud instance-metadata endpoint. Redirects are checked at
+every hop, so a public URL cannot bounce the server onto a private address.
+
+If you install models from a mirror on your own network, re-enable those
+addresses in `invokeai.yaml`:
+
+```yaml
+allow_private_download_urls: true
+```
+
+For security, the guarded downloader ignores ambient `HTTP_PROXY`, `HTTPS_PROXY`,
+and `ALL_PROXY` settings. It still honors `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`,
+and `.netrc`. If direct outbound access is unavailable, set `download_proxy` to an
+explicit proxy whose destination policy blocks private addresses; proxy-side DNS
+cannot be checked by InvokeAI. Do not enable `allow_private_download_urls` merely to
+make an untrusted proxy work. The two settings are independent: `download_proxy` is
+honored whether or not `allow_private_download_urls` is enabled.
+
+
:::note[Strict Password Checking]
It is recommended that you enable strict password checking. This will
force all users to select good passwords that follow the
diff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.json
index a3d8a9bf6a..a3af416a70 100644
--- a/docs/src/generated/settings.json
+++ b/docs/src/generated/settings.json
@@ -754,6 +754,28 @@
"type": "<class 'bool'>",
"validation": {}
},
+ {
+ "category": "MODEL INSTALL",
+ "default": false,
+ "description": "Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.",
+ "env_var": "INVOKEAI_ALLOW_PRIVATE_DOWNLOAD_URLS",
+ "literal_values": [],
+ "name": "allow_private_download_urls",
+ "required": false,
+ "type": "<class 'bool'>",
+ "validation": {}
+ },
+ {
+ "category": "MODEL INSTALL",
+ "default": null,
+ "description": "Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.",
+ "env_var": "INVOKEAI_DOWNLOAD_PROXY",
+ "literal_values": [],
+ "name": "download_proxy",
+ "required": false,
+ "type": "typing.Optional[str]",
+ "validation": {}
+ },
{
"category": "MODEL INSTALL",
"default": false,
diff --git a/invokeai/app/api/routers/app_info.py b/invokeai/app/api/routers/app_info.py
index 1546291670..ceaa64b3e9 100644
--- a/invokeai/app/api/routers/app_info.py
+++ b/invokeai/app/api/routers/app_info.py
@@ -187,8 +187,9 @@ def _redact_config_secrets(config: InvokeAIAppConfig) -> InvokeAIAppConfig:
configured.
NOTE: coverage is by convention, not automatic. Only `*_api_key` fields listed in
- EXTERNAL_PROVIDER_CONFIG_FIELDS plus `remote_api_tokens` are masked. If you add a credential to
- InvokeAIAppConfig under any other name, you must extend this function or it will be served verbatim.
+ EXTERNAL_PROVIDER_CONFIG_FIELDS plus `remote_api_tokens` and credentials embedded in
+ `download_proxy` are masked. If you add a credential to InvokeAIAppConfig under any other
+ name, you must extend this function or it will be served verbatim.
"""
updates: dict[str, Any] = {}
@@ -203,6 +204,9 @@ def _redact_config_secrets(config: InvokeAIAppConfig) -> InvokeAIAppConfig:
pair.model_copy(update={"token": REDACTED_SECRET}) for pair in config.remote_api_tokens
]
+ if config.download_proxy and "@" in config.download_proxy:
+ updates["download_proxy"] = REDACTED_SECRET
+
return config.model_copy(update=updates) if updates else config
diff --git a/invokeai/app/api/routers/download_queue.py b/invokeai/app/api/routers/download_queue.py
deleted file mode 100644
index 305eaf9273..0000000000
--- a/invokeai/app/api/routers/download_queue.py
+++ /dev/null
@@ -1,138 +0,0 @@
-# Copyright (c) 2023 Lincoln D. Stein
-"""FastAPI route for the download queue."""
-
-from pathlib import Path as FsPath
-from pathlib import PurePosixPath, PureWindowsPath
-from typing import List, Optional
-
-from fastapi import Body, Path, Response
-from fastapi.routing import APIRouter
-from pydantic.networks import AnyHttpUrl
-from starlette.exceptions import HTTPException
-
-from invokeai.app.api.auth_dependencies import AdminUserOrDefault, CurrentUserOrDefault
-from invokeai.app.api.dependencies import ApiDependencies
-from invokeai.app.services.download import (
- DownloadJob,
- UnknownJobIDException,
-)
-
-download_queue_router = APIRouter(prefix="/v1/download_queue", tags=["download_queue"])
-
-
-def _validate_dest(dest: str) -> str:
- """Reject absolute paths and parent-traversal segments.
-
- Accepts a relative POSIX- or Windows-style path. Returns the original string
- for the caller to wrap in `Path(...)`. Raises 400 on suspicious input so the
- download service never sees it.
- """
- if not dest or not dest.strip():
- raise HTTPException(status_code=400, detail="Download destination must not be empty.")
-
- posix = PurePosixPath(dest)
- windows = PureWindowsPath(dest)
- if posix.is_absolute() or windows.is_absolute():
- raise HTTPException(status_code=400, detail="Download destination must be a relative path.")
-
- if ".." in posix.parts or ".." in windows.parts:
- raise HTTPException(status_code=400, detail="Download destination must not contain '..' segments.")
-
- return dest
-
-
-@download_queue_router.get(
- "/",
- operation_id="list_downloads",
-)
-async def list_downloads(current_user: CurrentUserOrDefault) -> List[DownloadJob]:
- """Get a list of active and inactive jobs."""
- queue = ApiDependencies.invoker.services.download_queue
- return queue.list_jobs()
-
-
-@download_queue_router.patch(
- "/",
- operation_id="prune_downloads",
- responses={
- 204: {"description": "All completed jobs have been pruned"},
- 400: {"description": "Bad request"},
- },
-)
-async def prune_downloads(current_user: AdminUserOrDefault) -> Response:
- """Prune completed and errored jobs."""
- queue = ApiDependencies.invoker.services.download_queue
- queue.prune_jobs()
- return Response(status_code=204)
-
-
-@download_queue_router.post(
- "/i/",
- operation_id="download",
-)
-async def download(
- current_user: CurrentUserOrDefault,
- source: AnyHttpUrl = Body(description="download source"),
- dest: str = Body(description="download destination"),
- priority: int = Body(default=10, description="queue priority"),
- access_token: Optional[str] = Body(default=None, description="token for authorization to download"),
-) -> DownloadJob:
- """Download the source URL to the file or directory indicted in dest."""
- validated_dest = _validate_dest(dest)
- queue = ApiDependencies.invoker.services.download_queue
- return queue.download(source, FsPath(validated_dest), priority, access_token)
-
-
-@download_queue_router.get(
- "/i/{id}",
- operation_id="get_download_job",
- responses={
- 200: {"description": "Success"},
- 404: {"description": "The requested download JobID could not be found"},
- },
-)
-async def get_download_job(
- current_user: CurrentUserOrDefault,
- id: int = Path(description="ID of the download job to fetch."),
-) -> DownloadJob:
- """Get a download job using its ID."""
- try:
- job = ApiDependencies.invoker.services.download_queue.id_to_job(id)
- return job
- except UnknownJobIDException as e:
- raise HTTPException(status_code=404, detail=str(e))
-
-
-@download_queue_router.delete(
- "/i/{id}",
- operation_id="cancel_download_job",
- responses={
- 204: {"description": "Job has been cancelled"},
- 404: {"description": "The requested download JobID could not be found"},
- },
-)
-async def cancel_download_job(
- current_user: CurrentUserOrDefault,
- id: int = Path(description="ID of the download job to cancel."),
-) -> Response:
- """Cancel a download job using its ID."""
- try:
- queue = ApiDependencies.invoker.services.download_queue
- job = queue.id_to_job(id)
- queue.cancel_job(job)
- return Response(status_code=204)
- except UnknownJobIDException as e:
- raise HTTPException(status_code=404, detail=str(e))
-
-
-@download_queue_router.delete(
- "/i",
- operation_id="cancel_all_download_jobs",
- responses={
- 204: {"description": "Download jobs have been cancelled"},
- },
-)
-async def cancel_all_download_jobs(current_user: AdminUserOrDefault) -> Response:
- """Cancel all download jobs."""
- ApiDependencies.invoker.services.download_queue.cancel_all_jobs()
- return Response(status_code=204)
diff --git a/invokeai/app/api/sockets.py b/invokeai/app/api/sockets.py
index c1cc753c88..83f7be27f0 100644
--- a/invokeai/app/api/sockets.py
+++ b/invokeai/app/api/sockets.py
@@ -607,8 +607,12 @@ class SocketIO:
)
return
- # Model install / download events remain broadcast to all connected sockets - they feed
- # the model manager UI, which is not per-user.
+ # Model install and download events contain signed source URLs and server filesystem
+ # paths. They feed the admin-only model manager UI and must not be broadcast to users.
+ if isinstance(event_data, (DownloadEventBase, ModelEventBase)):
+ await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room="admin")
+ return
+
await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"))
async def _handle_llm_task_event(self, event: FastAPIEvent[LLMTaskEventBase]) -> None:
diff --git a/invokeai/app/api_app.py b/invokeai/app/api_app.py
index c0722c4bd1..b89746dcac 100644
--- a/invokeai/app/api_app.py
+++ b/invokeai/app/api_app.py
@@ -28,7 +28,6 @@ from invokeai.app.api.routers import (
boards,
client_state,
custom_nodes,
- download_queue,
gallery,
image_moves,
images,
@@ -408,7 +407,6 @@ app.add_middleware(GZipMiddleware, minimum_size=1000)
app.include_router(auth.auth_router, prefix="/api")
app.include_router(utilities.utilities_router, prefix="/api")
app.include_router(model_manager.model_manager_router, prefix="/api")
-app.include_router(download_queue.download_queue_router, prefix="/api")
app.include_router(image_moves.image_moves_router, prefix="/api")
app.include_router(images.images_router, prefix="/api")
app.include_router(videos.videos_router, prefix="/api")
diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.py
index 3de35caf14..7344ed0b5a 100644
--- a/invokeai/app/services/config/config_default.py
+++ b/invokeai/app/services/config/config_default.py
@@ -127,6 +127,8 @@ class InvokeAIAppConfig(BaseSettings):
hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`
remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.
scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.
+ allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.
+ download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.
unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.
allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.
multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.
@@ -238,6 +240,8 @@ class InvokeAIAppConfig(BaseSettings):
hashing_algorithm: HASHING_ALGORITHMS = Field(default="blake3_single", description="Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.")
remote_api_tokens: Optional[list[URLRegexTokenPair]] = Field(default=None, description="List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.")
scan_models_on_startup: bool = Field(default=False, description="Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.")
+ allow_private_download_urls: bool = Field(default=False, description="Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.")
+ download_proxy: Optional[str] = Field(default=None, description="Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.")
unsafe_disable_picklescan: bool = Field(default=False, description="UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.")
allow_unknown_models: bool = Field(default=True, description="Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.")
diff --git a/invokeai/app/services/download/download_base.py b/invokeai/app/services/download/download_base.py
index 1798fd69df..9f943bf187 100644
--- a/invokeai/app/services/download/download_base.py
+++ b/invokeai/app/services/download/download_base.py
@@ -7,7 +7,7 @@ from functools import total_ordering
from pathlib import Path
from typing import Any, Callable, List, Optional, Set, Union
-from pydantic import BaseModel, Field, PrivateAttr
+from pydantic import BaseModel, Field, PrivateAttr, field_serializer
from pydantic.networks import AnyHttpUrl
from invokeai.backend.model_manager.metadata import RemoteModelFile
@@ -60,6 +60,17 @@ class DownloadJobBase(BaseModel):
error_type: Optional[str] = Field(default=None, description="Name of exception that caused an error")
error: Optional[str] = Field(default=None, description="Traceback of the exception that caused an error")
+ @field_serializer("dest", "download_path")
+ def _serialize_path(self, path: Optional[Path]) -> Optional[str]:
+ """Emit paths with forward slashes so the wire format does not depend on the server's OS.
+
+ `str(WindowsPath("models/x.bin"))` is `models\\x.bin`, so without this a client that
+ submits a POSIX-style `dest` gets a different spelling back from a Windows host than
+ from a Linux one. The download events already normalise this way - see
+ `DownloadStartedEvent.build` in `events_common.py`.
+ """
+ return path.as_posix() if path is not None else None
+
# internal flag
_cancelled: bool = PrivateAttr(default=False)
_paused: bool = PrivateAttr(default=False)
diff --git a/invokeai/app/services/download/download_default.py b/invokeai/app/services/download/download_default.py
index d978acaf7f..94154c3b49 100644
--- a/invokeai/app/services/download/download_default.py
+++ b/invokeai/app/services/download/download_default.py
@@ -6,11 +6,11 @@ import re
import threading
import time
import traceback
-from pathlib import Path
+from pathlib import Path, PurePosixPath, PureWindowsPath
from queue import Empty, PriorityQueue
from shutil import disk_usage
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Set
-from urllib.parse import urlparse
+from urllib.parse import urljoin, urlparse
import requests
from pydantic.networks import AnyHttpUrl
@@ -31,6 +31,7 @@ from invokeai.app.services.download.download_base import (
UnknownJobIDException,
)
from invokeai.app.util.misc import get_iso_timestamp
+from invokeai.app.util.ssrf import build_guarded_session, validate_download_url, warn_if_proxied
from invokeai.backend.model_manager.metadata import RemoteModelFile
from invokeai.backend.util.logging import InvokeAILogger
@@ -71,7 +72,27 @@ class DownloadQueueService(DownloadQueueServiceBase):
self._lock = threading.Lock()
self._logger = InvokeAILogger.get_logger("DownloadQueueService")
self._event_bus = event_bus
- self._requests = requests_session or requests.Session()
+ # A caller-supplied session is left exactly as given (the tests inject mock
+ # transports). Sessions we build ourselves refuse to connect to a non-public
+ # address, which is the check that holds against DNS rebinding and against host
+ # spellings that `requests` decodes differently from us.
+ self._request_proxies: Optional[Dict[str, str]] = None
+ if requests_session is not None:
+ self._requests = requests_session
+ elif self._app_config.allow_private_download_urls:
+ # The operator has opted out of the address policy, so ambient proxy variables
+ # keep working here exactly as they always have — but an explicitly configured
+ # download_proxy must still be honored rather than silently ignored when both
+ # settings are present. It is applied per request (see the single call site in
+ # _do_download) because that is the only level that takes precedence over
+ # ambient *_PROXY variables in a plain Session.
+ self._requests = requests.Session()
+ if self._app_config.download_proxy:
+ proxy = self._app_config.download_proxy
+ self._request_proxies = {"http": proxy, "https": proxy}
+ else:
+ self._requests = build_guarded_session(proxy=self._app_config.download_proxy)
+ warn_if_proxied(self._requests, self._logger)
self._accept_download_requests = False
self._max_parallel_dl = max_parallel_dl
@@ -420,8 +441,18 @@ class DownloadQueueService(DownloadQueueServiceBase):
job.resume_message = "Partial file missing. Restarted download from the beginning."
# Make a streaming request. This will retrieve headers including
- # content-length and content-disposition, but not fetch any content itself
- resp = self._requests.get(str(url), headers=header, stream=True)
+ # content-length and content-disposition, but not fetch any content itself.
+ # The URL is checked here rather than at submit time so that it is the address we
+ # are about to connect to that gets vetted, and the response hook re-checks every
+ # redirect hop — otherwise a public URL could bounce us onto a private address.
+ self._validate_url(url)
+ resp = self._requests.get(
+ str(url),
+ headers=header,
+ stream=True,
+ hooks={"response": self._reject_unsafe_redirect},
+ proxies=self._request_proxies,
+ )
job.final_url = str(resp.url) if resp.url else None
self._logger.debug(
"Resume response: "
@@ -475,6 +506,11 @@ class DownloadQueueService(DownloadQueueServiceBase):
if self._validate_filename(job.dest.as_posix(), remote_name):
file_name = remote_name
+ # The URL path is attacker-influenced too -- a final segment of ".." would
+ # otherwise put download_path one level above dest.
+ if not self._validate_filename(job.dest.as_posix(), file_name):
+ raise ValueError(f"Cannot derive a safe filename for {url} from '{file_name}'")
+
job.download_path = job.dest / file_name
else:
@@ -586,13 +622,40 @@ class DownloadQueueService(DownloadQueueServiceBase):
self._logger.debug(f"{job.source}: saved to {job.download_path} (bytes={job.bytes})")
in_progress_path.rename(job.download_path)
+ def _validate_url(self, url: str) -> None:
+ """Refuse to fetch URLs that point at addresses only the server can reach."""
+ validate_download_url(str(url), allow_private_urls=self._app_config.allow_private_download_urls)
+
+ def _reject_unsafe_redirect(self, response: requests.Response, *args: Any, **kwargs: Any) -> requests.Response:
+ """Response hook: vet each redirect target before `requests` follows it."""
+ if response.is_redirect or response.is_permanent_redirect:
+ location = response.headers.get("location")
+ if location:
+ try:
+ self._validate_url(urljoin(response.url, location))
+ except Exception:
+ response.close()
+ raise
+ return response
+
def _validate_filename(self, directory: str, filename: str) -> bool:
pc_name_max = get_pc_name_max(directory)
pc_path_max = get_pc_path_max(directory)
- if "/" in filename:
+ # The name must be a single path component. A remote server picks this value, so
+ # separators of either flavour, drive letters and '..' all have to be rejected --
+ # on Windows `Path(dir) / "..\\evil"` escapes `dir` even though it has no '/'.
+ if "/" in filename or "\\" in filename:
+ return False
+ if filename in ("", ".", ".."):
return False
if filename.startswith(".."):
return False
+ if PurePosixPath(filename).is_absolute() or PureWindowsPath(filename).is_absolute():
+ return False
+ # `WindowsPath("D:/dest") / "C:evil"` yields "C:evil" -- a drive-relative name
+ # replaces the destination entirely without ever looking absolute.
+ if PureWindowsPath(filename).drive:
+ return False
if len(filename) > pc_name_max:
return False
if len(os.path.join(directory, filename)) > pc_path_max:
diff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.py
index 53eb6da168..bf12040a76 100644
--- a/invokeai/app/services/model_install/model_install_default.py
+++ b/invokeai/app/services/model_install/model_install_default.py
@@ -387,7 +387,8 @@ class ModelInstallService(ModelInstallServiceBase):
self._logger.debug("calling stop_event.set()")
self._stop_event.set()
self._clear_pending_jobs()
- self._download_cache.clear()
+ with self._lock:
+ self._download_cache.clear()
assert self._install_thread is not None
self._install_thread.join()
self._running = False
@@ -579,7 +580,14 @@ class ModelInstallService(ModelInstallServiceBase):
if not self._wait_for_restore_complete(timeout=restore_timeout):
raise TimeoutError("Timeout exceeded")
- while len(self._download_cache) > 0:
+ while True:
+ # The completion callback removes a download from this cache while holding
+ # the same lock it uses to enqueue the install. Do not observe the cache
+ # between those two operations.
+ with self._lock:
+ downloads_pending = bool(self._download_cache)
+ if not downloads_pending:
+ break
if self._downloads_changed_event.wait(timeout=0.25): # in case we miss an event
self._downloads_changed_event.clear()
if timeout > 0 and time.time() - start > timeout:
@@ -1339,7 +1347,8 @@ class ModelInstallService(ModelInstallServiceBase):
part.final_url = meta.get("final_url") or part.final_url
if meta.get("download_path"):
part.download_path = Path(meta.get("download_path"))
- self._download_cache[multifile_job.id] = job
+ with self._lock:
+ self._download_cache[multifile_job.id] = job
job._multifile_job = multifile_job
self._write_install_marker(job, status=InstallStatus.WAITING)
diff --git a/invokeai/app/util/ssrf.py b/invokeai/app/util/ssrf.py
new file mode 100644
index 0000000000..4825c9e1cc
--- /dev/null
+++ b/invokeai/app/util/ssrf.py
@@ -0,0 +1,361 @@
+"""Guards against server-side request forgery (SSRF) via user-supplied download URLs.
+
+The download queue fetches URLs supplied over the API. Without a check, a caller can
+point the server at addresses only the server can reach — loopback services, other
+hosts on the private network, or the cloud metadata endpoint at 169.254.169.254 — and
+use the download job as a proxy for them.
+
+There are two layers here, and the second is the one that actually holds:
+
+`build_guarded_session()` returns a `requests.Session` that validates the peer address
+of every socket it opens, before a single byte of the request is written. Checking the
+connected socket is the only check that cannot be desynchronised from what the HTTP
+client does: it is immune to DNS rebinding (the client resolves again after any
+up-front check, and an attacker controlling the zone can answer the two lookups
+differently) and to hostname spellings that we and `requests` disagree about (it
+percent-decodes unreserved characters in the host, so `http://%6cocalhost/` and
+`http://169.254.169%2e254/` reach loopback and the metadata service respectively).
+
+`validate_download_url()` is the cheap up-front check. It rejects the obvious cases
+before any packet is sent — which keeps the API's error messages useful and stops the
+socket layer being used as a port-existence oracle — but it resolves the host itself,
+so it must never be relied on alone.
+
+Ambient `HTTP_PROXY`/`HTTPS_PROXY`/`ALL_PROXY` settings are ignored by the guarded session.
+That keeps destination resolution inside this process, where the socket-level policy can
+inspect the connected peer, while Requests' CA-bundle and netrc environment support remains
+enabled. A caller that explicitly adds a proxy to a session accepts the proxy's destination
+policy instead; `warn_if_proxied()` reports that weaker configuration.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import logging
+import socket
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import unquote, urlsplit
+from urllib.request import getproxies
+
+import requests
+from requests.adapters import HTTPAdapter
+from requests.auth import _basic_auth_str
+from requests.models import PreparedRequest
+from requests.utils import get_auth_from_url, resolve_proxies
+from urllib3.connection import HTTPConnection, HTTPSConnection
+from urllib3.connectionpool import HTTPConnectionPool, HTTPSConnectionPool
+
+ALLOWED_SCHEMES = ("http", "https")
+logger = logging.getLogger(__name__)
+
+IpAddress = ipaddress.IPv4Address | ipaddress.IPv6Address
+
+
+class UnsafeDownloadURLException(ValueError):
+ """Raised when a URL points at a network location the download service refuses to fetch."""
+
+
+# RFC 5214 reserves this interface-identifier marker for ISATAP; the 32 bits after it are
+# the tunnelled IPv4 address. `u/g` may be 0x0000 or 0x0200.
+_ISATAP_MARKERS = (0x00005EFE, 0x02005EFE)
+
+
+def _candidates(ip: IpAddress) -> Iterator[IpAddress]:
+ """The address itself, plus every IPv4 address it can carry traffic to.
+
+ IPv6 has several ways to wrap an IPv4 destination, and on a host with the matching
+ transition mechanism enabled, connecting to the wrapper reaches the embedded IPv4
+ address. `IPv6Address("::ffff:127.0.0.1").is_loopback` is False, so the inner address
+ has to be pulled out and judged on its own.
+
+ An IPv4-mapped IPv6 address is an alternate spelling of its embedded IPv4 address, so
+ only the embedded address is judged. Other wrappers must be acceptable themselves and
+ what they wrap, which is why those addresses are yielded rather than substituted: a
+ Teredo address whose embedded client is public is still a Teredo address.
+
+ Only wrappers identifiable from the address alone are enumerated: v4-mapped, 6to4,
+ Teredo and ISATAP. The NAT64 well-known prefixes (`64:ff9b::/96`, `64:ff9b:1::/48`)
+ need no special case — they sit in `::/8` and so are already `is_reserved`. NAT64 with
+ an operator-chosen network-specific prefix, 6rd, and SIIT-EAM are out of scope by
+ construction: their prefix length and bit offsets are site-local configuration, so a
+ translated address is indistinguishable from any other global one. 6over4 is likewise
+ excluded — its "IPv4 in the low 32 bits" layout is what an ordinary hand-assigned
+ address looks like, so screening for it would reject a great deal of real traffic.
+ """
+ if isinstance(ip, ipaddress.IPv6Address):
+ if ip.ipv4_mapped is not None:
+ yield ip.ipv4_mapped
+ return
+ yield ip
+ teredo = ip.teredo
+ for inner in (ip.sixtofour, teredo[1] if teredo else None):
+ if inner is not None:
+ yield inner
+ if (int(ip) >> 32) & 0xFFFFFFFF in _ISATAP_MARKERS:
+ yield ipaddress.IPv4Address(int(ip) & 0xFFFFFFFF)
+ else:
+ yield ip
+
+
+def _is_blocked(ip: IpAddress) -> bool:
+ """Allow only globally-routable unicast addresses, wrappers included.
+
+ `is_global` rather than a hand-written range list, so that the shared address space
+ (`100.64.0.0/10`, RFC 6598) and the benchmarking range are covered — neither is
+ `is_private` or `is_reserved`, but both reach a provider's internal infrastructure.
+
+ `is_reserved` and `is_multicast` are still needed on top of it: for IPv6, CPython
+ defines `is_global` as `not is_private`, and the IPv6 private list covers neither the
+ reserved/unallocated space (`::/8`, `4000::/3`, the NAT64 prefixes) nor multicast, all
+ of which report `is_global == True`.
+ """
+ return any(not c.is_global or c.is_reserved or c.is_multicast for c in _candidates(ip))
+
+
+def _resolve(host: str, port: int | None) -> list[IpAddress]:
+ infos = socket.getaddrinfo(host, port, proto=socket.IPPROTO_TCP)
+ return [ipaddress.ip_address(info[4][0]) for info in infos]
+
+
+def _host_spellings(host: str) -> list[str]:
+ """Every host string the HTTP client might end up connecting to.
+
+ `requests` runs the URL through `requote_uri()`, which decodes percent-escapes of
+ unreserved characters. So `169.254.169%2e254` is checked by us as-is but connected to
+ as `169.254.169.254`. Check the decoded form too; the socket-level guard is what
+ finally catches anything this misses.
+ """
+ spellings = [host]
+ decoded = unquote(host)
+ if decoded != host:
+ spellings.append(decoded)
+ return spellings
+
+
+def _parse_ipv4_literal(host: str) -> IpAddress | None:
+ """Parse dotted and legacy numeric IPv4 spellings accepted by HTTP clients."""
+ host = host.removesuffix(".")
+ try:
+ return ipaddress.ip_address(host)
+ except ValueError:
+ pass
+
+ parts = host.split(".")
+ if not 1 <= len(parts) <= 4:
+ return None
+
+ values: list[int] = []
+ for part in parts:
+ if not part or part[0] in "+-" or not part.isascii():
+ return None
+ if part.lower().startswith("0x"):
+ base, digits = 16, part[2:]
+ elif len(part) > 1 and part.startswith("0"):
+ base, digits = 8, part[1:]
+ else:
+ base, digits = 10, part
+ alphabet = "0123456789abcdef"[:base]
+ if not digits or any(char.lower() not in alphabet for char in digits):
+ return None
+ try:
+ values.append(int(digits, base))
+ except ValueError:
+ return None
+
+ widths = {1: (32,), 2: (8, 24), 3: (8, 8, 16), 4: (8, 8, 8, 8)}[len(values)]
+ if any(value >= 1 << width for value, width in zip(values, widths, strict=True)):
+ return None
+
+ address = 0
+ for value, width in zip(values, widths, strict=True):
+ address = (address << width) | value
+ return ipaddress.IPv4Address(address)
+
+
+def check_address(ip: IpAddress, host: str) -> None:
+ """Raise if `ip` is not an address we are willing to connect to."""
+ if _is_blocked(ip):
+ logger.warning("Blocked download host %s resolving to non-public address %s", host, ip)
+ raise UnsafeDownloadURLException(
+ f"Refusing to download from '{host}': it resolves to a non-public address. "
+ "Set `allow_private_download_urls` in invokeai.yaml to permit downloads from loopback "
+ "and private-network addresses."
+ )
+
+
+def validate_download_url(url: str, allow_private_urls: bool = False) -> None:
+ """Reject `url` up front if it obviously points somewhere only the server can reach.
+
+ Every address the host resolves to must be public — a hostname with both a public and a
+ loopback record is rejected, because we cannot control which one the HTTP client picks.
+
+ An unresolvable host is allowed through to the HTTP client, so that offline test
+ environments and mocked sessions keep working. That is only safe because the session
+ from `build_guarded_session()` re-checks the address it actually connects to.
+ """
+ parts = urlsplit(str(url))
+
+ if parts.scheme.lower() not in ALLOWED_SCHEMES:
+ raise UnsafeDownloadURLException(f"Unsupported URL scheme '{parts.scheme}'. Only http and https are allowed.")
+
+ host = parts.hostname
+ if not host:
+ raise UnsafeDownloadURLException(f"Download URL '{url}' has no host.")
+
+ try:
+ port = parts.port
+ except ValueError as e:
+ raise UnsafeDownloadURLException(f"Download URL '{url}' has an invalid port.") from e
+
+ if allow_private_urls:
+ return
+
+ for spelling in _host_spellings(host):
+ literal = _parse_ipv4_literal(spelling)
+ if literal is not None:
+ candidates = [literal]
+ else:
+ try:
+ candidates = _resolve(spelling, port)
+ except (OSError, UnicodeError, ValueError):
+ continue
+ for candidate in candidates:
+ check_address(candidate, host)
+
+
+def _check_socket(sock: socket.socket) -> None:
+ """Validate the address a socket is actually connected to."""
+ peer = sock.getpeername()
+ # IPv6 peers come back as (host, port, flowinfo, scope_id) and the host may carry a
+ # "%iface" suffix; ip_address() will not parse that.
+ address = ipaddress.ip_address(str(peer[0]).partition("%")[0])
+ check_address(address, str(peer[0]))
+
+
+class _GuardedHTTPConnection(HTTPConnection):
+ def _new_conn(self) -> socket.socket:
+ sock = super()._new_conn()
+ try:
+ _check_socket(sock)
+ except BaseException:
+ sock.close()
+ raise
+ return sock
+
+
+class _GuardedHTTPSConnection(HTTPSConnection):
+ def _new_conn(self) -> socket.socket:
+ # Checked here rather than after `connect()` so that we bail out before the TLS
+ # handshake, not just before the HTTP request.
+ sock = super()._new_conn()
+ try:
+ _check_socket(sock)
+ except BaseException:
+ sock.close()
+ raise
+ return sock
+
+
+class _GuardedHTTPConnectionPool(HTTPConnectionPool):
+ ConnectionCls = _GuardedHTTPConnection
+
+
+class _GuardedHTTPSConnectionPool(HTTPSConnectionPool):
+ ConnectionCls = _GuardedHTTPSConnection
+
+
+class SsrfGuardedAdapter(HTTPAdapter):
+ """A `requests` adapter that refuses to talk to non-public addresses."""
+
+ def init_poolmanager(self, *args: Any, **kwargs: Any) -> None:
+ super().init_poolmanager(*args, **kwargs)
+ self.poolmanager.pool_classes_by_scheme = {
+ "http": _GuardedHTTPConnectionPool,
+ "https": _GuardedHTTPSConnectionPool,
+ }
+
+
+class _SsrfGuardedSession(requests.Session):
+ """Session that keeps Requests environment support but drops ambient proxies."""
+
+ _ignore_environment_proxies = True
+
+ def merge_environment_settings(
+ self,
+ url: str,
+ proxies: dict[str, str] | None,
+ stream: bool | None,
+ verify: bool | str | None,
+ cert: str | tuple[str, str] | None,
+ ) -> dict[str, Any]:
+ request_proxies = dict(proxies or {})
+ settings = super().merge_environment_settings(url, proxies, stream, verify, cert)
+ # `super()` supplies CA-bundle and netrc environment settings, which we want to
+ # retain. Replace only the merged proxy map so ambient proxies cannot bypass the
+ # peer-address check. Explicit session/request proxies remain supported but weaker.
+ effective_proxies = dict(self.proxies)
+ effective_proxies.update(request_proxies)
+ settings["proxies"] = effective_proxies
+ return settings
+
+ def rebuild_proxies(self, prepared_request: PreparedRequest, proxies: dict[str, str] | None) -> dict[str, str]:
+ """Rebuild explicit proxies across redirects without consulting the environment."""
+ new_proxies = resolve_proxies(prepared_request, proxies, trust_env=False)
+ headers = prepared_request.headers
+ if "Proxy-Authorization" in headers:
+ del headers["Proxy-Authorization"]
+
+ scheme = urlsplit(prepared_request.url).scheme
+ try:
+ username, password = get_auth_from_url(new_proxies[scheme])
+ except KeyError:
+ username, password = None, None
+
+ # urllib3 handles proxy authorization for HTTPS tunnels. Avoid putting these
+ # credentials in the tunneled request headers.
+ if not scheme.startswith("https") and username and password:
+ headers["Proxy-Authorization"] = _basic_auth_str(username, password)
+ return new_proxies
+
+ def send(self, request: PreparedRequest, **kwargs: Any) -> requests.Response:
+ """Keep direct `send()` calls from reintroducing ambient proxies."""
+ if kwargs.get("proxies") is None:
+ kwargs["proxies"] = dict(self.proxies)
+ return super().send(request, **kwargs)
+
+
+def build_guarded_session(proxy: str | None = None) -> requests.Session:
+ """A `requests.Session` that will not open a connection to a non-public address."""
+ session = _SsrfGuardedSession()
+ if proxy:
+ session.proxies.update({"http": proxy, "https": proxy})
+ adapter = SsrfGuardedAdapter()
+ session.mount("http://", adapter)
+ session.mount("https://", adapter)
+ return session
+
+
+def proxies_in_effect(session: requests.Session) -> dict[str, str]:
+ """Proxies this session would use, including ones inherited from the environment."""
+ proxies = dict(session.proxies)
+ if session.trust_env and not getattr(session, "_ignore_environment_proxies", False):
+ # Every key, not just http/https: `ALL_PROXY` arrives as the key "all", which
+ # `requests.utils.select_proxy` honours as a catch-all. Filtering by scheme would
+ # miss the form most egress-proxy setups actually use.
+ for scheme, proxy_url in getproxies().items():
+ proxies.setdefault(scheme, proxy_url)
+ return proxies
+
+
+def warn_if_proxied(session: requests.Session, logger: logging.Logger) -> None:
+ """Report explicit proxies or ignored ambient proxy settings."""
+ proxies = proxies_in_effect(session)
+ if proxies:
+ logger.warning(
+ "An explicit HTTP proxy is configured (%s). Downloads through it cannot be checked "
+ "against loopback/private addresses at the socket; restrict outbound access at the proxy.",
+ ", ".join(sorted(proxies)),
+ )
+ elif getattr(session, "_ignore_environment_proxies", False) and getproxies():
+ logger.warning("Ambient HTTP proxy settings are ignored for guarded downloads.")
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 108308b33e..639bab5d38 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -4577,234 +4577,6 @@
]
}
},
- "/api/v1/download_queue/": {
- "get": {
- "tags": ["download_queue"],
- "summary": "List Downloads",
- "description": "Get a list of active and inactive jobs.",
- "operationId": "list_downloads",
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "items": {
- "$ref": "#/components/schemas/DownloadJob"
- },
- "type": "array",
- "title": "Response List Downloads"
- }
- }
- }
- }
- },
- "security": [
- {
- "HTTPBearer": []
- }
- ]
- },
- "patch": {
- "tags": ["download_queue"],
- "summary": "Prune Downloads",
- "description": "Prune completed and errored jobs.",
- "operationId": "prune_downloads",
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {}
- }
- }
- },
- "204": {
- "description": "All completed jobs have been pruned"
- },
- "400": {
- "description": "Bad request"
- }
- },
- "security": [
- {
- "HTTPBearer": []
- }
- ]
- }
- },
- "/api/v1/download_queue/i/": {
- "post": {
- "tags": ["download_queue"],
- "summary": "Download",
- "description": "Download the source URL to the file or directory indicted in dest.",
- "operationId": "download",
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/Body_download"
- }
- }
- },
- "required": true
- },
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/DownloadJob"
- }
- }
- }
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- }
- }
- },
- "security": [
- {
- "HTTPBearer": []
- }
- ]
- }
- },
- "/api/v1/download_queue/i/{id}": {
- "get": {
- "tags": ["download_queue"],
- "summary": "Get Download Job",
- "description": "Get a download job using its ID.",
- "operationId": "get_download_job",
- "security": [
- {
- "HTTPBearer": []
- }
- ],
- "parameters": [
- {
- "name": "id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "integer",
- "description": "ID of the download job to fetch.",
- "title": "Id"
- },
- "description": "ID of the download job to fetch."
- }
- ],
- "responses": {
- "200": {
- "description": "Success",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/DownloadJob"
- }
- }
- }
- },
- "404": {
- "description": "The requested download JobID could not be found"
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- }
- }
- }
- },
- "delete": {
- "tags": ["download_queue"],
- "summary": "Cancel Download Job",
- "description": "Cancel a download job using its ID.",
- "operationId": "cancel_download_job",
- "security": [
- {
- "HTTPBearer": []
- }
- ],
- "parameters": [
- {
- "name": "id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "integer",
- "description": "ID of the download job to cancel.",
- "title": "Id"
- },
- "description": "ID of the download job to cancel."
- }
- ],
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {}
- }
- }
- },
- "204": {
- "description": "Job has been cancelled"
- },
- "404": {
- "description": "The requested download JobID could not be found"
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- }
- }
- }
- }
- },
- "/api/v1/download_queue/i": {
- "delete": {
- "tags": ["download_queue"],
- "summary": "Cancel All Download Jobs",
- "description": "Cancel all download jobs.",
- "operationId": "cancel_all_download_jobs",
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": {}
- }
- }
- },
- "204": {
- "description": "Download jobs have been cancelled"
- }
- },
- "security": [
- {
- "HTTPBearer": []
- }
- ]
- }
- },
"/api/v1/image_moves/start": {
"post": {
"tags": ["image_moves"],
@@ -15887,43 +15659,6 @@
"required": ["token"],
"title": "Body_do_hf_login"
},
- "Body_download": {
- "properties": {
- "source": {
- "type": "string",
- "minLength": 1,
- "format": "uri",
- "title": "Source",
- "description": "download source"
- },
- "dest": {
- "type": "string",
- "title": "Dest",
- "description": "download destination"
- },
- "priority": {
- "type": "integer",
- "title": "Priority",
- "description": "queue priority",
- "default": 10
- },
- "access_token": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "title": "Access Token",
- "description": "token for authorization to download"
- }
- },
- "type": "object",
- "required": ["source", "dest"],
- "title": "Body_download"
- },
"Body_download_images_from_list": {
"properties": {
"image_names": {
@@ -49292,6 +49027,24 @@
"description": "Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.",
"default": false
},
+ "allow_private_download_urls": {
+ "type": "boolean",
+ "title": "Allow Private Download Urls",
+ "description": "Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.",
+ "default": false
+ },
+ "download_proxy": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Download Proxy",
+ "description": "Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI."
+ },
"unsafe_disable_picklescan": {
"type": "boolean",
"title": "Unsafe Disable Picklescan",
@@ -49416,7 +49169,7 @@
"additionalProperties": false,
"type": "object",
"title": "InvokeAIAppConfig",
- "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `cuda:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set."
+ "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `cuda:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set."
},
"InvokeAIAppConfigWithSetFields": {
"properties": {
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 4cf2aeb20e..5cae91fb5b 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -957,94 +957,6 @@ export type paths = {
patch?: never;
trace?: never;
};
- "/api/v1/download_queue/": {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- /**
- * List Downloads
- * @description Get a list of active and inactive jobs.
- */
- get: operations["list_downloads"];
- put?: never;
- post?: never;
- delete?: never;
- options?: never;
- head?: never;
- /**
- * Prune Downloads
- * @description Prune completed and errored jobs.
- */
- patch: operations["prune_downloads"];
- trace?: never;
- };
- "/api/v1/download_queue/i/": {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- get?: never;
- put?: never;
- /**
- * Download
- * @description Download the source URL to the file or directory indicted in dest.
- */
- post: operations["download"];
- delete?: never;
- options?: never;
- head?: never;
- patch?: never;
- trace?: never;
- };
- "/api/v1/download_queue/i/{id}": {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- /**
- * Get Download Job
- * @description Get a download job using its ID.
- */
- get: operations["get_download_job"];
- put?: never;
- post?: never;
- /**
- * Cancel Download Job
- * @description Cancel a download job using its ID.
- */
- delete: operations["cancel_download_job"];
- options?: never;
- head?: never;
- patch?: never;
- trace?: never;
- };
- "/api/v1/download_queue/i": {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- get?: never;
- put?: never;
- post?: never;
- /**
- * Cancel All Download Jobs
- * @description Cancel all download jobs.
- */
- delete: operations["cancel_all_download_jobs"];
- options?: never;
- head?: never;
- patch?: never;
- trace?: never;
- };
"/api/v1/image_moves/start": {
parameters: {
query?: never;
@@ -4835,31 +4747,6 @@ export type components = {
*/
token: string;
};
- /** Body_download */
- Body_download: {
- /**
- * Source
- * Format: uri
- * @description download source
- */
- source: string;
- /**
- * Dest
- * @description download destination
- */
- dest: string;
- /**
- * Priority
- * @description queue priority
- * @default 10
- */
- priority?: number;
- /**
- * Access Token
- * @description token for authorization to download
- */
- access_token?: string | null;
- };
/** Body_download_images_from_list */
Body_download_images_from_list: {
/**
@@ -18939,6 +18826,8 @@ export type components = {
* hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`
* remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.
* scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.
+ * allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.
+ * download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.
* unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.
* allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.
* multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.
@@ -19350,6 +19239,17 @@ export type components = {
* @default false
*/
scan_models_on_startup?: boolean;
+ /**
+ * Allow Private Download Urls
+ * @description Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.
+ * @default false
+ */
+ allow_private_download_urls?: boolean;
+ /**
+ * Download Proxy
+ * @description Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.
+ */
+ download_proxy?: string | null;
/**
* Unsafe Disable Picklescan
* @description UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.
@@ -43641,205 +43541,6 @@ export interface operations {
};
};
};
- list_downloads: {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- requestBody?: never;
- responses: {
- /** @description Successful Response */
- 200: {
- headers: {
- [name: string]: unknown;
- };
- content: {
- "application/json": components["schemas"]["DownloadJob"][];
- };
- };
- };
- };
- prune_downloads: {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- requestBody?: never;
- responses: {
- /** @description Successful Response */
- 200: {
- headers: {
- [name: string]: unknown;
- };
- content: {
- "application/json": unknown;
- };
- };
- /** @description All completed jobs have been pruned */
- 204: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- /** @description Bad request */
- 400: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- };
- };
- download: {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- requestBody: {
- content: {
- "application/json": components["schemas"]["Body_download"];
- };
- };
- responses: {
- /** @description Successful Response */
- 200: {
- headers: {
- [name: string]: unknown;
- };
- content: {
- "application/json": components["schemas"]["DownloadJob"];
- };
- };
- /** @description Validation Error */
- 422: {
- headers: {
- [name: string]: unknown;
- };
- content: {
- "application/json": components["schemas"]["HTTPValidationError"];
- };
- };
- };
- };
- get_download_job: {
- parameters: {
- query?: never;
- header?: never;
- path: {
- /** @description ID of the download job to fetch. */
- id: number;
- };
- cookie?: never;
- };
- requestBody?: never;
- responses: {
- /** @description Success */
- 200: {
- headers: {
- [name: string]: unknown;
- };
- content: {
- "application/json": components["schemas"]["DownloadJob"];
- };
- };
- /** @description The requested download JobID could not be found */
- 404: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- /** @description Validation Error */
- 422: {
- headers: {
- [name: string]: unknown;
- };
- content: {
- "application/json": components["schemas"]["HTTPValidationError"];
- };
- };
- };
- };
- cancel_download_job: {
- parameters: {
- query?: never;
- header?: never;
- path: {
- /** @description ID of the download job to cancel. */
- id: number;
- };
- cookie?: never;
- };
- requestBody?: never;
- responses: {
- /** @description Successful Response */
- 200: {
- headers: {
- [name: string]: unknown;
- };
- content: {
- "application/json": unknown;
- };
- };
- /** @description Job has been cancelled */
- 204: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- /** @description The requested download JobID could not be found */
- 404: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- /** @description Validation Error */
- 422: {
- headers: {
- [name: string]: unknown;
- };
- content: {
- "application/json": components["schemas"]["HTTPValidationError"];
- };
- };
- };
- };
- cancel_all_download_jobs: {
- parameters: {
- query?: never;
- header?: never;
- path?: never;
- cookie?: never;
- };
- requestBody?: never;
- responses: {
- /** @description Successful Response */
- 200: {
- headers: {
- [name: string]: unknown;
- };
- content: {
- "application/json": unknown;
- };
- };
- /** @description Download jobs have been cancelled */
- 204: {
- headers: {
- [name: string]: unknown;
- };
- content?: never;
- };
- };
- };
start_image_move: {
parameters: {
query?: never;
diff --git a/tests/app/routers/conftest.py b/tests/app/routers/conftest.py
index e5ca28e16f..5ff2058af1 100644
--- a/tests/app/routers/conftest.py
+++ b/tests/app/routers/conftest.py
@@ -3,8 +3,8 @@
Note: This conftest intentionally does NOT redefine `mock_services` / `mock_invoker`
to avoid shadowing the project-level fixtures in `tests/conftest.py`. Instead, the
`enable_multiuser` fixture below injects MagicMock services for the routers that
-have no real backing service in the default mock_services (download_queue,
-style_preset_image_files, model_relationships, model_manager).
+have no real backing service in the default mock_services (style_preset_image_files,
+model_relationships, model_manager).
WARNING for future authors: `enable_multiuser` *unconditionally* replaces several
services on `mock_invoker.services` with MagicMocks. If you add a router test that
@@ -50,7 +50,6 @@ _PATCHED_API_DEPENDENCIES_MODULES = (
"invokeai.app.api_app",
"invokeai.app.api.auth_dependencies",
"invokeai.app.api.routers.auth",
- "invokeai.app.api.routers.download_queue",
"invokeai.app.api.routers.style_presets",
"invokeai.app.api.routers.model_relationships",
"invokeai.app.api.routers.utilities",
@@ -105,7 +104,6 @@ def enable_multiuser(monkeypatch: Any, mock_invoker: Invoker):
mock_invoker.services.configuration.multiuser = True
# Replace services that are None in the default mock_services with MagicMocks.
- mock_invoker.services.download_queue = MagicMock()
mock_invoker.services.style_preset_image_files = MagicMock()
mock_invoker.services.model_relationships = MagicMock()
mock_invoker.services.model_manager = MagicMock()
diff --git a/tests/app/routers/test_download_queue_router.py b/tests/app/routers/test_download_queue_router.py
deleted file mode 100644
index b3976f051f..0000000000
--- a/tests/app/routers/test_download_queue_router.py
+++ /dev/null
@@ -1,112 +0,0 @@
-"""Router-level tests for /api/v1/download_queue.
-
-Covers:
-- Auth gating (CurrentUserOrDefault on read/per-job, AdminUserOrDefault on prune & cancel-all).
-- Bug regression: `dest` path validation must reject absolute paths and '..' segments
- BEFORE the queue service is invoked.
-"""
-
-from typing import Any
-from unittest.mock import MagicMock
-
-import pytest
-from fastapi import status
-from fastapi.testclient import TestClient
-
-from invokeai.app.services.download import DownloadJob
-from invokeai.app.services.invoker import Invoker
-
-
-def _make_job(id: int = 1) -> DownloadJob:
- from pathlib import Path
-
- return DownloadJob(id=id, source="http://example.com/file.bin", dest=Path("models/file.bin"))
-
-
-# ----------------------------- Auth gating -----------------------------
-
-
- ("method", "path"),
- [
- ("GET", "/api/v1/download_queue/"),
- ("PATCH", "/api/v1/download_queue/"),
- ("POST", "/api/v1/download_queue/i/"),
- ("GET", "/api/v1/download_queue/i/1"),
- ("DELETE", "/api/v1/download_queue/i/1"),
- ("DELETE", "/api/v1/download_queue/i"),
- ],
-)
-def test_routes_require_auth_in_multiuser_mode(enable_multiuser: Any, client: TestClient, method: str, path: str):
- response = client.request(method, path, json={"source": "http://x/y", "dest": "models/x"})
- assert response.status_code == status.HTTP_401_UNAUTHORIZED
-
-
-def test_list_downloads_as_regular_user(client: TestClient, user1_token: str, mock_invoker: Invoker):
- mock_invoker.services.download_queue.list_jobs = MagicMock(return_value=[])
- r = client.get("/api/v1/download_queue/", headers={"Authorization": f"Bearer {user1_token}"})
- assert r.status_code == status.HTTP_200_OK
- assert r.json() == []
-
-
-def test_prune_downloads_forbidden_for_regular_user(client: TestClient, user1_token: str, mock_invoker: Invoker):
- r = client.patch("/api/v1/download_queue/", headers={"Authorization": f"Bearer {user1_token}"})
- assert r.status_code == status.HTTP_403_FORBIDDEN
- mock_invoker.services.download_queue.prune_jobs.assert_not_called()
-
-
-def test_prune_downloads_allowed_for_admin(client: TestClient, admin_token: str, mock_invoker: Invoker):
- r = client.patch("/api/v1/download_queue/", headers={"Authorization": f"Bearer {admin_token}"})
- assert r.status_code == status.HTTP_204_NO_CONTENT
- mock_invoker.services.download_queue.prune_jobs.assert_called_once()
-
-
-def test_cancel_all_forbidden_for_regular_user(client: TestClient, user1_token: str, mock_invoker: Invoker):
- r = client.delete("/api/v1/download_queue/i", headers={"Authorization": f"Bearer {user1_token}"})
- assert r.status_code == status.HTTP_403_FORBIDDEN
- mock_invoker.services.download_queue.cancel_all_jobs.assert_not_called()
-
-
-def test_cancel_all_allowed_for_admin(client: TestClient, admin_token: str, mock_invoker: Invoker):
- r = client.delete("/api/v1/download_queue/i", headers={"Authorization": f"Bearer {admin_token}"})
- assert r.status_code == status.HTTP_204_NO_CONTENT
- mock_invoker.services.download_queue.cancel_all_jobs.assert_called_once()
-
-
-# ----------------------------- Bug D regression: dest validation -----------------------------
-
-
- "bad_dest",
- [
- "/etc/passwd",
- "C:/Windows/System32",
- "models/../../etc/passwd",
- "..",
- "",
- " ",
- ],
-)
-def test_download_rejects_unsafe_dest_before_service_call(
- client: TestClient, user1_token: str, mock_invoker: Invoker, bad_dest: str
-):
- """Absolute paths, '..' segments, and empty strings must produce 400 and
- must NOT invoke the download_queue service."""
- r = client.post(
- "/api/v1/download_queue/i/",
- json={"source": "http://example.com/file.bin", "dest": bad_dest},
- headers={"Authorization": f"Bearer {user1_token}"},
- )
- assert r.status_code == status.HTTP_400_BAD_REQUEST
- mock_invoker.services.download_queue.download.assert_not_called()
-
-
-def test_download_accepts_relative_dest(client: TestClient, user1_token: str, mock_invoker: Invoker):
- mock_invoker.services.download_queue.download = MagicMock(return_value=_make_job())
- r = client.post(
- "/api/v1/download_queue/i/",
- json={"source": "http://example.com/file.bin", "dest": "models/sd15.safetensors"},
- headers={"Authorization": f"Bearer {user1_token}"},
- )
- assert r.status_code == status.HTTP_200_OK
- mock_invoker.services.download_queue.download.assert_called_once()
diff --git a/tests/app/routers/test_model_manager_authorization.py b/tests/app/routers/test_model_manager_authorization.py
index 3cb937f511..ba54a3a50d 100644
--- a/tests/app/routers/test_model_manager_authorization.py
+++ b/tests/app/routers/test_model_manager_authorization.py
@@ -297,6 +297,7 @@ def test_runtime_config_redacts_secrets() -> None:
external_openai_api_key="sk-super-secret",
external_gemini_base_url="https://example.invalid",
remote_api_tokens=[URLRegexTokenPair(url_regex="example.com", token="bearer-secret")],
+ download_proxy="http://proxy-user:[email protected]:3128",
)
redacted = _redact_config_secrets(config)
@@ -306,9 +307,11 @@ def test_runtime_config_redacts_secrets() -> None:
# Non-secret fields are untouched, and the original config is not mutated.
assert redacted.remote_api_tokens[0].url_regex == "example.com"
assert redacted.external_gemini_base_url == "https://example.invalid"
+ assert redacted.download_proxy == REDACTED_SECRET
assert config.external_openai_api_key == "sk-super-secret"
assert config.remote_api_tokens is not None
assert config.remote_api_tokens[0].token == "bearer-secret"
+ assert config.download_proxy == "http://proxy-user:[email protected]:3128"
def test_runtime_config_response_has_no_secrets(
diff --git a/tests/app/services/download/test_download_queue.py b/tests/app/services/download/test_download_queue.py
index b66c687d16..ab6d1dd42f 100644
--- a/tests/app/services/download/test_download_queue.py
+++ b/tests/app/services/download/test_download_queue.py
@@ -5,13 +5,15 @@ import time
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Generator, Optional
+from unittest.mock import MagicMock, patch
import pytest
from pydantic.networks import AnyHttpUrl
+from requests import Response
from requests.sessions import Session
from requests_testadapter import TestAdapter, TestSession
-from invokeai.app.services.config import get_config
+from invokeai.app.services.config import InvokeAIAppConfig, get_config
from invokeai.app.services.config.config_default import URLRegexTokenPair
from invokeai.app.services.download import DownloadJob, DownloadJobStatus, DownloadQueueService, MultiFileDownloadJob
from invokeai.app.services.events.events_common import (
@@ -21,6 +23,8 @@ from invokeai.app.services.events.events_common import (
DownloadProgressEvent,
DownloadStartedEvent,
)
+from invokeai.app.util import ssrf
+from invokeai.app.util.ssrf import UnsafeDownloadURLException
from invokeai.backend.model_manager.metadata import HuggingFaceMetadataFetch, ModelMetadataWithFiles, RemoteModelFile
from tests.test_nodes import TestEventService
@@ -504,3 +508,182 @@ def test_tokens(tmp_path: Path, mm2_session: Session):
assert job1.access_token == "cv_12345"
assert job2.access_token is None
queue.stop()
+
+
+# ---------------- Advisory regression: SSRF guard in the download worker ----------------
+
+
+def test_production_queue_uses_guarded_session_by_default() -> None:
+ queue = DownloadQueueService(app_config=InvokeAIAppConfig(allow_private_download_urls=False))
+ try:
+ assert isinstance(queue._requests.get_adapter("https://example.com"), ssrf.SsrfGuardedAdapter)
+ assert queue._requests.trust_env is True
+ finally:
+ queue._requests.close()
+
+
+def test_production_queue_allows_explicit_private_download_opt_in() -> None:
+ queue = DownloadQueueService(app_config=InvokeAIAppConfig(allow_private_download_urls=True))
+ try:
+ assert not isinstance(queue._requests.get_adapter("https://example.com"), ssrf.SsrfGuardedAdapter)
+ finally:
+ queue._requests.close()
+
+
+def test_production_queue_accepts_explicit_download_proxy() -> None:
+ queue = DownloadQueueService(
+ app_config=InvokeAIAppConfig(
+ allow_private_download_urls=False,
+ download_proxy="http://proxy.internal:3128",
+ )
+ )
+ try:
+ assert ssrf.proxies_in_effect(queue._requests) == {
+ "http": "http://proxy.internal:3128",
+ "https": "http://proxy.internal:3128",
+ }
+ finally:
+ queue._requests.close()
+
+
+def test_private_opt_in_still_honors_explicit_download_proxy(monkeypatch: Any) -> None:
+ """allow_private_download_urls=True must not silently drop an explicitly configured
+ download_proxy: the two settings are independent. The proxy is applied at request
+ level because that is the only level that beats ambient *_PROXY variables in a
+ plain (unguarded) Session."""
+ monkeypatch.setenv("HTTP_PROXY", "http://ambient.invalid:9")
+ monkeypatch.setenv("HTTPS_PROXY", "http://ambient.invalid:9")
+ queue = DownloadQueueService(
+ app_config=InvokeAIAppConfig(
+ allow_private_download_urls=True,
+ download_proxy="http://proxy.internal:3128",
+ )
+ )
+ try:
+ assert queue._request_proxies == {
+ "http": "http://proxy.internal:3128",
+ "https": "http://proxy.internal:3128",
+ }
+ # The explicit proxy must win over the ambient variables in requests' merge order.
+ merged = queue._requests.merge_environment_settings(
+ "https://example.com/x", queue._request_proxies, None, None, None
+ )
+ assert merged["proxies"]["https"] == "http://proxy.internal:3128"
+ finally:
+ queue._requests.close()
+
+
[email protected](timeout=10, method="thread")
+def test_download_refuses_non_public_source(tmp_path: Path) -> None:
+ """A job whose source points at loopback errors out without issuing the request."""
+ source = AnyHttpUrl("http://127.0.0.1:19191/proof.txt")
+ session = TestSession()
+ session.mount(str(source), TestAdapter(b"secret", status=200))
+
+ queue = DownloadQueueService(requests_session=session)
+ queue.start()
+ try:
+ job = queue.download(source=source, dest=tmp_path)
+ queue.join()
+ finally:
+ queue.stop()
+
+ assert job.status == DownloadJobStatus.ERROR
+ assert "UnsafeDownloadURLException" in (job.error_type or "")
+ assert not any(tmp_path.iterdir())
+
+
[email protected](timeout=10, method="thread")
+def test_download_refuses_redirect_to_non_public_address(tmp_path: Path) -> None:
+ """A public URL must not be able to bounce the worker onto a private address."""
+ source = AnyHttpUrl("https://test.com/redirector")
+ session = TestSession()
+ session.mount(
+ str(source),
+ TestAdapter(b"", status=302, headers={"Location": "http://169.254.169.254/latest/meta-data/"}),
+ )
+ session.mount("http://169.254.169.254/", TestAdapter(b"cloud-credentials", status=200))
+
+ queue = DownloadQueueService(requests_session=session)
+ queue.start()
+ try:
+ job = queue.download(source=source, dest=tmp_path)
+ queue.join()
+ finally:
+ queue.stop()
+
+ assert job.status == DownloadJobStatus.ERROR
+ assert "UnsafeDownloadURLException" in (job.error_type or "")
+ assert not any(tmp_path.iterdir())
+
+
+def test_rejected_redirect_closes_streamed_response() -> None:
+ queue = DownloadQueueService(requests_session=TestSession())
+ response = Response()
+ response.status_code = 302
+ response.url = "https://public.example/redirect"
+ response.headers["Location"] = "http://127.0.0.1/private"
+ response.raw = MagicMock()
+
+ with pytest.raises(UnsafeDownloadURLException):
+ queue._reject_unsafe_redirect(response)
+
+ response.raw.close.assert_called_once()
+
+
[email protected](timeout=10, method="thread")
+def test_download_refuses_multi_hop_redirect_to_non_public_address(tmp_path: Path) -> None:
+ """Every redirect response must be checked, not only the first hop."""
+ source = AnyHttpUrl("https://test.com/redirector-1")
+ second_hop = "https://test.com/redirector-2"
+ session = TestSession()
+ session.mount(
+ str(source),
+ TestAdapter(b"", status=302, headers={"Location": second_hop}),
+ )
+ session.mount(
+ second_hop,
+ TestAdapter(b"", status=302, headers={"Location": "http://169.254.169.254/latest/meta-data/"}),
+ )
+
+ queue = DownloadQueueService(requests_session=session)
+ queue.start()
+ try:
+ job = queue.download(source=source, dest=tmp_path)
+ queue.join()
+ finally:
+ queue.stop()
+
+ assert job.status == DownloadJobStatus.ERROR
+ assert "UnsafeDownloadURLException" in (job.error_type or "")
+ assert not any(tmp_path.iterdir())
+
+
[email protected](timeout=10, method="thread")
+def test_download_allows_non_public_source_when_opted_in(tmp_path: Path) -> None:
+ source = AnyHttpUrl("http://127.0.0.1:19191/mirror.safetensors")
+ session = TestSession()
+ session.mount(str(source), TestAdapter(b"model-bytes", status=200))
+
+ config = get_config()
+ with patch.object(config, "allow_private_download_urls", True):
+ queue = DownloadQueueService(app_config=config, requests_session=session)
+ queue.start()
+ try:
+ job = queue.download(source=source, dest=tmp_path / "mirror.safetensors")
+ queue.join()
+ finally:
+ queue.stop()
+
+ assert job.status == DownloadJobStatus.COMPLETED
+ assert (tmp_path / "mirror.safetensors").read_bytes() == b"model-bytes"
+
+
+ "filename",
+ ["../evil", "..\\evil", "sub/evil", "sub\\evil", "C:\\evil", "C:evil", "/evil", ".", "..", ""],
+)
+def test_content_disposition_filename_must_be_one_safe_component(filename: str) -> None:
+ """The remote server picks this name; it must never be able to leave `dest`."""
+ queue = DownloadQueueService()
+ assert queue._validate_filename("/tmp", filename) is False
diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.py
index 8d94205237..2b9d04647b 100644
--- a/tests/app/services/model_install/test_model_install.py
+++ b/tests/app/services/model_install/test_model_install.py
@@ -9,6 +9,7 @@ import threading
import time
import uuid
from pathlib import Path
+from types import SimpleNamespace
from typing import Any, Dict
import pytest
@@ -324,6 +325,56 @@ def test_simple_download(mm2_installer: ModelInstallServiceBase, mm2_app_config:
assert isinstance(bus.events[4], ModelInstallCompleteEvent) # install completed
[email protected](timeout=10, method="thread")
+def test_wait_for_installs_waits_for_download_completion_to_enqueue_install(
+ mm2_installer: ModelInstallServiceBase, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Do not report all installs done between download-cache removal and install enqueue."""
+ assert isinstance(mm2_installer, ModelInstallService)
+ job = ModelInstallJob(
+ id=123,
+ source=URLModelSource(url=Url("https://www.test.foo/download/test_embedding.safetensors")),
+ local_path=tmp_path,
+ )
+ with mm2_installer._lock:
+ mm2_installer._download_cache[job.id] = job
+ monkeypatch.setattr(mm2_installer, "_signal_job_downloads_done", lambda install_job: None)
+ assert mm2_installer._wait_for_restore_complete(timeout=2)
+
+ wait_finished = threading.Event()
+
+ def wait_for_installs() -> None:
+ mm2_installer.wait_for_installs(timeout=2)
+ wait_finished.set()
+
+ wait_thread = threading.Thread(target=wait_for_installs)
+ wait_thread.start()
+
+ enqueue_started = threading.Event()
+ release_enqueue = threading.Event()
+
+ def blocked_enqueue(install_job: ModelInstallJob) -> None:
+ assert install_job is job
+ enqueue_started.set()
+ assert release_enqueue.wait(timeout=2)
+
+ monkeypatch.setattr(mm2_installer, "_put_in_queue", blocked_enqueue)
+ callback_thread = threading.Thread(
+ target=mm2_installer._download_complete_callback,
+ args=(SimpleNamespace(id=job.id),),
+ )
+ callback_thread.start()
+ assert enqueue_started.wait(timeout=2)
+ assert not wait_finished.wait(timeout=0.5)
+
+ release_enqueue.set()
+ callback_thread.join(timeout=2)
+ wait_thread.join(timeout=2)
+ assert not callback_thread.is_alive()
+ assert not wait_thread.is_alive()
+ assert wait_finished.is_set()
+
+
@pytest.mark.timeout(timeout=10, method="thread")
def test_import_waits_for_startup_restore(
mm2_app_config: InvokeAIAppConfig,
diff --git a/tests/app/test_invocation_event_socketio.py b/tests/app/test_invocation_event_socketio.py
index 33c71f0cda..35dab858eb 100644
--- a/tests/app/test_invocation_event_socketio.py
+++ b/tests/app/test_invocation_event_socketio.py
@@ -12,14 +12,18 @@ from unittest.mock import AsyncMock
import pytest
from fastapi import FastAPI
+from pydantic.networks import AnyHttpUrl
from invokeai.app.api.sockets import SocketIO
from invokeai.app.services.events.events_common import (
+ DownloadStartedEvent,
InvocationCompleteEvent,
InvocationErrorEvent,
InvocationProgressEvent,
InvocationStartedEvent,
+ ModelInstallStartedEvent,
)
+from invokeai.app.services.model_install.model_install_common import URLModelSource
@pytest.fixture
@@ -152,18 +156,23 @@ async def test_model_load_events_are_emitted_only_to_triggering_user() -> None:
@pytest.mark.anyio
-async def test_model_install_events_remain_broadcast() -> None:
- from invokeai.app.services.events.events_common import ModelInstallStartedEvent
-
+async def test_download_and_model_install_events_are_admin_only() -> None:
socketio = SocketIO(FastAPI())
socketio._sio.emit = AsyncMock()
- from types import SimpleNamespace
-
- event = SimpleNamespace(model_dump=lambda mode="json": {"id": 1})
- # Not a load event, so it takes the broadcast path (no room argument).
- assert not isinstance(event, ModelInstallStartedEvent)
+ download_event = DownloadStartedEvent(source="https://example.com/model", download_path="/cache/model")
+ install_event = ModelInstallStartedEvent(
+ id=1,
+ source=URLModelSource(url=AnyHttpUrl("https://example.com/model")),
+ )
- await socketio._handle_model_event(("model_install_started", event))
+ await socketio._handle_model_event(("download_started", download_event))
+ await socketio._handle_model_event(("model_install_started", install_event))
- socketio._sio.emit.assert_awaited_once_with(event="model_install_started", data={"id": 1})
+ socketio._sio.emit.assert_any_await(
+ event="download_started", data=download_event.model_dump(mode="json"), room="admin"
+ )
+ socketio._sio.emit.assert_any_await(
+ event="model_install_started", data=install_event.model_dump(mode="json"), room="admin"
+ )
+ assert socketio._sio.emit.await_count == 2
diff --git a/tests/app/util/test_ssrf.py b/tests/app/util/test_ssrf.py
new file mode 100644
index 0000000000..4cd5f82df7
--- /dev/null
+++ b/tests/app/util/test_ssrf.py
@@ -0,0 +1,346 @@
+"""Unit tests for the download-URL SSRF guard."""
+
+import http.server
+import ipaddress
+import logging
+import threading
+from typing import Any, Generator
+
+import pytest
+import requests
+from requests import Request
+from requests.models import PreparedRequest
+from requests.utils import select_proxy
+
+from invokeai.app.util import ssrf
+from invokeai.app.util.ssrf import UnsafeDownloadURLException, build_guarded_session, validate_download_url
+
+
+def fake_dns(monkeypatch: Any):
+ """Resolve hostnames from a table so the tests never touch a real resolver."""
+ table: dict[str, list[str]] = {}
+
+ def _resolve(host: str, port: int | None):
+ if host not in table:
+ raise OSError(f"no fake DNS record for {host}")
+ return [ipaddress.ip_address(a) for a in table[host]]
+
+ monkeypatch.setattr(ssrf, "_resolve", _resolve)
+ return table
+
+
+ "url",
+ [
+ "http://127.0.0.1/x",
+ "http://127.1.2.3/x",
+ "https://10.0.0.1/x",
+ "http://172.16.4.5/x",
+ "http://192.168.1.1/x",
+ "http://169.254.169.254/latest/meta-data/", # cloud metadata
+ "http://0.0.0.0/x",
+ "http://[::1]/x",
+ "http://[fe80::1]/x",
+ "http://[fc00::1]/x",
+ "http://[::ffff:127.0.0.1]/x", # IPv4-mapped loopback
+ "http://[::ffff:10.0.0.1]/x",
+ "http://[2002:7f00:0001::]/x", # 6to4-wrapped 127.0.0.1
+ "http://0177.0.0.1/x", # legacy octal IPv4 literal for 127.0.0.1
+ "http://0177.0.0.1./x", # trailing-dot legacy octal literal
+ "http://2130706433/x", # integer literal
+ "http://100.64.0.1/x", # RFC 6598 shared address space -- not is_private
+ "http://198.18.0.1/x", # benchmarking range -- not is_reserved
+ # `requests` percent-decodes unreserved characters in the host before connecting,
+ # so these reach loopback / the metadata service.
+ "http://127%2e0%2e0%2e1/x",
+ "http://169.254.169%2e254/latest/meta-data/",
+ "http://%31%30.0.0.5/x",
+ # IPv6 wrappers that reach an IPv4 destination. These are all `is_global == True`,
+ # so a "not is_global" test on its own lets them through.
+ "http://[64:ff9b::a9fe:a9fe]/latest/meta-data/", # NAT64 for 169.254.169.254
+ "http://[64:ff9b::a00:1]/x", # NAT64 for 10.0.0.1
+ "http://[64:ff9b:1::7f00:1]/x", # NAT64 local-use prefix for 127.0.0.1
+ "http://[::127.0.0.1]/x", # IPv4-compatible loopback
+ "http://[5f00::1]/x", # unallocated
+ "http://[ff02::1]/x", # link-local all-nodes multicast
+ # Teredo: the embedded client is public, but the wrapper itself is not global.
+ "http://[2001:0:53aa:64c:0:5bfe:5f00:1]/x",
+ ],
+)
+def test_rejects_non_public_addresses(url: str):
+ with pytest.raises(UnsafeDownloadURLException):
+ validate_download_url(url)
+
+
+ "url",
+ ["http://93.184.216.34/x", "https://8.8.8.8/x", "http://[2606:4700:4700::1111]/x"],
+)
+def test_allows_public_literals(url: str):
+ validate_download_url(url)
+
+
+def test_allows_public_ipv4_mapped_ipv6_literal():
+ validate_download_url("http://[::ffff:8.8.8.8]/x")
+
+
+def test_rejects_invalid_port_before_dns():
+ with pytest.raises(UnsafeDownloadURLException, match="invalid port"):
+ validate_download_url("http://example.com:65536/x")
+
+
+def test_rejects_hostname_resolving_to_loopback(fake_dns: dict[str, list[str]]):
+ fake_dns["localtest.me"] = ["127.0.0.1"]
+ with pytest.raises(UnsafeDownloadURLException):
+ validate_download_url("http://localtest.me/x")
+
+
[email protected]("host", ["0177.0.0.1", "0177.0.0.1.", "2130706433", "0x7f000001", "127.0.0.1."])
+def test_rejects_legacy_ipv4_literal_without_dns(monkeypatch: Any, host: str):
+ """Legacy numeric IPv4 spellings must not depend on resolver normalization."""
+
+ def fail_resolve(host: str, port: int | None) -> list[ipaddress.IPv4Address]:
+ raise AssertionError(f"unexpected DNS lookup for numeric host {host}")
+
+ monkeypatch.setattr(ssrf, "_resolve", fail_resolve)
+ with pytest.raises(UnsafeDownloadURLException):
+ validate_download_url(f"http://{host}/x")
+
+
+def test_rejects_hostname_with_any_non_public_record(fake_dns: dict[str, list[str]]):
+ """A split-horizon name must not slip through on the strength of its public record."""
+ fake_dns["mixed.example.com"] = ["93.184.216.34", "127.0.0.1"]
+ with pytest.raises(UnsafeDownloadURLException):
+ validate_download_url("http://mixed.example.com/x")
+
+
+def test_blocked_address_error_hides_resolved_ip(fake_dns: dict[str, list[str]], caplog: Any):
+ fake_dns["private.example.com"] = ["10.0.0.7"]
+ with pytest.raises(UnsafeDownloadURLException) as excinfo:
+ validate_download_url("http://private.example.com/x")
+
+ assert "10.0.0.7" not in str(excinfo.value)
+ assert "10.0.0.7" in caplog.text
+
+
+def test_allows_hostname_resolving_to_public_address(fake_dns: dict[str, list[str]]):
+ fake_dns["cdn.example.com"] = ["93.184.216.34", "2606:4700:4700::1111"]
+ validate_download_url("http://cdn.example.com/x")
+
+
+def test_unresolvable_host_is_left_to_the_http_client(fake_dns: dict[str, list[str]]):
+ """We share a resolver with `requests`; if we cannot resolve it, neither can it."""
+ validate_download_url("http://no-such-host.invalid/x")
+
+
[email protected]("url", ["file:///etc/passwd", "ftp://example.com/x", "gopher://example.com/x"])
+def test_rejects_non_http_schemes(url: str):
+ with pytest.raises(UnsafeDownloadURLException):
+ validate_download_url(url)
+
+
+def test_opt_in_allows_private_addresses():
+ validate_download_url("http://127.0.0.1/x", allow_private_urls=True)
+
+
+def test_opt_in_still_rejects_bad_schemes():
+ with pytest.raises(UnsafeDownloadURLException):
+ validate_download_url("file:///etc/passwd", allow_private_urls=True)
+
+
+# --------------- Socket-level guard: the check that survives rebinding ---------------
+
+
+class _Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self): # noqa: N802
+ body = b"internal-only"
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+
+def loopback_server() -> Generator[int, None, None]:
+ srv = http.server.HTTPServer(("127.0.0.1", 0), _Handler)
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ try:
+ yield srv.server_address[1]
+ finally:
+ srv.shutdown()
+
+
+def _unsafe_in_chain(exc: BaseException) -> bool:
+ seen = exc
+ while seen is not None:
+ if isinstance(seen, UnsafeDownloadURLException):
+ return True
+ seen = seen.__cause__ or seen.__context__
+ return False
+
+
+def test_guarded_session_refuses_loopback(loopback_server: int):
+ session = build_guarded_session()
+ with pytest.raises(Exception) as excinfo:
+ session.get(f"http://127.0.0.1:{loopback_server}/x", timeout=5)
+ assert _unsafe_in_chain(excinfo.value)
+
+
+def test_guarded_session_blocks_dns_rebinding(loopback_server: int, monkeypatch: Any):
+ """The up-front check sees a public record; the socket still lands on loopback.
+
+ An attacker who controls the zone can answer our lookup and the HTTP client's lookup
+ differently, so only the connected-socket check can catch this.
+ """
+ monkeypatch.setattr(ssrf, "_resolve", lambda host, port: [ipaddress.ip_address("93.184.216.34")])
+
+ url = f"http://localhost:{loopback_server}/x"
+ validate_download_url(url) # up-front check is fooled, by construction
+
+ session = build_guarded_session()
+ with pytest.raises(Exception) as excinfo:
+ session.get(url, timeout=5)
+ assert _unsafe_in_chain(excinfo.value)
+
+
+def test_guarded_session_blocks_percent_encoded_host(loopback_server: int, monkeypatch: Any):
+ """Even with the up-front check disabled, `%6cocalhost` cannot reach loopback."""
+ monkeypatch.setattr(ssrf, "_host_spellings", lambda host: [host])
+ url = f"http://%6cocalhost:{loopback_server}/x"
+ validate_download_url(url) # unresolvable as spelled -> fails open, by construction
+
+ session = build_guarded_session()
+ with pytest.raises(Exception) as excinfo:
+ session.get(url, timeout=5)
+ assert _unsafe_in_chain(excinfo.value)
+
+
+def test_guarded_session_is_installed_for_both_schemes():
+ session = build_guarded_session()
+ for prefix in ("http://", "https://"):
+ adapter = session.get_adapter(prefix + "example.com")
+ assert isinstance(adapter, ssrf.SsrfGuardedAdapter)
+ assert adapter.poolmanager.pool_classes_by_scheme["http"] is ssrf._GuardedHTTPConnectionPool
+ assert adapter.poolmanager.pool_classes_by_scheme["https"] is ssrf._GuardedHTTPSConnectionPool
+
+
+ "url",
+ [
+ "http://100.63.255.255/x", # just below the shared address space
+ "http://100.128.0.1/x", # just above it
+ "http://[2606:4700:4700::1111]/x",
+ ],
+)
+def test_public_neighbours_of_blocked_ranges_still_allowed(url: str):
+ """The `is_global` tightening must not spill over into genuinely public space."""
+ validate_download_url(url)
+
+
+# ----------------------------- Proxy visibility -----------------------------
+
+
+def test_guarded_session_ignores_environment_proxy(monkeypatch: Any, caplog: Any):
+ """Ambient proxies must not move destination resolution outside the socket guard."""
+ monkeypatch.setenv("HTTP_PROXY", "http://proxy.internal:3128")
+ session = build_guarded_session()
+ assert session.trust_env is True
+ assert ssrf.proxies_in_effect(session) == {}
+ assert session.merge_environment_settings("https://example.com", {}, None, None, None)["proxies"] == {}
+
+ logger = logging.getLogger("test-ssrf-proxy")
+ with caplog.at_level(logging.WARNING, logger="test-ssrf-proxy"):
+ ssrf.warn_if_proxied(session, logger)
+ assert "proxy settings are ignored" in caplog.text
+
+
+def test_guarded_session_preserves_environment_ca_bundle(monkeypatch: Any):
+ ca_bundle = "/tmp/invokeai-test-ca.pem"
+ monkeypatch.setenv("REQUESTS_CA_BUNDLE", ca_bundle)
+ session = build_guarded_session()
+ settings = session.merge_environment_settings("https://example.com", {}, None, None, None)
+ assert settings["verify"] == ca_bundle
+
+
+def test_guarded_session_preserves_environment_netrc(monkeypatch: Any, tmp_path: Any):
+ netrc = tmp_path / "netrc"
+ netrc.write_text("machine example.com login netrc-user password netrc-pass\n")
+ monkeypatch.setenv("NETRC", str(netrc))
+ prepared = build_guarded_session().prepare_request(Request("GET", "https://example.com/file.bin"))
+ assert prepared.headers["Authorization"] == "Basic bmV0cmMtdXNlcjpuZXRyYy1wYXNz"
+
+
+def test_guarded_session_supports_explicit_proxy(monkeypatch: Any):
+ monkeypatch.setenv("HTTPS_PROXY", "http://ambient.internal:3128")
+ session = build_guarded_session(proxy="http://proxy.internal:3128")
+ assert ssrf.proxies_in_effect(session) == {
+ "http": "http://proxy.internal:3128",
+ "https": "http://proxy.internal:3128",
+ }
+ assert session.merge_environment_settings("https://example.com", {}, None, None, None)["proxies"] == {
+ "http": "http://proxy.internal:3128",
+ "https": "http://proxy.internal:3128",
+ }
+ request = PreparedRequest()
+ request.prepare(method="GET", url="https://example.com/file.bin")
+ assert session.rebuild_proxies(request, {}) == {}
+ assert session.rebuild_proxies(request, session.proxies) == session.proxies
+
+ captured: dict[str, Any] = {}
+
+ def capture_send(_session: requests.Session, _request: PreparedRequest, **kwargs: Any) -> None:
+ captured.update(kwargs)
+
+ monkeypatch.setattr(requests.Session, "send", capture_send)
+ session.send(request)
+ assert captured["proxies"] == session.proxies
+
+
+def test_no_warning_without_a_proxy(monkeypatch: Any, caplog: Any):
+ for var in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"):
+ monkeypatch.delenv(var, raising=False)
+ session = build_guarded_session()
+ assert ssrf.proxies_in_effect(session) == {}
+
+ logger = logging.getLogger("test-ssrf-noproxy")
+ with caplog.at_level(logging.WARNING, logger="test-ssrf-noproxy"):
+ ssrf.warn_if_proxied(session, logger)
+ assert caplog.text == ""
+
+
[email protected]("var", ["ALL_PROXY", "all_proxy", "HTTP_PROXY", "http_proxy"])
+def test_proxy_detection_covers_every_env_spelling(monkeypatch: Any, var: str):
+ """`ALL_PROXY` becomes the key "all", which requests honours as a catch-all.
+
+ Filtering `getproxies()` by scheme silently missed it, so the warning did not fire in
+ the setup where it matters most.
+ """
+ for name in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"):
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setenv(var, "http://proxy.internal:3128")
+
+ session = ssrf.requests.Session()
+ detected = ssrf.proxies_in_effect(session)
+ assert detected, f"{var} was not detected"
+ assert select_proxy("http://example.com/x", detected) == "http://proxy.internal:3128"
+
+
+ ("url", "blocked"),
+ [
+ ("http://[2a01:1:2:3:0:5efe:a00:1]/x", True), # ISATAP wrapping 10.0.0.1
+ ("http://[2a01:1:2:3:200:5efe:7f00:1]/x", True), # ISATAP wrapping 127.0.0.1
+ ("http://[2a01:1:2:3:0:5efe:5db8:d822]/x", False), # ISATAP wrapping a public v4
+ ("http://[64:ff9b::a9fe:a9fe]/x", True), # NAT64 WKP -- caught as ::/8 reserved
+ ],
+)
+def test_ipv6_transition_wrappers(url: str, blocked: bool):
+ if blocked:
+ with pytest.raises(UnsafeDownloadURLException):
+ validate_download_url(url)
+ else:
+ validate_download_url(url)