diff --git a/server/src/__tests__/oauth-dcr-failure-reporting.test.ts b/server/src/__tests__/oauth-dcr-failure-reporting.test.ts new file mode 100644 index 00000000000..e6b9c445de4 --- /dev/null +++ b/server/src/__tests__/oauth-dcr-failure-reporting.test.ts @@ -0,0 +1,86 @@ +import express from "express"; +import request from "supertest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { errorHandler } from "../middleware/error-handler.js"; +import { createOAuthClientProtocol } from "../services/tool-access/oauth/client.js"; +import { oauthProviderFailureDiagnosticsFor } from "../services/tool-access/oauth/provider-failure-diagnostics.js"; + +const captureExceptionMock = vi.hoisted(() => vi.fn()); + +vi.mock("../sentry.js", () => ({ captureException: captureExceptionMock })); +vi.mock("../telemetry.js", () => ({ getTelemetryClient: () => null })); + +const PROVIDER_CANARY = "provider-body-canary-7c1e"; + +function createApp(status: number, body: unknown) { + const { requestOAuthClientRegistration } = createOAuthClientProtocol({ + assertOAuthEndpointUrl: (_kind, value) => String(value), + fetchRemoteHttpUrl: async () => new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }), + }); + const app = express(); + app.post("/register", async (_req, res) => { + res.json(await requestOAuthClientRegistration({ + endpoints: { + provider: "fixture", + scopes: [], + authorizationUrl: "https://auth.example.test/authorize", + tokenUrl: "https://auth.example.test/token", + registrationUrl: "https://auth.example.test/register", + }, + redirectUri: "https://paperclip.example.test/api/tools/oauth/callback", + })); + }); + app.use(errorHandler); + return app; +} + +describe("OAuth dynamic client registration failure reporting", () => { + beforeEach(() => captureExceptionMock.mockReset()); + + it.each([401, 403, 404, 429, 500, 503])( + "answers a provider-side %i with a 502 and no crash report", + async (status) => { + const res = await request(createApp(status, { message: PROVIDER_CANARY })).post("/register"); + + expect(res.status).toBe(502); + expect(res.body).toMatchObject({ + error: "OAuth dynamic client registration failed", + code: "oauth_dynamic_client_registration_failed", + details: { code: "oauth_dynamic_client_registration_failed", providerError: null, status }, + }); + expect(JSON.stringify(res.body)).not.toContain(PROVIDER_CANARY); + expect(captureExceptionMock).not.toHaveBeenCalled(); + }, + ); + + it("still reports a 400 rejection with only its status and allowlisted error label", async () => { + const res = await request(createApp(400, { error: "invalid_client_metadata", error_description: PROVIDER_CANARY })) + .post("/register"); + + expect(res.status).toBe(502); + expect(res.body).toMatchObject({ + error: "The authorization server rejected Paperclip's client registration details.", + details: { providerError: "invalid_client_metadata", status: 400 }, + }); + expect(captureExceptionMock).toHaveBeenCalledTimes(1); + const reported = captureExceptionMock.mock.calls[0]![0]; + expect(oauthProviderFailureDiagnosticsFor(reported)).toEqual({ + operation: "dynamic_client_registration", + httpStatus: 400, + providerError: "invalid_client_metadata", + }); + expect(JSON.stringify(oauthProviderFailureDiagnosticsFor(reported))).not.toContain(PROVIDER_CANARY); + }); + + it("still reports a successful response with unusable client metadata", async () => { + const res = await request(createApp(201, { redirect_uris: [] })).post("/register"); + + expect(res.status).toBe(502); + expect(res.body).toMatchObject({ code: "oauth_dcr_response_invalid" }); + expect(captureExceptionMock).toHaveBeenCalledTimes(1); + expect(oauthProviderFailureDiagnosticsFor(captureExceptionMock.mock.calls[0]![0])).toBeNull(); + }); +}); diff --git a/server/src/__tests__/sentry-oauth-provider-failure.test.ts b/server/src/__tests__/sentry-oauth-provider-failure.test.ts new file mode 100644 index 00000000000..2d38212e086 --- /dev/null +++ b/server/src/__tests__/sentry-oauth-provider-failure.test.ts @@ -0,0 +1,51 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { HttpError } from "../errors.js"; + +const BACKEND_DSN_ENV = "SENTRY_DSN_BACKEND"; +const originalBackendDsn = process.env[BACKEND_DSN_ENV]; + +afterEach(() => { + if (originalBackendDsn === undefined) delete process.env[BACKEND_DSN_ENV]; + else process.env[BACKEND_DSN_ENV] = originalBackendDsn; + vi.doUnmock("@sentry/node"); + vi.doUnmock("../peer-version-check.js"); +}); + +describe("captureException OAuth provider failures", () => { + it("adds only the provider status and allowlisted error label to that event", async () => { + process.env[BACKEND_DSN_ENV] = "https://fixture@example.com/1"; + const captureException = vi.fn((_error: unknown, _hint?: unknown) => "event-id"); + vi.doMock("@sentry/node", () => ({ + getClient: () => ({ on: vi.fn() }), + init: vi.fn(), + captureException, + close: vi.fn(async () => true), + httpIntegration: vi.fn((options: unknown) => ({ name: "Http", ...(options as object) })), + onUnhandledRejectionIntegration: vi.fn((options: unknown) => ({ name: "OnUnhandledRejection", ...(options as object) })), + })); + vi.doMock("../peer-version-check.js", () => ({ checkExactPeerVersions: () => ({ ok: true }) })); + vi.resetModules(); + const sentry = await import("../sentry.js"); + const { recordOAuthProviderFailure } = await import("../services/tool-access/oauth/provider-failure-diagnostics.js"); + await sentry.sentryReady; + + const error = recordOAuthProviderFailure( + new HttpError(502, "OAuth dynamic client registration failed", { registrationUrl: "https://private.example.test/register" }), + { operation: "dynamic_client_registration", httpStatus: 400, providerError: null }, + ); + sentry.captureException(error, { runId: "run-1" }); + const unrelated = new Error("unrelated"); + sentry.captureException(unrelated); + + expect(captureException.mock.calls[0]).toEqual([ + error, + { + tags: { run_id: "run-1", oauth_operation: "dynamic_client_registration", oauth_provider_status: "400" }, + contexts: { oauth_provider_failure: { operation: "dynamic_client_registration", httpStatus: 400, providerError: null } }, + fingerprint: ["{{ default }}"], + }, + ]); + expect(JSON.stringify(captureException.mock.calls[0]![1])).not.toContain("private"); + expect(captureException.mock.calls[1]).toEqual([unrelated]); + }); +}); diff --git a/server/src/sentry.ts b/server/src/sentry.ts index 24b2637db7c..7d085d1252f 100644 --- a/server/src/sentry.ts +++ b/server/src/sentry.ts @@ -76,6 +76,7 @@ import { AdapterStopTimeoutError } from "./services/adapter-stop-timeout.js"; import { CloudPortfolioError } from "./services/cloud-portfolio-error.js"; import { SecretSensitiveRequestError } from "./middleware/secret-sensitive-request-error.js"; import { storageFailureDiagnosticsFor } from "./storage/failure-diagnostics.js"; +import { oauthProviderFailureDiagnosticsFor } from "./services/tool-access/oauth/provider-failure-diagnostics.js"; import { directoryMergeLockTimeoutDiagnosticsFor } from "@paperclipai/adapter-utils/directory-merge-lock-diagnostics"; import type { RunFailureDiagnostics } from "./services/run-failure-diagnostics.js"; import { readBuildCommit } from "./build-commit.js"; @@ -137,6 +138,7 @@ export function captureException(error: unknown, reference?: SentryRunReference) } : {}; const storageFailure = storageFailureDiagnosticsFor(error); const lockTimeout = directoryMergeLockTimeoutDiagnosticsFor(error); + const oauthProviderFailure = oauthProviderFailureDiagnosticsFor(error); if (error instanceof AdapterStopTimeoutError) { // Event-local, fixed-shape context: no ambient scope or raw error fields. const exception = new Error(error.message); @@ -187,6 +189,17 @@ export function captureException(error: unknown, reference?: SentryRunReference) contexts: { directory_merge_lock: { ...lockTimeout } }, fingerprint: ["{{ default }}"], }); + } else if (oauthProviderFailure) { + sentryHandle.captureException(error, { + tags: { + ...tags, + oauth_operation: oauthProviderFailure.operation, + oauth_provider_status: String(oauthProviderFailure.httpStatus), + ...(oauthProviderFailure.providerError ? { oauth_provider_error: oauthProviderFailure.providerError } : {}), + }, + contexts: { oauth_provider_failure: { ...oauthProviderFailure } }, + fingerprint: ["{{ default }}"], + }); } else if (reference) { sentryHandle.captureException(error, { tags, contexts: {}, fingerprint: ["{{ default }}"] }); } else { diff --git a/server/src/services/tool-access/oauth/client.ts b/server/src/services/tool-access/oauth/client.ts index d5a1d898e9b..38e6bf191c5 100644 --- a/server/src/services/tool-access/oauth/client.ts +++ b/server/src/services/tool-access/oauth/client.ts @@ -4,6 +4,8 @@ import { normalizeOAuthProviderError, oauthProviderErrorMessage } from "./provid import type { OAuthProviderEndpoints, OAuthTokenEndpointAuthMethod, OAuthTransport } from "./types.js"; import { oauthApplicationType } from "./client-metadata.js"; import { CLIENT_ASSERTION_TYPE } from "./client-credentials.js"; +import { recordOAuthProviderFailure } from "./provider-failure-diagnostics.js"; +import { markMcpHttpResponseFailure } from "../../mcp-connection-failure.js"; const MAX_OAUTH_DCR_CLIENT_ID_LENGTH = 4_096; @@ -208,7 +210,7 @@ export function createOAuthClientProtocol({ fetchRemoteHttpUrl, assertOAuthEndpo ); if (!response.ok) { const providerError = normalizeOAuthProviderError(record.error); - throw new HttpError( + const error = new HttpError( 502, oauthProviderErrorMessage( providerError, @@ -220,6 +222,12 @@ export function createOAuthClientProtocol({ fetchRemoteHttpUrl, assertOAuthEndpo status: response.status, }, ); + recordOAuthProviderFailure(error, { + operation: "dynamic_client_registration", + httpStatus: response.status, + providerError, + }); + throw markMcpHttpResponseFailure(response, error); } const clientId = parseOAuthDcrString(record, "client_id", { required: true, diff --git a/server/src/services/tool-access/oauth/provider-failure-diagnostics.ts b/server/src/services/tool-access/oauth/provider-failure-diagnostics.ts new file mode 100644 index 00000000000..89ecac8f7af --- /dev/null +++ b/server/src/services/tool-access/oauth/provider-failure-diagnostics.ts @@ -0,0 +1,18 @@ +export type OAuthProviderFailureOperation = "dynamic_client_registration"; + +export interface OAuthProviderFailureDiagnostics { + operation: OAuthProviderFailureOperation; + httpStatus: number; + providerError: string | null; +} + +const recorded = new WeakMap>(); + +export function recordOAuthProviderFailure(error: T, diagnostics: OAuthProviderFailureDiagnostics): T { + recorded.set(error, Object.freeze({ ...diagnostics })); + return error; +} + +export function oauthProviderFailureDiagnosticsFor(error: unknown): Readonly | null { + return error instanceof Error ? recorded.get(error) ?? null : null; +}