Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+150
@@ -0,0 +1,150 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
type TokenRow = {
|
||||
clientId: string;
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
revokedAt: Date | null;
|
||||
scopes: string[];
|
||||
createdAt: Date;
|
||||
expiresAt: Date;
|
||||
client: { clientName: string };
|
||||
};
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
accessRows: [] as TokenRow[],
|
||||
refreshRows: [] as TokenRow[],
|
||||
audit: vi.fn(),
|
||||
boundTenantIds: [] as string[],
|
||||
}));
|
||||
|
||||
/**
|
||||
* The fake transaction mirrors the policy instead of answering every query:
|
||||
* a mock that returns rows regardless of the bound tenant/user would hide
|
||||
* exactly the cross-tenant bug this suite is here to catch (AGENTS.md, RLS).
|
||||
*/
|
||||
function matches(row: TokenRow, where: Record<string, unknown>, boundTenantId: string): boolean {
|
||||
if (row.tenantId !== boundTenantId) return false;
|
||||
for (const [key, value] of Object.entries(where)) {
|
||||
if (key === "revokedAt") {
|
||||
if (value === null && row.revokedAt !== null) return false;
|
||||
continue;
|
||||
}
|
||||
if ((row as unknown as Record<string, unknown>)[key] !== value) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: (tenantId: string, callback: (tx: unknown) => unknown) => {
|
||||
mocks.boundTenantIds.push(tenantId);
|
||||
const model = (rows: TokenRow[]) => ({
|
||||
findMany: async ({ where }: { where: Record<string, unknown> }) => rows.filter((row) => matches(row, where, tenantId)),
|
||||
count: async ({ where }: { where: Record<string, unknown> }) => rows.filter((row) => matches(row, where, tenantId)).length,
|
||||
updateMany: async ({ where, data }: { where: Record<string, unknown>; data: { revokedAt: Date } }) => {
|
||||
const hits = rows.filter((row) => matches(row, where, tenantId));
|
||||
for (const row of hits) row.revokedAt = data.revokedAt;
|
||||
return { count: hits.length };
|
||||
},
|
||||
});
|
||||
return callback({
|
||||
mcpOAuthAccessToken: model(mocks.accessRows),
|
||||
mcpOAuthRefreshToken: model(mocks.refreshRows),
|
||||
tenant: { findUnique: async () => ({ name: "Acme", slug: "acme" }) },
|
||||
});
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({
|
||||
createAuditEventInExistingTransaction: (input: unknown) => {
|
||||
mocks.audit(input);
|
||||
return Promise.resolve({});
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/services/mcp/oauth.server", () => ({
|
||||
getMcpOAuthPublicUrls: () => ({ resource: "https://staging-mcp.hivegrid.de" }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/connector/tenantConnector.server", () => ({ tenantHasModule: vi.fn() }));
|
||||
vi.mock("~/utils/loaders.middleware", () => ({ requireAuth: vi.fn() }));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn() }));
|
||||
|
||||
import { loadMcpConnectVM, revokeMcpConnection } from "./connect.server";
|
||||
|
||||
const CTX = { tenantId: "tenant-1", tenantSlug: "acme", tenantName: "Acme", userId: "user-1" };
|
||||
|
||||
function row(overrides: Partial<TokenRow> = {}): TokenRow {
|
||||
return {
|
||||
clientId: "client-1",
|
||||
tenantId: "tenant-1",
|
||||
userId: "user-1",
|
||||
revokedAt: null,
|
||||
scopes: ["mcp:read"],
|
||||
createdAt: new Date("2026-07-20T08:00:00.000Z"),
|
||||
expiresAt: new Date("2026-07-28T18:00:00.000Z"),
|
||||
client: { clientName: "Claude" },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.accessRows = [];
|
||||
mocks.refreshRows = [];
|
||||
mocks.boundTenantIds = [];
|
||||
mocks.audit.mockClear();
|
||||
});
|
||||
|
||||
describe("loadMcpConnectVM", () => {
|
||||
it("lists the current user's own connections only", async () => {
|
||||
mocks.accessRows = [row(), row({ clientId: "client-2", userId: "user-2", client: { clientName: "Fremd" } })];
|
||||
|
||||
const vm = await loadMcpConnectVM(CTX, new Date("2026-07-28T12:00:00.000Z"));
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.connections.map((connection) => connection.id)).toEqual(["client-1"]);
|
||||
});
|
||||
|
||||
it("reads inside the tenant's RLS context", async () => {
|
||||
await loadMcpConnectVM(CTX, new Date("2026-07-28T12:00:00.000Z"));
|
||||
expect(mocks.boundTenantIds).toEqual(["tenant-1"]);
|
||||
});
|
||||
|
||||
it("hands the environment connector URL to the view-model", async () => {
|
||||
const vm = await loadMcpConnectVM(CTX, new Date("2026-07-28T12:00:00.000Z"));
|
||||
expect(vm.data?.connectorUrl).toBe("https://staging-mcp.hivegrid.de");
|
||||
});
|
||||
});
|
||||
|
||||
describe("revokeMcpConnection", () => {
|
||||
it("cuts access and refresh tokens together", async () => {
|
||||
mocks.accessRows = [row()];
|
||||
mocks.refreshRows = [row()];
|
||||
|
||||
const result = await revokeMcpConnection(CTX, "client-1", new Date("2026-07-28T12:00:00.000Z"));
|
||||
|
||||
expect(result.revokedTokens).toBe(1);
|
||||
// A live refresh token would mint a new access token minutes later.
|
||||
expect(mocks.refreshRows[0]?.revokedAt).not.toBeNull();
|
||||
});
|
||||
|
||||
it("refuses to revoke another user's connection", async () => {
|
||||
mocks.accessRows = [row({ userId: "user-2" })];
|
||||
|
||||
await expect(revokeMcpConnection(CTX, "client-1")).rejects.toMatchObject({ name: "CatalogError" });
|
||||
expect(mocks.accessRows[0]?.revokedAt).toBeNull();
|
||||
});
|
||||
|
||||
it("refuses an unknown client id", async () => {
|
||||
await expect(revokeMcpConnection(CTX, "does-not-exist")).rejects.toMatchObject({ name: "CatalogError" });
|
||||
});
|
||||
|
||||
it("writes the audit record in the same transaction", async () => {
|
||||
mocks.accessRows = [row()];
|
||||
|
||||
await revokeMcpConnection(CTX, "client-1");
|
||||
|
||||
expect(mocks.audit).toHaveBeenCalledWith(expect.objectContaining({ action: "mcp.connection.revoke", actorId: "user-1", targetId: "client-1" }));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { createAuditEventInExistingTransaction } from "@hivegrid/db/audit-events.server";
|
||||
import { featureKeys } from "@hivegrid/entitlements";
|
||||
import { buildMcpConnectVM, type McpConnectTokenInput, type McpConnectVM } from "@hivegrid/view-models";
|
||||
import type { Params } from "react-router";
|
||||
|
||||
import { getMcpOAuthPublicUrls } from "~/services/mcp/oauth.server";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
|
||||
/**
|
||||
* Server side of the app-shell "Mit KI verbinden" dialog.
|
||||
*
|
||||
* The MCP runtime lives in its own container on its own host and speaks OAuth
|
||||
* 2.1 with dynamic client registration, so a client (Claude, ChatGPT, Cursor)
|
||||
* onboards itself: it discovers the metadata, registers, and sends the user
|
||||
* through our consent screen. This service therefore never mints credentials —
|
||||
* it hands out the connector URL, lists what the current user already
|
||||
* connected, and lets them cut a connection.
|
||||
*/
|
||||
|
||||
export const MCP_MODULE_KEY = featureKeys.mcp;
|
||||
|
||||
export type McpConnectContext = {
|
||||
readonly tenantId: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly tenantName: string;
|
||||
readonly userId: string;
|
||||
};
|
||||
|
||||
export async function loadMcpConnectContext({ request, params }: { request: Request; params: Params }): Promise<McpConnectContext> {
|
||||
await requireAuth({ request, params });
|
||||
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
|
||||
if (!tenantId || !userInfo.userId) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
// A tenant without the MCP module must not even learn that the connector
|
||||
// exists — 404, not 403 (Bauprinzip A.5.3).
|
||||
if (!(await tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: MCP_MODULE_KEY }))) {
|
||||
throw new CatalogError(foundationErrors.notFound, { module: MCP_MODULE_KEY });
|
||||
}
|
||||
const tenant = await withTenantRLS(tenantId, (tx) => tx.tenant.findUnique({ where: { id: tenantId }, select: { name: true, slug: true } }));
|
||||
if (!tenant) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
return { tenantId, tenantSlug: tenant.slug, tenantName: tenant.name, userId: userInfo.userId };
|
||||
}
|
||||
|
||||
export async function loadMcpConnectVM(ctx: McpConnectContext, now: Date = new Date()): Promise<McpConnectVM> {
|
||||
const tokens = await withTenantRLS(ctx.tenantId, (tx) =>
|
||||
tx.mcpOAuthAccessToken.findMany({
|
||||
// Own connections only: an access token is bound to the user who walked
|
||||
// through consent, so nobody inspects a colleague's AI clients here.
|
||||
where: { tenantId: ctx.tenantId, userId: ctx.userId, revokedAt: null },
|
||||
select: { clientId: true, scopes: true, createdAt: true, expiresAt: true, client: { select: { clientName: true } } },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 200,
|
||||
})
|
||||
);
|
||||
|
||||
return buildMcpConnectVM({
|
||||
connectorUrl: getMcpOAuthPublicUrls().resource,
|
||||
tenantName: ctx.tenantName,
|
||||
appName: loadRequiredWebConfig().appName,
|
||||
docsHref: null,
|
||||
canRevoke: true,
|
||||
nowIso: now.toISOString(),
|
||||
tokens: tokens.map(
|
||||
(token): McpConnectTokenInput => ({
|
||||
clientId: token.clientId,
|
||||
clientName: token.client?.clientName ?? "",
|
||||
scopes: normalizeScopeJson(token.scopes),
|
||||
createdAtIso: token.createdAt.toISOString(),
|
||||
expiresAtIso: token.expiresAt.toISOString(),
|
||||
revoked: false,
|
||||
})
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export type RevokeMcpConnectionResult = { readonly revokedTokens: number };
|
||||
|
||||
/**
|
||||
* Cutting a connection revokes both halves: leaving the refresh token alive
|
||||
* would let the client mint a fresh access token minutes later.
|
||||
*/
|
||||
export async function revokeMcpConnection(ctx: McpConnectContext, clientId: string, now: Date = new Date()): Promise<RevokeMcpConnectionResult> {
|
||||
const trimmed = clientId.trim();
|
||||
if (!trimmed) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
|
||||
return withTenantRLS(ctx.tenantId, async (tx) => {
|
||||
const scope = { clientId: trimmed, tenantId: ctx.tenantId, userId: ctx.userId, revokedAt: null } as const;
|
||||
const owned = await tx.mcpOAuthAccessToken.count({ where: scope });
|
||||
const ownedRefresh = await tx.mcpOAuthRefreshToken.count({ where: scope });
|
||||
if (owned === 0 && ownedRefresh === 0) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
|
||||
const [access] = await Promise.all([
|
||||
tx.mcpOAuthAccessToken.updateMany({ where: scope, data: { revokedAt: now } }),
|
||||
tx.mcpOAuthRefreshToken.updateMany({ where: scope, data: { revokedAt: now } }),
|
||||
]);
|
||||
|
||||
// Same transaction as the revoke itself: a connection must never appear cut
|
||||
// without the audit record that says who cut it.
|
||||
await createAuditEventInExistingTransaction(
|
||||
{
|
||||
tenantId: ctx.tenantId,
|
||||
actorId: ctx.userId,
|
||||
actorType: "user",
|
||||
action: "mcp.connection.revoke",
|
||||
targetType: "McpOAuthClient",
|
||||
targetId: trimmed,
|
||||
sourceModule: "mcp",
|
||||
outcome: "success",
|
||||
dataSensitivity: "internal",
|
||||
metadata: { revokedAccessTokens: access.count },
|
||||
},
|
||||
// Same structural cast the other in-transaction audit writers use: the
|
||||
// Prisma transaction client is wider than the writer's minimal contract.
|
||||
tx as unknown as Parameters<typeof createAuditEventInExistingTransaction>[1]
|
||||
);
|
||||
|
||||
return { revokedTokens: access.count };
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeScopeJson(value: unknown): string[] {
|
||||
if (Array.isArray(value)) {
|
||||
return value.filter((entry): entry is string => typeof entry === "string");
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
return value.split(/\s+/).filter(Boolean);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
// @vitest-environment node
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
checkAuthRateLimit: vi.fn(),
|
||||
consumeMcpOAuthAuthorizationCodeWithRlsBootstrap: vi.fn(),
|
||||
consumeMcpOAuthRefreshTokenWithRlsBootstrap: vi.fn(),
|
||||
createMcpOAuthAuthorizationCode: vi.fn(),
|
||||
findMcpOAuthClient: vi.fn(),
|
||||
issueMcpOAuthTokenPair: vi.fn(),
|
||||
registerMcpOAuthClient: vi.fn(),
|
||||
revokeMcpOAuthTokenWithRlsBootstrap: vi.fn(),
|
||||
getAuthUserWithoutPasswordById: vi.fn(),
|
||||
getTenantByIdOrSlug: vi.fn(),
|
||||
getTenantMembershipByIds: vi.fn(),
|
||||
getTenantsForUser: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/services/auth/auth-rate-limit.server", () => ({
|
||||
checkAuthRateLimit: mocks.checkAuthRateLimit,
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/mcp-oauth.server", () => ({
|
||||
consumeMcpOAuthAuthorizationCodeWithRlsBootstrap: mocks.consumeMcpOAuthAuthorizationCodeWithRlsBootstrap,
|
||||
consumeMcpOAuthRefreshTokenWithRlsBootstrap: mocks.consumeMcpOAuthRefreshTokenWithRlsBootstrap,
|
||||
createMcpOAuthAuthorizationCode: mocks.createMcpOAuthAuthorizationCode,
|
||||
findMcpOAuthClient: mocks.findMcpOAuthClient,
|
||||
issueMcpOAuthTokenPair: mocks.issueMcpOAuthTokenPair,
|
||||
registerMcpOAuthClient: mocks.registerMcpOAuthClient,
|
||||
revokeMcpOAuthTokenWithRlsBootstrap: mocks.revokeMcpOAuthTokenWithRlsBootstrap,
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/db/auth-boundary.server", () => ({
|
||||
getAuthUserWithoutPasswordById: mocks.getAuthUserWithoutPasswordById,
|
||||
getTenantByIdOrSlug: mocks.getTenantByIdOrSlug,
|
||||
getTenantMembershipByIds: mocks.getTenantMembershipByIds,
|
||||
getTenantsForUser: mocks.getTenantsForUser,
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/config", () => ({
|
||||
loadRequiredWebConfig: () => ({
|
||||
routing: {
|
||||
protocol: "https",
|
||||
webAppHost: "app.example.test",
|
||||
appBaseDomain: "example.test",
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
const {
|
||||
MCP_OAUTH_SUPPORTED_SCOPES,
|
||||
McpOAuthError,
|
||||
approveAuthorizeRequest,
|
||||
oauthAuthorizationServerMetadata,
|
||||
registerOAuthClientFromRequest,
|
||||
resolveAuthorizeRequest,
|
||||
resolveMcpOAuthTokenHashSecret,
|
||||
revokeEndpointFromRequest,
|
||||
tokenEndpointFromRequest,
|
||||
} = await import("./oauth.server");
|
||||
|
||||
function registrationRequest(body: Record<string, unknown>) {
|
||||
return new Request("https://app.example.test/oauth/register", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", "cf-connecting-ip": "203.0.113.10" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
delete process.env.MCP_OAUTH_TOKEN_HASH_SECRET;
|
||||
delete process.env.API_KEY_HASH_SECRET;
|
||||
mocks.checkAuthRateLimit.mockResolvedValue({ allowed: true });
|
||||
mocks.registerMcpOAuthClient.mockResolvedValue({
|
||||
id: "client_row_1",
|
||||
clientId: "hgomc_client_1",
|
||||
clientName: "Safe Client",
|
||||
redirectUris: ["https://client.example/callback"],
|
||||
scopes: ["mcp:read"],
|
||||
active: true,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("MCP OAuth dynamic client registration hardening", () => {
|
||||
it("rate-limits before parsing or persisting registration metadata", async () => {
|
||||
mocks.checkAuthRateLimit.mockResolvedValue({ allowed: false, retryAfterSeconds: 120 });
|
||||
|
||||
const response = await registerOAuthClientFromRequest(registrationRequest({ redirect_uris: ["https://client.example/callback"] }));
|
||||
|
||||
expect(response.status).toBe(429);
|
||||
expect(response.headers.get("Retry-After")).toBe("120");
|
||||
expect(response.headers.get("Cache-Control")).toBe("no-store");
|
||||
expect(mocks.registerMcpOAuthClient).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("persists only bounded normalized metadata", async () => {
|
||||
const response = await registerOAuthClientFromRequest(
|
||||
registrationRequest({
|
||||
client_name: " Safe Client ",
|
||||
redirect_uris: ["https://client.example/callback"],
|
||||
scope: "mcp:read",
|
||||
grant_types: ["authorization_code", "refresh_token"],
|
||||
contacts: ["ops@example.com"],
|
||||
client_uri: "https://client.example",
|
||||
attacker_nested_blob: { value: "must-not-be-persisted" },
|
||||
})
|
||||
);
|
||||
|
||||
expect(response.status).toBe(201);
|
||||
expect(mocks.checkAuthRateLimit).toHaveBeenCalledWith(expect.objectContaining({ action: "oauth-register" }));
|
||||
expect(mocks.registerMcpOAuthClient).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
clientName: "Safe Client",
|
||||
contacts: ["ops@example.com"],
|
||||
metadata: expect.objectContaining({ client_name: "Safe Client", client_uri: "https://client.example" }),
|
||||
})
|
||||
);
|
||||
const input = mocks.registerMcpOAuthClient.mock.calls[0]?.[0];
|
||||
expect(JSON.stringify(input.metadata)).not.toContain("attacker_nested_blob");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ client_name: "x".repeat(201), redirect_uris: ["https://client.example/callback"] }, "invalid_client_metadata", "client_name"],
|
||||
[{ redirect_uris: Array.from({ length: 11 }, (_, index) => `https://client${index}.example/callback`) }, "invalid_client_metadata", "redirect_uris"],
|
||||
[{ redirect_uris: ["https://user:pass@client.example/callback"] }, "invalid_redirect_uri", "credentials"],
|
||||
[{ redirect_uris: ["https://client.example/callback#fragment"] }, "invalid_redirect_uri", "fragment"],
|
||||
[
|
||||
{ redirect_uris: ["https://client.example/callback"], contacts: Array.from({ length: 11 }, () => "ops@example.com") },
|
||||
"invalid_client_metadata",
|
||||
"contacts",
|
||||
],
|
||||
[{ redirect_uris: ["https://client.example/callback"], scope: "x".repeat(1_025) }, "invalid_client_metadata", "scope"],
|
||||
[{ redirect_uris: ["https://client.example/callback"], grant_types: ["password"] }, "invalid_client_metadata", "unsupported"],
|
||||
])("rejects oversized or ambiguous registration metadata", async (body, expectedError, expectedMessage) => {
|
||||
await expect(registerOAuthClientFromRequest(registrationRequest(body))).rejects.toMatchObject({
|
||||
name: McpOAuthError.name,
|
||||
error: expectedError,
|
||||
message: expect.stringContaining(expectedMessage),
|
||||
});
|
||||
expect(mocks.registerMcpOAuthClient).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("MCP OAuth public endpoint throttling", () => {
|
||||
it.each([
|
||||
["token", tokenEndpointFromRequest, "oauth-token"],
|
||||
["revoke", revokeEndpointFromRequest, "oauth-revoke"],
|
||||
] as const)("rate-limits the %s endpoint before parsing or querying tokens", async (_name, handler, action) => {
|
||||
mocks.checkAuthRateLimit.mockResolvedValueOnce({ allowed: false, retryAfterSeconds: 45 });
|
||||
const request = new Request(`https://app.example.test/oauth/${_name}`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded", "cf-connecting-ip": "203.0.113.10" },
|
||||
body: "token=attacker-controlled&grant_type=refresh_token",
|
||||
});
|
||||
|
||||
const response = await handler(request);
|
||||
|
||||
expect(response.status).toBe(429);
|
||||
expect(response.headers.get("Retry-After")).toBe("45");
|
||||
expect(response.headers.get("Cache-Control")).toBe("no-store");
|
||||
expect(mocks.checkAuthRateLimit).toHaveBeenCalledWith(expect.objectContaining({ action }));
|
||||
expect(mocks.revokeMcpOAuthTokenWithRlsBootstrap).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("MCP OAuth token-secret boundary", () => {
|
||||
it("accepts only an explicitly configured secret of at least 32 UTF-8 bytes", () => {
|
||||
expect(() => resolveMcpOAuthTokenHashSecret({ MCP_OAUTH_TOKEN_HASH_SECRET: "short" })).toThrow(
|
||||
expect.objectContaining({ error: "server_error", status: 503 })
|
||||
);
|
||||
expect(resolveMcpOAuthTokenHashSecret({ MCP_OAUTH_TOKEN_HASH_SECRET: "0123456789abcdef0123456789abcdef" })).toBe("0123456789abcdef0123456789abcdef");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["authorization_code", "code=code_1&client_id=client_1&redirect_uri=https%3A%2F%2Fclient.example%2Fcb&code_verifier=verifier"],
|
||||
["refresh_token", "refresh_token=refresh_1&client_id=client_1"],
|
||||
])("fails the %s token flow before any token lookup when the secret is weak", async (grantType, fields) => {
|
||||
process.env.MCP_OAUTH_TOKEN_HASH_SECRET = "too-short";
|
||||
const request = new Request("https://app.example.test/oauth/token", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body: `grant_type=${grantType}&${fields}`,
|
||||
});
|
||||
|
||||
await expect(tokenEndpointFromRequest(request)).rejects.toMatchObject({ error: "server_error", status: 503 });
|
||||
expect(mocks.consumeMcpOAuthAuthorizationCodeWithRlsBootstrap).not.toHaveBeenCalled();
|
||||
expect(mocks.consumeMcpOAuthRefreshTokenWithRlsBootstrap).not.toHaveBeenCalled();
|
||||
expect(mocks.issueMcpOAuthTokenPair).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails authorization approval and revocation before code/token persistence when the secret is absent", async () => {
|
||||
const approval = new Request("https://app.example.test/oauth/authorize/approve", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body: "decision=approve",
|
||||
});
|
||||
const revocation = new Request("https://app.example.test/oauth/revoke", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body: "token=access_1",
|
||||
});
|
||||
|
||||
await expect(approveAuthorizeRequest(approval, "user_1")).rejects.toMatchObject({ error: "server_error", status: 503 });
|
||||
await expect(revokeEndpointFromRequest(revocation)).rejects.toMatchObject({ error: "server_error", status: 503 });
|
||||
expect(mocks.findMcpOAuthClient).not.toHaveBeenCalled();
|
||||
expect(mocks.createMcpOAuthAuthorizationCode).not.toHaveBeenCalled();
|
||||
expect(mocks.revokeMcpOAuthTokenWithRlsBootstrap).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("MCP OAuth metadata", () => {
|
||||
it("advertises the complete supported scope contract", () => {
|
||||
vi.stubEnv("MCP_AUTHORIZATION_SERVER_URL", "https://auth.example.test");
|
||||
vi.stubEnv("MCP_RESOURCE_URL", "https://mcp.example.test");
|
||||
|
||||
const expectedScopes = [
|
||||
"mcp:read",
|
||||
"mcp:write",
|
||||
"mcp:lead:read",
|
||||
"mcp:lead:create",
|
||||
"mcp:contact:read",
|
||||
"mcp:project:read",
|
||||
"mcp:project:write",
|
||||
"mcp:pipeline:read",
|
||||
"mcp:activity:read",
|
||||
"mcp:activity:write",
|
||||
"mcp:task:read",
|
||||
"mcp:task:write",
|
||||
];
|
||||
|
||||
expect(MCP_OAUTH_SUPPORTED_SCOPES).toEqual(expectedScopes);
|
||||
expect(oauthAuthorizationServerMetadata()).toMatchObject({
|
||||
issuer: "https://auth.example.test",
|
||||
scopes_supported: expectedScopes,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("MCP OAuth tenant resolution", () => {
|
||||
const TENANTS = [
|
||||
{ id: "tenant-a", slug: "acme", name: "Acme" },
|
||||
{ id: "tenant-b", slug: "globex", name: "Globex" },
|
||||
];
|
||||
|
||||
function authorizeUrl(extra: Record<string, string> = {}): URL {
|
||||
const url = new URL("https://app.example.test/oauth/authorize");
|
||||
const params: Record<string, string> = {
|
||||
response_type: "code",
|
||||
client_id: "hgomc_client_1",
|
||||
redirect_uri: "https://client.example/callback",
|
||||
code_challenge: "challenge",
|
||||
code_challenge_method: "S256",
|
||||
scope: "mcp:read",
|
||||
...extra,
|
||||
};
|
||||
for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
|
||||
return url;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.findMcpOAuthClient.mockResolvedValue({
|
||||
id: "client_row_1",
|
||||
clientId: "hgomc_client_1",
|
||||
clientName: "Claude",
|
||||
redirectUris: ["https://client.example/callback"],
|
||||
scopes: ["mcp:read"],
|
||||
active: true,
|
||||
});
|
||||
mocks.getTenantsForUser.mockResolvedValue(TENANTS);
|
||||
mocks.getAuthUserWithoutPasswordById.mockResolvedValue({ defaultTenantId: null });
|
||||
});
|
||||
|
||||
it("connects the tenant the user is currently working in, not the first membership", async () => {
|
||||
mocks.getAuthUserWithoutPasswordById.mockResolvedValue({ defaultTenantId: "tenant-b" });
|
||||
|
||||
const resolved = await resolveAuthorizeRequest(authorizeUrl(), "user-1");
|
||||
|
||||
expect(resolved.tenant).toEqual({ id: "tenant-b", slug: "globex", name: "Globex" });
|
||||
});
|
||||
|
||||
it("falls back to the first membership when no active tenant is known", async () => {
|
||||
const resolved = await resolveAuthorizeRequest(authorizeUrl(), "user-1");
|
||||
|
||||
expect(resolved.tenant.id).toBe("tenant-a");
|
||||
});
|
||||
|
||||
it("ignores an active tenant the user is no longer a member of", async () => {
|
||||
mocks.getAuthUserWithoutPasswordById.mockResolvedValue({ defaultTenantId: "tenant-gone" });
|
||||
|
||||
const resolved = await resolveAuthorizeRequest(authorizeUrl(), "user-1");
|
||||
|
||||
expect(resolved.tenant.id).toBe("tenant-a");
|
||||
});
|
||||
|
||||
it("still honours an explicit tenant parameter over the active tenant", async () => {
|
||||
mocks.getAuthUserWithoutPasswordById.mockResolvedValue({ defaultTenantId: "tenant-b" });
|
||||
mocks.getTenantByIdOrSlug.mockResolvedValue({ id: "tenant-a", slug: "acme", name: "Acme" });
|
||||
mocks.getTenantMembershipByIds.mockResolvedValue({ id: "membership-1" });
|
||||
|
||||
const resolved = await resolveAuthorizeRequest(authorizeUrl({ tenant: "acme" }), "user-1");
|
||||
|
||||
expect(resolved.tenant.id).toBe("tenant-a");
|
||||
});
|
||||
});
|
||||
+245
-65
@@ -1,18 +1,19 @@
|
||||
import { redirect } from "react-router";
|
||||
import {
|
||||
consumeMcpOAuthAuthorizationCode,
|
||||
consumeMcpOAuthRefreshToken,
|
||||
consumeMcpOAuthAuthorizationCodeWithRlsBootstrap,
|
||||
consumeMcpOAuthRefreshTokenWithRlsBootstrap,
|
||||
createMcpOAuthAuthorizationCode,
|
||||
findMcpOAuthClient,
|
||||
issueMcpOAuthTokenPair,
|
||||
registerMcpOAuthClient,
|
||||
revokeMcpOAuthToken,
|
||||
verifyMcpOAuthPkceS256,
|
||||
revokeMcpOAuthTokenWithRlsBootstrap,
|
||||
type McpOAuthClientSummary,
|
||||
} from "@hivegrid/db/mcp-oauth.server";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { getTenantByIdOrSlug, getTenantMembershipByIds, getTenantsForUser } from "@hivegrid/db/auth-boundary.server";
|
||||
import { getAuthUserWithoutPasswordById, getTenantByIdOrSlug, getTenantMembershipByIds, getTenantsForUser } from "@hivegrid/db/auth-boundary.server";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { checkAuthRateLimit } from "~/services/auth/auth-rate-limit.server";
|
||||
|
||||
export const MCP_OAUTH_SUPPORTED_SCOPES = [
|
||||
"mcp:read",
|
||||
@@ -23,11 +24,28 @@ export const MCP_OAUTH_SUPPORTED_SCOPES = [
|
||||
"mcp:project:read",
|
||||
"mcp:project:write",
|
||||
"mcp:pipeline:read",
|
||||
"mcp:activity:read",
|
||||
"mcp:activity:write",
|
||||
"mcp:task:read",
|
||||
"mcp:task:write",
|
||||
] as const;
|
||||
|
||||
const DEFAULT_SCOPE = "mcp:read";
|
||||
const SUPPORTED_SCOPE_SET = new Set<string>(MCP_OAUTH_SUPPORTED_SCOPES);
|
||||
const OAUTH_REGISTRATION_RATE_LIMIT = 60;
|
||||
const OAUTH_REGISTRATION_RATE_WINDOW_MS = 60 * 60 * 1000;
|
||||
const OAUTH_TOKEN_RATE_LIMIT = 120;
|
||||
const OAUTH_TOKEN_RATE_WINDOW_MS = 60 * 1000;
|
||||
const OAUTH_REVOKE_RATE_LIMIT = 120;
|
||||
const OAUTH_REVOKE_RATE_WINDOW_MS = 60 * 1000;
|
||||
const OAUTH_CLIENT_NAME_MAX_LENGTH = 200;
|
||||
const OAUTH_REDIRECT_URI_MAX_COUNT = 10;
|
||||
const OAUTH_REDIRECT_URI_MAX_LENGTH = 2_048;
|
||||
const OAUTH_CONTACT_MAX_COUNT = 10;
|
||||
const OAUTH_CONTACT_MAX_LENGTH = 320;
|
||||
const OAUTH_SCOPE_MAX_LENGTH = 1_024;
|
||||
const OAUTH_METADATA_STRING_MAX_LENGTH = 2_048;
|
||||
const OAUTH_METADATA_STRING_KEYS = ["client_uri", "logo_uri", "tos_uri", "policy_uri", "software_id", "software_version"] as const;
|
||||
|
||||
export type McpOAuthAuthorizeRequest = {
|
||||
responseType: "code";
|
||||
@@ -141,6 +159,7 @@ export async function resolveAuthorizeRequest(url: URL, userId: string): Promise
|
||||
}
|
||||
|
||||
export async function approveAuthorizeRequest(request: Request, userId: string): Promise<Response> {
|
||||
const tokenHashSecret = resolveMcpOAuthTokenHashSecret();
|
||||
const form = await request.formData();
|
||||
const url = new URL("/oauth/authorize", request.url);
|
||||
for (const key of ["response_type", "client_id", "redirect_uri", "scope", "state", "code_challenge", "code_challenge_method", "resource", "tenant"]) {
|
||||
@@ -154,35 +173,64 @@ export async function approveAuthorizeRequest(request: Request, userId: string):
|
||||
throw redirect(withOAuthRedirectParams(resolved.redirectUri, { error: "access_denied", state: resolved.state }));
|
||||
}
|
||||
|
||||
const { code } = await createMcpOAuthAuthorizationCode({
|
||||
clientId: resolved.client.id,
|
||||
userId,
|
||||
tenantId: resolved.tenant.id,
|
||||
tenantSlug: resolved.tenant.slug,
|
||||
redirectUri: resolved.redirectUri,
|
||||
scopes: resolved.scopes,
|
||||
resource: resolved.resource,
|
||||
codeChallenge: resolved.codeChallenge,
|
||||
codeChallengeMethod: "S256",
|
||||
secret: getMcpOAuthTokenHashSecret(),
|
||||
});
|
||||
const { code } = await runWithRlsContext({ tenantId: resolved.tenant.id, userId }, () =>
|
||||
createMcpOAuthAuthorizationCode({
|
||||
clientId: resolved.client.id,
|
||||
userId,
|
||||
tenantId: resolved.tenant.id,
|
||||
tenantSlug: resolved.tenant.slug,
|
||||
redirectUri: resolved.redirectUri,
|
||||
scopes: resolved.scopes,
|
||||
resource: resolved.resource,
|
||||
codeChallenge: resolved.codeChallenge,
|
||||
codeChallengeMethod: "S256",
|
||||
secret: tokenHashSecret,
|
||||
})
|
||||
);
|
||||
|
||||
throw redirect(withOAuthRedirectParams(resolved.redirectUri, { code, state: resolved.state }));
|
||||
}
|
||||
|
||||
export async function registerOAuthClientFromRequest(request: Request): Promise<Response> {
|
||||
const rateLimit = await checkAuthRateLimit({
|
||||
request,
|
||||
action: "oauth-register",
|
||||
limit: OAUTH_REGISTRATION_RATE_LIMIT,
|
||||
windowMs: OAUTH_REGISTRATION_RATE_WINDOW_MS,
|
||||
});
|
||||
if (!rateLimit.allowed) {
|
||||
return new Response(JSON.stringify({ error: "rate_limited", error_description: "OAuth client registration rate limit exceeded." }), {
|
||||
status: 429,
|
||||
headers: {
|
||||
"Cache-Control": "no-store",
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Retry-After": String(rateLimit.retryAfterSeconds),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const body = await readJson(request);
|
||||
const redirectUris = normalizeRedirectUris(body.redirect_uris);
|
||||
const scopes = parseScopes(typeof body.scope === "string" ? body.scope : undefined);
|
||||
const rawScope = optionalBoundedString(body.scope, "scope", OAUTH_SCOPE_MAX_LENGTH);
|
||||
const scopes = parseScopes(rawScope);
|
||||
assertScopesSupported(scopes);
|
||||
const grantTypes = normalizeGrantTypes(body.grant_types);
|
||||
const clientName = normalizeClientName(body.client_name);
|
||||
const contacts = normalizeContacts(body.contacts);
|
||||
const metadata = normalizeClientMetadata(body, {
|
||||
clientName,
|
||||
contacts,
|
||||
grantTypes,
|
||||
redirectUris,
|
||||
scopes,
|
||||
});
|
||||
const client = await registerMcpOAuthClient({
|
||||
clientName: typeof body.client_name === "string" && body.client_name.trim() ? body.client_name.trim() : "MCP Client",
|
||||
clientName,
|
||||
redirectUris,
|
||||
scopes,
|
||||
grantTypes,
|
||||
contacts: Array.isArray(body.contacts) ? body.contacts.filter((item): item is string => typeof item === "string") : undefined,
|
||||
metadata: body as Prisma.InputJsonObject,
|
||||
contacts,
|
||||
metadata,
|
||||
});
|
||||
return json(
|
||||
{
|
||||
@@ -195,27 +243,49 @@ export async function registerOAuthClientFromRequest(request: Request): Promise<
|
||||
token_endpoint_auth_method: "none",
|
||||
scope: client.scopes.join(" "),
|
||||
},
|
||||
201,
|
||||
201
|
||||
);
|
||||
}
|
||||
|
||||
export async function tokenEndpointFromRequest(request: Request): Promise<Response> {
|
||||
const rateLimit = await checkAuthRateLimit({
|
||||
request,
|
||||
action: "oauth-token",
|
||||
limit: OAUTH_TOKEN_RATE_LIMIT,
|
||||
windowMs: OAUTH_TOKEN_RATE_WINDOW_MS,
|
||||
});
|
||||
if (!rateLimit.allowed) {
|
||||
return oauthRateLimitedResponse(rateLimit.retryAfterSeconds);
|
||||
}
|
||||
|
||||
const tokenHashSecret = resolveMcpOAuthTokenHashSecret();
|
||||
const form = await request.formData();
|
||||
const grantType = stringFormValue(form, "grant_type");
|
||||
if (grantType === "authorization_code") {
|
||||
return exchangeAuthorizationCode(form);
|
||||
return exchangeAuthorizationCode(form, tokenHashSecret);
|
||||
}
|
||||
if (grantType === "refresh_token") {
|
||||
return exchangeRefreshToken(form);
|
||||
return exchangeRefreshToken(form, tokenHashSecret);
|
||||
}
|
||||
return oauthJsonError("unsupported_grant_type", "Unsupported grant_type.", 400);
|
||||
}
|
||||
|
||||
export async function revokeEndpointFromRequest(request: Request): Promise<Response> {
|
||||
const rateLimit = await checkAuthRateLimit({
|
||||
request,
|
||||
action: "oauth-revoke",
|
||||
limit: OAUTH_REVOKE_RATE_LIMIT,
|
||||
windowMs: OAUTH_REVOKE_RATE_WINDOW_MS,
|
||||
});
|
||||
if (!rateLimit.allowed) {
|
||||
return oauthRateLimitedResponse(rateLimit.retryAfterSeconds);
|
||||
}
|
||||
|
||||
const tokenHashSecret = resolveMcpOAuthTokenHashSecret();
|
||||
const form = await request.formData();
|
||||
const token = stringFormValue(form, "token");
|
||||
if (token) {
|
||||
await revokeMcpOAuthToken(token, getMcpOAuthTokenHashSecret());
|
||||
await revokeMcpOAuthTokenWithRlsBootstrap(token, tokenHashSecret);
|
||||
}
|
||||
return new Response(null, { status: 200 });
|
||||
}
|
||||
@@ -224,52 +294,69 @@ export function oauthJsonError(error: string, description: string, status = 400)
|
||||
return json({ error, error_description: description }, status);
|
||||
}
|
||||
|
||||
async function exchangeAuthorizationCode(form: FormData): Promise<Response> {
|
||||
function oauthRateLimitedResponse(retryAfterSeconds: number): Response {
|
||||
const response = oauthJsonError("rate_limited", "OAuth endpoint rate limit exceeded.", 429);
|
||||
response.headers.set("Retry-After", String(retryAfterSeconds));
|
||||
return response;
|
||||
}
|
||||
|
||||
async function exchangeAuthorizationCode(form: FormData, tokenHashSecret: string): Promise<Response> {
|
||||
const code = requiredFormValue(form, "code");
|
||||
const clientId = requiredFormValue(form, "client_id");
|
||||
const redirectUri = requiredFormValue(form, "redirect_uri");
|
||||
const codeVerifier = requiredFormValue(form, "code_verifier");
|
||||
const consumed = await consumeMcpOAuthAuthorizationCode(code, getMcpOAuthTokenHashSecret());
|
||||
if (!consumed || consumed.client.clientId !== clientId || consumed.redirectUri !== redirectUri) {
|
||||
const consumed = await consumeMcpOAuthAuthorizationCodeWithRlsBootstrap({
|
||||
code,
|
||||
secret: tokenHashSecret,
|
||||
clientId,
|
||||
redirectUri,
|
||||
codeVerifier,
|
||||
});
|
||||
if (!consumed) {
|
||||
return oauthJsonError("invalid_grant", "Authorization code is invalid, expired, or already used.", 400);
|
||||
}
|
||||
if (!verifyMcpOAuthPkceS256(codeVerifier, consumed.codeChallenge)) {
|
||||
return oauthJsonError("invalid_grant", "PKCE verification failed.", 400);
|
||||
}
|
||||
const pair = await issueMcpOAuthTokenPair({
|
||||
clientId: consumed.client.id,
|
||||
userId: consumed.userId,
|
||||
tenantId: consumed.tenantId,
|
||||
tenantSlug: consumed.tenantSlug,
|
||||
scopes: consumed.scopes,
|
||||
resource: consumed.resource,
|
||||
secret: getMcpOAuthTokenHashSecret(),
|
||||
});
|
||||
const pair = await runWithRlsContext({ tenantId: consumed.tenantId, userId: consumed.userId }, () =>
|
||||
issueMcpOAuthTokenPair({
|
||||
clientId: consumed.client.id,
|
||||
userId: consumed.userId,
|
||||
tenantId: consumed.tenantId,
|
||||
tenantSlug: consumed.tenantSlug,
|
||||
scopes: consumed.scopes,
|
||||
resource: consumed.resource,
|
||||
secret: tokenHashSecret,
|
||||
})
|
||||
);
|
||||
return tokenResponse(pair.accessToken, pair.refreshToken, pair.accessTokenExpiresIn, consumed.scopes, consumed.resource);
|
||||
}
|
||||
|
||||
async function exchangeRefreshToken(form: FormData): Promise<Response> {
|
||||
async function exchangeRefreshToken(form: FormData, tokenHashSecret: string): Promise<Response> {
|
||||
const refreshToken = requiredFormValue(form, "refresh_token");
|
||||
const clientId = requiredFormValue(form, "client_id");
|
||||
const consumed = await consumeMcpOAuthRefreshToken(refreshToken, getMcpOAuthTokenHashSecret());
|
||||
if (!consumed || consumed.client.clientId !== clientId) {
|
||||
const consumed = await consumeMcpOAuthRefreshTokenWithRlsBootstrap({
|
||||
token: refreshToken,
|
||||
secret: tokenHashSecret,
|
||||
clientId,
|
||||
});
|
||||
if (!consumed) {
|
||||
return oauthJsonError("invalid_grant", "Refresh token is invalid, expired, or already rotated.", 400);
|
||||
}
|
||||
// A deactivated tenant is an operator kill-switch — do not let a rotating
|
||||
// refresh token keep minting fresh access tokens for it indefinitely.
|
||||
const tenant = await getTenantByIdOrSlug(consumed.tenantId);
|
||||
const tenant = await runWithRlsContext({ tenantId: consumed.tenantId, userId: consumed.userId }, () => getTenantByIdOrSlug(consumed.tenantId));
|
||||
if (!tenant || tenant.deactivatedReason) {
|
||||
return oauthJsonError("invalid_grant", "Tenant is deactivated.", 400);
|
||||
}
|
||||
const pair = await issueMcpOAuthTokenPair({
|
||||
clientId: consumed.client.id,
|
||||
userId: consumed.userId,
|
||||
tenantId: consumed.tenantId,
|
||||
tenantSlug: consumed.tenantSlug,
|
||||
scopes: consumed.scopes,
|
||||
resource: consumed.resource,
|
||||
secret: getMcpOAuthTokenHashSecret(),
|
||||
});
|
||||
const pair = await runWithRlsContext({ tenantId: consumed.tenantId, userId: consumed.userId }, () =>
|
||||
issueMcpOAuthTokenPair({
|
||||
clientId: consumed.client.id,
|
||||
userId: consumed.userId,
|
||||
tenantId: consumed.tenantId,
|
||||
tenantSlug: consumed.tenantSlug,
|
||||
scopes: consumed.scopes,
|
||||
resource: consumed.resource,
|
||||
secret: tokenHashSecret,
|
||||
})
|
||||
);
|
||||
return tokenResponse(pair.accessToken, pair.refreshToken, pair.accessTokenExpiresIn, consumed.scopes, consumed.resource);
|
||||
}
|
||||
|
||||
@@ -284,8 +371,14 @@ function tokenResponse(accessToken: string, refreshToken: string, expiresIn: num
|
||||
});
|
||||
}
|
||||
|
||||
function getMcpOAuthTokenHashSecret(): string | undefined {
|
||||
return process.env.MCP_OAUTH_TOKEN_HASH_SECRET ?? process.env.API_KEY_HASH_SECRET;
|
||||
export function resolveMcpOAuthTokenHashSecret(
|
||||
env: Partial<Record<"MCP_OAUTH_TOKEN_HASH_SECRET" | "API_KEY_HASH_SECRET", string | undefined>> = process.env
|
||||
): string {
|
||||
const secret = (env.MCP_OAUTH_TOKEN_HASH_SECRET ?? env.API_KEY_HASH_SECRET)?.trim();
|
||||
if (!secret || Buffer.byteLength(secret, "utf8") < 32) {
|
||||
throw new McpOAuthError("server_error", "OAuth token protection is unavailable.", 503);
|
||||
}
|
||||
return secret;
|
||||
}
|
||||
|
||||
async function resolveAuthorizeTenant(tenantParam: string | null, userId: string): Promise<{ id: string; slug: string; name: string }> {
|
||||
@@ -301,8 +394,19 @@ async function resolveAuthorizeTenant(tenantParam: string | null, userId: string
|
||||
return { id: tenant.id, slug: tenant.slug, name: tenant.name };
|
||||
}
|
||||
|
||||
// Claude, ChatGPT and Cursor build the authorize URL from discovery metadata,
|
||||
// so they never send a `tenant`. Falling back to the first membership would
|
||||
// silently connect a multi-tenant user to the wrong workspace, so prefer the
|
||||
// tenant they are actually working in: `User.defaultTenantId` is rewritten on
|
||||
// every tenant page view (see `app.$tenant.tsx`) and is the closest thing to
|
||||
// "where the user is right now". Membership is re-checked either way.
|
||||
const tenants = await getTenantsForUser(userId);
|
||||
const tenant = tenants[0];
|
||||
if (tenants.length === 0) {
|
||||
throw new McpOAuthError("access_denied", "Current user has no active tenant.", 403);
|
||||
}
|
||||
|
||||
const activeTenantId = (await getAuthUserWithoutPasswordById(userId))?.defaultTenantId ?? null;
|
||||
const tenant = tenants.find((candidate) => candidate.id === activeTenantId) ?? tenants[0];
|
||||
if (!tenant) {
|
||||
throw new McpOAuthError("access_denied", "Current user has no active tenant.", 403);
|
||||
}
|
||||
@@ -336,7 +440,10 @@ function normalizeRedirectUris(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) {
|
||||
throw new McpOAuthError("invalid_client_metadata", "redirect_uris must be an array.");
|
||||
}
|
||||
const redirectUris = value.filter((item): item is string => typeof item === "string").map((item) => item.trim()).filter(Boolean);
|
||||
if (value.length > OAUTH_REDIRECT_URI_MAX_COUNT || value.some((item) => typeof item !== "string")) {
|
||||
throw new McpOAuthError("invalid_client_metadata", `redirect_uris must contain at most ${OAUTH_REDIRECT_URI_MAX_COUNT} strings.`);
|
||||
}
|
||||
const redirectUris = value.map((item) => (item as string).trim()).filter(Boolean);
|
||||
if (redirectUris.length === 0) {
|
||||
throw new McpOAuthError("invalid_client_metadata", "At least one redirect_uri is required.");
|
||||
}
|
||||
@@ -347,17 +454,24 @@ function normalizeRedirectUris(value: unknown): string[] {
|
||||
}
|
||||
|
||||
function assertAllowedRedirectUri(uri: string) {
|
||||
if (uri.length > OAUTH_REDIRECT_URI_MAX_LENGTH) {
|
||||
throw new McpOAuthError("invalid_redirect_uri", `redirect_uri must not exceed ${OAUTH_REDIRECT_URI_MAX_LENGTH} characters.`);
|
||||
}
|
||||
let parsed: URL;
|
||||
try {
|
||||
const parsed = new URL(uri);
|
||||
if (parsed.protocol === "https:") {
|
||||
return;
|
||||
}
|
||||
if (parsed.protocol === "http:" && ["localhost", "127.0.0.1", "::1"].includes(parsed.hostname)) {
|
||||
return;
|
||||
}
|
||||
parsed = new URL(uri);
|
||||
} catch {
|
||||
throw new McpOAuthError("invalid_redirect_uri", "redirect_uri must be an absolute URL.");
|
||||
}
|
||||
if (parsed.username || parsed.password || parsed.hash) {
|
||||
throw new McpOAuthError("invalid_redirect_uri", "redirect_uri must not contain credentials or a fragment.");
|
||||
}
|
||||
if (parsed.protocol === "https:") {
|
||||
return;
|
||||
}
|
||||
if (parsed.protocol === "http:" && ["localhost", "127.0.0.1", "::1", "[::1]"].includes(parsed.hostname)) {
|
||||
return;
|
||||
}
|
||||
throw new McpOAuthError("invalid_redirect_uri", "redirect_uri must use https or localhost http.");
|
||||
}
|
||||
|
||||
@@ -365,11 +479,77 @@ function normalizeGrantTypes(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) {
|
||||
return ["authorization_code", "refresh_token"];
|
||||
}
|
||||
const requested = value.filter((item): item is string => typeof item === "string");
|
||||
if (value.length > 2 || value.some((item) => typeof item !== "string")) {
|
||||
throw new McpOAuthError("invalid_client_metadata", "grant_types must contain at most two strings.");
|
||||
}
|
||||
const requested = value as string[];
|
||||
if (requested.some((item) => item !== "authorization_code" && item !== "refresh_token")) {
|
||||
throw new McpOAuthError("invalid_client_metadata", "grant_types contains an unsupported grant.");
|
||||
}
|
||||
const allowed = requested.filter((item) => item === "authorization_code" || item === "refresh_token");
|
||||
return allowed.includes("authorization_code") ? [...new Set(allowed)] : ["authorization_code", "refresh_token"];
|
||||
}
|
||||
|
||||
function normalizeClientName(value: unknown): string {
|
||||
if (value === undefined || value === null || value === "") return "MCP Client";
|
||||
if (typeof value !== "string") {
|
||||
throw new McpOAuthError("invalid_client_metadata", "client_name must be a string.");
|
||||
}
|
||||
const name = value.trim();
|
||||
if (!name || name.length > OAUTH_CLIENT_NAME_MAX_LENGTH || /[\u0000-\u001f\u007f]/u.test(name)) {
|
||||
throw new McpOAuthError("invalid_client_metadata", `client_name must contain 1-${OAUTH_CLIENT_NAME_MAX_LENGTH} printable characters.`);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
function normalizeContacts(value: unknown): string[] | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
if (!Array.isArray(value) || value.length > OAUTH_CONTACT_MAX_COUNT || value.some((item) => typeof item !== "string")) {
|
||||
throw new McpOAuthError("invalid_client_metadata", `contacts must contain at most ${OAUTH_CONTACT_MAX_COUNT} strings.`);
|
||||
}
|
||||
const contacts = value.map((item) => (item as string).trim()).filter(Boolean);
|
||||
if (contacts.some((contact) => contact.length > OAUTH_CONTACT_MAX_LENGTH || /[\u0000-\u001f\u007f]/u.test(contact))) {
|
||||
throw new McpOAuthError("invalid_client_metadata", `contacts entries must not exceed ${OAUTH_CONTACT_MAX_LENGTH} printable characters.`);
|
||||
}
|
||||
return [...new Set(contacts)];
|
||||
}
|
||||
|
||||
function optionalBoundedString(value: unknown, field: string, maxLength: number): string | undefined {
|
||||
if (value === undefined || value === null || value === "") return undefined;
|
||||
if (typeof value !== "string" || value.length > maxLength || /[\u0000-\u001f\u007f]/u.test(value)) {
|
||||
throw new McpOAuthError("invalid_client_metadata", `${field} must be a printable string of at most ${maxLength} characters.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function normalizeClientMetadata(
|
||||
body: Record<string, unknown>,
|
||||
normalized: {
|
||||
clientName: string;
|
||||
contacts?: string[];
|
||||
grantTypes: string[];
|
||||
redirectUris: string[];
|
||||
scopes: string[];
|
||||
}
|
||||
): Prisma.InputJsonObject {
|
||||
const optionalMetadata = Object.fromEntries(
|
||||
OAUTH_METADATA_STRING_KEYS.flatMap((key) => {
|
||||
const value = optionalBoundedString(body[key], key, OAUTH_METADATA_STRING_MAX_LENGTH);
|
||||
return value === undefined ? [] : [[key, value]];
|
||||
})
|
||||
) as Prisma.InputJsonObject;
|
||||
return {
|
||||
client_name: normalized.clientName,
|
||||
redirect_uris: normalized.redirectUris,
|
||||
scope: normalized.scopes.join(" "),
|
||||
grant_types: normalized.grantTypes,
|
||||
response_types: ["code"],
|
||||
token_endpoint_auth_method: "none",
|
||||
...(normalized.contacts ? { contacts: normalized.contacts } : {}),
|
||||
...optionalMetadata,
|
||||
};
|
||||
}
|
||||
|
||||
function requiredParam(url: URL, name: string): string {
|
||||
const value = url.searchParams.get(name)?.trim();
|
||||
if (!value) {
|
||||
|
||||
Reference in new issue
Block a user