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 Steinfd22e89c6c08
diff --git a/invokeai/app/api/sockets.py b/invokeai/app/api/sockets.pyindex f96d02057f..37534bef5a 100644--- a/invokeai/app/api/sockets.py+++ b/invokeai/app/api/sockets.py@@ -88,6 +88,15 @@ SOCKET_REVALIDATION_INTERVAL_SECONDS = 30.0SOCKET_REVALIDATION_FAILURE_LIMIT = 3+# Client-chosen ids must never be able to name a privileged room (`admin`, `user:<id>`, a sid).+def _queue_room(queue_id: str) -> str:+ return f"queue:{queue_id}"+++def _bulk_download_room(bulk_download_id: str) -> str:+ return f"bulk_download:{bulk_download_id}"++class QueueSubscriptionEvent(BaseModel):"""Event data for subscribing to the socket.io queue room.This is a pydantic model to ensure the data is in the correct format."""@@ -829,7 +838,7 @@ class SocketIO:is_admin = self._socket_users[sid]["is_admin"]# Add socket to the queue room- await self._sio.enter_room(sid, queue_id)+ await self._sio.enter_room(sid, _queue_room(queue_id))# Also add socket to a user-specific room for event filteringuser_room = f"user:{user_id}"@@ -864,7 +873,7 @@ class SocketIO:)async def _handle_unsub_queue(self, sid: str, data: Any) -> None:- await self._sio.leave_room(sid, QueueSubscriptionEvent(**data).queue_id)+ await self._sio.leave_room(sid, _queue_room(QueueSubscriptionEvent(**data).queue_id))async def _handle_sub_bulk_download(self, sid: str, data: Any) -> None:# In multiuser mode, only allow authenticated sockets to subscribe.@@ -874,10 +883,10 @@ class SocketIO:if self._is_multiuser_enabled() and sid not in self._socket_users:logger.warning(f"Refusing bulk download subscription for unknown socket {sid} in multiuser mode")return- await self._sio.enter_room(sid, BulkDownloadSubscriptionEvent(**data).bulk_download_id)+ await self._sio.enter_room(sid, _bulk_download_room(BulkDownloadSubscriptionEvent(**data).bulk_download_id))async def _handle_unsub_bulk_download(self, sid: str, data: Any) -> None:- await self._sio.leave_room(sid, BulkDownloadSubscriptionEvent(**data).bulk_download_id)+ await self._sio.leave_room(sid, _bulk_download_room(BulkDownloadSubscriptionEvent(**data).bulk_download_id))def _admin_sids(self) -> list[str]:"""Sids belonging to admin sockets."""@@ -952,7 +961,7 @@ class SocketIO:await self._sio.emit(event=event_name,data=sanitized.model_dump(mode="json"),- room=event_data.queue_id,+ room=_queue_room(event_data.queue_id),skip_sid=self._owner_and_admin_sids(event_data.user_ids),)logger.debug(@@ -1055,7 +1064,7 @@ class SocketIO:await self._sio.emit(event=event_name,data=sanitized.model_dump(mode="json"),- room=event_data.queue_id,+ room=_queue_room(event_data.queue_id),skip_sid=self._owner_and_admin_sids(event_data.user_id),)@@ -1114,7 +1123,7 @@ class SocketIO:await self._sio.emit(event=event_name,data=sanitized.model_dump(mode="json"),- room=event_data.queue_id,+ room=_queue_room(event_data.queue_id),skip_sid=self._owner_and_admin_sids(event_data.user_id),)logger.debug(@@ -1148,7 +1157,7 @@ class SocketIO:elif isinstance(event_data, QueueClearedEvent):if event_data.user_id is None:await self._sio.emit(- event=event_name, data=event_data.model_dump(mode="json"), room=event_data.queue_id+ event=event_name, data=event_data.model_dump(mode="json"), room=_queue_room(event_data.queue_id))logger.debug(f"Emitted unscoped queue_cleared to all subscribers in queue {event_data.queue_id}")else:@@ -1160,7 +1169,7 @@ class SocketIO:await self._sio.emit(event=event_name,data=sanitized.model_dump(mode="json"),- room=event_data.queue_id,+ room=_queue_room(event_data.queue_id),skip_sid=self._owner_and_admin_sids(event_data.user_id),)logger.debug(@@ -1186,7 +1195,7 @@ class SocketIO:)else:await self._sio.emit(- event=event_name, data=event_data.model_dump(mode="json"), room=event_data.queue_id+ event=event_name, data=event_data.model_dump(mode="json"), room=_queue_room(event_data.queue_id))logger.debug(f"Emitted general queue event {event_name} to all subscribers in queue {event_data.queue_id}"@@ -1309,7 +1318,9 @@ class SocketIO:await self._sio.emit(event=event_name, data=event_data.model_dump(mode="json"), room="admin")else:await self._sio.emit(- event=event_name, data=event_data.model_dump(mode="json"), room=event_data.bulk_download_id+ event=event_name,+ data=event_data.model_dump(mode="json"),+ room=_bulk_download_room(event_data.bulk_download_id),)async def _handle_workflow_event(self, event: FastAPIEvent[WorkflowEventBase]) -> None:diff --git a/tests/app/routers/test_multiuser_authorization.py b/tests/app/routers/test_multiuser_authorization.pyindex 339ba3ae4b..ca5f847a8a 100644--- a/tests/app/routers/test_multiuser_authorization.py+++ b/tests/app/routers/test_multiuser_authorization.py@@ -2687,8 +2687,7 @@ class TestBulkDownloadAccessControl:asyncio.run(socketio._handle_bulk_image_download_event(("bulk_download_complete", event)))rooms_emitted_to = [call.kwargs.get("room") for call in mock_emit.call_args_list]- assert "default" not in rooms_emitted_to- assert "user:owner-xyz" in rooms_emitted_to+ assert set(rooms_emitted_to) == {"user:owner-xyz", "admin"}# ===========================================================================@@ -2970,7 +2969,7 @@ class TestWebSocketAuth:assert payload["destination"] == "canvas"# A sanitized companion event must go to the queue_id room with sensitive fields cleared- queue_emits = [(p, s) for r, p, s in emits if r == "default"]+ queue_emits = [(p, s) for r, p, s in emits if r == "queue:default"]assert len(queue_emits) == 1, "expected exactly one sanitized emit to queue room"sanitized_payload, skip_sid = queue_emits[0]assert sanitized_payload["user_id"] == "redacted"@@ -3041,7 +3040,7 @@ class TestWebSocketAuth:assert payload["origin"] == "workflows"# Sanitized event to queue room: user/batch/origin redacted, owner+admin skipped- queue_emits = [(p, s) for r, p, s in emits if r == "default"]+ queue_emits = [(p, s) for r, p, s in emits if r == "queue:default"]assert len(queue_emits) == 1sanitized_payload, skip_sid = queue_emits[0]assert sanitized_payload["user_id"] == "redacted"@@ -3097,7 +3096,9 @@ class TestWebSocketAuth:# CRITICAL: nothing identifying may reach the queue room. The only emit there is the# sanitized companion, which must not name any owner or any retried item.- queue_room_payloads = [c.kwargs["data"] for c in mock_emit.call_args_list if c.kwargs.get("room") == "default"]+ queue_room_payloads = [+ c.kwargs["data"] for c in mock_emit.call_args_list if c.kwargs.get("room") == "queue:default"+ ]assert len(queue_room_payloads) == 1assert queue_room_payloads[0]["retried_item_ids"] == []assert queue_room_payloads[0]["user_ids"] == []@@ -3132,7 +3133,7 @@ class TestWebSocketAuth:asyncio.run(socketio._handle_queue_event(("queue_items_retried", event)))- queue_emits = [c for c in mock_emit.call_args_list if c.kwargs.get("room") == "default"]+ queue_emits = [c for c in mock_emit.call_args_list if c.kwargs.get("room") == "queue:default"]assert len(queue_emits) == 1, "expected exactly one sanitized emit to the queue room"payload = queue_emits[0].kwargs["data"]skip_sid = queue_emits[0].kwargs["skip_sid"]@@ -3196,7 +3197,7 @@ class TestWebSocketAuth:assert owner_123_calls[0].kwargs["data"]["retried_items"] == [{"source_item_id": 10, "item_id": 30}]assert owner_456_calls[0].kwargs["data"]["retried_items"] == [{"source_item_id": 20, "item_id": 31}]assert len(admin_calls[0].kwargs["data"]["retried_items"]) == 2- sanitized_calls = [call for call in mock_emit.call_args_list if call.kwargs.get("room") == "default"]+ sanitized_calls = [call for call in mock_emit.call_args_list if call.kwargs.get("room") == "queue:default"]assert sanitized_calls[0].kwargs["data"]["retried_items"] == []def test_queue_items_canceled_routed_privately_per_owner(self, socketio: Any) -> None:@@ -3239,7 +3240,9 @@ class TestWebSocketAuth:# Nothing identifying may reach the queue room: the only emit there is the sanitized# companion, which must not name any owner or any canceled item.- queue_room_payloads = [c.kwargs["data"] for c in mock_emit.call_args_list if c.kwargs.get("room") == "default"]+ queue_room_payloads = [+ c.kwargs["data"] for c in mock_emit.call_args_list if c.kwargs.get("room") == "queue:default"+ ]assert len(queue_room_payloads) == 1assert queue_room_payloads[0]["canceled_item_ids"] == []assert queue_room_payloads[0]["user_ids"] == []@@ -3271,7 +3274,7 @@ class TestWebSocketAuth:asyncio.run(socketio._handle_queue_event(("queue_items_canceled", event)))- queue_emits = [c for c in mock_emit.call_args_list if c.kwargs.get("room") == "default"]+ queue_emits = [c for c in mock_emit.call_args_list if c.kwargs.get("room") == "queue:default"]assert len(queue_emits) == 1, "expected exactly one sanitized emit to the queue room"payload = queue_emits[0].kwargs["data"]skip_sid = queue_emits[0].kwargs["skip_sid"]@@ -3341,7 +3344,7 @@ class TestWebSocketAuth:asyncio.run(socketio._handle_queue_event(("queue_cleared", event)))assert len(mock_emit.call_args_list) == 1- assert mock_emit.call_args_list[0].kwargs.get("room") == "default"+ assert mock_emit.call_args_list[0].kwargs.get("room") == "queue:default"assert mock_emit.call_args_list[0].kwargs.get("data")["user_id"] is Nonedef test_user_scoped_queue_cleared_routed_privately(self, socketio: Any) -> None:@@ -3377,7 +3380,7 @@ class TestWebSocketAuth:assert private_emits[0][0]["user_id"] == "owner-xyz"# Sanitized companion goes to the queue room, skipping the owner's and admins' sids- queue_emits = [(p, s) for r, p, s in emits if r == "default"]+ queue_emits = [(p, s) for r, p, s in emits if r == "queue:default"]assert len(queue_emits) == 1, "expected exactly one sanitized emit to queue room"sanitized_payload, skip_sid = queue_emits[0]assert sanitized_payload["user_id"] == "redacted"@@ -3421,7 +3424,7 @@ class TestWebSocketAuth:assert isinstance(room, list)assert set(room) == {"user:owner-recall", "admin"}# And never to the shared queue room, which would leak to other users.- assert "default" not in room+ assert "queue:default" not in roomdef test_video_recall_is_emitted_once_to_the_owner_only(self, socketio: Any) -> None:"""A video recall names the owner's media and no admin UI consumes it, so it goes to thediff --git a/tests/app/test_socket_privilege_revocation.py b/tests/app/test_socket_privilege_revocation.pyindex b094c0b566..b9f0f4c11e 100644--- a/tests/app/test_socket_privilege_revocation.py+++ b/tests/app/test_socket_privilege_revocation.py@@ -15,9 +15,16 @@ from unittest.mock import AsyncMockimport pytestfrom fastapi import FastAPI+from socketio.packet import Packetfrom invokeai.app.api.sockets import SOCKET_REVALIDATION_FAILURE_LIMIT, SocketIO-from invokeai.app.services.events.events_common import UserAccessChangedEvent+from invokeai.app.services.events.events_common import (+ BulkDownloadCompleteEvent,+ InvocationCompleteEvent,+ ModelInstallStartedEvent,+ QueueClearedEvent,+ UserAccessChangedEvent,+)from invokeai.app.services.progress_previews.progress_previews_default import MemoryProgressPreviews@@ -1246,3 +1253,204 @@ class TestHandlerRereadsAtThePointOfDecision:socketio._sio.enter_room.assert_not_awaited()socketio._sio.leave_room.assert_awaited_once_with("sid-1", "admin")assert socketio._socket_users["sid-1"]["is_admin"] is False+++class TestClientNamedRoomsCannotReachPrivilegedRooms:+ """Queue and bulk-download ids are chosen by the client; they must not name a privileged room.++ Uses python-socketio's real room manager so the assertion is about actual membership.+ """++ @staticmethod+ async def _connect(socketio: SocketIO, eio_sid: str) -> str:+ sid = socketio._sio.manager.connect(eio_sid, "/")+ return (await sid) if asyncio.iscoroutine(sid) else sid++ @classmethod+ async def _connect_non_admin(cls, socketio: SocketIO) -> str:+ sid = await cls._connect(socketio, "eio-attacker")+ socketio._socket_users[sid] = {"user_id": "attacker", "is_admin": False, "authenticated": True}+ return sid++ @staticmethod+ async def _subscribe(socketio: SocketIO, sid: str, kind: str, room_id: str) -> None:+ if kind == "queue":+ await socketio._handle_sub_queue(sid, {"queue_id": room_id})+ else:+ await socketio._handle_sub_bulk_download(sid, {"bulk_download_id": room_id})++ @staticmethod+ def _deliveries(transport: AsyncMock) -> dict[str, list[list]]:+ deliveries: dict[str, list[list]] = {}+ for call in transport.await_args_list:+ eio_sid, packet = call.args+ deliveries.setdefault(eio_sid, []).append(Packet(encoded_packet=packet.data).data)+ return deliveries++ @pytest.mark.anyio+ @pytest.mark.parametrize("handler", ["queue", "bulk_download"])+ async def test_hostile_subscriptions_cannot_receive_private_events(+ self, monkeypatch: pytest.MonkeyPatch, handler: str+ ) -> None:+ monkeypatch.setattr("invokeai.app.api.dependencies.ApiDependencies.invoker", None, raising=False)+ socketio = SocketIO(FastAPI())+ socketio._is_multiuser_enabled = lambda: True+ transport = AsyncMock()+ socketio._sio._send_eio_packet = transport+ victim_sid = await self._connect(socketio, "eio-victim")+ admin_sid = await self._connect(socketio, "eio-admin")+ await socketio._sio.enter_room(victim_sid, "user:victim")+ await socketio._sio.enter_room(admin_sid, "admin")+ attacker_sid = await self._connect_non_admin(socketio)++ for hostile_id in ("admin", "user:victim", victim_sid):+ await self._subscribe(socketio, attacker_sid, handler, hostile_id)++ invocation = InvocationCompleteEvent(+ queue_id="default",+ item_id=1,+ batch_id="private-batch",+ user_id="victim",+ session_id="private-session",+ invocation={"type": "add", "id": "node-1", "a": 1, "b": 2},+ invocation_source_id="node-1",+ result={"type": "integer_output", "value": 3},+ )+ install = ModelInstallStartedEvent(id=1, source={"type": "url", "url": "https://example.com/model"})+ await socketio._handle_queue_event(("invocation_complete", invocation))+ await socketio._handle_model_event(("model_install_started", install))+ await socketio._sio.emit("private_socket_reply", {"secret": "victim-only"}, to=victim_sid)++ assert self._deliveries(transport) == {+ "eio-victim": [+ ["invocation_complete", invocation.model_dump(mode="json")],+ ["private_socket_reply", {"secret": "victim-only"}],+ ],+ "eio-admin": [+ ["invocation_complete", invocation.model_dump(mode="json")],+ ["model_install_started", install.model_dump(mode="json")],+ ],+ }++ @pytest.mark.anyio+ @pytest.mark.parametrize("handler", ["queue", "bulk_download"])+ async def test_hostile_unsubscriptions_preserve_server_owned_rooms(self, handler: str) -> None:+ socketio = SocketIO(FastAPI())+ sid = await self._connect(socketio, "eio-victim")+ for room in ("user:victim", "admin", "workflows:shared"):+ await socketio._sio.enter_room(sid, room)+ server_rooms = set(socketio._sio.manager.get_rooms(sid, "/"))++ for hostile_id in ("user:victim", "admin", "workflows:shared", sid):+ if handler == "queue":+ await socketio._handle_unsub_queue(sid, {"queue_id": hostile_id})+ else:+ await socketio._handle_unsub_bulk_download(sid, {"bulk_download_id": hostile_id})++ assert set(socketio._sio.manager.get_rooms(sid, "/")) == server_rooms++ @pytest.mark.anyio+ async def test_queue_subscriber_receives_only_sanitized_companion_and_can_unsubscribe(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr("invokeai.app.api.dependencies.ApiDependencies.invoker", None, raising=False)+ socketio = SocketIO(FastAPI())+ socketio._is_multiuser_enabled = lambda: True+ transport = AsyncMock()+ socketio._sio._send_eio_packet = transport+ subscriber_sid = await self._connect_non_admin(socketio)+ await socketio._handle_sub_queue(subscriber_sid, {"queue_id": "default"})+ bulk_sid = await self._connect(socketio, "eio-bulk")+ socketio._socket_users[bulk_sid] = {"user_id": "other", "is_admin": False}+ await socketio._handle_sub_bulk_download(bulk_sid, {"bulk_download_id": "default"})+ event = QueueClearedEvent(queue_id="default", user_id="victim")++ await socketio._handle_queue_event(("queue_cleared", event))++ assert self._deliveries(transport) == {+ "eio-attacker": [["queue_cleared", {**event.model_dump(mode="json"), "user_id": "redacted"}]]+ }+ await socketio._handle_unsub_queue(subscriber_sid, {"queue_id": "default"})+ transport.reset_mock()+ await socketio._handle_queue_event(("queue_cleared", event))+ transport.assert_not_awaited()++ @pytest.mark.anyio+ @pytest.mark.parametrize("handler", ["queue", "bulk_download"])+ @pytest.mark.parametrize("hostile_id", ["admin", "user:victim", "workflows:shared"])+ async def test_subscription_cannot_join_privileged_room(+ self, monkeypatch: pytest.MonkeyPatch, handler: str, hostile_id: str+ ) -> None:+ monkeypatch.setattr("invokeai.app.api.dependencies.ApiDependencies.invoker", None, raising=False)+ socketio = SocketIO(FastAPI())+ socketio._is_multiuser_enabled = lambda: True+ sid = await self._connect_non_admin(socketio)++ await self._subscribe(socketio, sid, handler, hostile_id)++ rooms = socketio._sio.manager.get_rooms(sid, "/")+ assert "admin" not in rooms+ assert "user:victim" not in rooms+ assert "workflows:shared" not in rooms+ assert f"{handler}:{hostile_id}" in rooms++ @pytest.mark.anyio+ @pytest.mark.parametrize("handler", ["queue", "bulk_download"])+ async def test_subscription_cannot_join_another_sockets_sid_room(+ self, monkeypatch: pytest.MonkeyPatch, handler: str+ ) -> None:+ monkeypatch.setattr("invokeai.app.api.dependencies.ApiDependencies.invoker", None, raising=False)+ socketio = SocketIO(FastAPI())+ socketio._is_multiuser_enabled = lambda: True+ victim_sid = await self._connect(socketio, "eio-victim")+ sid = await self._connect_non_admin(socketio)++ await self._subscribe(socketio, sid, handler, victim_sid)++ assert victim_sid not in socketio._sio.manager.get_rooms(sid, "/")+ assert f"{handler}:{victim_sid}" in socketio._sio.manager.get_rooms(sid, "/")++ @pytest.mark.anyio+ async def test_default_queue_subscription_lands_in_namespaced_room(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("invokeai.app.api.dependencies.ApiDependencies.invoker", None, raising=False)+ socketio = SocketIO(FastAPI())+ socketio._is_multiuser_enabled = lambda: True+ sid = await self._connect_non_admin(socketio)++ await socketio._handle_sub_queue(sid, {"queue_id": "default"})+ assert {"queue:default", "user:attacker"} <= set(socketio._sio.manager.get_rooms(sid, "/"))++ await socketio._handle_unsub_queue(sid, {"queue_id": "default"})+ assert "queue:default" not in socketio._sio.manager.get_rooms(sid, "/")++ @pytest.mark.anyio+ async def test_bulk_download_subscription_round_trips_through_namespaced_room(self) -> None:+ socketio = SocketIO(FastAPI())+ socketio._is_multiuser_enabled = lambda: True+ sid = await self._connect_non_admin(socketio)++ await socketio._handle_sub_bulk_download(sid, {"bulk_download_id": "dl-1"})+ assert "bulk_download:dl-1" in socketio._sio.manager.get_rooms(sid, "/")++ await socketio._handle_unsub_bulk_download(sid, {"bulk_download_id": "dl-1"})+ assert "bulk_download:dl-1" not in socketio._sio.manager.get_rooms(sid, "/")++ @pytest.mark.anyio+ async def test_single_user_bulk_download_event_targets_namespaced_room(self) -> None:+ socketio = SocketIO(FastAPI())+ socketio._is_multiuser_enabled = lambda: False+ transport = AsyncMock()+ socketio._sio._send_eio_packet = transport+ sid = await self._connect(socketio, "eio-bulk")+ await socketio._handle_sub_bulk_download(sid, {"bulk_download_id": "queue:default"})+ queue_sid = await self._connect(socketio, "eio-queue")+ await socketio._sio.enter_room(queue_sid, "queue:default")+ event = BulkDownloadCompleteEvent.build("queue:default", "item-1", "item-1.zip", user_id="system")++ await socketio._handle_bulk_image_download_event(("bulk_download_complete", event))++ assert self._deliveries(transport) == {"eio-bulk": [["bulk_download_complete", event.model_dump(mode="json")]]}+ await socketio._handle_unsub_bulk_download(sid, {"bulk_download_id": "queue:default"})+ transport.reset_mock()+ await socketio._handle_bulk_image_download_event(("bulk_download_complete", event))+ transport.assert_not_awaited()