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
fix(auth): keep a password-change token when a routine refresh lands first (#9599)
Mohammad Hijjawie927a2ebf59d
diff --git a/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.test.ts b/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.test.tsindex 8908a14228..9c0714d348 100644--- a/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.test.ts+++ b/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.test.ts@@ -58,6 +58,55 @@ describe('refreshed token acceptance', () => {expect(shouldAcceptRefreshedToken('token-a', generation)).toBe(false);});+ it('accepts a password-change replacement after a routine refresh of the same session committed first', () => {+ // The request carried T0; a routine refresh T0' (same user and epoch) committed before the+ // password change's epoch-advancing replacement R arrived.+ const requestToken = tokenFor('user', 1, 0);+ localStorage.setItem('auth_token', requestToken);+ const generation = captureAuthGeneration();+ localStorage.setItem('auth_token', tokenFor('user', 2, 0));++ expect(shouldAcceptRefreshedToken(requestToken, generation, tokenFor('user', 3, 1))).toBe(true);+ });++ it('still rejects a routine refresh superseded by a newer refresh of the same session', () => {+ const requestToken = tokenFor('user', 1, 0);+ localStorage.setItem('auth_token', requestToken);+ const generation = captureAuthGeneration();+ localStorage.setItem('auth_token', tokenFor('user', 2, 0));++ expect(shouldAcceptRefreshedToken(requestToken, generation, tokenFor('user', 3, 0))).toBe(false);+ });++ it('rejects an epoch replacement once the stored token is no longer the same session', () => {+ const requestToken = tokenFor('user', 1, 0);+ localStorage.setItem('auth_token', requestToken);+ const generation = captureAuthGeneration();+ const replacement = tokenFor('user', 3, 1);++ // Already moved past this epoch (e.g. a newer replacement committed first).+ localStorage.setItem('auth_token', tokenFor('user', 4, 2));+ expect(shouldAcceptRefreshedToken(requestToken, generation, replacement)).toBe(false);++ // Another user's token.+ localStorage.setItem('auth_token', tokenFor('other', 5, 0));+ expect(shouldAcceptRefreshedToken(requestToken, generation, replacement)).toBe(false);++ // Logged out.+ localStorage.removeItem('auth_token');+ expect(shouldAcceptRefreshedToken(requestToken, generation, replacement)).toBe(false);+ });++ it('rejects an epoch replacement after a login transition started', () => {+ const requestToken = tokenFor('user', 1, 0);+ localStorage.setItem('auth_token', requestToken);+ const generation = captureAuthGeneration();+ beginAuthTransition();+ localStorage.setItem('auth_token', tokenFor('user', 2, 0));++ expect(shouldAcceptRefreshedToken(requestToken, generation, tokenFor('user', 3, 1))).toBe(false);+ });+it('recovers from a malformed stored generation', () => {localStorage.setItem('auth_generation', 'not-a-number');diff --git a/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.ts b/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.tsindex 844b3f69bf..5d2e9645cb 100644--- a/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.ts+++ b/invokeai/frontend/web/src/features/auth/store/authTokenRefresh.ts@@ -22,16 +22,18 @@ export const markTokenRefreshAccepted = () => {lastTokenRefreshAcceptedAt = Date.now();};+/** True when `refreshedToken` is the same user's replacement that advances the revocation epoch. */+const isEpochReplacement = (requestToken: string, refreshedToken: string): boolean =>+ tokensBelongToSameUser(requestToken, refreshedToken) &&+ getTokenSessionKey(requestToken) !== getTokenSessionKey(refreshedToken);+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)- );+ return !isEpochReplacement(requestToken, refreshedToken);};type FallbackLockTicket = {@@ -54,8 +56,36 @@ export const beginAuthTransition = () => {return next;};-export const shouldAcceptRefreshedToken = (requestToken: string, requestGeneration: number) =>- getAuthGeneration() === requestGeneration && localStorage.getItem('auth_token') === requestToken;+/**+ * True when `refreshedToken`, returned for a request sent with `requestToken`, may replace the+ * stored token.+ *+ * Byte equality with the stored token rejects refreshes that belong to a different login: a+ * logout, another user logging in, or another tab adopting a new token. A routine sliding-window+ * refresh of the same session committed in the meantime is not one of those, but it changes the+ * bytes too. For an epoch-advancing replacement (a password change) that would drop the only+ * credential that survives the revocation, so it is also accepted when the stored token is the+ * same session (user id and epoch) as `requestToken`. It is then strictly newer than both. The+ * generation check still rejects any login transition that started after the request was sent.+ */+export const shouldAcceptRefreshedToken = (+ requestToken: string,+ requestGeneration: number,+ refreshedToken?: string+): boolean => {+ if (getAuthGeneration() !== requestGeneration) {+ return false;+ }+ const storedToken = localStorage.getItem('auth_token');+ if (storedToken === requestToken) {+ return true;+ }+ return (+ refreshedToken !== undefined &&+ isEpochReplacement(requestToken, refreshedToken) &&+ getTokenSessionKey(storedToken) === getTokenSessionKey(requestToken)+ );+};/*** True when a 401 for a request that carried `requestToken` should end the live session.diff --git a/invokeai/frontend/web/src/services/api/endpoints/auth.test.ts b/invokeai/frontend/web/src/services/api/endpoints/auth.test.tsindex 16bcffea42..f1b85a7466 100644--- a/invokeai/frontend/web/src/services/api/endpoints/auth.test.ts+++ b/invokeai/frontend/web/src/services/api/endpoints/auth.test.ts@@ -5,7 +5,7 @@ import { markTokenRefreshAccepted } from 'features/auth/store/authTokenRefresh';import { authApi } from 'services/api/endpoints/auth';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { api, buildV1Url, dynamicBaseQuery } from '..';+import { acceptRefreshedToken, api, buildV1Url, dynamicBaseQuery } from '..';/*** `dynamicBaseQuery` reads the bearer token out of localStorage, and `getDeploymentBaseUrl`@@ -169,6 +169,52 @@ describe('refreshed token acceptance', () => {expect(fetchMock).toHaveBeenCalledTimes(2);expect(dispatch).toHaveBeenCalledWith(tokenRefreshed(refreshedToken));});++ describe('a password-change replacement racing a routine refresh of the same session', () => {+ // The request carried T0. A routine refresh T0' (same epoch) and the password change's+ // epoch-advancing replacement R were both minted for it, and T0' commits first.+ const requestToken = tokenFor(1, 0);+ const routineToken = tokenFor(2, 0);+ const replacementToken = tokenFor(3, 1);++ // Commits like the real `tokenRefreshed` reducer, so the second acceptance sees T0' stored.+ const dispatch = vi.fn((action: ReturnType<typeof tokenRefreshed>) => {+ localStorage.setItem('auth_token', action.payload);+ });++ beforeEach(() => {+ // Put the throttle past its window, so the routine refresh is accepted and commits.+ const now = vi.spyOn(Date, 'now').mockReturnValue(300_000);+ markTokenRefreshAccepted();+ now.mockReturnValue(360_001);+ dispatch.mockClear();+ localStorage.setItem('auth_token', requestToken);+ vi.stubGlobal(+ 'fetch',+ vi.fn(() => Promise.resolve(new Response(null, { status: 204 })))+ );+ });++ it('keeps the replacement when the routine refresh committed before it arrived', async () => {+ await acceptRefreshedToken(routineToken, requestToken, 0, dispatch);+ expect(localStorage.getItem('auth_token')).toBe(routineToken);++ await acceptRefreshedToken(replacementToken, requestToken, 0, dispatch);++ expect(localStorage.getItem('auth_token')).toBe(replacementToken);+ });++ it('keeps the replacement when it queued on the lock behind the routine refresh', async () => {+ // Both pass the check before the lock while T0 is still stored; the replacement then waits+ // for the routine refresh to commit and re-checks inside the lock.+ const routine = acceptRefreshedToken(routineToken, requestToken, 0, dispatch);+ const replacement = acceptRefreshedToken(replacementToken, requestToken, 0, dispatch);+ await Promise.all([routine, replacement]);++ expect(dispatch.mock.calls.map(([action]) => action.payload)).toEqual([routineToken, replacementToken]);+ expect(localStorage.getItem('auth_token')).toBe(replacementToken);+ });+ });});describe('getCurrentUser', () => {diff --git a/invokeai/frontend/web/src/services/api/index.ts b/invokeai/frontend/web/src/services/api/index.tsindex e68eb65cbe..3a0dc7d2c3 100644--- a/invokeai/frontend/web/src/services/api/index.ts+++ b/invokeai/frontend/web/src/services/api/index.ts@@ -176,14 +176,14 @@ export const acceptRefreshedToken = async (): Promise<void> => {if (shouldThrottleRefreshedToken(requestToken, refreshedToken) ||- !shouldAcceptRefreshedToken(requestToken, requestGeneration)+ !shouldAcceptRefreshedToken(requestToken, requestGeneration, refreshedToken)) {return;}await runWithMediaAuthLock(async () => {if (shouldThrottleRefreshedToken(requestToken, refreshedToken) ||- !shouldAcceptRefreshedToken(requestToken, requestGeneration)+ !shouldAcceptRefreshedToken(requestToken, requestGeneration, refreshedToken)) {return;}@@ -208,7 +208,7 @@ export const acceptRefreshedToken = async (// failure would trade a transiently stale media cookie for a hard session// expiry mid-activity.}- if (shouldAcceptRefreshedToken(requestToken, requestGeneration)) {+ if (shouldAcceptRefreshedToken(requestToken, requestGeneration, refreshedToken)) {markTokenRefreshAccepted();dispatch(tokenRefreshed(refreshedToken));}