diff --git a/browser_tests/fixtures/apiKeyAuthFixture.ts b/browser_tests/fixtures/apiKeyAuthFixture.ts new file mode 100644 index 00000000000..ca4d4471ae9 --- /dev/null +++ b/browser_tests/fixtures/apiKeyAuthFixture.ts @@ -0,0 +1,160 @@ +import type { Route } from '@playwright/test' +import { test as base } from '@playwright/test' + +import type { + BillingBalanceResponse, + BillingEventsResponse, + BillingPlansResponse, + BillingStatusResponse, + CurrentWorkspaceResponse +} from '@comfyorg/ingest-types' +import { formatCreditsFromCents } from '@/base/credits/comfyCredits' +import type { operations } from '@/types/comfyRegistryTypes' +import { ComfyPage } from '@e2e/fixtures/ComfyPage' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' + +type CreateCustomerResponse = + operations['createCustomer']['responses']['201']['content']['application/json'] + +const E2E_API_KEY = 'comfyui-e2e-api-key' + +// Workspace-rail mocks authenticate like the real API: a request that does +// not carry the stored key as X-API-KEY gets a 401 instead of data, so the +// suite fails if the client stops wiring the credential through. +const fulfillForApiKey = (route: Route, body: T) => + route.request().headers()['x-api-key'] === E2E_API_KEY + ? route.fulfill(jsonRoute(body)) + : route.fulfill({ + status: 401, + json: { code: 'UNAUTHORIZED', message: 'X-API-KEY required' } + }) + +export const API_KEY_WORKSPACE: CurrentWorkspaceResponse = { + id: 'ws-api-key-team', + name: 'API Key Team', + type: 'team', + role: 'owner', + auth_method: 'cloud_api_key' +} + +const API_KEY_BALANCE_CENTS = 123_400 + +export const API_KEY_BALANCE_DISPLAY = formatCreditsFromCents({ + cents: API_KEY_BALANCE_CENTS, + locale: 'en', + numberOptions: { minimumFractionDigits: 0, maximumFractionDigits: 2 } +}) + +const API_KEY_WORKSPACE_EVENT_ID = 'evt-api-key-workspace' + +/** + * Boots the local (non-Cloud) build as an API-key-only session: no Firebase + * user, a stored `comfy_api_key`, and the cloud API resolving that key to a + * single bound workspace. Mirrors the QA flow behind the 1.51 API-key billing + * findings: workspace context, balance, and activity must all come from the + * key's workspace via `/api/workspaces/current` and `/api/billing/*`, never + * from the legacy user-scoped `/customers/*` rail. + * + * The fixture records any legacy-rail read so specs can assert the session + * never falls back to it. + */ +export const apiKeyAuthFixture = base.extend<{ + comfyPage: ComfyPage + legacyBillingReads: string[] +}>({ + legacyBillingReads: async ({ page }, use) => { + const reads: string[] = [] + await page.route('**/customers/balance', (route) => { + reads.push(route.request().url()) + return route.fulfill(jsonRoute({ amount_micros: 0, currency: 'usd' })) + }) + await page.route('**/customers/events**', (route) => { + reads.push(route.request().url()) + return route.fulfill( + jsonRoute({ events: [], page: 1, limit: 7, total: 0, totalPages: 0 }) + ) + }) + await use(reads) + }, + comfyPage: async ({ page, request, legacyBillingReads }, use, testInfo) => { + testInfo.setTimeout(45_000) + void legacyBillingReads + + const comfyPage = new ComfyPage(page, request) + const userId = await comfyPage.setupUser( + `playwright-api-key-${testInfo.parallelIndex}` + ) + await comfyPage.setupSettings({ + 'Comfy.TutorialCompleted': true, + 'Comfy.userId': userId + }) + + await page.route('**/customers', (route) => { + if (route.request().method() !== 'POST') return route.fallback() + return route.fulfill({ + status: 201, + json: { id: 'api-key-user-e2e' } satisfies CreateCustomerResponse + }) + }) + await page.route('**/api/workspaces/current', (route) => + fulfillForApiKey(route, API_KEY_WORKSPACE) + ) + await page.route('**/api/billing/status', (route) => + fulfillForApiKey(route, { + billing_rail: 'stripe', + billing_status: 'paid', + has_funds: true, + is_active: true, + max_seats: 50, + occupied_seats: 1, + subscription_status: 'active', + subscription_tier: 'TEAM', + team_credit_stop: null + } satisfies BillingStatusResponse) + ) + await page.route('**/api/billing/balance', (route) => + fulfillForApiKey(route, { + amount_micros: API_KEY_BALANCE_CENTS, + currency: 'usd', + effective_balance_micros: API_KEY_BALANCE_CENTS + } satisfies BillingBalanceResponse) + ) + await page.route('**/api/billing/plans', (route) => + fulfillForApiKey(route, { plans: [] } satisfies BillingPlansResponse) + ) + await page.route('**/api/billing/events**', (route) => + fulfillForApiKey(route, { + events: [ + { + event_id: API_KEY_WORKSPACE_EVENT_ID, + event_type: 'credit_added', + createdAt: '2026-08-25T00:00:00Z', + params: { amount: API_KEY_BALANCE_CENTS } + } + ], + page: 1, + limit: 7, + total: 1, + totalPages: 1 + } satisfies BillingEventsResponse) + ) + + await page.addInitScript( + ({ id, key }) => { + if (localStorage.getItem('Comfy.userId') !== id) { + localStorage.clear() + sessionStorage.clear() + localStorage.setItem('Comfy.userId', id) + localStorage.setItem('comfy_api_key', key) + } + }, + { id: userId, key: E2E_API_KEY } + ) + + await comfyPage.goto() + await page.waitForFunction(() => document.fonts.ready) + await comfyPage.waitForAppReady() + + await use(comfyPage) + } +}) diff --git a/browser_tests/tests/workspace/apiKeyLoginBilling.spec.ts b/browser_tests/tests/workspace/apiKeyLoginBilling.spec.ts new file mode 100644 index 00000000000..784a5252035 --- /dev/null +++ b/browser_tests/tests/workspace/apiKeyLoginBilling.spec.ts @@ -0,0 +1,57 @@ +import { expect } from '@playwright/test' + +import { TestIds } from '@e2e/fixtures/selectors' +import { + API_KEY_BALANCE_DISPLAY, + API_KEY_WORKSPACE, + apiKeyAuthFixture as test +} from '@e2e/fixtures/apiKeyAuthFixture' + +/** + * Regression coverage for the 1.51 QA API-key login findings: an API-key + * session never established workspace context, so every billing surface fell + * back to the legacy user-scoped /customers/* rail — empty workspace name, + * zero balance, another workspace's activity, and top-ups the backend + * rejects. The session must read workspace name, balance, and activity from + * the key's server-resolved workspace via /api/workspaces/current and + * /api/billing/*. + */ +test.describe('API-key login billing surfaces', () => { + test('shows the key workspace context, balance, and activity from the workspace rail', async ({ + comfyPage, + legacyBillingReads + }) => { + const page = comfyPage.page + + await page.getByTestId(TestIds.user.currentUserButton).click() + const popover = page.getByTestId(TestIds.user.currentUserPopover) + await expect(popover).toBeVisible() + + const workspaceRow = popover.getByTestId('workspace-context-row') + await expect(workspaceRow).toContainText(API_KEY_WORKSPACE.name) + await expect(popover.getByTestId('workspace-switcher-trigger')).toHaveCount( + 0 + ) + await expect(popover).toContainText(API_KEY_BALANCE_DISPLAY) + + await popover.getByTestId('plans-credits-menu-item').click() + + const settingsDialog = comfyPage.settingDialog + await settingsDialog.waitForVisible() + await expect( + settingsDialog.contentArea.getByRole('heading', { + name: API_KEY_WORKSPACE.name + }) + ).toBeVisible() + await expect(settingsDialog.contentArea).toContainText( + API_KEY_BALANCE_DISPLAY + ) + + await settingsDialog.contentArea + .getByRole('button', { name: 'Activity' }) + .click() + await expect(settingsDialog.contentArea).toContainText('Credits Added') + + expect(legacyBillingReads).toEqual([]) + }) +}) diff --git a/src/composables/auth/useCurrentUser.test.ts b/src/composables/auth/useCurrentUser.test.ts new file mode 100644 index 00000000000..7b6e55f0c17 --- /dev/null +++ b/src/composables/auth/useCurrentUser.test.ts @@ -0,0 +1,55 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { useCurrentUser } from './useCurrentUser' + +const mockAuthState = { + currentUser: null as { uid: string } | null, + loading: false, + tokenRefreshTrigger: 0 +} +vi.mock('@/stores/authStore', () => ({ + useAuthStore: () => mockAuthState +})) + +const mockApiKeyState = { + isAuthenticated: false, + currentUser: null as { id: string; email?: string; name?: string } | null +} +vi.mock('@/stores/apiKeyAuthStore', () => ({ + useApiKeyAuthStore: () => mockApiKeyState +})) + +vi.mock('@/stores/commandStore', () => ({ + useCommandStore: () => ({ execute: vi.fn() }) +})) + +describe('useCurrentUser', () => { + beforeEach(() => { + mockAuthState.currentUser = null + mockApiKeyState.isAuthenticated = false + mockApiKeyState.currentUser = null + }) + + it('treats a key-only session as an API-key login', () => { + mockApiKeyState.isAuthenticated = true + mockApiKeyState.currentUser = { id: 'key-user' } + + const { isApiKeyLogin, isLoggedIn, resolvedUserInfo } = useCurrentUser() + + expect(isApiKeyLogin.value).toBe(true) + expect(isLoggedIn.value).toBe(true) + expect(resolvedUserInfo.value).toEqual({ id: 'key-user' }) + }) + + it('gives the Firebase session precedence over a stored API key', () => { + mockAuthState.currentUser = { uid: 'firebase-user' } + mockApiKeyState.isAuthenticated = true + mockApiKeyState.currentUser = { id: 'key-user' } + + const { isApiKeyLogin, isLoggedIn, resolvedUserInfo } = useCurrentUser() + + expect(isApiKeyLogin.value).toBe(false) + expect(isLoggedIn.value).toBe(true) + expect(resolvedUserInfo.value).toEqual({ id: 'firebase-user' }) + }) +}) diff --git a/src/composables/auth/useCurrentUser.ts b/src/composables/auth/useCurrentUser.ts index 9615f6a327f..de07744e1cd 100644 --- a/src/composables/auth/useCurrentUser.ts +++ b/src/composables/auth/useCurrentUser.ts @@ -12,7 +12,12 @@ export const useCurrentUser = () => { const apiKeyStore = useApiKeyAuthStore() const firebaseUser = computed(() => authStore.currentUser) - const isApiKeyLogin = computed(() => apiKeyStore.isAuthenticated) + // A Firebase session takes precedence on every auth rail (see + // authStore.getUserAuthHeader), so a stored key behind a Firebase login is + // not an API-key session. + const isApiKeyLogin = computed( + () => apiKeyStore.isAuthenticated && firebaseUser.value === null + ) const isLoggedIn = computed( () => !!isApiKeyLogin.value || firebaseUser.value !== null ) diff --git a/src/platform/workspace/api/workspaceApi.ts b/src/platform/workspace/api/workspaceApi.ts index 5d95cb589fb..283c0228be1 100644 --- a/src/platform/workspace/api/workspaceApi.ts +++ b/src/platform/workspace/api/workspaceApi.ts @@ -14,6 +14,7 @@ import type { CreateTopupRequest, CreateTopupResponse, CreateWorkspaceRequest, + CurrentWorkspaceResponse, ListInvitesResponse, ListMembersResponse, ListWorkspacesResponse, @@ -76,6 +77,7 @@ export type { SubscriptionTier } export type { SubscriptionDuration } export type { WorkspaceWithRole } export type { ListWorkspacesResponse } +export type { CurrentWorkspaceResponse } export type { Plan } export type { BillingPlansResponse } export type { TeamCreditStops } @@ -191,6 +193,23 @@ export const workspaceApi = { } }, + /** + * Get the workspace bound to the current credential + * GET /api/workspaces/current + */ + async getCurrentWorkspace(): Promise { + const headers = await getAuthHeaderOrThrow() + try { + const response = await workspaceApiClient.get( + workspaceApiUrl('/workspaces/current'), + { headers } + ) + return response.data + } catch (err) { + handleAxiosError(err) + } + }, + /** * Create a new workspace * POST /api/workspaces diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts index c6b0c769720..42b3762185a 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.test.ts +++ b/src/platform/workspace/auth/WorkspaceAuthGate.test.ts @@ -73,6 +73,7 @@ vi.mock('@/platform/workspace/stores/workspaceAuthStore', () => ({ })) const mockWorkspaceStoreInitialize = vi.fn() +const mockWorkspaceStoreReset = vi.fn() const mockBillingCapabilitiesInitialize = vi.hoisted(() => vi.fn()) const mockWorkspaceStoreInitState = vi.hoisted(() => ({ value: 'uninitialized' as string @@ -88,7 +89,18 @@ vi.mock('@/platform/workspace/stores/teamWorkspaceStore', () => ({ get activeWorkspaceId() { return mockActiveWorkspaceId.value }, - initialize: mockWorkspaceStoreInitialize + initialize: mockWorkspaceStoreInitialize, + resetForIdentityChange: mockWorkspaceStoreReset + }) +})) + +const mockApiKeyAuthenticated = ref(false) +vi.mock('@/stores/apiKeyAuthStore', () => ({ + useApiKeyAuthStore: () => ({ + get isAuthenticated() { + return mockApiKeyAuthenticated.value + }, + getApiKey: () => (mockApiKeyAuthenticated.value ? 'comfyui-test-key' : null) }) })) @@ -110,6 +122,7 @@ describe('WorkspaceAuthGate', () => { mockIsCloud.value = true mockIsInitialized.value = false mockCurrentUser.value = null + mockApiKeyAuthenticated.value = false mockUnifiedCloudAuthEnabled.value = false mockRemoteConfigState.value = 'authenticated' mockRemoteConfigErrorStatus.value = null @@ -120,6 +133,9 @@ describe('WorkspaceAuthGate', () => { mockWorkspaceStoreInitialize.mockImplementation(async () => { mockWorkspaceStoreInitState.value = 'ready' }) + mockWorkspaceStoreReset.mockImplementation(() => { + mockWorkspaceStoreInitState.value = 'uninitialized' + }) mockMintAtLogin.mockResolvedValue(true) mockGetUnifiedToken.mockReturnValue('cloud-jwt') }) @@ -211,6 +227,48 @@ describe('WorkspaceAuthGate', () => { expect(mockWorkspaceStoreInitialize).not.toHaveBeenCalled() }) + + it('initializes workspace context after an API-key sign-in', async () => { + mockIsCloud.value = false + mockIsInitialized.value = true + + mountComponent() + await flushPromises() + expect(mockWorkspaceStoreInitialize).not.toHaveBeenCalled() + + mockApiKeyAuthenticated.value = true + await flushPromises() + + expect(mockWorkspaceStoreInitialize).toHaveBeenCalledOnce() + }) + + it('cancels pending initialization on API-key sign-out', async () => { + mockIsCloud.value = false + mockApiKeyAuthenticated.value = true + + mountComponent() + mockApiKeyAuthenticated.value = false + mockIsInitialized.value = true + await flushPromises() + + expect(mockWorkspaceStoreInitialize).not.toHaveBeenCalled() + }) + + it('resets workspace state when the session identity changes', async () => { + mockIsCloud.value = false + mockIsInitialized.value = true + mockApiKeyAuthenticated.value = true + + mountComponent() + await flushPromises() + + mockApiKeyAuthenticated.value = false + mockCurrentUser.value = { uid: 'user-123' } + await flushPromises() + + expect(mockWorkspaceStoreReset).toHaveBeenCalled() + expect(mockWorkspaceStoreInitialize).toHaveBeenCalledTimes(2) + }) }) describe('cloud builds - unauthenticated user', () => { diff --git a/src/platform/workspace/auth/WorkspaceAuthGate.vue b/src/platform/workspace/auth/WorkspaceAuthGate.vue index 0a2eea33639..ccd830fed86 100644 --- a/src/platform/workspace/auth/WorkspaceAuthGate.vue +++ b/src/platform/workspace/auth/WorkspaceAuthGate.vue @@ -59,6 +59,7 @@ import { until } from '@vueuse/core' import { storeToRefs } from 'pinia' import { + computed, nextTick, onMounted, onUnmounted, @@ -80,6 +81,7 @@ import { reportError } from '@/platform/telemetry/reportError' import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' +import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' import { useAuthStore } from '@/stores/authStore' const FIREBASE_INIT_TIMEOUT_MS = 16_000 @@ -235,16 +237,29 @@ async function initializeWorkspaceMode(): Promise { } } +// The local session identity: the Firebase uid, or the validated API key for +// key-only sessions. Workspace initialization keys off this so an API-key +// login boots workspace context the same way a Firebase login does. +function localSessionIdentity(): string | null { + const { currentUser } = storeToRefs(useAuthStore()) + if (currentUser.value?.uid) return currentUser.value.uid + const apiKeyStore = useApiKeyAuthStore() + return apiKeyStore.isAuthenticated ? apiKeyStore.getApiKey() : null +} + function initializeWorkspacesInBackground(): Promise { - const { isInitialized, currentUser } = storeToRefs(useAuthStore()) - const userId = currentUser.value?.uid ?? null - if (backgroundInitialization && backgroundInitializationUserId === userId) { + const { isInitialized } = storeToRefs(useAuthStore()) + const sessionId = localSessionIdentity() + if ( + backgroundInitialization && + backgroundInitializationUserId === sessionId + ) { return backgroundInitialization } cancelInitialization() const generation = initializationGeneration - backgroundInitializationUserId = userId + backgroundInitializationUserId = sessionId const operation = (async () => { if (!isInitialized.value) { @@ -254,8 +269,9 @@ function initializeWorkspacesInBackground(): Promise { }) } if ( + sessionId === null || generation !== initializationGeneration || - currentUser.value?.uid !== userId + localSessionIdentity() !== sessionId ) { return } @@ -287,9 +303,12 @@ onMounted(() => { }) if (!isCloud) { - const { currentUser } = storeToRefs(useAuthStore()) - watch(currentUser, (user) => { - if (user) { + const sessionIdentity = computed(() => localSessionIdentity()) + watch(sessionIdentity, (identity, previousIdentity) => { + if (previousIdentity !== null && identity !== previousIdentity) { + useTeamWorkspaceStore().resetForIdentityChange() + } + if (identity) { void initializeWorkspacesInBackground() } else { cancelInitialization() diff --git a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue index f759dadff28..e24bd9b085a 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue @@ -26,43 +26,62 @@
- - + +
@@ -293,8 +312,13 @@ const { accountActionsOnly = false } = defineProps<{ const { buildDocsUrl, docsPaths } = useExternalLink() -const { userDisplayName, userEmail, userPhotoUrl, handleSignOut } = - useCurrentUser() +const { + userDisplayName, + userEmail, + userPhotoUrl, + handleSignOut, + isApiKeyLogin +} = useCurrentUser() const settingsDialog = useSettingsDialog() const dialogService = useDialogService() const { diff --git a/src/platform/workspace/stores/teamWorkspaceStore.test.ts b/src/platform/workspace/stores/teamWorkspaceStore.test.ts index 71667da6e95..4ca140cd9cd 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.test.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.test.ts @@ -49,18 +49,24 @@ vi.mock('@/platform/auth/session/useSessionCookie', () => ({ }) })) -// Mock current user (drives the original-owner self-row match by email) +// Mock current user (drives the original-owner self-row match by email and +// the API-key bootstrap branch) const mockCurrentUser = vi.hoisted(() => ({ - userEmail: { value: null as string | null } + userEmail: { value: null as string | null }, + isApiKeyLogin: { value: false } })) vi.mock('@/composables/auth/useCurrentUser', () => ({ - useCurrentUser: () => ({ userEmail: mockCurrentUser.userEmail }) + useCurrentUser: () => ({ + userEmail: mockCurrentUser.userEmail, + isApiKeyLogin: mockCurrentUser.isApiKeyLogin + }) })) // Mock workspaceApi const mockWorkspaceApi = vi.hoisted(() => ({ list: vi.fn(), + getCurrentWorkspace: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn(), @@ -165,6 +171,7 @@ describe('useTeamWorkspaceStore', () => { vi.stubGlobal('localStorage', mockLocalStorage) sessionStorage.clear() mockCurrentUser.userEmail.value = null + mockCurrentUser.isApiKeyLogin.value = false // Reset workspaceAuthStore mock state mockWorkspaceAuthStore.currentWorkspace = null @@ -446,6 +453,91 @@ describe('useTeamWorkspaceStore', () => { }) }) + describe('initialize with an API-key session', () => { + beforeEach(() => { + mockCurrentUser.isApiKeyLogin.value = true + mockWorkspaceApi.getCurrentWorkspace.mockResolvedValue({ + id: 'ws-api-key', + name: 'Key Workspace', + type: 'team', + role: 'owner', + auth_method: 'cloud_api_key' + }) + }) + + it('seeds the credential-bound workspace without discovery or token exchange', async () => { + const store = useTeamWorkspaceStore() + + await store.initialize() + + expect(store.initState).toBe('ready') + expect(store.workspaces).toEqual([ + expect.objectContaining({ + id: 'ws-api-key', + name: 'Key Workspace', + type: 'team', + role: 'owner' + }) + ]) + expect(store.activeWorkspaceId).toBe('ws-api-key') + expect(mockWorkspaceApi.list).not.toHaveBeenCalled() + expect(mockWorkspaceAuthStore.switchWorkspace).not.toHaveBeenCalled() + expect(mockEnsureSessionCookie).not.toHaveBeenCalled() + }) + + it('defaults an omitted role to member so owner-only actions stay hidden', async () => { + mockWorkspaceApi.getCurrentWorkspace.mockResolvedValue({ + id: 'ws-api-key', + name: 'Key Workspace', + type: 'personal', + auth_method: 'comfy_api_key' + }) + + const store = useTeamWorkspaceStore() + await store.initialize() + + expect(store.activeWorkspace?.role).toBe('member') + }) + + it('fails immediately when the credential resolves no workspace', async () => { + mockWorkspaceApi.getCurrentWorkspace.mockRejectedValue( + new mockWorkspaceApiError('No workspace is bound', 404, 'NOT_FOUND') + ) + + const store = useTeamWorkspaceStore() + + await expect(store.initialize()).rejects.toThrow('No workspace is bound') + + expect(mockWorkspaceApi.getCurrentWorkspace).toHaveBeenCalledOnce() + expect(store.initState).toBe('error') + expect(store.activeWorkspaceId).toBeNull() + }) + + it('retries transient failures before seeding the workspace', async () => { + mockWorkspaceApi.getCurrentWorkspace + .mockRejectedValueOnce( + new mockWorkspaceApiError('bad gateway', 502, 'BAD_GATEWAY') + ) + .mockResolvedValueOnce({ + id: 'ws-api-key', + name: 'Key Workspace', + type: 'team', + role: 'owner', + auth_method: 'cloud_api_key' + }) + + const store = useTeamWorkspaceStore() + const initialization = store.initialize() + + await vi.advanceTimersByTimeAsync(1000) + await initialization + + expect(mockWorkspaceApi.getCurrentWorkspace).toHaveBeenCalledTimes(2) + expect(store.initState).toBe('ready') + expect(store.activeWorkspaceId).toBe('ws-api-key') + }) + }) + describe('switchWorkspace', () => { it('does nothing if switching to current workspace', async () => { const store = useTeamWorkspaceStore() diff --git a/src/platform/workspace/stores/teamWorkspaceStore.ts b/src/platform/workspace/stores/teamWorkspaceStore.ts index eda9eaeda5b..473f20fef83 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.ts @@ -14,13 +14,14 @@ import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuth import type { BillingRail, + CurrentWorkspaceResponse, ListMembersParams, Member, PendingInvite as ApiPendingInvite, SubscriptionTier, WorkspaceWithRole } from '../api/workspaceApi' -import { workspaceApi } from '../api/workspaceApi' +import { WorkspaceApiError, workspaceApi } from '../api/workspaceApi' export interface WorkspaceMember { id: string @@ -89,6 +90,26 @@ function createWorkspaceState(workspace: WorkspaceWithRole): WorkspaceState { } } +/** + * Builds workspace state from GET /api/workspaces/current — the single + * workspace bound to an API-key credential. The response carries no + * membership timestamps (only sortWorkspaces reads them, and a one-entry list + * never sorts) and may omit role, which fails closed to member so owner-only + * billing actions stay hidden rather than 403 on click. + */ +function createWorkspaceStateFromCredential( + current: CurrentWorkspaceResponse +): WorkspaceState { + return createWorkspaceState({ + id: current.id, + name: current.name, + type: current.type, + role: current.role ?? 'member', + created_at: '', + joined_at: '' + }) +} + export function sortWorkspaces(list: T[]): T[] { return [...list].sort((a, b) => { if (a.type === 'personal') return -1 @@ -277,9 +298,24 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { error.value = null const workspaceAuthStore = useWorkspaceAuthStore() + const isApiKeySession = useCurrentUser().isApiKeyLogin.value for (let attempt = 0; attempt <= MAX_INIT_RETRIES; attempt++) { try { + // An API-key credential is bound to exactly one workspace on the + // server. There is no discovery, switching, or token exchange for it: + // the server echoes the binding back and the key itself authenticates + // workspace-scoped calls. + if (isApiKeySession) { + const current = await workspaceApi.getCurrentWorkspace() + if (isStaleIdentity(generation)) return + workspaces.value = [createWorkspaceStateFromCredential(current)] + mutableActiveWorkspaceId.value = current.id + initState.value = 'ready' + isFetchingWorkspaces.value = false + return + } + const { useSessionCookie } = await import('@/platform/auth/session/useSessionCookie') await useSessionCookie().ensureSessionCookie() @@ -371,9 +407,24 @@ export const useTeamWorkspaceStore = defineStore('teamWorkspace', () => { if (isStaleIdentity(generation)) return const isNoWorkspacesError = e instanceof Error && e.message === 'No workspaces available' + // A definitive 4xx on the credential lookup cannot be repaired by + // resending the same key; retries stay reserved for transient + // failures (network, 408/429, 5xx). + const isPermanentCredentialError = + isApiKeySession && + e instanceof WorkspaceApiError && + e.status !== undefined && + e.status >= 400 && + e.status < 500 && + e.status !== 408 && + e.status !== 429 // Don't retry on permanent errors (no workspaces available) - if (isNoWorkspacesError || attempt >= MAX_INIT_RETRIES) { + if ( + isNoWorkspacesError || + isPermanentCredentialError || + attempt >= MAX_INIT_RETRIES + ) { error.value = e instanceof Error ? e : new Error('Unknown error') initState.value = 'error' isFetchingWorkspaces.value = false diff --git a/src/scripts/app.test.ts b/src/scripts/app.test.ts index fbdb3b189cb..1ff60816042 100644 --- a/src/scripts/app.test.ts +++ b/src/scripts/app.test.ts @@ -70,10 +70,12 @@ const { mockWorkflowService } = vi.hoisted(() => ({ mockApiKeyAuthStore: { - getApiKey: vi.fn() + getApiKey: vi.fn(), + isAuthenticated: false }, mockAuthStore: { - getWorkspaceAuthToken: vi.fn() + getWorkspaceAuthToken: vi.fn(), + currentUser: null as { uid: string } | null }, mockSettingStore: { get: vi.fn() @@ -295,6 +297,8 @@ describe('ComfyApp', () => { return workflow }) mockApiKeyAuthStore.getApiKey.mockReturnValue(undefined) + mockApiKeyAuthStore.isAuthenticated = false + mockAuthStore.currentUser = null mockAuthStore.getWorkspaceAuthToken.mockResolvedValue('workspace-token') mockTeamWorkspaceStore.activeWorkspaceId = 'workspace-a' mockTeamWorkspaceStore.workspaceTransitionGeneration = 0 @@ -503,6 +507,36 @@ describe('ComfyApp', () => { expect(showDialog).toHaveBeenCalledOnce() }) + it('does not accept the API key when a Firebase session lost its workspace token', async () => { + prepareEmptyPromptQueue() + mockAuthStore.currentUser = { uid: 'firebase-user' } + mockApiKeyAuthStore.isAuthenticated = true + mockApiKeyAuthStore.getApiKey.mockReturnValue('api-key') + mockAuthStore.getWorkspaceAuthToken.mockResolvedValueOnce(undefined) + const queuePrompt = vi.spyOn(api, 'queuePrompt') + const showDialog = vi.spyOn(useDialogStore(), 'showDialog') + + await expect(app.queuePrompt(0)).resolves.toBe(false) + expect(queuePrompt).not.toHaveBeenCalled() + expect(showDialog).toHaveBeenCalledOnce() + }) + + it('submits with the validated API key when the key session has a workspace', async () => { + prepareEmptyPromptQueue() + mockApiKeyAuthStore.isAuthenticated = true + mockApiKeyAuthStore.getApiKey.mockReturnValue('comfyui-valid-key') + mockAuthStore.getWorkspaceAuthToken.mockResolvedValueOnce(undefined) + const queuePrompt = vi + .spyOn(api, 'queuePrompt') + .mockImplementation(() => { + expect(api.apiKey).toBe('comfyui-valid-key') + return Promise.resolve({ prompt_id: 'job-1', error: '' }) + }) + + await expect(app.queuePrompt(0)).resolves.toBe(true) + expect(queuePrompt).toHaveBeenCalledOnce() + }) + it('does not submit after switching away and back to the same workspace', async () => { prepareEmptyPromptQueue() mockAuthStore.getWorkspaceAuthToken.mockResolvedValueOnce( diff --git a/src/scripts/app.ts b/src/scripts/app.ts index f4995c941e6..84e054eb915 100644 --- a/src/scripts/app.ts +++ b/src/scripts/app.ts @@ -1653,7 +1653,19 @@ export class ComfyApp { workspaceGenerationBeforeAuthentication !== executionWorkspaceGeneration) && (isCloud || workspaceIdBeforeAuthentication !== null) - if (executionWorkspaceId && !comfyOrgAuthToken) { + const comfyOrgApiKey = useApiKeyAuthStore().getApiKey() + // An API-key session mints no workspace JWT: the key itself is the + // execution credential and the server resolves its bound workspace. Only a + // key-authenticated session may pass without a token — a Firebase session + // whose token mint failed must still fail closed rather than fall back to + // a stored key and charge the key's workspace. + const isApiKeySessionExecution = + !useAuthStore().currentUser && useApiKeyAuthStore().isAuthenticated + if ( + executionWorkspaceId && + !comfyOrgAuthToken && + !isApiKeySessionExecution + ) { useDialogService().showErrorDialog( new Error(t('toastMessages.userNotAuthenticated')), { @@ -1665,7 +1677,6 @@ export class ComfyApp { this.processingQueue = false return false } - const comfyOrgApiKey = useApiKeyAuthStore().getApiKey() try { while (this.queueItems.length) { diff --git a/src/stores/__tests__/authTokenPriority.test.ts b/src/stores/__tests__/authTokenPriority.test.ts index 2164ae37640..2921944674a 100644 --- a/src/stores/__tests__/authTokenPriority.test.ts +++ b/src/stores/__tests__/authTokenPriority.test.ts @@ -108,12 +108,15 @@ vi.mock('@/services/dialogService') vi.mock('@/platform/distribution/types', () => mockDistributionTypes) const mockApiKeyGetAuthHeader = vi.fn().mockReturnValue(null) +const mockApiKeyState = { isAuthenticated: false } vi.mock('@/stores/apiKeyAuthStore', () => ({ useApiKeyAuthStore: () => ({ getAuthHeader: mockApiKeyGetAuthHeader, getApiKey: vi.fn(), currentUser: null, - isAuthenticated: false, + get isAuthenticated() { + return mockApiKeyState.isAuthenticated + }, storeApiKey: vi.fn(), clearStoredApiKey: vi.fn() }) @@ -146,6 +149,7 @@ describe('auth token priority chain', () => { mockMintAtLogin.mockResolvedValue(false) mockInitializeWorkspaces.mockResolvedValue(undefined) mockApiKeyGetAuthHeader.mockReturnValue(null) + mockApiKeyState.isAuthenticated = false mockUser.getIdToken.mockResolvedValue('firebase-token') vi.mocked(vuefire.useFirebaseAuth).mockReturnValue( @@ -260,6 +264,36 @@ describe('auth token priority chain', () => { }) describe('explicit workspace authentication', () => { + it('sends the stored API key for workspace calls in an API-key session', async () => { + mockDistributionTypes.isCloud = false + authStateCallback(null) + mockApiKeyState.isAuthenticated = true + mockApiKeyGetAuthHeader.mockReturnValue({ 'X-API-KEY': 'comfyui-test' }) + mockActiveWorkspaceId = 'workspace-123' + + await expect(store.getWorkspaceAuthHeader()).resolves.toEqual({ + 'X-API-KEY': 'comfyui-test' + }) + expect(mockEnsureWorkspaceAuthHeader).not.toHaveBeenCalled() + + await expect(store.getWorkspaceAuthToken()).resolves.toBeUndefined() + expect(mockEnsureWorkspaceToken).not.toHaveBeenCalled() + }) + + it('prefers the Firebase session over a stored API key for workspace calls', async () => { + mockDistributionTypes.isCloud = false + mockApiKeyState.isAuthenticated = true + mockApiKeyGetAuthHeader.mockReturnValue({ 'X-API-KEY': 'comfyui-test' }) + mockActiveWorkspaceId = 'workspace-123' + mockEnsureWorkspaceAuthHeader.mockResolvedValue({ + Authorization: 'Bearer workspace-token' + }) + + await expect(store.getWorkspaceAuthHeader()).resolves.toEqual({ + Authorization: 'Bearer workspace-token' + }) + }) + it('uses selected workspace authentication outside Cloud', async () => { mockDistributionTypes.isCloud = false mockActiveWorkspaceId = 'workspace-123' diff --git a/src/stores/apiKeyAuthStore.ts b/src/stores/apiKeyAuthStore.ts index bd203b63f9e..4f6989460a7 100644 --- a/src/stores/apiKeyAuthStore.ts +++ b/src/stores/apiKeyAuthStore.ts @@ -38,15 +38,17 @@ export const useApiKeyAuthStore = defineStore('apiKeyAuth', () => { currentUser.value = createCustomerResponse } + // The stored key and its validated user form one session value: replacing + // the key ends the previous user's session immediately instead of exposing + // the old user while the new key validates. watch( apiKey, async (watchedApiKey) => { + currentUser.value = null if (watchedApiKey) { await nextTick() if (apiKey.value !== watchedApiKey) return void initializeUserFromApiKey(watchedApiKey) - } else { - currentUser.value = null } }, { immediate: true } diff --git a/src/stores/authStore.ts b/src/stores/authStore.ts index 27a012e95d3..59d105f4a5c 100644 --- a/src/stores/authStore.ts +++ b/src/stores/authStore.ts @@ -313,12 +313,23 @@ export const useAuthStore = defineStore('auth', () => { } } + /** + * Returns the workspace-scoped auth header. An API-key session has no + * Firebase token to exchange for a workspace token; the key itself is the + * workspace credential (the server resolves the key's bound workspace), so + * it is sent directly instead of minting a token. + */ const getWorkspaceAuthHeader = async (): Promise => { if (flags.unifiedCloudAuthEnabled) { const token = useWorkspaceAuthStore().getUnifiedToken() return token ? { Authorization: `Bearer ${token}` } : null } + if (currentUser.value === null) { + const apiKeyHeader = useApiKeyAuthStore().getAuthHeader() + if (apiKeyHeader) return apiKeyHeader + } + const activeWorkspaceId = useTeamWorkspaceStore().activeWorkspaceId if (!activeWorkspaceId) return getFirebaseAuthHeader() return useWorkspaceAuthStore().ensureWorkspaceAuthHeader(activeWorkspaceId) @@ -358,6 +369,10 @@ export const useAuthStore = defineStore('auth', () => { return useWorkspaceAuthStore().getUnifiedToken() } + if (currentUser.value === null && useApiKeyAuthStore().isAuthenticated) { + return undefined + } + const teamWorkspaceStore = useTeamWorkspaceStore() if ( !isCloud &&