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
9 changes: 9 additions & 0 deletions src/platform/auth/session/cloudWebSessionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,15 @@ export const useCloudWebSessionStore = defineStore('cloudWebSession', () => {
}
)

// A unified credential from a token-rail fallback would adopt a sibling's
// token and overwrite the workspace this tab's session requests carry.
watch(
() => signedInUser.value?.id,
(userId) => {
if (userId) useWorkspaceAuthStore().clearUnifiedContext()
}
)

const reconnecting = shallowRef(false)
const readsFailing = computed(
() => 'failures' in state.value && state.value.failures > 0
Expand Down
43 changes: 39 additions & 4 deletions src/platform/auth/webSessionFlagOn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,7 @@ function installIngest(features: Record<string, boolean> = {}) {
userId: 'user-a',
csrfToken: 'csrf-1',
sessionDown: false,
sessionMissing: false,
refusals: [] as string[],
mintRefusal: undefined as (() => Response) | undefined,
mintGate: undefined as Promise<void> | undefined,
Expand Down Expand Up @@ -747,19 +748,24 @@ function installIngest(features: Record<string, boolean> = {}) {
)
}

const answerSession = (): Response =>
ingest.sessionDown
const answerSession = (method: string): Response => {
if (ingest.sessionMissing) {
return jsonResponse({ code: 'no_session', message: 'no_session' }, 401)
}
if (method === 'POST') return jsonResponse({ success: true })
return ingest.sessionDown
? jsonResponse({ code: 'unavailable', message: 'down' }, 503)
: jsonResponse({
...sessionBody(ingest.userId, {
hasPersonalWorkspace: ingest.hasPersonalWorkspace
}),
csrf_token: ingest.csrfToken
})
}

const respond = (request: ApiRequest, body: unknown): Response => {
const { path, headers } = request
if (path === '/api/auth/session') return answerSession()
if (path === '/api/auth/session') return answerSession(request.method)
if (path === '/api/auth/token') return mint(body)
if (path === '/api/workspaces/current') {
if (ingest.currentWorkspaceDown) return ingest.currentWorkspaceDown()
Expand Down Expand Up @@ -2115,13 +2121,42 @@ describe('a sibling tab under unified_cloud_auth', () => {
})
const workspaceAuth = useWorkspaceAuthStore()

await expect(workspaceAuth.mintAtLogin()).resolves.toBe(true)
await vi.waitFor(() =>
expect(workspaceAuth.getUnifiedToken()).toBeDefined()
)
publishFromSibling()

expect(firebaseExchanges()).toHaveLength(1)
expect(workspaceAuth.currentWorkspace?.id).toBe('ws-personal')
expect(workspaceAuth.getUnifiedToken()).toBe('sibling-jwt')
})
it('drops the fallback credential once the session signs the tab in, so a sibling token cannot move its Run', async () => {
const ingest = installIngest({ unified_cloud_auth: true })
ingest.sessionMissing = true
await refreshRemoteConfig({ useAuth: false })
useAuthStore()
const workspaceAuth = useWorkspaceAuthStore()
identity.signIn(USER_A)
await useSessionCookie().ensureSessionCookie()
await expect(workspaceAuth.mintAtLogin()).resolves.toBe(true)

ingest.sessionMissing = false
const webSession = useCloudWebSessionStore()
webSession.signedInInteractively(USER_A)
await webSession.whenSessionCreated()
await workspaceAuth.switchWorkspace('ws-team')
publishFromSibling()
await postPrompt()

expect(workspaceAuth.currentWorkspace?.id).toBe('ws-team')
expect(ingest.requests.at(-1)).toEqual(
sessionRequest('POST', '/api/prompt', {
'x-comfy-workspace-id': 'ws-team',
...PROMPT_HEADERS,
'x-csrf-token': 'csrf-1'
})
)
})
})

describe('billing on a tab that arrived by session', () => {
Expand Down
68 changes: 61 additions & 7 deletions src/platform/workspace/auth/WorkspaceAuthGate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,16 @@ describe('WorkspaceAuthGate', () => {
})

describe('cloud builds - Firebase user signed in on the web session', () => {
const signedInScope: WebSessionRequestScope = {
session: {
user: { id: 'user-a', email: 'a@example.com', emailVerified: true },
csrfToken: 'csrf-1',
expiresAt: Date.now() + 60 * 60_000,
absoluteExpiresAt: Date.now() + 24 * 60 * 60_000
},
epoch: 1
}
let sessionScope: WebSessionRequestScope | undefined
let releaseRequests = () => {}

beforeEach(() => {
Expand All @@ -428,22 +438,57 @@ describe('WorkspaceAuthGate', () => {
vi.mocked(useWorkspaceAuthStore().getUnifiedToken).mockReturnValue(
undefined
)
sessionScope = signedInScope
releaseRequests = provideWebSessionRequests(
fromPartial<WebSessionRequests>({
scope: async () => fromPartial<WebSessionRequestScope>({})
})
fromPartial<WebSessionRequests>({ scope: async () => sessionScope })
)
})

afterEach(() => releaseRequests())

it('initializes the workspace without minting a unified token', async () => {
mountComponent()
await flushPromises()

expect(await screen.findByTestId('slot-content')).toBeInTheDocument()
expect(useWorkspaceAuthStore().mintAtLogin).not.toHaveBeenCalled()
expect(useTeamWorkspaceStore().initialize).toHaveBeenCalled()
expect(screen.getByTestId('slot-content')).toBeInTheDocument()
})

it('renders the app when the session signs the tab in while the login mint is refused', async () => {
sessionScope = undefined
vi.mocked(useWorkspaceAuthStore().mintAtLogin).mockImplementation(
async () => {
sessionScope = signedInScope
return false
}
)

mountComponent()

expect(await screen.findByTestId('slot-content')).toBeInTheDocument()
expect(useTeamWorkspaceStore().initialize).toHaveBeenCalled()
})

it('renders the app when the session signs the tab in during workspace setup', async () => {
sessionScope = undefined
vi.mocked(useWorkspaceAuthStore().mintAtLogin).mockResolvedValue(true)
vi.mocked(useWorkspaceAuthStore().getUnifiedToken).mockReturnValue(
'cloud-jwt'
)
vi.mocked(useTeamWorkspaceStore().initialize).mockImplementation(
async () => {
sessionScope = signedInScope
vi.mocked(useWorkspaceAuthStore().getUnifiedToken).mockReturnValue(
undefined
)
Object.assign(useTeamWorkspaceStore(), { initState: 'ready' })
}
)

mountComponent()

expect(await screen.findByTestId('slot-content')).toBeInTheDocument()
expect(useWorkspaceAuthStore().mintAtLogin).toHaveBeenCalledOnce()
})

it('mints nothing when unmounted while the session lookup is pending', async () => {
Expand All @@ -454,12 +499,21 @@ describe('WorkspaceAuthGate', () => {
settleScope = resolve
}
)
let lookupStarted = () => {}
const lookupStarting = new Promise<void>((resolve) => {
lookupStarted = resolve
})
releaseRequests = provideWebSessionRequests(
fromPartial<WebSessionRequests>({ scope: () => pendingScope })
fromPartial<WebSessionRequests>({
scope: () => {
lookupStarted()
return pendingScope
}
})
)

const { unmount } = mountComponent()
await flushPromises()
await lookupStarting
unmount()
settleScope(undefined)
await flushPromises()
Expand Down
10 changes: 8 additions & 2 deletions src/platform/workspace/auth/WorkspaceAuthGate.vue
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,11 @@ async function requiresUnifiedToken(): Promise<boolean> {
)
}

/** A session sign-in mid-setup lifts the need for the token that went missing. */
async function missingUnifiedToken(hasToken: boolean): Promise<boolean> {
return !hasToken && (await requiresUnifiedToken())
}

async function initialize(): Promise<void> {
if (!isCloud) {
void initializeWorkspacesInBackground()
Expand Down Expand Up @@ -198,15 +203,16 @@ async function initialize(): Promise<void> {
if (needsUnifiedToken) {
const authenticated = await workspaceAuthStore.mintAtLogin()
if (generation !== initializationGeneration) return
if (!authenticated) {
if (await missingUnifiedToken(authenticated)) {
throw new Error('Failed to initialize unified cloud auth')
}
}

await initializeWorkspaceMode()
if (generation !== initializationGeneration) return
void billingCapabilities.initialize(controller.signal)
if (needsUnifiedToken && !workspaceAuthStore.getUnifiedToken()) {
const hasUnifiedToken = Boolean(workspaceAuthStore.getUnifiedToken())
if (needsUnifiedToken && (await missingUnifiedToken(hasUnifiedToken))) {
throw new Error('Unified cloud auth was cleared during workspace setup')
}

Expand Down
52 changes: 51 additions & 1 deletion src/platform/workspace/stores/useWorkspaceAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,14 @@ import type { User } from 'firebase/auth'

import { storeToRefs } from 'pinia'
import { nextTick } from 'vue'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'

import { firebaseIdentity } from '@/platform/auth/firebaseIdentity'
import type {
WebSessionRequestScope,
WebSessionRequests
} from '@/platform/auth/session/webSessionFetch'
import { provideWebSessionRequests } from '@/platform/auth/session/webSessionFetch'
import { useFeatureFlags } from '@/composables/useFeatureFlags'
import { t } from '@/i18n'
import { useTelemetry } from '@/platform/telemetry'
Expand Down Expand Up @@ -3186,6 +3191,51 @@ describe('useWorkspaceAuthStore', () => {
expect(unifiedToken.value).toBeNull()
})

it('refuses a mint that parked on the identity before the session signed the tab in', async () => {
const mockFetch = vi.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve(personalTokenResponse)
})
vi.stubGlobal('fetch', mockFetch)
vi.mocked(useAuthStore().getIdToken).mockResolvedValue(
'firebase-token-xyz'
)
const heldPort = replayIdentityPort(() => null)
vi.spyOn(firebaseIdentity, 'onUserChanged').mockImplementation(
heldPort.register
)
const signedInScope: WebSessionRequestScope = {
session: {
user: { id: 'user-1', email: 'a@example.com', emailVerified: true },
csrfToken: 'csrf-1',
expiresAt: Date.now() + 60 * 60_000,
absoluteExpiresAt: Date.now() + 24 * 60 * 60_000
},
epoch: 1
}
let signedIn = false
onTestFinished(
provideWebSessionRequests(
fromPartial<WebSessionRequests>({
scope: async () => (signedIn ? signedInScope : undefined)
})
)
)

const store = useWorkspaceAuthStore()
const { unifiedToken } = storeToRefs(store)
Object.assign(useAuthStore(), { currentUser: { uid: 'user-1' } })
const parked = store.mintAtLogin()

signedIn = true
await nextTick()
heldPort.emit(portUser({ uid: 'user-1' }))

await expect(parked).resolves.toBe(false)
expect(mockFetch).not.toHaveBeenCalled()
expect(unifiedToken.value).toBeNull()
})

it('is fully dormant under the flag OFF: no unified network, timer, or rotation', async () => {
vi.mocked(useFeatureFlags().flags).unifiedCloudAuthEnabled = false
vi.mocked(useAuthStore().getIdToken).mockResolvedValue(
Expand Down
9 changes: 7 additions & 2 deletions src/platform/workspace/stores/workspaceAuthStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -583,9 +583,13 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => {
return false
}
const authUser = await unifiedUser()
// Re-check after the wait: a rollback that flips the flag off while a mint
// Re-check after the wait: a rollback or a session sign-in while a mint
// is parked on unifiedUser() must not let the resumed mint commit a token.
if (!unifiedRailEnabled() || !authUser) {
if (
!unifiedRailEnabled() ||
!authUser ||
(webSessionRequests() !== undefined && (await signedInOnWebSession()))
) {
return false
}
const target = currentUnifiedTarget() ?? personalWorkspaceTarget()
Expand Down Expand Up @@ -726,6 +730,7 @@ export const useWorkspaceAuthStore = defineStore('workspaceAuth', () => {
getUnifiedSessionClient,
getUnifiedMintWorkspaceId,
clearWorkspaceContext,
clearUnifiedContext,
dropDeniedWorkspace
}
})
Loading