import { createHash } from "node:crypto"; import { beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ queryRaw: vi.fn(), clientCreate: vi.fn(), authorizationFindUnique: vi.fn(), authorizationUpdateMany: vi.fn(), refreshFindUnique: vi.fn(), refreshUpdateMany: vi.fn(), })); vi.mock("./client.server.js", () => ({ getDbClient: () => ({ $queryRaw: mocks.queryRaw, mcpOAuthClient: { create: mocks.clientCreate, }, mcpOAuthAuthorizationCode: { findUnique: mocks.authorizationFindUnique, updateMany: mocks.authorizationUpdateMany, }, mcpOAuthRefreshToken: { findUnique: mocks.refreshFindUnique, updateMany: mocks.refreshUpdateMany, }, }), })); import { consumeMcpOAuthAuthorizationCode, consumeMcpOAuthRefreshToken, registerMcpOAuthClient } from "./mcp-oauth.server"; const secret = "0123456789abcdef0123456789abcdef"; const now = new Date("2026-07-12T08:00:00.000Z"); const codeVerifier = "correct-pkce-code-verifier"; const codeChallenge = createHash("sha256").update(codeVerifier).digest().toString("base64url"); function authorizationRow() { return { id: "authorization_code_row_1", clientId: "client_row_1", userId: "user_1", tenantId: "tenant_1", tenantSlug: "acme", redirectUri: "https://client.example/callback", scopes: ["mcp:read"], resource: "https://mcp.example.test", codeChallenge, codeChallengeMethod: "S256", consumedAt: null, expiresAt: new Date(now.getTime() + 60_000), client: { id: "client_row_1", clientId: "hgomc_client_1", clientName: "Test Client", redirectUris: ["https://client.example/callback"], scopes: ["mcp:read"], active: true, }, }; } function refreshRow() { return { id: "refresh_token_row_1", clientId: "client_row_1", userId: "user_1", tenantId: "tenant_1", tenantSlug: "acme", scopes: ["mcp:read"], resource: "https://mcp.example.test", revokedAt: null, rotatedAt: null, expiresAt: new Date(now.getTime() + 60_000), client: { id: "client_row_1", clientId: "hgomc_client_1", clientName: "Test Client", redirectUris: ["https://client.example/callback"], scopes: ["mcp:read"], active: true, }, }; } beforeEach(() => { vi.clearAllMocks(); mocks.authorizationFindUnique.mockResolvedValue(authorizationRow()); mocks.refreshFindUnique.mockResolvedValue(refreshRow()); }); describe("MCP OAuth dynamic client registration capability", () => { it("generates both identifiers in JavaScript and binds registration data as scalar SQL parameters", async () => { mocks.queryRaw.mockResolvedValue([ { id: "client_row_1", clientId: "hgomc_returned_client", clientName: "Test Client", redirectUris: ["https://client.example/callback"], scopes: ["mcp:read"], active: true, }, ]); await expect( registerMcpOAuthClient({ clientName: "Test Client", redirectUris: ["https://client.example/callback"], grantTypes: ["authorization_code"], scopes: ["mcp:read"], contacts: ["security@example.test"], metadata: { software_id: "client-software-1" }, }) ).resolves.toEqual({ id: "client_row_1", clientId: "hgomc_returned_client", clientName: "Test Client", redirectUris: ["https://client.example/callback"], scopes: ["mcp:read"], active: true, }); expect(mocks.clientCreate).not.toHaveBeenCalled(); expect(mocks.queryRaw).toHaveBeenCalledTimes(1); const query = mocks.queryRaw.mock.calls[0]?.[0] as { strings: readonly string[]; values: readonly unknown[] }; expect(query.strings.join("?")).toContain("public.hivegrid_register_mcp_oauth_client("); expect(query.values[0]).toEqual(expect.stringMatching(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)); expect(query.values[1]).toEqual(expect.stringMatching(/^hgomc_[A-Za-z0-9_-]{32}$/)); expect(query.values.slice(2)).toEqual([ "Test Client", JSON.stringify(["https://client.example/callback"]), JSON.stringify(["authorization_code"]), JSON.stringify(["mcp:read"]), JSON.stringify(["security@example.test"]), JSON.stringify({ software_id: "client-software-1" }), ]); }); it("passes SQL null for optional JSON and fails closed for a missing or ambiguous return row", async () => { mocks.queryRaw.mockResolvedValueOnce([]).mockResolvedValueOnce([{ id: "client_1" }, { id: "client_2" }]); const input = { clientName: "Minimal Client", redirectUris: ["https://client.example/callback"], scopes: ["mcp:read"], }; await expect(registerMcpOAuthClient(input)).rejects.toThrow("did not return exactly one row"); const query = mocks.queryRaw.mock.calls[0]?.[0] as { values: readonly unknown[] }; expect(query.values.slice(4)).toEqual([JSON.stringify(["authorization_code", "refresh_token"]), JSON.stringify(["mcp:read"]), null, null]); await expect(registerMcpOAuthClient(input)).rejects.toThrow("did not return exactly one row"); expect(mocks.clientCreate).not.toHaveBeenCalled(); }); }); describe("MCP OAuth authorization-code atomic consumption", () => { it.each([ ["wrong client", { clientId: "hgomc_wrong" }], ["wrong redirect", { redirectUri: "https://attacker.example/callback" }], ["wrong PKCE", { codeVerifier: "wrong-code-verifier" }], ])("does not consume a valid code for %s", async (_case, override) => { const result = await consumeMcpOAuthAuthorizationCode({ code: "hgoc_code_1", secret, clientId: "hgomc_client_1", redirectUri: "https://client.example/callback", codeVerifier, now, ...override, }); expect(result).toBeNull(); expect(mocks.authorizationUpdateMany).not.toHaveBeenCalled(); }); it("lets exactly one of two parallel valid exchanges win the consume CAS", async () => { let consumed = false; mocks.authorizationUpdateMany.mockImplementation(async () => { await Promise.resolve(); if (consumed) return { count: 0 }; consumed = true; return { count: 1 }; }); const input = { code: "hgoc_code_1", secret, clientId: "hgomc_client_1", redirectUri: "https://client.example/callback", codeVerifier, now, }; const results = await Promise.all([consumeMcpOAuthAuthorizationCode(input), consumeMcpOAuthAuthorizationCode(input)]); expect(results.filter(Boolean)).toHaveLength(1); expect(mocks.authorizationUpdateMany).toHaveBeenCalledTimes(2); expect(mocks.authorizationUpdateMany).toHaveBeenCalledWith({ where: { id: "authorization_code_row_1", clientId: "client_row_1", redirectUri: "https://client.example/callback", consumedAt: null, expiresAt: { gt: now }, }, data: { consumedAt: now }, }); }); }); describe("MCP OAuth refresh-token atomic rotation", () => { it("does not rotate a valid refresh token for the wrong client", async () => { const result = await consumeMcpOAuthRefreshToken({ token: "hgor_refresh_1", secret, clientId: "hgomc_wrong", now, }); expect(result).toBeNull(); expect(mocks.refreshUpdateMany).not.toHaveBeenCalled(); }); it("lets exactly one of two parallel valid refreshes win the rotation CAS", async () => { let rotated = false; mocks.refreshUpdateMany.mockImplementation(async () => { await Promise.resolve(); if (rotated) return { count: 0 }; rotated = true; return { count: 1 }; }); const input = { token: "hgor_refresh_1", secret, clientId: "hgomc_client_1", now, }; const results = await Promise.all([consumeMcpOAuthRefreshToken(input), consumeMcpOAuthRefreshToken(input)]); expect(results.filter(Boolean)).toHaveLength(1); expect(mocks.refreshUpdateMany).toHaveBeenCalledTimes(2); expect(mocks.refreshUpdateMany).toHaveBeenCalledWith({ where: { id: "refresh_token_row_1", clientId: "client_row_1", revokedAt: null, rotatedAt: null, expiresAt: { gt: now }, }, data: { rotatedAt: now }, }); }); });