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(auth): accept epoch-changing token refreshes (#9560)

Nianze Wuadb062350a49
diff --git a/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.test.ts b/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.test.ts
index e1e99c9779..8908a14228 100644
--- a/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.test.ts
+++ b/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.test.ts
@@ -4,11 +4,16 @@ import {
beginAuthTransition,
captureAuthGeneration,
createMediaAuthLock,
+ markTokenRefreshAccepted,
runWithMediaAuthLock,
shouldAcceptRefreshedToken,
shouldEndSessionForUnauthorized,
+ shouldThrottleRefreshedToken,
} from './authTokenRefresh';
+const tokenFor = (userId: string, nonce: number, epoch: number) =>
+ `header.${btoa(JSON.stringify({ user_id: userId, nonce, token_epoch: epoch }))}.signature`;
+
describe('refreshed token acceptance', () => {
beforeAll(() => {
const values = new Map<string, string>();
@@ -60,6 +65,36 @@ describe('refreshed token acceptance', () => {
expect(beginAuthTransition()).toBe(1);
});
+ it('does not throttle the replacement token that advances the current user revocation epoch', () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValue(100_000);
+ markTokenRefreshAccepted();
+
+ expect(shouldThrottleRefreshedToken(tokenFor('user', 1, 0), tokenFor('user', 2, 1))).toBe(false);
+
+ now.mockRestore();
+ });
+
+ it('keeps routine, cross-user, and unreadable replacements throttled', () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValue(200_000);
+ markTokenRefreshAccepted();
+
+ expect(shouldThrottleRefreshedToken(tokenFor('user', 1, 1), tokenFor('user', 2, 1))).toBe(true);
+ expect(shouldThrottleRefreshedToken(tokenFor('user-a', 1, 0), tokenFor('user-b', 2, 1))).toBe(true);
+ expect(shouldThrottleRefreshedToken('opaque-old', 'opaque-new')).toBe(true);
+
+ now.mockRestore();
+ });
+
+ it('accepts a routine same-epoch replacement after the throttle window', () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValue(300_000);
+ markTokenRefreshAccepted();
+ now.mockReturnValue(360_001);
+
+ expect(shouldThrottleRefreshedToken(tokenFor('user', 1, 1), tokenFor('user', 2, 1))).toBe(false);
+
+ now.mockRestore();
+ });
+
it('serializes media-cookie writes', async () => {
const calls: string[] = [];
let releaseFirst: (() => void) | undefined;
diff --git a/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.ts b/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.ts
index 15f5be3285..844b3f69bf 100644
--- a/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.ts
+++ b/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.ts
@@ -1,4 +1,4 @@
-import { tokensBelongToSameUser } from 'features/auth/store/authSlice';
+import { getTokenSessionKey, tokensBelongToSameUser } from 'features/auth/store/authSlice';
const AUTH_GENERATION_KEY = 'auth_generation';
const MEDIA_AUTH_LOCK = 'invokeai-media-auth';
@@ -22,6 +22,18 @@ export const markTokenRefreshAccepted = () => {
lastTokenRefreshAcceptedAt = Date.now();
};
+export const shouldThrottleRefreshedToken = (requestToken: string, refreshedToken: string): boolean => {
+ if (!isTokenRefreshThrottled()) {
+ return false;
+ }
+ // An epoch-changing replacement is the only credential that remains valid after revocation.
+ // Keep every other replacement on the normal sliding-refresh throttle.
+ return !(
+ tokensBelongToSameUser(requestToken, refreshedToken) &&
+ getTokenSessionKey(requestToken) !== getTokenSessionKey(refreshedToken)
+ );
+};
+
type FallbackLockTicket = {
choosing: boolean;
expiresAt: number;
diff --git a/invokeai/frontend/web/src/services/api/endpoints/auth.test.ts b/invokeai/frontend/web/src/services/api/endpoints/auth.test.ts
index b3f35c79bc..16bcffea42 100644
--- a/invokeai/frontend/web/src/services/api/endpoints/auth.test.ts
+++ b/invokeai/frontend/web/src/services/api/endpoints/auth.test.ts
@@ -1,15 +1,20 @@
import { configureStore } from '@reduxjs/toolkit';
+import type { BaseQueryApi } from '@reduxjs/toolkit/query';
+import { tokenRefreshed } from 'features/auth/store/authSlice';
+import { markTokenRefreshAccepted } from 'features/auth/store/authTokenRefresh';
import { authApi } from 'services/api/endpoints/auth';
-import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { api } from '..';
+import { api, buildV1Url, dynamicBaseQuery } from '..';
/**
* `dynamicBaseQuery` reads the bearer token out of localStorage, and `getDeploymentBaseUrl`
* reads `window.location.origin`. Neither exists in the default (node) test environment.
*/
-beforeAll(() => {
- const values = new Map<string, string>();
+const values = new Map<string, string>();
+
+beforeEach(() => {
+ values.clear();
vi.stubGlobal('localStorage', {
clear: () => values.clear(),
getItem: (key: string) => values.get(key) ?? null,
@@ -23,8 +28,9 @@ beforeAll(() => {
vi.stubGlobal('window', { location: { origin: 'http://localhost' } });
});
-beforeEach(() => {
- localStorage.clear();
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
});
const buildStore = () =>
@@ -33,6 +39,138 @@ const buildStore = () =>
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
});
+const tokenFor = (nonce: number, epoch?: number) =>
+ `header.${btoa(
+ JSON.stringify({ user_id: 'user-1', nonce, ...(epoch === undefined ? {} : { token_epoch: epoch }) })
+ )}.signature`;
+
+describe('refreshed token acceptance', () => {
+ it.each([
+ ['an explicit epoch-zero token', tokenFor(1, 0)],
+ ['a legacy token without an epoch claim', tokenFor(1)],
+ ])(
+ 'accepts an epoch-changing replacement for %s inside the routine refresh throttle window',
+ async (_, requestToken) => {
+ const refreshedToken = tokenFor(2, 1);
+ localStorage.setItem('auth_token', requestToken);
+ markTokenRefreshAccepted();
+
+ const events: string[] = [];
+ const dispatch = vi.fn(() => events.push('dispatch'));
+ const fetchMock = vi.fn((input: string | URL | Request, init?: RequestInit) => {
+ const url = input instanceof Request ? input.url : input.toString();
+ if (url.endsWith('/api/v1/auth/media-cookie')) {
+ events.push('media-cookie');
+ expect(new Headers(init?.headers).get('Authorization')).toBe(`Bearer ${refreshedToken}`);
+ return Promise.resolve(new Response(null, { status: 204 }));
+ }
+ return Promise.resolve(
+ new Response('{}', {
+ headers: { 'content-type': 'application/json', 'X-Refreshed-Token': refreshedToken },
+ })
+ );
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await dynamicBaseQuery(
+ buildV1Url('images/i/example.png'),
+ {
+ dispatch,
+ getState: () => ({}),
+ signal: new AbortController().signal,
+ abort: () => {},
+ endpoint: 'getImageDTO',
+ type: 'query',
+ forced: false,
+ extra: undefined,
+ } as unknown as BaseQueryApi,
+ {}
+ );
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(dispatch).toHaveBeenCalledWith(tokenRefreshed(refreshedToken));
+ expect(events).toEqual(['media-cookie', 'dispatch']);
+ }
+ );
+
+ it('keeps a same-epoch replacement inside the routine refresh throttle window', async () => {
+ const requestToken = tokenFor(1, 1);
+ const refreshedToken = tokenFor(2, 1);
+ localStorage.setItem('auth_token', requestToken);
+ markTokenRefreshAccepted();
+
+ const dispatch = vi.fn();
+ const fetchMock = vi.fn(() =>
+ Promise.resolve(
+ new Response('{}', {
+ headers: { 'content-type': 'application/json', 'X-Refreshed-Token': refreshedToken },
+ })
+ )
+ );
+ vi.stubGlobal('fetch', fetchMock);
+
+ await dynamicBaseQuery(
+ buildV1Url('images/i/example.png'),
+ {
+ dispatch,
+ getState: () => ({}),
+ signal: new AbortController().signal,
+ abort: () => {},
+ endpoint: 'getImageDTO',
+ type: 'query',
+ forced: false,
+ extra: undefined,
+ } as unknown as BaseQueryApi,
+ {}
+ );
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('commits a same-epoch replacement after the routine refresh throttle window', async () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValue(300_000);
+ const requestToken = tokenFor(1, 1);
+ const refreshedToken = tokenFor(2, 1);
+ localStorage.setItem('auth_token', requestToken);
+ markTokenRefreshAccepted();
+ now.mockReturnValue(360_001);
+
+ const dispatch = vi.fn();
+ const fetchMock = vi.fn((input: string | URL | Request, init?: RequestInit) => {
+ const url = input instanceof Request ? input.url : input.toString();
+ if (url.endsWith('/api/v1/auth/media-cookie')) {
+ expect(new Headers(init?.headers).get('Authorization')).toBe(`Bearer ${refreshedToken}`);
+ return Promise.resolve(new Response(null, { status: 204 }));
+ }
+ return Promise.resolve(
+ new Response('{}', {
+ headers: { 'content-type': 'application/json', 'X-Refreshed-Token': refreshedToken },
+ })
+ );
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await dynamicBaseQuery(
+ buildV1Url('images/i/example.png'),
+ {
+ dispatch,
+ getState: () => ({}),
+ signal: new AbortController().signal,
+ abort: () => {},
+ endpoint: 'getImageDTO',
+ type: 'query',
+ forced: false,
+ extra: undefined,
+ } as unknown as BaseQueryApi,
+ {}
+ );
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(dispatch).toHaveBeenCalledWith(tokenRefreshed(refreshedToken));
+ });
+});
+
describe('getCurrentUser', () => {
it('does not let a replacement session read the 401 of the token it replaced', async () => {
// The sequence this exists for: a tab page-loads with an expired token and asks who it is;
diff --git a/invokeai/frontend/web/src/services/api/index.ts b/invokeai/frontend/web/src/services/api/index.ts
index 36574d6672..e68eb65cbe 100644
--- a/invokeai/frontend/web/src/services/api/index.ts
+++ b/invokeai/frontend/web/src/services/api/index.ts
@@ -12,12 +12,12 @@ import { sessionExpiredLogout, tokenRefreshed } from 'features/auth/store/authSl
import {
beginAuthTransition,
captureAuthGeneration,
- isTokenRefreshThrottled,
markTokenRefreshAccepted,
MEDIA_COOKIE_SYNC_TIMEOUT_MS,
runWithMediaAuthLock,
shouldAcceptRefreshedToken,
shouldEndSessionForUnauthorized,
+ shouldThrottleRefreshedToken,
} from 'features/auth/store/authTokenRefresh';
import queryString from 'query-string';
import stableHash from 'stable-hash';
@@ -174,11 +174,17 @@ export const acceptRefreshedToken = async (
requestGeneration: number,
dispatch: (action: ReturnType<typeof tokenRefreshed>) => unknown
): Promise<void> => {
- if (isTokenRefreshThrottled() || !shouldAcceptRefreshedToken(requestToken, requestGeneration)) {
+ if (
+ shouldThrottleRefreshedToken(requestToken, refreshedToken) ||
+ !shouldAcceptRefreshedToken(requestToken, requestGeneration)
+ ) {
return;
}
await runWithMediaAuthLock(async () => {
- if (isTokenRefreshThrottled() || !shouldAcceptRefreshedToken(requestToken, requestGeneration)) {
+ if (
+ shouldThrottleRefreshedToken(requestToken, refreshedToken) ||
+ !shouldAcceptRefreshedToken(requestToken, requestGeneration)
+ ) {
return;
}
try {