From 875738a8d4f81d467685f360760bd0b3a7c8e82d Mon Sep 17 00:00:00 2001 From: paperclipbugbot Date: Fri, 20 Nov 2026 07:52:23 -0800 Subject: [PATCH] fix(tool-access): keep provider-side OAuth registration failures out of Sentry (#22416) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - People connect remote MCP apps through OAuth. Paperclip registers its own OAuth client with the provider through dynamic client registration (RFC 7591). > - When the provider's registration endpoint answers with an error, Paperclip returns a 502 to the person. The error handler also sends every 5xx `HttpError` to Sentry. > - A provider that refuses or fails registration (401, 403, 404, 429 or 5xx) is a provider-side failure. It is not a Paperclip server fault, so it adds noise to Sentry. > - MCP discovery already marks the same provider statuses as expected remote failures, and the error handler does not report them. > - This pull request applies the same marking to the registration response. It also adds the provider status and the allowlisted error label to registration failures that Paperclip still reports. > - The benefit is that Sentry shows only registration failures that can be Paperclip faults, and each one tells which status the provider sent. ## Linked Issues or Issue Description **What happened?** A hosted server reported `Error: OAuth dynamic client registration failed` three times in two minutes. The stack is `startOAuth` -> `registerOAuthClient` -> `requestOAuthClientRegistration`. The message is the generic fallback, so the provider sent no recognized RFC 7591 `error` code. The event did not include the provider's HTTP status. Thus, the event did not show if the provider refused the request or if Paperclip sent bad metadata. **Expected behavior** The person gets the same 502 and code `oauth_dynamic_client_registration_failed`. Sentry does not get a crash report when the provider refuses or fails the request on its side (401, 403, 404, 429, 5xx). Sentry continues to get a report for other statuses, such as a 400 that rejects Paperclip's metadata. That report includes the status, so the cause is visible. **Steps to reproduce** 1. Point an OAuth connection at an authorization server whose registration endpoint returns 403 (closed or token-gated registration), 404, 429 or 503. 2. Start the OAuth connection. 3. See the 502 response and one Sentry crash report. **Paperclip version or commit** `master` at fe0c4aa95d8ef97c8058f3793e20bb7c1691d86b. No related open PR covers this reporting path. #20433 changes which client method Paperclip accepts after a successful registration. It does not change failure reporting. ## What Changed - `server/src/services/tool-access/oauth/client.ts`: A non-OK registration response now goes through `markMcpHttpResponseFailure`. This is the same classifier that MCP discovery uses. 401, 403, 404, 429 and 5xx become expected remote failures, so `errorHandler` does not report them. The HTTP response does not change. - `server/src/services/tool-access/oauth/provider-failure-diagnostics.ts` (new): A server-only `WeakMap` record keeps the operation, the HTTP status and the already-normalized provider error label. It does not keep the provider URL, body, description or headers. - `server/src/sentry.ts`: `captureException` adds `oauth_operation`, `oauth_provider_status` and the optional `oauth_provider_error` tags and an `oauth_provider_failure` context for an error that has this record. Grouping does not change (`{{ default }}`). - Tests: `oauth-dcr-failure-reporting.test.ts` sends each status through the real `errorHandler`. `sentry-oauth-provider-failure.test.ts` checks the exact Sentry tags and context. ## Verification - `cd server && npx vitest run src/__tests__/oauth-dcr-failure-reporting.test.ts src/__tests__/sentry-oauth-provider-failure.test.ts src/__tests__/sentry.test.ts src/__tests__/remote-http-rebinding.test.ts src/__tests__/openrouter-catalog-error-handler.test.ts`: all pass. - `cd server && npx vitest run src/__tests__/generic-mcp-connection.test.ts src/__tests__/tool-access-client-credentials.test.ts src/__tests__/error-handler.test.ts`: 154 tests pass. This includes the existing hostile-provider DCR redaction test. - Red check: without the `client.ts` change, the six provider-side status cases and the 400 diagnostics case fail. Without the `sentry.ts` change, the Sentry tag test fails. - Local `tsc` was stopped by the sandbox (SIGKILL), also for a scoped config. CI typecheck must cover this. ## Risks - Low risk. The HTTP status, body and code for the person do not change. - Sentry stops reporting registration failures with 401, 403, 404, 429 and 5xx status. A provider outage during registration is then visible only in the response and logs. This is the same policy that MCP discovery already uses. - The new tags contain only an integer status and an allowlisted label. No provider text goes to Sentry. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used as a coding agent with tool use (shell, file edit and test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com> --- .../oauth-dcr-failure-reporting.test.ts | 86 +++++++++++++++++++ .../sentry-oauth-provider-failure.test.ts | 51 +++++++++++ server/src/sentry.ts | 13 +++ .../src/services/tool-access/oauth/client.ts | 10 ++- .../oauth/provider-failure-diagnostics.ts | 18 ++++ 5 files changed, 177 insertions(+), 1 deletion(-) create mode 100644 server/src/__tests__/oauth-dcr-failure-reporting.test.ts create mode 100644 server/src/__tests__/sentry-oauth-provider-failure.test.ts create mode 100644 server/src/services/tool-access/oauth/provider-failure-diagnostics.ts 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; +}