Skip to content
18 changes: 14 additions & 4 deletions browser_tests/tests/agent/agentRunModePopover.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,9 @@ test.describe('Agent run permissions popover', { tag: '@cloud' }, () => {
})
})

// A rejected write keeps the menu open to retry from, but the options go
// aria-disabled mid-write: that retry survives only if focus does.
test('A failed save can be retried from the keyboard', async ({
// Regression coverage for https://github.com/Comfy-Org/ComfyUI_frontend/pull/20177:
// auth diagnostics must leave the rejected write retryable at the UI.
test('An auth-rejected save can be retried from the keyboard', async ({
agentPanel,
comfyPage
}) => {
Expand All @@ -145,7 +145,17 @@ test.describe('Agent run permissions popover', { tag: '@cloud' }, () => {
if (rejectNext) {
rejectNext = false
await held
return route.fulfill({ status: 500, body: 'nope' })
return route.fulfill({
...jsonRoute({
accepted: ['bearer_jwt', 'x_api_key'],
error: {
type: 'auth_type_not_allowed',
message:
'Authentication method not allowed for this endpoint. Accepted: bearer_jwt, x_api_key'
}
}),
status: 403
})
}
return route.fulfill(jsonRoute(saved))
})
Expand Down
41 changes: 41 additions & 0 deletions src/platform/auth/authCredential.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { describe, expect, it, vi } from 'vitest'

import type { AuthHeader } from '@/types/authTypes'

import { authCredentialOf, notifyAuthCredential } from './authCredential'

describe('authCredentialOf', () => {
it.for([
[null, 'none'],
[{ Authorization: 'Bearer t' }, 'bearer'],
[{ 'X-API-KEY': 'k' }, 'api-key'],
[{}, 'none'],
[{ authorization: 'Bearer t' }, 'none']
] as const)('classifies %j as %s', ([header, credential]) => {
expect(authCredentialOf(header as AuthHeader | null)).toBe(credential)
})
})

describe('notifyAuthCredential', () => {
it('delivers the credential kind', () => {
const callback = vi.fn()

notifyAuthCredential(callback, 'bearer')

expect(callback).toHaveBeenCalledExactlyOnceWith('bearer')
})

it('does nothing without a callback', () => {
expect(() => notifyAuthCredential(undefined, 'none')).not.toThrow()
})

it('swallows a throwing callback', () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})

expect(() =>
notifyAuthCredential(() => {
throw new Error('boom')
}, 'none')
).not.toThrow()
})
})
38 changes: 38 additions & 0 deletions src/platform/auth/authCredential.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type {
ApiKeyAuthHeader,
AuthCredential,
AuthHeader,
LoggedInAuthHeader
} from '@/types/authTypes'

const HEADER_CREDENTIAL = {
Authorization: 'bearer',
'X-API-KEY': 'api-key'
} as const satisfies Record<
keyof LoggedInAuthHeader | keyof ApiKeyAuthHeader,
AuthCredential
>

/** The credential kind an auth header carries; `none` when it carries neither. */
export function authCredentialOf(header: AuthHeader | null): AuthCredential {
if (header === null) return 'none'
const headerKey = Object.keys(HEADER_CREDENTIAL).find((key) => key in header)
return headerKey === undefined
? 'none'
: HEADER_CREDENTIAL[headerKey as keyof typeof HEADER_CREDENTIAL]
}

/**
* Delivers a credential kind to a diagnostics callback without letting the
* callback affect the request: telemetry must fail open.
*/
export function notifyAuthCredential(
callback: ((credential: AuthCredential) => void) | undefined,
credential: AuthCredential
): void {
try {
callback?.(credential)
} catch (error) {
console.warn('onAuthCredential callback failed:', error)
}
}
120 changes: 120 additions & 0 deletions src/platform/auth/authRejection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { describe, expect, it } from 'vitest'

import {
MAX_ACCEPTED_METHODS,
MAX_REASON_TEXT_LENGTH,
authRejectionTags,
isAuthRejectionStatus
} from './authRejection'

const NOT_ALLOWED_MESSAGE =
'Authentication method not allowed for this endpoint. Accepted: bearer_jwt, x_api_key'

describe('isAuthRejectionStatus', () => {
it.for([
[401, true],
[403, true],
[400, false],
[404, false],
[500, false]
] as const)('%i -> %s', ([status, expected]) => {
expect(isAuthRejectionStatus(status)).toBe(expected)
})
})

describe('authRejectionTags', () => {
it('describes an auth-type refusal from its structure', () => {
expect(
authRejectionTags(
{
accepted: ['bearer_jwt', 'x_api_key'],
error: { type: 'auth_type_not_allowed', message: NOT_ALLOWED_MESSAGE }
},
NOT_ALLOWED_MESSAGE
)
).toEqual({
backendReason: 'auth_method_not_allowed',
backendErrorType: 'auth_type_not_allowed',
acceptedMethods: 'bearer_jwt,x_api_key'
})
})

it('classifies the plain { error: string } shape from the message', () => {
expect(
authRejectionTags({ error: NOT_ALLOWED_MESSAGE }, NOT_ALLOWED_MESSAGE)
).toEqual({ backendReason: 'auth_method_not_allowed' })
})

it('reads the ingest { code, message } shape, preferring its message', () => {
expect(
authRejectionTags({ code: 'UNAUTHORIZED', message: 'no credential' }, '')
).toEqual({ backendReason: 'other', backendErrorCode: 'UNAUTHORIZED' })
})

it.for([
'user 3f2b8c1e-9a4d-4e57-8b1a-0c6d2f7e5a91 not authorized for workspace 7d1e4b2a-5c3f-4a68-9e0b-1f2a3b4c5d6e',
'invalid key 9f86d081884c7d659a2feaa0c55ad015',
'token eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abc rejected',
'denied for someone@example.com'
])('reports no part of free-form text: %s', (text) => {
const tags = authRejectionTags({ error: text }, text)

expect(tags).toEqual({ backendReason: 'other' })
})

it('never copies an unknown code or method into a tag', () => {
const tags = authRejectionTags(
{
code: 'ws_7d1e4b2a5c3f4a689e0b1f2a3b4c5d6e',
message: 'nope'
},
''
)
const methods = authRejectionTags(
{
accepted: ['bearer_jwt', 'custom-7d1e4b2a', 'x_api_key', 'again'],
error: { type: 'auth_type_not_allowed', message: 'nope' }
},
'nope'
)

expect(tags.backendErrorCode).toBe('other')
expect(methods.acceptedMethods).toBe('bearer_jwt,other,x_api_key')
})

it('reads only the first MAX_ACCEPTED_METHODS accepted methods', () => {
const accepted = [
...Array.from({ length: MAX_ACCEPTED_METHODS }, () => 'unlisted'),
'bearer_jwt'
]

const tags = authRejectionTags(
{ accepted, error: { type: 'auth_type_not_allowed', message: 'x' } },
'x'
)

expect(tags.acceptedMethods).toBe('other')
})

it('reads only a bounded prefix of the message', () => {
const text = `${' '.repeat(MAX_REASON_TEXT_LENGTH)}authentication method not allowed`

expect(authRejectionTags(undefined, text)).toEqual({})
})

it.for([
undefined,
null,
0,
'text',
[],
[1, 2],
{},
{ error: null },
{ error: { type: 5 } },
{ accepted: 'bearer_jwt' },
{ code: 403, message: 7 }
])('is total for the hostile body %j', (body) => {
expect(() => authRejectionTags(body, '')).not.toThrow()
})
})
113 changes: 113 additions & 0 deletions src/platform/auth/authRejection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import type { AuthTypeNotAllowedError } from '@comfyorg/ingest-types'
import {
zAuthTypeNotAllowedError,
zErrorResponse
} from '@comfyorg/ingest-types/zod'

export const AUTH_REJECTION_STATUSES = [401, 403] as const
export type AuthRejectionStatus = (typeof AUTH_REJECTION_STATUSES)[number]

export function isAuthRejectionStatus(
status: number
): status is AuthRejectionStatus {
return AUTH_REJECTION_STATUSES.some((rejection) => rejection === status)
}

const OTHER = 'other'
type Other = typeof OTHER

/**
* Backend values are reported only when they are on these lists, and anything
* else is `other`: the backend text is uncontrolled and can carry user,
* workspace or key identifiers, and an open value space would make the tags
* unbounded in cardinality. The generated ingest types describe these codes in
* prose only, so this is the one place they are listed.
*/
export const KNOWN_AUTH_REFUSAL_CODES = [
'UNAUTHORIZED',
'FORBIDDEN',
'csrf_invalid',
'workspace_access_denied',
'workspace_id_invalid',
'origin_not_allowed',
'cross_site_request'
] as const
export const KNOWN_ACCEPTED_AUTH_METHODS = ['bearer_jwt', 'x_api_key'] as const

/** Message phrases for the plain `{ error: string }` shape, which has no code. */
const REASON_PHRASES = [
{
phrase: 'authentication method not allowed',
reason: 'auth_method_not_allowed'
}
] as const

export const MAX_REASON_TEXT_LENGTH = 500
export const MAX_ACCEPTED_METHODS = 8

type AuthRefusalCode = (typeof KNOWN_AUTH_REFUSAL_CODES)[number] | Other
type AcceptedAuthMethod = (typeof KNOWN_ACCEPTED_AUTH_METHODS)[number] | Other
type AuthRejectionReason = (typeof REASON_PHRASES)[number]['reason'] | Other

interface BackendFields {
reason: AuthRejectionReason
errorType: AuthTypeNotAllowedError['error']['type']
errorCode: AuthRefusalCode
}

/** Tags describing the backend's refusal: `backendReason`, `backendErrorType`, ... */
export type AuthRejectionTags = {
[K in keyof BackendFields as `backend${Capitalize<K>}`]?: BackendFields[K]
} & { acceptedMethods?: string }

function isOneOf<T extends string>(
known: readonly T[],
value: string
): value is T {
return known.some((entry) => entry === value)
}

function reasonOf(text: string): AuthRejectionReason | undefined {
const bounded = text.slice(0, MAX_REASON_TEXT_LENGTH).toLowerCase()
if (bounded.trim().length === 0) return undefined
return (
REASON_PHRASES.find(({ phrase }) => bounded.includes(phrase))?.reason ??
OTHER
)
}

function codeOf(code: string): AuthRefusalCode {
return isOneOf(KNOWN_AUTH_REFUSAL_CODES, code) ? code : OTHER
}

function acceptedMethodsOf(accepted: readonly string[]): string | undefined {
const methods = accepted
.slice(0, MAX_ACCEPTED_METHODS)
.map(
(method): AcceptedAuthMethod =>
isOneOf(KNOWN_ACCEPTED_AUTH_METHODS, method) ? method : OTHER
)
return methods.length > 0 ? [...new Set(methods)].join(',') : undefined
}

/**
* The tags that tell an auth refusal's causes apart, taken from the ingest
* error shapes (`AuthTypeNotAllowedError`, `ErrorResponse`) or, for a body in
* neither, from the already-extracted message. Pure and total: any input
* yields a (possibly empty) tag set, and no value is copied from the response.
*/
export function authRejectionTags(
body: unknown,
message: string
): AuthRejectionTags {
const notAllowed = zAuthTypeNotAllowedError.safeParse(body).data
const refusal = zErrorResponse.safeParse(body).data
const reason = reasonOf(refusal?.message ?? message)
const acceptedMethods = notAllowed && acceptedMethodsOf(notAllowed.accepted)
return {
...(reason && { backendReason: reason }),
...(notAllowed && { backendErrorType: notAllowed.error.type }),
...(refusal && { backendErrorCode: codeOf(refusal.code) }),
...(acceptedMethods && { acceptedMethods })
}
}
Loading
Loading