diff --git a/docs/adr/AUTH-IDENTITY-0028-account-package-firebase-entry-delivers-cloud-identity.md b/docs/adr/AUTH-IDENTITY-0028-account-package-firebase-entry-delivers-cloud-identity.md index 65fce5f2203..e2f8b5fce4e 100644 --- a/docs/adr/AUTH-IDENTITY-0028-account-package-firebase-entry-delivers-cloud-identity.md +++ b/docs/adr/AUTH-IDENTITY-0028-account-package-firebase-entry-delivers-cloud-identity.md @@ -6,6 +6,9 @@ Date: 2026-09-09 Proposed +Amended 2026-09-16: rules 1 and 4 follow the session client taking identity at +construction (FE-2196). + ## Context The cloud app holds two consumers of Firebase identity: @@ -28,8 +31,9 @@ is not a contract to build on. 1. Identity reaches the session client through the package entry bound to the app's own `Auth` instance: `authStore` creates - `createFirebaseIdentity({ auth })` and `workspaceAuthStore` attaches it - as the client's `IdentityPort`. No hand-rolled port exists in `src/`. + `createFirebaseIdentity({ auth })` and `workspaceAuthStore` passes it to + `createSessionClient` at construction. No hand-rolled port exists in + `src/`. 2. The Pinia `authStore` is a projection for app-wide side effects. It is not an identity authority for the session client and pushes nothing into it. @@ -44,10 +48,27 @@ is not a contract to build on. port's user is what mints. The wait is bounded, so a silent port fails the mint closed instead of hanging the auth gate. Mints stay host-driven (`autoMint: false`), so telemetry and coalescing are - unchanged. -4. `syncUnifiedIdentity` is gone; the flag rule stays: with - `unified_cloud_auth` off the port is never attached and no state is - held. + unchanged. The two stores construct each other (`workspaceAuthStore` + reads `useAuthStore().identity` in its setup, `authStore`'s listener + calls `useWorkspaceAuthStore()`), which holds only because the SDK + delivers a new observer's first emission asynchronously, after + persistence resolves; a synchronous identity source in its place would + re-enter a half-built store: built workspace-first it throws a boot-time + `TypeError` from `authStore`'s listener against the half-assigned store, + built auth-first it leaves the client unsubscribed and every mint waiting + its ceiling. The "store construction order" test in `authStore.test.ts` + pins the working microtask order. +4. `syncUnifiedIdentity` is gone, and the flag gates minting, not + subscription: identity is bound to the session client for the store's + lifetime. With `unified_cloud_auth` off the port stays subscribed but + inert. The store drives every mint explicitly (`autoMint: false`), so an + identity event mints nothing, and `clearUnifiedContext()` invalidates the + credential and stops the scheduler and cross-tab lease. A mint already + parked on `unifiedUser()` when the flag flips is caught by the flag-gated + helpers re-checking the flag after that await, so it commits nothing + either: no unified token, network call or timer exists. The residue is the + snapshot's user and a `minting`/`pending` phase that no flag-off consumer + reads. 5. Nothing in `src/` may initialize a second Firebase app through `createFirebaseIdentity({ options })` while the app runs on vuefire; a second auth instance diverges the session. Package-initialized Firebase diff --git a/src/platform/auth/unified/remintRetry.test.ts b/src/platform/auth/unified/remintRetry.test.ts index 69a232f1f38..8893cdd9bb9 100644 --- a/src/platform/auth/unified/remintRetry.test.ts +++ b/src/platform/auth/unified/remintRetry.test.ts @@ -1,4 +1,5 @@ import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' +import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' import type { AxiosAdapter } from 'axios' import axios, { AxiosError } from 'axios' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -17,6 +18,9 @@ const { mockRemint, flagState } = vi.hoisted(() => ({ vi.mock(import('@/platform/telemetry')) +vi.mock(import('vuefire'), () => ({ useFirebaseAuth: vi.fn() })) +vi.mock(import('firebase/auth')) + vi.mock(import('@/composables/useFeatureFlags'), () => ({ useFeatureFlags: () => ({ flags: { @@ -34,6 +38,7 @@ vi.mock(import('@/platform/distribution/types'), () => ({ })) beforeEach(() => { + stubAccountIdentityPort() vi.mocked(useWorkspaceAuthStore().remintUnifiedOnce).mockImplementation( mockRemint ) diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts index 0d17febbd5a..ba53d60a135 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts @@ -20,6 +20,8 @@ import { remoteConfigState } from '@/platform/remoteConfig/remoteConfig' +import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' + import WorkspaceAuthGate from './WorkspaceAuthGate.vue' vi.mock(import('firebase/auth'), { spy: true }) @@ -28,6 +30,7 @@ beforeEach(() => { vi.mocked(setPersistence).mockResolvedValue(undefined) vi.mocked(onAuthStateChanged).mockImplementation(vi.fn()) vi.mocked(onIdTokenChanged).mockImplementation(vi.fn()) + stubAccountIdentityPort() }) async function flushPromises() { diff --git a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts index ca4b83015ac..19c055194b3 100644 --- a/src/platform/workspace/billing/sdk/billingSdkStore.test.ts +++ b/src/platform/workspace/billing/sdk/billingSdkStore.test.ts @@ -5,6 +5,7 @@ import { useToastStore } from '@/platform/updates/common/toastStore' import { WorkspaceApiError } from '@/platform/workspace/api/workspaceApi' import { workspaceApiUrl } from '@/platform/workspace/api/workspaceApiUrl' import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' +import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' import { useDialogStore } from '@/stores/dialogStore' import { useBillingSdkStore } from './billingSdkStore' @@ -78,6 +79,9 @@ vi.mock(import('@/composables/useFeatureFlags'), () => ({ vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) +vi.mock(import('vuefire'), () => ({ useFirebaseAuth: vi.fn() })) +vi.mock(import('firebase/auth')) + const mockLoadStripe = vi.hoisted(() => vi.fn()) vi.mock(import('@stripe/stripe-js/pure'), () => ({ loadStripe: mockLoadStripe @@ -87,6 +91,7 @@ let harness: ReturnType let options: BillingSdkOptions beforeEach(() => { + stubAccountIdentityPort() flagState.embeddedCheckoutEnabled = false flagState.hostedBillingDestination = 'stripe' harness = fakeBillingSdk() diff --git a/src/platform/workspace/composables/useTopupOperation.test.ts b/src/platform/workspace/composables/useTopupOperation.test.ts index d9a4c8f5523..3238391bd51 100644 --- a/src/platform/workspace/composables/useTopupOperation.test.ts +++ b/src/platform/workspace/composables/useTopupOperation.test.ts @@ -11,6 +11,10 @@ import type { BillingSdk } from '@/platform/workspace/billing/sdk/createBillingS import { billingOperation } from '@/platform/workspace/composables/billingOperationTestUtils' import { useTopupOperation } from '@/platform/workspace/composables/useTopupOperation' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' +import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' + +vi.mock(import('vuefire'), () => ({ useFirebaseAuth: vi.fn() })) +vi.mock(import('firebase/auth')) const flagState = vi.hoisted(() => ({ billingSdkTopupEnabled: false, @@ -58,6 +62,7 @@ vi.mock(import('@/platform/workspace/billing/sdk/createBillingSdk'), () => ({ let harness: ReturnType beforeEach(() => { + stubAccountIdentityPort() harness = fakeBillingSdk() mockCreateBillingSdk.mockReturnValue(harness.sdk) flagState.unifiedCloudAuthEnabled = true diff --git a/src/platform/workspace/composables/useWorkspaceBilling.sdk.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.sdk.test.ts index 153168ceebb..c3c9df33c38 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.sdk.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.sdk.test.ts @@ -9,6 +9,10 @@ import { fakeBillingSdk } from '@/platform/workspace/billing/sdk/billingSdkTestU import type { BillingSdk } from '@/platform/workspace/billing/sdk/createBillingSdk' import { useWorkspaceBilling } from '@/platform/workspace/composables/useWorkspaceBilling' import { useBillingOperationStore } from '@/platform/workspace/stores/billingOperationStore' +import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' + +vi.mock(import('vuefire'), () => ({ useFirebaseAuth: vi.fn() })) +vi.mock(import('firebase/auth')) const flagState = vi.hoisted(() => ({ billingSdkTopupEnabled: false, @@ -118,6 +122,7 @@ function setupBilling() { } beforeEach(() => { + stubAccountIdentityPort() harness = fakeBillingSdk() mockCreateBillingSdk.mockReturnValue(harness.sdk) flagState.billingSdkSubscriptionEnabled = false diff --git a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts index 27a216c715d..7b9a6ba0241 100644 --- a/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts +++ b/src/platform/workspace/composables/useWorkspaceBilling.subscriptionRail.test.ts @@ -1,6 +1,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { effectScope } from 'vue' +vi.mock(import('firebase/auth')) +vi.mock(import('vuefire'), () => ({ + useFirebaseAuth: vi.fn(() => ({})) +})) + import type { BillingTelemetryEvent } from '@/platform/telemetry/types' import type { BillingStatusResponse, diff --git a/src/platform/workspace/stores/teamWorkspaceStore.test.ts b/src/platform/workspace/stores/teamWorkspaceStore.test.ts index c148d6e25ab..b71e8940f3f 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.test.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.test.ts @@ -1,5 +1,6 @@ import { computed } from 'vue' import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' +import { stubAccountIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' import { beforeEach, describe, expect, it, vi } from 'vitest' import { useCurrentUser } from '@/composables/auth/useCurrentUser' @@ -11,6 +12,9 @@ const mockDistributionTypes = vi.hoisted(() => ({ isCloud: true })) vi.mock(import('@/platform/distribution/types'), () => mockDistributionTypes) +vi.mock(import('vuefire'), () => ({ useFirebaseAuth: vi.fn() })) +vi.mock(import('firebase/auth')) + const mockClearWorkflowRestoreState = vi.hoisted(() => vi.fn()) const mockPrepareWorkflowWorkspaceTransition = vi.hoisted(() => vi.fn()) @@ -134,6 +138,7 @@ function expectCleanupBeforeContextAndReload(): void { } beforeEach(() => { + stubAccountIdentityPort() useCurrentUser().userEmail = computed(() => null) Object.assign(useWorkspaceAuthStore(), { diff --git a/src/platform/workspace/stores/useWorkspaceAuth.test.ts b/src/platform/workspace/stores/useWorkspaceAuth.test.ts index c036c2ebb45..b998753b154 100644 --- a/src/platform/workspace/stores/useWorkspaceAuth.test.ts +++ b/src/platform/workspace/stores/useWorkspaceAuth.test.ts @@ -15,6 +15,7 @@ import { useFeatureFlags } from '@/composables/useFeatureFlags' import { useTelemetry } from '@/platform/telemetry' import { + UNIFIED_IDENTITY_SETTLE_TIMEOUT_MS, useWorkspaceAuthStore, WorkspaceAuthError } from '@/platform/workspace/stores/workspaceAuthStore' @@ -24,6 +25,7 @@ import { StorageKeys } from '@/platform/workflow/persistence/base/storageKeys' import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' +import { replayIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' vi.mock(import('firebase/auth'), { spy: true }) @@ -32,13 +34,14 @@ vi.mock(import('firebase/auth'), { spy: true }) * `value` moves the store's user AND fires the port, the way a real * auth-state event reaches both; `deliver` fires the port alone. */ -const portListeners = new Set<(user: User | null) => void>() const portUser = (user: { uid: string } | null): User | null => user && ({ ...user, getIdToken: () => useAuthStore().getIdToken() } as Partial as User) +const port = replayIdentityPort(() => portUser(useAuthStore().currentUser)) +const portListeners = port.observers const mockCurrentUser = { listeners: portListeners, get value(): { uid: string } | null { @@ -46,10 +49,10 @@ const mockCurrentUser = { }, set value(user: { uid: string } | null) { Object.assign(useAuthStore(), { currentUser: user }) - portListeners.forEach((listener) => listener(portUser(user))) + port.emit(portUser(user)) }, deliver(user: { uid: string } | null) { - portListeners.forEach((listener) => listener(portUser(user))) + port.emit(portUser(user)) } } @@ -123,11 +126,7 @@ beforeEach(() => { beforeEach(() => { portListeners.clear() vi.spyOn(useAuthStore().identity, 'onUserChanged').mockImplementation( - (listener) => { - portListeners.add(listener) - listener(portUser(useAuthStore().currentUser)) - return () => portListeners.delete(listener) - } + port.register ) vi.mocked(useAuthStore().getIdToken).mockResolvedValue(undefined) vi.mocked(useAuthStore().notifyTokenRefreshed).mockImplementation(() => {}) @@ -2055,6 +2054,32 @@ describe('useWorkspaceAuthStore', () => { expect(unifiedToken.value).toBeNull() }) + it('a port that delivers synchronously inside onUserChanged still leaves the store subscribed and minting for that user', async () => { + const syncPort = replayIdentityPort( + () => portUser(useAuthStore().currentUser), + 'sync' + ) + vi.spyOn(useAuthStore().identity, 'onUserChanged').mockImplementation( + syncPort.register + ) + vi.mocked(useAuthStore().getIdToken).mockResolvedValue( + 'firebase-token-xyz' + ) + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ + ok: true, + json: () => Promise.resolve(personalTokenResponse) + }) + ) + + const store = useWorkspaceAuthStore() + + expect(syncPort.observers.size, 'the port stays subscribed').toBe(1) + await expect(store.mintAtLogin()).resolves.toBe(true) + expect(store.getUnifiedToken()).toBe('unified-token-1') + }) + it('mints the personal default once into the dormant unifiedToken slot when flag ON', async () => { vi.mocked(useAuthStore().getIdToken).mockResolvedValue( 'firebase-token-xyz' @@ -2123,9 +2148,8 @@ describe('useWorkspaceAuthStore', () => { expect(sessionStorage.getItem(WORKSPACE_STORAGE_KEYS.TOKEN)).toBeNull() }) - it('attaches and mints the current target when the flag flips on', async () => { + it('mints the current target when the flag flips on', async () => { vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = false - vi.mocked(useAuthStore().getIdToken).mockResolvedValue( 'firebase-token-xyz' ) @@ -2834,7 +2858,8 @@ describe('useWorkspaceAuthStore', () => { expect(mockFetch).not.toHaveBeenCalled() }) - it('destroy detaches the unified identity and drops the token', async () => { + it('destroy disposes the session client and drops the token', async () => { + vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true vi.mocked(useAuthStore().getIdToken).mockResolvedValue( 'firebase-token-xyz' ) @@ -2857,11 +2882,18 @@ describe('useWorkspaceAuthStore', () => { mockFetch.mockClear() await vi.advanceTimersByTimeAsync(60 * 60 * 1000) expect(mockFetch).not.toHaveBeenCalled() + + const mintAfterDestroy = store.mintAtLogin() + await vi.advanceTimersByTimeAsync(UNIFIED_IDENTITY_SETTLE_TIMEOUT_MS) + await expect( + mintAfterDestroy, + 'destroy detaches identity with no path back, so a mint waits the settle ceiling and fails closed' + ).resolves.toBe(false) + expect(mockFetch).not.toHaveBeenCalled() }) - it('destroy stops the flag watcher so a later flag flip cannot reattach or mint', async () => { + it('destroy stops the flag watcher so a later flag flip cannot resubscribe or mint', async () => { vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true - vi.mocked(useAuthStore().getIdToken).mockResolvedValue( 'firebase-token-xyz' ) @@ -2876,9 +2908,10 @@ describe('useWorkspaceAuthStore', () => { expect(portListeners.size).toBe(1) store.destroy() - expect(portListeners.size, 'destroy must detach the identity port').toBe( - 0 - ) + expect( + portListeners.size, + 'destroy must unsubscribe the identity port' + ).toBe(0) mockFetch.mockClear() vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = false @@ -2889,7 +2922,7 @@ describe('useWorkspaceAuthStore', () => { expect( portListeners.size, - 'a destroyed store must not reattach identity when the flag flips' + 'a destroyed store must not resubscribe identity when the flag flips' ).toBe(0) expect( mockFetch, @@ -2898,9 +2931,8 @@ describe('useWorkspaceAuthStore', () => { expect(store.getUnifiedToken()).toBeUndefined() }) - it('turning the flag OFF detaches the identity, clears the slot, and stops refreshing', async () => { + it('turning the flag OFF keeps the identity subscribed, clears the slot, and does not mint or refresh while the flag is off', async () => { vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true - vi.mocked(useAuthStore().getIdToken).mockResolvedValue( 'firebase-token-xyz' ) @@ -2927,14 +2959,63 @@ describe('useWorkspaceAuthStore', () => { expect(unifiedToken.value, 'the slot must empty on rollback').toBeNull() expect( portListeners.size, - 'the port must be detached, not left listening for the legacy rail' - ).toBe(0) + 'the port outlives the flag: identity is bound for the store lifetime' + ).toBe(1) await vi.advanceTimersByTimeAsync(expiresInMs) expect( mockFetch, 'no scheduled refresh may run for a disabled feature' ).toHaveBeenCalledTimes(1) expect(useAuthStore().notifyTokenRefreshed).not.toHaveBeenCalled() + + expect( + await store.mintAtLogin(), + 'the login mint is the gate: it must refuse while the flag is off' + ).toBe(false) + expect(mockFetch).toHaveBeenCalledTimes(1) + expect(unifiedToken.value).toBeNull() + + vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true + expect(await store.mintAtLogin()).toBe(true) + expect(mockFetch).toHaveBeenCalledTimes(2) + expect(unifiedToken.value).toBe('unified-token-1') + }) + + it('refuses a mint that parked on the identity before the flag went off', async () => { + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => Promise.resolve(personalTokenResponse) + }) + vi.stubGlobal('fetch', mockFetch) + vi.mocked(useAuthStore().getIdToken).mockResolvedValue( + 'firebase-token-xyz' + ) + + // A port that never replays on its own, so the mint parks on + // unifiedUser() until we deliver the user by hand. + const heldPort = replayIdentityPort(() => null) + vi.spyOn(useAuthStore().identity, 'onUserChanged').mockImplementation( + heldPort.register + ) + + const store = useWorkspaceAuthStore() + const { unifiedToken } = storeToRefs(store) + Object.assign(useAuthStore(), { currentUser: { uid: 'user-1' } }) + const parked = store.mintAtLogin() + + vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = false + await nextTick() + heldPort.emit(portUser({ uid: 'user-1' })) + + await expect( + parked, + 'a mint that resumes after the rollback must fail closed' + ).resolves.toBe(false) + expect( + mockFetch, + 'no /auth/token exchange may fire for a disabled feature' + ).not.toHaveBeenCalled() + expect(unifiedToken.value).toBeNull() }) it('is fully dormant under the flag OFF: no unified network, timer, or rotation', async () => { @@ -3290,7 +3371,7 @@ describe('useWorkspaceAuthStore', () => { expect(store.unifiedToken).toBeNull() const pending = store.mintAtLogin() - await vi.advanceTimersByTimeAsync(15_000) + await vi.advanceTimersByTimeAsync(UNIFIED_IDENTITY_SETTLE_TIMEOUT_MS) expect( await pending, diff --git a/src/platform/workspace/stores/workspaceAuthStore.ts b/src/platform/workspace/stores/workspaceAuthStore.ts index dbf7d011787..fc8b27cd611 100644 --- a/src/platform/workspace/stores/workspaceAuthStore.ts +++ b/src/platform/workspace/stores/workspaceAuthStore.ts @@ -60,7 +60,7 @@ const MAX_SCHEDULED_REFRESH_RETRIES = 3 const UNIFIED_REFRESH_RETRY_BASE_MS = 5000 /** Ceiling on waiting for the identity port before a host mint gives up. */ -const UNIFIED_IDENTITY_SETTLE_TIMEOUT_MS = 15_000 +export const UNIFIED_IDENTITY_SETTLE_TIMEOUT_MS = 15_000 const RECOVERY_COOLDOWN_MS = 5000 @@ -144,6 +144,9 @@ function surfacePermanentAuthError(err: WorkspaceAuthError): void { export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { const { flags } = useFeatureFlags() + // Read fresh after an await: the reactive flag can flip mid-mint, and a + // captured read is narrowed to the value at the function's opening guard. + const unifiedRailEnabled = () => flags.unifiedCloudAuthEnabled // State const currentWorkspace = shallowRef(null) @@ -330,8 +333,7 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { function destroy(): void { stopRefreshTimer() stopUnifiedFlagWatch() - detachUnifiedIdentity?.() - detachUnifiedIdentity = undefined + unifiedSessionClient.dispose() clearUnifiedContext() stopUnifiedSnapshot() } @@ -764,7 +766,6 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { let unifiedTarget: UnifiedMintBody | null = null let unifiedScheduledRetryCount = 0 let unifiedPermanentFailureSurfaced = false - let detachUnifiedIdentity: (() => void) | undefined function personalWorkspaceTarget(): UnifiedMintBody { return {} @@ -851,30 +852,36 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { // falls back to per-tab refresh. const crossTabRefreshPort = createWebCrossTabRefreshPort() - const unifiedSessionClient = createSessionClient({ - exchangeUrl: workspaceApiUrl('/auth/token'), - // In-memory only: a persisted JWT can outlive its server expiry, so a - // reload re-mints instead of rehydrating. - storage: { - read: () => null, - write: () => undefined, - clear: () => undefined + const unifiedSessionClient = createSessionClient( + { + exchangeUrl: workspaceApiUrl('/auth/token'), + autoMint: false, + // In-memory only: a persisted JWT can outlive its server expiry, so a + // reload re-mints instead of rehydrating. + storage: { + read: () => null, + write: () => undefined, + clear: () => undefined + }, + refreshScheduler: { + bufferMs: TOKEN_REFRESH_BUFFER_MS, + retryBaseMs: UNIFIED_REFRESH_RETRY_BASE_MS, + maxRetries: MAX_SCHEDULED_REFRESH_RETRIES, + onScheduledOutcome: handleScheduledRefreshOutcome, + ...(crossTabRefreshPort && { + crossTab: { + port: crossTabRefreshPort, + // A sibling's rotation is still a rotation for this tab: the + // session cookie and the onAuthTokenRefreshed hook must see it. + onCredentialAdopted: () => useAuthStore().notifyTokenRefreshed() + } + }) + } }, - refreshScheduler: { - bufferMs: TOKEN_REFRESH_BUFFER_MS, - retryBaseMs: UNIFIED_REFRESH_RETRY_BASE_MS, - maxRetries: MAX_SCHEDULED_REFRESH_RETRIES, - onScheduledOutcome: handleScheduledRefreshOutcome, - ...(crossTabRefreshPort && { - crossTab: { - port: crossTabRefreshPort, - // A sibling's rotation is still a rotation for this tab: the - // session cookie and the onAuthTokenRefreshed hook must see it. - onCredentialAdopted: () => useAuthStore().notifyTokenRefreshed() - } - }) - } - }) + // Keep synchronous within setup: Firebase's first delivery is a microtask, + // so this store is fully assigned before authStore's listener re-enters it. + useAuthStore().identity + ) const stopUnifiedSnapshot = unifiedSessionClient.subscribe((snapshot) => { if (snapshot.phase === 'authenticated') { @@ -906,34 +913,15 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { unifiedTokenOwnerUid.value = null }) - // The package's Firebase entry, bound in authStore to the app's own Auth - // instance, is the session client's identity source. No ordering with the - // auth listener's teardown is load-bearing: invalidate() keeps the - // identity, and the port fails closed on an identity change by itself. - function ensureUnifiedIdentityAttached(): void { - if (!flags.unifiedCloudAuthEnabled || detachUnifiedIdentity) return - detachUnifiedIdentity = unifiedSessionClient.attachIdentity( - useAuthStore().identity, - { autoMint: false } - ) - } - - // The flag owns both ends: enabling the rail must attach identity and mint - // the current target before consumers switch to it, or an already-signed-in - // session starts sending no auth header; a rollback must stop the unified - // scheduler and cross-tab lease, or they keep rotating the cookie and - // refilling the slot the API callers no longer read. + // Identity is bound for the store's lifetime; the flag gates minting, and a + // rollback invalidates the credential, so scheduler and cross-tab lease stop. const stopUnifiedFlagWatch = watch( () => flags.unifiedCloudAuthEnabled, (enabled) => { if (enabled) { - ensureUnifiedIdentityAttached() void mintAtLogin() return } - if (!detachUnifiedIdentity) return - detachUnifiedIdentity() - detachUnifiedIdentity = undefined clearUnifiedContext() } ) @@ -946,7 +934,6 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { * ceiling, so a caller can fail closed instead of hanging. */ function unifiedUser(): Promise { - ensureUnifiedIdentityAttached() const expectedUid = useAuthStore().currentUser?.uid ?? null const matches = (user: User | null) => (user?.uid ?? null) === expectedUid const current = unifiedSessionClient.getSnapshot().user @@ -995,6 +982,9 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { await import('@/platform/auth/session/useSessionCookie') await useSessionCookie().ensureSessionCookie() const authUser = await unifiedUser() + // A rollback during the awaits above must abort the unified switch rather + // than commit a token for a flag that is now off. + if (!unifiedRailEnabled()) return if (!authUser) { throw new WorkspaceAuthError('Workspace identity changed during switch') } @@ -1031,7 +1021,9 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { return true } const authUser = await unifiedUser() - if (!authUser) { + // Re-check after the wait: a rollback that flips the flag off while a mint + // is parked on unifiedUser() must not let the resumed mint commit a token. + if (!unifiedRailEnabled() || !authUser) { return false } const target = currentUnifiedTarget() ?? personalWorkspaceTarget() @@ -1076,7 +1068,7 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { } if (expectedToken !== currentToken) return currentToken const authUser = await unifiedUser() - if (!authUser) return null + if (!unifiedRailEnabled() || !authUser) return null const result = await unifiedSessionClient.remint(authUser, { workspaceId: unifiedWorkspaceIdFor(target), preserveCredentialOnTransientFailure: true diff --git a/src/stores/authStore.test.ts b/src/stores/authStore.test.ts index 8e36a6aabc0..c1dc046eeca 100644 --- a/src/stores/authStore.test.ts +++ b/src/stores/authStore.test.ts @@ -26,6 +26,8 @@ import { useDialogService } from '@/services/dialogService' import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' import { api } from '@/scripts/api' import { AuthStoreError, useAuthStore } from '@/stores/authStore' +import type { IdentityObserver } from '@/utils/__tests__/stubAccountIdentityPort' +import { replayIdentityPort } from '@/utils/__tests__/stubAccountIdentityPort' const { mockDistributionTypes } = vi.hoisted(() => ({ mockDistributionTypes: { @@ -119,7 +121,7 @@ describe('useAuthStore', () => { delete: vi.fn().mockResolvedValue(undefined) } as Partial as MockUser - beforeEach(() => { + beforeEach(async () => { mockResetSocket = vi.spyOn(api, 'resetSocket').mockResolvedValue(undefined) vi.stubGlobal('fetch', mockFetch) clearPreservedQuery(PRESERVED_QUERY_NAMESPACES.SHARE_AUTH) @@ -131,18 +133,10 @@ describe('useAuthStore', () => { > as ReturnType ) - // Every observer registered on the Auth instance (the store's listener - // and the package port) gets each auth-state event, as Firebase does. - const authStateObservers: Array<(user: User | null) => void> = [] - authStateCallback = (user) => - authStateObservers.forEach((observer) => observer(user)) + const port = replayIdentityPort(() => mockUser) + authStateCallback = port.emit vi.mocked(firebaseAuth.onAuthStateChanged).mockImplementation( - (_, callback) => { - const observer = callback as (user: User | null) => void - authStateObservers.push(observer) - observer(mockUser) - return vi.fn() - } + (_, callback) => port.register(callback as IdentityObserver) ) vi.mocked(firebaseAuth.onIdTokenChanged).mockImplementation( (_auth, callback) => { @@ -169,6 +163,7 @@ describe('useAuthStore', () => { }) store = useAuthStore() + await vi.waitFor(() => expect(store.isInitialized).toBe(true)) // Reset and set up getIdToken mock mockUser.getIdToken.mockResolvedValue('mock-id-token') @@ -338,14 +333,26 @@ describe('useAuthStore', () => { describe('unified identity source', () => { it('the session client listens to the same Auth instance through the package port', async () => { vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true - vi.mocked(firebaseAuth.onAuthStateChanged).mockClear() + const observedAuths = () => + vi + .mocked(firebaseAuth.onAuthStateChanged) + .mock.calls.map(([auth]) => auth) + const registeredAtConstruction = observedAuths().length + expect( + registeredAtConstruction, + 'the store listener and the port both registered' + ).toBe(2) + expect( + new Set(observedAuths()), + 'every observer, the port included, targets the one Auth instance; identity is not pushed from this store' + ).toEqual(new Set([mockAuth])) await useWorkspaceAuthStore().mintAtLogin() expect( - vi.mocked(firebaseAuth.onAuthStateChanged), - 'the port registers its own observer on the same Auth instance; identity is not pushed from this store' - ).toHaveBeenCalledExactlyOnceWith(mockAuth, expect.any(Function)) + observedAuths(), + 'a mint reuses the port subscribed at construction' + ).toHaveLength(registeredAtConstruction) }) }) @@ -2339,7 +2346,7 @@ describe('useAuthStore in local/desktop distribution', () => { delete: vi.fn().mockResolvedValue(undefined) } as Partial as MockUser - beforeEach(() => { + beforeEach(async () => { mockDistributionTypes.isCloud = false mockDistributionTypes.isDesktop = false mockDistributionTypes.DISTRIBUTION = 'localhost' @@ -2352,12 +2359,10 @@ describe('useAuthStore in local/desktop distribution', () => { > as ReturnType ) + const port = replayIdentityPort(() => mockUser) + authStateCallback = port.emit vi.mocked(firebaseAuth.onAuthStateChanged).mockImplementation( - (_, callback) => { - authStateCallback = callback as (user: User | null) => void - ;(callback as (user: User | null) => void)(mockUser) - return vi.fn() - } + (_, callback) => port.register(callback as IdentityObserver) ) vi.mocked(firebaseAuth.onIdTokenChanged).mockImplementation(() => vi.fn()) @@ -2369,6 +2374,7 @@ describe('useAuthStore in local/desktop distribution', () => { }) store = useAuthStore() + await vi.waitFor(() => expect(store.isInitialized).toBe(true)) mockUser.getIdToken.mockResolvedValue('mock-id-token') mockResetSocket.mockClear() }) @@ -2432,3 +2438,64 @@ describe('useAuthStore in local/desktop distribution', () => { ).not.toHaveBeenCalled() }) }) + +describe('store construction order', () => { + const mockAuth: MockAuth = {} + const mockUser: MockUser = { + uid: 'construction-user-id', + email: 'construction@example.com', + getIdToken: vi.fn().mockResolvedValue('mock-id-token'), + delete: vi.fn().mockResolvedValue(undefined) + } as Partial as MockUser + const tokenResponse = { + token: 'construction-token', + expires_at: new Date(Date.now() + 3600 * 1000).toISOString(), + workspace: { id: 'workspace-personal', name: 'Personal', type: 'personal' }, + role: 'owner', + permissions: ['owner:*'] + } + + beforeEach(() => { + vi.stubGlobal('fetch', mockFetch) + vi.mocked(useDialogService, { partial: true }).mockReturnValue({ + showErrorDialog: vi.fn() + }) + vi.mocked(vuefire.useFirebaseAuth).mockReturnValue( + mockAuth as Partial< + ReturnType + > as ReturnType + ) + vi.mocked(firebaseAuth.onIdTokenChanged).mockImplementation(() => vi.fn()) + vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true + mockUser.getIdToken.mockResolvedValue('mock-id-token') + mockFetch.mockImplementation((url: string) => { + if (url.endsWith('/customers')) { + return Promise.resolve(mockCreateCustomerResponse) + } + if (url.endsWith('/auth/token')) { + return Promise.resolve({ + ok: true, + json: () => Promise.resolve(tokenResponse) + }) + } + return Promise.reject(new Error('Unexpected API call')) + }) + }) + + it('building the workspace store first subscribes its port and mints once Firebase delivers on its microtask', async () => { + const port = replayIdentityPort(() => mockUser) + vi.mocked(firebaseAuth.onAuthStateChanged).mockImplementation( + (_, callback) => port.register(callback as IdentityObserver) + ) + + const workspaceAuth = useWorkspaceAuthStore() + await vi.waitFor(() => expect(useAuthStore().isInitialized).toBe(true)) + + expect( + port.observers.size, + 'the authStore listener and the session client port' + ).toBe(2) + await expect(workspaceAuth.mintAtLogin()).resolves.toBe(true) + expect(workspaceAuth.getUnifiedToken()).toBe('construction-token') + }) +}) diff --git a/src/utils/__tests__/stubAccountIdentityPort.ts b/src/utils/__tests__/stubAccountIdentityPort.ts new file mode 100644 index 00000000000..0853d31cfee --- /dev/null +++ b/src/utils/__tests__/stubAccountIdentityPort.ts @@ -0,0 +1,42 @@ +import type { User } from 'firebase/auth' +import { vi } from 'vitest' + +import { useAuthStore } from '@/stores/authStore' + +export type IdentityObserver = (user: User | null) => void + +/** + * Silences the session client's construction-time port subscription: the spy + * keeps the identity's lazy auth resolver from reaching `firebase/app`; the + * suite's `firebase/auth` automock already silences `onAuthStateChanged`. + * Call after the suite's `firebase/auth` stubs and before the first + * `useWorkspaceAuthStore()`. + */ +export function stubAccountIdentityPort(): void { + vi.spyOn(useAuthStore().identity, 'onUserChanged').mockReturnValue(() => {}) +} + +/** + * Fakes the auth-state registration behind the identity port: every observer + * joins `observers` and is replayed with `currentUser()` on registration. + * Firebase resolves persistence before its first emission, so 'microtask' is + * the SDK's timing; 'sync' exists to prove what does not depend on it. + */ +export function replayIdentityPort( + currentUser: () => User | null, + deliver: 'microtask' | 'sync' = 'microtask' +) { + const observers = new Set() + const register = (observer: IdentityObserver): (() => void) => { + observers.add(observer) + const replay = () => { + if (observers.has(observer)) observer(currentUser()) + } + if (deliver === 'sync') replay() + else queueMicrotask(replay) + return () => observers.delete(observer) + } + const emit = (user: User | null): void => + observers.forEach((observer) => observer(user)) + return { observers, register, emit } +}