diff --git a/src/platform/workspace/stores/legacyWorkspaceTokenRail.lifecycle.test.ts b/src/platform/workspace/stores/legacyWorkspaceTokenRail.lifecycle.test.ts new file mode 100644 index 00000000000..14a6f672a0a --- /dev/null +++ b/src/platform/workspace/stores/legacyWorkspaceTokenRail.lifecycle.test.ts @@ -0,0 +1,657 @@ +import { ref, shallowRef } from 'vue' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type { LegacyWorkspaceTokenRailDeps } from '@/platform/workspace/stores/legacyWorkspaceTokenRail' +import { createLegacyWorkspaceTokenRail } from '@/platform/workspace/stores/legacyWorkspaceTokenRail' +import { + TOKEN_REFRESH_BUFFER_MS, + WORKSPACE_STORAGE_KEYS +} from '@/platform/workspace/workspaceConstants' +import type { WorkspaceIdentity } from '@/platform/workspace/workspaceTypes' + +const mockEnsureSessionCookie = vi.hoisted(() => vi.fn()) +const mockDistributionTypes = vi.hoisted(() => ({ isCloud: true })) + +vi.mock(import('@/platform/distribution/types'), () => mockDistributionTypes) + +vi.mock(import('@/platform/workspace/api/workspaceApiUrl'), () => ({ + workspaceApiUrl: (route: string) => `https://api.example.com/api${route}` +})) + +vi.mock(import('@/platform/auth/session/useSessionCookie'), () => ({ + useSessionCookie: () => ({ ensureSessionCookie: mockEnsureSessionCookie }) +})) + +const workspace: WorkspaceIdentity = { + id: 'workspace-123', + name: 'Test Workspace', + type: 'team', + role: 'owner' +} + +const expiresInMs = 3600 * 1000 +const recoveryCooldownMs = 5000 +const retryBackoffTotalMs = 1000 + 2000 + 4000 + +function tokenResponse( + overrides: Record = {}, + workspaceId = workspace.id +) { + return { + ok: true, + json: () => + Promise.resolve({ + token: `token-${workspaceId}`, + expires_at: new Date(Date.now() + expiresInMs).toISOString(), + workspace: { id: workspaceId, name: workspace.name, type: 'team' }, + role: 'owner', + permissions: ['owner:*'], + ...overrides + }) + } +} + +function failedResponse(status: number) { + return { + ok: false, + status, + statusText: `HTTP ${status}`, + text: () => Promise.resolve(JSON.stringify({ message: 'nope' })) + } +} + +function createRail() { + const identity = { uid: 'user-a' as string | null } + const deps: LegacyWorkspaceTokenRailDeps = { + currentWorkspace: shallowRef(null), + isLoading: ref(false), + error: ref(null), + currentUserUid: () => identity.uid, + isCurrentUser: (ownerUid: string) => ownerUid === identity.uid, + getIdToken: vi.fn(async () => 'firebase-token'), + hasSignedInUser: vi.fn(() => true), + activeWorkspaceId: vi.fn(() => null), + switchWorkspace: vi.fn((workspaceId: string) => + rail.switchLegacyWorkspace(workspaceId) + ), + endWorkspaceSession: vi.fn(() => { + rail.clearLegacyContext() + return false + }), + persistWorkspaceIdentity: vi.fn(), + clearSessionStorage: vi.fn(), + surfacePermanentAuthError: vi.fn() + } + const rail = createLegacyWorkspaceTokenRail(deps) + return { rail, deps, identity } +} + +type SessionKey = 'CURRENT_WORKSPACE' | 'TOKEN' | 'EXPIRES_AT' | 'OWNER_UID' +const sessionKeys: readonly SessionKey[] = [ + 'CURRENT_WORKSPACE', + 'TOKEN', + 'EXPIRES_AT', + 'OWNER_UID' +] + +function seedSession( + overrides: Partial> = {} +): void { + const entries: Record = { + CURRENT_WORKSPACE: JSON.stringify(workspace), + TOKEN: 'token-workspace-123', + EXPIRES_AT: String(Date.now() + expiresInMs), + OWNER_UID: 'user-a', + ...overrides + } + for (const key of sessionKeys) { + const value = entries[key] + if (value !== null) + sessionStorage.setItem(WORKSPACE_STORAGE_KEYS[key], value) + } +} + +let mockFetch: ReturnType + +beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: false }) + mockDistributionTypes.isCloud = true + mockEnsureSessionCookie.mockResolvedValue(undefined) + mockFetch = vi.fn((_url: string, init: { body: string }) => { + const { workspace_id: workspaceId } = JSON.parse(init.body) + return Promise.resolve(tokenResponse({}, workspaceId)) + }) + vi.stubGlobal('fetch', mockFetch) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.spyOn(console, 'error').mockImplementation(() => {}) +}) + +describe('minting a workspace token', () => { + it.for([ + { + failure: 'no signed-in user', + uid: null, + idToken: 'firebase-token', + response: tokenResponse, + code: 'NOT_AUTHENTICATED' + }, + { + failure: 'no identity token', + uid: 'user-a', + idToken: undefined, + response: tokenResponse, + code: 'NOT_AUTHENTICATED' + }, + { + failure: 'a 401', + uid: 'user-a', + idToken: 'firebase-token', + response: () => failedResponse(401), + code: 'INVALID_FIREBASE_TOKEN' + }, + { + failure: 'a 403', + uid: 'user-a', + idToken: 'firebase-token', + response: () => failedResponse(403), + code: 'ACCESS_DENIED' + }, + { + failure: 'a 404', + uid: 'user-a', + idToken: 'firebase-token', + response: () => failedResponse(404), + code: 'WORKSPACE_NOT_FOUND' + }, + { + failure: 'a 500', + uid: 'user-a', + idToken: 'firebase-token', + response: () => failedResponse(500), + code: 'TOKEN_EXCHANGE_FAILED' + }, + { + failure: 'a body that fails the schema', + uid: 'user-a', + idToken: 'firebase-token', + response: () => ({ ok: true, json: () => Promise.resolve({ token: 1 }) }), + code: 'TOKEN_EXCHANGE_FAILED' + }, + { + failure: 'an unparsable expiry', + uid: 'user-a', + idToken: 'firebase-token', + response: () => tokenResponse({ expires_at: 'never' }), + code: 'TOKEN_EXCHANGE_FAILED' + } + ])( + 'fails closed with $code on $failure', + async ({ uid, idToken, response, code }) => { + const { rail, deps, identity } = createRail() + identity.uid = uid + vi.mocked(deps.getIdToken).mockResolvedValue(idToken) + mockFetch.mockResolvedValue(response()) + + await expect( + rail.switchLegacyWorkspace('workspace-123') + ).rejects.toMatchObject({ code }) + + expect(rail.workspaceToken.value).toBeNull() + expect(deps.error.value).toMatchObject({ code }) + expect(deps.persistWorkspaceIdentity).not.toHaveBeenCalled() + } + ) + + it('discards a mint that lands after the user changes and settles loading', async () => { + const { rail, deps, identity } = createRail() + let deliverToken: (value: unknown) => void = () => {} + mockFetch.mockReturnValue( + new Promise((resolve) => { + deliverToken = resolve + }) + ) + + const switching = rail.switchLegacyWorkspace('workspace-123') + await vi.advanceTimersByTimeAsync(1) + expect(mockFetch).toHaveBeenCalledOnce() + expect(deps.isLoading.value).toBe(true) + identity.uid = 'user-b' + deliverToken(tokenResponse()) + await switching + + expect(rail.workspaceToken.value).toBeNull() + expect(deps.currentWorkspace.value).toBeNull() + expect(deps.persistWorkspaceIdentity).not.toHaveBeenCalled() + expect(deps.error.value).toBeNull() + expect(deps.isLoading.value).toBe(false) + }) +}) + +describe('restoring a session', () => { + it.for([ + { session: 'has no token', overrides: { TOKEN: null } }, + { session: 'belongs to another user', overrides: { OWNER_UID: 'user-b' } }, + { session: 'has expired', overrides: { EXPIRES_AT: '0' } }, + { session: 'has an unparsable expiry', overrides: { EXPIRES_AT: 'soon' } }, + { + session: 'carries an identity that fails the schema', + overrides: { CURRENT_WORKSPACE: JSON.stringify({ id: 'workspace-123' }) } + }, + { + session: 'carries corrupt identity JSON', + overrides: { CURRENT_WORKSPACE: '{' } + } + ])('does not restore a session that $session', ({ overrides }) => { + const { rail, deps } = createRail() + seedSession(overrides) + + expect(rail.initializeFromSession()).toBe(false) + + expect(deps.clearSessionStorage).toHaveBeenCalledOnce() + expect(deps.currentWorkspace.value).toBeNull() + expect(rail.hasValidWorkspaceToken()).toBe(false) + }) + + it('restores a valid session and arms its refresh', async () => { + const { rail, deps } = createRail() + seedSession() + + expect(rail.initializeFromSession()).toBe(true) + + expect(deps.currentWorkspace.value).toEqual(workspace) + expect(rail.getWorkspaceToken()).toBe('token-workspace-123') + await vi.advanceTimersByTimeAsync(expiresInMs - TOKEN_REFRESH_BUFFER_MS) + expect(deps.switchWorkspace).toHaveBeenCalledExactlyOnceWith( + 'workspace-123' + ) + }) +}) + +describe('ensureWorkspaceToken', () => { + it('serves the held token without a mint while it is valid for the target', async () => { + const { rail } = createRail() + await rail.switchLegacyWorkspace('workspace-123') + + await expect(rail.ensureWorkspaceToken('workspace-123')).resolves.toBe( + 'token-workspace-123' + ) + expect(mockFetch).toHaveBeenCalledOnce() + }) + + it.for([ + { + when: 'nobody is signed in', + uid: null, + isCloud: true, + active: null, + target: 'workspace-123', + token: null, + mints: 0 + }, + { + when: 'there is no target workspace', + uid: 'user-a', + isCloud: true, + active: null, + target: undefined, + token: null, + mints: 0 + }, + { + when: 'the local active workspace differs', + uid: 'user-a', + isCloud: false, + active: 'workspace-other', + target: 'workspace-123', + token: null, + mints: 0 + }, + { + when: 'the local active workspace matches', + uid: 'user-a', + isCloud: false, + active: 'workspace-123', + target: 'workspace-123', + token: 'token-workspace-123', + mints: 1 + }, + { + when: 'cloud ignores the local selection', + uid: 'user-a', + isCloud: true, + active: 'workspace-other', + target: 'workspace-123', + token: 'token-workspace-123', + mints: 1 + } + ])( + 'resolves $token with $mints mint(s) when $when', + async ({ uid, isCloud, active, target, token, mints }) => { + mockDistributionTypes.isCloud = isCloud + const { rail, deps, identity } = createRail() + identity.uid = uid + vi.mocked(deps.activeWorkspaceId).mockReturnValue(active) + + await expect(rail.ensureWorkspaceToken(target)).resolves.toBe(token) + expect(mockFetch).toHaveBeenCalledTimes(mints) + } + ) + + it.for([ + { retry: 'immediately', after: 0, mints: 1 }, + { + retry: 'just inside the cooldown', + after: recoveryCooldownMs - 1, + mints: 1 + }, + { retry: 'once the cooldown lapses', after: recoveryCooldownMs, mints: 2 } + ])( + 'backs off a failed recovery: retrying $retry makes $mints mint(s)', + async ({ after, mints }) => { + const { rail } = createRail() + mockFetch.mockResolvedValue(failedResponse(500)) + + await expect( + rail.ensureWorkspaceToken('workspace-123') + ).resolves.toBeNull() + vi.advanceTimersByTime(after) + await expect( + rail.ensureWorkspaceToken('workspace-123') + ).resolves.toBeNull() + + expect(mockFetch).toHaveBeenCalledTimes(mints) + } + ) + + it('retries at once after a revoked selection has been forgotten', async () => { + const { rail, deps } = createRail() + vi.mocked(deps.endWorkspaceSession).mockImplementation(() => { + rail.clearLegacyContext() + return true + }) + mockFetch.mockResolvedValueOnce(failedResponse(403)) + + await expect(rail.ensureWorkspaceToken('workspace-123')).resolves.toBeNull() + await expect(rail.ensureWorkspaceToken('workspace-123')).resolves.toBe( + 'token-workspace-123' + ) + + expect(mockFetch).toHaveBeenCalledTimes(2) + }) + + it('fails closed and backs off when the mint lands on a different workspace', async () => { + const { rail } = createRail() + mockFetch.mockResolvedValue(tokenResponse({}, 'workspace-123')) + + await expect(rail.ensureWorkspaceToken('workspace-456')).resolves.toBeNull() + await expect(rail.ensureWorkspaceToken('workspace-456')).resolves.toBeNull() + + expect(mockFetch).toHaveBeenCalledOnce() + }) + + it.for([ + { + failure: 'a 403', + idToken: 'firebase-token', + signedIn: true, + response: () => failedResponse(403), + ended: [['workspace-999']], + surfaced: 1 + }, + { + failure: 'a 404', + idToken: 'firebase-token', + signedIn: true, + response: () => failedResponse(404), + ended: [['workspace-999']], + surfaced: 1 + }, + { + failure: 'a 401', + idToken: 'firebase-token', + signedIn: true, + response: () => failedResponse(401), + ended: [[undefined]], + surfaced: 1 + }, + { + failure: 'a 500', + idToken: 'firebase-token', + signedIn: true, + response: () => failedResponse(500), + ended: [], + surfaced: 0 + }, + { + failure: 'a missing identity token while signed in', + idToken: undefined, + signedIn: true, + response: tokenResponse, + ended: [], + surfaced: 0 + }, + { + failure: 'a missing identity token after sign-out', + idToken: undefined, + signedIn: false, + response: tokenResponse, + ended: [[undefined]], + surfaced: 1 + } + ])( + 'classifies $failure during recovery', + async ({ idToken, signedIn, response, ended, surfaced }) => { + const { rail, deps } = createRail() + await rail.switchLegacyWorkspace('workspace-123') + vi.mocked(deps.getIdToken).mockResolvedValue(idToken) + vi.mocked(deps.hasSignedInUser).mockReturnValue(signedIn) + mockFetch.mockResolvedValue(response()) + + await expect( + rail.ensureWorkspaceToken('workspace-999') + ).resolves.toBeNull() + + expect(vi.mocked(deps.endWorkspaceSession).mock.calls).toEqual(ended) + expect(deps.surfacePermanentAuthError).toHaveBeenCalledTimes(surfaced) + } + ) + + it('collapses concurrent callers onto the in-flight mint', async () => { + const { rail } = createRail() + let deliverToken: (value: unknown) => void = () => {} + mockFetch.mockReturnValueOnce( + new Promise((resolve) => { + deliverToken = resolve + }) + ) + + const switching = rail.switchLegacyWorkspace('workspace-123') + const waiters = Promise.all([ + rail.ensureWorkspaceToken('workspace-123'), + rail.ensureWorkspaceToken('workspace-123') + ]) + deliverToken(tokenResponse()) + await switching + + await expect(waiters).resolves.toEqual([ + 'token-workspace-123', + 'token-workspace-123' + ]) + expect(mockFetch).toHaveBeenCalledOnce() + }) + + it.for([ + { + distribution: 'cloud', + isCloud: true, + token: 'token-workspace-123', + current: 'workspace-123', + mints: 2 + }, + { + distribution: 'local', + isCloud: false, + token: null, + current: 'workspace-other', + mints: 1 + } + ])( + 'after joining a switch to another workspace on $distribution, resolves $token', + async ({ isCloud, token, current, mints }) => { + mockDistributionTypes.isCloud = isCloud + const { rail, deps } = createRail() + vi.mocked(deps.activeWorkspaceId).mockReturnValue('workspace-123') + + const switching = rail.switchLegacyWorkspace('workspace-other') + const recovered = rail.ensureWorkspaceToken('workspace-123') + await switching + + await expect(recovered).resolves.toBe(token) + expect(deps.currentWorkspace.value?.id).toBe(current) + expect(mockFetch).toHaveBeenCalledTimes(mints) + } + ) +}) + +describe('refreshToken', () => { + it('is a no-op without a workspace context', async () => { + const { rail } = createRail() + + await rail.refreshToken() + + expect(mockFetch).not.toHaveBeenCalled() + }) + + it.for([ + { + failure: 'a 403', + response: () => failedResponse(403), + fetches: 2, + ended: [['workspace-123']], + token: undefined + }, + { + failure: 'a 404', + response: () => failedResponse(404), + fetches: 2, + ended: [['workspace-123']], + token: undefined + }, + { + failure: 'a 401', + response: () => failedResponse(401), + fetches: 2, + ended: [[undefined]], + token: undefined + } + ])( + 'settles $failure after $fetches exchange(s)', + async ({ response, fetches, ended, token }) => { + const { rail, deps } = createRail() + await rail.switchLegacyWorkspace('workspace-123') + mockFetch.mockResolvedValue(response()) + + const refreshing = rail.refreshToken() + await vi.advanceTimersByTimeAsync(retryBackoffTotalMs) + await refreshing + + expect(mockFetch).toHaveBeenCalledTimes(fetches) + expect(vi.mocked(deps.endWorkspaceSession).mock.calls).toEqual(ended) + expect(rail.getWorkspaceToken()).toBe(token) + } + ) + + it('retries repeated 500s on a doubling backoff, then keeps the held token', async () => { + const { rail, deps } = createRail() + await rail.switchLegacyWorkspace('workspace-123') + mockFetch.mockResolvedValue(failedResponse(500)) + + const refreshing = rail.refreshToken() + await vi.advanceTimersByTimeAsync(999) + expect(mockFetch).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(1) + expect(mockFetch).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(1999) + expect(mockFetch).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(1) + expect(mockFetch).toHaveBeenCalledTimes(4) + await vi.advanceTimersByTimeAsync(3999) + expect(mockFetch).toHaveBeenCalledTimes(4) + await vi.advanceTimersByTimeAsync(1) + expect(mockFetch).toHaveBeenCalledTimes(5) + await refreshing + + expect(deps.endWorkspaceSession).not.toHaveBeenCalled() + expect(rail.getWorkspaceToken()).toBe('token-workspace-123') + }) + + it('ends the session without retrying when the mint fails before the exchange', async () => { + const { rail, deps } = createRail() + await rail.switchLegacyWorkspace('workspace-123') + mockEnsureSessionCookie.mockRejectedValue(new Error('offline')) + + const refreshing = rail.refreshToken() + await vi.advanceTimersByTimeAsync(retryBackoffTotalMs) + await refreshing + + expect(mockFetch).toHaveBeenCalledOnce() + expect(vi.mocked(deps.endWorkspaceSession).mock.calls).toEqual([[]]) + }) + + it.for([ + { held: 'has expired', clockAdvanceMs: expiresInMs + 1, uid: 'user-a' }, + { held: 'belongs to another user', clockAdvanceMs: 0, uid: 'user-b' } + ])( + 'ends the session once retries are exhausted and the held token $held', + async ({ clockAdvanceMs, uid }) => { + const { rail, deps, identity } = createRail() + await rail.switchLegacyWorkspace('workspace-123') + mockFetch.mockResolvedValue(failedResponse(500)) + vi.setSystemTime(Date.now() + clockAdvanceMs) + identity.uid = uid + + const refreshing = rail.refreshToken() + await vi.advanceTimersByTimeAsync(retryBackoffTotalMs) + await refreshing + + expect(mockFetch).toHaveBeenCalledTimes(5) + expect(vi.mocked(deps.endWorkspaceSession).mock.calls).toEqual([[]]) + } + ) + + it('abandons the retry chain once the workspace context has moved on', async () => { + const { rail, deps } = createRail() + await rail.switchLegacyWorkspace('workspace-123') + mockFetch.mockResolvedValueOnce(failedResponse(500)) + + const refreshing = rail.refreshToken() + await vi.advanceTimersByTimeAsync(999) + rail.clearLegacyContext() + await vi.advanceTimersByTimeAsync(retryBackoffTotalMs) + await refreshing + + expect(mockFetch).toHaveBeenCalledTimes(2) + expect(deps.currentWorkspace.value).toBeNull() + expect(deps.endWorkspaceSession).not.toHaveBeenCalled() + }) + + it('caps scheduled refresh retries and ends the session at expiry', async () => { + const { rail, deps } = createRail() + await rail.switchLegacyWorkspace('workspace-123') + mockFetch.mockResolvedValue(failedResponse(500)) + + const refreshing = rail.refreshToken() + await vi.advanceTimersByTimeAsync(60_000) + await refreshing + + expect(mockFetch).toHaveBeenCalledTimes(17) + expect(rail.getWorkspaceToken()).toBe('token-workspace-123') + expect(deps.error.value).toBeNull() + expect(deps.endWorkspaceSession).not.toHaveBeenCalled() + + await vi.advanceTimersByTimeAsync(expiresInMs - 60_000) + + expect(mockFetch).toHaveBeenCalledTimes(17) + expect(vi.mocked(deps.endWorkspaceSession).mock.calls).toEqual([[]]) + }) +}) diff --git a/src/platform/workspace/stores/legacyWorkspaceTokenRail.test.ts b/src/platform/workspace/stores/legacyWorkspaceTokenRail.test.ts new file mode 100644 index 00000000000..70c8de7b31f --- /dev/null +++ b/src/platform/workspace/stores/legacyWorkspaceTokenRail.test.ts @@ -0,0 +1,123 @@ +import { ref, shallowRef } from 'vue' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type { LegacyWorkspaceTokenRailDeps } from '@/platform/workspace/stores/legacyWorkspaceTokenRail' +import { createLegacyWorkspaceTokenRail } from '@/platform/workspace/stores/legacyWorkspaceTokenRail' +import type { WorkspaceIdentity } from '@/platform/workspace/workspaceTypes' + +vi.mock(import('@/platform/auth/session/useSessionCookie'), () => ({ + useSessionCookie: () => ({ ensureSessionCookie: vi.fn() }) +})) + +const workspace: WorkspaceIdentity = { + id: 'workspace-123', + name: 'Test Workspace', + type: 'team', + role: 'owner' +} + +const expiresInMs = 3600 * 1000 + +function makeDeps(): LegacyWorkspaceTokenRailDeps { + return { + currentWorkspace: shallowRef(null), + isLoading: ref(false), + error: ref(null), + currentUserUid: vi.fn(() => 'user-a'), + isCurrentUser: vi.fn((ownerUid: string) => ownerUid === 'user-a'), + getIdToken: vi.fn(async () => 'firebase-token'), + hasSignedInUser: vi.fn(() => true), + activeWorkspaceId: vi.fn(() => null), + switchWorkspace: vi.fn(async () => {}), + endWorkspaceSession: vi.fn(() => false), + persistWorkspaceIdentity: vi.fn(), + clearSessionStorage: vi.fn(), + surfacePermanentAuthError: vi.fn() + } +} + +describe('createLegacyWorkspaceTokenRail', () => { + let mockFetch: ReturnType + + beforeEach(() => { + vi.useFakeTimers({ shouldAdvanceTime: false }) + mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => + Promise.resolve({ + token: 'workspace-token-abc', + expires_at: new Date(Date.now() + expiresInMs).toISOString(), + workspace: { id: workspace.id, name: workspace.name, type: 'team' }, + role: 'owner', + permissions: ['owner:*'] + }) + }) + vi.stubGlobal('fetch', mockFetch) + }) + + it('mints through the identity token and persists the workspace identity', async () => { + const deps = makeDeps() + const rail = createLegacyWorkspaceTokenRail(deps) + + await rail.switchLegacyWorkspace('workspace-123') + + expect(mockFetch).toHaveBeenCalledWith( + expect.stringContaining('/auth/token'), + expect.objectContaining({ + headers: expect.objectContaining({ + Authorization: 'Bearer firebase-token' + }), + body: JSON.stringify({ workspace_id: 'workspace-123' }) + }) + ) + expect(rail.workspaceToken.value).toBe('workspace-token-abc') + expect(deps.currentWorkspace.value).toEqual(workspace) + expect(deps.persistWorkspaceIdentity).toHaveBeenCalledWith(workspace) + }) + + it.for([ + { owner: 'the current user', currentUser: true, valid: true }, + { owner: 'another user', currentUser: false, valid: false } + ])( + 'a minted token is valid only while owned by $owner', + async ({ currentUser, valid }) => { + const deps = makeDeps() + const rail = createLegacyWorkspaceTokenRail(deps) + await rail.switchLegacyWorkspace('workspace-123') + + vi.mocked(deps.isCurrentUser).mockReturnValue(currentUser) + + expect(rail.hasValidWorkspaceToken()).toBe(valid) + } + ) + + it('clears the token and the workspace identity together', async () => { + const deps = makeDeps() + const rail = createLegacyWorkspaceTokenRail(deps) + await rail.switchLegacyWorkspace('workspace-123') + + rail.clearLegacyContext() + + expect(rail.workspaceToken.value).toBeNull() + expect(deps.currentWorkspace.value).toBeNull() + expect(rail.hasValidWorkspaceToken()).toBe(false) + }) + + it.for([ + { timer: 'armed', stop: false, refreshes: 1 }, + { timer: 'stopped', stop: true, refreshes: 0 } + ])( + 'the refresh deadline dispatches $refreshes refresh(es) with the timer $timer', + async ({ stop, refreshes }) => { + const deps = makeDeps() + const rail = createLegacyWorkspaceTokenRail(deps) + await rail.switchLegacyWorkspace('workspace-123') + + if (stop) rail.stopRefreshTimer() + await vi.advanceTimersByTimeAsync(expiresInMs) + + expect(deps.switchWorkspace).toHaveBeenCalledTimes(refreshes) + expect(mockFetch).toHaveBeenCalledOnce() + } + ) +}) diff --git a/src/platform/workspace/stores/legacyWorkspaceTokenRail.ts b/src/platform/workspace/stores/legacyWorkspaceTokenRail.ts new file mode 100644 index 00000000000..9fb5a7d8b9a --- /dev/null +++ b/src/platform/workspace/stores/legacyWorkspaceTokenRail.ts @@ -0,0 +1,724 @@ +import { zWorkspaceWithRole } from '@comfyorg/ingest-types/zod' +import { delay } from 'es-toolkit' +import type { Ref, ShallowRef } from 'vue' +import { ref } from 'vue' +import { z } from 'zod' +import { fromZodError } from 'zod-validation-error' + +import { t } from '@/i18n' +import { isCloud } from '@/platform/distribution/types' +import { parseErrorResponse } from '@/platform/remote/comfyui/errors' +import { workspaceApiUrl } from '@/platform/workspace/api/workspaceApiUrl' +import { WorkspaceAuthError } from '@/platform/workspace/stores/workspaceAuthError' +import { + MAX_SCHEDULED_REFRESH_RETRIES, + TOKEN_REFRESH_BUFFER_MS, + WORKSPACE_STORAGE_KEYS +} from '@/platform/workspace/workspaceConstants' +import type { WorkspaceIdentity } from '@/platform/workspace/workspaceTypes' +import type { AuthHeader } from '@/types/authTypes' + +// Picked off the generated schema: a hand-written enum that lags the spec would +// reject a valid persisted identity and silently clear the session. +const WorkspaceIdentitySchema = zWorkspaceWithRole.pick({ + id: true, + name: true, + type: true, + role: true +}) + +const WorkspaceTokenResponseSchema = z.object({ + token: z.string(), + expires_at: z.string(), + workspace: zWorkspaceWithRole.pick({ id: true, name: true, type: true }), + role: zWorkspaceWithRole.shape.role, + permissions: z.array(z.string()) +}) + +export type WorkspaceTokenResponse = z.infer< + typeof WorkspaceTokenResponseSchema +> + +const RECOVERY_COOLDOWN_MS = 5000 + +interface MintedToken { + token: string + expiresAt: number + workspace: WorkspaceIdentity + ownerUid: string +} + +const PERMANENT_AUTH_ERROR_CODES = new Set([ + 'ACCESS_DENIED', + 'WORKSPACE_NOT_FOUND', + 'INVALID_FIREBASE_TOKEN', + 'NOT_AUTHENTICATED' +]) + +function isPermanentAuthError(err: unknown): err is WorkspaceAuthError { + return ( + err instanceof WorkspaceAuthError && + PERMANENT_AUTH_ERROR_CODES.has(err.code ?? '') + ) +} + +function isTransientAuthError(err: unknown): err is WorkspaceAuthError { + return ( + err instanceof WorkspaceAuthError && err.code === 'TOKEN_EXCHANGE_FAILED' + ) +} + +function notAuthenticatedError(): WorkspaceAuthError { + return new WorkspaceAuthError( + t('workspaceAuth.errors.notAuthenticated'), + 'NOT_AUTHENTICATED' + ) +} + +function tokenExchangeFailedError(error: string): WorkspaceAuthError { + return new WorkspaceAuthError( + t('workspaceAuth.errors.tokenExchangeFailed', { error }), + 'TOKEN_EXCHANGE_FAILED' + ) +} + +function tokenExchangeErrorForStatus( + status: number, + message: string +): WorkspaceAuthError { + if (status === 401) { + return new WorkspaceAuthError( + t('workspaceAuth.errors.invalidFirebaseToken'), + 'INVALID_FIREBASE_TOKEN' + ) + } + if (status === 403) { + return new WorkspaceAuthError( + t('workspaceAuth.errors.accessDenied'), + 'ACCESS_DENIED' + ) + } + if (status === 404) { + return new WorkspaceAuthError( + t('workspaceAuth.errors.workspaceNotFound'), + 'WORKSPACE_NOT_FOUND' + ) + } + return tokenExchangeFailedError(message) +} + +function parseMintedToken(rawData: unknown, ownerUid: string): MintedToken { + const parseResult = WorkspaceTokenResponseSchema.safeParse(rawData) + if (!parseResult.success) { + throw tokenExchangeFailedError(fromZodError(parseResult.error).message) + } + + const data = parseResult.data + const expiresAt = new Date(data.expires_at).getTime() + if (isNaN(expiresAt)) { + throw tokenExchangeFailedError('Invalid expiry timestamp') + } + + return { + token: data.token, + expiresAt, + workspace: { ...data.workspace, role: data.role }, + ownerUid + } +} + +interface StoredSession { + workspace: WorkspaceIdentity + token: string + expiresAt: number + ownerUid: string +} + +const REFRESH_ATTEMPT_MAX_RETRIES = 3 +const REFRESH_BASE_DELAY_MS = 1000 + +function refreshBackoffMs(attempt: number): number { + return REFRESH_BASE_DELAY_MS * Math.pow(2, attempt) +} + +export interface LegacyWorkspaceTokenRailDeps { + currentWorkspace: ShallowRef + isLoading: Ref + error: Ref + currentUserUid: () => string | null + isCurrentUser: (ownerUid: string) => boolean + getIdToken: () => Promise + hasSignedInUser: () => boolean + activeWorkspaceId: () => string | null + switchWorkspace: (workspaceId: string) => Promise + endWorkspaceSession: (revokedWorkspaceId?: string) => boolean + persistWorkspaceIdentity: (workspace: WorkspaceIdentity) => void + clearSessionStorage: () => void + surfacePermanentAuthError: (err: WorkspaceAuthError) => void +} + +export function createLegacyWorkspaceTokenRail({ + currentWorkspace, + isLoading, + error, + currentUserUid, + isCurrentUser, + getIdToken, + hasSignedInUser, + activeWorkspaceId, + switchWorkspace, + endWorkspaceSession, + persistWorkspaceIdentity, + clearSessionStorage, + surfacePermanentAuthError +}: LegacyWorkspaceTokenRailDeps) { + const workspaceToken = ref(null) + const workspaceTokenExpiresAt = ref(null) + const workspaceTokenOwnerUid = ref(null) + + // Timer state + let refreshTimerId: ReturnType | null = null + let inFlightSwitchCount = 0 + let inFlightSwitchPromise: Promise | null = null + let recoveryCooldownUntil = 0 + let scheduledRefreshRetryCount = 0 + + // Request ID to prevent stale refresh operations from overwriting newer workspace contexts + let refreshRequestId = 0 + + // Private helpers + function stopRefreshTimer(): void { + if (refreshTimerId !== null) { + clearTimeout(refreshTimerId) + refreshTimerId = null + } + } + + function scheduleTokenRefresh(expiresAt: number): void { + stopRefreshTimer() + scheduledRefreshRetryCount = 0 + const now = Date.now() + const refreshAt = expiresAt - TOKEN_REFRESH_BUFFER_MS + const delay = Math.max(0, refreshAt - now) + + refreshTimerId = setTimeout(() => { + void refreshToken() + }, delay) + } + + function scheduleClearAtExpiry(): void { + if (workspaceTokenExpiresAt.value === null) { + endWorkspaceSession() + return + } + + const timeUntilExpiry = workspaceTokenExpiresAt.value - Date.now() + if (timeUntilExpiry <= 0) { + endWorkspaceSession() + return + } + + stopRefreshTimer() + refreshTimerId = setTimeout(() => { + endWorkspaceSession() + }, timeUntilExpiry) + } + + function scheduleTokenRefreshRetry(delayMs: number): boolean { + if (workspaceTokenExpiresAt.value === null) { + endWorkspaceSession() + return false + } + + const timeUntilExpiry = workspaceTokenExpiresAt.value - Date.now() + if (timeUntilExpiry <= 0) { + endWorkspaceSession() + return false + } + + if (scheduledRefreshRetryCount >= MAX_SCHEDULED_REFRESH_RETRIES) { + scheduleClearAtExpiry() + return false + } + + scheduledRefreshRetryCount += 1 + stopRefreshTimer() + const timeUntilRefreshBuffer = Math.max( + 0, + timeUntilExpiry - TOKEN_REFRESH_BUFFER_MS + ) + refreshTimerId = setTimeout( + () => { + void refreshToken() + }, + Math.min(delayMs, timeUntilRefreshBuffer) + ) + return true + } + + function isStaleWorkspaceRequest( + capturedRequestId: number, + ownerUid?: string | null + ): boolean { + return ( + capturedRequestId !== refreshRequestId || + (ownerUid !== undefined && ownerUid !== null && !isCurrentUser(ownerUid)) + ) + } + + function persistToSession( + workspace: WorkspaceIdentity, + token: string, + expiresAt: number, + ownerUid: string + ): void { + persistWorkspaceIdentity(workspace) + try { + sessionStorage.setItem(WORKSPACE_STORAGE_KEYS.TOKEN, token) + sessionStorage.setItem( + WORKSPACE_STORAGE_KEYS.EXPIRES_AT, + expiresAt.toString() + ) + sessionStorage.setItem(WORKSPACE_STORAGE_KEYS.OWNER_UID, ownerUid) + } catch { + console.warn('Failed to persist workspace token to sessionStorage') + } + } + + function retireLegacyToken(): void { + stopRefreshTimer() + workspaceToken.value = null + workspaceTokenExpiresAt.value = null + workspaceTokenOwnerUid.value = null + try { + sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.TOKEN) + sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.EXPIRES_AT) + sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.OWNER_UID) + } catch { + console.warn( + 'Failed to retire legacy workspace token from sessionStorage' + ) + } + } + + function readStoredSession(): StoredSession | null { + const workspaceJson = sessionStorage.getItem( + WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE + ) + const token = sessionStorage.getItem(WORKSPACE_STORAGE_KEYS.TOKEN) + const expiresAtStr = sessionStorage.getItem( + WORKSPACE_STORAGE_KEYS.EXPIRES_AT + ) + const ownerUid = sessionStorage.getItem(WORKSPACE_STORAGE_KEYS.OWNER_UID) + if (!workspaceJson || !token || !expiresAtStr || !ownerUid) return null + if (!isCurrentUser(ownerUid)) return null + + const parseResult = WorkspaceIdentitySchema.safeParse( + JSON.parse(workspaceJson) + ) + if (!parseResult.success) return null + + return { + workspace: parseResult.data, + token, + expiresAt: parseInt(expiresAtStr, 10), + ownerUid + } + } + + function isUnexpiredSession({ expiresAt }: StoredSession): boolean { + return !isNaN(expiresAt) && expiresAt > Date.now() + } + + function initializeFromSession(): boolean { + try { + const session = readStoredSession() + if (!session || !isUnexpiredSession(session)) { + clearSessionStorage() + return false + } + + currentWorkspace.value = session.workspace + workspaceToken.value = session.token + workspaceTokenExpiresAt.value = session.expiresAt + workspaceTokenOwnerUid.value = session.ownerUid + error.value = null + + scheduleTokenRefresh(session.expiresAt) + return true + } catch { + clearSessionStorage() + return false + } + } + + /** + * Exchanges the Firebase identity for a Cloud JWT via POST /auth/token. + * An id-less body ({}) mints the caller's personal-workspace token; a + * concrete workspace_id mints that workspace's token. Pure network + parse: + * it writes no store state, schedules no timer, and reads no flag. + */ + async function requestToken(workspaceId?: string): Promise { + const ownerUid = currentUserUid() + if (!ownerUid) throw notAuthenticatedError() + + const firebaseToken = await getIdToken() + if (!firebaseToken) throw notAuthenticatedError() + + const response = await fetch(workspaceApiUrl('/auth/token'), { + method: 'POST', + headers: { + Authorization: `Bearer ${firebaseToken}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify(workspaceId ? { workspace_id: workspaceId } : {}) + }) + + if (!response.ok) { + const { message } = await parseErrorResponse(response) + throw tokenExchangeErrorForStatus(response.status, message) + } + + return parseMintedToken(await response.json(), ownerUid) + } + + async function performSwitchWorkspace(workspaceId: string): Promise { + const capturedRequestId = refreshRequestId + const capturedOwnerUid = currentUserUid() + + inFlightSwitchCount += 1 + isLoading.value = true + error.value = null + + try { + const { useSessionCookie } = + await import('@/platform/auth/session/useSessionCookie') + await useSessionCookie().ensureSessionCookie() + if (isStaleWorkspaceRequest(capturedRequestId, capturedOwnerUid)) return + + const { token, expiresAt, workspace, ownerUid } = + await requestToken(workspaceId) + + if (isStaleWorkspaceRequest(capturedRequestId, ownerUid)) { + console.warn( + 'Aborting stale workspace switch: workspace context changed before commit' + ) + return + } + + if (currentWorkspace.value?.id !== workspaceId) { + refreshRequestId++ + } + currentWorkspace.value = workspace + workspaceToken.value = token + workspaceTokenExpiresAt.value = expiresAt + workspaceTokenOwnerUid.value = ownerUid + scheduledRefreshRetryCount = 0 + recoveryCooldownUntil = 0 + + persistToSession(workspace, token, expiresAt, ownerUid) + scheduleTokenRefresh(expiresAt) + } catch (err) { + if (isStaleWorkspaceRequest(capturedRequestId, capturedOwnerUid)) { + console.warn( + 'Aborting stale workspace switch: workspace context changed before error commit', + err + ) + return + } + + error.value = err instanceof Error ? err : new Error(String(err)) + throw error.value + } finally { + inFlightSwitchCount = Math.max(0, inFlightSwitchCount - 1) + isLoading.value = inFlightSwitchCount > 0 + } + } + + function switchLegacyWorkspace(workspaceId: string): Promise { + const promise = performSwitchWorkspace(workspaceId) + inFlightSwitchPromise = promise + void promise + .catch(() => {}) + .finally(() => { + if (inFlightSwitchPromise === promise) { + inFlightSwitchPromise = null + } + }) + return promise + } + + function hasValidTokenForWorkspace(workspaceId: string | undefined): boolean { + return ( + hasValidWorkspaceToken() && + (workspaceId === undefined || currentWorkspace.value?.id === workspaceId) + ) + } + + // NOT_AUTHENTICATED while still signed in is a transient network failure, not + // a revoked session, so it must not tear down a valid context. + function isPermanentRecoveryFailure(err: unknown): err is WorkspaceAuthError { + if (!isPermanentAuthError(err)) { + return false + } + if (err.code === 'NOT_AUTHENTICATED' && hasSignedInUser()) { + return false + } + return true + } + + // The workspace selection itself is invalid (revoked or deleted), so + // abandoning it can help — unlike a plain auth failure. + function isWorkspaceSelectionInvalid( + err: unknown + ): err is WorkspaceAuthError { + return ( + err instanceof WorkspaceAuthError && + (err.code === 'ACCESS_DENIED' || err.code === 'WORKSPACE_NOT_FOUND') + ) + } + + function startRecoveryCooldown(): void { + recoveryCooldownUntil = Date.now() + RECOVERY_COOLDOWN_MS + } + + function handleRecoveryFailure( + err: unknown, + failedWorkspaceId?: string + ): void { + let invalidSelectionHandled = false + if (isPermanentRecoveryFailure(err)) { + const hadContext = currentWorkspace.value !== null + invalidSelectionHandled = endWorkspaceSession( + failedWorkspaceId && isWorkspaceSelectionInvalid(err) + ? failedWorkspaceId + : undefined + ) + if (hadContext) { + surfacePermanentAuthError(err) + } + } + if (!invalidSelectionHandled) startRecoveryCooldown() + console.warn('Workspace auth recovery failed:', err) + } + + async function canRecheckAfterInFlightSwitch( + inFlight: Promise, + ownerUid: string, + targetWorkspaceId: string | undefined + ): Promise { + await inFlight.catch(() => {}) + if (!isCurrentUser(ownerUid)) return false + return isCloud || currentWorkspace.value?.id === targetWorkspaceId + } + + function canStartRecoveryMint( + targetWorkspaceId: string | undefined + ): targetWorkspaceId is string { + if (!targetWorkspaceId || Date.now() < recoveryCooldownUntil) return false + return isCloud || activeWorkspaceId() === targetWorkspaceId + } + + async function recoverWorkspaceToken( + ownerUid: string, + targetWorkspaceId: string | undefined + ): Promise { + if (!canStartRecoveryMint(targetWorkspaceId)) return null + try { + await switchWorkspace(targetWorkspaceId) + } catch (err) { + if (isCurrentUser(ownerUid)) handleRecoveryFailure(err, targetWorkspaceId) + return null + } + + if (!isCurrentUser(ownerUid)) return null + if (hasValidTokenForWorkspace(targetWorkspaceId)) { + return workspaceToken.value + } + + // Resolved without a usable token; back off like a failure and fail closed. + startRecoveryCooldown() + return null + } + + /** + * Resolve a valid workspace token, minting one if needed. Coalesces a burst of + * callers onto a single in-flight mint, backs off after failure, and returns + * null so callers fail closed rather than downgrade to the personal identity. + */ + async function ensureWorkspaceToken( + preferredWorkspaceId?: string + ): Promise { + const ownerUid = currentUserUid() + if (!ownerUid) return null + const targetWorkspaceId = preferredWorkspaceId ?? currentWorkspace.value?.id + + for (;;) { + if (!isCurrentUser(ownerUid)) return null + if (hasValidTokenForWorkspace(targetWorkspaceId)) { + return workspaceToken.value + } + if (!inFlightSwitchPromise) break + + // Join any in-flight mint and re-check rather than launching our own. + const mayRecheck = await canRecheckAfterInFlightSwitch( + inFlightSwitchPromise, + ownerUid, + targetWorkspaceId + ) + if (!mayRecheck) return null + } + + return recoverWorkspaceToken(ownerUid, targetWorkspaceId) + } + + async function ensureWorkspaceAuthHeader( + preferredWorkspaceId?: string + ): Promise { + const token = await ensureWorkspaceToken(preferredWorkspaceId) + return token ? { Authorization: `Bearer ${token}` } : null + } + + function endRefreshOnPermanentError( + err: WorkspaceAuthError, + workspaceId: string, + capturedRequestId: number + ): void { + if (isStaleWorkspaceRequest(capturedRequestId)) return + console.error('Workspace access revoked or auth invalid:', err) + endWorkspaceSession( + isWorkspaceSelectionInvalid(err) ? workspaceId : undefined + ) + } + + async function waitForRefreshBackoff( + attempt: number, + err: unknown + ): Promise { + const delayMs = refreshBackoffMs(attempt) + console.warn( + `Token refresh failed (attempt ${attempt + 1}/${REFRESH_ATTEMPT_MAX_RETRIES + 1}), retrying in ${delayMs}ms:`, + err + ) + await delay(delayMs) + } + + function preserveTokenAfterExhaustedRefresh(err: unknown): void { + error.value = null + const retryScheduled = scheduleTokenRefreshRetry( + refreshBackoffMs(REFRESH_ATTEMPT_MAX_RETRIES) + ) + console.warn( + retryScheduled + ? 'Failed to refresh workspace token after retries; preserving existing valid token and retrying later:' + : 'Failed to refresh workspace token after retries; preserving existing valid token until expiry:', + err + ) + } + + function settleExhaustedRefresh( + err: unknown, + capturedRequestId: number + ): void { + if (isStaleWorkspaceRequest(capturedRequestId)) return + if (isTransientAuthError(err) && hasValidWorkspaceToken()) { + preserveTokenAfterExhaustedRefresh(err) + return + } + console.error('Failed to refresh workspace token after retries:', err) + endWorkspaceSession() + } + + async function refreshToken(): Promise { + if (!currentWorkspace.value) { + return + } + + const workspaceId = currentWorkspace.value.id + const capturedRequestId = refreshRequestId + // Clear any previous error optimistically; a stale-aborted refresh should + // not leave a stale error visible on the new workspace's context. + error.value = null + + for (let attempt = 0; attempt <= REFRESH_ATTEMPT_MAX_RETRIES; attempt++) { + if (isStaleWorkspaceRequest(capturedRequestId)) { + console.warn( + 'Aborting stale token refresh: workspace context changed during refresh' + ) + return + } + + try { + await switchWorkspace(workspaceId) + return + } catch (err) { + if (isPermanentAuthError(err)) { + endRefreshOnPermanentError(err, workspaceId, capturedRequestId) + return + } + if ( + isTransientAuthError(err) && + attempt < REFRESH_ATTEMPT_MAX_RETRIES + ) { + await waitForRefreshBackoff(attempt, err) + continue + } + settleExhaustedRefresh(err, capturedRequestId) + return + } + } + } + + function getWorkspaceAuthHeader(): AuthHeader | null { + if (!hasValidWorkspaceToken()) { + return null + } + return { + Authorization: `Bearer ${workspaceToken.value}` + } + } + + function getWorkspaceToken(): string | undefined { + return hasValidWorkspaceToken() + ? (workspaceToken.value ?? undefined) + : undefined + } + + function hasValidWorkspaceToken(): boolean { + return ( + workspaceToken.value !== null && + workspaceTokenExpiresAt.value !== null && + workspaceTokenExpiresAt.value > Date.now() && + workspaceTokenOwnerUid.value !== null && + isCurrentUser(workspaceTokenOwnerUid.value) + ) + } + + function clearLegacyContext(): void { + refreshRequestId++ + stopRefreshTimer() + currentWorkspace.value = null + workspaceToken.value = null + workspaceTokenExpiresAt.value = null + workspaceTokenOwnerUid.value = null + scheduledRefreshRetryCount = 0 + recoveryCooldownUntil = 0 + // refreshRequestId bump above aborts any in-flight switch before it commits. + inFlightSwitchPromise = null + } + + return { + workspaceToken, + initializeFromSession, + switchLegacyWorkspace, + refreshToken, + ensureWorkspaceToken, + ensureWorkspaceAuthHeader, + getWorkspaceAuthHeader, + getWorkspaceToken, + hasValidWorkspaceToken, + retireLegacyToken, + stopRefreshTimer, + clearLegacyContext + } +} diff --git a/src/platform/workspace/stores/useWorkspaceAuth.test.ts b/src/platform/workspace/stores/useWorkspaceAuth.test.ts index 891d1a5f3ea..4b5b0443a80 100644 --- a/src/platform/workspace/stores/useWorkspaceAuth.test.ts +++ b/src/platform/workspace/stores/useWorkspaceAuth.test.ts @@ -22,7 +22,10 @@ import { getWorkspaceId, StorageKeys } from '@/platform/workflow/persistence/base/storageKeys' -import { WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' +import { + TOKEN_REFRESH_BUFFER_MS, + WORKSPACE_STORAGE_KEYS +} from '@/platform/workspace/workspaceConstants' import { replayIdentityPort, stubFirebaseAuthHarness @@ -3574,6 +3577,145 @@ describe('useWorkspaceAuthStore', () => { expect(useToastStore().add).not.toHaveBeenCalled() }) }) + + describe('legacy rail seam', () => { + it('routes the legacy refresh deadline through the flag dispatcher once unified auth turns on', async () => { + vi.mocked(useAuthStore().getIdToken).mockResolvedValue( + 'firebase-token-xyz' + ) + const expiresInMs = 3600 * 1000 + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => + Promise.resolve({ + ...mockTokenResponse, + expires_at: new Date(Date.now() + expiresInMs).toISOString() + }) + }) + vi.stubGlobal('fetch', mockFetch) + + const store = useWorkspaceAuthStore() + const { workspaceToken } = storeToRefs(store) + await store.switchWorkspace('workspace-123') + expect(workspaceToken.value).toBe('workspace-token-abc') + + vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true + vi.advanceTimersByTime(expiresInMs - TOKEN_REFRESH_BUFFER_MS) + + await vi.waitFor(() => { + expect(store.getUnifiedMintWorkspaceId()).toBe('workspace-123') + expect(store.getUnifiedToken()).toBe('workspace-token-abc') + }) + expect(workspaceToken.value).toBeNull() + expect(sessionStorage.getItem(WORKSPACE_STORAGE_KEYS.TOKEN)).toBeNull() + }) + + it('routes an expired-token recovery through the flag dispatcher and fails closed on the legacy rail', async () => { + vi.mocked(useAuthStore().getIdToken).mockResolvedValue( + 'firebase-token-xyz' + ) + const expiresInMs = 3600 * 1000 + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => + Promise.resolve({ + ...mockTokenResponse, + expires_at: new Date(Date.now() + expiresInMs).toISOString() + }) + }) + vi.stubGlobal('fetch', mockFetch) + + const store = useWorkspaceAuthStore() + const { workspaceToken } = storeToRefs(store) + await store.switchWorkspace('workspace-123') + expect(workspaceToken.value).toBe('workspace-token-abc') + + vi.setSystemTime(Date.now() + expiresInMs + 1) + vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = true + const recovered = store.ensureWorkspaceToken('workspace-123') + + await expect(recovered).resolves.toBeNull() + expect(store.getUnifiedMintWorkspaceId()).toBe('workspace-123') + expect(store.getUnifiedToken()).toBe('workspace-token-abc') + expect(workspaceToken.value).toBeNull() + }) + + it('returns null rather than a token for a different workspace when the requested one cannot be entered', async () => { + vi.mocked(useAuthStore().getIdToken).mockResolvedValue( + 'firebase-token-xyz' + ) + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => + Promise.resolve({ + ...mockTokenResponse, + expires_at: new Date(Date.now() + 3600 * 1000).toISOString() + }) + }) + vi.stubGlobal('fetch', mockFetch) + + const store = useWorkspaceAuthStore() + const { workspaceToken, currentWorkspace } = storeToRefs(store) + + const token = await store.ensureWorkspaceToken('workspace-456') + + expect(token).toBeNull() + expect(currentWorkspace.value?.id).toBe('workspace-123') + expect(workspaceToken.value).toBe('workspace-token-abc') + expect(mockFetch).toHaveBeenCalledOnce() + + await expect( + store.ensureWorkspaceToken('workspace-456') + ).resolves.toBeNull() + expect(mockFetch).toHaveBeenCalledOnce() + }) + + it('resolves the identity token at mint time, not at store construction', async () => { + vi.mocked(useAuthStore().getIdToken).mockResolvedValue('firebase-token-1') + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => Promise.resolve(mockTokenResponse) + }) + vi.stubGlobal('fetch', mockFetch) + + const store = useWorkspaceAuthStore() + await store.switchWorkspace('workspace-123') + Object.assign(useAuthStore(), { + getIdToken: vi.fn().mockResolvedValue('firebase-token-2') + }) + await store.switchWorkspace('workspace-123') + + expect( + mockFetch.mock.calls.map(([, init]) => init.headers.Authorization) + ).toEqual(['Bearer firebase-token-1', 'Bearer firebase-token-2']) + }) + + it('reads the active local workspace at recovery time, not at store construction', async () => { + mockDistributionTypes.isCloud = false + vi.mocked(useAuthStore().getIdToken).mockResolvedValue( + 'firebase-token-xyz' + ) + const mockFetch = vi.fn().mockResolvedValue({ + ok: true, + json: () => + Promise.resolve({ + ...mockTokenResponse, + expires_at: new Date(Date.now() + 3600 * 1000).toISOString() + }) + }) + vi.stubGlobal('fetch', mockFetch) + + const store = useWorkspaceAuthStore() + Object.assign(useTeamWorkspaceStore(), { + activeWorkspaceId: 'workspace-123' + }) + + await expect(store.ensureWorkspaceToken('workspace-123')).resolves.toBe( + 'workspace-token-abc' + ) + expect(mockFetch).toHaveBeenCalledOnce() + }) + }) }) describe('useWorkspaceAuthStore constructed before authStore', () => { diff --git a/src/platform/workspace/stores/workspaceAuthError.ts b/src/platform/workspace/stores/workspaceAuthError.ts new file mode 100644 index 00000000000..bf108906cd9 --- /dev/null +++ b/src/platform/workspace/stores/workspaceAuthError.ts @@ -0,0 +1,9 @@ +export class WorkspaceAuthError extends Error { + constructor( + message: string, + public readonly code?: string + ) { + super(message) + this.name = 'WorkspaceAuthError' + } +} diff --git a/src/platform/workspace/stores/workspaceAuthStore.ts b/src/platform/workspace/stores/workspaceAuthStore.ts index b1aa26ec734..f39d6a400d1 100644 --- a/src/platform/workspace/stores/workspaceAuthStore.ts +++ b/src/platform/workspace/stores/workspaceAuthStore.ts @@ -1,9 +1,6 @@ -import { zWorkspaceWithRole } from '@comfyorg/ingest-types/zod' import type { User } from 'firebase/auth' import { defineStore } from 'pinia' import { computed, ref, shallowRef, watch } from 'vue' -import { z } from 'zod' -import { fromZodError } from 'zod-validation-error' import type { ScheduledRefreshReport, @@ -21,86 +18,36 @@ import { firebaseIdentity } from '@/platform/auth/firebaseIdentity' import enMessages from '@/locales/en/main.json' with { type: 'json' } import { useTelemetry } from '@/platform/telemetry' import type { UnifiedAuthRefreshOutcome } from '@/platform/telemetry/types' -import { parseErrorResponse } from '@/platform/remote/comfyui/errors' import { prepareWorkflowWorkspaceTransition } from '@/platform/workflow/persistence/base/storageIO' import { + MAX_SCHEDULED_REFRESH_RETRIES, TOKEN_REFRESH_BUFFER_MS, WORKSPACE_STORAGE_KEYS } from '@/platform/workspace/workspaceConstants' +import { createLegacyWorkspaceTokenRail } from '@/platform/workspace/stores/legacyWorkspaceTokenRail' +import type { WorkspaceTokenResponse } from '@/platform/workspace/stores/legacyWorkspaceTokenRail' +import { WorkspaceAuthError } from '@/platform/workspace/stores/workspaceAuthError' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { useToastStore } from '@/platform/updates/common/toastStore' import { useAuthStore } from '@/stores/authStore' -import type { AuthHeader } from '@/types/authTypes' import type { WorkspaceIdentity } from '@/platform/workspace/workspaceTypes' import { useFeatureFlags } from '@/composables/useFeatureFlags' import { isCloud } from '@/platform/distribution/types' import { workspaceApiUrl } from '@/platform/workspace/api/workspaceApiUrl' -// Picked off the generated schema: a hand-written enum that lags the spec would -// reject a valid persisted identity and silently clear the session. -const WorkspaceIdentitySchema = zWorkspaceWithRole.pick({ - id: true, - name: true, - type: true, - role: true -}) - -const WorkspaceTokenResponseSchema = z.object({ - token: z.string(), - expires_at: z.string(), - workspace: zWorkspaceWithRole.pick({ id: true, name: true, type: true }), - role: zWorkspaceWithRole.shape.role, - permissions: z.array(z.string()) -}) - -export type WorkspaceTokenResponse = z.infer< - typeof WorkspaceTokenResponseSchema -> - -const MAX_SCHEDULED_REFRESH_RETRIES = 3 +export { WorkspaceAuthError } +// The e2e fixtures import this type from the store path. +export type { WorkspaceTokenResponse } const UNIFIED_REFRESH_RETRY_BASE_MS = 5000 /** Ceiling on waiting for the identity port before a host mint gives up. */ export const UNIFIED_IDENTITY_SETTLE_TIMEOUT_MS = 15_000 -const RECOVERY_COOLDOWN_MS = 5000 - // Retain expired unified-token contexts briefly so a concurrent reactive-401 // replay for the just-rotated token still resolves, then evict them so a // long-lived session cannot grow the context Map unbounded. const ISSUED_TOKEN_CONTEXT_GRACE_MS = 5 * 60 * 1000 -export class WorkspaceAuthError extends Error { - constructor( - message: string, - public readonly code?: string - ) { - super(message) - this.name = 'WorkspaceAuthError' - } -} - -interface MintedToken { - token: string - expiresAt: number - workspace: WorkspaceIdentity - ownerUid: string -} - -const PERMANENT_AUTH_ERROR_CODES = new Set([ - 'ACCESS_DENIED', - 'WORKSPACE_NOT_FOUND', - 'INVALID_FIREBASE_TOKEN', - 'NOT_AUTHENTICATED' -]) - -function isPermanentAuthError(err: unknown): err is WorkspaceAuthError { - return ( - err instanceof WorkspaceAuthError && - PERMANENT_AUTH_ERROR_CODES.has(err.code ?? '') - ) -} - function isSessionErrorCode( code: string | undefined ): code is SessionErrorCode { @@ -151,9 +98,6 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { // State const currentWorkspace = shallowRef(null) - const workspaceToken = ref(null) - const workspaceTokenExpiresAt = ref(null) - const workspaceTokenOwnerUid = ref(null) const isLoading = ref(false) const error = ref(null) @@ -166,15 +110,34 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { { ownerUid: string; targetKey: string; expiresAt: number } >() - // Timer state - let refreshTimerId: ReturnType | null = null - let inFlightSwitchCount = 0 - let inFlightSwitchPromise: Promise | null = null - let recoveryCooldownUntil = 0 - let scheduledRefreshRetryCount = 0 - - // Request ID to prevent stale refresh operations from overwriting newer workspace contexts - let refreshRequestId = 0 + const { + workspaceToken, + initializeFromSession, + switchLegacyWorkspace, + refreshToken, + ensureWorkspaceToken, + ensureWorkspaceAuthHeader, + getWorkspaceAuthHeader, + getWorkspaceToken, + hasValidWorkspaceToken, + retireLegacyToken, + stopRefreshTimer, + clearLegacyContext + } = createLegacyWorkspaceTokenRail({ + currentWorkspace, + isLoading, + error, + currentUserUid, + isCurrentUser, + getIdToken: () => useAuthStore().getIdToken(), + hasSignedInUser: () => useAuthStore().currentUser !== null, + activeWorkspaceId: () => useTeamWorkspaceStore().activeWorkspaceId, + switchWorkspace, + endWorkspaceSession, + persistWorkspaceIdentity, + clearSessionStorage, + surfacePermanentAuthError + }) // Getters const isAuthenticated = computed( @@ -189,86 +152,6 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { return currentUserUid() === ownerUid } - // Private helpers - function stopRefreshTimer(): void { - if (refreshTimerId !== null) { - clearTimeout(refreshTimerId) - refreshTimerId = null - } - } - - function scheduleTokenRefresh(expiresAt: number): void { - stopRefreshTimer() - scheduledRefreshRetryCount = 0 - const now = Date.now() - const refreshAt = expiresAt - TOKEN_REFRESH_BUFFER_MS - const delay = Math.max(0, refreshAt - now) - - refreshTimerId = setTimeout(() => { - void refreshToken() - }, delay) - } - - function scheduleClearAtExpiry(): void { - if (workspaceTokenExpiresAt.value === null) { - endWorkspaceSession() - return - } - - const timeUntilExpiry = workspaceTokenExpiresAt.value - Date.now() - if (timeUntilExpiry <= 0) { - endWorkspaceSession() - return - } - - stopRefreshTimer() - refreshTimerId = setTimeout(() => { - endWorkspaceSession() - }, timeUntilExpiry) - } - - function scheduleTokenRefreshRetry(delayMs: number): boolean { - if (workspaceTokenExpiresAt.value === null) { - endWorkspaceSession() - return false - } - - const timeUntilExpiry = workspaceTokenExpiresAt.value - Date.now() - if (timeUntilExpiry <= 0) { - endWorkspaceSession() - return false - } - - if (scheduledRefreshRetryCount >= MAX_SCHEDULED_REFRESH_RETRIES) { - scheduleClearAtExpiry() - return false - } - - scheduledRefreshRetryCount += 1 - stopRefreshTimer() - const timeUntilRefreshBuffer = Math.max( - 0, - timeUntilExpiry - TOKEN_REFRESH_BUFFER_MS - ) - refreshTimerId = setTimeout( - () => { - void refreshToken() - }, - Math.min(delayMs, timeUntilRefreshBuffer) - ) - return true - } - - function isStaleWorkspaceRequest( - capturedRequestId: number, - ownerUid?: string | null - ): boolean { - return ( - capturedRequestId !== refreshRequestId || - (ownerUid !== undefined && ownerUid !== null && !isCurrentUser(ownerUid)) - ) - } - function persistWorkspaceIdentity(workspace: WorkspaceIdentity): void { try { sessionStorage.setItem( @@ -280,25 +163,6 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { } } - function persistToSession( - workspace: WorkspaceIdentity, - token: string, - expiresAt: number, - ownerUid: string - ): void { - persistWorkspaceIdentity(workspace) - try { - sessionStorage.setItem(WORKSPACE_STORAGE_KEYS.TOKEN, token) - sessionStorage.setItem( - WORKSPACE_STORAGE_KEYS.EXPIRES_AT, - expiresAt.toString() - ) - sessionStorage.setItem(WORKSPACE_STORAGE_KEYS.OWNER_UID, ownerUid) - } catch { - console.warn('Failed to persist workspace token to sessionStorage') - } - } - function clearSessionStorage(): void { try { sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE) @@ -310,22 +174,6 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { } } - function retireLegacyToken(): void { - stopRefreshTimer() - workspaceToken.value = null - workspaceTokenExpiresAt.value = null - workspaceTokenOwnerUid.value = null - try { - sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.TOKEN) - sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.EXPIRES_AT) - sessionStorage.removeItem(WORKSPACE_STORAGE_KEYS.OWNER_UID) - } catch { - console.warn( - 'Failed to retire legacy workspace token from sessionStorage' - ) - } - } - // Actions function init(): void { initializeFromSession() @@ -339,416 +187,12 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { stopUnifiedSnapshot() } - function initializeFromSession(): boolean { - try { - const workspaceJson = sessionStorage.getItem( - WORKSPACE_STORAGE_KEYS.CURRENT_WORKSPACE - ) - const token = sessionStorage.getItem(WORKSPACE_STORAGE_KEYS.TOKEN) - const expiresAtStr = sessionStorage.getItem( - WORKSPACE_STORAGE_KEYS.EXPIRES_AT - ) - const ownerUid = sessionStorage.getItem(WORKSPACE_STORAGE_KEYS.OWNER_UID) - - if ( - !workspaceJson || - !token || - !expiresAtStr || - !ownerUid || - !isCurrentUser(ownerUid) - ) { - clearSessionStorage() - return false - } - - const expiresAt = parseInt(expiresAtStr, 10) - if (isNaN(expiresAt) || expiresAt <= Date.now()) { - clearSessionStorage() - return false - } - - const parseResult = WorkspaceIdentitySchema.safeParse( - JSON.parse(workspaceJson) - ) - - if (!parseResult.success) { - clearSessionStorage() - return false - } - - currentWorkspace.value = parseResult.data - workspaceToken.value = token - workspaceTokenExpiresAt.value = expiresAt - workspaceTokenOwnerUid.value = ownerUid - error.value = null - - scheduleTokenRefresh(expiresAt) - return true - } catch { - clearSessionStorage() - return false - } - } - - /** - * Exchanges the Firebase identity for a Cloud JWT via POST /auth/token. - * An id-less body ({}) mints the caller's personal-workspace token; a - * concrete workspace_id mints that workspace's token. Pure network + parse: - * it writes no store state, schedules no timer, and reads no flag, so both - * the legacy switch path and the unified path can reuse it without inheriting - * each other's gates. - */ - async function requestToken(workspaceId?: string): Promise { - const ownerUid = currentUserUid() - if (!ownerUid) { - throw new WorkspaceAuthError( - t('workspaceAuth.errors.notAuthenticated'), - 'NOT_AUTHENTICATED' - ) - } - - const firebaseToken = await useAuthStore().getIdToken() - if (!firebaseToken) { - throw new WorkspaceAuthError( - t('workspaceAuth.errors.notAuthenticated'), - 'NOT_AUTHENTICATED' - ) - } - - const response = await fetch(workspaceApiUrl('/auth/token'), { - method: 'POST', - headers: { - Authorization: `Bearer ${firebaseToken}`, - 'Content-Type': 'application/json' - }, - body: JSON.stringify(workspaceId ? { workspace_id: workspaceId } : {}) - }) - - if (!response.ok) { - const { message } = await parseErrorResponse(response) - - if (response.status === 401) { - throw new WorkspaceAuthError( - t('workspaceAuth.errors.invalidFirebaseToken'), - 'INVALID_FIREBASE_TOKEN' - ) - } - if (response.status === 403) { - throw new WorkspaceAuthError( - t('workspaceAuth.errors.accessDenied'), - 'ACCESS_DENIED' - ) - } - if (response.status === 404) { - throw new WorkspaceAuthError( - t('workspaceAuth.errors.workspaceNotFound'), - 'WORKSPACE_NOT_FOUND' - ) - } - - throw new WorkspaceAuthError( - t('workspaceAuth.errors.tokenExchangeFailed', { error: message }), - 'TOKEN_EXCHANGE_FAILED' - ) - } - - const rawData = await response.json() - const parseResult = WorkspaceTokenResponseSchema.safeParse(rawData) - - if (!parseResult.success) { - throw new WorkspaceAuthError( - t('workspaceAuth.errors.tokenExchangeFailed', { - error: fromZodError(parseResult.error).message - }), - 'TOKEN_EXCHANGE_FAILED' - ) - } - - const data = parseResult.data - const expiresAt = new Date(data.expires_at).getTime() - - if (isNaN(expiresAt)) { - throw new WorkspaceAuthError( - t('workspaceAuth.errors.tokenExchangeFailed', { - error: 'Invalid expiry timestamp' - }), - 'TOKEN_EXCHANGE_FAILED' - ) - } - - return { - token: data.token, - expiresAt, - workspace: { ...data.workspace, role: data.role }, - ownerUid - } - } - - async function performSwitchWorkspace(workspaceId: string): Promise { - const capturedRequestId = refreshRequestId - const capturedOwnerUid = currentUserUid() - - inFlightSwitchCount += 1 - isLoading.value = true - error.value = null - - try { - const { useSessionCookie } = - await import('@/platform/auth/session/useSessionCookie') - await useSessionCookie().ensureSessionCookie() - if (isStaleWorkspaceRequest(capturedRequestId, capturedOwnerUid)) return - - const { token, expiresAt, workspace, ownerUid } = - await requestToken(workspaceId) - - if (isStaleWorkspaceRequest(capturedRequestId, ownerUid)) { - console.warn( - 'Aborting stale workspace switch: workspace context changed before commit' - ) - return - } - - if (currentWorkspace.value?.id !== workspaceId) { - refreshRequestId++ - } - currentWorkspace.value = workspace - workspaceToken.value = token - workspaceTokenExpiresAt.value = expiresAt - workspaceTokenOwnerUid.value = ownerUid - scheduledRefreshRetryCount = 0 - recoveryCooldownUntil = 0 - - persistToSession(workspace, token, expiresAt, ownerUid) - scheduleTokenRefresh(expiresAt) - } catch (err) { - if (isStaleWorkspaceRequest(capturedRequestId, capturedOwnerUid)) { - console.warn( - 'Aborting stale workspace switch: workspace context changed before error commit', - err - ) - return - } - - error.value = err instanceof Error ? err : new Error(String(err)) - throw error.value - } finally { - inFlightSwitchCount = Math.max(0, inFlightSwitchCount - 1) - isLoading.value = inFlightSwitchCount > 0 - } - } - function switchWorkspace(workspaceId: string): Promise { if (flags.unifiedCloudAuthEnabled) { return switchUnifiedWorkspace(workspaceId) } - const promise = performSwitchWorkspace(workspaceId) - inFlightSwitchPromise = promise - void promise - .catch(() => {}) - .finally(() => { - if (inFlightSwitchPromise === promise) { - inFlightSwitchPromise = null - } - }) - return promise - } - - function hasValidTokenForWorkspace(workspaceId: string | undefined): boolean { - return ( - hasValidWorkspaceToken() && - (workspaceId === undefined || currentWorkspace.value?.id === workspaceId) - ) - } - - // NOT_AUTHENTICATED while still signed in is a transient network failure, not - // a revoked session, so it must not tear down a valid context. - function isPermanentRecoveryFailure(err: unknown): err is WorkspaceAuthError { - if (!isPermanentAuthError(err)) { - return false - } - if (err.code === 'NOT_AUTHENTICATED' && useAuthStore().currentUser) { - return false - } - return true - } - - // The workspace selection itself is invalid (revoked or deleted), so - // abandoning it can help — unlike a plain auth failure. - function isWorkspaceSelectionInvalid( - err: unknown - ): err is WorkspaceAuthError { - return ( - err instanceof WorkspaceAuthError && - (err.code === 'ACCESS_DENIED' || err.code === 'WORKSPACE_NOT_FOUND') - ) - } - - function startRecoveryCooldown(): void { - recoveryCooldownUntil = Date.now() + RECOVERY_COOLDOWN_MS - } - - function handleRecoveryFailure( - err: unknown, - failedWorkspaceId?: string - ): void { - let invalidSelectionHandled = false - if (isPermanentRecoveryFailure(err)) { - const hadContext = currentWorkspace.value !== null - invalidSelectionHandled = endWorkspaceSession( - failedWorkspaceId && isWorkspaceSelectionInvalid(err) - ? failedWorkspaceId - : undefined - ) - if (hadContext) { - surfacePermanentAuthError(err) - } - } - if (!invalidSelectionHandled) startRecoveryCooldown() - console.warn('Workspace auth recovery failed:', err) - } - - /** - * Resolve a valid workspace token, minting one if needed. Coalesces a burst of - * callers onto a single in-flight mint, backs off after failure, and returns - * null so callers fail closed rather than downgrade to the personal identity. - */ - async function ensureWorkspaceToken( - preferredWorkspaceId?: string - ): Promise { - const ownerUid = currentUserUid() - if (!ownerUid) return null - const targetWorkspaceId = preferredWorkspaceId ?? currentWorkspace.value?.id - - for (;;) { - if (!isCurrentUser(ownerUid)) return null - if (hasValidTokenForWorkspace(targetWorkspaceId)) { - return workspaceToken.value - } - - // Join any in-flight mint and re-check rather than launching our own. - if (inFlightSwitchPromise) { - await inFlightSwitchPromise.catch(() => {}) - if (!isCurrentUser(ownerUid)) return null - if (!isCloud && currentWorkspace.value?.id !== targetWorkspaceId) { - return null - } - continue - } - - if (!targetWorkspaceId || Date.now() < recoveryCooldownUntil) { - return null - } - if ( - !isCloud && - useTeamWorkspaceStore().activeWorkspaceId !== targetWorkspaceId - ) { - return null - } - - try { - await switchWorkspace(targetWorkspaceId) - } catch (err) { - if (!isCurrentUser(ownerUid)) return null - handleRecoveryFailure(err, targetWorkspaceId) - return null - } - - if (!isCurrentUser(ownerUid)) return null - if (hasValidTokenForWorkspace(targetWorkspaceId)) { - return workspaceToken.value - } - - // Resolved without a usable token; back off like a failure and fail closed. - startRecoveryCooldown() - return null - } - } - - async function ensureWorkspaceAuthHeader( - preferredWorkspaceId?: string - ): Promise { - const token = await ensureWorkspaceToken(preferredWorkspaceId) - return token ? { Authorization: `Bearer ${token}` } : null - } - - async function refreshToken(): Promise { - if (!currentWorkspace.value) { - return - } - - const workspaceId = currentWorkspace.value.id - const capturedRequestId = refreshRequestId - const maxRetries = 3 - const baseDelayMs = 1000 - // Clear any previous error optimistically; a stale-aborted refresh should - // not leave a stale error visible on the new workspace's context. - error.value = null - - for (let attempt = 0; attempt <= maxRetries; attempt++) { - if (isStaleWorkspaceRequest(capturedRequestId)) { - console.warn( - 'Aborting stale token refresh: workspace context changed during refresh' - ) - return - } - - try { - await switchWorkspace(workspaceId) - return - } catch (err) { - const isAuthError = err instanceof WorkspaceAuthError - - const isPermanentError = - isAuthError && - (err.code === 'ACCESS_DENIED' || - err.code === 'WORKSPACE_NOT_FOUND' || - err.code === 'INVALID_FIREBASE_TOKEN' || - err.code === 'NOT_AUTHENTICATED') - - if (isPermanentError) { - if (!isStaleWorkspaceRequest(capturedRequestId)) { - console.error('Workspace access revoked or auth invalid:', err) - endWorkspaceSession( - isWorkspaceSelectionInvalid(err) ? workspaceId : undefined - ) - } - return - } - - const isTransientError = - isAuthError && err.code === 'TOKEN_EXCHANGE_FAILED' - - if (isTransientError && attempt < maxRetries) { - const delay = baseDelayMs * Math.pow(2, attempt) - console.warn( - `Token refresh failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${delay}ms:`, - err - ) - await new Promise((resolve) => setTimeout(resolve, delay)) - continue - } - - if (!isStaleWorkspaceRequest(capturedRequestId)) { - if (isTransientError && hasValidWorkspaceToken()) { - error.value = null - const retryScheduled = scheduleTokenRefreshRetry( - baseDelayMs * Math.pow(2, maxRetries) - ) - console.warn( - retryScheduled - ? 'Failed to refresh workspace token after retries; preserving existing valid token and retrying later:' - : 'Failed to refresh workspace token after retries; preserving existing valid token until expiry:', - err - ) - return - } - - console.error('Failed to refresh workspace token after retries:', err) - endWorkspaceSession() - } - } - } + return switchLegacyWorkspace(workspaceId) } // --- Unified Cloud-JWT lifecycle (flag-gated: unified_cloud_auth) ---------- @@ -1090,31 +534,6 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { return null } - function getWorkspaceAuthHeader(): AuthHeader | null { - if (!hasValidWorkspaceToken()) { - return null - } - return { - Authorization: `Bearer ${workspaceToken.value}` - } - } - - function getWorkspaceToken(): string | undefined { - return hasValidWorkspaceToken() - ? (workspaceToken.value ?? undefined) - : undefined - } - - function hasValidWorkspaceToken(): boolean { - return ( - workspaceToken.value !== null && - workspaceTokenExpiresAt.value !== null && - workspaceTokenExpiresAt.value > Date.now() && - workspaceTokenOwnerUid.value !== null && - isCurrentUser(workspaceTokenOwnerUid.value) - ) - } - function getUnifiedToken(): string | undefined { return unifiedToken.value !== null && unifiedTokenOwnerUid.value !== null && @@ -1124,16 +543,7 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => { } function clearWorkspaceContext(): void { - refreshRequestId++ - stopRefreshTimer() - currentWorkspace.value = null - workspaceToken.value = null - workspaceTokenExpiresAt.value = null - workspaceTokenOwnerUid.value = null - scheduledRefreshRetryCount = 0 - recoveryCooldownUntil = 0 - // refreshRequestId bump above aborts any in-flight switch before it commits. - inFlightSwitchPromise = null + clearLegacyContext() error.value = null clearSessionStorage() clearUnifiedContext() diff --git a/src/platform/workspace/workspaceConstants.ts b/src/platform/workspace/workspaceConstants.ts index e24d6a8efb5..af2ec21a8e5 100644 --- a/src/platform/workspace/workspaceConstants.ts +++ b/src/platform/workspace/workspaceConstants.ts @@ -9,3 +9,5 @@ export const WORKSPACE_STORAGE_KEYS = { } as const export const TOKEN_REFRESH_BUFFER_MS = 5 * 60 * 1000 + +export const MAX_SCHEDULED_REFRESH_RETRIES = 3