diff --git a/server/src/adapters/registry.ts b/server/src/adapters/registry.ts index adc1304bd10..8512db5a0ff 100644 --- a/server/src/adapters/registry.ts +++ b/server/src/adapters/registry.ts @@ -2,6 +2,7 @@ import { pluginRunnerAiConnectionRequiredTestResult } from "../services/plugin-r import { HttpError } from "../errors.js"; import type { AdapterRuntimeCommandSpec, ServerAdapterModule } from "./types.js"; import { parseAdapterModelsEnv } from "../services/adapter-models-env.js"; +import { isAiKeyVerificationFailureCode } from "../services/ai-api-key-failures.js"; import { validateAiApiKey } from "../services/ai-api-key-test.js"; import type { AdapterEnvironmentTestResult } from "@paperclipai/shared"; import { stampClaudeAgentIdHeader } from "./claude-agent-id-header.js"; @@ -169,9 +170,10 @@ async function verifyNativeAcpxApiKey( } catch (error) { const details = error && typeof error === "object" && "details" in error ? error.details as { code?: string } | undefined : undefined; + const code = isAiKeyVerificationFailureCode(details?.code) ? details.code : "ai_connection_verification_failed"; + const reason = code !== "ai_connection_verification_failed" && error instanceof Error ? error.message : "Check the connection and try again."; return { ...result, status: "fail", checks: [...result.checks, { - code: details?.code === "ai_connection_api_key_rejected" ? details.code : "ai_connection_verification_failed", - level: "error", message: `Could not verify the ${account.name} API key. Check the connection and try again.`, + code, level: "error", message: `Could not verify the ${account.name} API key. ${reason}`, }] }; } } diff --git a/server/src/services/agent-environment-test.ts b/server/src/services/agent-environment-test.ts index 38cb939f11c..78d9a983c66 100644 --- a/server/src/services/agent-environment-test.ts +++ b/server/src/services/agent-environment-test.ts @@ -19,6 +19,7 @@ import { resolveEnvironmentExecutionTarget } from "./environment-execution-targe import { prepareManagedAiRuntime, assertManagedAiProjectAuth } from "./ai-connection-runtime.js"; import { isRunnerRevisionMismatch, runnerRevisionMismatchTestResult } from "./runner-revision-mismatch.js"; import { aiConnectionService } from "./ai-connections.js"; +import { isAiKeyVerificationFailureCode } from "./ai-api-key-failures.js"; import { validateAiApiKey } from "./ai-api-key-test.js"; import { probeCopilotExecutionTarget } from "./copilot-connection-probe.js"; import type { PluginWorkerManager } from "./plugin-worker-manager.js"; @@ -630,8 +631,8 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin result.checks.push({ code: "ai_connection_api_key_reverified", level: "info", message: "The provider verified this API key for adoption." }); } catch (error) { result.status = "fail"; - const rejected = error instanceof HttpError && asRecord(error.details)?.code === "ai_connection_api_key_rejected"; - result.checks.push({ code: rejected ? "ai_connection_api_key_rejected" : "ai_connection_verification_failed", level: "error", message: error instanceof HttpError ? error.message : "Could not verify the account. Try again." }); + const code = error instanceof HttpError ? asRecord(error.details)?.code : undefined; + result.checks.push({ code: isAiKeyVerificationFailureCode(code) ? code : "ai_connection_verification_failed", level: "error", message: error instanceof HttpError ? error.message : "Could not verify the account. Try again." }); } return finishManagedConnectionTest(adapterType, context, result); } diff --git a/server/src/services/ai-api-key-failures.ts b/server/src/services/ai-api-key-failures.ts new file mode 100644 index 00000000000..fb76d358dd2 --- /dev/null +++ b/server/src/services/ai-api-key-failures.ts @@ -0,0 +1,17 @@ +export const AI_KEY_VERIFICATION_FAILURES = { + rejected: { code: "ai_connection_api_key_rejected", message: "The provider rejected this API key." }, + billing: { code: "ai_connection_billing_required", message: "The provider account for this API key has no credit or billing set up. Add credit with the provider, then try again." }, + rateLimited: { code: "ai_connection_rate_limited", message: "The provider is limiting requests for this account right now. Wait a minute, then try again." }, + unavailable: { code: "ai_connection_provider_unavailable", message: "The provider is having problems right now. Try again in a few minutes." }, + timeout: { code: "ai_connection_verification_timeout", message: "The provider did not answer in time. Try again." }, + unreachable: { code: "ai_connection_provider_unreachable", message: "Paperclip could not reach the provider. Check this server's network connection, then try again." }, + failed: { code: "ai_connection_verification_failed", message: "The provider could not verify this account. Try again." }, +} as const; + +export type AiKeyVerificationFailure = keyof typeof AI_KEY_VERIFICATION_FAILURES; + +const VERIFICATION_FAILURE_CODES: ReadonlySet = new Set(Object.values(AI_KEY_VERIFICATION_FAILURES).map(failure => failure.code)); + +export function isAiKeyVerificationFailureCode(code: unknown): code is (typeof AI_KEY_VERIFICATION_FAILURES)[AiKeyVerificationFailure]["code"] { + return typeof code === "string" && VERIFICATION_FAILURE_CODES.has(code); +} diff --git a/server/src/services/ai-api-key-test.test.ts b/server/src/services/ai-api-key-test.test.ts new file mode 100644 index 00000000000..db1f9776494 --- /dev/null +++ b/server/src/services/ai-api-key-test.test.ts @@ -0,0 +1,103 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const warn = vi.hoisted(() => vi.fn()); +vi.mock("../middleware/logger.js", () => ({ logger: { warn } })); + +const { validateAiApiKey } = await import("./ai-api-key-test.js"); + +const KEY = "sk-ant-api03-fixture-key-0123456789"; + +function respond(status: number, body: unknown = "") { + return vi.fn().mockResolvedValue(new Response(typeof body === "string" ? body : JSON.stringify(body), { status })); +} + +async function failure(request: typeof fetch, provider: Parameters[0] = "anthropic") { + const error = await validateAiApiKey(provider, KEY, request).then(() => null, (thrown: unknown) => thrown); + expect(error).not.toBeNull(); + const { status, message, details } = error as { status: number; message: string; details: { code: string } }; + return { status, message, code: details.code }; +} + +describe("validateAiApiKey", () => { + beforeEach(() => warn.mockReset()); + + it("accepts a key the provider verifies", async () => { + await expect(validateAiApiKey("anthropic", KEY, respond(200, { data: [] }))).resolves.toBeUndefined(); + expect(warn).not.toHaveBeenCalled(); + }); + + it.each([401, 403])("keeps rejecting the key on %s", async status => { + expect(await failure(respond(status, `{"error":{"type":"authentication_error","message":"invalid x-api-key ${KEY}"}}`))) + .toEqual({ status: 422, code: "ai_connection_api_key_rejected", message: "The provider rejected this API key." }); + }); + + it.each([ + ["a 400", 400, { error: { type: "invalid_request_error" } }, "ai_connection_verification_failed"], + ["a 402", 402, { error: { code: 402, message: "Insufficient credits" } }, "ai_connection_billing_required"], + ["an Anthropic billing error", 400, { type: "error", error: { type: "billing_error" } }, "ai_connection_billing_required"], + ["an OpenAI quota error on 429", 429, { error: { type: "insufficient_quota", code: "insufficient_quota" } }, "ai_connection_billing_required"], + ["a quota code behind another error type on 429", 429, { error: { type: "invalid_request_error", code: "insufficient_quota" } }, "ai_connection_billing_required"], + ["a 429", 429, { error: { type: "rate_limit_error" } }, "ai_connection_rate_limited"], + ["a 500", 500, { error: { type: "api_error" } }, "ai_connection_provider_unavailable"], + ["an Anthropic overload", 529, { error: { type: "overloaded_error" } }, "ai_connection_provider_unavailable"], + ])("gives %s its own code", async (_label, status, body, code) => { + const result = await failure(respond(status, body)); + expect(result.code).toBe(code); + expect(result.status).toBe(422); + }); + + it("gives each failure its own message", async () => { + const messages = new Set(); + for (const [status, body] of [[400, {}], [402, {}], [429, {}], [500, {}]] as const) { + messages.add((await failure(respond(status, body))).message); + } + expect(messages.size).toBe(4); + }); + + it("logs the status and the provider's error type without the key or the response text", async () => { + await failure(respond(429, { error: { type: "rate_limit_error", message: `slow down ${KEY}` } })); + + expect(warn).toHaveBeenCalledWith( + { provider: "anthropic", status: 429, providerErrorType: "rate_limit_error", failure: "ai_connection_rate_limited" }, + "AI provider did not verify an API key", + ); + expect(JSON.stringify(warn.mock.calls)).not.toContain(KEY); + expect(JSON.stringify(warn.mock.calls)).not.toContain("slow down"); + }); + + it("logs the billing field when the error type and code differ", async () => { + await failure(respond(429, { error: { type: "invalid_request_error", code: "insufficient_quota" } })); + + expect(warn.mock.calls[0]![0]).toMatchObject({ providerErrorType: "insufficient_quota", failure: "ai_connection_billing_required" }); + }); + + it("logs only known provider error types", async () => { + await failure(respond(500, { error: { type: KEY } })); + await failure(respond(500, { error: { type: `${KEY}_suffix` } })); + await failure(respond(500, { error: { type: "fixture" } }), "openai"); + await failure(respond(429, { error: { type: "custom_upstream_type", code: "rate_limit_exceeded" } }), "openai"); + await failure(respond(503, { error: { status: "UNAVAILABLE" } }), "google"); + await failure(respond(500, "upstream error")); + + expect(warn.mock.calls.map(([fields]) => fields.providerErrorType)) + .toEqual([null, null, null, "rate_limit_exceeded", "UNAVAILABLE", null]); + expect(JSON.stringify(warn.mock.calls)).not.toContain(KEY); + }); + + it("reads at most a bounded part of a large error body", async () => { + const body = `{"error":{"type":"api_error"},"padding":"${"x".repeat(64 * 1024)}"}`; + const result = await failure(respond(500, body)); + expect(result.code).toBe("ai_connection_provider_unavailable"); + expect(warn.mock.calls[0]![0].providerErrorType).toBeNull(); + }); + + it("separates a timeout from an unreachable provider", async () => { + const timedOut = await failure(vi.fn().mockRejectedValue(new DOMException("The operation timed out.", "TimeoutError"))); + expect(timedOut.code).toBe("ai_connection_verification_timeout"); + + const unreachable = await failure(vi.fn().mockRejectedValue(new TypeError("fetch failed", { cause: { code: "ENOTFOUND" } }))); + expect(unreachable.code).toBe("ai_connection_provider_unreachable"); + + expect(warn.mock.calls.map(([fields]) => fields.networkError)).toEqual(["timeout", "ENOTFOUND"]); + }); +}); diff --git a/server/src/services/ai-api-key-test.ts b/server/src/services/ai-api-key-test.ts index 4ed513f28e3..8c103f18725 100644 --- a/server/src/services/ai-api-key-test.ts +++ b/server/src/services/ai-api-key-test.ts @@ -1,5 +1,62 @@ import type { AiProvider } from "@paperclipai/shared"; import { unprocessable } from "../errors.js"; +import { logger } from "../middleware/logger.js"; +import { AI_KEY_VERIFICATION_FAILURES, type AiKeyVerificationFailure } from "./ai-api-key-failures.js"; + +const KNOWN_PROVIDER_ERROR_TYPES: ReadonlySet = new Set([ + "invalid_request_error", "authentication_error", "permission_error", "not_found_error", "request_too_large", + "rate_limit_error", "api_error", "overloaded_error", "billing_error", "timeout_error", + "insufficient_quota", "invalid_api_key", "rate_limit_exceeded", "server_error", "model_not_found", "insufficient_credits", + "INVALID_ARGUMENT", "FAILED_PRECONDITION", "PERMISSION_DENIED", "UNAUTHENTICATED", "NOT_FOUND", + "RESOURCE_EXHAUSTED", "INTERNAL", "UNAVAILABLE", "DEADLINE_EXCEEDED", +]); +const MAX_ERROR_BODY_BYTES = 8 * 1024; +const BILLING_ERROR_TYPES = new Set(["billing_error", "insufficient_quota", "insufficient_credits"]); + +async function readBoundedBody(response: Response): Promise { + const reader = response.body?.getReader(); + if (!reader) return ""; + const chunks: Uint8Array[] = []; + let bytes = 0; + try { + while (bytes < MAX_ERROR_BODY_BYTES) { + const { done, value } = await reader.read(); + if (done) break; + chunks.push(value); + bytes += value.length; + } + } finally { + await reader.cancel().catch(() => {}); + } + return Buffer.concat(chunks).subarray(0, MAX_ERROR_BODY_BYTES).toString("utf8"); +} + +async function providerErrorTypes(response: Response): Promise { + let parsed: unknown; + try { + parsed = JSON.parse(await readBoundedBody(response)); + } catch { + return []; + } + const error = parsed && typeof parsed === "object" ? (parsed as { error?: unknown }).error : undefined; + if (!error || typeof error !== "object") return []; + const { type, code, status } = error as { type?: unknown; code?: unknown; status?: unknown }; + return [type, code, status].filter((candidate): candidate is string => + typeof candidate === "string" && KNOWN_PROVIDER_ERROR_TYPES.has(candidate)); +} + +function classify(status: number, errorTypes: string[]): AiKeyVerificationFailure { + if (status === 401 || status === 403) return "rejected"; + if (status === 402 || errorTypes.some(type => BILLING_ERROR_TYPES.has(type))) return "billing"; + if (status === 429) return "rateLimited"; + if (status >= 500) return "unavailable"; + return "failed"; +} + +function fail(failure: AiKeyVerificationFailure): never { + const { code, message } = AI_KEY_VERIFICATION_FAILURES[failure]; + throw unprocessable(message, { code }); +} /** Fixed provider endpoints; credentials are never sent to a caller-supplied URL or through a redirect. */ export async function validateAiApiKey( @@ -25,15 +82,22 @@ export async function validateAiApiKey( ? { "x-api-key": key, "anthropic-version": "2023-06-01" } : { Authorization: `Bearer ${key}` }, }); - } catch { - throw unprocessable("Could not verify the account. Try again.", { code: "ai_connection_verification_failed" }); + } catch (error) { + const timedOut = error instanceof Error && error.name === "TimeoutError"; + const cause = error instanceof Error && error.cause && typeof error.cause === "object" ? error.cause as { code?: unknown } : undefined; + logger.warn({ provider, networkError: timedOut ? "timeout" : typeof cause?.code === "string" ? cause.code : "request_failed" }, + "AI provider API key verification request failed"); + fail(timedOut ? "timeout" : "unreachable"); } - await response.body?.cancel(); - if (!response.ok) - throw unprocessable( - response.status === 401 || response.status === 403 - ? "The provider rejected this API key." - : "The provider could not verify this account. Try again.", - { code: response.status === 401 || response.status === 403 ? "ai_connection_api_key_rejected" : "ai_connection_verification_failed" }, - ); + if (response.ok) { + await response.body?.cancel(); + return; + } + const errorTypes = response.status === 401 || response.status === 403 ? [] : await providerErrorTypes(response); + if (response.status === 401 || response.status === 403) await response.body?.cancel(); + const failure = classify(response.status, errorTypes); + const errorType = errorTypes.find(type => BILLING_ERROR_TYPES.has(type)) ?? errorTypes[0] ?? null; + logger.warn({ provider, status: response.status, providerErrorType: errorType, failure: AI_KEY_VERIFICATION_FAILURES[failure].code }, + "AI provider did not verify an API key"); + fail(failure); } diff --git a/tests/runner-e2e/connection-evidence.ts b/tests/runner-e2e/connection-evidence.ts index 9ccb4c4d105..f221fa0f516 100644 --- a/tests/runner-e2e/connection-evidence.ts +++ b/tests/runner-e2e/connection-evidence.ts @@ -4,6 +4,18 @@ import type { RunnerE2EResult } from "./types.js"; export const connectionCheckpoints = ["target", "connection_created", "connection_reloaded", "agent_created", "binding", "setup_probe", "first_run", "artifact", "tool_receipt", "followup", "visible_result"] as const; export type ConnectionCheckpoint = typeof connectionCheckpoints[number]; export const connectionRunSignals = ["provider_overloaded", "provider_quota", "missing_file_conversion", "unsupported_session_configuration", "command_substitution_denied"] as const; +export const connectionVerificationFailureCodes = [ + "ai_connection_api_key_rejected", + "ai_connection_billing_required", + "ai_connection_rate_limited", + "ai_connection_provider_unavailable", + "ai_connection_verification_timeout", + "ai_connection_provider_unreachable", + "ai_connection_verification_failed", +] as const; +export const connectionCreationFailureCodes = [...connectionVerificationFailureCodes, "connection_request_rejected"] as const; +export type ConnectionCreationFailureCode = (typeof connectionCreationFailureCodes)[number]; + export interface ConnectionRunDiagnostic { runId: string; status: "succeeded" | "failed" | "cancelled" | "interrupted" | "timed_out" | "unknown"; @@ -28,7 +40,7 @@ export interface ConnectionEvidence { model?: string; inputTransport?: "prompt_base64"; setupChecks?: Array<{ code: string; level: "info" | "warn" | "error" }>; - creationFailure?: { status: number; code: "ai_connection_api_key_rejected" | "ai_connection_verification_failed" | "connection_request_rejected" }; + creationFailure?: { status: number; code: ConnectionCreationFailureCode }; cleanupRetained?: boolean; companyArchived?: boolean; artifactChecks?: Array<{ filename: string; runId: string; sha256: string; fields: Record; exactFields: boolean }>; diff --git a/tests/runner-e2e/connection-flow.ts b/tests/runner-e2e/connection-flow.ts index 1e6393c0189..ce7b540e08d 100644 --- a/tests/runner-e2e/connection-flow.ts +++ b/tests/runner-e2e/connection-flow.ts @@ -5,7 +5,7 @@ import { getConnectableAppDefinition } from "../../packages/shared/src/app-defin import { connectionCell, type ConnectionHarness, type ConnectionMode } from "./connection-cases.js"; import { ConnectionBlock, ConnectionFailure, type ConnectionConfig, type resolveConnectionSettings } from "./connection-config.js"; import { ConnectionApi, connectionDelay } from "./connection-target.js"; -import { createConnectionProof, verifyConnectionArtifact, verifyConnectionRun, completedConnectionArtifactRun, connectionProbeChecks, type ConnectionEvidence } from "./connection-evidence.js"; +import { createConnectionProof, verifyConnectionArtifact, verifyConnectionRun, completedConnectionArtifactRun, connectionProbeChecks, connectionVerificationFailureCodes, type ConnectionCreationFailureCode, type ConnectionEvidence } from "./connection-evidence.js"; import { createTaskThroughUi, submitTaskReply } from "./user-actions.js"; import { collectRunEvents } from "./run-observations.js"; import type { MatrixExecution } from "./types.js"; @@ -56,8 +56,8 @@ async function submitConnection(input: ConnectionFlowInput, submit: () => Promis if (!created) throw new ConnectionFailure("connection_request_timeout"); if (created.ok()) return; const payload = await created.json().catch(() => ({})); - const allowed = ["ai_connection_api_key_rejected", "ai_connection_verification_failed"]; - const code = allowed.includes(payload?.details?.code) ? payload.details.code : "connection_request_rejected"; + const allowed: readonly string[] = connectionVerificationFailureCodes; + const code: ConnectionCreationFailureCode = allowed.includes(payload?.details?.code) ? payload.details.code : "connection_request_rejected"; input.evidence.creationFailure = { status: created.status(), code }; if (code === "ai_connection_api_key_rejected") throw new ConnectionBlock("missing_credential", code); throw new ConnectionFailure(code); diff --git a/tests/runner-e2e/connection-support.test.ts b/tests/runner-e2e/connection-support.test.ts index 98fb816bca3..7f5978eb56b 100644 --- a/tests/runner-e2e/connection-support.test.ts +++ b/tests/runner-e2e/connection-support.test.ts @@ -3,11 +3,12 @@ import { chmod, mkdtemp, writeFile, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { AGENT_ADAPTER_TYPES } from "../../packages/shared/src/constants.js"; +import { AI_KEY_VERIFICATION_FAILURES } from "../../server/src/services/ai-api-key-failures.js"; import { runnerMatrix } from "./catalog.js"; import { parseRunnerSelectors, selectRunnerExecutions, buildMatrixJobs } from "./selectors.js"; import { connectionHarnesses, connectionScopeGaps, connectionCell, supportsConnection } from "./connection-cases.js"; import { parseConnectionConfig, targetOrigin, selectedSecret, resolveConnectionSecret, resolveConnectionSettings } from "./connection-config.js"; -import { connectionCheckpoints, connectionEvidencePasses, connectionRunDiagnostic, createConnectionProof, verifyConnectionArtifact, verifyConnectionRun, completedConnectionArtifactRun, connectionProbeChecks, type ConnectionEvidence } from "./connection-evidence.js"; +import { connectionCheckpoints, connectionVerificationFailureCodes, connectionEvidencePasses, connectionRunDiagnostic, createConnectionProof, verifyConnectionArtifact, verifyConnectionRun, completedConnectionArtifactRun, connectionProbeChecks, type ConnectionEvidence } from "./connection-evidence.js"; import { validateRetainedRunnerResult } from "./result-validation.js"; import { ConnectionApi, verifyConnectionTarget } from "./connection-target.js"; import { cleanupConnectionCompany, connectionCreationReceipt, runConnectionCampaign, safeConnectionFailure, withConnectionCampaignCancellation } from "./connection-launch.js"; @@ -300,3 +301,10 @@ describe("independent qualification", () => { expect(cleanupFailed.failed).toBe(1); expect(cleanupFailed.incomplete).toBe(0); }); }); + +describe("connection creation failure codes", () => { + it("keeps every API key verification code the server can return", () => { + expect([...connectionVerificationFailureCodes].sort()) + .toEqual(Object.values(AI_KEY_VERIFICATION_FAILURES).map(failure => failure.code).sort()); + }); +}); diff --git a/tests/runner-e2e/result-validation.ts b/tests/runner-e2e/result-validation.ts index b89ab770fec..31901bc1f44 100644 --- a/tests/runner-e2e/result-validation.ts +++ b/tests/runner-e2e/result-validation.ts @@ -2,7 +2,7 @@ import { SCREENSHOT_PRIVACY_REASONS } from "./screenshot-privacy.js"; import { POSTGRES_IMAGE, POSTGRES_IMAGE_ID, POSTGRES_AMD64_IMAGE, POSTGRES_AMD64_IMAGE_IDS, reviewedPostgresReceiptIdentity } from "./docker-postgres.js"; import { agentJourneyRuns, agentJourneyRunCountValid, journeyRequiredChecks } from "./product-journeys/success-contract.js"; import { validateWorkerTiming } from "./worker-timing.js"; -import { connectionCheckpoints, connectionEvidencePasses, connectionRunSignals } from "./connection-evidence.js"; +import { connectionCreationFailureCodes, connectionCheckpoints, connectionEvidencePasses, connectionRunSignals } from "./connection-evidence.js"; import { githubJourneyCheckpoints, gradeGitHubReviewJourney } from "./github-review-evidence.js"; import { gradeAntigravityJourney, validateAntigravityJourneyEvidence } from "./antigravity-journey-evidence.js"; import { STARTUP_REUSE_LAYERS, STARTUP_REUSE_REASONS } from "../../packages/adapter-utils/src/startup-reuse.js"; @@ -395,7 +395,7 @@ const fields = { inputTransport: optional(oneOf("prompt_base64")), setupChecks: optional(array(shape({ code: string, level: oneOf("info", "warn", "error") }))), runDiagnostics: optional(array(shape({ runId: string, status: oneOf("succeeded", "failed", "cancelled", "interrupted", "timed_out", "unknown"), signals: array(oneOf(...connectionRunSignals)), logAvailable: boolean }))), - creationFailure: optional(shape({ status: integer, code: oneOf("ai_connection_api_key_rejected", "ai_connection_verification_failed", "connection_request_rejected") })), + creationFailure: optional(shape({ status: integer, code: oneOf(...connectionCreationFailureCodes) })), connectionId: optional(string), agentId: optional(string), companyId: optional(string), artifactSha256: optional(string), model: optional(string), cleanupRetained: optional(boolean), companyArchived: optional(boolean), })), completionQuality: optional(array(shape({