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
Harden/router auth and bugfixes (#9200)
Alexander Eichhorn3e72b8883933
diff --git a/invokeai/app/api/routers/_access.py b/invokeai/app/api/routers/_access.pynew file mode 100644index 0000000000..fae3971a14--- /dev/null+++ b/invokeai/app/api/routers/_access.py@@ -0,0 +1,92 @@+"""Cross-router authorization helpers.++These helpers are imported by multiple router modules. Keep them free of router+specifics so any route can call them after resolving `current_user`.+"""++from fastapi import HTTPException++from invokeai.app.api.auth_dependencies import CurrentUserOrDefault+from invokeai.app.api.dependencies import ApiDependencies+from invokeai.app.services.board_records.board_records_common import BoardVisibility+++def assert_image_owner(image_name: str, current_user: CurrentUserOrDefault) -> None:+ """Raise 403 if the current user does not own the image and is not an admin.++ Ownership is satisfied when ANY of these hold:+ - The user is an admin.+ - The user is the image's direct owner (image_records.user_id).+ - The user owns the board the image sits on.+ - The image sits on a Public board (public boards grant mutation rights).+ """+ if current_user.is_admin:+ return+ owner = ApiDependencies.invoker.services.image_records.get_user_id(image_name)+ if owner is not None and owner == current_user.user_id:+ return++ board_id = ApiDependencies.invoker.services.board_image_records.get_board_for_image(image_name)+ if board_id is not None:+ try:+ board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)+ if board.user_id == current_user.user_id:+ return+ if board.board_visibility == BoardVisibility.Public:+ return+ except Exception:+ pass++ raise HTTPException(status_code=403, detail="Not authorized to modify this image")+++def assert_image_read_access(image_name: str, current_user: CurrentUserOrDefault) -> None:+ """Raise 403 if the current user may not view the image.++ Access is granted when ANY of these hold:+ - The user is an admin.+ - The user owns the image.+ - The image sits on a shared or public board.+ """+ if current_user.is_admin:+ return++ owner = ApiDependencies.invoker.services.image_records.get_user_id(image_name)+ if owner is not None and owner == current_user.user_id:+ return++ board_id = ApiDependencies.invoker.services.board_image_records.get_board_for_image(image_name)+ if board_id is not None:+ try:+ board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)+ if board.board_visibility in (BoardVisibility.Shared, BoardVisibility.Public):+ return+ except Exception:+ pass++ raise HTTPException(status_code=403, detail="Not authorized to access this image")+++def assert_board_read_access(board_id: str, current_user: CurrentUserOrDefault) -> None:+ """Raise 403 if the current user may not read images from this board.++ Access is granted when ANY of these hold:+ - The user is an admin.+ - The user owns the board.+ - The board visibility is Shared or Public.+ """+ if current_user.is_admin:+ return++ try:+ board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)+ except Exception:+ raise HTTPException(status_code=404, detail="Board not found")++ if board.user_id == current_user.user_id:+ return++ if board.board_visibility in (BoardVisibility.Shared, BoardVisibility.Public):+ return++ raise HTTPException(status_code=403, detail="Not authorized to access this board")diff --git a/invokeai/app/api/routers/download_queue.py b/invokeai/app/api/routers/download_queue.pyindex 2633b28bca..305eaf9273 100644--- a/invokeai/app/api/routers/download_queue.py+++ b/invokeai/app/api/routers/download_queue.py@@ -1,6 +1,8 @@# Copyright (c) 2023 Lincoln D. Stein"""FastAPI route for the download queue."""+from pathlib import Path as FsPath+from pathlib import PurePosixPath, PureWindowsPathfrom typing import List, Optionalfrom fastapi import Body, Path, Response@@ -8,6 +10,7 @@ from fastapi.routing import APIRouterfrom pydantic.networks import AnyHttpUrlfrom starlette.exceptions import HTTPException+from invokeai.app.api.auth_dependencies import AdminUserOrDefault, CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.services.download import (DownloadJob,@@ -17,11 +20,32 @@ from invokeai.app.services.download import (download_queue_router = APIRouter(prefix="/v1/download_queue", tags=["download_queue"])+def _validate_dest(dest: str) -> str:+ """Reject absolute paths and parent-traversal segments.++ Accepts a relative POSIX- or Windows-style path. Returns the original string+ for the caller to wrap in `Path(...)`. Raises 400 on suspicious input so the+ download service never sees it.+ """+ if not dest or not dest.strip():+ raise HTTPException(status_code=400, detail="Download destination must not be empty.")++ posix = PurePosixPath(dest)+ windows = PureWindowsPath(dest)+ if posix.is_absolute() or windows.is_absolute():+ raise HTTPException(status_code=400, detail="Download destination must be a relative path.")++ if ".." in posix.parts or ".." in windows.parts:+ raise HTTPException(status_code=400, detail="Download destination must not contain '..' segments.")++ return dest++@download_queue_router.get("/",operation_id="list_downloads",)-async def list_downloads() -> List[DownloadJob]:+async def list_downloads(current_user: CurrentUserOrDefault) -> List[DownloadJob]:"""Get a list of active and inactive jobs."""queue = ApiDependencies.invoker.services.download_queuereturn queue.list_jobs()@@ -35,7 +59,7 @@ async def list_downloads() -> List[DownloadJob]:400: {"description": "Bad request"},},)-async def prune_downloads() -> Response:+async def prune_downloads(current_user: AdminUserOrDefault) -> Response:"""Prune completed and errored jobs."""queue = ApiDependencies.invoker.services.download_queuequeue.prune_jobs()@@ -47,14 +71,16 @@ async def prune_downloads() -> Response:operation_id="download",)async def download(+ current_user: CurrentUserOrDefault,source: AnyHttpUrl = Body(description="download source"),dest: str = Body(description="download destination"),priority: int = Body(default=10, description="queue priority"),access_token: Optional[str] = Body(default=None, description="token for authorization to download"),) -> DownloadJob:"""Download the source URL to the file or directory indicted in dest."""+ validated_dest = _validate_dest(dest)queue = ApiDependencies.invoker.services.download_queue- return queue.download(source, Path(dest), priority, access_token)+ return queue.download(source, FsPath(validated_dest), priority, access_token)@download_queue_router.get(@@ -66,6 +92,7 @@ async def download(},)async def get_download_job(+ current_user: CurrentUserOrDefault,id: int = Path(description="ID of the download job to fetch."),) -> DownloadJob:"""Get a download job using its ID."""@@ -85,6 +112,7 @@ async def get_download_job(},)async def cancel_download_job(+ current_user: CurrentUserOrDefault,id: int = Path(description="ID of the download job to cancel."),) -> Response:"""Cancel a download job using its ID."""@@ -104,7 +132,7 @@ async def cancel_download_job(204: {"description": "Download jobs have been cancelled"},},)-async def cancel_all_download_jobs() -> Response:+async def cancel_all_download_jobs(current_user: AdminUserOrDefault) -> Response:"""Cancel all download jobs."""ApiDependencies.invoker.services.download_queue.cancel_all_jobs()return Response(status_code=204)diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.pyindex a3ae6fce82..976434c68f 100644--- a/invokeai/app/api/routers/images.py+++ b/invokeai/app/api/routers/images.py@@ -12,6 +12,15 @@ from pydantic import BaseModel, Field, model_validatorfrom invokeai.app.api.auth_dependencies import CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.api.extract_metadata_from_image import extract_metadata_from_image+from invokeai.app.api.routers._access import (+ assert_board_read_access as _assert_board_read_access,+)+from invokeai.app.api.routers._access import (+ assert_image_owner as _assert_image_owner,+)+from invokeai.app.api.routers._access import (+ assert_image_read_access as _assert_image_read_access,+)from invokeai.app.invocations.fields import MetadataFieldfrom invokeai.app.services.image_records.image_records_common import (ImageCategory,@@ -38,96 +47,6 @@ images_router = APIRouter(prefix="/v1/images", tags=["images"])IMAGE_MAX_AGE = 31536000-def _assert_image_owner(image_name: str, current_user: CurrentUserOrDefault) -> None:- """Raise 403 if the current user does not own the image and is not an admin.-- Ownership is satisfied when ANY of these hold:- - The user is an admin.- - The user is the image's direct owner (image_records.user_id).- - The user owns the board the image sits on.- - The image sits on a Public board (public boards grant mutation rights).- """- from invokeai.app.services.board_records.board_records_common import BoardVisibility-- if current_user.is_admin:- return- owner = ApiDependencies.invoker.services.image_records.get_user_id(image_name)- if owner is not None and owner == current_user.user_id:- return-- # Check whether the user owns the board the image belongs to,- # or the board is Public (public boards grant mutation rights).- board_id = ApiDependencies.invoker.services.board_image_records.get_board_for_image(image_name)- if board_id is not None:- try:- board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)- if board.user_id == current_user.user_id:- return- if board.board_visibility == BoardVisibility.Public:- return- except Exception:- pass-- raise HTTPException(status_code=403, detail="Not authorized to modify this image")---def _assert_image_read_access(image_name: str, current_user: CurrentUserOrDefault) -> None:- """Raise 403 if the current user may not view the image.-- Access is granted when ANY of these hold:- - The user is an admin.- - The user owns the image.- - The image sits on a shared or public board.- """- from invokeai.app.services.board_records.board_records_common import BoardVisibility-- if current_user.is_admin:- return-- owner = ApiDependencies.invoker.services.image_records.get_user_id(image_name)- if owner is not None and owner == current_user.user_id:- return-- # Check whether the image's board makes it visible to other users.- board_id = ApiDependencies.invoker.services.board_image_records.get_board_for_image(image_name)- if board_id is not None:- try:- board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)- if board.board_visibility in (BoardVisibility.Shared, BoardVisibility.Public):- return- except Exception:- pass-- raise HTTPException(status_code=403, detail="Not authorized to access this image")---def _assert_board_read_access(board_id: str, current_user: CurrentUserOrDefault) -> None:- """Raise 403 if the current user may not read images from this board.-- Access is granted when ANY of these hold:- - The user is an admin.- - The user owns the board.- - The board visibility is Shared or Public.- """- from invokeai.app.services.board_records.board_records_common import BoardVisibility-- if current_user.is_admin:- return-- try:- board = ApiDependencies.invoker.services.boards.get_dto(board_id=board_id)- except Exception:- raise HTTPException(status_code=404, detail="Board not found")-- if board.user_id == current_user.user_id:- return-- if board.board_visibility in (BoardVisibility.Shared, BoardVisibility.Public):- return-- raise HTTPException(status_code=403, detail="Not authorized to access this board")--class ResizeToDimensions(BaseModel):width: int = Field(..., gt=0)height: int = Field(..., gt=0)diff --git a/invokeai/app/api/routers/model_relationships.py b/invokeai/app/api/routers/model_relationships.pyindex 9dc1eafb58..0ec4507095 100644--- a/invokeai/app/api/routers/model_relationships.py+++ b/invokeai/app/api/routers/model_relationships.py@@ -5,6 +5,7 @@ from typing import Listfrom fastapi import APIRouter, Body, HTTPException, Path, statusfrom pydantic import BaseModel, Field+from invokeai.app.api.auth_dependencies import AdminUserOrDefault, CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependenciesmodel_relationships_router = APIRouter(prefix="/v1/model_relationships", tags=["model_relationships"])@@ -85,15 +86,13 @@ class ModelRelationshipBatchRequest(BaseModel):},)async def get_related_models(+ current_user: CurrentUserOrDefault,model_key: str = Path(..., description="The key of the model to get relationships for"),) -> list[str]:"""Get a list of model keys related to a given model."""- try:- return ApiDependencies.invoker.services.model_relationships.get_related_model_keys(model_key)- except Exception as e:- raise HTTPException(status_code=500, detail=str(e))+ return ApiDependencies.invoker.services.model_relationships.get_related_model_keys(model_key)@model_relationships_router.post(@@ -110,6 +109,7 @@ async def get_related_models(description="Creates a **bidirectional** relationship between two models, allowing each to reference the other as related.",)async def add_model_relationship(+ current_user: AdminUserOrDefault,req: ModelRelationshipCreateRequest = Body(..., description="The model keys to relate"),) -> None:"""@@ -120,18 +120,16 @@ async def add_model_relationship(- Raises 400 if keys are invalid or identical.- Raises 409 if the relationship already exists."""- try:- if req.model_key_1 == req.model_key_2:- raise HTTPException(status_code=400, detail="Cannot relate a model to itself.")+ if req.model_key_1 == req.model_key_2:+ raise HTTPException(status_code=400, detail="Cannot relate a model to itself.")+ try:ApiDependencies.invoker.services.model_relationships.add_model_relationship(req.model_key_1,req.model_key_2,)except ValueError as e:raise HTTPException(status_code=409, detail=str(e))- except Exception as e:- raise HTTPException(status_code=500, detail=str(e))@model_relationships_router.delete(@@ -148,6 +146,7 @@ async def add_model_relationship(description="Removes a **bidirectional** relationship between two models. The relationship must already exist.",)async def remove_model_relationship(+ current_user: AdminUserOrDefault,req: ModelRelationshipCreateRequest = Body(..., description="The model keys to disconnect"),) -> None:"""@@ -156,18 +155,16 @@ async def remove_model_relationship(- Raises 400 if attempting to unlink a model from itself.- Raises 404 if the relationship was not found."""- try:- if req.model_key_1 == req.model_key_2:- raise HTTPException(status_code=400, detail="Cannot unlink a model from itself.")+ if req.model_key_1 == req.model_key_2:+ raise HTTPException(status_code=400, detail="Cannot unlink a model from itself.")+ try:ApiDependencies.invoker.services.model_relationships.remove_model_relationship(req.model_key_1,req.model_key_2,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e))- except Exception as e:- raise HTTPException(status_code=500, detail=str(e))@model_relationships_router.post(@@ -198,6 +195,7 @@ async def remove_model_relationship(description="Retrieves all **unique related model keys** for a list of given models. This is useful for contextual suggestions or filtering.",)async def get_related_models_batch(+ current_user: CurrentUserOrDefault,req: ModelRelationshipBatchRequest = Body(..., description="Model keys to check for related connections"),) -> list[str]:"""@@ -205,11 +203,8 @@ async def get_related_models_batch(Useful when working with multiple selections in the UI or cross-model comparisons."""- try:- all_related: set[str] = set()- for key in req.model_keys:- related = ApiDependencies.invoker.services.model_relationships.get_related_model_keys(key)- all_related.update(related)- return list(all_related)- except Exception as e:- raise HTTPException(status_code=500, detail=str(e))+ all_related: set[str] = set()+ for key in req.model_keys:+ related = ApiDependencies.invoker.services.model_relationships.get_related_model_keys(key)+ all_related.update(related)+ return list(all_related)diff --git a/invokeai/app/api/routers/style_presets.py b/invokeai/app/api/routers/style_presets.pyindex dadd89debb..91acf8e7a6 100644--- a/invokeai/app/api/routers/style_presets.py+++ b/invokeai/app/api/routers/style_presets.py@@ -10,8 +10,10 @@ from fastapi.responses import FileResponsefrom PIL import Imagefrom pydantic import BaseModel, Field+from invokeai.app.api.auth_dependencies import AdminUserOrDefault, CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.api.routers.model_manager import IMAGE_MAX_AGE+from invokeai.app.services.auth.token_service import TokenDatafrom invokeai.app.services.style_preset_images.style_preset_images_common import StylePresetImageFileNotFoundExceptionfrom invokeai.app.services.style_preset_records.style_preset_records_common import (InvalidPresetImportDataError,@@ -19,6 +21,7 @@ from invokeai.app.services.style_preset_records.style_preset_records_common impoPresetType,StylePresetChanges,StylePresetNotFoundError,+ StylePresetRecordDTO,StylePresetRecordWithImage,StylePresetWithoutId,UnsupportedFileTypeError,@@ -31,11 +34,43 @@ class StylePresetFormData(BaseModel):positive_prompt: str = Field(description="Positive prompt")negative_prompt: str = Field(description="Negative prompt")type: PresetType = Field(description="Preset type")+ is_public: bool = Field(default=False, description="Whether the preset is visible to other users")style_presets_router = APIRouter(prefix="/v1/style_presets", tags=["style_presets"])+def _assert_preset_read(record: StylePresetRecordDTO, current_user: TokenData) -> None:+ """Allow read access if admin, owner, default preset, or public preset."""+ if current_user.is_admin:+ return+ if record.type == PresetType.Default:+ return+ if record.is_public:+ return+ if record.user_id == current_user.user_id:+ return+ raise HTTPException(status_code=403, detail="Not authorized to access this style preset")+++def _assert_preset_write(record: StylePresetRecordDTO, current_user: TokenData) -> None:+ """Allow write access only for admin or owner. Defaults are immutable for non-admins."""+ if current_user.is_admin:+ return+ if record.type == PresetType.Default:+ raise HTTPException(status_code=403, detail="Default style presets cannot be modified")+ if record.user_id == current_user.user_id:+ return+ raise HTTPException(status_code=403, detail="Not authorized to modify this style preset")+++def _load_record_or_404(style_preset_id: str) -> StylePresetRecordDTO:+ try:+ return ApiDependencies.invoker.services.style_preset_records.get(style_preset_id)+ except StylePresetNotFoundError:+ raise HTTPException(status_code=404, detail="Style preset not found")++@style_presets_router.get("/i/{style_preset_id}",operation_id="get_style_preset",@@ -44,15 +79,14 @@ style_presets_router = APIRouter(prefix="/v1/style_presets", tags=["style_preset},)async def get_style_preset(+ current_user: CurrentUserOrDefault,style_preset_id: str = Path(description="The style preset to get"),) -> StylePresetRecordWithImage:"""Gets a style preset"""- try:- image = ApiDependencies.invoker.services.style_preset_image_files.get_url(style_preset_id)- style_preset = ApiDependencies.invoker.services.style_preset_records.get(style_preset_id)- return StylePresetRecordWithImage(image=image, **style_preset.model_dump())- except StylePresetNotFoundError:- raise HTTPException(status_code=404, detail="Style preset not found")+ record = _load_record_or_404(style_preset_id)+ _assert_preset_read(record, current_user)+ image = ApiDependencies.invoker.services.style_preset_image_files.get_url(style_preset_id)+ return StylePresetRecordWithImage(image=image, **record.model_dump())@style_presets_router.patch(@@ -63,11 +97,30 @@ async def get_style_preset(},)async def update_style_preset(+ current_user: CurrentUserOrDefault,image: Optional[UploadFile] = File(description="The image file to upload", default=None),style_preset_id: str = Path(description="The id of the style preset to update"),data: str = Form(description="The data of the style preset to update"),) -> StylePresetRecordWithImage:"""Updates a style preset"""+ # Validate the data payload BEFORE any image-state mutation so a malformed+ # request can't leave the preset image partially updated.+ try:+ parsed_data = json.loads(data)+ validated_data = StylePresetFormData(**parsed_data)++ name = validated_data.name+ type = validated_data.type+ positive_prompt = validated_data.positive_prompt+ negative_prompt = validated_data.negative_prompt+ is_public = validated_data.is_public++ except (json.JSONDecodeError, pydantic.ValidationError):+ raise HTTPException(status_code=400, detail="Invalid preset data")++ record = _load_record_or_404(style_preset_id)+ _assert_preset_write(record, current_user)+if image is not None:if not image.content_type or not image.content_type.startswith("image"):raise HTTPException(status_code=415, detail="Not an image")@@ -90,20 +143,8 @@ async def update_style_preset(except StylePresetImageFileNotFoundException:pass- try:- parsed_data = json.loads(data)- validated_data = StylePresetFormData(**parsed_data)-- name = validated_data.name- type = validated_data.type- positive_prompt = validated_data.positive_prompt- negative_prompt = validated_data.negative_prompt-- except pydantic.ValidationError:- raise HTTPException(status_code=400, detail="Invalid preset data")-preset_data = PresetData(positive_prompt=positive_prompt, negative_prompt=negative_prompt)- changes = StylePresetChanges(name=name, preset_data=preset_data, type=type)+ changes = StylePresetChanges(name=name, preset_data=preset_data, type=type, is_public=is_public)style_preset_image = ApiDependencies.invoker.services.style_preset_image_files.get_url(style_preset_id)style_preset = ApiDependencies.invoker.services.style_preset_records.update(@@ -117,9 +158,13 @@ async def update_style_preset(operation_id="delete_style_preset",)async def delete_style_preset(+ current_user: CurrentUserOrDefault,style_preset_id: str = Path(description="The style preset to delete"),) -> None:"""Deletes a style preset"""+ record = _load_record_or_404(style_preset_id)+ _assert_preset_write(record, current_user)+try:ApiDependencies.invoker.services.style_preset_image_files.delete(style_preset_id)except StylePresetImageFileNotFoundException:@@ -136,6 +181,7 @@ async def delete_style_preset(},)async def create_style_preset(+ current_user: CurrentUserOrDefault,image: Optional[UploadFile] = File(description="The image file to upload", default=None),data: str = Form(description="The data of the style preset to create"),) -> StylePresetRecordWithImage:@@ -149,13 +195,20 @@ async def create_style_preset(type = validated_data.typepositive_prompt = validated_data.positive_promptnegative_prompt = validated_data.negative_prompt+ is_public = validated_data.is_public- except pydantic.ValidationError:+ except (json.JSONDecodeError, pydantic.ValidationError):raise HTTPException(status_code=400, detail="Invalid preset data")+ # Only admins may create default-typed presets — they're the shipped catalog.+ if type == PresetType.Default and not current_user.is_admin:+ raise HTTPException(status_code=403, detail="Only admins can create default presets")+preset_data = PresetData(positive_prompt=positive_prompt, negative_prompt=negative_prompt)- style_preset = StylePresetWithoutId(name=name, preset_data=preset_data, type=type)- new_style_preset = ApiDependencies.invoker.services.style_preset_records.create(style_preset=style_preset)+ style_preset = StylePresetWithoutId(name=name, preset_data=preset_data, type=type, is_public=is_public)+ new_style_preset = ApiDependencies.invoker.services.style_preset_records.create(+ style_preset=style_preset, user_id=current_user.user_id+ )if image is not None:if not image.content_type or not image.content_type.startswith("image"):@@ -185,10 +238,13 @@ async def create_style_preset(200: {"model": list[StylePresetRecordWithImage]},},)-async def list_style_presets() -> list[StylePresetRecordWithImage]:- """Gets a page of style presets"""+async def list_style_presets(current_user: CurrentUserOrDefault) -> list[StylePresetRecordWithImage]:+ """Gets the style presets visible to the current user."""style_presets_with_image: list[StylePresetRecordWithImage] = []- style_presets = ApiDependencies.invoker.services.style_preset_records.get_many()+ style_presets = ApiDependencies.invoker.services.style_preset_records.get_many(+ user_id=current_user.user_id,+ is_admin=current_user.is_admin,+ )for preset in style_presets:image = ApiDependencies.invoker.services.style_preset_image_files.get_url(preset.id)style_preset_with_image = StylePresetRecordWithImage(image=image, **preset.model_dump())@@ -210,9 +266,12 @@ async def list_style_presets() -> list[StylePresetRecordWithImage]:status_code=200,)async def get_style_preset_image(+ current_user: CurrentUserOrDefault,style_preset_id: str = Path(description="The id of the style preset image to get"),) -> FileResponse:"""Gets an image file that previews the model"""+ record = _load_record_or_404(style_preset_id)+ _assert_preset_read(record, current_user)try:path = ApiDependencies.invoker.services.style_preset_image_files.get_path(style_preset_id)@@ -235,15 +294,18 @@ async def get_style_preset_image(responses={200: {"content": {"text/csv": {}}, "description": "A CSV file with the requested data."}},status_code=200,)-async def export_style_presets():- # Create an in-memory stream to store the CSV data+async def export_style_presets(current_user: AdminUserOrDefault):+ # Admin-only export covers every user preset.output = io.StringIO()writer = csv.writer(output)- # Write the headerwriter.writerow(["name", "prompt", "negative_prompt"])- style_presets = ApiDependencies.invoker.services.style_preset_records.get_many(type=PresetType.User)+ style_presets = ApiDependencies.invoker.services.style_preset_records.get_many(+ type=PresetType.User,+ user_id=current_user.user_id,+ is_admin=True,+ )for preset in style_presets:writer.writerow([preset.name, preset.preset_data.positive_prompt, preset.preset_data.negative_prompt])@@ -262,10 +324,13 @@ async def export_style_presets():"/import",operation_id="import_style_presets",)-async def import_style_presets(file: UploadFile = File(description="The file to import")):+async def import_style_presets(+ current_user: AdminUserOrDefault,+ file: UploadFile = File(description="The file to import"),+):try:style_presets = await parse_presets_from_file(file)- ApiDependencies.invoker.services.style_preset_records.create_many(style_presets)+ ApiDependencies.invoker.services.style_preset_records.create_many(style_presets, user_id=current_user.user_id)except InvalidPresetImportDataError as e:ApiDependencies.invoker.services.logger.error(traceback.format_exc())raise HTTPException(status_code=400, detail=str(e))diff --git a/invokeai/app/api/routers/utilities.py b/invokeai/app/api/routers/utilities.pyindex f77f77a853..568546603a 100644--- a/invokeai/app/api/routers/utilities.py+++ b/invokeai/app/api/routers/utilities.py@@ -12,7 +12,9 @@ from pydantic import BaseModel, Fieldfrom pyparsing import ParseExceptionfrom transformers import AutoProcessor, AutoTokenizer, LlavaOnevisionForConditionalGeneration, LlavaOnevisionProcessor+from invokeai.app.api.auth_dependencies import CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependencies+from invokeai.app.api.routers._access import assert_image_read_accessfrom invokeai.app.services.image_files.image_files_common import ImageFileNotFoundExceptionfrom invokeai.app.services.model_records.model_records_base import UnknownModelExceptionfrom invokeai.backend.llava_onevision_pipeline import LlavaOnevisionPipeline@@ -41,6 +43,7 @@ class DynamicPromptsResponse(BaseModel):},)async def parse_dynamicprompts(+ current_user: CurrentUserOrDefault,prompt: str = Body(description="The prompt to parse with dynamicprompts"),max_prompts: int = Body(ge=1, le=10000, default=1000, description="The max number of prompts to generate"),combinatorial: bool = Body(default=True, description="Whether to use the combinatorial generator"),@@ -122,7 +125,7 @@ def _run_expand_prompt(prompt: str, model_key: str, max_tokens: int, system_prom200: {"model": ExpandPromptResponse},},)-async def expand_prompt(body: ExpandPromptRequest) -> ExpandPromptResponse:+async def expand_prompt(current_user: CurrentUserOrDefault, body: ExpandPromptRequest) -> ExpandPromptResponse:"""Expand a brief prompt into a detailed image generation prompt using a text LLM."""try:expanded = await asyncio.to_thread(@@ -199,8 +202,12 @@ def _run_image_to_prompt(image_name: str, model_key: str, instruction: str) -> s200: {"model": ImageToPromptResponse},},)-async def image_to_prompt(body: ImageToPromptRequest) -> ImageToPromptResponse:+async def image_to_prompt(current_user: CurrentUserOrDefault, body: ImageToPromptRequest) -> ImageToPromptResponse:"""Generate a descriptive prompt from an image using a vision-language model."""+ # Reuse the image-read access check so non-owners can't probe stored images+ # via this endpoint (mirrors the policy in routers/images.py).+ assert_image_read_access(body.image_name, current_user)+try:prompt = await asyncio.to_thread(_run_image_to_prompt,diff --git a/invokeai/app/services/style_preset_records/style_preset_records_base.py b/invokeai/app/services/style_preset_records/style_preset_records_base.pyindex a4dee2fbbd..87437a8dc0 100644--- a/invokeai/app/services/style_preset_records/style_preset_records_base.py+++ b/invokeai/app/services/style_preset_records/style_preset_records_base.py@@ -13,30 +13,41 @@ class StylePresetRecordsStorageBase(ABC):@abstractmethoddef get(self, style_preset_id: str) -> StylePresetRecordDTO:- """Get style preset by id."""+ """Get style preset by id. Authorization is the caller's responsibility."""pass@abstractmethod- def create(self, style_preset: StylePresetWithoutId) -> StylePresetRecordDTO:- """Creates a style preset."""+ def create(self, style_preset: StylePresetWithoutId, user_id: str) -> StylePresetRecordDTO:+ """Creates a style preset owned by user_id."""pass@abstractmethod- def create_many(self, style_presets: list[StylePresetWithoutId]) -> None:- """Creates many style presets."""+ def create_many(self, style_presets: list[StylePresetWithoutId], user_id: str) -> None:+ """Creates many style presets owned by user_id."""pass@abstractmethoddef update(self, style_preset_id: str, changes: StylePresetChanges) -> StylePresetRecordDTO:- """Updates a style preset."""+ """Updates a style preset. Authorization is the caller's responsibility."""pass@abstractmethoddef delete(self, style_preset_id: str) -> None:- """Deletes a style preset."""+ """Deletes a style preset. Authorization is the caller's responsibility."""pass@abstractmethod- def get_many(self, type: PresetType | None = None) -> list[StylePresetRecordDTO]:- """Gets many workflows."""+ def get_many(+ self,+ type: PresetType | None = None,+ user_id: str | None = None,+ is_admin: bool = False,+ ) -> list[StylePresetRecordDTO]:+ """Gets style presets visible to user_id.++ Visibility rules:+ - is_admin=True: all presets.+ - Else: presets owned by user_id, plus all `default` presets, plus any public preset.+ - If user_id is None and is_admin is False: only `default` and public presets.+ """passdiff --git a/invokeai/app/services/style_preset_records/style_preset_records_common.py b/invokeai/app/services/style_preset_records/style_preset_records_common.pyindex 9ea0b0219c..9e6df88c98 100644--- a/invokeai/app/services/style_preset_records/style_preset_records_common.py+++ b/invokeai/app/services/style_preset_records/style_preset_records_common.py@@ -32,16 +32,19 @@ class StylePresetChanges(BaseModel, extra="forbid"):name: Optional[str] = Field(default=None, description="The style preset's new name.")preset_data: Optional[PresetData] = Field(default=None, description="The updated data for style preset.")type: Optional[PresetType] = Field(description="The updated type of the style preset")+ is_public: Optional[bool] = Field(default=None, description="Whether the preset is visible to other users.")class StylePresetWithoutId(BaseModel):name: str = Field(description="The name of the style preset.")preset_data: PresetData = Field(description="The preset data")type: PresetType = Field(description="The type of style preset")+ is_public: bool = Field(default=False, description="Whether the preset is visible to other users.")class StylePresetRecordDTO(StylePresetWithoutId):id: str = Field(description="The style preset ID.")+ user_id: str = Field(description="The user who owns this style preset.")@classmethoddef from_dict(cls, data: dict[str, Any]) -> "StylePresetRecordDTO":diff --git a/invokeai/app/services/style_preset_records/style_preset_records_sqlite.py b/invokeai/app/services/style_preset_records/style_preset_records_sqlite.pyindex 35819fa0f0..03397133ae 100644--- a/invokeai/app/services/style_preset_records/style_preset_records_sqlite.py+++ b/invokeai/app/services/style_preset_records/style_preset_records_sqlite.py@@ -13,6 +13,10 @@ from invokeai.app.services.style_preset_records.style_preset_records_common impo)from invokeai.app.util.misc import uuid_string+# System user id used for default / shipped presets and for legacy rows pre-dating+# the per-user ownership columns added in migration 27.+SYSTEM_USER_ID = "system"+class SqliteStylePresetRecordsStorage(StylePresetRecordsStorageBase):def __init__(self, db: SqliteDatabase) -> None:@@ -39,7 +43,7 @@ class SqliteStylePresetRecordsStorage(StylePresetRecordsStorageBase):raise StylePresetNotFoundError(f"Style preset with id {style_preset_id} not found")return StylePresetRecordDTO.from_dict(dict(row))- def create(self, style_preset: StylePresetWithoutId) -> StylePresetRecordDTO:+ def create(self, style_preset: StylePresetWithoutId, user_id: str) -> StylePresetRecordDTO:style_preset_id = uuid_string()with self._db.transaction() as cursor:cursor.execute(@@ -48,40 +52,46 @@ class SqliteStylePresetRecordsStorage(StylePresetRecordsStorageBase):id,name,preset_data,- type+ type,+ user_id,+ is_public)- VALUES (?, ?, ?, ?);+ VALUES (?, ?, ?, ?, ?, ?);""",(style_preset_id,style_preset.name,style_preset.preset_data.model_dump_json(),style_preset.type,+ user_id,+ 1 if style_preset.is_public else 0,),)return self.get(style_preset_id)- def create_many(self, style_presets: list[StylePresetWithoutId]) -> None:- style_preset_ids = []+ def create_many(self, style_presets: list[StylePresetWithoutId], user_id: str) -> None:with self._db.transaction() as cursor:for style_preset in style_presets:style_preset_id = uuid_string()- style_preset_ids.append(style_preset_id)cursor.execute("""--sqlINSERT OR IGNORE INTO style_presets (id,name,preset_data,- type+ type,+ user_id,+ is_public)- VALUES (?, ?, ?, ?);+ VALUES (?, ?, ?, ?, ?, ?);""",(style_preset_id,style_preset.name,style_preset.preset_data.model_dump_json(),style_preset.type,+ user_id,+ 1 if style_preset.is_public else 0,),)@@ -89,7 +99,6 @@ class SqliteStylePresetRecordsStorage(StylePresetRecordsStorageBase):def update(self, style_preset_id: str, changes: StylePresetChanges) -> StylePresetRecordDTO:with self._db.transaction() as cursor:- # Change the name of a style presetif changes.name is not None:cursor.execute("""--sql@@ -100,7 +109,6 @@ class SqliteStylePresetRecordsStorage(StylePresetRecordsStorageBase):(changes.name, style_preset_id),)- # Change the preset data for a style presetif changes.preset_data is not None:cursor.execute("""--sql@@ -111,6 +119,16 @@ class SqliteStylePresetRecordsStorage(StylePresetRecordsStorageBase):(changes.preset_data.model_dump_json(), style_preset_id),)+ if changes.is_public is not None:+ cursor.execute(+ """--sql+ UPDATE style_presets+ SET is_public = ?+ WHERE id = ?;+ """,+ (1 if changes.is_public else 0, style_preset_id),+ )+return self.get(style_preset_id)def delete(self, style_preset_id: str) -> None:@@ -124,42 +142,47 @@ class SqliteStylePresetRecordsStorage(StylePresetRecordsStorageBase):)return None- def get_many(self, type: PresetType | None = None) -> list[StylePresetRecordDTO]:- with self._db.transaction() as cursor:- main_query = """- SELECT- *- FROM style_presets- """-- if type is not None:- main_query += "WHERE type = ? "-- main_query += "ORDER BY LOWER(name) ASC"-- if type is not None:- cursor.execute(main_query, (type,))- else:- cursor.execute(main_query)+ def get_many(+ self,+ type: PresetType | None = None,+ user_id: str | None = None,+ is_admin: bool = False,+ ) -> list[StylePresetRecordDTO]:+ clauses: list[str] = []+ params: list[object] = []++ if not is_admin:+ # Visible to non-admin: own + default + public.+ visibility = "(type = 'default' OR is_public = 1"+ if user_id is not None:+ visibility += " OR user_id = ?"+ params.append(user_id)+ visibility += ")"+ clauses.append(visibility)++ if type is not None:+ clauses.append("type = ?")+ params.append(type)++ where = f"WHERE {' AND '.join(clauses)} " if clauses else ""+ query = f"SELECT * FROM style_presets {where}ORDER BY LOWER(name) ASC"+ with self._db.transaction() as cursor:+ cursor.execute(query, params)rows = cursor.fetchall()- style_presets = [StylePresetRecordDTO.from_dict(dict(row)) for row in rows]-- return style_presets+ return [StylePresetRecordDTO.from_dict(dict(row)) for row in rows]def _sync_default_style_presets(self) -> None:"""Syncs default style presets to the database. Internal use only."""with self._db.transaction() as cursor:- # First delete all existing default style presetscursor.execute("""--sqlDELETE FROM style_presetsWHERE type = "default";""")- # Next, parse and create the default style presetswith open(Path(__file__).parent / Path("default_style_presets.json"), "r") as file:presets = json.load(file)for preset in presets:style_preset = StylePresetWithoutId.model_validate(preset)- self.create(style_preset)+ self.create(style_preset, user_id=SYSTEM_USER_ID)diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.jsonindex 4a36cf31e2..e13946511e 100644--- a/invokeai/frontend/web/openapi.json+++ b/invokeai/frontend/web/openapi.json@@ -481,7 +481,12 @@}}}- }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]}},"/api/v1/utilities/expand-prompt": {@@ -521,7 +526,12 @@}}}- }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]}},"/api/v1/utilities/image-to-prompt": {@@ -561,7 +571,12 @@}}}- }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]}},"/api/v2/models/": {@@ -3932,7 +3947,12 @@}}}- }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]},"patch": {"tags": ["download_queue"],@@ -3954,7 +3974,12 @@"400": {"description": "Bad request"}- }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]}},"/api/v1/download_queue/i/": {@@ -3994,7 +4019,12 @@}}}- }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]}},"/api/v1/download_queue/i/{id}": {@@ -4003,6 +4033,11 @@"summary": "Get Download Job","description": "Get a download job using its ID.","operationId": "get_download_job",+ "security": [+ {+ "HTTPBearer": []+ }+ ],"parameters": [{"name": "id",@@ -4047,6 +4082,11 @@"summary": "Cancel Download Job","description": "Cancel a download job using its ID.","operationId": "cancel_download_job",+ "security": [+ {+ "HTTPBearer": []+ }+ ],"parameters": [{"name": "id",@@ -4106,7 +4146,12 @@"204": {"description": "Download jobs have been cancelled"}- }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]}},"/api/v1/images/upload": {@@ -6142,6 +6187,11 @@"summary": "Get Related Models","description": "Get a list of model keys related to a given model.","operationId": "get_related_models",+ "security": [+ {+ "HTTPBearer": []+ }+ ],"parameters": [{"name": "model_key",@@ -6217,7 +6267,12 @@"500": {"description": "Internal server error"}- }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]},"delete": {"tags": ["model_relationships"],@@ -6251,7 +6306,12 @@"500": {"description": "Internal server error"}- }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]}},"/api/v1/model_relationships/batch": {@@ -6301,7 +6361,12 @@"500": {"description": "Internal server error"}- }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]}},"/api/v1/app/version": {@@ -8864,6 +8929,11 @@"summary": "Get Style Preset","description": "Gets a style preset","operationId": "get_style_preset",+ "security": [+ {+ "HTTPBearer": []+ }+ ],"parameters": [{"name": "style_preset_id",@@ -8905,6 +8975,11 @@"summary": "Update Style Preset","description": "Updates a style preset","operationId": "update_style_preset",+ "security": [+ {+ "HTTPBearer": []+ }+ ],"parameters": [{"name": "style_preset_id",@@ -8956,6 +9031,11 @@"summary": "Delete Style Preset","description": "Deletes a style preset","operationId": "delete_style_preset",+ "security": [+ {+ "HTTPBearer": []+ }+ ],"parameters": [{"name": "style_preset_id",@@ -8995,7 +9075,7 @@"get": {"tags": ["style_presets"],"summary": "List Style Presets",- "description": "Gets a page of style presets",+ "description": "Gets the style presets visible to the current user.","operationId": "list_style_presets","responses": {"200": {@@ -9012,7 +9092,12 @@}}}- }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]},"post": {"tags": ["style_presets"],@@ -9050,7 +9135,12 @@}}}- }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]}},"/api/v1/style_presets/i/{style_preset_id}/image": {@@ -9059,6 +9149,11 @@"summary": "Get Style Preset Image","description": "Gets an image file that previews the model","operationId": "get_style_preset_image",+ "security": [+ {+ "HTTPBearer": []+ }+ ],"parameters": [{"name": "style_preset_id",@@ -9115,7 +9210,12 @@"text/csv": {}}}- }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]}},"/api/v1/style_presets/import": {@@ -9152,7 +9252,12 @@}}}- }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]}},"/api/v1/client_state/{queue_id}/get_by_key": {@@ -66768,11 +66873,22 @@"$ref": "#/components/schemas/PresetType","description": "The type of style preset"},+ "is_public": {+ "type": "boolean",+ "title": "Is Public",+ "description": "Whether the preset is visible to other users.",+ "default": false+ },"id": {"type": "string","title": "Id","description": "The style preset ID."},+ "user_id": {+ "type": "string",+ "title": "User Id",+ "description": "The user who owns this style preset."+ },"image": {"anyOf": [{@@ -66787,7 +66903,7 @@}},"type": "object",- "required": ["name", "preset_data", "type", "id", "image"],+ "required": ["name", "preset_data", "type", "id", "user_id", "image"],"title": "StylePresetRecordWithImage"},"SubModelType": {diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.tsindex e9de97db96..7ca0f26fe9 100644--- a/invokeai/frontend/web/src/services/api/schema.ts+++ b/invokeai/frontend/web/src/services/api/schema.ts@@ -2471,7 +2471,7 @@ export type paths = {};/*** List Style Presets- * @description Gets a page of style presets+ * @description Gets the style presets visible to the current user.*/get: operations["list_style_presets"];put?: never;@@ -29068,11 +29068,22 @@ export type components = {preset_data: components["schemas"]["PresetData"];/** @description The type of style preset */type: components["schemas"]["PresetType"];+ /**+ * Is Public+ * @description Whether the preset is visible to other users.+ * @default false+ */+ is_public?: boolean;/*** Id* @description The style preset ID.*/id: string;+ /**+ * User Id+ * @description The user who owns this style preset.+ */+ user_id: string;/*** Image* @description The path for imagediff --git a/tests/app/routers/conftest.py b/tests/app/routers/conftest.pynew file mode 100644index 0000000000..73cd38e45f--- /dev/null+++ b/tests/app/routers/conftest.py@@ -0,0 +1,143 @@+"""Shared fixtures and helpers for router-level multiuser/auth tests.++Note: This conftest intentionally does NOT redefine `mock_services` / `mock_invoker`+to avoid shadowing the project-level fixtures in `tests/conftest.py`. Instead, the+`enable_multiuser` fixture below injects MagicMock services for the routers that+have no real backing service in the default mock_services (download_queue,+style_preset_image_files, model_relationships, model_manager).++WARNING for future authors: `enable_multiuser` *unconditionally* replaces several+services on `mock_invoker.services` with MagicMocks. If you add a router test that+expects the real service (e.g. a SQLite-backed implementation), you must restore+that service in your own fixture before the request — otherwise your test will+pass against a MagicMock that accepts every call. `style_preset_records` is wired+up to a real SQLite storage here because cross-user filtering needs real SQL.++WARNING for new routers: every router that calls `ApiDependencies.invoker.services`+must be added to `_PATCHED_API_DEPENDENCIES_MODULES` below, or its routes will hit+the un-patched singleton and fail with `AttributeError: type object+'ApiDependencies' has no attribute 'invoker'`.++Existing test files that define their own `enable_multiuser` / `admin_token` / etc.+fixtures locally are NOT affected — pytest's local-shadows-conftest rule applies.+"""++from typing import Any+from unittest.mock import MagicMock++import pytest+from fastapi.testclient import TestClient++from invokeai.app.api.dependencies import ApiDependencies+from invokeai.app.api_app import app+from invokeai.app.services.invoker import Invoker+from invokeai.app.services.users.users_common import UserCreateRequest+++class MockApiDependencies(ApiDependencies):+ """Minimal stand-in that lets tests inject their own Invoker."""++ invoker: Invoker++ def __init__(self, invoker: Invoker) -> None:+ self.invoker = invoker+++# Every module that reads `ApiDependencies.invoker.services` must be patched here+# so the in-test invoker is reachable. Add new routers / shared helpers to this+# list when they start touching ApiDependencies.+_PATCHED_API_DEPENDENCIES_MODULES = (+ "invokeai.app.api.auth_dependencies",+ "invokeai.app.api.routers.auth",+ "invokeai.app.api.routers.download_queue",+ "invokeai.app.api.routers.style_presets",+ "invokeai.app.api.routers.model_relationships",+ "invokeai.app.api.routers.utilities",+ "invokeai.app.api.routers.virtual_boards",+ "invokeai.app.api.routers.images",+ "invokeai.app.api.routers._access",+)+++def setup_jwt_secret():+ from invokeai.app.services.auth.token_service import set_jwt_secret++ set_jwt_secret("test-secret-key-for-unit-tests-only-do-not-use-in-production")+++def client():+ return TestClient(app)+++def _create_user(mock_invoker: Invoker, email: str, display_name: str, is_admin: bool = False) -> str:+ user = mock_invoker.services.users.create(+ UserCreateRequest(email=email, display_name=display_name, password="TestPass123", is_admin=is_admin)+ )+ return user.user_id+++def _login(client: TestClient, email: str) -> str:+ r = client.post("/api/v1/auth/login", json={"email": email, "password": "TestPass123", "remember_me": False})+ assert r.status_code == 200, f"Login failed for {email}: {r.text}"+ return r.json()["token"]+++def _auth(token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {token}"}+++def enable_multiuser(monkeypatch: Any, mock_invoker: Invoker):+ """Enable multiuser mode and patch ApiDependencies across the routers covered by router-level tests.++ Replaces None-valued services with MagicMocks so that routes can run end-to-end.+ """+ from invokeai.app.services.style_preset_records.style_preset_records_sqlite import (+ SqliteStylePresetRecordsStorage,+ )++ mock_invoker.services.configuration.multiuser = True++ # Replace services that are None in the default mock_services with MagicMocks.+ mock_invoker.services.download_queue = MagicMock()+ mock_invoker.services.style_preset_image_files = MagicMock()+ mock_invoker.services.model_relationships = MagicMock()+ mock_invoker.services.model_manager = MagicMock()++ # Style preset records uses a real SQLite-backed storage on the same in-memory+ # database that image_records was wired up against. This lets cross-user tests+ # exercise the actual filter SQL instead of asserting on MagicMock calls.+ mock_invoker.services.style_preset_records = SqliteStylePresetRecordsStorage(+ db=mock_invoker.services.image_records._db+ )++ # Required by board_image_records-touching helpers in some tests.+ if mock_invoker.services.board_images is None:+ mock_board_images = MagicMock()+ mock_board_images.get_all_board_image_names_for_board.return_value = []+ mock_invoker.services.board_images = mock_board_images++ mock_deps = MockApiDependencies(mock_invoker)+ for module_path in _PATCHED_API_DEPENDENCIES_MODULES:+ monkeypatch.setattr(f"{module_path}.ApiDependencies", mock_deps)+ yield+++def admin_token(setup_jwt_secret: None, enable_multiuser: Any, mock_invoker: Invoker, client: TestClient) -> str:+ _create_user(mock_invoker, "[email protected]", "Admin", is_admin=True)+ return _login(client, "[email protected]")+++def user1_token(enable_multiuser: Any, mock_invoker: Invoker, client: TestClient, admin_token: str) -> str:+ _create_user(mock_invoker, "[email protected]", "User One")+ return _login(client, "[email protected]")+++def user2_token(enable_multiuser: Any, mock_invoker: Invoker, client: TestClient, admin_token: str) -> str:+ _create_user(mock_invoker, "[email protected]", "User Two")+ return _login(client, "[email protected]")diff --git a/tests/app/routers/test_download_queue_router.py b/tests/app/routers/test_download_queue_router.pynew file mode 100644index 0000000000..b3976f051f--- /dev/null+++ b/tests/app/routers/test_download_queue_router.py@@ -0,0 +1,112 @@+"""Router-level tests for /api/v1/download_queue.++Covers:+- Auth gating (CurrentUserOrDefault on read/per-job, AdminUserOrDefault on prune & cancel-all).+- Bug regression: `dest` path validation must reject absolute paths and '..' segments+ BEFORE the queue service is invoked.+"""++from typing import Any+from unittest.mock import MagicMock++import pytest+from fastapi import status+from fastapi.testclient import TestClient++from invokeai.app.services.download import DownloadJob+from invokeai.app.services.invoker import Invoker+++def _make_job(id: int = 1) -> DownloadJob:+ from pathlib import Path++ return DownloadJob(id=id, source="http://example.com/file.bin", dest=Path("models/file.bin"))+++# ----------------------------- Auth gating -----------------------------+++ ("method", "path"),+ [+ ("GET", "/api/v1/download_queue/"),+ ("PATCH", "/api/v1/download_queue/"),+ ("POST", "/api/v1/download_queue/i/"),+ ("GET", "/api/v1/download_queue/i/1"),+ ("DELETE", "/api/v1/download_queue/i/1"),+ ("DELETE", "/api/v1/download_queue/i"),+ ],+)+def test_routes_require_auth_in_multiuser_mode(enable_multiuser: Any, client: TestClient, method: str, path: str):+ response = client.request(method, path, json={"source": "http://x/y", "dest": "models/x"})+ assert response.status_code == status.HTTP_401_UNAUTHORIZED+++def test_list_downloads_as_regular_user(client: TestClient, user1_token: str, mock_invoker: Invoker):+ mock_invoker.services.download_queue.list_jobs = MagicMock(return_value=[])+ r = client.get("/api/v1/download_queue/", headers={"Authorization": f"Bearer {user1_token}"})+ assert r.status_code == status.HTTP_200_OK+ assert r.json() == []+++def test_prune_downloads_forbidden_for_regular_user(client: TestClient, user1_token: str, mock_invoker: Invoker):+ r = client.patch("/api/v1/download_queue/", headers={"Authorization": f"Bearer {user1_token}"})+ assert r.status_code == status.HTTP_403_FORBIDDEN+ mock_invoker.services.download_queue.prune_jobs.assert_not_called()+++def test_prune_downloads_allowed_for_admin(client: TestClient, admin_token: str, mock_invoker: Invoker):+ r = client.patch("/api/v1/download_queue/", headers={"Authorization": f"Bearer {admin_token}"})+ assert r.status_code == status.HTTP_204_NO_CONTENT+ mock_invoker.services.download_queue.prune_jobs.assert_called_once()+++def test_cancel_all_forbidden_for_regular_user(client: TestClient, user1_token: str, mock_invoker: Invoker):+ r = client.delete("/api/v1/download_queue/i", headers={"Authorization": f"Bearer {user1_token}"})+ assert r.status_code == status.HTTP_403_FORBIDDEN+ mock_invoker.services.download_queue.cancel_all_jobs.assert_not_called()+++def test_cancel_all_allowed_for_admin(client: TestClient, admin_token: str, mock_invoker: Invoker):+ r = client.delete("/api/v1/download_queue/i", headers={"Authorization": f"Bearer {admin_token}"})+ assert r.status_code == status.HTTP_204_NO_CONTENT+ mock_invoker.services.download_queue.cancel_all_jobs.assert_called_once()+++# ----------------------------- Bug D regression: dest validation -----------------------------+++ "bad_dest",+ [+ "/etc/passwd",+ "C:/Windows/System32",+ "models/../../etc/passwd",+ "..",+ "",+ " ",+ ],+)+def test_download_rejects_unsafe_dest_before_service_call(+ client: TestClient, user1_token: str, mock_invoker: Invoker, bad_dest: str+):+ """Absolute paths, '..' segments, and empty strings must produce 400 and+ must NOT invoke the download_queue service."""+ r = client.post(+ "/api/v1/download_queue/i/",+ json={"source": "http://example.com/file.bin", "dest": bad_dest},+ headers={"Authorization": f"Bearer {user1_token}"},+ )+ assert r.status_code == status.HTTP_400_BAD_REQUEST+ mock_invoker.services.download_queue.download.assert_not_called()+++def test_download_accepts_relative_dest(client: TestClient, user1_token: str, mock_invoker: Invoker):+ mock_invoker.services.download_queue.download = MagicMock(return_value=_make_job())+ r = client.post(+ "/api/v1/download_queue/i/",+ json={"source": "http://example.com/file.bin", "dest": "models/sd15.safetensors"},+ headers={"Authorization": f"Bearer {user1_token}"},+ )+ assert r.status_code == status.HTTP_200_OK+ mock_invoker.services.download_queue.download.assert_called_once()diff --git a/tests/app/routers/test_model_relationships.py b/tests/app/routers/test_model_relationships.pynew file mode 100644index 0000000000..de78e94f95--- /dev/null+++ b/tests/app/routers/test_model_relationships.py@@ -0,0 +1,156 @@+"""Router-level tests for /api/v1/model_relationships.++Covers:+- Auth gating (CurrentUserOrDefault on read/batch, AdminUserOrDefault on add/remove).+- Bug regression: self-relationship checks must return 400 (not 500 — the previous+ broad `except Exception` swallowed the HTTPException and converted it).+- Service exception mapping: ValueError → 409 on add, 404 on remove.+"""++from typing import Any+from unittest.mock import MagicMock++import pytest+from fastapi import status+from fastapi.testclient import TestClient++from invokeai.app.services.invoker import Invoker++REQ_BODY = {+ "model_key_1": "aa3b247f-90c9-4416-bfcd-aeaa57a5339e",+ "model_key_2": "ac32b914-10ab-496e-a24a-3068724b9c35",+}+++# ----------------------------- Auth gating -----------------------------+++ ("method", "path", "body"),+ [+ ("GET", "/api/v1/model_relationships/i/some-key", None),+ ("POST", "/api/v1/model_relationships/", REQ_BODY),+ ("DELETE", "/api/v1/model_relationships/", REQ_BODY),+ ("POST", "/api/v1/model_relationships/batch", {"model_keys": ["a", "b"]}),+ ],+)+def test_routes_require_auth(enable_multiuser: Any, client: TestClient, method: str, path: str, body: dict | None):+ r = client.request(method, path, json=body)+ assert r.status_code == status.HTTP_401_UNAUTHORIZED+++def test_get_related_models_allowed_for_regular_user(client: TestClient, user1_token: str, mock_invoker: Invoker):+ mock_invoker.services.model_relationships.get_related_model_keys = MagicMock(return_value=["k1"])+ r = client.get(+ "/api/v1/model_relationships/i/some-key",+ headers={"Authorization": f"Bearer {user1_token}"},+ )+ assert r.status_code == status.HTTP_200_OK+ assert r.json() == ["k1"]+++def test_batch_allowed_for_regular_user(client: TestClient, user1_token: str, mock_invoker: Invoker):+ mock_invoker.services.model_relationships.get_related_model_keys = MagicMock(side_effect=lambda k: [f"r-{k}"])+ r = client.post(+ "/api/v1/model_relationships/batch",+ json={"model_keys": ["a", "b"]},+ headers={"Authorization": f"Bearer {user1_token}"},+ )+ assert r.status_code == status.HTTP_200_OK+ assert set(r.json()) == {"r-a", "r-b"}+++def test_add_forbidden_for_regular_user(client: TestClient, user1_token: str, mock_invoker: Invoker):+ r = client.post(+ "/api/v1/model_relationships/",+ json=REQ_BODY,+ headers={"Authorization": f"Bearer {user1_token}"},+ )+ assert r.status_code == status.HTTP_403_FORBIDDEN+ mock_invoker.services.model_relationships.add_model_relationship.assert_not_called()+++def test_remove_forbidden_for_regular_user(client: TestClient, user1_token: str, mock_invoker: Invoker):+ r = client.request(+ "DELETE",+ "/api/v1/model_relationships/",+ json=REQ_BODY,+ headers={"Authorization": f"Bearer {user1_token}"},+ )+ assert r.status_code == status.HTTP_403_FORBIDDEN+ mock_invoker.services.model_relationships.remove_model_relationship.assert_not_called()+++def test_add_allowed_for_admin(client: TestClient, admin_token: str, mock_invoker: Invoker):+ r = client.post(+ "/api/v1/model_relationships/",+ json=REQ_BODY,+ headers={"Authorization": f"Bearer {admin_token}"},+ )+ assert r.status_code == status.HTTP_204_NO_CONTENT+ mock_invoker.services.model_relationships.add_model_relationship.assert_called_once()+++def test_remove_allowed_for_admin(client: TestClient, admin_token: str, mock_invoker: Invoker):+ r = client.request(+ "DELETE",+ "/api/v1/model_relationships/",+ json=REQ_BODY,+ headers={"Authorization": f"Bearer {admin_token}"},+ )+ assert r.status_code == status.HTTP_204_NO_CONTENT+ mock_invoker.services.model_relationships.remove_model_relationship.assert_called_once()+++# ----------------------------- Bug A regression: self-relationship → 400 -----------------------------+++def test_add_self_relationship_returns_400_not_500(client: TestClient, admin_token: str, mock_invoker: Invoker):+ """Before the fix, the inner HTTPException(400) was caught by `except Exception`+ and re-raised as 500."""+ r = client.post(+ "/api/v1/model_relationships/",+ json={"model_key_1": "same-key", "model_key_2": "same-key"},+ headers={"Authorization": f"Bearer {admin_token}"},+ )+ assert r.status_code == status.HTTP_400_BAD_REQUEST+ mock_invoker.services.model_relationships.add_model_relationship.assert_not_called()+++def test_remove_self_relationship_returns_400_not_500(client: TestClient, admin_token: str, mock_invoker: Invoker):+ r = client.request(+ "DELETE",+ "/api/v1/model_relationships/",+ json={"model_key_1": "same-key", "model_key_2": "same-key"},+ headers={"Authorization": f"Bearer {admin_token}"},+ )+ assert r.status_code == status.HTTP_400_BAD_REQUEST+ mock_invoker.services.model_relationships.remove_model_relationship.assert_not_called()+++# ----------------------------- Service exception mapping -----------------------------+++def test_add_value_error_returns_409(client: TestClient, admin_token: str, mock_invoker: Invoker):+ mock_invoker.services.model_relationships.add_model_relationship = MagicMock(+ side_effect=ValueError("relationship already exists")+ )+ r = client.post(+ "/api/v1/model_relationships/",+ json=REQ_BODY,+ headers={"Authorization": f"Bearer {admin_token}"},+ )+ assert r.status_code == status.HTTP_409_CONFLICT+++def test_remove_value_error_returns_404(client: TestClient, admin_token: str, mock_invoker: Invoker):+ mock_invoker.services.model_relationships.remove_model_relationship = MagicMock(+ side_effect=ValueError("relationship not found")+ )+ r = client.request(+ "DELETE",+ "/api/v1/model_relationships/",+ json=REQ_BODY,+ headers={"Authorization": f"Bearer {admin_token}"},+ )+ assert r.status_code == status.HTTP_404_NOT_FOUNDdiff --git a/tests/app/routers/test_multiuser_authorization.py b/tests/app/routers/test_multiuser_authorization.pyindex 3461f37e7e..93a0c71064 100644--- a/tests/app/routers/test_multiuser_authorization.py+++ b/tests/app/routers/test_multiuser_authorization.py@@ -174,6 +174,7 @@ def enable_multiuser(monkeypatch: Any, mock_invoker: Invoker):monkeypatch.setattr("invokeai.app.api.routers.boards.ApiDependencies", mock_deps)monkeypatch.setattr("invokeai.app.api.routers.board_images.ApiDependencies", mock_deps)monkeypatch.setattr("invokeai.app.api.routers.images.ApiDependencies", mock_deps)+ monkeypatch.setattr("invokeai.app.api.routers._access.ApiDependencies", mock_deps)monkeypatch.setattr("invokeai.app.api.routers.workflows.ApiDependencies", mock_deps)monkeypatch.setattr("invokeai.app.api.routers.session_queue.ApiDependencies", mock_deps)monkeypatch.setattr("invokeai.app.api.routers.recall_parameters.ApiDependencies", mock_deps)diff --git a/tests/app/routers/test_style_presets.py b/tests/app/routers/test_style_presets.pynew file mode 100644index 0000000000..5712ec2ef4--- /dev/null+++ b/tests/app/routers/test_style_presets.py@@ -0,0 +1,414 @@+"""Router-level tests for /api/v1/style_presets.++Backed by a real SqliteStylePresetRecordsStorage from the shared conftest, so SQL+filtering and ownership rules are exercised end-to-end. style_preset_image_files+remains a MagicMock — file IO is not under test here.++Covers:+- Auth gating (CurrentUserOrDefault on CRUD/list/image, AdminUserOrDefault on export/import).+- Bug regression: json.JSONDecodeError must surface as 400 (not 500).+- Bug regression: malformed `data` payload after a valid image upload must NOT have+ persisted the image (validation runs before image mutation).+- Cross-user isolation: owner / non-owner / admin / default / public matrix on+ get, list, update, delete, and image fetch.+"""++import io+import json+from typing import Any++import pytest+from fastapi import status+from fastapi.testclient import TestClient+from PIL import Image++from invokeai.app.services.invoker import Invoker+from invokeai.app.services.style_preset_records.style_preset_records_common import (+ PresetData,+ PresetType,+ StylePresetRecordDTO,+ StylePresetWithoutId,+)+++def _png_bytes() -> bytes:+ buf = io.BytesIO()+ Image.new("RGB", (4, 4), color="red").save(buf, format="PNG")+ return buf.getvalue()+++def _user_id(mock_invoker: Invoker, email: str) -> str:+ user = mock_invoker.services.users.get_by_email(email)+ assert user is not None, f"user {email} not seeded"+ return user.user_id+++def _seed(+ mock_invoker: Invoker,+ user_id: str,+ name: str = "P",+ is_public: bool = False,+ preset_type: PresetType = PresetType.User,+) -> StylePresetRecordDTO:+ return mock_invoker.services.style_preset_records.create(+ StylePresetWithoutId(+ name=name,+ preset_data=PresetData(positive_prompt="p", negative_prompt="n"),+ type=preset_type,+ is_public=is_public,+ ),+ user_id=user_id,+ )+++def _auth(token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {token}"}+++def _form(name: str = "X", preset_type: str = "user", is_public: bool = False) -> dict[str, str]:+ return {+ "data": json.dumps(+ {+ "name": name,+ "positive_prompt": "p",+ "negative_prompt": "n",+ "type": preset_type,+ "is_public": is_public,+ }+ )+ }+++# ----------------------------- Auth gating -----------------------------+++ ("method", "path"),+ [+ ("GET", "/api/v1/style_presets/i/preset-1"),+ ("DELETE", "/api/v1/style_presets/i/preset-1"),+ ("GET", "/api/v1/style_presets/"),+ ("GET", "/api/v1/style_presets/i/preset-1/image"),+ ("GET", "/api/v1/style_presets/export"),+ ],+)+def test_simple_routes_require_auth(enable_multiuser: Any, client: TestClient, method: str, path: str):+ r = client.request(method, path)+ assert r.status_code == status.HTTP_401_UNAUTHORIZED+++def test_create_requires_auth(enable_multiuser: Any, client: TestClient):+ r = client.post("/api/v1/style_presets/", data=_form())+ assert r.status_code == status.HTTP_401_UNAUTHORIZED+++def test_update_requires_auth(enable_multiuser: Any, client: TestClient):+ r = client.patch("/api/v1/style_presets/i/preset-1", data=_form())+ assert r.status_code == status.HTTP_401_UNAUTHORIZED+++def test_import_requires_auth(enable_multiuser: Any, client: TestClient):+ r = client.post(+ "/api/v1/style_presets/import",+ files={"file": ("x.csv", b"name,prompt,negative_prompt\n", "text/csv")},+ )+ assert r.status_code == status.HTTP_401_UNAUTHORIZED+++def test_export_forbidden_for_regular_user(client: TestClient, user1_token: str):+ r = client.get("/api/v1/style_presets/export", headers=_auth(user1_token))+ assert r.status_code == status.HTTP_403_FORBIDDEN+++def test_export_allowed_for_admin(client: TestClient, admin_token: str):+ r = client.get("/api/v1/style_presets/export", headers=_auth(admin_token))+ assert r.status_code == status.HTTP_200_OK+++def test_import_forbidden_for_regular_user(client: TestClient, user1_token: str):+ r = client.post(+ "/api/v1/style_presets/import",+ files={"file": ("x.csv", b"name,prompt,negative_prompt\n", "text/csv")},+ headers=_auth(user1_token),+ )+ assert r.status_code == status.HTTP_403_FORBIDDEN+++# ----------------------------- Bug B regression: JSONDecodeError → 400 -----------------------------+++def test_create_malformed_json_returns_400(client: TestClient, user1_token: str, mock_invoker: Invoker):+ r = client.post("/api/v1/style_presets/", data={"data": "not-valid-json"}, headers=_auth(user1_token))+ assert r.status_code == status.HTTP_400_BAD_REQUEST+ # Nothing persisted.+ assert mock_invoker.services.style_preset_records.get_many(user_id=_user_id(mock_invoker, "[email protected]")) == []+++def test_update_malformed_json_returns_400(client: TestClient, user1_token: str, mock_invoker: Invoker):+ # No need for a real record — JSON validation happens before the record is loaded.+ r = client.patch("/api/v1/style_presets/i/some-id", data={"data": "not-valid-json"}, headers=_auth(user1_token))+ assert r.status_code == status.HTTP_400_BAD_REQUEST+++# ----------------------------- Bug C regression: validation before image mutation -----------------------------+++def test_update_with_invalid_data_does_not_save_image(client: TestClient, user1_token: str, mock_invoker: Invoker):+ """A valid image plus malformed `data` must reject (400) AND must not have+ persisted or deleted the preset image — the validation has to run first."""+ r = client.patch(+ "/api/v1/style_presets/i/preset-1",+ data={"data": "not-valid-json"},+ files={"image": ("x.png", _png_bytes(), "image/png")},+ headers=_auth(user1_token),+ )+ assert r.status_code == status.HTTP_400_BAD_REQUEST+ mock_invoker.services.style_preset_image_files.save.assert_not_called()+ mock_invoker.services.style_preset_image_files.delete.assert_not_called()+++def test_update_without_image_and_invalid_data_does_not_delete(+ client: TestClient, user1_token: str, mock_invoker: Invoker+):+ """The pre-fix code would call `delete` on the image even though `data` is invalid."""+ r = client.patch("/api/v1/style_presets/i/preset-1", data={"data": "not-valid-json"}, headers=_auth(user1_token))+ assert r.status_code == status.HTTP_400_BAD_REQUEST+ mock_invoker.services.style_preset_image_files.delete.assert_not_called()+++# ----------------------------- Happy path -----------------------------+++def test_create_with_valid_data_persists_record(client: TestClient, user1_token: str, mock_invoker: Invoker):+ mock_invoker.services.style_preset_image_files.get_url.return_value = None+ r = client.post("/api/v1/style_presets/", data=_form(name="Mine"), headers=_auth(user1_token))+ assert r.status_code == status.HTTP_200_OK+ user1 = _user_id(mock_invoker, "[email protected]")+ presets = mock_invoker.services.style_preset_records.get_many(user_id=user1)+ names = [p.name for p in presets]+ assert "Mine" in names+ # New record is owned by user1.+ owned = [p for p in presets if p.name == "Mine"]+ assert owned[0].user_id == user1+ assert owned[0].is_public is False+++def test_update_with_valid_data_changes_record(client: TestClient, user1_token: str, mock_invoker: Invoker):+ mock_invoker.services.style_preset_image_files.get_url.return_value = None+ user1 = _user_id(mock_invoker, "[email protected]")+ seeded = _seed(mock_invoker, user1, name="Before")++ r = client.patch(+ f"/api/v1/style_presets/i/{seeded.id}",+ data=_form(name="After"),+ headers=_auth(user1_token),+ )+ assert r.status_code == status.HTTP_200_OK+ refreshed = mock_invoker.services.style_preset_records.get(seeded.id)+ assert refreshed.name == "After"+++def test_update_with_non_image_returns_415(client: TestClient, user1_token: str, mock_invoker: Invoker):+ user1 = _user_id(mock_invoker, "[email protected]")+ seeded = _seed(mock_invoker, user1, name="X")+ r = client.patch(+ f"/api/v1/style_presets/i/{seeded.id}",+ data=_form(name="X"),+ files={"image": ("x.txt", b"not an image", "text/plain")},+ headers=_auth(user1_token),+ )+ assert r.status_code == status.HTTP_415_UNSUPPORTED_MEDIA_TYPE+ mock_invoker.services.style_preset_image_files.save.assert_not_called()+++# ----------------------------- Cross-user ownership policy -----------------------------+++class TestOwnership:+ def test_list_returns_only_own_plus_defaults_plus_public(+ self, client: TestClient, user1_token: str, user2_token: str, mock_invoker: Invoker+ ):+ u1 = _user_id(mock_invoker, "[email protected]")+ u2 = _user_id(mock_invoker, "[email protected]")+ _seed(mock_invoker, u1, name="u1-private")+ _seed(mock_invoker, u1, name="u1-public", is_public=True)+ _seed(mock_invoker, u2, name="u2-private")+ _seed(mock_invoker, "system", name="default-A", preset_type=PresetType.Default)++ mock_invoker.services.style_preset_image_files.get_url.return_value = None+ r = client.get("/api/v1/style_presets/", headers=_auth(user1_token))+ assert r.status_code == status.HTTP_200_OK+ names = {p["name"] for p in r.json()}+ assert "u1-private" in names+ assert "u1-public" in names+ assert "default-A" in names+ assert "u2-private" not in names++ def test_list_includes_other_users_public_preset(+ self, client: TestClient, user1_token: str, user2_token: str, mock_invoker: Invoker+ ):+ u1 = _user_id(mock_invoker, "[email protected]")+ _seed(mock_invoker, u1, name="u1-public", is_public=True)+ mock_invoker.services.style_preset_image_files.get_url.return_value = None+ r = client.get("/api/v1/style_presets/", headers=_auth(user2_token))+ assert r.status_code == status.HTTP_200_OK+ names = {p["name"] for p in r.json()}+ assert "u1-public" in names++ def test_get_other_users_private_is_forbidden(+ self, client: TestClient, user1_token: str, user2_token: str, mock_invoker: Invoker+ ):+ u1 = _user_id(mock_invoker, "[email protected]")+ seeded = _seed(mock_invoker, u1, name="private")+ mock_invoker.services.style_preset_image_files.get_url.return_value = None+ r = client.get(f"/api/v1/style_presets/i/{seeded.id}", headers=_auth(user2_token))+ assert r.status_code == status.HTTP_403_FORBIDDEN++ def test_get_other_users_public_is_allowed(+ self, client: TestClient, user1_token: str, user2_token: str, mock_invoker: Invoker+ ):+ u1 = _user_id(mock_invoker, "[email protected]")+ seeded = _seed(mock_invoker, u1, name="pub", is_public=True)+ mock_invoker.services.style_preset_image_files.get_url.return_value = None+ r = client.get(f"/api/v1/style_presets/i/{seeded.id}", headers=_auth(user2_token))+ assert r.status_code == status.HTTP_200_OK+ assert r.json()["name"] == "pub"++ def test_get_default_is_allowed_for_any_user(self, client: TestClient, user1_token: str, mock_invoker: Invoker):+ seeded = _seed(mock_invoker, "system", name="builtin", preset_type=PresetType.Default)+ mock_invoker.services.style_preset_image_files.get_url.return_value = None+ r = client.get(f"/api/v1/style_presets/i/{seeded.id}", headers=_auth(user1_token))+ assert r.status_code == status.HTTP_200_OK++ def test_update_other_users_preset_is_forbidden(+ self, client: TestClient, user1_token: str, user2_token: str, mock_invoker: Invoker+ ):+ u1 = _user_id(mock_invoker, "[email protected]")+ seeded = _seed(mock_invoker, u1, name="orig")+ r = client.patch(+ f"/api/v1/style_presets/i/{seeded.id}",+ data=_form(name="hijack"),+ headers=_auth(user2_token),+ )+ assert r.status_code == status.HTTP_403_FORBIDDEN+ # Even a public preset cannot be modified by a non-owner.+ seeded_public = _seed(mock_invoker, u1, name="orig-pub", is_public=True)+ r = client.patch(+ f"/api/v1/style_presets/i/{seeded_public.id}",+ data=_form(name="hijack-pub"),+ headers=_auth(user2_token),+ )+ assert r.status_code == status.HTTP_403_FORBIDDEN++ def test_delete_other_users_preset_is_forbidden(+ self, client: TestClient, user1_token: str, user2_token: str, mock_invoker: Invoker+ ):+ u1 = _user_id(mock_invoker, "[email protected]")+ seeded = _seed(mock_invoker, u1, name="keep")+ r = client.delete(f"/api/v1/style_presets/i/{seeded.id}", headers=_auth(user2_token))+ assert r.status_code == status.HTTP_403_FORBIDDEN+ # Record is still there.+ still = mock_invoker.services.style_preset_records.get(seeded.id)+ assert still.id == seeded.id++ def test_update_default_preset_forbidden_for_non_admin(+ self, client: TestClient, user1_token: str, mock_invoker: Invoker+ ):+ seeded = _seed(mock_invoker, "system", name="builtin", preset_type=PresetType.Default)+ r = client.patch(+ f"/api/v1/style_presets/i/{seeded.id}",+ data=_form(name="hijacked", preset_type="default"),+ headers=_auth(user1_token),+ )+ assert r.status_code == status.HTTP_403_FORBIDDEN++ def test_delete_default_preset_forbidden_for_non_admin(+ self, client: TestClient, user1_token: str, mock_invoker: Invoker+ ):+ seeded = _seed(mock_invoker, "system", name="builtin", preset_type=PresetType.Default)+ r = client.delete(f"/api/v1/style_presets/i/{seeded.id}", headers=_auth(user1_token))+ assert r.status_code == status.HTTP_403_FORBIDDEN++ def test_create_default_preset_forbidden_for_non_admin(+ self, client: TestClient, user1_token: str, mock_invoker: Invoker+ ):+ mock_invoker.services.style_preset_image_files.get_url.return_value = None+ r = client.post(+ "/api/v1/style_presets/",+ data=_form(name="Sneaky", preset_type="default"),+ headers=_auth(user1_token),+ )+ assert r.status_code == status.HTTP_403_FORBIDDEN++ def test_admin_can_get_any_preset(+ self, client: TestClient, admin_token: str, user1_token: str, mock_invoker: Invoker+ ):+ u1 = _user_id(mock_invoker, "[email protected]")+ seeded = _seed(mock_invoker, u1, name="private")+ mock_invoker.services.style_preset_image_files.get_url.return_value = None+ r = client.get(f"/api/v1/style_presets/i/{seeded.id}", headers=_auth(admin_token))+ assert r.status_code == status.HTTP_200_OK++ def test_admin_can_update_any_preset(+ self, client: TestClient, admin_token: str, user1_token: str, mock_invoker: Invoker+ ):+ u1 = _user_id(mock_invoker, "[email protected]")+ seeded = _seed(mock_invoker, u1, name="orig")+ mock_invoker.services.style_preset_image_files.get_url.return_value = None+ r = client.patch(+ f"/api/v1/style_presets/i/{seeded.id}",+ data=_form(name="admin-edit"),+ headers=_auth(admin_token),+ )+ assert r.status_code == status.HTTP_200_OK+ assert mock_invoker.services.style_preset_records.get(seeded.id).name == "admin-edit"++ def test_admin_can_delete_default_preset(self, client: TestClient, admin_token: str, mock_invoker: Invoker):+ seeded = _seed(mock_invoker, "system", name="del-default", preset_type=PresetType.Default)+ r = client.delete(f"/api/v1/style_presets/i/{seeded.id}", headers=_auth(admin_token))+ # delete returns 200 with no body (operation_id has no explicit status_code)+ assert r.status_code in (status.HTTP_200_OK, status.HTTP_204_NO_CONTENT)++ def test_admin_list_returns_everything(+ self, client: TestClient, admin_token: str, user1_token: str, user2_token: str, mock_invoker: Invoker+ ):+ u1 = _user_id(mock_invoker, "[email protected]")+ u2 = _user_id(mock_invoker, "[email protected]")+ _seed(mock_invoker, u1, name="u1-only")+ _seed(mock_invoker, u2, name="u2-only")+ mock_invoker.services.style_preset_image_files.get_url.return_value = None+ r = client.get("/api/v1/style_presets/", headers=_auth(admin_token))+ names = {p["name"] for p in r.json()}+ assert {"u1-only", "u2-only"}.issubset(names)++ def test_owner_can_flip_to_public(+ self, client: TestClient, user1_token: str, user2_token: str, mock_invoker: Invoker+ ):+ u1 = _user_id(mock_invoker, "[email protected]")+ seeded = _seed(mock_invoker, u1, name="will-be-public")+ mock_invoker.services.style_preset_image_files.get_url.return_value = None+ # user2 can't see it yet+ r = client.get("/api/v1/style_presets/", headers=_auth(user2_token))+ assert "will-be-public" not in {p["name"] for p in r.json()}++ # user1 flips is_public=True+ r = client.patch(+ f"/api/v1/style_presets/i/{seeded.id}",+ data=_form(name="will-be-public", is_public=True),+ headers=_auth(user1_token),+ )+ assert r.status_code == status.HTTP_200_OK+ assert r.json()["is_public"] is True++ # user2 now sees it+ r = client.get("/api/v1/style_presets/", headers=_auth(user2_token))+ assert "will-be-public" in {p["name"] for p in r.json()}++ def test_image_fetch_enforces_same_policy_as_get(+ self, client: TestClient, user1_token: str, user2_token: str, mock_invoker: Invoker+ ):+ u1 = _user_id(mock_invoker, "[email protected]")+ seeded = _seed(mock_invoker, u1, name="img-private")+ r = client.get(f"/api/v1/style_presets/i/{seeded.id}/image", headers=_auth(user2_token))+ assert r.status_code == status.HTTP_403_FORBIDDEN+ mock_invoker.services.style_preset_image_files.get_path.assert_not_called()diff --git a/tests/app/routers/test_utilities.py b/tests/app/routers/test_utilities.pynew file mode 100644index 0000000000..ce91f2efd2--- /dev/null+++ b/tests/app/routers/test_utilities.py@@ -0,0 +1,129 @@+"""Router-level tests for /api/v1/utilities.++Covers:+- Auth gating (CurrentUserOrDefault on all three utility routes).+- image-to-prompt: image read-access check must fire BEFORE the model is loaded,+ so non-owners can't probe stored images.+- image-to-prompt: a missing image surfaces as 404, not 500.+"""++from typing import Any+from unittest.mock import MagicMock++import pytest+from fastapi import status+from fastapi.testclient import TestClient++from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin+from invokeai.app.services.invoker import Invoker+++def _save_image(mock_invoker: Invoker, image_name: str, user_id: str) -> None:+ mock_invoker.services.image_records.save(+ image_name=image_name,+ image_origin=ResourceOrigin.INTERNAL,+ image_category=ImageCategory.GENERAL,+ width=100,+ height=100,+ has_workflow=False,+ user_id=user_id,+ )+++def _create_extra_user(mock_invoker: Invoker, email: str) -> str:+ from invokeai.app.services.users.users_common import UserCreateRequest++ user = mock_invoker.services.users.create(+ UserCreateRequest(email=email, display_name=email, password="TestPass123", is_admin=False)+ )+ return user.user_id+++# ----------------------------- Auth gating -----------------------------+++ "path,body",+ [+ ("/api/v1/utilities/dynamicprompts", {"prompt": "hi"}),+ ("/api/v1/utilities/expand-prompt", {"prompt": "hi", "model_key": "m"}),+ ("/api/v1/utilities/image-to-prompt", {"image_name": "img-1", "model_key": "m"}),+ ],+)+def test_routes_require_auth(enable_multiuser: Any, client: TestClient, mock_invoker: Invoker, path: str, body: dict):+ r = client.post(path, json=body)+ assert r.status_code == status.HTTP_401_UNAUTHORIZED+ mock_invoker.services.model_manager.store.get_model.assert_not_called()+++def test_dynamicprompts_works_for_user(client: TestClient, user1_token: str):+ r = client.post(+ "/api/v1/utilities/dynamicprompts",+ json={"prompt": "a {b|c}"},+ headers={"Authorization": f"Bearer {user1_token}"},+ )+ assert r.status_code == status.HTTP_200_OK+ body = r.json()+ assert "prompts" in body+++# ----------------------------- image_to_prompt: ownership / read-access -----------------------------+++def test_image_to_prompt_forbidden_for_non_owner(+ client: TestClient, user1_token: str, user2_token: str, mock_invoker: Invoker+):+ """A second user must not be able to read a private image via image-to-prompt."""+ # Need to discover user1's id, then save an image under that id.+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None+ _save_image(mock_invoker, "private-img.png", user1.user_id)++ r = client.post(+ "/api/v1/utilities/image-to-prompt",+ json={"image_name": "private-img.png", "model_key": "some-key"},+ headers={"Authorization": f"Bearer {user2_token}"},+ )+ assert r.status_code == status.HTTP_403_FORBIDDEN+ # The model must not have been loaded — ownership must fire BEFORE inference.+ mock_invoker.services.model_manager.store.get_model.assert_not_called()+++def test_image_to_prompt_owner_reaches_model_load(client: TestClient, user1_token: str, mock_invoker: Invoker):+ """The owner passes the read-access check and the model load is attempted.+ We force an UnknownModelException to keep the test light and assert 404."""+ from invokeai.app.services.model_records.model_records_base import UnknownModelException++ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None+ _save_image(mock_invoker, "owned-img.png", user1.user_id)++ mock_invoker.services.model_manager.store.get_model = MagicMock(side_effect=UnknownModelException("no such model"))++ r = client.post(+ "/api/v1/utilities/image-to-prompt",+ json={"image_name": "owned-img.png", "model_key": "missing-model"},+ headers={"Authorization": f"Bearer {user1_token}"},+ )+ assert r.status_code == status.HTTP_404_NOT_FOUND+ mock_invoker.services.model_manager.store.get_model.assert_called_once()+++def test_image_to_prompt_admin_can_access_any_image(+ client: TestClient, admin_token: str, user1_token: str, mock_invoker: Invoker+):+ from invokeai.app.services.model_records.model_records_base import UnknownModelException++ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None+ _save_image(mock_invoker, "user1-img.png", user1.user_id)++ mock_invoker.services.model_manager.store.get_model = MagicMock(side_effect=UnknownModelException("no model"))++ r = client.post(+ "/api/v1/utilities/image-to-prompt",+ json={"image_name": "user1-img.png", "model_key": "x"},+ headers={"Authorization": f"Bearer {admin_token}"},+ )+ # Admin passes the read-access check; model loading then fails with 404.+ assert r.status_code == status.HTTP_404_NOT_FOUNDdiff --git a/tests/app/routers/test_virtual_boards.py b/tests/app/routers/test_virtual_boards.pynew file mode 100644index 0000000000..42ae0be778--- /dev/null+++ b/tests/app/routers/test_virtual_boards.py@@ -0,0 +1,81 @@+"""Router-level tests for /api/v1/virtual_boards.++These routes already use CurrentUserOrDefault, but until now had no tests pinning+the anonymous-rejection + per-user filtering behavior.+"""++from typing import Any++from fastapi import status+from fastapi.testclient import TestClient++from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOrigin+from invokeai.app.services.invoker import Invoker+++def _save_image(mock_invoker: Invoker, image_name: str, user_id: str) -> None:+ mock_invoker.services.image_records.save(+ image_name=image_name,+ image_origin=ResourceOrigin.INTERNAL,+ image_category=ImageCategory.GENERAL,+ width=10,+ height=10,+ has_workflow=False,+ user_id=user_id,+ )+++def test_list_by_date_requires_auth(enable_multiuser: Any, client: TestClient):+ r = client.get("/api/v1/virtual_boards/by_date")+ assert r.status_code == status.HTTP_401_UNAUTHORIZED+++def test_image_names_by_date_requires_auth(enable_multiuser: Any, client: TestClient):+ r = client.get("/api/v1/virtual_boards/by_date/2026-05-18/image_names")+ assert r.status_code == status.HTTP_401_UNAUTHORIZED+++def test_user_sees_only_own_dates(client: TestClient, user1_token: str, user2_token: str, mock_invoker: Invoker):+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ user2 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None and user2 is not None++ _save_image(mock_invoker, "u1-img-a.png", user1.user_id)+ _save_image(mock_invoker, "u2-img-a.png", user2.user_id)++ r1 = client.get(+ "/api/v1/virtual_boards/by_date",+ headers={"Authorization": f"Bearer {user1_token}"},+ )+ assert r1.status_code == status.HTTP_200_OK+ user1_counts = sum(b.get("image_count", 0) for b in r1.json())++ r2 = client.get(+ "/api/v1/virtual_boards/by_date",+ headers={"Authorization": f"Bearer {user2_token}"},+ )+ assert r2.status_code == status.HTTP_200_OK+ user2_counts = sum(b.get("image_count", 0) for b in r2.json())++ # Each user sees only their single image — not the other user's.+ assert user1_counts == 1+ assert user2_counts == 1+++def test_admin_sees_all_dates(+ client: TestClient, admin_token: str, user1_token: str, user2_token: str, mock_invoker: Invoker+):+ user1 = mock_invoker.services.users.get_by_email("[email protected]")+ user2 = mock_invoker.services.users.get_by_email("[email protected]")+ assert user1 is not None and user2 is not None++ _save_image(mock_invoker, "u1-shared.png", user1.user_id)+ _save_image(mock_invoker, "u2-shared.png", user2.user_id)++ r = client.get(+ "/api/v1/virtual_boards/by_date",+ headers={"Authorization": f"Bearer {admin_token}"},+ )+ assert r.status_code == status.HTTP_200_OK+ total = sum(b.get("image_count", 0) for b in r.json())+ assert total >= 2 # admin sees images from both users