From 1e5a5c91748888fb109d08f625ef43eae7202a0e Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 25 Aug 2026 19:03:45 +0000 Subject: [PATCH 1/3] fix(workspace): establish workspace context for API-key sessions An API-key login never initialized the team workspace store: the gate only watched the Firebase user, and workspace API calls had no API-key auth fallback. Billing routing therefore stayed on the legacy user-scoped /customers/* rail, showing an empty workspace name, zero balance, another workspace's activity, and top-ups the backend rejects with workspace_billing_required. The key is bound to exactly one workspace on the server, so the session now bootstraps from GET /api/workspaces/current, sends X-API-KEY on workspace-scoped calls, and hides workspace switching per the API-key auth contract. --- browser_tests/fixtures/apiKeyAuthFixture.ts | 149 ++++++++++++++++++ .../workspace/apiKeyLoginBilling.spec.ts | 57 +++++++ src/platform/workspace/api/workspaceApi.ts | 19 +++ .../workspace/auth/WorkspaceAuthGate.test.ts | 60 ++++++- .../workspace/auth/WorkspaceAuthGate.vue | 35 +++- .../CurrentUserPopoverWorkspace.vue | 25 ++- .../stores/teamWorkspaceStore.test.ts | 77 ++++++++- .../workspace/stores/teamWorkspaceStore.ts | 36 +++++ .../__tests__/authTokenPriority.test.ts | 36 ++++- src/stores/authStore.ts | 15 ++ 10 files changed, 494 insertions(+), 15 deletions(-) create mode 100644 browser_tests/fixtures/apiKeyAuthFixture.ts create mode 100644 browser_tests/tests/workspace/apiKeyLoginBilling.spec.ts diff --git a/browser_tests/fixtures/apiKeyAuthFixture.ts b/browser_tests/fixtures/apiKeyAuthFixture.ts new file mode 100644 index 00000000000..cfbe3a983e7 --- /dev/null +++ b/browser_tests/fixtures/apiKeyAuthFixture.ts @@ -0,0 +1,149 @@ +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'] + +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) => + route.fulfill(jsonRoute(API_KEY_WORKSPACE)) + ) + await page.route('**/api/billing/status', (route) => + route.fulfill( + jsonRoute({ + 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) => + route.fulfill( + jsonRoute({ + amount_micros: API_KEY_BALANCE_CENTS, + currency: 'usd', + effective_balance_micros: API_KEY_BALANCE_CENTS + } satisfies BillingBalanceResponse) + ) + ) + await page.route('**/api/billing/plans', (route) => + route.fulfill(jsonRoute({ plans: [] } satisfies BillingPlansResponse)) + ) + await page.route('**/api/billing/events**', (route) => + route.fulfill( + jsonRoute({ + 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) => { + if (localStorage.getItem('Comfy.userId') !== id) { + localStorage.clear() + sessionStorage.clear() + localStorage.setItem('Comfy.userId', id) + localStorage.setItem('comfy_api_key', 'comfyui-e2e-api-key') + } + }, userId) + + 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/platform/workspace/api/workspaceApi.ts b/src/platform/workspace/api/workspaceApi.ts index 79b7227495f..44d725cec07 100644 --- a/src/platform/workspace/api/workspaceApi.ts +++ b/src/platform/workspace/api/workspaceApi.ts @@ -13,6 +13,7 @@ import type { CreateTopupRequest, CreateTopupResponse, CreateWorkspaceRequest, + CurrentWorkspaceResponse, ListInvitesResponse, ListMembersResponse, ListWorkspacesResponse, @@ -74,6 +75,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 } @@ -187,6 +189,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 df7c37044c8..6e8ac22b21e 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 mockWorkspaceStoreInitState = vi.hoisted(() => ({ value: 'uninitialized' as string })) @@ -87,7 +88,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) }) })) @@ -103,6 +115,7 @@ describe('WorkspaceAuthGate', () => { mockIsCloud.value = true mockIsInitialized.value = false mockCurrentUser.value = null + mockApiKeyAuthenticated.value = false mockUnifiedCloudAuthEnabled.value = false mockRemoteConfigState.value = 'authenticated' mockRemoteConfigErrorStatus.value = null @@ -112,6 +125,9 @@ describe('WorkspaceAuthGate', () => { mockWorkspaceStoreInitialize.mockImplementation(async () => { mockWorkspaceStoreInitState.value = 'ready' }) + mockWorkspaceStoreReset.mockImplementation(() => { + mockWorkspaceStoreInitState.value = 'uninitialized' + }) mockMintAtLogin.mockResolvedValue(true) mockGetUnifiedToken.mockReturnValue('cloud-jwt') }) @@ -202,6 +218,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 1d8fdca44a9..517167390c0 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, @@ -79,6 +80,7 @@ import { refreshRemoteConfig } from '@/platform/remoteConfig/refreshRemoteConfig import { reportError } from '@/platform/telemetry/reportError' import { useWorkspaceAuthStore } from '@/platform/workspace/stores/workspaceAuthStore' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' +import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore' import { useAuthStore } from '@/stores/authStore' const FIREBASE_INIT_TIMEOUT_MS = 16_000 @@ -232,16 +234,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) { @@ -251,8 +266,9 @@ function initializeWorkspacesInBackground(): Promise { }) } if ( + sessionId === null || generation !== initializationGeneration || - currentUser.value?.uid !== userId + localSessionIdentity() !== sessionId ) { return } @@ -284,9 +300,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..ea67def48a3 100644 --- a/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue +++ b/src/platform/workspace/components/CurrentUserPopoverWorkspace.vue @@ -26,7 +26,23 @@
+ +
+ + + {{ workspaceName }} + +
- + + - - - - + From 84690be5a4f51751d2f358089e4568005c956e08 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Tue, 25 Aug 2026 21:42:02 +0000 Subject: [PATCH 3/3] fix(auth): accept the validated API-key credential in the prompt guard Review follow-ups: the execution guard rejected any active workspace without a workspace JWT, which an API-key session can never mint, so every submission failed once workspace bootstrap succeeded. A validated key session now passes the guard while a Firebase session whose token mint failed still fails closed. Replacing a stored key ends the previous user's session before validating the new key, a definitive 4xx on the credential lookup fails immediately instead of retrying, and the E2E workspace-rail mocks 401 any request that does not carry the key. --- browser_tests/fixtures/apiKeyAuthFixture.ts | 103 ++++++++++-------- .../stores/teamWorkspaceStore.test.ts | 33 +++++- .../workspace/stores/teamWorkspaceStore.ts | 19 +++- src/scripts/app.test.ts | 38 ++++++- src/scripts/app.ts | 15 ++- src/stores/apiKeyAuthStore.ts | 6 +- 6 files changed, 154 insertions(+), 60 deletions(-) diff --git a/browser_tests/fixtures/apiKeyAuthFixture.ts b/browser_tests/fixtures/apiKeyAuthFixture.ts index cfbe3a983e7..ca4d4471ae9 100644 --- a/browser_tests/fixtures/apiKeyAuthFixture.ts +++ b/browser_tests/fixtures/apiKeyAuthFixture.ts @@ -1,3 +1,4 @@ +import type { Route } from '@playwright/test' import { test as base } from '@playwright/test' import type { @@ -15,6 +16,19 @@ 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', @@ -83,62 +97,59 @@ export const apiKeyAuthFixture = base.extend<{ }) }) await page.route('**/api/workspaces/current', (route) => - route.fulfill(jsonRoute(API_KEY_WORKSPACE)) + fulfillForApiKey(route, API_KEY_WORKSPACE) ) await page.route('**/api/billing/status', (route) => - route.fulfill( - jsonRoute({ - 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) - ) + 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) => - route.fulfill( - jsonRoute({ - amount_micros: API_KEY_BALANCE_CENTS, - currency: 'usd', - effective_balance_micros: API_KEY_BALANCE_CENTS - } satisfies BillingBalanceResponse) - ) + 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) => - route.fulfill(jsonRoute({ plans: [] } satisfies BillingPlansResponse)) + fulfillForApiKey(route, { plans: [] } satisfies BillingPlansResponse) ) await page.route('**/api/billing/events**', (route) => - route.fulfill( - jsonRoute({ - 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) - ) + 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) => { - if (localStorage.getItem('Comfy.userId') !== id) { - localStorage.clear() - sessionStorage.clear() - localStorage.setItem('Comfy.userId', id) - localStorage.setItem('comfy_api_key', 'comfyui-e2e-api-key') - } - }, userId) + 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) diff --git a/src/platform/workspace/stores/teamWorkspaceStore.test.ts b/src/platform/workspace/stores/teamWorkspaceStore.test.ts index e9124679f71..4ca140cd9cd 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.test.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.test.ts @@ -499,22 +499,43 @@ describe('useTeamWorkspaceStore', () => { expect(store.activeWorkspace?.role).toBe('member') }) - it('errors after retries when the credential resolves no workspace', async () => { + 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() - const initialization = store.initialize() - await vi.advanceTimersByTimeAsync(1000) - await vi.advanceTimersByTimeAsync(2000) - await vi.advanceTimersByTimeAsync(4000) - await expect(initialization).rejects.toThrow('No workspace is bound') + 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', () => { diff --git a/src/platform/workspace/stores/teamWorkspaceStore.ts b/src/platform/workspace/stores/teamWorkspaceStore.ts index 1e05f90fa32..473f20fef83 100644 --- a/src/platform/workspace/stores/teamWorkspaceStore.ts +++ b/src/platform/workspace/stores/teamWorkspaceStore.ts @@ -21,7 +21,7 @@ import type { SubscriptionTier, WorkspaceWithRole } from '../api/workspaceApi' -import { workspaceApi } from '../api/workspaceApi' +import { WorkspaceApiError, workspaceApi } from '../api/workspaceApi' export interface WorkspaceMember { id: string @@ -407,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/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 }