// @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) { 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 = {}): URL { const url = new URL("https://app.example.test/oauth/authorize"); const params: Record = { 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"); }); });