Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(webv2): authenticate media requests with the login cookie

joshistoast3432f7703e63
diff --git a/invokeai/frontend/webv2/src/features/identity/data/api.ts b/invokeai/frontend/webv2/src/features/identity/data/api.ts
index 176739e3df..36c68fd457 100644
--- a/invokeai/frontend/webv2/src/features/identity/data/api.ts
+++ b/invokeai/frontend/webv2/src/features/identity/data/api.ts
@@ -72,6 +72,18 @@ export const login = (request: LoginRequest, signal?: AbortSignal): Promise<Logi
export const logout = (): Promise<{ success: boolean }> =>
apiFetchJson<{ success: boolean }>(`${AUTH_BASE}/logout`, { method: 'POST' });
+/**
+ * Re-issues the HttpOnly cookie that authenticates `<img>` / `<video>` media requests.
+ *
+ * Login sets the cookie, but a session restored from stored-token state has a valid JWT and
+ * no cookie — it may predate the cookie, or the cookie may have been cleared while the token
+ * survived. Media elements cannot send an Authorization header, so such a session loads every
+ * other API call fine while showing blank thumbnails. In single-user mode the backend returns
+ * success without setting anything, so this is a safe no-op there.
+ */
+export const refreshMediaCookie = (signal?: AbortSignal): Promise<{ success: boolean }> =>
+ apiFetchJson<{ success: boolean }>(`${AUTH_BASE}/media-cookie`, { method: 'POST', signal });
+
export const getCurrentUser = (): Promise<UserDTO> => apiFetchJson<UserDTO>(`${AUTH_BASE}/me`);
export const setupAdmin = (request: SetupRequest): Promise<{ success: boolean; user: UserDTO }> =>
diff --git a/invokeai/frontend/webv2/src/features/identity/session.test.ts b/invokeai/frontend/webv2/src/features/identity/session.test.ts
index 0d7a885100..8d004b30b4 100644
--- a/invokeai/frontend/webv2/src/features/identity/session.test.ts
+++ b/invokeai/frontend/webv2/src/features/identity/session.test.ts
@@ -39,6 +39,7 @@ const api = vi.hoisted(() => ({
getCurrentUser: vi.fn(),
login: vi.fn(),
logout: vi.fn(),
+ refreshMediaCookie: vi.fn(),
setupAdmin: vi.fn(),
}));
@@ -128,7 +129,12 @@ beforeEach(async () => {
api.getCurrentUser.mockReset();
api.login.mockReset();
api.logout.mockReset();
+ api.refreshMediaCookie.mockReset();
api.setupAdmin.mockReset();
+ api.refreshMediaCookie.mockImplementation(() => {
+ testState.events.push('api.refreshMediaCookie');
+ return Promise.resolve({ success: true });
+ });
api.getAuthStatus.mockResolvedValue({
admin_email: '[email protected]',
@@ -421,3 +427,38 @@ describe('identity account transitions', () => {
expect(testState.getToken()).toBeNull();
});
});
+
+describe('media cookie recovery on restore', () => {
+ it('re-issues the media cookie when a stored token restores a session', async () => {
+ testState.tokenAdapter.set('stored-token');
+ api.getCurrentUser.mockResolvedValue(user);
+ const observed = createObservedLifecycle();
+ session.configureIdentityAccountLifecycle(observed.port);
+
+ await session.ensureAuthSession();
+
+ // A restored session has a valid JWT but no media cookie, so every <img> would 401
+ // without this call. Login needs no equivalent — the backend sets the cookie there.
+ expect(api.refreshMediaCookie).toHaveBeenCalledTimes(1);
+ expect(session.getAuthSession()).toMatchObject({ phase: 'ready', user });
+ });
+
+ it('still restores the session when the media cookie refresh fails', async () => {
+ testState.tokenAdapter.set('stored-token');
+ api.getCurrentUser.mockResolvedValue(user);
+ api.refreshMediaCookie.mockRejectedValue(new Error('network down'));
+ const observed = createObservedLifecycle();
+ session.configureIdentityAccountLifecycle(observed.port);
+
+ await session.ensureAuthSession();
+
+ // Broken media is a degraded gallery; it must not present the user as signed out.
+ expect(session.getAuthSession()).toMatchObject({ phase: 'ready', sessionExpired: false, user });
+ });
+
+ it('does not request a media cookie when there is no stored token to restore', async () => {
+ await resolveSignedOutMultiuserSession();
+
+ expect(api.refreshMediaCookie).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/identity/session.ts b/invokeai/frontend/webv2/src/features/identity/session.ts
index 011d729ce6..c4958c87f8 100644
--- a/invokeai/frontend/webv2/src/features/identity/session.ts
+++ b/invokeai/frontend/webv2/src/features/identity/session.ts
@@ -3,7 +3,16 @@ import { ApiError } from '@platform/transport/http';
import { shouldExpireUnauthorizedSession } from './core/sessionPolicy';
import { browserIdentityTokenAdapter } from './core/tokenStorage';
-import { getAuthStatus, getCurrentUser, login, logout, setupAdmin, type AuthStatus, type UserDTO } from './data/api';
+import {
+ getAuthStatus,
+ getCurrentUser,
+ login,
+ logout,
+ refreshMediaCookie,
+ setupAdmin,
+ type AuthStatus,
+ type UserDTO,
+} from './data/api';
/**
* Session-lived auth state shared by the router guards and shell chrome. When
@@ -192,6 +201,11 @@ const resolveSession = async (): Promise<AuthSession> => {
if (status.multiuser_enabled && !status.setup_required && browserIdentityTokenAdapter.get()) {
try {
user = await getCurrentUser();
+ // This branch is the restore-from-stored-token path, the one case that holds a valid JWT
+ // without the media cookie login would have set. Re-issue it before anything renders an
+ // <img>, or every thumbnail 401s. Awaited (a small POST) so the first paint already has
+ // the cookie, but never fatal: failing here leaves media broken, not the session.
+ await refreshMediaCookie().catch(() => undefined);
} catch (error) {
if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {
browserIdentityTokenAdapter.clear();
diff --git a/invokeai/frontend/webv2/src/platform/transport/http.test.ts b/invokeai/frontend/webv2/src/platform/transport/http.test.ts
index 83b4e9b5ea..b3c6802980 100644
--- a/invokeai/frontend/webv2/src/platform/transport/http.test.ts
+++ b/invokeai/frontend/webv2/src/platform/transport/http.test.ts
@@ -154,3 +154,30 @@ describe('request identity ownership', () => {
await expect(oldRequest).rejects.toMatchObject({ name: 'HttpRequestIdentityExpiredError' });
});
});
+
+describe('media cookie credentials', () => {
+ beforeEach(() => {
+ // One stable identity for the whole request: a fresh object per call would read as a
+ // mid-request account rotation and reject before the assertion.
+ const identity = {};
+ configureHttpAuth({ getIdentity: () => identity, getToken: () => null, onUnauthorized: vi.fn() });
+ });
+
+ it('sends credentials so login can set the media cookie that authenticates <img> requests', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response('', { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await apiFetch('/api/v1/auth/login', { method: 'POST' });
+
+ expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({ credentials: 'same-origin' });
+ });
+
+ it('lets a caller override credentials for a cross-origin API base', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response('', { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await apiFetch('/api/v1/auth/media-cookie', { credentials: 'include', method: 'POST' });
+
+ expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({ credentials: 'include' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/transport/http.ts b/invokeai/frontend/webv2/src/platform/transport/http.ts
index b483d37707..c88be8d6bc 100644
--- a/invokeai/frontend/webv2/src/platform/transport/http.ts
+++ b/invokeai/frontend/webv2/src/platform/transport/http.ts
@@ -148,7 +148,17 @@ const fetchWithAuthToken = (path: string, init: RequestInit | undefined, token:
headers.set('Authorization', `Bearer ${token}`);
}
- return fetch(buildApiUrl(path), { ...init, headers });
+ // `credentials` is stated rather than left to the fetch default because the backend now
+ // authenticates media routes (`/images/i/{name}/full`, `/videos/i/{name}/full`) with the
+ // path-scoped HttpOnly cookie that login sets — `<img>`/`<video>` cannot send a bearer
+ // header. Losing the login `Set-Cookie` would blank every thumbnail in multiuser mode, so
+ // the cookie behavior is pinned here where it can be asserted.
+ //
+ // 'same-origin' covers the normal deployment and the dev Vite proxy. A cross-origin
+ // VITE_INVOKEAI_API_BASE_URL would additionally need 'include' here plus
+ // Access-Control-Allow-Credentials on the backend; requesting 'include' unconditionally
+ // would instead break those setups outright, so callers opt in via `init`.
+ return fetch(buildApiUrl(path), { credentials: 'same-origin', ...init, headers });
};
/** Authenticated fetch that leaves status handling to the caller. */