mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
Bound unauthenticated MCP registrations across replicas
Serialize registration quotas in PostgreSQL, cap retained clients, and expire unused clients and authorization requests. Preserve consented clients, grants, receipts, and audit history. Concurrent replica and active-grant retention tests pass. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
85b30d8981
commit
826de9e6c2
3 files changed
+44
-3
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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<Awaited<ReturnType<typeof oauth.register>>> => 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));
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
@@ -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<number>`count(*)::int`,
|
||||
recent: sql<number>`(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) {
|
||||
|
||||
Reference in new issue
Block a user