From 84c78bdccf28417d90d6df3427e31f8b8ecf6565 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 5 Oct 2026 09:25:40 +0000 Subject: [PATCH 1/3] fix(agent): report backend detail and credential kind on auth rejection Keep the stable Sentry message for agent 401/403 rejections but add the credential kind sent (session cookie, bearer, api key, none), the backend error type/code, the accepted auth methods and a bounded, scrubbed copy of the backend text, so the next event shows whether the request was cookie-only, had no token, or carried the wrong credential. --- src/scripts/api.fetchApi.test.ts | 42 +++++ src/scripts/api.ts | 20 ++- .../services/agent/agentRestClient.test.ts | 146 ++++++++++++++++-- .../agent/services/agent/agentRestClient.ts | 90 ++++++++++- 4 files changed, 280 insertions(+), 18 deletions(-) diff --git a/src/scripts/api.fetchApi.test.ts b/src/scripts/api.fetchApi.test.ts index bc7138b892e..2c1783b7369 100644 --- a/src/scripts/api.fetchApi.test.ts +++ b/src/scripts/api.fetchApi.test.ts @@ -274,6 +274,48 @@ describe('api.fetchApi', () => { expect(onAuthScheme).toHaveBeenCalledExactlyOnceWith('none') }) + it('reports the credential kind each auth path sent', async () => { + vi.mocked(global.fetch).mockResolvedValue(new Response()) + const offCloud = vi.fn() + await api.fetchApi('/test', { onAuthCredential: offCloud }) + + signInOnCloud() + const getAuthHeader = vi.mocked(useAuthStore().getAuthHeader) + const bearer = vi.fn() + getAuthHeader.mockResolvedValueOnce({ Authorization: 'Bearer tokenA' }) + await api.fetchApi('/test', { onAuthCredential: bearer }) + const apiKey = vi.fn() + getAuthHeader.mockResolvedValueOnce({ 'X-API-KEY': 'key' }) + await api.fetchApi('/test', { onAuthCredential: apiKey }) + const missing = vi.fn() + getAuthHeader.mockResolvedValueOnce(null) + await api.fetchApi('/test', { onAuthCredential: missing }) + const session = vi.fn() + const release = provideWebSessionRequests( + fromPartial({ + scope: async () => ({ session: fromPartial({}), epoch: 1 }), + send: vi.fn().mockResolvedValue(new Response()) + }) + ) + try { + await api.fetchApi('/test', { onAuthCredential: session }) + } finally { + release() + } + + expect( + [offCloud, bearer, apiKey, missing, session].map( + (callback) => callback.mock.calls + ) + ).toEqual([ + [['none']], + [['bearer']], + [['api-key']], + [['none']], + [['session-cookie']] + ]) + }) + it('is not forwarded to fetch as a request option', async () => { vi.mocked(global.fetch).mockResolvedValue(new Response()) diff --git a/src/scripts/api.ts b/src/scripts/api.ts index ff6def8a6ae..0691cb68459 100644 --- a/src/scripts/api.ts +++ b/src/scripts/api.ts @@ -156,11 +156,16 @@ const FETCH_RESPONSE_HEADERS_TIMEOUT_MS = 60_000 */ export type AuthScheme = 'web-session' | 'cloud-auth-header' | 'none' +/** What credential a request carried, for telemetry; never the credential itself. */ +export type AuthCredential = 'session-cookie' | 'bearer' | 'api-key' | 'none' + interface FetchApiOptions extends RequestInit { timeoutMs?: number | null onAuthHeader?: (attached: boolean) => void /** Reports which auth path was taken, independent of onAuthHeader's attached/not boolean. */ onAuthScheme?: (scheme: AuthScheme) => void + /** Reports the kind of credential sent, to tell a missing token from a wrong one. */ + onAuthCredential?: (credential: AuthCredential) => void } const FETCH_ROUTE_GROUPS = new Set([ @@ -609,7 +614,11 @@ export class ComfyApi extends EventTarget { private async addCloudAuthHeader( headers: HeadersInit, onAuthHeader: FetchApiOptions['onAuthHeader'] - ): Promise<{ scheme: AuthScheme; unifiedRetryOn401: boolean }> { + ): Promise<{ + scheme: AuthScheme + credential: AuthCredential + unifiedRetryOn401: boolean + }> { // Get Firebase JWT token if user is logged in const getAuthHeaderIfAvailable = async (): Promise => { try { @@ -623,13 +632,16 @@ export class ComfyApi extends EventTarget { const authHeader = await getAuthHeaderIfAvailable() onAuthHeader?.(authHeader !== null) - if (!authHeader) return { scheme: 'none', unifiedRetryOn401: false } + if (!authHeader) { + return { scheme: 'none', credential: 'none', unifiedRetryOn401: false } + } for (const [key, value] of Object.entries(authHeader)) { addHeaderEntry(headers, key, value) } return { scheme: 'cloud-auth-header', + credential: 'Authorization' in authHeader ? 'bearer' : 'api-key', unifiedRetryOn401: await shouldRemintCloudRequest() } } @@ -662,6 +674,7 @@ export class ComfyApi extends EventTarget { timeoutMs = FETCH_RESPONSE_HEADERS_TIMEOUT_MS, onAuthHeader, onAuthScheme, + onAuthCredential, ...requestOptions } = options ?? {} const headers: HeadersInit = requestOptions.headers ?? {} @@ -674,14 +687,17 @@ export class ComfyApi extends EventTarget { if (sendOnWebSession) { onAuthHeader?.(true) onAuthScheme?.('web-session') + onAuthCredential?.('session-cookie') } else { const cloudAuth = await this.addCloudAuthHeader(headers, onAuthHeader) unifiedRetryOn401 = cloudAuth.unifiedRetryOn401 onAuthScheme?.(cloudAuth.scheme) + onAuthCredential?.(cloudAuth.credential) } } else { onAuthHeader?.(false) onAuthScheme?.('none') + onAuthCredential?.('none') } addHeaderEntry(headers, 'Comfy-User', this.user) diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts index 3480c09af2e..cb421023a67 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts @@ -4,7 +4,7 @@ import { markErrorReported, reportError } from '@/platform/telemetry/reportError' -import type { AuthScheme } from '@/scripts/api' +import type { AuthCredential, AuthScheme } from '@/scripts/api' import { api } from '@/scripts/api' import type { CloudWorkflowEntry } from '../../schemas/agentApiSchema' @@ -34,13 +34,24 @@ function respond(response: Response) { vi.mocked(api.fetchApi).mockResolvedValueOnce(response) } -function respondWithAuthScheme(response: Response, scheme: AuthScheme) { +function respondWithAuthScheme( + response: Response, + scheme: AuthScheme, + credential?: AuthCredential +) { vi.mocked(api.fetchApi).mockImplementationOnce(async (_route, init) => { init?.onAuthScheme?.(scheme) + if (credential) init?.onAuthCredential?.(credential) return response }) } +/** The `extra` context of the most recent `reportError` call. */ +function reportedContext(): Record | undefined { + expect(reportError).toHaveBeenCalledOnce() + return vi.mocked(reportError).mock.calls.at(-1)?.[1].context +} + function lastCall(): { route: string; init: RequestInit } { const [route, init] = vi.mocked(api.fetchApi).mock.calls.at(-1)! return { route, init: init ?? {} } @@ -611,7 +622,11 @@ describe('error mapping', () => { tags: { operation: 'get_thread_messages', status: 401, - authScheme: 'web-session' + authScheme: 'web-session', + credential: 'unreported' + }, + context: { + backendMessage: 'Authentication method not allowed for this endpoint' }, level: 'warning' }) @@ -630,7 +645,8 @@ describe('error mapping', () => { expect(reportedTags()).toEqual({ operation: 'get_thread_messages', status: 403, - authScheme: 'cloud-auth-header' + authScheme: 'cloud-auth-header', + credential: 'unreported' }) }) @@ -644,7 +660,8 @@ describe('error mapping', () => { expect(reportedTags()).toEqual({ operation: 'get_thread_messages', status: 401, - authScheme: 'none' + authScheme: 'none', + credential: 'unreported' }) }) @@ -658,7 +675,115 @@ describe('error mapping', () => { expect(reportedTags()).toEqual({ operation: 'get_thread_messages', status: 401, - authScheme: 'unreported' + authScheme: 'unreported', + credential: 'unreported' + }) + }) + + it('reports the credential kind and the backend refusal details on an auth-type rejection', async () => { + respondWithAuthScheme( + jsonResponse(403, { + 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' + } + }), + 'web-session', + 'session-cookie' + ) + + const error = await makeClient() + .getRunMode() + .catch((e: unknown) => e) + + expect(reportError).toHaveBeenCalledExactlyOnceWith(expect.any(Error), { + surface: 'agent', + errorType: 'agent_api_auth_rejected', + tags: { + operation: 'get_run_mode', + status: 403, + authScheme: 'web-session', + credential: 'session-cookie', + backendErrorType: 'auth_type_not_allowed', + acceptedMethods: 'bearer_jwt,x_api_key' + }, + context: { + backendMessage: + 'Authentication method not allowed for this endpoint. Accepted: bearer_jwt, x_api_key' + }, + level: 'warning' + }) + expect(reportedError().message).toBe( + 'Agent API request rejected by authentication' + ) + expect(error).toBeInstanceOf(AgentApiError) + }) + + it.for([ + ['session-cookie', 'web-session'], + ['bearer', 'cloud-auth-header'], + ['api-key', 'cloud-auth-header'], + ['none', 'none'] + ] as const)( + 'tags the %s credential so cookie-only, missing and wrong tokens stay distinguishable', + async ([credential, scheme]) => { + respondWithAuthScheme( + jsonResponse(401, { code: 'UNAUTHORIZED', message: 'no credential' }), + scheme, + credential + ) + + await makeClient() + .getRunMode() + .catch((e: unknown) => e) + + expect(reportedTags()).toMatchObject({ + authScheme: scheme, + credential, + backendErrorCode: 'UNAUTHORIZED' + }) + } + ) + + it('bounds and scrubs the backend text before reporting it', async () => { + const token = `eyJ${'a'.repeat(60)}.${'b'.repeat(60)}.${'c'.repeat(60)}` + respondWithAuthScheme( + jsonResponse(401, { + error: `denied for someone@example.com with ${token} ${'x '.repeat(300)}` + }), + 'cloud-auth-header', + 'bearer' + ) + + await makeClient() + .getRunMode() + .catch((e: unknown) => e) + + const backendMessage = String(reportedContext()?.backendMessage) + expect(backendMessage).not.toContain('example.com') + expect(backendMessage).not.toContain(token) + expect(backendMessage).toContain('[redacted]') + expect(backendMessage.length).toBeLessThanOrEqual(200) + }) + + it('caps the reported accepted-methods list and ignores non-string entries', async () => { + respondWithAuthScheme( + jsonResponse(403, { + accepted: ['a', 1, null, 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], + error: { type: 'auth_type_not_allowed', message: 'nope' } + }), + 'web-session', + 'session-cookie' + ) + + await makeClient() + .getRunMode() + .catch((e: unknown) => e) + + expect(reportedTags()).toMatchObject({ + acceptedMethods: 'a,b,c,d,e,f,g,h' }) }) @@ -675,7 +800,8 @@ describe('error mapping', () => { expect(reportedTags()).toEqual({ operation: 'answer_thread_ask', status: 403, - authScheme: 'cloud-auth-header' + authScheme: 'cloud-auth-header', + credential: 'unreported' }) const serialized = JSON.stringify([ reportedError().message, @@ -699,7 +825,8 @@ describe('error mapping', () => { expect(reportedTags()).toEqual({ operation: 'cancel_thread_message', status: 403, - authScheme: 'cloud-auth-header' + authScheme: 'cloud-auth-header', + credential: 'unreported' }) const serialized = JSON.stringify([ reportedError().message, @@ -740,7 +867,8 @@ describe('error mapping', () => { expect(reportedTags()).toEqual({ operation: 'list_cloud_workflows', status: 401, - authScheme: 'cloud-auth-header' + authScheme: 'cloud-auth-header', + credential: 'unreported' }) }) diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.ts index 9c1668ec81c..f175205e697 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.ts @@ -13,7 +13,7 @@ import { markErrorReported, reportError } from '@/platform/telemetry/reportError' -import type { AuthScheme } from '@/scripts/api' +import type { AuthCredential, AuthScheme } from '@/scripts/api' import { api } from '@/scripts/api' import { @@ -77,17 +77,76 @@ type AgentApiOperation = | 'upload_image' type ReportedAuthScheme = AuthScheme | 'unreported' +type ReportedAuthCredential = AuthCredential | 'unreported' /** * The reported message for an auth rejection, constant by construction. * * The backend's own text is what `AgentApiError` carries to the caller, but it - * is not what gets reported: it is uncontrolled, is not needed to diagnose - * PM-1802, and varies enough to fragment issue grouping across what is one - * failure mode. Status, operation and auth scheme ride as tags instead. + * is not the Sentry message: it is uncontrolled and varies enough to fragment + * issue grouping across what is one failure mode. Status, operation, auth + * scheme and credential kind ride as tags, and the backend's bounded text + * rides as an extra. */ const AUTH_REJECTED_MESSAGE = 'Agent API request rejected by authentication' +const MAX_BACKEND_TEXT_LENGTH = 200 +const MAX_TAG_LENGTH = 64 +const MAX_ACCEPTED_METHODS = 8 + +interface AuthRejectionDetails { + message: string + errorType?: string + errorCode?: string + accepted?: string +} + +function boundedText(value: unknown, maxLength: number): string | undefined { + if (typeof value !== 'string' || value.length === 0) return undefined + return value.slice(0, maxLength) +} + +/** Backend text is untrusted: opaque long runs and emails never reach telemetry. */ +function scrubBackendText(text: string): string { + return text + .replace(/[^\s@]+@[^\s@]+/g, '[email]') + .replace(/[\w+/=.~-]{40,}/g, '[redacted]') + .slice(0, MAX_BACKEND_TEXT_LENGTH) +} + +function asRecord(value: unknown): Record | undefined { + return typeof value === 'object' && value !== null + ? (value as Record) + : undefined +} + +/** + * The bounded fields of an auth rejection that tell its causes apart. Ingest + * answers a credential the route does not take with + * `{ accepted: [...], error: { type: 'auth_type_not_allowed', message } }`, + * and its other auth refusals with `{ code, message }`. + */ +function describeAuthRejection( + body: unknown, + message: string +): AuthRejectionDetails { + const record = asRecord(body) + const error = asRecord(record?.error) + const accepted = Array.isArray(record?.accepted) + ? record.accepted + .filter((entry): entry is string => typeof entry === 'string') + .slice(0, MAX_ACCEPTED_METHODS) + .map((entry) => entry.slice(0, MAX_TAG_LENGTH)) + .join(',') + : undefined + return { + message: scrubBackendText(message), + errorType: boundedText(error?.type, MAX_TAG_LENGTH), + errorCode: boundedText(record?.code ?? error?.code, MAX_TAG_LENGTH), + accepted: accepted || undefined + } +} + export class AgentApiError extends Error { readonly status: number readonly body: unknown @@ -432,7 +491,8 @@ export function createAgentRestClient() { async function toApiError( response: Response, operation: AgentApiOperation, - authScheme: ReportedAuthScheme + authScheme: ReportedAuthScheme, + credential: ReportedAuthCredential ): Promise { const body = parseErrorBody(await response.text()) const message = getErrorMessage(body, response.statusText) @@ -450,10 +510,20 @@ export function createAgentRestClient() { retryAfterSeconds ) if (response.status === 401 || response.status === 403) { + const details = describeAuthRejection(body, message) reportError(new Error(AUTH_REJECTED_MESSAGE), { surface: 'agent', errorType: 'agent_api_auth_rejected', - tags: { operation, status: response.status, authScheme }, + tags: withoutUndefined({ + operation, + status: response.status, + authScheme, + credential, + backendErrorType: details.errorType, + backendErrorCode: details.errorCode, + acceptedMethods: details.accepted + }), + context: { backendMessage: details.message }, level: 'warning' }) // Callers still receive the backend text for the UI, but their generic @@ -471,13 +541,19 @@ export function createAgentRestClient() { schema: z.ZodType ): Promise { let authScheme: ReportedAuthScheme = 'unreported' + let credential: ReportedAuthCredential = 'unreported' const response = await api.fetchApi(route, { ...init, onAuthScheme: (scheme) => { authScheme = scheme + }, + onAuthCredential: (kind) => { + credential = kind } }) - if (!response.ok) throw await toApiError(response, operation, authScheme) + if (!response.ok) { + throw await toApiError(response, operation, authScheme, credential) + } let payload: unknown try { payload = await response.json() From 14be12fd7414f249956fe3933a6d426ecc22f84b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 5 Oct 2026 10:01:59 +0000 Subject: [PATCH 2/3] fix(agent): report only allowlisted backend detail on auth rejection Replace the scrubbed free-text extra with allowlisted tags (reason, error type, error code, accepted methods; anything else is 'other') so no backend text, id or token can reach telemetry and tag cardinality stays bounded. Read the ingest { code, message } shape, fall back to error.code when the top-level code is not a string, and only report an api-key credential when an X-API-KEY header was actually attached. --- src/scripts/api.ts | 8 +- .../services/agent/agentRestClient.test.ts | 124 +++++++++++++----- .../agent/services/agent/agentRestClient.ts | 100 +++++++++----- 3 files changed, 169 insertions(+), 63 deletions(-) diff --git a/src/scripts/api.ts b/src/scripts/api.ts index 0691cb68459..391ec0e2155 100644 --- a/src/scripts/api.ts +++ b/src/scripts/api.ts @@ -635,13 +635,19 @@ export class ComfyApi extends EventTarget { if (!authHeader) { return { scheme: 'none', credential: 'none', unifiedRetryOn401: false } } + const credential: AuthCredential = + 'Authorization' in authHeader + ? 'bearer' + : 'X-API-KEY' in authHeader + ? 'api-key' + : 'none' for (const [key, value] of Object.entries(authHeader)) { addHeaderEntry(headers, key, value) } return { scheme: 'cloud-auth-header', - credential: 'Authorization' in authHeader ? 'bearer' : 'api-key', + credential, unifiedRetryOn401: await shouldRemintCloudRequest() } } diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts index cb421023a67..38080c5dcb8 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts @@ -46,12 +46,6 @@ function respondWithAuthScheme( }) } -/** The `extra` context of the most recent `reportError` call. */ -function reportedContext(): Record | undefined { - expect(reportError).toHaveBeenCalledOnce() - return vi.mocked(reportError).mock.calls.at(-1)?.[1].context -} - function lastCall(): { route: string; init: RequestInit } { const [route, init] = vi.mocked(api.fetchApi).mock.calls.at(-1)! return { route, init: init ?? {} } @@ -623,10 +617,8 @@ describe('error mapping', () => { operation: 'get_thread_messages', status: 401, authScheme: 'web-session', - credential: 'unreported' - }, - context: { - backendMessage: 'Authentication method not allowed for this endpoint' + credential: 'unreported', + backendReason: 'auth_method_not_allowed' }, level: 'warning' }) @@ -646,7 +638,8 @@ describe('error mapping', () => { operation: 'get_thread_messages', status: 403, authScheme: 'cloud-auth-header', - credential: 'unreported' + credential: 'unreported', + backendReason: 'other' }) }) @@ -661,7 +654,8 @@ describe('error mapping', () => { operation: 'get_thread_messages', status: 401, authScheme: 'none', - credential: 'unreported' + credential: 'unreported', + backendReason: 'unauthorized' }) }) @@ -676,7 +670,8 @@ describe('error mapping', () => { operation: 'get_thread_messages', status: 401, authScheme: 'unreported', - credential: 'unreported' + credential: 'unreported', + backendReason: 'unauthorized' }) }) @@ -706,13 +701,10 @@ describe('error mapping', () => { status: 403, authScheme: 'web-session', credential: 'session-cookie', + backendReason: 'auth_method_not_allowed', backendErrorType: 'auth_type_not_allowed', acceptedMethods: 'bearer_jwt,x_api_key' }, - context: { - backendMessage: - 'Authentication method not allowed for this endpoint. Accepted: bearer_jwt, x_api_key' - }, level: 'warning' }) expect(reportedError().message).toBe( @@ -742,17 +734,45 @@ describe('error mapping', () => { expect(reportedTags()).toMatchObject({ authScheme: scheme, credential, + backendReason: 'other', backendErrorCode: 'UNAUTHORIZED' }) } ) - it('bounds and scrubs the backend text before reporting it', async () => { - const token = `eyJ${'a'.repeat(60)}.${'b'.repeat(60)}.${'c'.repeat(60)}` + it('classifies the ingest { code, message } shape from its message field', async () => { respondWithAuthScheme( jsonResponse(401, { - error: `denied for someone@example.com with ${token} ${'x '.repeat(300)}` + code: 'UNAUTHORIZED', + message: 'Authentication method not allowed for this endpoint' }), + 'web-session', + 'session-cookie' + ) + + await makeClient() + .getRunMode() + .catch((e: unknown) => e) + + expect(reportedTags()).toEqual({ + operation: 'get_run_mode', + status: 401, + authScheme: 'web-session', + credential: 'session-cookie', + backendReason: 'auth_method_not_allowed', + 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', + 'x '.repeat(5000) + ])('reports no part of free-form backend text: %s', async (text) => { + respondWithAuthScheme( + jsonResponse(403, { error: text }), 'cloud-auth-header', 'bearer' ) @@ -761,18 +781,39 @@ describe('error mapping', () => { .getRunMode() .catch((e: unknown) => e) - const backendMessage = String(reportedContext()?.backendMessage) - expect(backendMessage).not.toContain('example.com') - expect(backendMessage).not.toContain(token) - expect(backendMessage).toContain('[redacted]') - expect(backendMessage.length).toBeLessThanOrEqual(200) + expect(reportedTags()).toEqual({ + operation: 'get_run_mode', + status: 403, + authScheme: 'cloud-auth-header', + credential: 'bearer', + backendReason: 'other' + }) + expect(vi.mocked(reportError).mock.calls.at(-1)?.[1].context).toBe( + undefined + ) + expect(JSON.stringify(vi.mocked(reportError).mock.calls)).not.toMatch( + /[0-9a-f]{12,}|eyJ|example\.com/ + ) }) - it('caps the reported accepted-methods list and ignores non-string entries', async () => { + it('maps unknown backend codes, types and accepted methods to other and bounds the list', async () => { respondWithAuthScheme( jsonResponse(403, { - accepted: ['a', 1, null, 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], - error: { type: 'auth_type_not_allowed', message: 'nope' } + code: 'ws_7d1e4b2a5c3f4a689e0b1f2a3b4c5d6e', + accepted: [ + 'bearer_jwt', + 1, + null, + 'x_api_key', + 'custom_scheme_a', + 'custom_scheme_b', + 'a', + 'b', + 'c', + 'd', + 'e' + ], + error: { type: 'brand_new_type', message: 'nope' } }), 'web-session', 'session-cookie' @@ -783,10 +824,26 @@ describe('error mapping', () => { .catch((e: unknown) => e) expect(reportedTags()).toMatchObject({ - acceptedMethods: 'a,b,c,d,e,f,g,h' + backendErrorType: 'other', + backendErrorCode: 'other', + acceptedMethods: 'bearer_jwt,x_api_key,other' }) }) + it('falls back to error.code when the top-level code is not a string', async () => { + respondWithAuthScheme( + jsonResponse(403, { code: 403, error: { code: 'csrf_invalid' } }), + 'web-session', + 'session-cookie' + ) + + await makeClient() + .getRunMode() + .catch((e: unknown) => e) + + expect(reportedTags()).toMatchObject({ backendErrorCode: 'csrf_invalid' }) + }) + it('never reports a thread, message or ask id from the failing path (PM-1802)', async () => { const identifiers = ['t-secret', 'm-secret', 'ask-secret'] respondWithAuthScheme( @@ -801,7 +858,8 @@ describe('error mapping', () => { operation: 'answer_thread_ask', status: 403, authScheme: 'cloud-auth-header', - credential: 'unreported' + credential: 'unreported', + backendReason: 'other' }) const serialized = JSON.stringify([ reportedError().message, @@ -826,7 +884,8 @@ describe('error mapping', () => { operation: 'cancel_thread_message', status: 403, authScheme: 'cloud-auth-header', - credential: 'unreported' + credential: 'unreported', + backendReason: 'other' }) const serialized = JSON.stringify([ reportedError().message, @@ -868,7 +927,8 @@ describe('error mapping', () => { operation: 'list_cloud_workflows', status: 401, authScheme: 'cloud-auth-header', - credential: 'unreported' + credential: 'unreported', + backendReason: 'unauthorized' }) }) diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.ts index f175205e697..77f93287e1b 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.ts @@ -85,46 +85,90 @@ type ReportedAuthCredential = AuthCredential | 'unreported' * The backend's own text is what `AgentApiError` carries to the caller, but it * is not the Sentry message: it is uncontrolled and varies enough to fragment * issue grouping across what is one failure mode. Status, operation, auth - * scheme and credential kind ride as tags, and the backend's bounded text - * rides as an extra. + * scheme, credential kind and an allowlisted classification of the backend's + * refusal ride as tags. */ const AUTH_REJECTED_MESSAGE = 'Agent API request rejected by authentication' -const MAX_BACKEND_TEXT_LENGTH = 200 -const MAX_TAG_LENGTH = 64 +const MAX_CLASSIFIED_TEXT_LENGTH = 500 +const OTHER = 'other' + +/** + * Backend values are reported only when they are on these lists; anything else + * is tagged `other`. The backend text is uncontrolled and can carry user, + * workspace or key identifiers, and an open value space would also make the + * tags unbounded in cardinality. + */ +const KNOWN_AUTH_ERROR_TYPES: ReadonlySet = new Set([ + 'auth_type_not_allowed' +]) +const KNOWN_AUTH_ERROR_CODES: ReadonlySet = new Set([ + 'UNAUTHORIZED', + 'FORBIDDEN', + 'csrf_invalid', + 'workspace_access_denied', + 'workspace_id_invalid', + 'origin_not_allowed', + 'cross_site_request' +]) +const KNOWN_ACCEPTED_METHODS: ReadonlySet = new Set([ + 'bearer_jwt', + 'x_api_key', + 'session_cookie', + 'cookie' +]) const MAX_ACCEPTED_METHODS = 8 +/** Fixed phrases a backend refusal is classified into; the text itself is dropped. */ +const KNOWN_REASONS: readonly (readonly [phrase: string, reason: string])[] = [ + ['authentication method not allowed', 'auth_method_not_allowed'], + ['unauthorized', 'unauthorized'] +] + interface AuthRejectionDetails { - message: string + reason?: string errorType?: string errorCode?: string accepted?: string } -function boundedText(value: unknown, maxLength: number): string | undefined { +function asRecord(value: unknown): Record | undefined { + return typeof value === 'object' && value !== null + ? (value as Record) + : undefined +} + +function allowlisted( + value: unknown, + known: ReadonlySet +): string | undefined { if (typeof value !== 'string' || value.length === 0) return undefined - return value.slice(0, maxLength) + return known.has(value) ? value : OTHER } -/** Backend text is untrusted: opaque long runs and emails never reach telemetry. */ -function scrubBackendText(text: string): string { - return text - .replace(/[^\s@]+@[^\s@]+/g, '[email]') - .replace(/[\w+/=.~-]{40,}/g, '[redacted]') - .slice(0, MAX_BACKEND_TEXT_LENGTH) +function classifyReason(text: string): string | undefined { + const bounded = text.slice(0, MAX_CLASSIFIED_TEXT_LENGTH).toLowerCase() + if (bounded.trim().length === 0) return undefined + return ( + KNOWN_REASONS.find(([phrase]) => bounded.includes(phrase))?.[1] ?? OTHER + ) } -function asRecord(value: unknown): Record | undefined { - return typeof value === 'object' && value !== null - ? (value as Record) - : undefined +function acceptedMethods(value: unknown): string | undefined { + if (!Array.isArray(value)) return undefined + const methods = value + .filter((entry): entry is string => typeof entry === 'string') + .slice(0, MAX_ACCEPTED_METHODS) + .map((entry) => (KNOWN_ACCEPTED_METHODS.has(entry) ? entry : OTHER)) + return methods.length > 0 ? [...new Set(methods)].join(',') : undefined } /** * The bounded fields of an auth rejection that tell its causes apart. Ingest * answers a credential the route does not take with * `{ accepted: [...], error: { type: 'auth_type_not_allowed', message } }`, - * and its other auth refusals with `{ code, message }`. + * and its other auth refusals with `{ code, message }`. Every reported value + * comes from a fixed list, never from the response text. */ function describeAuthRejection( body: unknown, @@ -132,18 +176,14 @@ function describeAuthRejection( ): AuthRejectionDetails { const record = asRecord(body) const error = asRecord(record?.error) - const accepted = Array.isArray(record?.accepted) - ? record.accepted - .filter((entry): entry is string => typeof entry === 'string') - .slice(0, MAX_ACCEPTED_METHODS) - .map((entry) => entry.slice(0, MAX_TAG_LENGTH)) - .join(',') - : undefined + const text = typeof record?.message === 'string' ? record.message : message return { - message: scrubBackendText(message), - errorType: boundedText(error?.type, MAX_TAG_LENGTH), - errorCode: boundedText(record?.code ?? error?.code, MAX_TAG_LENGTH), - accepted: accepted || undefined + reason: classifyReason(text), + errorType: allowlisted(error?.type, KNOWN_AUTH_ERROR_TYPES), + errorCode: + allowlisted(record?.code, KNOWN_AUTH_ERROR_CODES) ?? + allowlisted(error?.code, KNOWN_AUTH_ERROR_CODES), + accepted: acceptedMethods(record?.accepted) } } @@ -519,11 +559,11 @@ export function createAgentRestClient() { status: response.status, authScheme, credential, + backendReason: details.reason, backendErrorType: details.errorType, backendErrorCode: details.errorCode, acceptedMethods: details.accepted }), - context: { backendMessage: details.message }, level: 'warning' }) // Callers still receive the backend text for the UI, but their generic From d6f7f1c9bf0230e2efd1c2f17bae5ead74c60b94 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 5 Oct 2026 20:29:00 +0000 Subject: [PATCH 3/3] refactor(agent): move auth rejection classification to platform/auth and fail open Move AuthScheme/AuthCredential to types/authTypes, derive the credential kind from the shared AuthHeader keys, and parse rejection bodies with the generated ingest schemas in a pure platform/auth/authRejection module so workbench imports downward and scripts/api no longer owns the types. Reporting and the onAuthCredential callback now swallow their own failures so the original error and response path is unchanged. --- src/platform/auth/authCredential.test.ts | 41 +++++ src/platform/auth/authCredential.ts | 38 +++++ src/platform/auth/authRejection.test.ts | 120 +++++++++++++ src/platform/auth/authRejection.ts | 113 ++++++++++++ src/scripts/api.fetchApi.test.ts | 20 +++ src/scripts/api.ts | 34 +--- src/types/authTypes.ts | 16 +- .../services/agent/agentRestClient.test.ts | 70 ++++---- .../agent/services/agent/agentRestClient.ts | 161 ++++++------------ 9 files changed, 444 insertions(+), 169 deletions(-) create mode 100644 src/platform/auth/authCredential.test.ts create mode 100644 src/platform/auth/authCredential.ts create mode 100644 src/platform/auth/authRejection.test.ts create mode 100644 src/platform/auth/authRejection.ts diff --git a/src/platform/auth/authCredential.test.ts b/src/platform/auth/authCredential.test.ts new file mode 100644 index 00000000000..688d861468c --- /dev/null +++ b/src/platform/auth/authCredential.test.ts @@ -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() + }) +}) diff --git a/src/platform/auth/authCredential.ts b/src/platform/auth/authCredential.ts new file mode 100644 index 00000000000..c453855a840 --- /dev/null +++ b/src/platform/auth/authCredential.ts @@ -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) + } +} diff --git a/src/platform/auth/authRejection.test.ts b/src/platform/auth/authRejection.test.ts new file mode 100644 index 00000000000..3e7a0768835 --- /dev/null +++ b/src/platform/auth/authRejection.test.ts @@ -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() + }) +}) diff --git a/src/platform/auth/authRejection.ts b/src/platform/auth/authRejection.ts new file mode 100644 index 00000000000..ed05f36ee5c --- /dev/null +++ b/src/platform/auth/authRejection.ts @@ -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}`]?: BackendFields[K] +} & { acceptedMethods?: string } + +function isOneOf( + 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 }) + } +} diff --git a/src/scripts/api.fetchApi.test.ts b/src/scripts/api.fetchApi.test.ts index 2c1783b7369..7e419b10f08 100644 --- a/src/scripts/api.fetchApi.test.ts +++ b/src/scripts/api.fetchApi.test.ts @@ -274,6 +274,26 @@ describe('api.fetchApi', () => { expect(onAuthScheme).toHaveBeenCalledExactlyOnceWith('none') }) + it('is not broken by a throwing onAuthCredential callback', async () => { + signInOnCloud() + vi.spyOn(console, 'warn').mockImplementation(() => {}) + vi.mocked(useAuthStore().getAuthHeader).mockResolvedValue({ + Authorization: 'Bearer tokenA' + }) + vi.mocked(global.fetch).mockResolvedValue(new Response('ok')) + + const response = await api.fetchApi('/test', { + onAuthCredential: () => { + throw new Error('callback bug') + } + }) + + expect(await response.text()).toBe('ok') + expect(vi.mocked(global.fetch).mock.calls[0][1]?.headers).toMatchObject({ + Authorization: 'Bearer tokenA' + }) + }) + it('reports the credential kind each auth path sent', async () => { vi.mocked(global.fetch).mockResolvedValue(new Response()) const offCloud = vi.fn() diff --git a/src/scripts/api.ts b/src/scripts/api.ts index 391ec0e2155..9946c51b24d 100644 --- a/src/scripts/api.ts +++ b/src/scripts/api.ts @@ -17,6 +17,10 @@ import { trimEnd } from 'es-toolkit' import { ref } from 'vue' import defaultClientFeatureFlags from '@/config/clientFeatureFlags.json' with { type: 'json' } +import { + authCredentialOf, + notifyAuthCredential +} from '@/platform/auth/authCredential' import { scopeMediaRoute } from '@/platform/auth/session/sessionMediaUrl' import { webSessionRequests } from '@/platform/auth/session/webSessionFetch' import { @@ -78,7 +82,7 @@ import type { } from '@/platform/remote/comfyui/jobs/jobTypes' import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' import type { useAuthStore } from '@/stores/authStore' -import type { AuthHeader } from '@/types/authTypes' +import type { AuthCredential, AuthHeader, AuthScheme } from '@/types/authTypes' import type { NodeExecutionId } from '@/types/nodeIdentification' import { fetchHistory, @@ -145,20 +149,6 @@ interface QueuePromptRequestBody { const FETCH_RESPONSE_HEADERS_TIMEOUT_MS = 60_000 -/** - * Which cloud auth path a request actually took, for error diagnostics (PM-1802). - * - * `none` means no auth scheme was used at all, which covers both a non-cloud - * distribution and a cloud request whose auth header was unavailable. Those are - * the same statement about the request - nothing authenticated it - and the - * deploy surface already distinguishes them, so this stays three values rather - * than growing a fourth that only restates `isCloud`. - */ -export type AuthScheme = 'web-session' | 'cloud-auth-header' | 'none' - -/** What credential a request carried, for telemetry; never the credential itself. */ -export type AuthCredential = 'session-cookie' | 'bearer' | 'api-key' | 'none' - interface FetchApiOptions extends RequestInit { timeoutMs?: number | null onAuthHeader?: (attached: boolean) => void @@ -635,19 +625,13 @@ export class ComfyApi extends EventTarget { if (!authHeader) { return { scheme: 'none', credential: 'none', unifiedRetryOn401: false } } - const credential: AuthCredential = - 'Authorization' in authHeader - ? 'bearer' - : 'X-API-KEY' in authHeader - ? 'api-key' - : 'none' for (const [key, value] of Object.entries(authHeader)) { addHeaderEntry(headers, key, value) } return { scheme: 'cloud-auth-header', - credential, + credential: authCredentialOf(authHeader), unifiedRetryOn401: await shouldRemintCloudRequest() } } @@ -693,17 +677,17 @@ export class ComfyApi extends EventTarget { if (sendOnWebSession) { onAuthHeader?.(true) onAuthScheme?.('web-session') - onAuthCredential?.('session-cookie') + notifyAuthCredential(onAuthCredential, 'session-cookie') } else { const cloudAuth = await this.addCloudAuthHeader(headers, onAuthHeader) unifiedRetryOn401 = cloudAuth.unifiedRetryOn401 onAuthScheme?.(cloudAuth.scheme) - onAuthCredential?.(cloudAuth.credential) + notifyAuthCredential(onAuthCredential, cloudAuth.credential) } } else { onAuthHeader?.(false) onAuthScheme?.('none') - onAuthCredential?.('none') + notifyAuthCredential(onAuthCredential, 'none') } addHeaderEntry(headers, 'Comfy-User', this.user) diff --git a/src/types/authTypes.ts b/src/types/authTypes.ts index 549cd01b86a..fab11c90fc6 100644 --- a/src/types/authTypes.ts +++ b/src/types/authTypes.ts @@ -1,4 +1,4 @@ -type LoggedInAuthHeader = { +export type LoggedInAuthHeader = { Authorization: `Bearer ${string}` } @@ -8,6 +8,20 @@ export type ApiKeyAuthHeader = { export type AuthHeader = LoggedInAuthHeader | ApiKeyAuthHeader +/** + * Which cloud auth path a request actually took, for error diagnostics. + * + * `none` means no auth scheme was used at all, which covers both a non-cloud + * distribution and a cloud request whose auth header was unavailable. Those are + * the same statement about the request - nothing authenticated it - and the + * deploy surface already distinguishes them, so this stays three values rather + * than growing a fourth that only restates `isCloud`. + */ +export type AuthScheme = 'web-session' | 'cloud-auth-header' | 'none' + +/** What credential a request carried, for telemetry; never the credential itself. */ +export type AuthCredential = 'session-cookie' | 'bearer' | 'api-key' | 'none' + /** * Identifier for an authenticated user. * diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts index 38080c5dcb8..52bf9824a3b 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts @@ -4,7 +4,8 @@ import { markErrorReported, reportError } from '@/platform/telemetry/reportError' -import type { AuthCredential, AuthScheme } from '@/scripts/api' +import type { AuthCredential, AuthScheme } from '@/types/authTypes' +import * as authRejection from '@/platform/auth/authRejection' import { api } from '@/scripts/api' import type { CloudWorkflowEntry } from '../../schemas/agentApiSchema' @@ -655,7 +656,7 @@ describe('error mapping', () => { status: 401, authScheme: 'none', credential: 'unreported', - backendReason: 'unauthorized' + backendReason: 'other' }) }) @@ -671,7 +672,7 @@ describe('error mapping', () => { status: 401, authScheme: 'unreported', credential: 'unreported', - backendReason: 'unauthorized' + backendReason: 'other' }) }) @@ -796,52 +797,49 @@ describe('error mapping', () => { ) }) - it('maps unknown backend codes, types and accepted methods to other and bounds the list', async () => { + it('still throws the original error unchanged when the reporter throws', async () => { + vi.mocked(reportError).mockImplementationOnce(() => { + throw new Error('sink down') + }) respondWithAuthScheme( - jsonResponse(403, { - code: 'ws_7d1e4b2a5c3f4a689e0b1f2a3b4c5d6e', - accepted: [ - 'bearer_jwt', - 1, - null, - 'x_api_key', - 'custom_scheme_a', - 'custom_scheme_b', - 'a', - 'b', - 'c', - 'd', - 'e' - ], - error: { type: 'brand_new_type', message: 'nope' } - }), - 'web-session', - 'session-cookie' + jsonResponse(403, { error: 'access denied' }), + 'cloud-auth-header', + 'bearer' ) - await makeClient() + const error = await makeClient() .getRunMode() .catch((e: unknown) => e) - expect(reportedTags()).toMatchObject({ - backendErrorType: 'other', - backendErrorCode: 'other', - acceptedMethods: 'bearer_jwt,x_api_key,other' - }) + expect(error).toBeInstanceOf(AgentApiError) + expect(error).toMatchObject({ status: 403, message: 'access denied' }) + expect(markErrorReported).not.toHaveBeenCalled() }) - it('falls back to error.code when the top-level code is not a string', async () => { + it('still reports the base tags when classifying the backend body throws', async () => { + const classify = vi + .spyOn(authRejection, 'authRejectionTags') + .mockImplementationOnce(() => { + throw new Error('classifier bug') + }) respondWithAuthScheme( - jsonResponse(403, { code: 403, error: { code: 'csrf_invalid' } }), - 'web-session', - 'session-cookie' + jsonResponse(403, { error: 'access denied' }), + 'cloud-auth-header', + 'bearer' ) - await makeClient() + const error = await makeClient() .getRunMode() .catch((e: unknown) => e) + classify.mockRestore() - expect(reportedTags()).toMatchObject({ backendErrorCode: 'csrf_invalid' }) + expect(error).toBeInstanceOf(AgentApiError) + expect(reportedTags()).toEqual({ + operation: 'get_run_mode', + status: 403, + authScheme: 'cloud-auth-header', + credential: 'bearer' + }) }) it('never reports a thread, message or ask id from the failing path (PM-1802)', async () => { @@ -928,7 +926,7 @@ describe('error mapping', () => { status: 401, authScheme: 'cloud-auth-header', credential: 'unreported', - backendReason: 'unauthorized' + backendReason: 'other' }) }) diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.ts index 77f93287e1b..f495928b647 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.ts @@ -9,12 +9,20 @@ import { } from '@comfyorg/ingest-types/zod' import type { z } from 'zod' +import type { + AuthRejectionStatus, + AuthRejectionTags +} from '@/platform/auth/authRejection' +import { + authRejectionTags, + isAuthRejectionStatus +} from '@/platform/auth/authRejection' import { markErrorReported, reportError } from '@/platform/telemetry/reportError' -import type { AuthCredential, AuthScheme } from '@/scripts/api' import { api } from '@/scripts/api' +import type { AuthCredential, AuthScheme } from '@/types/authTypes' import { zAgentAnswerAccepted, @@ -90,100 +98,45 @@ type ReportedAuthCredential = AuthCredential | 'unreported' */ const AUTH_REJECTED_MESSAGE = 'Agent API request rejected by authentication' -const MAX_CLASSIFIED_TEXT_LENGTH = 500 -const OTHER = 'other' - -/** - * Backend values are reported only when they are on these lists; anything else - * is tagged `other`. The backend text is uncontrolled and can carry user, - * workspace or key identifiers, and an open value space would also make the - * tags unbounded in cardinality. - */ -const KNOWN_AUTH_ERROR_TYPES: ReadonlySet = new Set([ - 'auth_type_not_allowed' -]) -const KNOWN_AUTH_ERROR_CODES: ReadonlySet = new Set([ - 'UNAUTHORIZED', - 'FORBIDDEN', - 'csrf_invalid', - 'workspace_access_denied', - 'workspace_id_invalid', - 'origin_not_allowed', - 'cross_site_request' -]) -const KNOWN_ACCEPTED_METHODS: ReadonlySet = new Set([ - 'bearer_jwt', - 'x_api_key', - 'session_cookie', - 'cookie' -]) -const MAX_ACCEPTED_METHODS = 8 - -/** Fixed phrases a backend refusal is classified into; the text itself is dropped. */ -const KNOWN_REASONS: readonly (readonly [phrase: string, reason: string])[] = [ - ['authentication method not allowed', 'auth_method_not_allowed'], - ['unauthorized', 'unauthorized'] -] - -interface AuthRejectionDetails { - reason?: string - errorType?: string - errorCode?: string - accepted?: string -} - -function asRecord(value: unknown): Record | undefined { - return typeof value === 'object' && value !== null - ? (value as Record) - : undefined -} - -function allowlisted( - value: unknown, - known: ReadonlySet -): string | undefined { - if (typeof value !== 'string' || value.length === 0) return undefined - return known.has(value) ? value : OTHER -} - -function classifyReason(text: string): string | undefined { - const bounded = text.slice(0, MAX_CLASSIFIED_TEXT_LENGTH).toLowerCase() - if (bounded.trim().length === 0) return undefined - return ( - KNOWN_REASONS.find(([phrase]) => bounded.includes(phrase))?.[1] ?? OTHER - ) -} - -function acceptedMethods(value: unknown): string | undefined { - if (!Array.isArray(value)) return undefined - const methods = value - .filter((entry): entry is string => typeof entry === 'string') - .slice(0, MAX_ACCEPTED_METHODS) - .map((entry) => (KNOWN_ACCEPTED_METHODS.has(entry) ? entry : OTHER)) - return methods.length > 0 ? [...new Set(methods)].join(',') : undefined +interface AuthRejection { + status: AuthRejectionStatus + operation: AgentApiOperation + authScheme: ReportedAuthScheme + credential: ReportedAuthCredential + body: unknown + message: string } /** - * The bounded fields of an auth rejection that tell its causes apart. Ingest - * answers a credential the route does not take with - * `{ accepted: [...], error: { type: 'auth_type_not_allowed', message } }`, - * and its other auth refusals with `{ code, message }`. Every reported value - * comes from a fixed list, never from the response text. + * Reports an auth rejection and says whether it was delivered. Diagnostics + * fail open: nothing in here may change the error the caller receives, so + * tag-building and the reporter are each allowed to fail on their own. */ -function describeAuthRejection( - body: unknown, - message: string -): AuthRejectionDetails { - const record = asRecord(body) - const error = asRecord(record?.error) - const text = typeof record?.message === 'string' ? record.message : message - return { - reason: classifyReason(text), - errorType: allowlisted(error?.type, KNOWN_AUTH_ERROR_TYPES), - errorCode: - allowlisted(record?.code, KNOWN_AUTH_ERROR_CODES) ?? - allowlisted(error?.code, KNOWN_AUTH_ERROR_CODES), - accepted: acceptedMethods(record?.accepted) +function reportAuthRejection({ + status, + operation, + authScheme, + credential, + body, + message +}: AuthRejection): boolean { + let backendTags: AuthRejectionTags = {} + try { + backendTags = authRejectionTags(body, message) + } catch (error) { + console.warn('Could not classify the agent auth rejection:', error) + } + try { + reportError(new Error(AUTH_REJECTED_MESSAGE), { + surface: 'agent', + errorType: 'agent_api_auth_rejected', + tags: { operation, status, authScheme, credential, ...backendTags }, + level: 'warning' + }) + return true + } catch (error) { + console.warn('Could not report the agent auth rejection:', error) + return false } } @@ -549,23 +502,17 @@ export function createAgentRestClient() { body, retryAfterSeconds ) - if (response.status === 401 || response.status === 403) { - const details = describeAuthRejection(body, message) - reportError(new Error(AUTH_REJECTED_MESSAGE), { - surface: 'agent', - errorType: 'agent_api_auth_rejected', - tags: withoutUndefined({ - operation, - status: response.status, - authScheme, - credential, - backendReason: details.reason, - backendErrorType: details.errorType, - backendErrorCode: details.errorCode, - acceptedMethods: details.accepted - }), - level: 'warning' + if ( + isAuthRejectionStatus(response.status) && + reportAuthRejection({ + status: response.status, + operation, + authScheme, + credential, + body, + message }) + ) { // Callers still receive the backend text for the UI, but their generic // catch boundaries must not emit it as a second, separately-grouped // report after the complete bounded diagnostic above.