diff --git a/doc/public-mcp.md b/doc/public-mcp.md index c9e59ee98f7..cf0349de56c 100644 --- a/doc/public-mcp.md +++ b/doc/public-mcp.md @@ -85,6 +85,11 @@ not elevate a grant beyond that company's role. Consent/revocation require an authenticated browser and the configured origin. Client registration does not fetch redirect URLs or accept arbitrary tool destinations. Rate limiting at the public edge is required in addition to the bounded per-process auth limiter. +Registration also has a database-enforced limit of 60 new clients per minute and +10,000 retained clients shared across replicas. Expired authorization requests +and never-consented clients older than 24 hours are collected during +registration. Clients with grants are retained, preserving their connections and +audit/mutation history. Revocation blocks future calls; it does not cancel already delegated work or undo in-flight mutations. Manage existing tasks and execution in Paperclip. diff --git a/server/src/__tests__/public-mcp.test.ts b/server/src/__tests__/public-mcp.test.ts index ad56d67b03a..2654b6a870b 100644 --- a/server/src/__tests__/public-mcp.test.ts +++ b/server/src/__tests__/public-mcp.test.ts @@ -3,7 +3,7 @@ import express, { type Request } from "express"; import request from "supertest"; import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; -import { createDb, authUsers, companies, companyMemberships, mcpOauthTokens, mcpOauthGrants, mcpMutationReceipts, agents, issues, issueComments, instanceUserRoles } from "@paperclipai/db"; +import { createDb, authUsers, companies, companyMemberships, mcpOauthTokens, mcpOauthGrants, mcpOauthClients, mcpMutationReceipts, agents, issues, issueComments, instanceUserRoles } from "@paperclipai/db"; import { createPublicMcpOAuth, publicMcpConfig, hashMcpSecret } from "../services/public-mcp/oauth.js"; import { createMcpApiDispatch, createPublicMcpExecutor, publicMcpCapabilities } from "../services/public-mcp/capabilities.js"; import { publicMcpIngressRoutes, publicMcpManagementRoutes } from "../routes/public-mcp.js"; @@ -261,4 +261,23 @@ describe.skipIf(!support.supported)("public MCP OAuth and tool boundary", () => expect((await request(app).delete(`/api/mcp/connections/${connection.id}`).set("Origin", config.origin)).status).toBe(204); expect((await db.select().from(mcpOauthGrants).where(eq(mcpOauthGrants.id, connection.id)))[0]?.revokedAt).not.toBeNull(); }); + it("shares registration quotas across replicas and preserves consented clients during retention", async () => { + const f = await fixture(); + const stale = "stale-" + randomUUID(); + const old = new Date(Date.now() - 2 * 86_400_000); + await db.insert(mcpOauthClients).values({ id: stale, name: "Never connected", redirectUris: [redirectUri], createdAt: old }); + await db.update(mcpOauthClients).set({ createdAt: old }); + const replica = createPublicMcpOAuth(db, config); + const registrations = await Promise.allSettled(Array.from({ length: 70 }, (_, index) => (index % 2 ? oauth : replica).register({ client_name: "Quota fixture", redirect_uris: [redirectUri] }))); + const accepted = registrations.filter((r): r is PromiseFulfilledResult>> => r.status === "fulfilled"); + try { + expect(accepted).toHaveLength(60); + for (const rejected of registrations.filter(r => r.status === "rejected")) expect((rejected as PromiseRejectedResult).reason).toMatchObject({ status: 429 }); + expect(await db.select().from(mcpOauthClients).where(eq(mcpOauthClients.id, stale))).toHaveLength(0); + expect(await oauth.authenticate(f.tokens.access_token)).toMatchObject({ grant: { clientId: f.client.client_id } }); + } finally { + for (const row of accepted) await db.delete(mcpOauthClients).where(eq(mcpOauthClients.id, row.value.client_id)); + } + }); + }); diff --git a/server/src/services/public-mcp/oauth.ts b/server/src/services/public-mcp/oauth.ts index 2cd1ac50a3e..70a80ad1bb0 100644 --- a/server/src/services/public-mcp/oauth.ts +++ b/server/src/services/public-mcp/oauth.ts @@ -1,5 +1,5 @@ import { createHash, randomBytes } from "node:crypto"; -import { and, eq, gt, inArray, isNull } from "drizzle-orm"; +import { and, eq, gt, inArray, isNull, lt, notExists, sql } from "drizzle-orm"; import { z } from "zod"; import type { Request } from "express"; import { @@ -102,7 +102,24 @@ export function createPublicMcpOAuth(db: Db, config: PublicMcpConfig) { const parsed = registrationSchema.safeParse(input); if (!parsed.success) throw new McpOAuthError("invalid_client_metadata", "Supply a client name, valid redirect URIs, and public-client PKCE authentication."); const client = { id: secret("pcmcp_client_"), name: parsed.data.client_name, redirectUris: parsed.data.redirect_uris }; - await db.insert(mcpOauthClients).values(client); + await db.transaction(async (tx) => { + // Bound public DCR across replicas, not only per-IP in each process. + await tx.execute(sql`SELECT pg_advisory_xact_lock(736721042)`); + const now = new Date(); + await tx.delete(mcpOauthRequests).where(lt(mcpOauthRequests.expiresAt, now)); + await tx.delete(mcpOauthClients).where(and( + lt(mcpOauthClients.createdAt, new Date(now.getTime() - 24 * 60 * minute)), + notExists(tx.select({ id: mcpOauthGrants.id }).from(mcpOauthGrants).where(eq(mcpOauthGrants.clientId, mcpOauthClients.id))), + notExists(tx.select({ id: mcpOauthRequests.id }).from(mcpOauthRequests).where(eq(mcpOauthRequests.clientId, mcpOauthClients.id))), + )); + const [counts] = await tx.select({ total: sql`count(*)::int`, + recent: sql`(count(*) FILTER (WHERE ${mcpOauthClients.createdAt} > ${new Date(now.getTime() - minute).toISOString()}::timestamptz))::int`, + }).from(mcpOauthClients); + if (!counts || counts.total >= 10_000 || counts.recent >= 60) { + throw new McpOAuthError("temporarily_unavailable", "Registration capacity reached. Retry later.", 429); + } + await tx.insert(mcpOauthClients).values(client); + }); return { ...parsed.data, client_id: client.id, client_id_issued_at: Math.floor(Date.now() / 1000) }; }, async authorize(input: unknown) {