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
55 changes: 45 additions & 10 deletions apps/billing-web/src/session/unifiedBillingSession.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof fetch>(async (input, init = {}) => {
const url = new URL(String(input))
sent.push({
Expand All @@ -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({}))
Expand Down Expand Up @@ -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({
Expand Down
36 changes: 28 additions & 8 deletions apps/billing-web/src/session/unifiedBillingSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { createWebSessionIdentity } from '@comfyorg/account-core/webSessionIdent

import type {
SessionEstablishment,
SessionRefusal,
SignInPort
} from '@/auth/useSignInController'
import type { BillingWebSessionPhase } from '@/router'
Expand Down Expand Up @@ -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<User | null> {
Expand Down Expand Up @@ -124,6 +137,8 @@ export function createUnifiedBillingSession(deps: UnifiedBillingSessionDeps) {

const state = shallowRef<WebSessionIdentityState>(identity.getState())
const workspace = shallowRef<WorkspaceResolution>()
/** Why the last attempt to create a session was refused, until one holds. */
const creationFailure = shallowRef<SessionRefusal>()
let resolvedBinding: string | undefined
let resolving: Promise<WorkspaceResolution> | undefined

Expand Down Expand Up @@ -178,7 +193,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 {
Expand Down Expand Up @@ -224,8 +242,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
Expand Down Expand Up @@ -268,7 +288,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,
Expand Down
2 changes: 2 additions & 0 deletions packages/account-core/src/core/sessionContracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down
20 changes: 20 additions & 0 deletions packages/account-core/src/core/webSession.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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') },
{
Expand Down
12 changes: 10 additions & 2 deletions packages/account-core/src/core/webSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down
Loading