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(api): reject path traversal in object-serializer names and model keys (#9595)

Lincoln Steinfac15fe772e6
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.py
index 52f6544e30..01b2e6f219 100644
--- a/invokeai/app/api/routers/model_manager.py
+++ b/invokeai/app/api/routers/model_manager.py
@@ -7,6 +7,7 @@ import io
import pathlib
import threading
import traceback
+import unicodedata
from collections.abc import Generator
from copy import deepcopy
from enum import Enum
@@ -24,7 +25,10 @@ from typing_extensions import Annotated
from invokeai.app.api.auth_dependencies import AdminUserOrDefault, CurrentUserOrDefault
from invokeai.app.api.dependencies import ApiDependencies
-from invokeai.app.services.model_images.model_images_common import ModelImageFileNotFoundException
+from invokeai.app.services.model_images.model_images_common import (
+ ModelImageFileDeleteException,
+ ModelImageFileNotFoundException,
+)
from invokeai.app.services.model_install.model_install_common import ModelInstallJob
from invokeai.app.services.model_records import (
InvalidModelException,
@@ -34,6 +38,7 @@ from invokeai.app.services.model_records import (
)
from invokeai.app.services.orphaned_models import CONVERSION_SCRATCH_DIRNAME, OrphanedModelInfo
from invokeai.app.services.shared.sqlite.sqlite_common import SQLiteDirection
+from invokeai.app.util.path_safety import is_plain_filename
from invokeai.app.util.suppress_output import SuppressOutput
from invokeai.backend.model_manager.configs.external_api import ExternalApiModelConfig
from invokeai.backend.model_manager.configs.factory import AnyModelConfig, ModelConfigFactory
@@ -77,6 +82,18 @@ _MODEL_KEY_CLAIM_LOCK = threading.Lock()
_CLAIMED_MODEL_KEYS: set[str] = set()
+def _claim_token(key: str) -> str:
+ """The form of a key recorded in `_CLAIMED_MODEL_KEYS`.
+
+ A model's cover image is stored as `<key>.webp`, and some filesystems map different strings to one file: the
+ macOS and Windows defaults are case-insensitive, and APFS also ignores Unicode normalization, so `\u00e9` and
+ `e\u0301` name the same entry. Claims use Unicode canonical caseless matching (NFD, casefold, NFD) so that such a
+ variant of a key cannot slip past a claim held on the key itself and touch that file. Two keys that are
+ distinct on disk but equal under this form would at worst serialize against each other.
+ """
+ return unicodedata.normalize("NFD", unicodedata.normalize("NFD", key).casefold())
+
+
@contextlib.contextmanager
def _claim_model_key(key: str) -> Generator[None, None, None]:
"""Hold the exclusive claim on one model key, or raise 409 if another request holds it."""
@@ -87,20 +104,21 @@ def _claim_model_key(key: str) -> Generator[None, None, None]:
status_code=409,
detail="Another model operation is already in progress. Wait for it to finish and try again.",
)
+ token = _claim_token(key)
try:
- if key in _CLAIMED_MODEL_KEYS:
+ if token in _CLAIMED_MODEL_KEYS:
raise HTTPException(
status_code=409,
detail=f"Another operation on model {key} is already in progress. Wait for it to finish and try again.",
)
- _CLAIMED_MODEL_KEYS.add(key)
+ _CLAIMED_MODEL_KEYS.add(token)
finally:
_MODEL_KEY_CLAIM_LOCK.release()
try:
yield
finally:
with _MODEL_KEY_CLAIM_LOCK:
- _CLAIMED_MODEL_KEYS.discard(key)
+ _CLAIMED_MODEL_KEYS.discard(token)
@contextlib.contextmanager
@@ -112,17 +130,18 @@ def _install_and_claim_model(
# request claims so a delete cannot observe the new record before its key is claimed.
with _MODEL_KEY_CLAIM_LOCK:
new_key = installer.install_path(model_path, config=config)
- if new_key in _CLAIMED_MODEL_KEYS:
+ token = _claim_token(new_key)
+ if token in _CLAIMED_MODEL_KEYS:
raise HTTPException(
status_code=409,
detail=f"Another operation on model {new_key} is already in progress. Wait for it to finish and try again.",
)
- _CLAIMED_MODEL_KEYS.add(new_key)
+ _CLAIMED_MODEL_KEYS.add(token)
try:
yield new_key
finally:
with _MODEL_KEY_CLAIM_LOCK:
- _CLAIMED_MODEL_KEYS.discard(new_key)
+ _CLAIMED_MODEL_KEYS.discard(token)
# The HF token is process-global state backed by a file in the HF cache. Concurrent writers would
@@ -580,6 +599,13 @@ async def update_model_record(
current_admin: AdminUserOrDefault,
) -> AnyModelConfig:
"""Update a model's config."""
+ # The key identifies the row; it is not an editable field, and there is no UI to change one. The edit form
+ # does post the record back whole, so an unchanged echo is expected and accepted - but a *different* key is
+ # written into the stored config while the row id keeps the old one, which leaves a record that answers to a
+ # key nothing can look it up by: `replace_model` (and so reidentify) raises `UnknownModelException` forever
+ # after, and the UI caches the model under the new key so every later request for it 404s.
+ if "key" in changes.model_fields_set and changes.key != key:
+ raise HTTPException(status_code=422, detail="A model's key cannot be changed")
return await asyncio.to_thread(_update_model_record, key, changes)
@@ -643,6 +669,7 @@ def get_model_image(
"description": "The model image was updated successfully",
},
400: {"description": "Bad request"},
+ 404: {"description": "The model could not be found"},
409: {"description": "Another operation on this model is already in progress"},
},
status_code=200,
@@ -660,6 +687,25 @@ async def update_model_image(
# A conversion moves this model's image to the replacement's key when it finishes, so claim
# the key before reading the upload and hold it until the image is saved.
with _claim_model_key(key):
+ # The image is stored in a file named after the key, so a key that names no model would have us write a
+ # stray file - and a key that is not a plain filename would have us write it outside the images folder.
+ # Resolving the record turns both into a 404 instead. It has to happen under the claim: the delete and
+ # convert routes claim the key too, so they cannot remove the record between this check and the save.
+ # (Removing an external provider's models in `app_info.py` does not take the claim, so that path can
+ # still leave an orphan image - which the image-delete route below can clean up.)
+ try:
+ ApiDependencies.invoker.services.model_manager.store.get_model(key)
+ except UnknownModelException as e:
+ raise HTTPException(status_code=404, detail=str(e))
+
+ # A record written before install requests had their keys validated can still carry a key that is not a
+ # plain filename. The storage service refuses to build a path from it; ask it now, so that is a 404
+ # rather than a save failure surfacing as a 500 after the upload has been read.
+ try:
+ model_images.get_path(key)
+ except ModelImageFileNotFoundException as e:
+ raise HTTPException(status_code=404, detail=str(e))
+
contents = await image.read()
try:
pil_image = await asyncio.to_thread(Image.open, io.BytesIO(contents))
@@ -847,13 +893,17 @@ def delete_model_image(
# Claimed for the same reason as the upload: a conversion carries this model's image over to
# the replacement's key, so a delete accepted meanwhile is undone by that copy.
with _claim_model_key(key):
+ # Unlike the upload, this does not require the model's record: deleting a model leaves its image
+ # behind, and this route is how that orphan gets cleaned up. The storage service rejects a key that
+ # is not a plain filename, and that - like a missing file - is a 404.
try:
model_images.delete(key)
logger.info(f"Deleted model image: {key}")
return
- except UnknownModelException as e:
- logger.error(str(e))
- raise HTTPException(status_code=404, detail=str(e))
+ except ModelImageFileDeleteException as e:
+ if isinstance(e.__cause__, ModelImageFileNotFoundException):
+ raise HTTPException(status_code=404, detail=str(e.__cause__))
+ raise
@model_manager_router.post(
@@ -906,6 +956,12 @@ def install_model(
"""
logger = ApiDependencies.invoker.services.logger
+ # A caller may name the key it wants, and the key names the directory the model is moved into and the file its
+ # cover image is written to. Reject an unusable one here, where it is being chosen, rather than letting the
+ # install fail later at one of those joins. Existing records are not held to this - see `ModelRecordChanges.key`.
+ if config.key is not None and not is_plain_filename(config.key):
+ raise HTTPException(status_code=422, detail=f"Invalid model key {config.key!r}: it must be a plain filename")
+
try:
installer = ApiDependencies.invoker.services.model_manager.install
result: ModelInstallJob = installer.heuristic_import(
diff --git a/invokeai/app/services/model_images/model_images_default.py b/invokeai/app/services/model_images/model_images_default.py
index 5fe8086c6a..e074bbf70c 100644
--- a/invokeai/app/services/model_images/model_images_default.py
+++ b/invokeai/app/services/model_images/model_images_default.py
@@ -11,6 +11,7 @@ from invokeai.app.services.model_images.model_images_common import (
ModelImageFileSaveException,
)
from invokeai.app.util.misc import uuid_string
+from invokeai.app.util.path_safety import is_contained_filename
from invokeai.app.util.thumbnails import make_thumbnail
@@ -38,7 +39,7 @@ class ModelImageFileStorageDisk(ModelImageFileStorageBase):
def save(self, image: PILImageType, model_key: str) -> None:
try:
self._validate_storage_folders()
- image_path = self._model_images_folder / (model_key + ".webp")
+ image_path = self.get_path(model_key)
thumbnail = make_thumbnail(image, 256)
thumbnail.save(image_path, format="webp")
@@ -46,14 +47,23 @@ class ModelImageFileStorageDisk(ModelImageFileStorageBase):
raise ModelImageFileSaveException from e
def get_path(self, model_key: str) -> Path:
+ self._validate_key(model_key)
path = self._model_images_folder / (model_key + ".webp")
return path
def get_url(self, model_key: str) -> str | None:
- path = self.get_path(model_key)
- if not self._validate_path(path):
- return
+ try:
+ path = self.get_path(model_key)
+ except ModelImageFileNotFoundException:
+ # This is called while listing every model, so a bad key must not take the whole list down.
+ return None
+ try:
+ if not self._validate_path(path):
+ return
+ except OSError:
+ # e.g. ENAMETOOLONG for an over-long stored key: as above, one bad key must not fail the whole list.
+ return None
url = self._invoker.services.urls.get_model_image_url(model_key)
@@ -78,6 +88,20 @@ class ModelImageFileStorageDisk(ModelImageFileStorageBase):
"""Validates the path given for an image."""
return path.exists()
+ @staticmethod
+ def _validate_key(model_key: str) -> None:
+ """Validates that a model key cannot escape the model images folder.
+
+ Keys are server-generated - a uuid, or a slug for external API models - but they arrive from the client as
+ a path parameter, so they are untrusted. This checks containment on the running platform rather than the
+ portable rules new keys must meet: a key stored by an older version may be a legal posix filename that
+ Windows would reject (`legacy:key`), and its existing cover must stay servable and manageable.
+
+ :raises ModelImageFileNotFoundException: if the key would not name a file inside the folder
+ """
+ if not is_contained_filename(model_key):
+ raise ModelImageFileNotFoundException(f"Invalid model key {model_key!r}")
+
def _validate_storage_folders(self) -> None:
"""Checks if the required folders exist and create them if they don't"""
self._model_images_folder.mkdir(parents=True, exist_ok=True)
diff --git a/invokeai/app/services/model_install/model_install_default.py b/invokeai/app/services/model_install/model_install_default.py
index 5b7337d587..72ecf76be8 100644
--- a/invokeai/app/services/model_install/model_install_default.py
+++ b/invokeai/app/services/model_install/model_install_default.py
@@ -41,6 +41,7 @@ from invokeai.app.services.model_install.model_install_common import (
from invokeai.app.services.model_records import DuplicateModelException, ModelRecordServiceBase, UnknownModelException
from invokeai.app.services.model_records.model_records_base import ModelRecordChanges
from invokeai.app.util.misc import get_iso_timestamp
+from invokeai.app.util.path_safety import is_plain_filename
from invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base
from invokeai.backend.model_manager.configs.external_api import (
ExternalApiModelConfig,
@@ -243,12 +244,18 @@ class ModelInstallService(ModelInstallServiceBase):
self._logger.info(f"Removing duplicate temporary directory {tmpdir}")
self._safe_rmtree(tmpdir, self._logger)
continue
+ # Inside the `try`: a marker written by an older version can hold a config that no longer
+ # validates, and that must skip this marker, not abort the restore of every marker after it. Note
+ # that an unsafe *key* is no longer such a case - `ModelRecordChanges` deliberately accepts one so
+ # the install is restored and then fails at the join in `install_path()`, which errors the job and
+ # reclaims its tmpdir. Skipping it here would strand the partial download instead: no job is
+ # created to clean up, and `_remove_dangling_install_dirs` keeps any readable non-terminal marker.
+ config_in = ModelRecordChanges(**(marker.get("config_in") or {}))
seen_sources.add(source_str)
except Exception as e:
self._logger.warning(f"Skipping install marker in {tmpdir}: {e}")
continue
- config_in = ModelRecordChanges(**(marker.get("config_in") or {}))
job = ModelInstallJob(
id=self._next_id(),
source=source,
@@ -460,6 +467,10 @@ class ModelInstallService(ModelInstallServiceBase):
config = config or ModelRecordChanges()
info: AnyModelConfig = self._probe(Path(model_path), config) # type: ignore
+ # The key names the directory the model is moved into. `ModelRecordChanges` validates a client-supplied key,
+ # but a caller can build one without validation, so check again here - before anything is created or moved.
+ if not is_plain_filename(info.key):
+ raise ValueError(f"Invalid model key {info.key!r}: it must be a plain filename")
dest_dir = self.app_config.models_path / info.key
try:
if dest_dir.exists():
@@ -1014,6 +1025,9 @@ class ModelInstallService(ModelInstallServiceBase):
)
name = job.config_in.name or f"{provider_id} {provider_model_id}"
key = job.config_in.key or slugify(f"{provider_id}-{provider_model_id}")
+ # External registration builds its config directly, so it never passes through `_probe`'s check.
+ if not is_plain_filename(key):
+ raise InvalidModelConfigException(f"Invalid model key {key!r}: it must be a plain filename")
existing_external = next(
(
@@ -1150,6 +1164,12 @@ class ModelInstallService(ModelInstallServiceBase):
def _probe(self, model_path: Path, config: Optional[ModelRecordChanges] = None):
config = config or ModelRecordChanges()
+ # A caller may name the key it wants, and the key names a directory under `models_path` and a file under
+ # `model_images`. `ModelRecordChanges` deliberately does not validate it (it is the update body too, and is
+ # re-parsed from old install markers), so assert it here - the one place a caller-supplied key becomes a
+ # record's key, for in-place registration as well as for a move-in install.
+ if config.key is not None and not is_plain_filename(config.key):
+ raise InvalidModelConfigException(f"Invalid model key {config.key!r}: it must be a plain filename")
hash_algo = self._app_config.hashing_algorithm
fields = config.model_dump()
diff --git a/invokeai/app/services/model_records/model_records_base.py b/invokeai/app/services/model_records/model_records_base.py
index 41f098addc..f37e839a55 100644
--- a/invokeai/app/services/model_records/model_records_base.py
+++ b/invokeai/app/services/model_records/model_records_base.py
@@ -109,7 +109,14 @@ class ModelRecordChanges(BaseModelExcludeNull):
description: Optional[str] = Field(description="Model description", default=None)
base: Optional[BaseModelType] = Field(description="The base model.", default=None)
type: Optional[ModelType] = Field(description="Type of model", default=None)
+ # Deliberately NOT validated here. This model is the *update* body as well as the install body, and the model
+ # edit form posts the whole record back (`ModelEdit.tsx` seeds the form from the config, key included), so a
+ # validator on this field makes a model whose key predates key validation impossible to edit: FastAPI answers
+ # 422 before the handler runs, and the UI offers no way to change a key. The same model is also re-parsed from
+ # install markers written by older versions during startup recovery. The key is validated where an install
+ # adopts one (`install_model`) and again at every join that builds a path out of it.
key: Optional[str] = Field(description="Database ID for this model", default=None)
+
hash: Optional[str] = Field(description="hash of model file", default=None)
file_size: Optional[int] = Field(description="Size of model file", default=None)
format: Optional[str] = Field(description="format of model file", default=None)
diff --git a/invokeai/app/services/object_serializer/object_serializer_common.py b/invokeai/app/services/object_serializer/object_serializer_common.py
index 7057386541..59f5fb01c4 100644
--- a/invokeai/app/services/object_serializer/object_serializer_common.py
+++ b/invokeai/app/services/object_serializer/object_serializer_common.py
@@ -3,3 +3,10 @@ class ObjectNotFoundError(KeyError):
def __init__(self, name: str) -> None:
super().__init__(f"Object with name {name} not found")
+
+
+class InvalidObjectNameError(ValueError):
+ """Raised when an object name is not a plain filename (e.g. it contains path separators)"""
+
+ def __init__(self, name: str) -> None:
+ super().__init__(f"Invalid object name {name!r}, potential directory traversal detected")
diff --git a/invokeai/app/services/object_serializer/object_serializer_disk.py b/invokeai/app/services/object_serializer/object_serializer_disk.py
index bbd3f78550..4c75a89a08 100644
--- a/invokeai/app/services/object_serializer/object_serializer_disk.py
+++ b/invokeai/app/services/object_serializer/object_serializer_disk.py
@@ -7,8 +7,12 @@ from typing import TYPE_CHECKING, Optional, TypeVar
import torch
from invokeai.app.services.object_serializer.object_serializer_base import ObjectSerializerBase
-from invokeai.app.services.object_serializer.object_serializer_common import ObjectNotFoundError
+from invokeai.app.services.object_serializer.object_serializer_common import (
+ InvalidObjectNameError,
+ ObjectNotFoundError,
+)
from invokeai.app.util.misc import uuid_string
+from invokeai.app.util.path_safety import is_plain_filename
if TYPE_CHECKING:
from invokeai.app.services.invoker import Invoker
@@ -53,7 +57,9 @@ class ObjectSerializerDisk(ObjectSerializerBase[T]):
def load(self, name: str) -> T:
file_path = self._get_path(name)
try:
- return torch.load(file_path) # pyright: ignore [reportUnknownMemberType]
+ # `weights_only=True` is the default from torch 2.6 onwards, but pin it explicitly: these files are
+ # named by (untrusted) graph input, so an unpickling path must never be reachable from a graph.
+ return torch.load(file_path, weights_only=True) # pyright: ignore [reportUnknownMemberType]
except FileNotFoundError as e:
raise ObjectNotFoundError(name) from e
@@ -75,8 +81,21 @@ class ObjectSerializerDisk(ObjectSerializerBase[T]):
return self.__obj_class_name
def _get_path(self, name: str) -> Path:
+ self._validate_name(name)
return self._output_dir / name
+ @staticmethod
+ def _validate_name(name: str) -> None:
+ """Validates that an object name is a plain filename, so it cannot escape the output directory.
+
+ Names are generated by `_new_name()`, but they travel to the client inside node outputs (e.g.
+ `TensorField.tensor_name`) and come back as node inputs, so they are untrusted on the way in.
+
+ :raises InvalidObjectNameError: if the name is not a plain filename
+ """
+ if not is_plain_filename(name):
+ raise InvalidObjectNameError(name)
+
def _new_name(self) -> str:
return f"{self._obj_class_name}_{uuid_string()}"
diff --git a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_24.py b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_24.py
index 6aa76991fc..40405cdd50 100644
--- a/invokeai/app/services/shared/sqlite_migrator/migrations/migration_24.py
+++ b/invokeai/app/services/shared/sqlite_migrator/migrations/migration_24.py
@@ -8,6 +8,7 @@ from pydantic import ValidationError
from invokeai.app.services.config import InvokeAIAppConfig
from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_common import Migration
+from invokeai.app.util.path_safety import is_contained_filename
from invokeai.backend.model_manager.configs.factory import AnyModelConfigValidator
@@ -117,7 +118,14 @@ class Migration24Callback:
# We'll store the file operations we perform so we can roll them back if needed.
rollback_ops: list[tuple[Path, Path]] = []
- # Destination directory is models_dir/<key> - a flat directory structure.
+ # Destination directory is models_dir/<key> - a flat directory structure. The key comes from the stored
+ # config blob, and older versions did not check what went in there, so a key that would not stay inside
+ # `models_dir` on this platform would mkdir and move the weights outside it. Leave such a model where it is
+ # rather than relocating it somewhere it should not be; it stays usable via its recorded path.
+ if not is_contained_filename(key):
+ self._logger.warning("Model key %r would escape the models directory; leaving its files in place", key)
+ return NormalizeResult(new_relative_path=None, rollback_ops=[])
+
destination_dir = models_dir / key
try:
diff --git a/invokeai/app/services/urls/urls_default.py b/invokeai/app/services/urls/urls_default.py
index cb21bd0222..73208c9948 100644
--- a/invokeai/app/services/urls/urls_default.py
+++ b/invokeai/app/services/urls/urls_default.py
@@ -1,4 +1,5 @@
import os
+from urllib.parse import quote
from invokeai.app.services.urls.urls_base import UrlServiceBase
@@ -27,7 +28,9 @@ class LocalUrlService(UrlServiceBase):
return f"{self._base_url}/videos/i/{video_basename}/full"
def get_model_image_url(self, model_key: str) -> str:
- return f"{self._base_url_v2}/models/i/{model_key}/image"
+ # A key stored by an older version can hold URL syntax (`?`, `#`, `%`); unencoded, `X?y` would address the
+ # route for model `X` instead of this image.
+ return f"{self._base_url_v2}/models/i/{quote(model_key, safe='')}/image"
def get_style_preset_image_url(self, style_preset_id: str) -> str:
return f"{self._base_url}/style_presets/i/{style_preset_id}/image"
diff --git a/invokeai/app/util/path_safety.py b/invokeai/app/util/path_safety.py
new file mode 100644
index 0000000000..4f8ab6ce69
--- /dev/null
+++ b/invokeai/app/util/path_safety.py
@@ -0,0 +1,89 @@
+import os
+from pathlib import PureWindowsPath
+
+# Read at call time by `is_contained_filename`, so tests can exercise both platforms' rules on either.
+_ON_WINDOWS = os.name == "nt"
+
+# C0, DEL and C1. `str.splitlines()` also splits on U+0085 (in C1), U+2028 and U+2029, so a name containing one
+# of those forges a second line in any log record that interpolates it.
+_CONTROL_CHARS = (
+ frozenset(chr(c) for c in range(0x20)) | frozenset(chr(c) for c in range(0x7F, 0xA0)) | {"\u2028", "\u2029"}
+)
+
+# Characters Windows does not allow in a filename. `:` is the one that matters for containment - see the
+# docstring - and the rest come along because a name that is not a valid filename everywhere is not a name we
+# should be joining onto a directory.
+_RESERVED_CHARS = frozenset('<>:"|?*')
+
+# Windows resolves these to the device namespace from *any* directory, so they never name a file in the directory
+# they were joined onto - `<store>/NUL.webp` is the NUL device, and a write to it is silently discarded. Matched on
+# the stem, case-insensitively: `CON.txt` is reserved, `CONTEXT` is not.
+# `COM`/`LPT` are reserved with the superscript digits too (Microsoft's "Naming Files, Paths, and Namespaces"
+# lists them explicitly), and with `0` on current Windows.
+_RESERVED_STEMS = frozenset(
+ {"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", "CLOCK$", "CONFIG$", "KEYBD$", "SCREEN$"}
+ | {f"{dev}{d}" for dev in ("COM", "LPT") for d in "0123456789\u00b9\u00b2\u00b3"}
+)
+
+
+def is_plain_filename(name: str) -> bool:
+ r"""Checks whether a name is safe to join onto a storage directory.
+
+ Names that identify a stored file - object serializer names, model keys, image names - are generated by the
+ server, but they travel out to the client and come back as request parameters or node inputs, so on the way in
+ they are untrusted. Joining one onto a directory is only safe if it is a bare filename: anything carrying a
+ separator, a drive letter or a `..` would resolve outside that directory.
+
+ Five details are worth spelling out:
+
+ - `PureWindowsPath` is used for the check rather than the platform's `Path`. It treats both `/` and `\` as
+ separators and understands drive letters, so backslash- and drive-shaped payloads are rejected on posix too,
+ instead of passing here and only escaping on Windows deployments.
+ - Colons are rejected outright rather than left to `PureWindowsPath`, which only reads a *single* leading
+ character as a drive: it parses `C:foo` as drive `C:` plus `foo`, but hands back `..:stream` whole. On NTFS
+ that names the alternate data stream `stream` on the file `..` - the parent directory - so
+ `<store>/..:stream` writes outside the store while looking like one bare component to `pathlib`.
+ - Trailing dots and spaces are stripped before the `.`/`..` comparison. `pathlib` keeps them, but the Win32
+ path normaliser drops them from the final component when the file is opened, so `".. "` would reach the
+ parent directory on Windows.
+ - Windows device names (`NUL`, `CON`, `COM1`, ...) are rejected. They do not escape upwards, but they do not
+ stay put either: Win32 resolves them to the device namespace from any directory, so the join silently does
+ not address a file in the store at all.
+ - Control characters are rejected outright. They cannot escape a directory on their own, but a name is only
+ "safe to join" if it also survives being put in a log line.
+
+ Nothing the server generates - a uuid, `f"{cls.__name__}_{uuid}"`, or a `slugify()`ed external-model key -
+ can contain any of the rejected characters, so this never turns away a name we produced ourselves.
+ """
+ if not name or _CONTROL_CHARS.intersection(name) or _RESERVED_CHARS.intersection(name):
+ return False
+ # Win32 strips trailing dots and spaces from the final component when it opens the file, so compare against
+ # what it would actually be left holding.
+ normalised = name.rstrip(" .")
+ if normalised in ("", ".", ".."):
+ return False
+ # Win32 takes the base name up to the first `.` and trims trailing spaces from it before the device lookup,
+ # so `"NUL .webp"` is still the NUL device - strip again after the split, not only before it.
+ if normalised.split(".", 1)[0].rstrip(" ").upper() in _RESERVED_STEMS:
+ return False
+ return PureWindowsPath(name).name == name
+
+
+def is_contained_filename(name: str) -> bool:
+ r"""Checks whether a name that may already be on disk can be joined onto its storage directory.
+
+ `is_plain_filename` is the gate for a name we are about to *accept*: it applies Windows' rules everywhere, so
+ nothing new can be stored that some deployment could not hold. But no released version checked model keys, and
+ on posix `: ? * | < > " \` and names like `NUL` are ordinary filename characters, so records exist whose keys
+ fail it - and whose files (a model's cover image, say) are sitting in the store under those names. Applying the
+ portable rules to *those* would only strand the data: its cover stops being served and can no longer be replaced
+ or deleted.
+
+ So this checks containment on the platform we are running on, and nothing more. On Windows that is exactly
+ `is_plain_filename`, since every rule there exists because Win32 would otherwise leave the directory (or the
+ file namespace). On posix, only an empty name, `.`, `..` or a `/` can leave it; control characters are refused
+ on both for the same log-safety reason `is_plain_filename` gives.
+ """
+ if _ON_WINDOWS:
+ return is_plain_filename(name)
+ return bool(name) and not _CONTROL_CHARS.intersection(name) and "/" not in name and name not in (".", "..")
diff --git a/invokeai/backend/model_manager/util/lora_metadata_extractor.py b/invokeai/backend/model_manager/util/lora_metadata_extractor.py
index 12b1073935..81047f6e68 100644
--- a/invokeai/backend/model_manager/util/lora_metadata_extractor.py
+++ b/invokeai/backend/model_manager/util/lora_metadata_extractor.py
@@ -7,6 +7,7 @@ from typing import Any, Dict, Optional, Set, Tuple
from PIL import Image
+from invokeai.app.util.path_safety import is_plain_filename
from invokeai.app.util.thumbnails import make_thumbnail
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.taxonomy import ModelType
@@ -42,6 +43,13 @@ def extract_lora_metadata(
def _process_preview_image(model_stem: str, model_dir: Path, model_key: str, model_images_path: Path) -> bool:
"""Find and process a preview image for the model, saving it to the model images store."""
+ # An install request may name its own key (`ModelRecordChanges.key`), and this writes a file named after it.
+ # `ModelImageFileStorageDisk` is not in play here - the path is built by hand - so the check has to happen
+ # here too, or a key like `../../foo` would write the thumbnail outside the model images folder.
+ if not is_plain_filename(model_key):
+ logger.warning(f"Refusing to write a preview image for invalid model key {model_key!r}")
+ return False
+
image_extensions = [".png", ".jpg", ".jpeg", ".webp"]
for ext in image_extensions:
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index d9faa385ef..fb4fc35325 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -3298,6 +3298,9 @@
"400": {
"description": "Bad request"
},
+ "404": {
+ "description": "The model could not be found"
+ },
"409": {
"description": "Another operation on this model is already in progress"
},
diff --git a/invokeai/frontend/web/src/services/api/endpoints/models.ts b/invokeai/frontend/web/src/services/api/endpoints/models.ts
index f279d46d82..db563ff6ec 100644
--- a/invokeai/frontend/web/src/services/api/endpoints/models.ts
+++ b/invokeai/frontend/web/src/services/api/endpoints/models.ts
@@ -134,7 +134,7 @@ export const modelsApi = api.injectEndpoints({
updateModel: build.mutation<UpdateModelResponse, UpdateModelArg>({
query: ({ key, body }) => {
return {
- url: buildModelsUrl(`i/${key}`),
+ url: buildModelsUrl(`i/${encodeURIComponent(key)}`),
method: 'PATCH',
body: body,
};
@@ -168,7 +168,7 @@ export const modelsApi = api.injectEndpoints({
const formData = new FormData();
formData.append('image', image);
return {
- url: buildModelsUrl(`i/${key}/image`),
+ url: buildModelsUrl(`i/${encodeURIComponent(key)}/image`),
method: 'PATCH',
body: formData,
};
@@ -189,7 +189,7 @@ export const modelsApi = api.injectEndpoints({
deleteModels: build.mutation<DeleteModelResponse, DeleteModelArg>({
query: ({ key }) => {
return {
- url: buildModelsUrl(`i/${key}`),
+ url: buildModelsUrl(`i/${encodeURIComponent(key)}`),
method: 'DELETE',
};
},
@@ -208,26 +208,26 @@ export const modelsApi = api.injectEndpoints({
deleteModelImage: build.mutation<DeleteModelImageResponse, string>({
query: (key) => {
return {
- url: buildModelsUrl(`i/${key}/image`),
+ url: buildModelsUrl(`i/${encodeURIComponent(key)}/image`),
method: 'DELETE',
};
},
invalidatesTags: [{ type: 'ModelConfig', id: LIST_TAG }],
}),
getModelImage: build.query<string, string>({
- query: (key) => buildModelsUrl(`i/${key}/image`),
+ query: (key) => buildModelsUrl(`i/${encodeURIComponent(key)}/image`),
}),
convertModel: build.mutation<ConvertMainModelResponse, string>({
query: (key) => {
return {
- url: buildModelsUrl(`convert/${key}`),
+ url: buildModelsUrl(`convert/${encodeURIComponent(key)}`),
method: 'PUT',
};
},
invalidatesTags: [{ type: 'ModelConfig', id: LIST_TAG }],
}),
getModelConfig: build.query<GetModelConfigResponse, string>({
- query: (key) => buildModelsUrl(`i/${key}`),
+ query: (key) => buildModelsUrl(`i/${encodeURIComponent(key)}`),
providesTags: (result) => {
const tags: ApiTagDescription[] = [];
@@ -418,7 +418,7 @@ export const modelsApi = api.injectEndpoints({
>({
query: ({ key }) => {
return {
- url: buildModelsUrl(`i/${key}/reidentify`),
+ url: buildModelsUrl(`i/${encodeURIComponent(key)}/reidentify`),
method: 'POST',
};
},
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 657014d10d..4dcd2e2af6 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -44076,6 +44076,13 @@ export interface operations {
};
content?: never;
};
+ /** @description The model could not be found */
+ 404: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
/** @description Another operation on this model is already in progress */
409: {
headers: {
diff --git a/tests/app/routers/test_model_manager.py b/tests/app/routers/test_model_manager.py
index 8fa0c6645d..28836cc61f 100644
--- a/tests/app/routers/test_model_manager.py
+++ b/tests/app/routers/test_model_manager.py
@@ -4,6 +4,7 @@ from typing import Any
import pytest
from fastapi.testclient import TestClient
+from PIL import Image
from invokeai.app.api.dependencies import ApiDependencies
from invokeai.app.api_app import app
@@ -636,3 +637,309 @@ def test_bulk_reidentify_reports_a_busy_key_instead_of_racing_it(conversion_in_f
assert [entry["key"] for entry in response.failed] == ["busy-key"]
assert "already in progress" in response.failed[0]["error"]
reidentify.assert_called_once_with("free-key")
+
+
+def real_model_images(tmp_path: Path):
+ from unittest.mock import MagicMock
+
+ from invokeai.app.services.model_images.model_images_default import ModelImageFileStorageDisk
+
+ storage = ModelImageFileStorageDisk(tmp_path / "model_images")
+ storage.start(MagicMock())
+ return storage
+
+
+def test_delete_model_image_removes_the_image_of_a_deleted_model(real_model_images) -> None:
+ """Deleting a model leaves its cover image behind, and this route is how that orphan is cleaned up - so it must
+ not require the model's record to still exist."""
+ from unittest.mock import MagicMock, patch
+
+ from invokeai.app.api.routers import model_manager
+ from invokeai.app.services.model_records.model_records_base import UnknownModelException
+
+ real_model_images.save(Image.new("RGB", (8, 8)), "deleted-model")
+ image_path = real_model_images.get_path("deleted-model")
+ assert image_path.exists()
+
+ with patch.object(model_manager, "ApiDependencies") as deps:
+ deps.invoker.services.logger = MagicMock()
+ deps.invoker.services.model_images = real_model_images
+ deps.invoker.services.model_manager.store.get_model.side_effect = UnknownModelException("deleted-model")
+
+ model_manager.delete_model_image(MagicMock(), key="deleted-model")
+
+ assert not image_path.exists()
+
+
+# `../escaped` is the case that matters on posix: the backslash and `..` shapes are literal (and missing) filenames
+# there, so they would 404 even with no key validation at all.
[email protected]("key", ["no-such-model", "../escaped", "..\\escaped", ".."])
+def test_delete_model_image_404s_for_a_missing_image_or_an_unsafe_key(real_model_images, key: str) -> None:
+ """A missing image and a key that is not a plain filename are both 404s - not 500s, and never an unlink of a
+ path outside the images folder. A file is planted at the traversal target so a missing guard would show."""
+ from unittest.mock import MagicMock, patch
+
+ from starlette.exceptions import HTTPException
+
+ from invokeai.app.api.routers import model_manager
+
+ images_dir = real_model_images._model_images_folder
+ images_dir.mkdir(parents=True, exist_ok=True)
+ planted = images_dir.parent / "escaped.webp"
+ planted.write_bytes(b"not yours")
+
+ with patch.object(model_manager, "ApiDependencies") as deps:
+ deps.invoker.services.logger = MagicMock()
+ deps.invoker.services.model_images = real_model_images
+
+ with pytest.raises(HTTPException) as exc_info:
+ model_manager.delete_model_image(MagicMock(), key=key)
+
+ assert exc_info.value.status_code == 404
+ assert planted.exists()
+ assert key not in model_manager._CLAIMED_MODEL_KEYS
+
+
[email protected]("key", ["no-such-model", "..\\..\\pwned", ".."])
+async def test_update_model_image_404s_for_a_key_that_names_no_model(key: str) -> None:
+ from unittest.mock import MagicMock, patch
+
+ from starlette.exceptions import HTTPException
+
+ from invokeai.app.api.routers import model_manager
+ from invokeai.app.services.model_records.model_records_base import UnknownModelException
+
+ image = MagicMock()
+ image.content_type = "image/png"
+
+ with patch.object(model_manager, "ApiDependencies") as deps:
+ deps.invoker.services.logger = MagicMock()
+ deps.invoker.services.model_images = MagicMock()
+ deps.invoker.services.model_manager.store.get_model.side_effect = UnknownModelException(key)
+
+ with pytest.raises(HTTPException) as exc_info:
+ await model_manager.update_model_image(key, image, MagicMock())
+
+ assert exc_info.value.status_code == 404
+ deps.invoker.services.model_images.save.assert_not_called()
+ assert key not in model_manager._CLAIMED_MODEL_KEYS
+
+
+async def test_update_model_image_404s_for_a_legacy_unsafe_model_key(real_model_images) -> None:
+ """A persisted legacy record can outlive current key validation, but an upload must still return a client error
+ when the storage layer rejects its key instead of surfacing a 500."""
+ from io import BytesIO
+ from unittest.mock import MagicMock, patch
+
+ from starlette.exceptions import HTTPException
+
+ from invokeai.app.api.routers import model_manager
+
+ key = "../escaped"
+ escaped_image_path = real_model_images._model_images_folder.parent / "escaped.webp"
+ image_bytes = BytesIO()
+ Image.new("RGB", (8, 8)).save(image_bytes, format="PNG")
+ image = MagicMock()
+ image.content_type = "image/png"
+
+ async def read() -> bytes:
+ return image_bytes.getvalue()
+
+ async def run_in_thread(function: Any, *args: Any, **kwargs: Any) -> Any:
+ return function(*args, **kwargs)
+
+ image.read = read
+
+ with (
+ patch.object(model_manager, "ApiDependencies") as deps,
+ patch.object(model_manager.asyncio, "to_thread", run_in_thread),
+ ):
+ deps.invoker.services.logger = MagicMock()
+ deps.invoker.services.model_images = real_model_images
+ # Simulate a model record written before unsafe model keys were rejected.
+ deps.invoker.services.model_manager.store.get_model.return_value = MagicMock()
+
+ with pytest.raises(HTTPException) as exc_info:
+ await model_manager.update_model_image(key, image, MagicMock())
+
+ assert exc_info.value.status_code == 404
+ assert not escaped_image_path.exists()
+ assert key not in model_manager._CLAIMED_MODEL_KEYS
+
+
+async def test_update_model_image_checks_the_record_while_holding_the_claim() -> None:
+ """Deletion and conversion claim the key too, so checking the record under the claim is what stops one of them
+ from removing the model between the check and the save - which would leave an orphan image behind a 200."""
+ from unittest.mock import MagicMock, patch
+
+ from invokeai.app.api.routers import model_manager
+
+ image = MagicMock()
+ image.content_type = "image/png"
+ claimed_during_lookup: list[bool] = []
+
+ def get_model(key: str) -> MagicMock:
+ claimed_during_lookup.append(key in model_manager._CLAIMED_MODEL_KEYS)
+ return MagicMock()
+
+ async def read() -> bytes:
+ return b"irrelevant"
+
+ image.read = read
+
+ with (
+ patch.object(model_manager, "ApiDependencies") as deps,
+ patch.object(model_manager.Image, "open", return_value=MagicMock()),
+ ):
+ deps.invoker.services.logger = MagicMock()
+ deps.invoker.services.model_images = MagicMock()
+ deps.invoker.services.model_manager.store.get_model.side_effect = get_model
+
+ await model_manager.update_model_image("some-model", image, MagicMock())
+
+ assert claimed_during_lookup == [True]
+ deps.invoker.services.model_images.save.assert_called_once()
+
+
+def test_update_model_image_documents_its_404(client: TestClient) -> None:
+ operation = client.get("/openapi.json").json()["paths"]["/api/v2/models/i/{key}/image"]["patch"]
+ assert "404" in operation["responses"]
+
+
+def test_a_case_variant_of_a_claimed_key_is_refused() -> None:
+ """Cover images are `<key>.webp`, which is one file for `K` and `k` on a case-insensitive filesystem - so a
+ claim on one must block the other, or an image delete could race a conversion of the same model."""
+ from starlette.exceptions import HTTPException
+
+ from invokeai.app.api.routers import model_manager
+
+ with model_manager._claim_model_key("abc-model"):
+ with pytest.raises(HTTPException) as exc_info:
+ with model_manager._claim_model_key("ABC-Model"):
+ pass
+ assert exc_info.value.status_code == 409
+
+ assert not model_manager._CLAIMED_MODEL_KEYS
+
+
+def test_a_normalization_variant_of_a_claimed_key_is_refused() -> None:
+ """APFS ignores Unicode normalization, so `é.webp` and `é.webp` are one file there - the claims must
+ conflict just like case variants do."""
+ from starlette.exceptions import HTTPException
+
+ from invokeai.app.api.routers import model_manager
+
+ with model_manager._claim_model_key("café"):
+ with pytest.raises(HTTPException) as exc_info:
+ with model_manager._claim_model_key("CAFÉ"):
+ pass
+ assert exc_info.value.status_code == 409
+
+ assert not model_manager._CLAIMED_MODEL_KEYS
+
+
[email protected]("new_key", ["../../pwned", "..:stream", "a-different-but-valid-key"])
+async def test_update_model_record_refuses_to_change_the_key(new_key: str) -> None:
+ """`update_model` copies every set field into the stored config, so a `key` in the body is written into the
+ blob while the row id keeps the old one. The record then answers to a key nothing can look it up by:
+ `replace_model` (and so reidentify) raises UnknownModelException forever after, and the UI caches the model
+ under the new key so every later request 404s. Note the last case - a *valid* key does this too, so the guard
+ is on the key changing, not on it being unsafe."""
+ from unittest.mock import MagicMock, patch
+
+ from starlette.exceptions import HTTPException
+
+ from invokeai.app.api.routers import model_manager
+ from invokeai.app.services.model_records.model_records_base import ModelRecordChanges
+
+ with patch.object(model_manager, "ApiDependencies") as deps:
+ with pytest.raises(HTTPException) as exc_info:
+ await model_manager.update_model_record(
+ key="real-key", changes=ModelRecordChanges(key=new_key, name="x"), current_admin=MagicMock()
+ )
+
+ assert exc_info.value.status_code == 422
+ deps.invoker.services.model_manager.store.update_model.assert_not_called()
+
+
+async def test_update_model_record_accepts_the_forms_unchanged_key_echo() -> None:
+ """`ModelEdit.tsx` seeds its form from the whole config, so the key rides along on every save. That echo must
+ go through - including for a key that predates key validation, which has no other way to be edited."""
+ from unittest.mock import MagicMock, patch
+
+ from invokeai.app.api.routers import model_manager
+ from invokeai.app.services.model_records.model_records_base import ModelRecordChanges
+
+ for key in ("ecd3b3a5-6c4f-4a5f-9a0e-4b1c2d3e4f50", "legacy:key", "legacy?key"):
+ with patch.object(model_manager, "_update_model_record") as update:
+ await model_manager.update_model_record(
+ key=key, changes=ModelRecordChanges(key=key, name="renamed"), current_admin=MagicMock()
+ )
+ assert update.call_args.args[0] == key
+
+
[email protected](os.name == "nt", reason="Legacy colon keys could only have been stored on POSIX filesystems")
+async def test_a_legacy_posix_key_can_still_replace_and_delete_its_cover(real_model_images) -> None:
+ """No released version checked model keys, so a posix install can hold a model keyed `legacy:key` with a cover
+ already on disk. The image routes must keep managing it rather than 404ing on a Windows-only rule."""
+ from io import BytesIO
+ from unittest.mock import MagicMock, patch
+
+ from invokeai.app.api.routers import model_manager
+
+ key = "legacy:key"
+ image_bytes = BytesIO()
+ Image.new("RGB", (8, 8)).save(image_bytes, format="PNG")
+ image = MagicMock()
+ image.content_type = "image/png"
+
+ async def read() -> bytes:
+ return image_bytes.getvalue()
+
+ image.read = read
+
+ with patch.object(model_manager, "ApiDependencies") as deps:
+ deps.invoker.services.logger = MagicMock()
+ deps.invoker.services.model_images = real_model_images
+ deps.invoker.services.model_manager.store.get_model.return_value = MagicMock()
+
+ await model_manager.update_model_image(key, image, MagicMock())
+ image_path = real_model_images._model_images_folder / f"{key}.webp"
+ assert image_path.exists()
+
+ model_manager.delete_model_image(MagicMock(), key=key)
+ assert not image_path.exists()
+
+
+def test_model_image_url_encodes_the_key() -> None:
+ """Unencoded, a stored key like `X?y` makes the cover URL address the route for model `X` instead."""
+ from invokeai.app.services.urls.urls_default import LocalUrlService
+
+ urls = LocalUrlService()
+ assert urls.get_model_image_url("X?y") == "api/v2/models/i/X%3Fy/image"
+ assert urls.get_model_image_url("a#b%c") == "api/v2/models/i/a%23b%25c/image"
+ assert urls.get_model_image_url("openai-dall-e-3") == "api/v2/models/i/openai-dall-e-3/image"
+
+
+def test_an_encoded_key_reaches_the_image_route_intact(client: TestClient, tmp_path: Path) -> None:
+ """The other half of the encoding: the server decodes `%3F` back into the key, rather than routing on it."""
+ from unittest.mock import patch
+
+ from invokeai.app.api.routers import model_manager
+
+ cover = tmp_path / "cover.webp"
+ Image.new("RGB", (8, 8)).save(cover, format="webp")
+
+ with patch.object(model_manager, "ApiDependencies") as deps:
+ deps.invoker.services.model_images.get_path.return_value = cover
+ response = client.get("/api/v2/models/i/X%3Fy/image")
+
+ assert response.status_code == 200
+ deps.invoker.services.model_images.get_path.assert_called_once_with("X?y")
diff --git a/tests/app/services/model_images/test_model_images_default.py b/tests/app/services/model_images/test_model_images_default.py
new file mode 100644
index 0000000000..4d36304d1d
--- /dev/null
+++ b/tests/app/services/model_images/test_model_images_default.py
@@ -0,0 +1,160 @@
+import os
+from pathlib import Path
+from unittest.mock import MagicMock
+
+import pytest
+from PIL import Image
+
+from invokeai.app.services.model_images.model_images_common import (
+ ModelImageFileDeleteException,
+ ModelImageFileNotFoundException,
+ ModelImageFileSaveException,
+)
+from invokeai.app.services.model_images.model_images_default import ModelImageFileStorageDisk
+from invokeai.app.util import path_safety
+
+# Model keys reach this service from the `/v2/models/i/{key}/image` path parameter and from an install
+# request's `ModelRecordChanges.key`. Note which of these are actually reachable over HTTP: uvicorn
+# percent-decodes before Starlette routes, so `%2F` never matches the `{key}` segment and the forward-slash
+# shapes 404 at routing. The backslash and drive-letter shapes DO reach the handler, which is why the guard
+# must reject them on posix rather than deferring to the platform's `Path`.
+TRAVERSAL_KEYS = [
+ "..",
+ ".",
+ "",
+ "../escaped",
+ "sub/nested",
+ "/etc/passwd",
+ "..\\escaped",
+ "C:\\Windows\\win",
+ "..:stream",
+ "nul\x00byte",
+]
+
+
+# The subset of TRAVERSAL_KEYS that leaves the folder on posix. The rest are ordinary filenames there, and an older
+# version may have stored a cover under one, so the store only refuses them on Windows.
+POSIX_TRAVERSAL_KEYS = ["..", ".", "", "../escaped", "sub/nested", "/etc/passwd", "nul\x00byte"]
+
+
+def windows_rules(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Apply Windows' containment rules whatever the host, so a posix CI run still covers the Windows payloads."""
+ monkeypatch.setattr(path_safety, "_ON_WINDOWS", True)
+
+
+def posix_rules(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(path_safety, "_ON_WINDOWS", False)
+
+
+def storage(tmp_path: Path) -> ModelImageFileStorageDisk:
+ storage = ModelImageFileStorageDisk(tmp_path / "model_images")
+ storage.start(MagicMock())
+ return storage
+
+
[email protected]("key", TRAVERSAL_KEYS)
+def test_get_path_rejects_traversal_keys(storage: ModelImageFileStorageDisk, windows_rules: None, key: str):
+ with pytest.raises(ModelImageFileNotFoundException):
+ storage.get_path(key)
+
+
[email protected]("key", POSIX_TRAVERSAL_KEYS)
+def test_get_path_rejects_posix_traversal_keys(storage: ModelImageFileStorageDisk, posix_rules: None, key: str):
+ with pytest.raises(ModelImageFileNotFoundException):
+ storage.get_path(key)
+
+
+# Skipped on Windows: `get_path` builds a real `WindowsPath`, which splits `a\\b` whatever rules are forced.
[email protected](os.name == "nt", reason="Legacy posix keys could only have been stored on POSIX filesystems")
[email protected]("key", ["legacy:key", "legacy?key", "a\\b", "NUL", "..:stream"])
+def test_get_path_keeps_legacy_posix_keys_inside_the_folder(
+ storage: ModelImageFileStorageDisk, posix_rules: None, key: str
+):
+ """On posix these are ordinary filenames that stay in the folder, and older versions stored covers under them."""
+ assert storage.get_path(key).parent == storage._model_images_folder
+
+
+def test_get_does_not_read_outside_the_images_folder(storage: ModelImageFileStorageDisk, tmp_path: Path):
+ """A traversal key that names a real file outside the folder must not be opened - without a guard, `get()`
+ finds it, `_validate_path` is happy, and it is served."""
+ Image.new("RGB", (8, 8)).save(tmp_path / "outside.webp", format="webp")
+
+ with pytest.raises(ModelImageFileNotFoundException):
+ storage.get("../outside")
+
+
[email protected]("key", TRAVERSAL_KEYS)
+def test_save_rejects_traversal_keys(storage: ModelImageFileStorageDisk, windows_rules: None, key: str):
+ with pytest.raises(ModelImageFileSaveException):
+ storage.save(Image.new("RGB", (8, 8)), key)
+
+
+def test_save_does_not_write_outside_the_images_folder(storage: ModelImageFileStorageDisk, tmp_path: Path):
+ """`save()` used to build its own path instead of going through `get_path()`, so it needs its own coverage."""
+ with pytest.raises(ModelImageFileSaveException):
+ storage.save(Image.new("RGB", (8, 8)), "../planted")
+ assert not (tmp_path / "planted.webp").exists()
+
+
+def test_delete_does_not_unlink_outside_the_images_folder(storage: ModelImageFileStorageDisk, tmp_path: Path):
+ victim = tmp_path / "victim.webp"
+ victim.write_bytes(b"not really a webp")
+
+ with pytest.raises(ModelImageFileDeleteException):
+ storage.delete("../victim")
+ assert victim.exists()
+
+
+def test_get_url_returns_none_for_a_traversal_key(storage: ModelImageFileStorageDisk, tmp_path: Path):
+ """`get_url()` runs for every model in the list response, so a bad key must not fail the whole listing - and
+ it must not advertise a file outside the folder either. The file has to exist for this to be a real test:
+ `get_url()` returns `None` for a missing file regardless."""
+ Image.new("RGB", (8, 8)).save(tmp_path / "outside.webp", format="webp")
+
+ assert storage.get_url("../outside") is None
+
+
+def test_ordinary_keys_still_round_trip(storage: ModelImageFileStorageDisk):
+ """The guard must not reject the key shapes the server actually generates: uuids and external-model slugs."""
+ for key in ("ecd3b3a5-6c4f-4a5f-9a0e-4b1c2d3e4f50", "openai-dall-e-3"):
+ storage.save(Image.new("RGB", (8, 8)), key)
+ assert storage.get_path(key).parent == storage._model_images_folder
+ assert storage.get(key).size == (8, 8)
+ storage.delete(key)
+ with pytest.raises(ModelImageFileNotFoundException):
+ storage.get(key)
+
+
[email protected](os.name == "nt", reason="Legacy colon keys could only have been stored on POSIX filesystems")
+def test_existing_legacy_posix_key_still_serves_its_cover(storage: ModelImageFileStorageDisk):
+ """Keys with Windows-reserved punctuation were valid on POSIX before this guard and may already have cover files."""
+ key = "legacy:key"
+ image_path = storage._model_images_folder / f"{key}.webp"
+ Image.new("RGB", (8, 8)).save(image_path, format="webp")
+ storage._invoker.services.urls.get_model_image_url.return_value = f"/api/v2/models/i/{key}/image"
+
+ url = storage.get_url(key)
+
+ assert url is not None
+ assert url.startswith(f"/api/v2/models/i/{key}/image?")
+
+
[email protected](os.name == "nt", reason="Legacy colon keys could only have been stored on POSIX filesystems")
+def test_existing_legacy_posix_key_cover_can_be_deleted(storage: ModelImageFileStorageDisk):
+ """An existing cover for a previously valid POSIX key must remain manageable after upgrade."""
+ key = "legacy:key"
+ image_path = storage._model_images_folder / f"{key}.webp"
+ Image.new("RGB", (8, 8)).save(image_path, format="webp")
+
+ storage.delete(key)
+
+ assert not image_path.exists()
+
+
+def test_get_url_returns_none_for_an_over_long_key(storage: ModelImageFileStorageDisk):
+ """`exists()` raises ENAMETOOLONG rather than returning False, and `get_url()` runs for every model in the list
+ response - so an over-long stored key must not fail the whole listing."""
+ assert storage.get_url("a" * 300) is None
diff --git a/tests/app/services/model_install/test_model_install.py b/tests/app/services/model_install/test_model_install.py
index 2b9d04647b..34417ff09b 100644
--- a/tests/app/services/model_install/test_model_install.py
+++ b/tests/app/services/model_install/test_model_install.py
@@ -3,6 +3,7 @@ Test the model installer
"""
import gc
+import json
import platform
import shutil
import threading
@@ -37,7 +38,11 @@ from invokeai.app.services.model_install.model_install_common import (
ModelInstallJob,
URLModelSource,
)
-from invokeai.app.services.model_install.model_install_default import TMPDIR_PREFIX
+from invokeai.app.services.model_install.model_install_default import (
+ INSTALL_MARKER_FILENAME,
+ INSTALL_MARKER_VERSION,
+ TMPDIR_PREFIX,
+)
from invokeai.app.services.model_records import ModelRecordChanges, UnknownModelException
from invokeai.backend.model_manager.configs.external_api import ExternalApiModelConfig
from invokeai.backend.model_manager.taxonomy import (
@@ -1078,3 +1083,102 @@ def test_heuristic_import_with_type(mm2_installer: ModelInstallServiceBase, mode
mm2_installer.wait_for_job(install_job2, timeout=10)
assert install_job2.complete
assert install_job2.config_out if model_params["type"] == "embedding" else not install_job2.config_out
+
+
+def test_restore_keeps_a_legacy_marker_whose_key_predates_key_validation(
+ mm2_installer: ModelInstallServiceBase,
+ mm2_app_config: InvokeAIAppConfig,
+ mm2_download_queue,
+ mm2_session,
+) -> None:
+ """A marker written before install keys were checked can carry a key that is not a plain filename. It must
+ still be restored: dropping it strands the partial download forever, because no job is created to clean up
+ the tmpdir and `_remove_dangling_install_dirs` keeps any tmpdir whose marker is readable and non-terminal.
+ Containment does not depend on this - `install_path()` checks the key at the join and errors the job."""
+ assert isinstance(mm2_installer, ModelInstallService)
+
+ tmpdirs: list[Path] = []
+ try:
+ for repo_id, config_in in [
+ ("stabilityai/legacy-key", ModelRecordChanges.model_construct(key="../escaped")),
+ ("stabilityai/ordinary", ModelRecordChanges()),
+ ]:
+ tmpdir = mm2_app_config.models_path / f"tmpinstall_legacy_{uuid.uuid4().hex}"
+ tmpdir.mkdir(parents=True, exist_ok=True)
+ tmpdirs.append(tmpdir)
+ job = ModelInstallJob(
+ id=99999,
+ source=HFModelSource(repo_id=repo_id, variant=ModelRepoVariant.Default),
+ config_in=config_in,
+ local_path=tmpdir,
+ )
+ job._install_tmpdir = tmpdir
+ job.status = InstallStatus.PAUSED
+ mm2_installer._write_install_marker(job, status=InstallStatus.PAUSED)
+
+ restored_installer = ModelInstallService(
+ app_config=mm2_app_config,
+ record_store=mm2_installer.record_store,
+ download_queue=mm2_download_queue,
+ session=mm2_session,
+ )
+ restored_installer._restore_incomplete_installs()
+
+ restored = {str(job.source) for job in restored_installer.list_jobs()}
+ assert restored == {"stabilityai/legacy-key", "stabilityai/ordinary"}
+ finally:
+ for tmpdir in tmpdirs:
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+def test_restore_skips_an_unparseable_marker_without_abandoning_the_rest(
+ mm2_installer: ModelInstallServiceBase,
+ mm2_app_config: InvokeAIAppConfig,
+ mm2_download_queue,
+ mm2_session,
+) -> None:
+ """A marker whose stored config no longer validates must skip that one marker, not raise out of the loop and
+ leave every interrupted install after it unrestored."""
+ assert isinstance(mm2_installer, ModelInstallService)
+
+ tmpdirs: list[Path] = []
+ try:
+ bad_tmpdir = mm2_app_config.models_path / f"tmpinstall_bad_{uuid.uuid4().hex}"
+ bad_tmpdir.mkdir(parents=True, exist_ok=True)
+ tmpdirs.append(bad_tmpdir)
+ (bad_tmpdir / INSTALL_MARKER_FILENAME).write_text(
+ json.dumps(
+ {
+ "version": INSTALL_MARKER_VERSION,
+ "source": "stabilityai/unparseable",
+ "config_in": {"base": "not-a-real-base"},
+ "status": InstallStatus.PAUSED.value,
+ }
+ )
+ )
+
+ good_tmpdir = mm2_app_config.models_path / f"tmpinstall_good_{uuid.uuid4().hex}"
+ good_tmpdir.mkdir(parents=True, exist_ok=True)
+ tmpdirs.append(good_tmpdir)
+ job = ModelInstallJob(
+ id=99998,
+ source=HFModelSource(repo_id="stabilityai/ordinary", variant=ModelRepoVariant.Default),
+ config_in=ModelRecordChanges(),
+ local_path=good_tmpdir,
+ )
+ job._install_tmpdir = good_tmpdir
+ job.status = InstallStatus.PAUSED
+ mm2_installer._write_install_marker(job, status=InstallStatus.PAUSED)
+
+ restored_installer = ModelInstallService(
+ app_config=mm2_app_config,
+ record_store=mm2_installer.record_store,
+ download_queue=mm2_download_queue,
+ session=mm2_session,
+ )
+ restored_installer._restore_incomplete_installs()
+
+ assert [str(job.source) for job in restored_installer.list_jobs()] == ["stabilityai/ordinary"]
+ finally:
+ for tmpdir in tmpdirs:
+ shutil.rmtree(tmpdir, ignore_errors=True)
diff --git a/tests/app/services/model_install/test_model_key_path_safety.py b/tests/app/services/model_install/test_model_key_path_safety.py
new file mode 100644
index 0000000000..f92245d94b
--- /dev/null
+++ b/tests/app/services/model_install/test_model_key_path_safety.py
@@ -0,0 +1,138 @@
+"""An install request may name the key it wants, and that key is joined onto the filesystem.
+
+`POST /v2/models/install` takes it in the body; the joins it feeds are the model's own directory under
+`models_path` and its cover image under `model_images`. The check lives on the install route rather than on
+`ModelRecordChanges` itself, because that model is also the *update* body and is re-parsed from install markers
+written by older versions - see the comment on `ModelRecordChanges.key`.
+"""
+
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from invokeai.app.services.model_records.model_records_base import ModelRecordChanges
+from invokeai.backend.model_manager.util.lora_metadata_extractor import _process_preview_image
+
+TRAVERSAL_KEYS = [
+ "../../pwned",
+ "..",
+ "sub/nested",
+ "/etc/pwned",
+ "..\\pwned",
+ "C:\\pwned",
+ "..:stream",
+ "nul\x00byte",
+]
+
+
[email protected]("key", TRAVERSAL_KEYS)
+def test_install_route_rejects_traversal_keys(key: str):
+ """`install_model` is where a client-chosen key is adopted, so that is where it is checked."""
+ from unittest.mock import MagicMock, patch
+
+ from starlette.exceptions import HTTPException
+
+ from invokeai.app.api.routers import model_manager
+
+ with patch.object(model_manager, "ApiDependencies") as deps:
+ deps.invoker.services.logger = MagicMock()
+
+ with pytest.raises(HTTPException) as exc_info:
+ model_manager.install_model(MagicMock(), source="/models/x.safetensors", config=ModelRecordChanges(key=key))
+
+ assert exc_info.value.status_code == 422
+ deps.invoker.services.model_manager.install.heuristic_import.assert_not_called()
+
+
[email protected]("key", ["ecd3b3a5-6c4f-4a5f-9a0e-4b1c2d3e4f50", "openai-dall-e-3", "external_test"])
+def test_install_route_accepts_generated_keys(key: str):
+ """uuids and `slugify()`ed external-model keys are what the server generates, and the route must pass them
+ through to the installer rather than merely not raising."""
+ from unittest.mock import MagicMock, patch
+
+ from invokeai.app.api.routers import model_manager
+
+ with patch.object(model_manager, "ApiDependencies") as deps:
+ deps.invoker.services.logger = MagicMock()
+ installer = deps.invoker.services.model_manager.install
+
+ model_manager.install_model(MagicMock(), source="/models/x.safetensors", config=ModelRecordChanges(key=key))
+
+ assert installer.heuristic_import.call_count == 1
+ assert installer.heuristic_import.call_args.kwargs["config"].key == key
+
+
[email protected]("key", TRAVERSAL_KEYS + ["legacy:key", "legacy?key", "legacy*key"])
+def test_model_record_changes_still_parses_a_legacy_key(key: str):
+ """`ModelRecordChanges` must NOT validate the key. It is the update body too, and the edit form posts the whole
+ record back unchanged (there is no key field in the form - `ModelEdit.tsx` seeds its defaults from the config,
+ so the key rides along as an echo), so validating here would answer 422 on every attempt to edit a model whose
+ key predates key validation. It is also re-parsed from install markers written by older versions, where a
+ rejection strands the partial download. Changing a key is refused by the route, not by this model."""
+ assert ModelRecordChanges(key=key).key == key
+
+
+def test_model_record_changes_without_a_key_is_unaffected():
+ assert ModelRecordChanges(name="some model").key is None
+
+
+def test_lora_preview_image_is_not_written_outside_the_images_folder(tmp_path: Path):
+ """`_process_preview_image` builds its path by hand rather than going through `ModelImageFileStorageDisk`, so
+ it needs its own guard: with none, a key of `../../pwned` lands the thumbnail two levels up."""
+ model_dir = tmp_path / "models"
+ model_dir.mkdir()
+ model_images = tmp_path / "root" / "model_images"
+ model_images.mkdir(parents=True)
+ Image.new("RGB", (32, 32)).save(model_dir / "mylora.png")
+
+ assert _process_preview_image("mylora", model_dir, "../../pwned", model_images) is False
+ assert not (tmp_path / "pwned.webp").exists()
+ assert list(model_images.iterdir()) == []
+
+
+def test_lora_preview_image_is_still_written_for_an_ordinary_key(tmp_path: Path):
+ model_dir = tmp_path / "models"
+ model_dir.mkdir()
+ model_images = tmp_path / "model_images"
+ model_images.mkdir()
+ Image.new("RGB", (32, 32)).save(model_dir / "mylora.png")
+
+ assert _process_preview_image("mylora", model_dir, "abc-123", model_images) is True
+ assert (model_images / "abc-123.webp").exists()
+
+
+def test_install_refuses_an_unvalidated_traversal_key(mm2_installer, embedding_file: Path):
+ """A caller can build `ModelRecordChanges` without going through the route, so `_probe()` - the one place a
+ caller-supplied key becomes a record's key, for in-place registration as well as for a move-in install -
+ refuses it before anything is created or moved."""
+ from invokeai.app.services.model_install.model_install_common import InvalidModelConfigException
+
+ models_path = mm2_installer.app_config.models_path
+ escaped = models_path.parent / "escaped"
+ config = ModelRecordChanges.model_construct(key="../escaped")
+
+ with pytest.raises(InvalidModelConfigException, match="plain filename"):
+ mm2_installer.install_path(embedding_file, config=config)
+
+ assert not escaped.exists()
+ assert embedding_file.exists()
+ assert mm2_installer.record_store.search_by_attr() == []
+
+
+def test_install_path_guards_the_join_even_if_the_key_got_past_probe(mm2_installer, embedding_file: Path):
+ """`install_path()` moves the model into `models_path / key`, so the join is guarded at the sink as well -
+ independently of `_probe()`. Bypass the probe check to prove the sink one is load-bearing on its own."""
+ from unittest.mock import patch
+
+ models_path = mm2_installer.app_config.models_path
+ escaped = models_path.parent / "escaped"
+ probed = mm2_installer._probe(embedding_file, ModelRecordChanges())
+ probed.key = "../escaped"
+
+ with patch.object(mm2_installer, "_probe", return_value=probed):
+ with pytest.raises(ValueError, match="plain filename"):
+ mm2_installer.install_path(embedding_file, config=ModelRecordChanges())
+
+ assert not escaped.exists()
+ assert embedding_file.exists()
diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_24_key_containment.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_24_key_containment.py
new file mode 100644
index 0000000000..b2443072da
--- /dev/null
+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_24_key_containment.py
@@ -0,0 +1,52 @@
+"""migration_24 moves each Invoke-managed model into `models_dir/<key>`, taking the key from the stored config blob.
+Older versions did not check that key, so the move is guarded: a key that would leave `models_dir` on this platform
+leaves the model where it is, and a key that is merely illegal on Windows is an ordinary directory name on posix."""
+
+import logging
+import os
+from pathlib import Path
+from unittest.mock import MagicMock
+
+import pytest
+
+from invokeai.app.services.shared.sqlite_migrator.migrations.migration_24 import Migration24Callback
+from invokeai.app.util import path_safety
+
+
+def models_dir(tmp_path: Path) -> Path:
+ models = tmp_path / "models"
+ (models / "sd-1").mkdir(parents=True)
+ (models / "sd-1" / "model.safetensors").write_bytes(b"weights")
+ return models
+
+
+def _callback(models_dir: Path) -> Migration24Callback:
+ app_config = MagicMock()
+ app_config.models_path = models_dir
+ return Migration24Callback(app_config=app_config, logger=logging.getLogger("test_migration_24"))
+
+
+def test_a_key_that_escapes_leaves_the_model_in_place(models_dir: Path):
+ result = _callback(models_dir)._normalize_model_storage("../escaped", "sd-1/model.safetensors")
+
+ assert result.new_relative_path is None
+ assert (models_dir / "sd-1" / "model.safetensors").exists()
+ assert not (models_dir.parent / "escaped").exists()
+
+
+def test_a_windows_only_key_is_left_in_place_under_windows_rules(models_dir: Path, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(path_safety, "_ON_WINDOWS", True)
+
+ result = _callback(models_dir)._normalize_model_storage("..:stream", "sd-1/model.safetensors")
+
+ assert result.new_relative_path is None
+ assert (models_dir / "sd-1" / "model.safetensors").exists()
+
+
[email protected](os.name == "nt", reason="Legacy colon keys could only have been stored on POSIX filesystems")
+def test_a_legacy_posix_key_is_normalized_like_any_other(models_dir: Path):
+ result = _callback(models_dir)._normalize_model_storage("legacy:key", "sd-1/model.safetensors")
+
+ assert result.new_relative_path == "legacy:key/model.safetensors"
+ assert (models_dir / "legacy:key" / "model.safetensors").exists()
diff --git a/tests/app/util/test_path_safety.py b/tests/app/util/test_path_safety.py
new file mode 100644
index 0000000000..ad43572a38
--- /dev/null
+++ b/tests/app/util/test_path_safety.py
@@ -0,0 +1,184 @@
+import pytest
+
+from invokeai.app.util import path_safety
+from invokeai.app.util.misc import uuid_string
+from invokeai.app.util.path_safety import is_contained_filename, is_plain_filename
+
+# Every one of these, joined onto a storage directory, resolves outside it - or, for the empty/dot cases,
+# resolves to the directory itself rather than a file in it. The backslash and drive-letter shapes only escape on
+# Windows, but they must be rejected on posix too: otherwise a posix-only test run reports all clear on a payload
+# that works against Windows deployments.
+UNSAFE_NAMES = [
+ "..",
+ ".",
+ "",
+ "../escaped",
+ "../../../../etc/passwd",
+ "/etc/passwd",
+ "//srv/share/file",
+ "sub/nested",
+ "foo/../../bar",
+ "trailing/",
+ "..\\escaped",
+ "sub\\nested",
+ "C:\\Windows\\win.ini",
+ "C:relative",
+ "\\\\?\\C:\\Windows\\win.ini",
+ # NTFS alternate data streams reaching the PARENT: `<name>:<stream>` names a stream on `<name>`, so a `..`
+ # before the colon addresses the store's parent directory. `PureWindowsPath` only reads a single *letter*
+ # followed by a colon as a drive, so it hands these back as one bare component and cannot catch them.
+ "..:stream",
+ "..:stream.webp",
+ "..:$DATA",
+ "..::$INDEX_ALLOCATION",
+ "..:",
+ "nul\x00byte",
+]
+
+SAFE_NAMES = [
+ "Tensor_ecd3b3a5-6c4f-4a5f-9a0e-4b1c2d3e4f50",
+ "ConditioningFieldData_ecd3b3a5-6c4f-4a5f-9a0e-4b1c2d3e4f50",
+ "openai-dall-e-3",
+ "image.png",
+ "..leading.dots",
+ "trailing.dots..",
+ "~tilde",
+ "spaces are fine",
+]
+
+
[email protected]("name", UNSAFE_NAMES)
+def test_is_plain_filename_rejects_traversal(name: str):
+ assert is_plain_filename(name) is False
+
+
[email protected]("name", SAFE_NAMES)
+def test_is_plain_filename_accepts_plain_names(name: str):
+ assert is_plain_filename(name) is True
+
+
+def test_is_plain_filename_accepts_generated_names():
+ """The predicate must never reject a name the server itself hands out."""
+ assert is_plain_filename(uuid_string()) is True
+ assert is_plain_filename(f"Tensor_{uuid_string()}") is True
+
+
[email protected]("name", [".. ", ".. ", "...", ".. .", " ", ". "])
+def test_is_plain_filename_rejects_windows_normalised_dot_names(name: str):
+ """`pathlib` keeps trailing dots and spaces, but the Win32 normaliser strips them from the final component at
+ open time - so on Windows `dir / ".. "` is the parent directory."""
+ assert is_plain_filename(name) is False
+
+
+ "name",
+ ["a\rb", "a\nb", "a\tb", "a\x00b", "a\x7fb", "a\x1bb", "a\x85b", "a\u2028b", "a\u2029b", "a\x80b", "a\x9fb"],
+)
+def test_is_plain_filename_rejects_control_characters(name: str):
+ """`str.splitlines()` splits on U+0085, U+2028 and U+2029 as well as the C0 set, and routes interpolate these
+ names into log records raw, so a name carrying one forges a second log line."""
+ assert is_plain_filename(name) is False
+
+
[email protected]("name", ["foo:bar", "foo::$DATA", ":stream", "...:s"])
+def test_is_plain_filename_rejects_contained_alternate_data_streams(name: str):
+ """These name a stream on a file inside the store, or on the store directory itself, rather than escaping it.
+ They are rejected because a stream is not the file the caller asked for - not because they traverse."""
+ assert is_plain_filename(name) is False
+
+
[email protected]("name", ["foo<bar", "foo>bar", 'foo"bar', "foo|bar", "foo?bar", "foo*bar"])
+def test_is_plain_filename_rejects_characters_windows_forbids(name: str):
+ """These cannot escape a directory on their own, but a name that is not a valid filename on every platform we
+ support is not one we should be joining onto a directory."""
+ assert is_plain_filename(name) is False
+
+
+ "name",
+ [
+ "NUL",
+ "nul",
+ "CON",
+ "PRN",
+ "AUX",
+ "COM1",
+ "LPT9",
+ "NUL.webp",
+ "CON.txt",
+ "NUL.",
+ "NUL ",
+ "CONIN$",
+ # Win32 trims trailing spaces from the base name before the device lookup, so the space between the stem
+ # and the extension does not save these.
+ "NUL .webp",
+ "CON .txt",
+ # `COM`/`LPT` are reserved with the superscript digits and with 0, not just ASCII 1-9.
+ "COM¹",
+ "COM²",
+ "COM³",
+ "LPT¹",
+ "COM0",
+ "LPT0",
+ # Legacy DOS devices, still reserved on some builds.
+ "CLOCK$",
+ "CONFIG$",
+ "KEYBD$",
+ "SCREEN$",
+ ],
+)
+def test_is_plain_filename_rejects_windows_device_names(name: str):
+ """Win32 resolves these to the device namespace from any directory, so the join does not address a file in the
+ store at all - a write to `<store>/NUL.webp` is silently discarded and `.exists()` still reports True."""
+ assert is_plain_filename(name) is False
+
+
[email protected]("name", ["console", "context", "nullish", "comic", "con-model", "NULL", "com10", "aux-enc"])
+def test_is_plain_filename_keeps_names_that_merely_start_like_a_device(name: str):
+ """The device rule matches the whole stem, so it must not swallow ordinary names with the same prefix."""
+ assert is_plain_filename(name) is True
+
+
[email protected]("name", ["foo..", "foo.", "a.b.c", "..leading"])
+def test_is_plain_filename_keeps_names_that_only_look_like_dot_names(name: str):
+ """The trailing-dot rule must not swallow ordinary names that happen to end in a dot."""
+ assert is_plain_filename(name) is True
+
+
+# Legal posix filenames that `is_plain_filename` refuses. Older versions stored model keys unchecked, so data can
+# already exist under these names on a posix install.
+LEGACY_POSIX_NAMES = [
+ "legacy:key",
+ "legacy?key",
+ "legacy*key",
+ 'a"b',
+ "a|b",
+ "<a>",
+ "a\\b",
+ "NUL",
+ "COM1",
+ "...",
+ "... ",
+ "..:stream",
+ "C:relative",
+]
+POSIX_ESCAPING_NAMES = ["", ".", "..", "../escaped", "/etc/passwd", "sub/nested", "trailing/", "nul\x00byte", "a\nb"]
+
+
[email protected]("name", LEGACY_POSIX_NAMES)
+def test_is_contained_filename_keeps_legacy_posix_names_on_posix(monkeypatch: pytest.MonkeyPatch, name: str):
+ monkeypatch.setattr(path_safety, "_ON_WINDOWS", False)
+ assert not is_plain_filename(name)
+ assert is_contained_filename(name)
+
+
[email protected]("name", POSIX_ESCAPING_NAMES)
+def test_is_contained_filename_rejects_posix_escapes_on_posix(monkeypatch: pytest.MonkeyPatch, name: str):
+ monkeypatch.setattr(path_safety, "_ON_WINDOWS", False)
+ assert not is_contained_filename(name)
+
+
[email protected]("name", UNSAFE_NAMES + LEGACY_POSIX_NAMES + SAFE_NAMES)
+def test_is_contained_filename_is_is_plain_filename_on_windows(monkeypatch: pytest.MonkeyPatch, name: str):
+ monkeypatch.setattr(path_safety, "_ON_WINDOWS", True)
+ assert is_contained_filename(name) == is_plain_filename(name)
diff --git a/tests/test_object_serializer_disk.py b/tests/test_object_serializer_disk.py
index 77e9e2d9f9..6d3f7cb3a0 100644
--- a/tests/test_object_serializer_disk.py
+++ b/tests/test_object_serializer_disk.py
@@ -7,7 +7,10 @@ from threading import Barrier
import pytest
import torch
-from invokeai.app.services.object_serializer.object_serializer_common import ObjectNotFoundError
+from invokeai.app.services.object_serializer.object_serializer_common import (
+ InvalidObjectNameError,
+ ObjectNotFoundError,
+)
from invokeai.app.services.object_serializer.object_serializer_disk import ObjectSerializerDisk
from invokeai.app.services.object_serializer.object_serializer_forward_cache import ObjectSerializerForwardCache
@@ -304,3 +307,80 @@ def test_obj_serializer_fwd_cache_concurrent_cache_misses_are_not_serialized(
loaded = [future.result(timeout=10) for future in futures]
assert {obj.foo for obj in loaded} == {f"obj-{i}" for i in range(len(names))}
+
+
+ "name",
+ [
+ "../escaped",
+ "../../../../etc/passwd",
+ "sub/nested",
+ "/etc/passwd",
+ "..",
+ ".",
+ "",
+ "foo/../../bar",
+ # Windows-shaped payloads must be rejected on posix too, so a posix-only CI run still covers them.
+ "..\\escaped",
+ "sub\\nested",
+ "C:\\Windows\\win.ini",
+ "C:relative",
+ "nul\x00byte",
+ ],
+)
+def test_obj_serializer_disk_rejects_traversal_names(obj_serializer: ObjectSerializerDisk[MockDataclass], name: str):
+ """Object names arrive from the client inside node fields (e.g. `TensorField.tensor_name`), so a name that is
+ not a plain filename must never be joined onto the output directory."""
+ with pytest.raises(InvalidObjectNameError):
+ obj_serializer.load(name)
+ with pytest.raises(InvalidObjectNameError):
+ obj_serializer.delete(name)
+ with pytest.raises(InvalidObjectNameError):
+ obj_serializer._get_path(name)
+
+
+def test_obj_serializer_disk_traversal_name_does_not_read_outside_dir(tmp_path: Path):
+ """The end-to-end shape of the reported issue: a file outside the store, named by a `..` traversal, must not
+ be deserialized."""
+ store = tmp_path / "store"
+ store.mkdir()
+ secret = tmp_path / "secret.pt"
+ torch.save(torch.ones((2, 2), dtype=torch.bool), secret)
+
+ obj_serializer = ObjectSerializerDisk[torch.Tensor](store, safe_globals=[torch.Tensor])
+ with pytest.raises(InvalidObjectNameError):
+ obj_serializer.load(f"../{secret.name}")
+
+
+def test_obj_serializer_disk_accepts_generated_names(obj_serializer: ObjectSerializerDisk[MockDataclass]):
+ """The guard must not reject the names the serializer itself hands out."""
+ name = obj_serializer.save(MockDataclass(foo="bar"))
+ assert obj_serializer._get_path(name).parent == obj_serializer._output_dir
+ assert obj_serializer.load(name).foo == "bar"
+
+
+def test_obj_serializer_fwd_cache_rejects_traversal_names(fwd_cache: ObjectSerializerForwardCache[MockDataclass]):
+ """The forward cache must not launder a traversal name past the disk serializer's guard."""
+ with pytest.raises(InvalidObjectNameError):
+ fwd_cache.load("../escaped")
+ with pytest.raises(InvalidObjectNameError):
+ fwd_cache.delete("../escaped")
+
+
+class UnregisteredClass:
+ """Deliberately never passed to `add_safe_globals`."""
+
+ def __init__(self) -> None:
+ self.foo = "bar"
+
+
+def test_obj_serializer_disk_does_not_unpickle_arbitrary_objects(tmp_path: Path):
+ """Object names are untrusted, so even a name that stays inside the store must not reach a full unpickle: a
+ file planted in the store (or swapped for one) must not be able to instantiate arbitrary classes."""
+ obj_serializer = ObjectSerializerDisk[MockDataclass](tmp_path, safe_globals=[MockDataclass])
+ name = "planted"
+ torch.save(UnregisteredClass(), tmp_path / name)
+
+ with pytest.raises(Exception) as exc_info:
+ obj_serializer.load(name)
+ assert "UnregisteredClass" in str(exc_info.value) or "weights_only" in str(exc_info.value)