fix(mcp): close OAuth 2.1 resource-server gaps before the remote surface ships

Harden the remote MCP endpoint and the in-repo OAuth bridge against the
adversarial review of the milestone branch. The two ship-blockers made the
"read-only, revocable" promise false; the rest tightened the surface.

Audience binding at the resource server: a token whose only grant is the new
`health:read` scope is the MCP read credential. The REST edge now accepts it on
safe (read) methods and refuses it on writes/deletes with 403, so a connector
token can read over `/mcp` and GET routes but can never POST/DELETE the record
despite a "read-only" consent. The `/mcp` resolver is unaffected.

Revocable, theft-detectable refresh tokens: refresh artifacts now anchor to a
persistent connection row. Revoking a connection stops every future refresh and
kills its access tokens; a replayed (already-rotated) refresh is treated as
theft and revokes the whole connection. Connections surface in settings as the
unit a user can disconnect. The old access token is revoked on rotation.

Also: fail closed on the OAuth/`/mcp` surface when no canonical origin is
configured and mark the discovery documents non-cacheable; honour the global API
kill-switch on `/mcp`, `/token`, `/authorize`, and `/register`; cap the CIMD and
registration body reads while streaming instead of after; show the verified
client origin on consent; validate CIMD redirect-URI schemes; assert same-origin
on the consent POST; and add a daily prune for expired connector tokens.

New migration 0195 adds the connection anchor and links access tokens to it.
This commit is contained in:
Marc-André Bombeck committed 2026-06-27 15:09:11 +02:00
1 parent 06363771ee
commit 22eb9cba0d
39 files changed
+1826 -72

No files matched your search

@@ -0,0 +1,195 @@
/**
* MCP OAuth connection anchor — H2 revocation + reuse-detection.
*
* These pin the security contract the stateless refresh artifact alone cannot
* provide: a revoked connection stops every future refresh, a replayed
* (already-rotated) jti revokes the whole connection, and a settings revoke
* terminates the chain and kills the connection's access tokens.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
mcpOAuthConnection: {
create: vi.fn(),
findUnique: vi.fn(),
updateMany: vi.fn(),
findMany: vi.fn(),
},
apiToken: {
updateMany: vi.fn(),
},
},
}));
import { prisma } from "@/lib/db";
import {
createConnection,
rotateConnection,
revokeConnectionForUser,
} from "../connections";
const CONN = {
id: "conn-1",
userId: "user-1",
clientId: "https://app.example/client.json",
currentJti: "jti-current",
revokedAt: null as Date | null,
};
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(prisma.apiToken.updateMany).mockResolvedValue({
count: 0,
} as never);
vi.mocked(prisma.mcpOAuthConnection.updateMany).mockResolvedValue({
count: 1,
} as never);
});
describe("createConnection", () => {
it("seeds currentJti with the first refresh jti", async () => {
vi.mocked(prisma.mcpOAuthConnection.create).mockResolvedValue({
id: "conn-1",
} as never);
const id = await createConnection({
userId: "user-1",
clientId: CONN.clientId,
clientName: "Claude",
scope: "health:read offline_access",
resource: "https://health.example/mcp",
jti: "jti-1",
});
expect(id).toBe("conn-1");
expect(prisma.mcpOAuthConnection.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ currentJti: "jti-1" }),
}),
);
});
});
describe("rotateConnection — happy path", () => {
it("advances currentJti and revokes prior access tokens (L4)", async () => {
vi.mocked(prisma.mcpOAuthConnection.findUnique).mockResolvedValue({
...CONN,
} as never);
const out = await rotateConnection({
connectionId: "conn-1",
presentedJti: "jti-current",
newJti: "jti-next",
clientId: CONN.clientId,
userId: "user-1",
});
expect(out.ok).toBe(true);
expect(prisma.mcpOAuthConnection.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({ currentJti: "jti-current" }),
data: expect.objectContaining({ currentJti: "jti-next" }),
}),
);
// L4 — prior access tokens revoked on rotation.
expect(prisma.apiToken.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { mcpConnectionId: "conn-1", revoked: false },
data: { revoked: true },
}),
);
});
});
describe("rotateConnection — revoked connection stops refresh", () => {
it("rejects when the connection is revoked", async () => {
vi.mocked(prisma.mcpOAuthConnection.findUnique).mockResolvedValue({
...CONN,
revokedAt: new Date(),
} as never);
const out = await rotateConnection({
connectionId: "conn-1",
presentedJti: "jti-current",
newJti: "jti-next",
clientId: CONN.clientId,
userId: "user-1",
});
expect(out).toEqual({ ok: false, reason: "revoked" });
expect(prisma.mcpOAuthConnection.updateMany).not.toHaveBeenCalled();
});
});
describe("rotateConnection — reuse detection revokes the family", () => {
it("revokes the connection when a stale jti is presented", async () => {
vi.mocked(prisma.mcpOAuthConnection.findUnique).mockResolvedValue({
...CONN,
currentJti: "jti-rotated-already",
} as never);
const out = await rotateConnection({
connectionId: "conn-1",
presentedJti: "jti-old", // not the current jti → replay
newJti: "jti-next",
clientId: CONN.clientId,
userId: "user-1",
});
expect(out).toEqual({ ok: false, reason: "reuse_detected" });
// The whole connection is revoked + its access tokens killed.
expect(prisma.mcpOAuthConnection.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "conn-1", revokedAt: null },
data: expect.objectContaining({ revokedAt: expect.any(Date) }),
}),
);
expect(prisma.apiToken.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { mcpConnectionId: "conn-1", revoked: false },
}),
);
});
it("rejects a connection owned by another user", async () => {
vi.mocked(prisma.mcpOAuthConnection.findUnique).mockResolvedValue({
...CONN,
userId: "someone-else",
} as never);
const out = await rotateConnection({
connectionId: "conn-1",
presentedJti: "jti-current",
newJti: "jti-next",
clientId: CONN.clientId,
userId: "user-1",
});
expect(out).toEqual({ ok: false, reason: "not_found" });
});
});
describe("revokeConnectionForUser — settings revoke kills the chain", () => {
it("revokes a connection owned by the user and its access tokens", async () => {
vi.mocked(prisma.mcpOAuthConnection.findUnique).mockResolvedValue({
id: "conn-1",
userId: "user-1",
revokedAt: null,
} as never);
const ok = await revokeConnectionForUser("user-1", "conn-1");
expect(ok).toBe(true);
expect(prisma.mcpOAuthConnection.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ revokedAt: expect.any(Date) }),
}),
);
expect(prisma.apiToken.updateMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { mcpConnectionId: "conn-1", revoked: false },
data: { revoked: true },
}),
);
});
it("refuses to revoke another user's connection", async () => {
vi.mocked(prisma.mcpOAuthConnection.findUnique).mockResolvedValue({
id: "conn-1",
userId: "someone-else",
revokedAt: null,
} as never);
const ok = await revokeConnectionForUser("user-1", "conn-1");
expect(ok).toBe(false);
expect(prisma.mcpOAuthConnection.updateMany).not.toHaveBeenCalled();
});
});
@@ -149,6 +149,35 @@ describe("clients — CIMD via safeFetch (SSRF-safe)", () => {
const res = await resolveClient("https://169.254.169.254/meta.json");
expect(res).toEqual({ ok: false, reason: "ssrf_blocked" });
});
it("rejects a CIMD doc with a non-https / non-loopback redirect (L2)", async () => {
const clientId = "https://app.example/mcp-client.json";
vi.mocked(safeFetch).mockResolvedValue(
new Response(
JSON.stringify({
client_id: clientId,
client_name: "Sketchy",
redirect_uris: ["http://evil.example/cb"], // non-loopback http
}),
{ status: 200 },
),
);
const res = await resolveClient(clientId);
expect(res).toEqual({ ok: false, reason: "invalid_metadata" });
});
it("rejects an oversized CIMD body via the streaming cap (M3)", async () => {
const clientId = "https://app.example/mcp-client.json";
// Declared Content-Length over the 16 KB cap → rejected before reading.
vi.mocked(safeFetch).mockResolvedValue(
new Response("x".repeat(64), {
status: 200,
headers: { "content-length": String(64 * 1024) },
}),
);
const res = await resolveClient(clientId);
expect(res).toEqual({ ok: false, reason: "invalid_metadata" });
});
});
describe("clients — redirect URI matching", () => {
+35 -3
View File
@@ -23,6 +23,7 @@
* ordinary registered entry.
*/
import { safeFetch } from "@/lib/safe-fetch";
import { readBodyCapped } from "@/lib/http/read-capped";
import { ARTIFACT_KINDS, signArtifact, verifyArtifact } from "./artifacts";
export interface ResolvedClient {
@@ -55,6 +56,30 @@ function asStringArray(value: unknown): string[] | null {
return out;
}
const REDIRECT_LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "::1", "[::1]"];
/**
* A redirect URI must be an absolute HTTPS URL or an `http` loopback URL. This
* is the single source of truth shared by DCR (the `register` route) and CIMD
* (L2): both registration paths enforce the identical https/loopback floor.
*/
export function isAllowableRedirectUri(value: string): boolean {
let url: URL;
try {
url = new URL(value);
} catch {
return false;
}
if (url.protocol === "https:") return true;
if (
url.protocol === "http:" &&
REDIRECT_LOOPBACK_HOSTS.includes(url.hostname)
) {
return true;
}
return false;
}
/** A `client_id` that is an HTTPS URL is a CIMD client (SEP-991). */
export function isCimdClientId(clientId: string): boolean {
try {
@@ -131,13 +156,16 @@ async function resolveCimdClient(clientId: string): Promise<ClientResolution> {
}
if (!res.ok) return { ok: false, reason: "unknown_client" };
const raw = await res.text();
if (raw.length > CIMD_MAX_BYTES) {
// M3 — enforce the byte cap WHILE reading: reject up front on an oversized
// Content-Length and abort the stream the moment it overflows, so a hostile
// CIMD host cannot buffer gigabytes into memory before a post-hoc check.
const read = await readBodyCapped(res, CIMD_MAX_BYTES);
if (!read.ok) {
return { ok: false, reason: "invalid_metadata" };
}
let doc: Record<string, unknown>;
try {
doc = JSON.parse(raw);
doc = JSON.parse(read.text);
} catch {
return { ok: false, reason: "invalid_metadata" };
}
@@ -148,6 +176,10 @@ async function resolveCimdClient(clientId: string): Promise<ClientResolution> {
}
const redirectUris = asStringArray(doc.redirect_uris);
if (!redirectUris) return { ok: false, reason: "invalid_metadata" };
// L2 — CIMD redirect URIs get the same https/loopback floor DCR enforces.
if (!redirectUris.every(isAllowableRedirectUri)) {
return { ok: false, reason: "invalid_metadata" };
}
return {
ok: true,
+52 -1
View File
@@ -15,9 +15,49 @@
* `resource` value matches the user-entered URL (a Claude.ai requirement).
*/
/**
* Thrown when the MCP/OAuth surface is asked to resolve its canonical origin but
* neither `APP_URL` nor `NEXT_PUBLIC_APP_URL` is configured. The surface fails
* closed in that case (M1): without an operator-pinned origin the issuer,
* endpoint URLs, and RFC 8707 audience would be derived from the attacker-
* influenceable `Host` header, so we refuse to serve rather than trust it.
*/
export class McpOriginNotConfiguredError extends Error {
constructor() {
super(
"APP_URL (or NEXT_PUBLIC_APP_URL) must be set to serve the MCP/OAuth surface",
);
this.name = "McpOriginNotConfiguredError";
}
}
/** The operator-configured origin, env-only — `Host` is never trusted. */
function configuredOrigin(): string | null {
for (const value of [process.env.APP_URL, process.env.NEXT_PUBLIC_APP_URL]) {
const trimmed = value?.trim();
if (!trimmed) continue;
try {
return new URL(trimmed).origin;
} catch {
// try the next candidate
}
}
return null;
}
/** Whether the operator has pinned a canonical origin (M1 fail-closed gate). */
export function isMcpOriginConfigured(): boolean {
return configuredOrigin() !== null;
}
/**
* Resolve the public origin of this deployment, e.g. `https://health.example`.
* Operator config wins; the request URL is the last resort.
*
* Operator config (`APP_URL` → `NEXT_PUBLIC_APP_URL`) is authoritative. The
* request URL is a last resort retained ONLY for non-security-bearing callers;
* every MCP/OAuth entry point first asserts `isMcpOriginConfigured()` and fails
* closed (M1), so on those paths the env value is always what is returned and
* the `Host`-derived fallback is never reached.
*/
export function resolveBaseOrigin(requestUrl?: string): string {
const candidates = [
@@ -38,6 +78,17 @@ export function resolveBaseOrigin(requestUrl?: string): string {
return "http://localhost:3000";
}
/**
* Like `resolveBaseOrigin` but fails closed: throws `McpOriginNotConfiguredError`
* when no operator origin is set. Every MCP/OAuth surface calls this so a
* missing `APP_URL` refuses service instead of trusting the `Host` header (M1).
*/
export function requireBaseOrigin(): string {
const origin = configuredOrigin();
if (!origin) throw new McpOriginNotConfiguredError();
return origin;
}
/**
* The canonical MCP resource identifier (RFC 8707 audience). This is the value
* the AS binds every issued token to and the value a client MUST send as
+190
View File
@@ -0,0 +1,190 @@
/**
* MCP OAuth connections — persistent, revocable, theft-detectable refresh
* state (Phase 3 security fix, H2).
*
* The bridge AS mints stateless `hlrt_` refresh artifacts (see `artifacts.ts`).
* On their own they reference no server row, so they could not be revoked and a
* replayed (already-rotated) artifact was not treated as theft. This module is
* the anchor the artifact lacked: one `McpOAuthConnection` row per connector
* connection that requested `offline_access`.
*
* - `createConnection` is called on the `authorization_code` exchange. It
* records the granted scope/audience and seeds `currentJti` with the jti of
* the first refresh artifact.
* - `rotateConnection` is called on every `refresh_token` exchange. It is the
* reuse-detection gate: a presented jti that is not the connection's
* `currentJti` is a replay of an already-rotated token → the connection is
* revoked (family revocation, mirroring `refresh-token.ts`) and the refresh
* fails. A revoked connection always fails. The happy path advances
* `currentJti` atomically (a `where currentJti = presented` guard so two
* concurrent refreshes cannot both win) and revokes the prior access tokens
* (L4).
* - `revokeConnection` is the kill switch the settings card flips: it stamps
* `revokedAt` and revokes every access token the connection ever issued, so
* a settings "revoke" terminates the whole refresh chain.
*
* The access tokens themselves stay ordinary `hlk_` `ApiToken` rows, linked
* back through `ApiToken.mcpConnectionId`.
*/
import { prisma } from "@/lib/db";
export interface ConnectionRotation {
/** The connection id (`cid`) embedded in the refresh artifact. */
connectionId: string;
/** The jti presented in the refresh artifact being exchanged. */
presentedJti: string;
/** The jti to advance the connection to (the new refresh artifact's jti). */
newJti: string;
/** The client the refresh artifact claims — must match the stored client. */
clientId: string;
/** The user the refresh artifact claims — must match the stored owner. */
userId: string;
}
export type RotationOutcome =
| { ok: true }
| {
ok: false;
reason: "not_found" | "revoked" | "reuse_detected" | "client_mismatch";
};
/** Create the connection anchor for a freshly-granted `offline_access` flow. */
export async function createConnection(args: {
userId: string;
clientId: string;
clientName: string;
scope: string;
resource: string;
jti: string;
}): Promise<string> {
const row = await prisma.mcpOAuthConnection.create({
data: {
userId: args.userId,
clientId: args.clientId,
clientName: args.clientName,
scope: args.scope,
resource: args.resource,
currentJti: args.jti,
},
select: { id: true },
});
return row.id;
}
/**
* Rotate a connection's refresh chain with reuse-detection.
*
* Returns `{ ok: true }` only when the presented jti is the connection's live
* `currentJti` and the connection is not revoked; on success `currentJti` is
* advanced to `newJti` and the connection's prior access tokens are revoked.
* A presented jti that does not match `currentJti` is a replay and revokes the
* connection before returning `reuse_detected`.
*/
export async function rotateConnection(
args: ConnectionRotation,
): Promise<RotationOutcome> {
const connection = await prisma.mcpOAuthConnection.findUnique({
where: { id: args.connectionId },
select: {
id: true,
userId: true,
clientId: true,
currentJti: true,
revokedAt: true,
},
});
if (!connection || connection.userId !== args.userId) {
return { ok: false, reason: "not_found" };
}
if (connection.clientId !== args.clientId) {
return { ok: false, reason: "client_mismatch" };
}
if (connection.revokedAt) {
return { ok: false, reason: "revoked" };
}
if (connection.currentJti !== args.presentedJti) {
// Replay of an already-rotated refresh token — treat as theft and revoke
// the whole connection (reuse-detection family revocation).
await revokeConnectionRow(connection.id);
return { ok: false, reason: "reuse_detected" };
}
// Advance the chain atomically: only the caller presenting the current jti
// wins, so two concurrent refreshes cannot both rotate the same row.
const advanced = await prisma.mcpOAuthConnection.updateMany({
where: {
id: connection.id,
currentJti: args.presentedJti,
revokedAt: null,
},
data: { currentJti: args.newJti, lastUsedAt: new Date() },
});
if (advanced.count === 0) {
return { ok: false, reason: "reuse_detected" };
}
// L4 — revoke the access tokens minted before this rotation so a leaked
// 60-minute access token cannot outlive the refresh that spawned it.
await prisma.apiToken.updateMany({
where: { mcpConnectionId: connection.id, revoked: false },
data: { revoked: true },
});
return { ok: true };
}
/** Internal — stamp `revokedAt` and revoke every linked access token. */
async function revokeConnectionRow(connectionId: string): Promise<void> {
await prisma.mcpOAuthConnection.updateMany({
where: { id: connectionId, revokedAt: null },
data: { revokedAt: new Date() },
});
await prisma.apiToken.updateMany({
where: { mcpConnectionId: connectionId, revoked: false },
data: { revoked: true },
});
}
/**
* Revoke a connection on behalf of its owner (settings "revoke"). Ownership is
* enforced so a connection id alone cannot revoke another user's connection.
* Returns true when a live connection owned by the user was revoked.
*/
export async function revokeConnectionForUser(
userId: string,
connectionId: string,
): Promise<boolean> {
const connection = await prisma.mcpOAuthConnection.findUnique({
where: { id: connectionId },
select: { id: true, userId: true, revokedAt: true },
});
if (!connection || connection.userId !== userId) return false;
await revokeConnectionRow(connection.id);
return true;
}
export interface ConnectionSummary {
id: string;
clientName: string;
scope: string;
createdAt: Date;
lastUsedAt: Date | null;
}
/** The user's live (non-revoked) connector connections for the settings list. */
export async function listConnectionsForUser(
userId: string,
): Promise<ConnectionSummary[]> {
return prisma.mcpOAuthConnection.findMany({
where: { userId, revokedAt: null },
select: {
id: true,
clientName: true,
scope: true,
createdAt: true,
lastUsedAt: true,
},
orderBy: { createdAt: "desc" },
});
}