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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions browser_tests/fixtures/apiKeyAuthFixture.ts
Original file line number Diff line number Diff line change
@@ -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 = <T>(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) =>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: The core boundary in this regression is that /api/workspaces/current and /api/billing/* receive X-API-KEY, but these route handlers fulfill every request without inspecting its headers. The E2E story would therefore pass if the production client omitted the key or accidentally sent Authorization instead. Could the fixture validate the expected X-API-KEY value on each workspace-rail request so the test proves the credential is wired through the actual request path?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 84690be. The workspace-rail mocks now authenticate like the real API: every /api/workspaces/current and /api/billing/* handler returns 401 unless the request carries the stored key as X-API-KEY (fulfillForApiKey), so the story fails if the client omits the key or sends a different header. Verified the spec still passes against a live backend with the validation in place.

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)
}
})
57 changes: 57 additions & 0 deletions browser_tests/tests/workspace/apiKeyLoginBilling.spec.ts
Original file line number Diff line number Diff line change
@@ -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([])
})
})
55 changes: 55 additions & 0 deletions src/composables/auth/useCurrentUser.test.ts
Original file line number Diff line number Diff line change
@@ -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' })
})
})
7 changes: 6 additions & 1 deletion src/composables/auth/useCurrentUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
19 changes: 19 additions & 0 deletions src/platform/workspace/api/workspaceApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type {
CreateTopupRequest,
CreateTopupResponse,
CreateWorkspaceRequest,
CurrentWorkspaceResponse,
ListInvitesResponse,
ListMembersResponse,
ListWorkspacesResponse,
Expand Down Expand Up @@ -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 }
Expand Down Expand Up @@ -191,6 +193,23 @@ export const workspaceApi = {
}
},

/**
* Get the workspace bound to the current credential
* GET /api/workspaces/current
*/
async getCurrentWorkspace(): Promise<CurrentWorkspaceResponse> {
const headers = await getAuthHeaderOrThrow()
try {
const response = await workspaceApiClient.get<CurrentWorkspaceResponse>(
workspaceApiUrl('/workspaces/current'),
{ headers }
)
return response.data
} catch (err) {
handleAxiosError(err)
}
},

/**
* Create a new workspace
* POST /api/workspaces
Expand Down
Loading
Loading