diff --git a/src/platform/auth/session/cloudWebSessionStore.ts b/src/platform/auth/session/cloudWebSessionStore.ts index 9017ef9f1b4..a4f75216808 100644 --- a/src/platform/auth/session/cloudWebSessionStore.ts +++ b/src/platform/auth/session/cloudWebSessionStore.ts @@ -223,6 +223,15 @@ export const useCloudWebSessionStore = defineStore('cloudWebSession', () => { } ) + // A unified credential from a token-rail fallback would adopt a sibling's + // token and overwrite the workspace this tab's session requests carry. + watch( + () => signedInUser.value?.id, + (userId) => { + if (userId) useWorkspaceAuthStore().clearUnifiedContext() + } + ) + const reconnecting = shallowRef(false) const readsFailing = computed( () => 'failures' in state.value && state.value.failures > 0 diff --git a/src/platform/auth/webSessionFlagOn.test.ts b/src/platform/auth/webSessionFlagOn.test.ts index 917e99234a5..e93a2b08ea7 100644 --- a/src/platform/auth/webSessionFlagOn.test.ts +++ b/src/platform/auth/webSessionFlagOn.test.ts @@ -679,6 +679,7 @@ function installIngest(features: Record = {}) { userId: 'user-a', csrfToken: 'csrf-1', sessionDown: false, + sessionMissing: false, refusals: [] as string[], mintRefusal: undefined as (() => Response) | undefined, mintGate: undefined as Promise | undefined, @@ -747,8 +748,12 @@ function installIngest(features: Record = {}) { ) } - const answerSession = (): Response => - ingest.sessionDown + const answerSession = (method: string): Response => { + if (ingest.sessionMissing) { + return jsonResponse({ code: 'no_session', message: 'no_session' }, 401) + } + if (method === 'POST') return jsonResponse({ success: true }) + return ingest.sessionDown ? jsonResponse({ code: 'unavailable', message: 'down' }, 503) : jsonResponse({ ...sessionBody(ingest.userId, { @@ -756,10 +761,11 @@ function installIngest(features: Record = {}) { }), csrf_token: ingest.csrfToken }) + } const respond = (request: ApiRequest, body: unknown): Response => { const { path, headers } = request - if (path === '/api/auth/session') return answerSession() + if (path === '/api/auth/session') return answerSession(request.method) if (path === '/api/auth/token') return mint(body) if (path === '/api/workspaces/current') { if (ingest.currentWorkspaceDown) return ingest.currentWorkspaceDown() @@ -2115,13 +2121,42 @@ describe('a sibling tab under unified_cloud_auth', () => { }) const workspaceAuth = useWorkspaceAuthStore() - await expect(workspaceAuth.mintAtLogin()).resolves.toBe(true) + await vi.waitFor(() => + expect(workspaceAuth.getUnifiedToken()).toBeDefined() + ) publishFromSibling() expect(firebaseExchanges()).toHaveLength(1) expect(workspaceAuth.currentWorkspace?.id).toBe('ws-personal') expect(workspaceAuth.getUnifiedToken()).toBe('sibling-jwt') }) + it('drops the fallback credential once the session signs the tab in, so a sibling token cannot move its Run', async () => { + const ingest = installIngest({ unified_cloud_auth: true }) + ingest.sessionMissing = true + await refreshRemoteConfig({ useAuth: false }) + useAuthStore() + const workspaceAuth = useWorkspaceAuthStore() + identity.signIn(USER_A) + await useSessionCookie().ensureSessionCookie() + await expect(workspaceAuth.mintAtLogin()).resolves.toBe(true) + + ingest.sessionMissing = false + const webSession = useCloudWebSessionStore() + webSession.signedInInteractively(USER_A) + await webSession.whenSessionCreated() + await workspaceAuth.switchWorkspace('ws-team') + publishFromSibling() + await postPrompt() + + expect(workspaceAuth.currentWorkspace?.id).toBe('ws-team') + expect(ingest.requests.at(-1)).toEqual( + sessionRequest('POST', '/api/prompt', { + 'x-comfy-workspace-id': 'ws-team', + ...PROMPT_HEADERS, + 'x-csrf-token': 'csrf-1' + }) + ) + }) }) describe('billing on a tab that arrived by session', () => { diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts index 0c2eaaf123c..fe11e5bc261 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts @@ -419,6 +419,16 @@ describe('WorkspaceAuthGate', () => { }) describe('cloud builds - Firebase user signed in on the web session', () => { + const signedInScope: WebSessionRequestScope = { + session: { + user: { id: 'user-a', email: 'a@example.com', emailVerified: true }, + csrfToken: 'csrf-1', + expiresAt: Date.now() + 60 * 60_000, + absoluteExpiresAt: Date.now() + 24 * 60 * 60_000 + }, + epoch: 1 + } + let sessionScope: WebSessionRequestScope | undefined let releaseRequests = () => {} beforeEach(() => { @@ -428,10 +438,9 @@ describe('WorkspaceAuthGate', () => { vi.mocked(useWorkspaceAuthStore().getUnifiedToken).mockReturnValue( undefined ) + sessionScope = signedInScope releaseRequests = provideWebSessionRequests( - fromPartial({ - scope: async () => fromPartial({}) - }) + fromPartial({ scope: async () => sessionScope }) ) }) @@ -439,11 +448,47 @@ describe('WorkspaceAuthGate', () => { it('initializes the workspace without minting a unified token', async () => { mountComponent() - await flushPromises() + expect(await screen.findByTestId('slot-content')).toBeInTheDocument() expect(useWorkspaceAuthStore().mintAtLogin).not.toHaveBeenCalled() expect(useTeamWorkspaceStore().initialize).toHaveBeenCalled() - expect(screen.getByTestId('slot-content')).toBeInTheDocument() + }) + + it('renders the app when the session signs the tab in while the login mint is refused', async () => { + sessionScope = undefined + vi.mocked(useWorkspaceAuthStore().mintAtLogin).mockImplementation( + async () => { + sessionScope = signedInScope + return false + } + ) + + mountComponent() + + expect(await screen.findByTestId('slot-content')).toBeInTheDocument() + expect(useTeamWorkspaceStore().initialize).toHaveBeenCalled() + }) + + it('renders the app when the session signs the tab in during workspace setup', async () => { + sessionScope = undefined + vi.mocked(useWorkspaceAuthStore().mintAtLogin).mockResolvedValue(true) + vi.mocked(useWorkspaceAuthStore().getUnifiedToken).mockReturnValue( + 'cloud-jwt' + ) + vi.mocked(useTeamWorkspaceStore().initialize).mockImplementation( + async () => { + sessionScope = signedInScope + vi.mocked(useWorkspaceAuthStore().getUnifiedToken).mockReturnValue( + undefined + ) + Object.assign(useTeamWorkspaceStore(), { initState: 'ready' }) + } + ) + + mountComponent() + + expect(await screen.findByTestId('slot-content')).toBeInTheDocument() + expect(useWorkspaceAuthStore().mintAtLogin).toHaveBeenCalledOnce() }) it('mints nothing when unmounted while the session lookup is pending', async () => { @@ -454,12 +499,21 @@ describe('WorkspaceAuthGate', () => { settleScope = resolve } ) + let lookupStarted = () => {} + const lookupStarting = new Promise((resolve) => { + lookupStarted = resolve + }) releaseRequests = provideWebSessionRequests( - fromPartial({ scope: () => pendingScope }) + fromPartial({ + scope: () => { + lookupStarted() + return pendingScope + } + }) ) const { unmount } = mountComponent() - await flushPromises() + await lookupStarting unmount() settleScope(undefined) await flushPromises() diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.vue b/src/platform/workspace/auth/WorkspaceAuthGate.vue index f95db8bff01..6af36533f7c 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.vue +++ b/src/platform/workspace/auth/WorkspaceAuthGate.vue @@ -142,6 +142,11 @@ async function requiresUnifiedToken(): Promise { ) } +/** A session sign-in mid-setup lifts the need for the token that went missing. */ +async function missingUnifiedToken(hasToken: boolean): Promise { + return !hasToken && (await requiresUnifiedToken()) +} + async function initialize(): Promise { if (!isCloud) { void initializeWorkspacesInBackground() @@ -198,7 +203,7 @@ async function initialize(): Promise { if (needsUnifiedToken) { const authenticated = await workspaceAuthStore.mintAtLogin() if (generation !== initializationGeneration) return - if (!authenticated) { + if (await missingUnifiedToken(authenticated)) { throw new Error('Failed to initialize unified cloud auth') } } @@ -206,7 +211,8 @@ async function initialize(): Promise { await initializeWorkspaceMode() if (generation !== initializationGeneration) return void billingCapabilities.initialize(controller.signal) - if (needsUnifiedToken && !workspaceAuthStore.getUnifiedToken()) { + const hasUnifiedToken = Boolean(workspaceAuthStore.getUnifiedToken()) + if (needsUnifiedToken && (await missingUnifiedToken(hasUnifiedToken))) { throw new Error('Unified cloud auth was cleared during workspace setup') } diff --git a/src/platform/workspace/stores/useWorkspaceAuth.test.ts b/src/platform/workspace/stores/useWorkspaceAuth.test.ts index 9b824e3c76c..4a249e2bde8 100644 --- a/src/platform/workspace/stores/useWorkspaceAuth.test.ts +++ b/src/platform/workspace/stores/useWorkspaceAuth.test.ts @@ -8,9 +8,14 @@ import type { User } from 'firebase/auth' import { storeToRefs } from 'pinia' import { nextTick } from 'vue' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { firebaseIdentity } from '@/platform/auth/firebaseIdentity' +import type { + WebSessionRequestScope, + WebSessionRequests +} from '@/platform/auth/session/webSessionFetch' +import { provideWebSessionRequests } from '@/platform/auth/session/webSessionFetch' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { t } from '@/i18n' import { useTelemetry } from '@/platform/telemetry' @@ -3186,6 +3191,51 @@ describe('useWorkspaceAuthStore', () => { expect(unifiedToken.value).toBeNull() }) + it('refuses a mint that parked on the identity before the session signed the tab in', async () => { + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => Promise.resolve(personalTokenResponse) + }) + vi.stubGlobal('fetch', mockFetch) + vi.mocked(useAuthStore().getIdToken).mockResolvedValue( + 'firebase-token-xyz' + ) + const heldPort = replayIdentityPort(() => null) + vi.spyOn(firebaseIdentity, 'onUserChanged').mockImplementation( + heldPort.register + ) + const signedInScope: WebSessionRequestScope = { + session: { + user: { id: 'user-1', email: 'a@example.com', emailVerified: true }, + csrfToken: 'csrf-1', + expiresAt: Date.now() + 60 * 60_000, + absoluteExpiresAt: Date.now() + 24 * 60 * 60_000 + }, + epoch: 1 + } + let signedIn = false + onTestFinished( + provideWebSessionRequests( + fromPartial({ + scope: async () => (signedIn ? signedInScope : undefined) + }) + ) + ) + + const store = useWorkspaceAuthStore() + const { unifiedToken } = storeToRefs(store) + Object.assign(useAuthStore(), { currentUser: { uid: 'user-1' } }) + const parked = store.mintAtLogin() + + signedIn = true + await nextTick() + heldPort.emit(portUser({ uid: 'user-1' })) + + await expect(parked).resolves.toBe(false) + expect(mockFetch).not.toHaveBeenCalled() + expect(unifiedToken.value).toBeNull() + }) + it('is fully dormant under the flag OFF: no unified network, timer, or rotation', async () => { vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = false vi.mocked(useAuthStore().getIdToken).mockResolvedValue( diff --git a/src/platform/workspace/stores/workspaceAuthStore.ts b/src/platform/workspace/stores/workspaceAuthStore.ts index f2cf8d282a0..d83148bc98b 100644 --- a/src/platform/workspace/stores/workspaceAuthStore.ts +++ b/src/platform/workspace/stores/workspaceAuthStore.ts @@ -583,9 +583,13 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { return false } const authUser = await unifiedUser() - // Re-check after the wait: a rollback that flips the flag off while a mint + // Re-check after the wait: a rollback or a session sign-in while a mint // is parked on unifiedUser() must not let the resumed mint commit a token. - if (!unifiedRailEnabled() || !authUser) { + if ( + !unifiedRailEnabled() || + !authUser || + (webSessionRequests() !== undefined && (await signedInOnWebSession())) + ) { return false } const target = currentUnifiedTarget() ?? personalWorkspaceTarget() @@ -726,6 +730,7 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { getUnifiedSessionClient, getUnifiedMintWorkspaceId, clearWorkspaceContext, + clearUnifiedContext, dropDeniedWorkspace } })