Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions src/platform/billing/localBillingHandoff.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { useTelemetry } from '@comfyorg/telemetry'
import { fetchRequests, respondToFetch } from '@comfyorg/test-utils/fetch'
import { fromPartial } from '@total-typescript/shoehorn'
import { FirebaseError } from 'firebase/app'
import { AuthErrorCodes } from 'firebase/auth'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import { useAuthDialogs } from '@/composables/auth/useAuthDialogs'
Expand All @@ -19,6 +21,7 @@ import {
} from '@/platform/billing/localBillingHandoff'
import { registerRefreshOnReturn } from '@/platform/billing/refreshOnReturn'
import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore'
import { signInFirebaseUser } from '@/utils/__tests__/stubAccountIdentityPort'

vi.mock(import('firebase/auth'))
vi.mock(import('@/i18n'))
Expand Down Expand Up @@ -616,3 +619,106 @@ describe('reserveBillingHandoffTab', () => {
)
})
})

describe('issueLocalBillingHandoff for a Firebase sign-in', () => {
function signIn(mint: () => Promise<string>) {
signInFirebaseUser(mint)
Object.assign(useTeamWorkspaceStore(), { activeWorkspaceId: 'ws-1' })
}

it.for([
{
name: 'a token minted for this handoff instead of the cached one',
mint: async () => 'minted-token',
sent: 'Bearer minted-token'
},
{
name: 'the cached token when a new one cannot be minted',
mint: () =>
Promise.reject(
new FirebaseError(AuthErrorCodes.NETWORK_REQUEST_FAILED, 'offline')
),
sent: 'Bearer cached-token'
}
])('issues with $name', async ({ mint, sent }) => {
signIn(mint)
respondToFetch(HANDOFFS, issued)

await expect(issueLocalBillingHandoff(TOP_UP, live)).resolves.toEqual({
status: 'ok',
url: ENTRY_URL
})

expect(fetchRequests(HANDOFFS)[0].headers.get('Authorization')).toBe(sent)
})

it('frees the next handoff once the caller abandons one still minting its ID token, and issues nothing for the late token', async () => {
let deliverLate: (token: string) => void = () => {}
const mint = vi
.fn<() => Promise<string>>()
.mockReturnValueOnce(
new Promise((resolve) => {
deliverLate = resolve
})
)
.mockResolvedValue('minted-token')
signIn(mint)
respondToFetch(HANDOFFS, issued)
const abandoned = new AbortController()

const dropped = issueLocalBillingHandoff(TOP_UP, abandoned.signal)
abandoned.abort()
await expect(dropped).resolves.toEqual({
status: 'error',
message: undefined
})
deliverLate('late-token')

await expect(issueLocalBillingHandoff(TOP_UP, live)).resolves.toEqual({
status: 'ok',
url: ENTRY_URL
})
expect(
fetchRequests(HANDOFFS).map((request) =>
request.headers.get('Authorization')
)
).toEqual(['Bearer minted-token'])
})

it('gives up on an ID token that never arrives, so later clicks are not stuck', async () => {
const overdue = new AbortController()
vi.spyOn(AbortSignal, 'timeout').mockReturnValueOnce(overdue.signal)
const mint = vi
.fn<() => Promise<string>>()
.mockReturnValueOnce(new Promise(() => {}))
.mockResolvedValue('minted-token')
signIn(mint)
respondToFetch(HANDOFFS, issued)

const stuck = issueLocalBillingHandoff(TOP_UP, live)
overdue.abort()

await expect(stuck).resolves.toEqual({
status: 'error',
message: undefined
})
expect(AbortSignal.timeout).toHaveBeenCalledWith(15_000)
await expect(issueLocalBillingHandoff(TOP_UP, live)).resolves.toEqual({
status: 'ok',
url: ENTRY_URL
})
})

it('is not superseded by the ID token rotation it causes, nor is the next handoff', async () => {
signIn(async () => 'minted-token')
respondToFetch(HANDOFFS, issued)

const duringRotation = await issueLocalBillingHandoff(TOP_UP, live)
const afterRotation = await issueLocalBillingHandoff(TOP_UP, live)

expect([duringRotation, afterRotation]).toEqual([
{ status: 'ok', url: ENTRY_URL },
{ status: 'ok', url: ENTRY_URL }
])
})
})
46 changes: 27 additions & 19 deletions src/platform/billing/localBillingHandoff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,7 @@ async function issueBillingHandoff(
'Content-Type': 'application/json'
},
body: JSON.stringify(issueBody(workspaceId, request)),
signal: combineAbortSignals([
signal,
AbortSignal.timeout(ISSUE_TIMEOUT_MS)
])
signal
})
if (response.status === 401) return { kind: 'sign_in_again' }
if (!response.ok) return refusal(response)
Expand Down Expand Up @@ -201,31 +198,22 @@ function refusedOnAbort(signal: AbortSignal): {
return { refusal, stop: () => signal.removeEventListener('abort', refuse) }
}

async function issueThroughDesktopUnlessAbandoned(
workspaceId: string,
request: BillingHandoffRequest,
async function unlessAbandoned(
issue: () => Promise<HandoffIssue>,
signal: AbortSignal
): Promise<HandoffIssue> {
if (signal.aborted) return UNEXPLAINED_REFUSAL
const abandoned = refusedOnAbort(signal)
return Promise.race([
issueThroughDesktop(workspaceId, request),
abandoned.refusal
]).finally(abandoned.stop)
return Promise.race([issue(), abandoned.refusal]).finally(abandoned.stop)
}

async function issueForScope(
async function issueWithFreshToken(
scope: HandoffScope,
request: BillingHandoffRequest,
signal: AbortSignal
): Promise<HandoffIssue> {
if (localSurface() === 'desktop')
return issueThroughDesktopUnlessAbandoned(
scope.workspaceId,
request,
signal
)
const token = await useAuthStore().getIdToken()
const token = await useAuthStore().getFreshIdToken()
Comment thread
dante01yoon marked this conversation as resolved.
Resolved
if (signal.aborted) return UNEXPLAINED_REFUSAL
if (!token) return SIGN_IN_AGAIN
return issueBillingHandoff(
token,
Expand All @@ -236,6 +224,26 @@ async function issueForScope(
)
}

function issueForScope(
scope: HandoffScope,
request: BillingHandoffRequest,
signal: AbortSignal
): Promise<HandoffIssue> {
if (localSurface() === 'desktop')
return unlessAbandoned(
() => issueThroughDesktop(scope.workspaceId, request),
signal
)
const abandonedOrOverdue = combineAbortSignals([
signal,
AbortSignal.timeout(ISSUE_TIMEOUT_MS)
])
return unlessAbandoned(
() => issueWithFreshToken(scope, request, abandonedOrOverdue),
abandonedOrOverdue
)
}

function settle(
issue: HandoffIssue,
scopeChanged: boolean
Expand Down
28 changes: 28 additions & 0 deletions src/platform/billing/stores/localBillingWebFlagStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { remoteConfig } from '@/platform/remoteConfig/remoteConfig'
import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore'
import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore'
import { useAuthStore } from '@/stores/authStore'
import { signInFirebaseUser } from '@/utils/__tests__/stubAccountIdentityPort'

vi.mock(import('firebase/auth'))

Expand Down Expand Up @@ -354,6 +355,33 @@ describe('useLocalBillingWebFlagStore', () => {
expect(store.enabled).toBe(true)
})

it('reads the flag with the cached ID token of a Firebase sign-in, minting none', async () => {
const mint = vi.fn(async () => 'minted-token')
signInFirebaseUser(mint)
serveFlags({ local_billing_web: false })

useLocalBillingWebFlagStore()
await settle()

expect(fetchRequests(FEATURES)[0].headers.get('Authorization')).toBe(
'Bearer cached-token'
)
expect(mint).not.toHaveBeenCalled()
})

it('stays on, without another read, while the Firebase ID token rotates', async () => {
signInFirebaseUser(async () => 'minted-token')
serveFlags({ local_billing_web: true })
const store = useLocalBillingWebFlagStore()
await settle()

await useAuthStore().getFreshIdToken()
await settle()

expect(store.enabled).toBe(true)
expect(fetchRequests(FEATURES)).toHaveLength(1)
})

it('never falls back to a stored API key for a signed-in account without a token', async () => {
const authStore = useAuthStore()
Object.assign(authStore, { userId: 'firebase-user' })
Expand Down
91 changes: 91 additions & 0 deletions src/stores/authStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,84 @@ describe('useAuthStore', () => {
})
})

describe('getFreshIdToken', () => {
const cachedUnless =
(mint: () => Promise<string>) => (forceRefresh?: boolean) =>
forceRefresh ? mint() : Promise.resolve('cached-token')

it.for([
{
name: 'a token minted now although a cached one exists',
mint: async () => 'minted-token',
token: 'minted-token'
},
{
name: 'the cached token when a new one cannot be minted',
mint: () =>
Promise.reject(
new FirebaseError(
firebaseAuth.AuthErrorCodes.NETWORK_REQUEST_FAILED,
'offline'
)
),
token: 'cached-token'
}
])('returns $name', async ({ mint, token }) => {
mockUser.getIdToken.mockImplementation(cachedUnless(mint))

await expect(store.getFreshIdToken()).resolves.toBe(token)
})

it('reports a mint that failed and fell back to the cached token', async () => {
const offline = new FirebaseError(
firebaseAuth.AuthErrorCodes.NETWORK_REQUEST_FAILED,
'offline'
)
mockUser.getIdToken.mockImplementation(
cachedUnless(() => Promise.reject(offline))
)

await store.getFreshIdToken()

expect(mockReportError).toHaveBeenCalledExactlyOnceWith(offline, {
surface: 'auth',
errorType: 'auth_id_token_refresh_failed'
})
})

it('leaves getIdToken on the cached token', async () => {
mockUser.getIdToken.mockImplementation(
cachedUnless(async () => 'minted-token')
)

await expect(store.getIdToken()).resolves.toBe('cached-token')
})

it('returns no token when no user is signed in', async () => {
authStateCallback(null)

await expect(store.getFreshIdToken()).resolves.toBeUndefined()
})

it('discards a token minted for an account the tab has since left', async () => {
let finishMint: (token: string) => void = () => {}
mockUser.getIdToken.mockImplementation(
cachedUnless(
() =>
new Promise((resolve) => {
finishMint = resolve
})
)
)
const token = store.getFreshIdToken()

authStateCallback({ ...mockUser, uid: 'different-user-id' })
finishMint('minted-token')

await expect(token).resolves.toBeUndefined()
})
})

describe('getAuthHeader', () => {
it('should handle network errors gracefully when getting Firebase token (reproduces issue #4468)', async () => {
// This test reproduces the issue where getAuthHeader fails due to network errors
Expand Down Expand Up @@ -1640,6 +1718,19 @@ describe('useAuthStore in local/desktop distribution', () => {
expect(mockUser.getIdToken).not.toHaveBeenCalled()
})

it('answers a fresh-token request from Desktop without minting through Firebase', async () => {
await startDesktopHostSession(
hostBridge({
status: 'signed_in',
userId: 'host-user',
workspaceId: 'ws-host'
})
)

await expect(store.getFreshIdToken()).resolves.toBe('host-token')
expect(mockUser.getIdToken).not.toHaveBeenCalled()
})

it("loads the host account's workspaces when Desktop signs in", async () => {
const initialize = vi
.spyOn(useTeamWorkspaceStore(), 'initialize')
Expand Down
19 changes: 19 additions & 0 deletions src/stores/authStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,19 @@ export const useAuthStore = defineStore('auth', () => {
}
}

const getFreshFirebaseIdToken = async (): Promise<string | undefined> => {
const user = currentUser.value
const minted = await user?.getIdToken(true).catch((error: unknown) => {
reportError(error, {
surface: 'auth',
errorType: 'auth_id_token_refresh_failed'
})
return undefined
})
if (currentUser.value?.uid !== user?.uid) return
return minted ?? getFirebaseIdToken()
}

/**
* Awaits any in-flight unified-auth login mint for the current identity.
* The wait can outlast an account switch, so callers must treat a `true`
Expand Down Expand Up @@ -579,6 +592,11 @@ export const useAuthStore = defineStore('auth', () => {
() => desktopHostTabToken(),
getFirebaseIdToken
)
/** An ID token minted now; the cached one when minting fails. */
const getFreshIdToken = preferDesktopHost(
() => desktopHostTabToken(),
getFreshFirebaseIdToken
)
const getAuthHeader = preferDesktopHost(
desktopHostTabHeader,
getAccountAuthHeader
Expand Down Expand Up @@ -906,6 +924,7 @@ export const useAuthStore = defineStore('auth', () => {
logout,
createCustomer,
getIdToken,
getFreshIdToken,
loginWithGoogle,
loginWithGithub,
sendPasswordReset,
Expand Down
Loading
Loading