Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
Merge commit from fork
Lincoln Stein3b4451a1ac44
diff --git a/docs/src/content/docs/configuration/Multi-User Mode/admin-guide.mdx b/docs/src/content/docs/configuration/Multi-User Mode/admin-guide.mdxindex b74da7f988..26da465b08 100644--- a/docs/src/content/docs/configuration/Multi-User Mode/admin-guide.mdx+++ b/docs/src/content/docs/configuration/Multi-User Mode/admin-guide.mdx@@ -319,6 +319,36 @@ cannot be checked by InvokeAI. Do not enable `allow_private_download_urls` merelmake an untrusted proxy work. The two settings are independent: `download_proxy` ishonored whether or not `allow_private_download_urls` is enabled.+### Node Filesystem Access++Workflow nodes that read or write files are confined to directories you+designate, and the confinement holds in both single-user and multi-user mode.++The **Prompts from File** node reads prompt lists from the prompt files+directory — `prompt_files_dir`, by default `<root>/prompt_files`. Its+`file_path` input is interpreted relative to that directory, and absolute+paths, `..` traversal and symlinks pointing out of the directory are refused.+Place a prompt list at `<root>/prompt_files/lists/fantasy.txt` and the node+addresses it as `lists/fantasy.txt`.++In multi-user mode the node is additionally **restricted to administrators**,+because the prompt files directory is shared by every account: a non-admin+reading from it would be reading prompt lists belonging to other users.+Unprivileged users should use wildcards instead, which are stored per account+and can be imported from the prompt panel.++If you do not want the node available at all, deny it in `invokeai.yaml`:++```yaml+deny_nodes:+ - prompt_from_file+```++The **Save Image (Gallery + File Export)** node is confined to the outputs+directory on the same terms. Its filename prefix and suffix cannot contain+path separators or `..`, so they cannot steer the exported file out of the+chosen directory.+:::note[Strict Password Checking]It is recommended that you enable strict password checking. This willforce all users to select good passwords that follow thediff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.jsonindex ef0184b18d..8dd062a020 100644--- a/docs/src/generated/settings.json+++ b/docs/src/generated/settings.json@@ -331,6 +331,17 @@"type": "<class 'pathlib.Path'>","validation": {}},+ {+ "category": "PATHS",+ "default": "prompt_files",+ "description": "Path to the directory holding prompt list files readable by the Prompts from File node. The node cannot read outside this directory.",+ "env_var": "INVOKEAI_PROMPT_FILES_DIR",+ "literal_values": [],+ "name": "prompt_files_dir",+ "required": false,+ "type": "<class 'pathlib.Path'>",+ "validation": {}+ },{"category": "PATHS","default": "workflow_thumbnails",diff --git a/invokeai/app/invocations/image.py b/invokeai/app/invocations/image.pyindex df6fc9748c..ee73424df7 100644--- a/invokeai/app/invocations/image.py+++ b/invokeai/app/invocations/image.py@@ -25,6 +25,7 @@ from invokeai.app.invocations.primitives import ImageOutput, StringOutputfrom invokeai.app.services.image_records.image_records_common import ImageCategoryfrom invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.app.util.misc import SEED_MAX+from invokeai.app.util.path_safety import is_plain_filename, resolve_contained_pathfrom invokeai.backend.image_util.color_conversion import (linear_srgb_from_oklab,linear_srgb_from_oklch,@@ -1162,36 +1163,36 @@ class SaveImageToFileInvocation(BaseInvocation, WithMetadata, WithBoard):)def invoke(self, context: InvocationContext) -> ImageOutput:- image = context.images.get_pil(self.image.image_name)-- image_dto = context.images.save(image=image)-- uuid = Path(image_dto.image_name).stem-+ # Validate every path input before the gallery save, so a rejected path leaves no orphan image behind.outputs_path = context.config.get().outputs_pathassert outputs_path is not Noneif not self.output_directory:target_dir = outputs_pathelse:- raw_str = self.output_directory- raw = Path(raw_str)- has_windows_drive = len(raw_str) >= 2 and raw_str[0].isalpha() and raw_str[1] == ":"- starts_with_sep = raw_str.startswith("/") or raw_str.startswith("\\")- if raw.is_absolute() or raw.drive or has_windows_drive or starts_with_sep:- raise ValueError(- f"Absolute paths are not allowed in output_directory: {raw_str!r}. "- "Use a path relative to the InvokeAI outputs folder."- )- candidate = (outputs_path / raw).resolve()- outputs_resolved = outputs_path.resolve()- if outputs_resolved != candidate and outputs_resolved not in candidate.parents:- raise ValueError(f"output_directory must stay within the outputs folder: {raw_str!r}")- target_dir = candidate+ try:+ target_dir = resolve_contained_path(outputs_path, self.output_directory)+ except ValueError as e:+ raise ValueError(f"Invalid output_directory {self.output_directory!r}: {e}") from e++ # The real stem is the gallery uuid (hex and dashes), so a uuid-shaped placeholder checks the affixes+ # exactly: a separator, drive or `..` in prefix/suffix would otherwise steer the write out of target_dir.+ if not is_plain_filename(f"{self.prefix}00000000-0000-0000-0000-000000000000{self.suffix}.{self.file_format}"):+ raise ValueError(+ f"Invalid prefix {self.prefix!r} or suffix {self.suffix!r}: the exported filename must be a plain "+ "filename without path separators, '..', drive letters or reserved characters."+ )+ # Before the gallery save too: a refusal here (output_directory names an existing file) leaves nothing behind.target_dir.mkdir(parents=True, exist_ok=True)+ image = context.images.get_pil(self.image.image_name)++ image_dto = context.images.save(image=image)++ uuid = Path(image_dto.image_name).stemfilename = f"{self.prefix}{uuid}{self.suffix}.{self.file_format}"+target_path = target_dir / filenameif self.file_format == "png":diff --git a/invokeai/app/invocations/prompt.py b/invokeai/app/invocations/prompt.pyindex f216e91c05..8bc2d04d4d 100644--- a/invokeai/app/invocations/prompt.py+++ b/invokeai/app/invocations/prompt.py@@ -1,14 +1,19 @@-from os.path import exists-from typing import Optional, Union+from pathlib import Path+from typing import TYPE_CHECKING, Optional, Unionimport numpy as np-from pydantic import field_validator-from invokeai.app.invocations.baseinvocation import BaseInvocation, invocation+from invokeai.app.invocations.baseinvocation import BaseInvocation, BaseInvocationOutput, invocationfrom invokeai.app.invocations.fields import InputField, UIComponentfrom invokeai.app.invocations.primitives import StringCollectionOutputfrom invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.app.util.dynamicprompts import expand_dynamic_prompt+from invokeai.app.util.path_safety import resolve_contained_path++if TYPE_CHECKING:+ from invokeai.app.services.invocation_services import InvocationServices++_PROMPT_FILES_DIR_HINT = "the prompt files directory (`prompt_files_dir`, default `<root>/prompt_files`)"@invocation(@@ -51,12 +56,26 @@ class DynamicPromptInvocation(BaseInvocation):title="Prompts from File",tags=["prompt", "file"],category="prompt",- version="1.0.2",+ # 2.0.0: `file_path` is now relative to the configured prompt files directory and cannot+ # address anything outside it. Absolute paths, which earlier versions accepted, are refused.+ # Major, so the editor does not carry an old `file_path` over as if it were still valid.+ version="2.0.0",+ use_cache=False,)class PromptsFromFileInvocation(BaseInvocation):- """Loads prompts from a text file"""+ """Loads prompts from a text file.- file_path: str = InputField(description="Path to prompt text file")+ The file is read from the InvokeAI prompt files directory (`prompt_files_dir`, by default+ `<root>/prompt_files`). `file_path` is relative to that directory - absolute paths and path+ traversal are rejected - so the node can only read prompt lists an operator has deliberately+ placed there.++ In multi-user mode the node is restricted to administrators: the directory is shared by every+ account, so letting one account read from it would hand it another account's prompt lists.+ Non-admin users should use wildcards, which are stored per account.+ """++ file_path: str = InputField(description="Path to prompt text file, relative to the InvokeAI prompt files directory")pre_prompt: Optional[str] = InputField(default=None,description="String to prepend to each prompt",@@ -70,15 +89,48 @@ class PromptsFromFileInvocation(BaseInvocation):start_line: int = InputField(default=1, ge=1, description="Line in the file to start start from")max_prompts: int = InputField(default=1, ge=0, description="Max lines to read from file (0=all)")- @field_validator("file_path")- def file_path_exists(cls, v):- if not exists(v):- raise ValueError(FileNotFoundError)- return v+ def _resolve_file_path(self, context: InvocationContext) -> Path:+ """Resolves `file_path` inside the prompt files directory, after checking the caller may read it.++ Deliberately *not* a pydantic validator. A validator runs while the enqueue request body is+ being parsed, which means every failure - including "that file does not exist" - is answered+ as a 422 before anything is queued, turning the node into a filesystem probe that leaves no+ queue item behind. Resolving here instead makes a bad path fail as an error on the caller's+ own queue item, the same as any other invocation failure.+ """+ config = context._services.configuration++ if config.multiuser:+ # The prompt files directory is shared by every account, so reading from it is an admin+ # capability. `call_saved_workflow` gates on the queueing user the same way.+ queue_user_id = context._data.queue_item.user_id+ user = context._services.users.get(queue_user_id)+ if not (user and user.is_admin):+ raise ValueError(+ "The 'Prompts from File' node is restricted to administrators in multi-user mode. "+ "Use wildcards instead - they are stored per account."+ )++ # Errors name the setting, not the resolved path: the absolute path is server-side detail, and+ # echoing it back would describe the host's layout to whoever enqueued the graph.+ try:+ resolved = resolve_contained_path(config.prompt_files_path, self.file_path)+ except ValueError as e:+ raise ValueError(+ f"Invalid prompt file path: {e} 'file_path' must be relative to {_PROMPT_FILES_DIR_HINT}."+ ) from e++ if not resolved.is_file():+ raise ValueError(+ f"No prompt file '{self.file_path}' in {_PROMPT_FILES_DIR_HINT}. "+ "Place prompt list files there to use them with this node."+ )++ return resolveddef promptsFromFile(self,- file_path: str,+ file_path: Union[str, Path],pre_prompt: Union[str, None],post_prompt: Union[str, None],start_line: int,@@ -97,9 +149,15 @@ class PromptsFromFileInvocation(BaseInvocation):breakreturn prompts+ def invoke_internal(self, context: InvocationContext, services: "InvocationServices") -> BaseInvocationOutput:+ # Never use the invocation cache: the admin gate lives in invoke() and cache keys carry no user+ # identity, so a hit would hand an admin's read to anyone (and the file can change under the key).+ self._validate_invoke_fields()+ return self.invoke(context)+def invoke(self, context: InvocationContext) -> StringCollectionOutput:prompts = self.promptsFromFile(- self.file_path,+ self._resolve_file_path(context),self.pre_prompt,self.post_prompt,self.start_line,diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.pyindex 99ea642ee7..fb3ae0d291 100644--- a/invokeai/app/services/config/config_default.py+++ b/invokeai/app/services/config/config_default.py@@ -100,6 +100,7 @@ class InvokeAIAppConfig(BaseSettings):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`custom_nodes_dir: Path to directory for custom nodes.style_presets_dir: Path to directory for style presets.+ prompt_files_dir: Path to the directory holding prompt list files readable by the Prompts from File node. The node cannot read outside this directory.workflow_thumbnails_dir: Path to directory for workflow thumbnails.log_handlers: Log handler. Valid options are "console", "file=<path>", "syslog=path|address:host:port", "http=<url>".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`@@ -221,6 +222,7 @@ class InvokeAIAppConfig(BaseSettings):image_subfolder_strategy: IMAGE_SUBFOLDER_STRATEGY = Field(default="flat", description="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.")custom_nodes_dir: Path = Field(default=Path("nodes"), description="Path to directory for custom nodes.")style_presets_dir: Path = Field(default=Path("style_presets"), description="Path to directory for style presets.")+ prompt_files_dir: Path = Field(default=Path("prompt_files"), description="Path to the directory holding prompt list files readable by the Prompts from File node. The node cannot read outside this directory.")workflow_thumbnails_dir: Path = Field(default=Path("workflow_thumbnails"), description="Path to directory for workflow thumbnails.")# LOGGING@@ -511,6 +513,11 @@ class InvokeAIAppConfig(BaseSettings):"""Path to the style presets directory, resolved to an absolute path.."""return self._resolve(self.style_presets_dir)+ @property+ def prompt_files_path(self) -> Path:+ """Path to the prompt list files directory, resolved to an absolute path."""+ return self._resolve(self.prompt_files_dir)+@propertydef workflow_thumbnails_path(self) -> Path:"""Path to the workflow thumbnails directory, resolved to an absolute path.."""@@ -759,6 +766,26 @@ def ensure_fonts_dir(fonts_path: Path) -> None:logger.warning("Unable to initialize fonts directory at %s", fonts_path, exc_info=True)+def ensure_prompt_files_dir(prompt_files_path: Path) -> None:+ prompt_files_readme_path = prompt_files_path / "README.txt"++ try:+ prompt_files_path.mkdir(parents=True, exist_ok=True)+ if not prompt_files_readme_path.exists():+ with open(prompt_files_readme_path, "wt", encoding="utf-8") as f:+ f.write(+ "Prompt list files for the InvokeAI 'Prompts from File' node.\n\n"+ "Place UTF-8 text files, one prompt per line, in this folder (or subfolders).\n"+ "The node's file_path input is relative to this folder: a file saved as\n"+ "'lists/fantasy.txt' here is addressed as 'lists/fantasy.txt'.\n\n"+ "The node cannot read files outside this folder. In multi-user mode it is\n"+ "restricted to administrators, because this folder is shared by all accounts -\n"+ "non-admins should use wildcards, which are per-account, instead.\n"+ )+ except OSError:+ logger.warning("Unable to initialize prompt files directory at %s", prompt_files_path, exc_info=True)++def load_config_from_root(root: Path) -> InvokeAIAppConfig:"""The config of the install at `root`, from the environment and its `invokeai.yaml` as `get_config` reads them,for the maintenance scripts. Unlike `get_config` it writes no example or default config file and copies no@@ -849,6 +876,7 @@ def get_config() -> InvokeAIAppConfig:default_config.write_file(config.config_file_path, as_example=False)ensure_fonts_dir(config.fonts_path)+ ensure_prompt_files_dir(config.prompt_files_path)api_keys_from_file = load_external_api_keys(config.api_keys_file_path)if api_keys_from_file:diff --git a/invokeai/app/services/workflow_records/default_workflows/Prompt from File.json b/invokeai/app/services/workflow_records/default_workflows/Prompt from File.jsonindex 747213e140..1fdb658504 100644--- a/invokeai/app/services/workflow_records/default_workflows/Prompt from File.json+++ b/invokeai/app/services/workflow_records/default_workflows/Prompt from File.json@@ -192,7 +192,7 @@"type": "invocation","data": {"id": "1b7e0df8-8589-4915-a4ea-c0088f15d642",- "version": "1.0.2",+ "version": "2.0.0","nodePack": "invokeai","label": "Prompts from File","notes": "",diff --git a/invokeai/app/util/path_safety.py b/invokeai/app/util/path_safety.pyindex 4f8ab6ce69..5b47068a40 100644--- a/invokeai/app/util/path_safety.py+++ b/invokeai/app/util/path_safety.py@@ -1,5 +1,5 @@import os-from pathlib import PureWindowsPath+from pathlib import Path, PureWindowsPath# Read at call time by `is_contained_filename`, so tests can exercise both platforms' rules on either._ON_WINDOWS = os.name == "nt"@@ -87,3 +87,54 @@ def is_contained_filename(name: str) -> bool: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 (".", "..")+++def resolve_contained_path(root: Path, candidate: str) -> Path:+ r"""Resolves a client-supplied relative path strictly inside `root`.++ `is_plain_filename` and `is_contained_filename` gate a *single* name. This gates a whole+ relative path - `exports/2026`, `lists/fantasy.txt` - for the case where a node or route lets+ the caller address a file under a directory the operator has designated. The caller never gets+ to name the root, only a path beneath it.++ Containment is checked twice, because the two checks catch different things:++ - Each component must pass `is_contained_filename`, which rejects `.`, `..`, separators,+ control characters and (on Windows) drive letters, colons and device names. This is the+ textual check, and it refuses the payload before it ever touches the filesystem.+ `is_contained_filename` rather than `is_plain_filename`: these paths address files that are+ *already on disk*, placed there by an operator, so a prompt list that a posix admin named+ `aux.txt` or `notes:1.txt` must stay readable. Windows containment is identical either way.+ - The joined path is then `resolve()`d and required to sit under the resolved root. This is+ what catches a symlink inside the root pointing out of it, which no amount of string+ inspection can see.++ `PureWindowsPath` parses the input so that backslash-separated and drive-shaped payloads are+ split and rejected on posix too, instead of passing here and only escaping on Windows.++ Raises:+ ValueError: if the path is absolute, drive-qualified, empty, or escapes `root`.+ """+ if not candidate:+ raise ValueError("A path is required.")++ raw = PureWindowsPath(candidate)+ if raw.is_absolute() or raw.drive or raw.root:+ raise ValueError(+ f"Absolute paths are not allowed: {candidate!r}. Use a path relative to the permitted directory."+ )++ # `.` and `./` carry no components and address the root itself, which is contained by definition.+ # `""` is refused above instead: an empty input is a missing value, not a reference to the root.+ parts = raw.parts+ if not parts:+ return root.resolve()+ for part in parts:+ if not is_contained_filename(part):+ raise ValueError(f"Path component {part!r} is not allowed in {candidate!r}.")++ resolved = (root / Path(*parts)).resolve()+ root_resolved = root.resolve()+ if resolved != root_resolved and root_resolved not in resolved.parents:+ raise ValueError(f"Path must stay within the permitted directory: {candidate!r}")+ return resolveddiff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 8f4fa38ba3..e0ea5af47a 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -63577,6 +63577,13 @@"description": "Path to directory for style presets.","default": "style_presets"},+ "prompt_files_dir": {+ "type": "string",+ "format": "path",+ "title": "Prompt Files Dir",+ "description": "Path to the directory holding prompt list files readable by the Prompts from File node. The node cannot read outside this directory.",+ "default": "prompt_files"+ },"workflow_thumbnails_dir": {"type": "string","format": "path",@@ -64220,7 +64227,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 show_donation_link: Show the Donate to InvokeAI link in the frontend menus.\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 db_url: URL of a MySQL 8.4+ or MariaDB 10.11+ database to use instead of the SQLite database in `db_dir`, e.g. `mariadb+pymysql://invokeai:[email protected]/invokeai`. Needs the `mysql` extra. One InvokeAI process uses a database at a time. Read at startup only.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\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 reserve_vram_gb: The amount of VRAM (in GB) to subtract from the model cache's available memory budget. Defaults to 0.\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 offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.\n clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n int8_compute: Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.\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. Unset on a ROCm build of PyTorch on Windows, \"expandable_segments:True\" is used.\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`, `xpu`, `cuda:N`, `xpu: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 rocm_aotriton_experimental: Use AOTriton's fused (flash and memory-efficient) attention kernels on AMD GPUs that PyTorch marks experimental for them, such as the RX 7600/7700/7800 series, Ryzen AI 300/Max and the RX 9060 series, by setting TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL. Without them, attention on those GPUs runs on the slower math kernel, which also needs far more memory. `auto` turns them on only with a ROCm 10 build of PyTorch, and only when every GPU used for generation is one they were measured correct on (so far gfx1200, the RX 9060 series); `on` and `off` decide for any build and GPU. A TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL value already set in the environment takes precedence. Has no effect on other GPUs.<br>Valid values: `auto`, `on`, `off`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n tiny_autoencoder_previews: Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs about 25 ms and 0.65 GB of transient VRAM on an RTX 4090; not recommended on CPU-only installs, where one takes about 2 s.\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 attention_backend: Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.<br>Valid values: `auto`, `sage`, `cudnn`, `flash`, `efficient`, `math`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, FLUX.2, Z-Image, Qwen-Image and Qwen-Image-2.1 VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.\n auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, FLUX.2, Z-Image, Qwen-Image, Qwen-Image-2.1, Krea-2 and Wan decodes, and Qwen-Image-2.1 encodes). Turn off to decode untiled unless tiling is requested; the FLUX.1, FLUX.2 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.\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 image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\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_atlascloud_api_key: API key for Atlas Cloud image generation.\n external_atlascloud_base_url: Base URL override for Atlas Cloud 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.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."+ "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 show_donation_link: Show the Donate to InvokeAI link in the frontend menus.\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 db_url: URL of a MySQL 8.4+ or MariaDB 10.11+ database to use instead of the SQLite database in `db_dir`, e.g. `mariadb+pymysql://invokeai:[email protected]/invokeai`. Needs the `mysql` extra. One InvokeAI process uses a database at a time. Read at startup only.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\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 prompt_files_dir: Path to the directory holding prompt list files readable by the Prompts from File node. The node cannot read outside this directory.\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 reserve_vram_gb: The amount of VRAM (in GB) to subtract from the model cache's available memory budget. Defaults to 0.\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 offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.\n clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n int8_compute: Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.\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. Unset on a ROCm build of PyTorch on Windows, \"expandable_segments:True\" is used.\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`, `xpu`, `cuda:N`, `xpu: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 rocm_aotriton_experimental: Use AOTriton's fused (flash and memory-efficient) attention kernels on AMD GPUs that PyTorch marks experimental for them, such as the RX 7600/7700/7800 series, Ryzen AI 300/Max and the RX 9060 series, by setting TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL. Without them, attention on those GPUs runs on the slower math kernel, which also needs far more memory. `auto` turns them on only with a ROCm 10 build of PyTorch, and only when every GPU used for generation is one they were measured correct on (so far gfx1200, the RX 9060 series); `on` and `off` decide for any build and GPU. A TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL value already set in the environment takes precedence. Has no effect on other GPUs.<br>Valid values: `auto`, `on`, `off`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n tiny_autoencoder_previews: Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs about 25 ms and 0.65 GB of transient VRAM on an RTX 4090; not recommended on CPU-only installs, where one takes about 2 s.\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 attention_backend: Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.<br>Valid values: `auto`, `sage`, `cudnn`, `flash`, `efficient`, `math`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, FLUX.2, Z-Image, Qwen-Image and Qwen-Image-2.1 VAE nodes, the Anima encode, the Z-Image control encode and the Krea-2 style reference; other model families ignore it.\n auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, FLUX.2, Z-Image, Qwen-Image, Qwen-Image-2.1, Krea-2 and Wan decodes, and Qwen-Image-2.1 encodes). Turn off to decode untiled unless tiling is requested; the FLUX.1, FLUX.2 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.\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 image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\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_atlascloud_api_key: API key for Atlas Cloud image generation.\n external_atlascloud_base_url: Base URL override for Atlas Cloud 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.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."},"InvokeAIAppConfigWithSetFields": {"properties": {@@ -98780,7 +98787,7 @@"category": "prompt","class": "invocation","classification": "stable",- "description": "Loads prompts from a text file",+ "description": "Loads prompts from a text file.\n\nThe file is read from the InvokeAI prompt files directory (`prompt_files_dir`, by default\n`<root>/prompt_files`). `file_path` is relative to that directory - absolute paths and path\ntraversal are rejected - so the node can only read prompt lists an operator has deliberately\nplaced there.\n\nIn multi-user mode the node is restricted to administrators: the directory is shared by every\naccount, so letting one account read from it would hand it another account's prompt lists.\nNon-admin users should use wildcards, which are stored per account.","node_pack": "invokeai","properties": {"id": {@@ -98801,7 +98808,7 @@"ui_type": "IsIntermediate"},"use_cache": {- "default": true,+ "default": false,"description": "Whether or not to use the cache","field_kind": "node_attribute","title": "Use Cache",@@ -98817,7 +98824,7 @@}],"default": null,- "description": "Path to prompt text file",+ "description": "Path to prompt text file, relative to the InvokeAI prompt files directory","field_kind": "input","input": "any","orig_required": true,@@ -98893,7 +98900,7 @@"tags": ["prompt", "file"],"title": "Prompts from File","type": "object",- "version": "1.0.2",+ "version": "2.0.0","output": {"$ref": "#/components/schemas/StringCollectionOutput"}diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 345091d305..c740748360 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -24231,6 +24231,7 @@ export type components = {* 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`* custom_nodes_dir: Path to directory for custom nodes.* style_presets_dir: Path to directory for style presets.+ * prompt_files_dir: Path to the directory holding prompt list files readable by the Prompts from File node. The node cannot read outside this directory.* workflow_thumbnails_dir: Path to directory for workflow thumbnails.* log_handlers: Log handler. Valid options are "console", "file=<path>", "syslog=path|address:host:port", "http=<url>".* 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`@@ -24505,6 +24506,13 @@ export type components = {* @default style_presets*/style_presets_dir?: string;+ /**+ * Prompt Files Dir+ * Format: path+ * @description Path to the directory holding prompt list files readable by the Prompts from File node. The node cannot read outside this directory.+ * @default prompt_files+ */+ prompt_files_dir?: string;/*** Workflow Thumbnails Dir* Format: path@@ -42293,7 +42301,16 @@ export type components = {};/*** Prompts from File- * @description Loads prompts from a text file+ * @description Loads prompts from a text file.+ *+ * The file is read from the InvokeAI prompt files directory (`prompt_files_dir`, by default+ * `<root>/prompt_files`). `file_path` is relative to that directory - absolute paths and path+ * traversal are rejected - so the node can only read prompt lists an operator has deliberately+ * placed there.+ *+ * In multi-user mode the node is restricted to administrators: the directory is shared by every+ * account, so letting one account read from it would hand it another account's prompt lists.+ * Non-admin users should use wildcards, which are stored per account.*/PromptsFromFileInvocation: {/**@@ -42310,12 +42327,12 @@ export type components = {/*** Use Cache* @description Whether or not to use the cache- * @default true+ * @default false*/use_cache?: boolean;/*** File Path- * @description Path to prompt text file+ * @description Path to prompt text file, relative to the InvokeAI prompt files directory* @default null*/file_path?: string | null;diff --git a/tests/app/invocations/test_prompt_from_file.py b/tests/app/invocations/test_prompt_from_file.pynew file mode 100644index 0000000000..221d7e5073--- /dev/null+++ b/tests/app/invocations/test_prompt_from_file.py@@ -0,0 +1,204 @@+"""Tests for PromptsFromFileInvocation.++Regression coverage for GHSA-xwjh-4cmx-mqjh: `prompt_from_file` took an unconstrained `file_path`,+opened it in the queue worker and returned every line to whoever enqueued the graph, so any account+with a session could read any UTF-8 file the service account could read.+"""++from pathlib import Path+from unittest.mock import MagicMock++import pytest++from invokeai.app.invocations.prompt import PromptsFromFileInvocation+from invokeai.app.services.invocation_cache.invocation_cache_memory import MemoryInvocationCache+++def _make_context(+ prompt_files_path: Path,+ multiuser: bool = False,+ user_id: str = "system",+ is_admin: bool = True,+ user_exists: bool = True,+) -> MagicMock:+ context = MagicMock()+ config = MagicMock()+ config.multiuser = multiuser+ config.prompt_files_path = prompt_files_path+ context._services.configuration = config+ context._data.queue_item.user_id = user_id+ if user_exists:+ user = MagicMock()+ user.is_admin = is_admin+ context._services.users.get.return_value = user+ else:+ context._services.users.get.return_value = None+ return context+++def _build_node(**overrides) -> PromptsFromFileInvocation:+ defaults = {"id": "test", "file_path": "prompts.txt"}+ defaults.update(overrides)+ return PromptsFromFileInvocation(**defaults)+++def prompt_files(tmp_path: Path) -> Path:+ root = tmp_path / "prompt_files"+ root.mkdir()+ (root / "prompts.txt").write_text("a red cat\na blue dog\na green bird\n", encoding="utf-8")+ (root / "lists").mkdir()+ (root / "lists" / "fantasy.txt").write_text("a dragon\na wizard\n", encoding="utf-8")+ return root+++class TestPromptsFromFileReadsPermittedFiles:+ def test_reads_file_in_root(self, prompt_files):+ ctx = _make_context(prompt_files)+ out = _build_node(max_prompts=0).invoke(ctx)+ assert out.collection == ["a red cat", "a blue dog", "a green bird"]++ def test_reads_file_in_subdirectory(self, prompt_files):+ ctx = _make_context(prompt_files)+ out = _build_node(file_path="lists/fantasy.txt", max_prompts=0).invoke(ctx)+ assert out.collection == ["a dragon", "a wizard"]++ def test_respects_start_line_and_max_prompts(self, prompt_files):+ ctx = _make_context(prompt_files)+ out = _build_node(start_line=2, max_prompts=1).invoke(ctx)+ assert out.collection == ["a blue dog"]++ def test_applies_pre_and_post_prompt(self, prompt_files):+ ctx = _make_context(prompt_files)+ out = _build_node(max_prompts=1, pre_prompt="masterpiece, ", post_prompt=", 4k").invoke(ctx)+ assert out.collection == ["masterpiece, a red cat, 4k"]+++class TestPromptsFromFileRefusesEscape:+ # The advisory's payloads, plus the spellings that only escape on Windows.+ @pytest.mark.parametrize(+ "file_path",+ [+ "/etc/passwd",+ "/proc/self/environ",+ "../../../../etc/passwd",+ "../outside.txt",+ "lists/../../outside.txt",+ "C:\\Windows\\win.ini",+ "..\\outside.txt",+ "\\\\server\\share\\f.txt",+ "",+ ],+ )+ def test_rejects_path_outside_root(self, prompt_files, file_path):+ (prompt_files.parent / "outside.txt").write_text("SECRET\n", encoding="utf-8")+ ctx = _make_context(prompt_files)+ with pytest.raises(ValueError) as exc:+ _build_node(file_path=file_path, max_prompts=0).invoke(ctx)+ # Names the setting so an upgrading operator knows where files now live, without the resolved path.+ assert "prompt_files_dir" in str(exc.value)+ assert str(prompt_files) not in str(exc.value)++ def test_rejects_symlink_escaping_root(self, prompt_files):+ secret = prompt_files.parent / "secret.txt"+ secret.write_text("SECRET\n", encoding="utf-8")+ (prompt_files / "escape.txt").symlink_to(secret)++ ctx = _make_context(prompt_files)+ with pytest.raises(ValueError, match="stay within"):+ _build_node(file_path="escape.txt", max_prompts=0).invoke(ctx)++ def test_etc_passwd_contents_never_returned(self, prompt_files):+ """The advisory's exact primitive: the response must not carry the file's contents."""+ ctx = _make_context(prompt_files)+ with pytest.raises(ValueError) as exc:+ _build_node(file_path="/etc/passwd", max_prompts=0).invoke(ctx)+ assert "root:x:0:0" not in str(exc.value)+++class TestPromptsFromFileExistenceIsNotAnOracle:+ def test_no_field_validator_rejects_at_request_validation(self):+ """Constructing the node must not touch the filesystem.++ The original `file_path_exists` validator ran while the enqueue body was parsed, so a+ missing path was answered as a 422 before anything was queued - a filesystem probe that+ left no queue item behind. Construction must now succeed regardless of the path.+ """+ node = _build_node(file_path="definitely/does/not/exist.txt")+ assert node.file_path == "definitely/does/not/exist.txt"+ # An absolute path must also survive construction - it is refused at invoke time, as a+ # failure on the caller's own queue item.+ assert _build_node(file_path="/etc/passwd").file_path == "/etc/passwd"++ def test_missing_file_fails_at_invoke(self, prompt_files):+ ctx = _make_context(prompt_files)+ with pytest.raises(ValueError, match=r"No prompt file 'nope\.txt' in .*prompt_files_dir"):+ _build_node(file_path="nope.txt").invoke(ctx)++ def test_missing_file_error_does_not_leak_absolute_path(self, prompt_files):+ ctx = _make_context(prompt_files)+ with pytest.raises(ValueError) as exc:+ _build_node(file_path="nope.txt").invoke(ctx)+ assert str(prompt_files) not in str(exc.value)++ def test_directory_is_not_readable_as_a_file(self, prompt_files):+ ctx = _make_context(prompt_files)+ with pytest.raises(ValueError, match="No prompt file"):+ _build_node(file_path="lists").invoke(ctx)+++class TestPromptsFromFileMultiuserAuthorization:+ def test_non_admin_is_refused(self, prompt_files):+ ctx = _make_context(prompt_files, multiuser=True, user_id="attacker", is_admin=False)+ with pytest.raises(ValueError, match="restricted to administrators"):+ _build_node(max_prompts=0).invoke(ctx)++ def test_unknown_user_is_refused(self, prompt_files):+ """Fail closed when the queueing account cannot be resolved."""+ ctx = _make_context(prompt_files, multiuser=True, user_id="ghost", user_exists=False)+ with pytest.raises(ValueError, match="restricted to administrators"):+ _build_node(max_prompts=0).invoke(ctx)++ def test_admin_is_allowed(self, prompt_files):+ ctx = _make_context(prompt_files, multiuser=True, user_id="admin", is_admin=True)+ out = _build_node(max_prompts=0).invoke(ctx)+ assert out.collection == ["a red cat", "a blue dog", "a green bird"]++ def test_authorization_is_checked_against_the_queueing_user(self, prompt_files):+ ctx = _make_context(prompt_files, multiuser=True, user_id="user-123", is_admin=True)+ _build_node(max_prompts=0).invoke(ctx)+ ctx._services.users.get.assert_called_once_with("user-123")++ def test_single_user_mode_does_not_require_a_user_lookup(self, prompt_files):+ ctx = _make_context(prompt_files, multiuser=False)+ _build_node(max_prompts=0).invoke(ctx)+ ctx._services.users.get.assert_not_called()++ @pytest.mark.parametrize("file_path", ["nope.txt", "escape.txt", "../outside.txt"])+ def test_non_admin_refused_before_the_file_is_opened(self, prompt_files, file_path):+ """The gate must precede path resolution, so a non-admin cannot even probe for existence or containment."""+ outside = prompt_files.parent / "outside.txt"+ outside.write_text("SECRET\n", encoding="utf-8")+ (prompt_files / "escape.txt").symlink_to(outside)+ ctx = _make_context(prompt_files, multiuser=True, user_id="attacker", is_admin=False)+ with pytest.raises(ValueError, match="restricted to administrators"):+ _build_node(file_path=file_path).invoke(ctx)+++class TestPromptsFromFileBypassesInvocationCache:+ def test_admin_warmed_cache_entry_is_not_served_to_non_admin(self, prompt_files):+ """Cache keys carry no user identity, so a cache hit would skip the admin gate in `invoke()`."""+ ctx = _make_context(prompt_files, multiuser=True, user_id="admin", is_admin=True)+ ctx._skip_invocation_cache = False+ services = ctx._services+ services.configuration.node_cache_size = 10+ services.invocation_cache = MemoryInvocationCache(max_cache_size=10)++ # Clients choose `use_cache` per node, whatever the decorator default.+ node = _build_node(max_prompts=0, use_cache=True)+ admin_out = node.invoke_internal_with_effects(ctx, services).output+ assert admin_out.collection == ["a red cat", "a blue dog", "a green bird"]++ services.users.get.return_value.is_admin = False+ with pytest.raises(ValueError, match="restricted to administrators"):+ _build_node(max_prompts=0, use_cache=True).invoke_internal_with_effects(ctx, services)diff --git a/tests/app/invocations/test_save_image_to_file.py b/tests/app/invocations/test_save_image_to_file.pyindex 095f67be28..8ceaf1d2f7 100644--- a/tests/app/invocations/test_save_image_to_file.py+++ b/tests/app/invocations/test_save_image_to_file.py@@ -124,6 +124,7 @@ class TestSaveImageToFileInvocation:with pytest.raises(ValueError, match="[Aa]bsolute"):node.invoke(ctx)+ ctx.images.save.assert_not_called()@pytest.mark.parametrize("traversal_path",@@ -140,6 +141,41 @@ class TestSaveImageToFileInvocation:with pytest.raises(ValueError):node.invoke(ctx)+ ctx.images.save.assert_not_called()++ @pytest.mark.parametrize(+ "field, make_value",+ [+ ("prefix", lambda outside: f"{outside}/"),+ ("prefix", lambda outside: "../escaped_"),+ ("suffix", lambda outside: "/../../escaped"),+ ("suffix", lambda outside: "\\..\\escaped"),+ ],+ )+ def test_filename_affixes_cannot_escape_target_dir(self, tmp_path, field, make_value):+ outputs = tmp_path / "outputs"+ outside = tmp_path / "outside"+ outside.mkdir()+ img = Image.new("RGB", (8, 8))+ ctx = _make_context(outputs, img)+ node = _build_node(**{field: make_value(outside)})++ with pytest.raises(ValueError, match="plain filename"):+ node.invoke(ctx)++ assert not any(outside.iterdir())+ assert not any(p.is_file() for p in tmp_path.iterdir())+ ctx.images.save.assert_not_called()++ def test_output_directory_naming_a_file_saves_nothing(self, tmp_path):+ (tmp_path / "taken").write_text("not a directory")+ img = Image.new("RGB", (8, 8))+ ctx = _make_context(tmp_path, img)+ node = _build_node(output_directory="taken")++ with pytest.raises(OSError):+ node.invoke(ctx)+ ctx.images.save.assert_not_called()def test_png_format(self, tmp_path):img = Image.new("RGBA", (8, 8), (10, 20, 30, 128))diff --git a/tests/app/util/test_path_safety.py b/tests/app/util/test_path_safety.pyindex ad43572a38..139682d51a 100644--- a/tests/app/util/test_path_safety.py+++ b/tests/app/util/test_path_safety.py@@ -182,3 +182,110 @@ def test_is_contained_filename_rejects_posix_escapes_on_posix(monkeypatch: pytesdef 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)+++# Relative paths that must never resolve inside the root. Separately from the single-name cases above, these are+# the shapes a *path*-taking input receives: traversal, absolute and drive-qualified payloads, and the backslash+# spellings that only escape on Windows but must be refused on posix too so a posix test run cannot report all+# clear on a payload that works against Windows deployments.+UNCONTAINED_PATHS = [+ "..",+ "../secret.txt",+ "../../../../etc/passwd",+ "sub/../../secret.txt",+ "/etc/passwd",+ "/proc/self/environ",+ "//srv/share/file",+ "..\\secret.txt",+ "sub\\..\\..\\secret.txt",+ "C:\\Windows\\win.ini",+ "C:relative",+ "\\\\?\\C:\\Windows\\win.ini",+ "\\\\server\\share\\f.txt",+ "",+ "nul\x00byte.txt",+ "sub/nul\x00byte.txt",+]++CONTAINED_PATHS = [+ "prompts.txt",+ "./prompts.txt",+ "lists/fantasy.txt",+ "lists/sub/deep.txt",+ # Backslashes are read as separators, so this addresses the same file as the forward-slash spelling.+ "lists\\fantasy.txt",+ "..leading.dots.txt",+]+++class TestResolveContainedPath:+ @pytest.mark.parametrize("candidate", UNCONTAINED_PATHS)+ def test_rejects_uncontained(self, tmp_path, candidate):+ root = tmp_path / "root"+ root.mkdir()+ with pytest.raises(ValueError):+ path_safety.resolve_contained_path(root, candidate)++ @pytest.mark.parametrize("candidate", CONTAINED_PATHS)+ def test_accepts_contained(self, tmp_path, candidate):+ root = tmp_path / "root"+ root.mkdir()+ resolved = path_safety.resolve_contained_path(root, candidate)+ assert resolved == root.resolve() or root.resolve() in resolved.parents++ # Legal posix filenames an operator may already have on disk; the portable is_plain_filename would refuse them.+ @pytest.mark.parametrize("candidate", ["aux.txt", "notes:1.txt", "lists/aux.txt"])+ def test_accepts_existing_posix_names_on_posix(self, tmp_path, monkeypatch: pytest.MonkeyPatch, candidate):+ monkeypatch.setattr(path_safety, "_ON_WINDOWS", False)+ root = tmp_path / "root"+ root.mkdir()+ assert path_safety.resolve_contained_path(root, candidate) == (root / candidate).resolve()++ def test_does_not_require_existence(self, tmp_path):+ """Callers that create the directory (save_image_to_file) resolve before it exists."""+ root = tmp_path / "root"+ root.mkdir()+ assert path_safety.resolve_contained_path(root, "not/yet/there") == (root / "not/yet/there").resolve()++ def test_rejects_symlink_escaping_root(self, tmp_path):+ """The check no amount of string inspection can make: a symlink inside the root pointing out of it."""+ root = tmp_path / "root"+ root.mkdir()+ secret = tmp_path / "secret.txt"+ secret.write_text("SECRET")+ (root / "escape.txt").symlink_to(secret)++ with pytest.raises(ValueError, match="stay within"):+ path_safety.resolve_contained_path(root, "escape.txt")++ def test_rejects_symlinked_directory_escaping_root(self, tmp_path):+ root = tmp_path / "root"+ root.mkdir()+ outside = tmp_path / "outside"+ outside.mkdir()+ (outside / "secret.txt").write_text("SECRET")+ (root / "link").symlink_to(outside, target_is_directory=True)++ with pytest.raises(ValueError, match="stay within"):+ path_safety.resolve_contained_path(root, "link/secret.txt")++ def test_allows_symlink_staying_inside_root(self, tmp_path):+ root = tmp_path / "root"+ root.mkdir()+ (root / "real.txt").write_text("ok")+ (root / "alias.txt").symlink_to(root / "real.txt")++ assert path_safety.resolve_contained_path(root, "alias.txt") == (root / "real.txt").resolve()++ def test_root_itself_is_contained(self, tmp_path):+ root = tmp_path / "root"+ root.mkdir()+ assert path_safety.resolve_contained_path(root, ".") == root.resolve()++ def test_sibling_directory_sharing_a_prefix_is_rejected(self, tmp_path):+ """`<tmp>/root-evil` must not pass as contained by `<tmp>/root` on a string prefix match."""+ root = tmp_path / "root"+ root.mkdir()+ (tmp_path / "root-evil").mkdir()+ with pytest.raises(ValueError):+ path_safety.resolve_contained_path(root, "../root-evil/f.txt")