diff --git a/apps/billing-web/src/session/unifiedBillingSession.test.ts b/apps/billing-web/src/session/unifiedBillingSession.test.ts index ed2c32cf30f..40b66b64bd8 100644 --- a/apps/billing-web/src/session/unifiedBillingSession.test.ts +++ b/apps/billing-web/src/session/unifiedBillingSession.test.ts @@ -99,11 +99,23 @@ function setup({ remembered = null as User | null, workspace = workspaceRoute(TEAM), workspaceId = undefined as string | undefined, - creationOutages = 0 + creationOutages = 0, + creationRefusal = undefined as object | undefined } = {}) { const endpoint = createFakeWebSessionEndpoint({ state }) const outage = { remaining: creationOutages } const sent: SentRequest[] = [] + function refuseCreation(): Response | undefined { + if (outage.remaining > 0) { + outage.remaining -= 1 + return new Response(JSON.stringify({ code: 'unavailable' }), { + status: 503 + }) + } + return creationRefusal + ? new Response(JSON.stringify(creationRefusal), { status: 403 }) + : undefined + } const fetchImpl = vi.fn(async (input, init = {}) => { const url = new URL(String(input)) sent.push({ @@ -115,15 +127,9 @@ function setup({ ) }) if (url.pathname === '/api/workspaces/current') return workspace() - if ( - init.method === 'POST' && - url.pathname === '/api/auth/session' && - outage.remaining > 0 - ) { - outage.remaining -= 1 - return new Response(JSON.stringify({ code: 'unavailable' }), { - status: 503 - }) + if (init.method === 'POST' && url.pathname === '/api/auth/session') { + const refused = refuseCreation() + if (refused) return refused } if (url.pathname.startsWith('/api/billing/')) { return new Response(JSON.stringify({})) @@ -398,6 +404,35 @@ describe('billing-web on the shared web session', () => { } ) + it.for([ + { + name: 'naming its organization', + body: { organization_id: 'org_acme' }, + failure: { code: 'SSO_REQUIRED', organizationId: 'org_acme' } + }, + { + name: 'without an organization', + body: {}, + failure: { code: 'SSO_REQUIRED' } + } + ])( + 'an account its SSO organization holds is refused as SSO_REQUIRED, $name', + async ({ body, failure }) => { + const { session } = setup({ + state: { kind: 'dead', code: 'no_session' }, + creationRefusal: { code: 'sso_required', message: 'use SSO', ...body } + }) + await expect(session.settledPhase()).resolves.toBe('signed-out') + await session.signInPort.loadIdentity() + + await expect( + session.signInPort.establish(firebaseUser('user-1')) + ).resolves.toEqual({ status: 'error', code: 'SSO_REQUIRED' }) + + expect(session.signInPort.failure.value).toEqual(failure) + } + ) + describe('when creating the shared session is unavailable', () => { it('Try again creates it for the Firebase user who just signed in', async () => { const { session, firebase, paths } = setup({ diff --git a/apps/billing-web/src/session/unifiedBillingSession.ts b/apps/billing-web/src/session/unifiedBillingSession.ts index 4899f683191..b09ec2e3d92 100644 --- a/apps/billing-web/src/session/unifiedBillingSession.ts +++ b/apps/billing-web/src/session/unifiedBillingSession.ts @@ -35,6 +35,7 @@ import { createWebSessionIdentity } from '@comfyorg/account-core/webSessionIdent import type { SessionEstablishment, + SessionRefusal, SignInPort } from '@/auth/useSignInController' import type { BillingWebSessionPhase } from '@/router' @@ -72,11 +73,23 @@ function establishmentOf( : { status: 'error', code: resolution.code } } -/** A refused credential is its own code; every other failure to create the session is one bucket, as in the token exchange. */ -function creationFailureCode(failure: WebSessionFailure): SessionErrorCode { - return failure.httpStatus === 401 - ? 'INVALID_FIREBASE_TOKEN' - : 'TOKEN_EXCHANGE_FAILED' +/** + * A refused credential and an account its SSO organization holds are their own + * codes; every other failure to create the session is one bucket, as in the + * token exchange. + */ +function creationRefusal(failure: WebSessionFailure): SessionRefusal { + if (failure.code === 'SSO_REQUIRED') { + return failure.organizationId === undefined + ? { code: 'SSO_REQUIRED' } + : { code: 'SSO_REQUIRED', organizationId: failure.organizationId } + } + return { + code: + failure.httpStatus === 401 + ? 'INVALID_FIREBASE_TOKEN' + : 'TOKEN_EXCHANGE_FAILED' + } } function restoredUser(identity: FirebaseIdentity): Promise { @@ -124,6 +137,8 @@ export function createUnifiedBillingSession(deps: UnifiedBillingSessionDeps) { const state = shallowRef(identity.getState()) const workspace = shallowRef() + /** Why the last attempt to create a session was refused, until one holds. */ + const creationFailure = shallowRef() let resolvedBinding: string | undefined let resolving: Promise | undefined @@ -192,7 +207,10 @@ export function createUnifiedBillingSession(deps: UnifiedBillingSessionDeps) { identity.subscribe((next) => { state.value = next workspace.value = undefined - if (next.phase === 'signed_in') void resolveWorkspace() + if (next.phase === 'signed_in') { + creationFailure.value = undefined + void resolveWorkspace() + } }) function settledOf(): BillingWebSessionPhase | undefined { @@ -238,8 +256,10 @@ export function createUnifiedBillingSession(deps: UnifiedBillingSessionDeps) { if (creator === undefined) return establishmentOf(await resolveWorkspace()) const created = await createWebSession(session, () => creator.getIdToken()) if (created.status !== 'ok') { - return { status: 'error', code: creationFailureCode(created) } + creationFailure.value = creationRefusal(created) + return { status: 'error', code: creationFailure.value.code } } + creationFailure.value = undefined identity.dispose() if ((await settledPhase()) === 'authenticated') return { status: 'ok' } const resolved = workspace.value @@ -282,7 +302,7 @@ export function createUnifiedBillingSession(deps: UnifiedBillingSessionDeps) { failure: computed(() => workspace.value?.status === 'error' ? { code: workspace.value.code } - : undefined + : creationFailure.value ), loadIdentity: async () => (await settledPhase()) === 'signed-out' ? deps.loadFirebase() : undefined, diff --git a/packages/account-core/src/core/sessionContracts.ts b/packages/account-core/src/core/sessionContracts.ts index a8ccd629cbf..f593c6e8875 100644 --- a/packages/account-core/src/core/sessionContracts.ts +++ b/packages/account-core/src/core/sessionContracts.ts @@ -196,6 +196,8 @@ export interface WebSessionFailure { readonly httpStatus?: number /** The server's `ErrorResponse.code`, when the body carried one. */ readonly serverCode?: string + /** The organization an `SSO_REQUIRED` refusal names. */ + readonly organizationId?: string } export type WebSessionResult = diff --git a/packages/account-core/src/core/webSession.test.ts b/packages/account-core/src/core/webSession.test.ts index 06686a9b260..bbe0f376a56 100644 --- a/packages/account-core/src/core/webSession.test.ts +++ b/packages/account-core/src/core/webSession.test.ts @@ -148,6 +148,26 @@ describe('web session status mapping', () => { } ) + it('keeps the organization an sso_required refusal names', async () => { + const result = await readWebSession( + optionsFor( + respondWith( + 403, + JSON.stringify({ + code: 'sso_required', + message: 'use SSO', + organization_id: 'org_acme' + }) + ) + ) + ) + + expect(result).toMatchObject({ + code: 'SSO_REQUIRED', + organizationId: 'org_acme' + }) + }) + it.for([ { name: '429 edge rate limit', status: 429, body: errorBody('no_session') }, { diff --git a/packages/account-core/src/core/webSession.ts b/packages/account-core/src/core/webSession.ts index 7918a128545..4eb699d67d3 100644 --- a/packages/account-core/src/core/webSession.ts +++ b/packages/account-core/src/core/webSession.ts @@ -15,7 +15,10 @@ import { z } from 'zod' import { COMFY_CLIENT } from './requestAuth.js' import { timedSignal } from './requestTimeout.js' -import { SSO_REQUIRED_SERVER_CODE } from './ssoRequired.js' +import { + SSO_REQUIRED_SERVER_CODE, + ssoRequiredOrganizationId +} from './ssoRequired.js' import type { WebSessionCommandResult, WebSessionErrorCode, @@ -100,7 +103,12 @@ export function classifyWebSessionFailure( : status === 403 ? (FORBIDDEN_CODES[serverCode] ?? 'SESSION_REQUEST_REFUSED') : 'SESSION_REQUEST_REFUSED' - return failure(byServerCode, status, serverCode) + const refusal = failure(byServerCode, status, serverCode) + const organizationId = + byServerCode === 'SSO_REQUIRED' + ? ssoRequiredOrganizationId(body) + : undefined + return organizationId === undefined ? refusal : { ...refusal, organizationId } } interface Answered {