* test: switch integration project to folder-based manifest (#1314) Replace the `integrationTests` enumeration in vite.config.ts with a folder glob (`src/test/integration/**/*.test.ts`). Files under that folder run in the integration vitest project (node env, 30s timeouts); everything else runs in the unit project (happy-dom). This removes the silent misclassification trap from #1307: a new integration-style test no longer falls into the unit project (and happy-dom) just because someone forgot to add it to the array. The 13 ported v1.5 tests + their helpers move under src/test/integration/ in a strict mirror of core/ source layout (mcp/, auth/, auth/node/, storage/). Renames use git mv so history is preserved. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test: address PR review on #1318 (glob extensions + AGENTS doc) - vite.config.ts: widen integrationGlob from `*.test.ts` to `*.test.{ts,tsx}` so the integration folder fully owns its contents. Without this, a `.test.tsx` placed under src/test/integration/ would match the unit project's `{ts,tsx}` include, fail the unit `.ts`-only exclude, and silently land under happy-dom — the exact misclassification trap this PR set out to close. - AGENTS.md: update the line describing where integration tests live; it still pointed at the old `src/test/core/` location and the removed `integrationTests` enumeration. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
02182e3b6c
commit
8bb389c8e3
4 changed files with 18 additions and 27 deletions
317
clients/web/src/test/integration/auth/discovery.test.ts
Normal file
317
clients/web/src/test/integration/auth/discovery.test.ts
Normal file
|
|
@ -0,0 +1,317 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import {
|
||||
discoverScopes,
|
||||
getAuthorizationServerUrl,
|
||||
} from "@inspector/core/auth/discovery.js";
|
||||
import type { OAuthProtectedResourceMetadata } from "@modelcontextprotocol/sdk/shared/auth.js";
|
||||
|
||||
// Mock SDK functions
|
||||
vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
|
||||
discoverAuthorizationServerMetadata: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("OAuth Scope Discovery", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should return scopes from resource metadata when available", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: "http://localhost:3000",
|
||||
authorization_servers: ["http://localhost:3000"],
|
||||
scopes_supported: ["read", "write", "admin"],
|
||||
};
|
||||
|
||||
const scopes = await discoverScopes(
|
||||
"http://localhost:3000",
|
||||
resourceMetadata,
|
||||
);
|
||||
|
||||
expect(scopes).toBe("read write admin");
|
||||
});
|
||||
|
||||
it("should fall back to OAuth metadata scopes when resource metadata has no scopes", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: "http://localhost:3000",
|
||||
authorization_servers: ["http://localhost:3000"],
|
||||
scopes_supported: [],
|
||||
};
|
||||
|
||||
const scopes = await discoverScopes(
|
||||
"http://localhost:3000",
|
||||
resourceMetadata,
|
||||
);
|
||||
|
||||
expect(scopes).toBe("read write");
|
||||
});
|
||||
|
||||
it("should fall back to OAuth metadata scopes when resource metadata is not provided", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
const scopes = await discoverScopes("http://localhost:3000");
|
||||
|
||||
expect(scopes).toBe("read write");
|
||||
});
|
||||
|
||||
it("should return undefined when no scopes are available", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: [],
|
||||
});
|
||||
|
||||
const scopes = await discoverScopes("http://localhost:3000");
|
||||
|
||||
expect(scopes).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return undefined when discovery fails", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockRejectedValue(
|
||||
new Error("Discovery failed"),
|
||||
);
|
||||
|
||||
const scopes = await discoverScopes("http://localhost:3000");
|
||||
|
||||
expect(scopes).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return undefined when metadata is undefined", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue(undefined);
|
||||
|
||||
const scopes = await discoverScopes("http://localhost:3000");
|
||||
|
||||
expect(scopes).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should use OAuth metadata scopes when resource has scopes_supported undefined", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: "http://localhost:3000",
|
||||
authorization_servers: ["http://localhost:3000"],
|
||||
scopes_supported: undefined as unknown as string[],
|
||||
};
|
||||
|
||||
const scopes = await discoverScopes(
|
||||
"http://localhost:3000",
|
||||
resourceMetadata,
|
||||
);
|
||||
|
||||
expect(scopes).toBe("read write");
|
||||
});
|
||||
|
||||
it("should return single scope when only one scope is supported", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["openid"],
|
||||
});
|
||||
|
||||
const scopes = await discoverScopes("http://localhost:3000");
|
||||
|
||||
expect(scopes).toBe("openid");
|
||||
});
|
||||
|
||||
it("should pass fetchFn to discoverAuthorizationServerMetadata when provided", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
const mockFetchFn = vi.fn();
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
await discoverScopes("http://localhost:3000", undefined, mockFetchFn);
|
||||
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL("/", "http://localhost:3000"),
|
||||
{ fetchFn: mockFetchFn },
|
||||
);
|
||||
});
|
||||
|
||||
it("should use authorization_servers URL from resource metadata for discovery (different domain)", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "https://auth-server.com",
|
||||
authorization_endpoint: "https://auth-server.com/authorize",
|
||||
token_endpoint: "https://auth-server.com/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: "https://mcp-server.com",
|
||||
authorization_servers: ["https://auth-server.com/"],
|
||||
scopes_supported: ["read", "write"],
|
||||
};
|
||||
|
||||
const scopes = await discoverScopes(
|
||||
"https://mcp-server.com",
|
||||
resourceMetadata,
|
||||
);
|
||||
|
||||
expect(scopes).toBe("read write");
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL("https://auth-server.com/"),
|
||||
{ fetchFn: undefined },
|
||||
);
|
||||
});
|
||||
|
||||
it("should preserve full path in authorization_servers URL", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "https://auth-server.com/realms/my-realm",
|
||||
authorization_endpoint:
|
||||
"https://auth-server.com/realms/my-realm/authorize",
|
||||
token_endpoint: "https://auth-server.com/realms/my-realm/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: "https://mcp-server.com",
|
||||
authorization_servers: ["https://auth-server.com/realms/my-realm/"],
|
||||
scopes_supported: ["read", "write"],
|
||||
};
|
||||
|
||||
const scopes = await discoverScopes(
|
||||
"https://mcp-server.com",
|
||||
resourceMetadata,
|
||||
);
|
||||
|
||||
expect(scopes).toBe("read write");
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL("https://auth-server.com/realms/my-realm/"),
|
||||
{ fetchFn: undefined },
|
||||
);
|
||||
});
|
||||
|
||||
it("should fall back to serverUrl when authorization_servers is empty", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "https://mcp-server.com",
|
||||
authorization_endpoint: "https://mcp-server.com/authorize",
|
||||
token_endpoint: "https://mcp-server.com/token",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read", "write"],
|
||||
});
|
||||
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: "https://mcp-server.com",
|
||||
authorization_servers: [],
|
||||
scopes_supported: ["read", "write"],
|
||||
};
|
||||
|
||||
const scopes = await discoverScopes(
|
||||
"https://mcp-server.com",
|
||||
resourceMetadata,
|
||||
);
|
||||
|
||||
expect(scopes).toBe("read write");
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL("/", "https://mcp-server.com"),
|
||||
{ fetchFn: undefined },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAuthorizationServerUrl", () => {
|
||||
const serverUrl = "https://mcp.example.com";
|
||||
|
||||
it("returns server URL when resourceMetadata is null", () => {
|
||||
expect(getAuthorizationServerUrl(serverUrl, null)).toEqual(
|
||||
new URL("/", serverUrl),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns server URL when resourceMetadata is undefined", () => {
|
||||
expect(getAuthorizationServerUrl(serverUrl)).toEqual(
|
||||
new URL("/", serverUrl),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns server URL when authorization_servers is empty array", () => {
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: serverUrl,
|
||||
authorization_servers: [],
|
||||
};
|
||||
expect(getAuthorizationServerUrl(serverUrl, resourceMetadata)).toEqual(
|
||||
new URL("/", serverUrl),
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to server URL when authorization_servers[0] is empty string", () => {
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: serverUrl,
|
||||
authorization_servers: [""],
|
||||
};
|
||||
expect(getAuthorizationServerUrl(serverUrl, resourceMetadata)).toEqual(
|
||||
new URL("/", serverUrl),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns authorization_servers[0] when present and truthy", () => {
|
||||
const authUrl = "https://auth.example.com/";
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: serverUrl,
|
||||
authorization_servers: [authUrl],
|
||||
};
|
||||
expect(getAuthorizationServerUrl(serverUrl, resourceMetadata)).toEqual(
|
||||
new URL(authUrl),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,240 @@
|
|||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import {
|
||||
createOAuthCallbackServer,
|
||||
type OAuthCallbackServer,
|
||||
} from "@inspector/core/auth/node/oauth-callback-server.js";
|
||||
|
||||
describe("OAuthCallbackServer", () => {
|
||||
let server: OAuthCallbackServer;
|
||||
|
||||
afterEach(async () => {
|
||||
if (server) await server.stop();
|
||||
});
|
||||
|
||||
it("start() returns port and redirectUrl", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({ port: 0 });
|
||||
|
||||
expect(result.port).toBeGreaterThan(0);
|
||||
expect(result.redirectUrl).toBe(
|
||||
`http://127.0.0.1:${result.port}/oauth/callback`,
|
||||
);
|
||||
});
|
||||
|
||||
it("start() supports custom host, path, and port", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({
|
||||
hostname: "127.0.0.1",
|
||||
port: 0,
|
||||
path: "/custom/path",
|
||||
});
|
||||
|
||||
expect(result.redirectUrl).toBe(
|
||||
`http://127.0.0.1:${result.port}/custom/path`,
|
||||
);
|
||||
});
|
||||
|
||||
it("GET /oauth/callback?code=abc&state=xyz returns 200 and invokes onCallback", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const received: { code?: string; state?: string } = {};
|
||||
const result = await server.start({
|
||||
port: 0,
|
||||
onCallback: async (p) => {
|
||||
received.code = p.code;
|
||||
received.state = p.state;
|
||||
},
|
||||
});
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=authcode123&state=mystate`,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toContain("text/html");
|
||||
const html = await res.text();
|
||||
expect(html).toContain("OAuth complete");
|
||||
expect(html).toContain("close this window");
|
||||
expect(received.code).toBe("authcode123");
|
||||
expect(received.state).toBe("mystate");
|
||||
});
|
||||
|
||||
it("GET /oauth/callback?code=abc returns 200 and invokes onCallback without state", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const received: { code?: string; state?: string } = {};
|
||||
const result = await server.start({
|
||||
port: 0,
|
||||
onCallback: async (p) => {
|
||||
received.code = p.code;
|
||||
received.state = p.state;
|
||||
},
|
||||
});
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=xyz`,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(received.code).toBe("xyz");
|
||||
expect(received.state).toBeUndefined();
|
||||
});
|
||||
|
||||
it("GET /oauth/callback/guided returns 404 (single path only)", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({ port: 0 });
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback/guided?code=guided-code`,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("GET /oauth/callback?error=access_denied returns 400 and invokes onError", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const errors: Array<{
|
||||
error: string;
|
||||
error_description?: string | null;
|
||||
}> = [];
|
||||
const result = await server.start({
|
||||
port: 0,
|
||||
onError: (p) => errors.push(p),
|
||||
});
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?error=access_denied&error_description=User%20denied`,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
const html = await res.text();
|
||||
expect(html).toContain("OAuth failed");
|
||||
expect(html).toContain("access_denied");
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(errors[0]!.error).toBe("access_denied");
|
||||
expect(errors[0]!.error_description).toBe("User denied");
|
||||
});
|
||||
|
||||
it("GET /oauth/callback (missing code and error) returns 400", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({ port: 0 });
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?state=foo`,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
const html = await res.text();
|
||||
expect(html).toContain("OAuth failed");
|
||||
});
|
||||
|
||||
it("GET /other returns 404", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({ port: 0 });
|
||||
|
||||
const res = await fetch(`http://localhost:${result.port}/other`);
|
||||
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("POST /oauth/callback returns 405", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({ port: 0 });
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=x`,
|
||||
{ method: "POST" },
|
||||
);
|
||||
|
||||
expect(res.status).toBe(405);
|
||||
});
|
||||
|
||||
it("stops server after first successful callback so second request fails", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({
|
||||
port: 0,
|
||||
onCallback: async () => {},
|
||||
});
|
||||
|
||||
const first = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=first`,
|
||||
);
|
||||
expect(first.status).toBe(200);
|
||||
|
||||
// Server stops after sending 200, so second request gets connection refused
|
||||
await expect(
|
||||
fetch(`http://localhost:${result.port}/oauth/callback?code=second`),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("stop() closes the server", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({ port: 0 });
|
||||
await server.stop();
|
||||
|
||||
await expect(
|
||||
fetch(`http://localhost:${result.port}/oauth/callback?code=x`),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("succeeds with 200 when no onCallback handler is configured", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({ port: 0 });
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=lonely`,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
const html = await res.text();
|
||||
expect(html).toContain("OAuth complete");
|
||||
});
|
||||
|
||||
it("returns 409 when a callback arrives after handled=true but before stop completes", async () => {
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({
|
||||
port: 0,
|
||||
// Hold onCallback open so handled=true is set but the server hasn't
|
||||
// yet finished stopping — second request slips into the 409 branch.
|
||||
onCallback: async () => {
|
||||
await gate;
|
||||
},
|
||||
});
|
||||
|
||||
const firstP = fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=first`,
|
||||
);
|
||||
// Give the server time to register handled=true before second hit.
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
const secondP = fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=second`,
|
||||
);
|
||||
const second = await secondP;
|
||||
expect(second.status).toBe(409);
|
||||
release();
|
||||
const first = await firstP;
|
||||
expect(first.status).toBe(200);
|
||||
});
|
||||
|
||||
it("onCallback rejection returns 500 and error HTML", async () => {
|
||||
server = createOAuthCallbackServer();
|
||||
const result = await server.start({
|
||||
port: 0,
|
||||
onCallback: async () => {
|
||||
throw new Error("exchange failed");
|
||||
},
|
||||
});
|
||||
|
||||
const res = await fetch(
|
||||
`http://localhost:${result.port}/oauth/callback?code=abc`,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(500);
|
||||
const html = await res.text();
|
||||
expect(html).toContain("OAuth failed");
|
||||
expect(html).toContain("exchange failed");
|
||||
});
|
||||
});
|
||||
601
clients/web/src/test/integration/auth/node/storage.test.ts
Normal file
601
clients/web/src/test/integration/auth/node/storage.test.ts
Normal file
|
|
@ -0,0 +1,601 @@
|
|||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import {
|
||||
NodeOAuthStorage,
|
||||
getOAuthStore,
|
||||
clearAllOAuthClientState,
|
||||
} from "@inspector/core/auth/node/storage-node.js";
|
||||
import type {
|
||||
OAuthClientInformation,
|
||||
OAuthTokens,
|
||||
OAuthMetadata,
|
||||
} from "@modelcontextprotocol/sdk/shared/auth.js";
|
||||
import * as fs from "node:fs/promises";
|
||||
import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import { waitForStateFile } from "@modelcontextprotocol/inspector-test-server";
|
||||
|
||||
// Unique path per process so parallel test files don't share the same state file
|
||||
const testStatePath = path.join(
|
||||
os.tmpdir(),
|
||||
`mcp-inspector-oauth-${process.pid}-storage-node.json`,
|
||||
);
|
||||
|
||||
describe("NodeOAuthStorage", () => {
|
||||
let storage: NodeOAuthStorage;
|
||||
const testServerUrl = "http://localhost:3000";
|
||||
const stateFilePath = testStatePath;
|
||||
|
||||
beforeEach(async () => {
|
||||
// Clean up any existing state file
|
||||
try {
|
||||
await fs.unlink(stateFilePath);
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
|
||||
// Reset store state by clearing all servers
|
||||
const store = getOAuthStore(testStatePath);
|
||||
const state = store.getState();
|
||||
// Clear all server states
|
||||
Object.keys(state.servers).forEach((url) => {
|
||||
state.clearServerState(url);
|
||||
});
|
||||
|
||||
storage = new NodeOAuthStorage(testStatePath);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// Clean up state file after each test
|
||||
try {
|
||||
await fs.unlink(stateFilePath);
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
|
||||
// Reset store state
|
||||
const store = getOAuthStore(testStatePath);
|
||||
const state = store.getState();
|
||||
Object.keys(state.servers).forEach((url) => {
|
||||
state.clearServerState(url);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getClientInformation", () => {
|
||||
it("should return undefined when no client information is stored", async () => {
|
||||
const result = await storage.getClientInformation(testServerUrl);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return stored client information", async () => {
|
||||
const clientInfo: OAuthClientInformation = {
|
||||
client_id: "test-client-id",
|
||||
client_secret: "test-secret",
|
||||
};
|
||||
|
||||
await storage.saveClientInformation(testServerUrl, clientInfo);
|
||||
|
||||
const result = await storage.getClientInformation(testServerUrl);
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.client_id).toBe(clientInfo.client_id);
|
||||
expect(result?.client_secret).toBe(clientInfo.client_secret);
|
||||
});
|
||||
|
||||
it("should return preregistered client information when requested", async () => {
|
||||
const preregisteredInfo: OAuthClientInformation = {
|
||||
client_id: "preregistered-id",
|
||||
client_secret: "preregistered-secret",
|
||||
};
|
||||
|
||||
// Store as preregistered by directly setting it in the store
|
||||
const store = getOAuthStore(testStatePath);
|
||||
store.getState().setServerState(testServerUrl, {
|
||||
preregisteredClientInformation: preregisteredInfo,
|
||||
});
|
||||
|
||||
const result = await storage.getClientInformation(testServerUrl, true);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.client_id).toBe(preregisteredInfo.client_id);
|
||||
expect(result?.client_secret).toBe(preregisteredInfo.client_secret);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveClientInformation", () => {
|
||||
it("should save client information", async () => {
|
||||
const clientInfo: OAuthClientInformation = {
|
||||
client_id: "test-client-id",
|
||||
};
|
||||
|
||||
await storage.saveClientInformation(testServerUrl, clientInfo);
|
||||
const result = await storage.getClientInformation(testServerUrl);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.client_id).toBe(clientInfo.client_id);
|
||||
});
|
||||
|
||||
it("should overwrite existing client information", async () => {
|
||||
const firstInfo: OAuthClientInformation = {
|
||||
client_id: "first-id",
|
||||
};
|
||||
|
||||
const secondInfo: OAuthClientInformation = {
|
||||
client_id: "second-id",
|
||||
};
|
||||
|
||||
storage.saveClientInformation(testServerUrl, firstInfo);
|
||||
storage.saveClientInformation(testServerUrl, secondInfo);
|
||||
const result = await storage.getClientInformation(testServerUrl);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.client_id).toBe(secondInfo.client_id);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTokens", () => {
|
||||
it("should return undefined when no tokens are stored", async () => {
|
||||
const result = await storage.getTokens(testServerUrl);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return stored tokens", async () => {
|
||||
const tokens: OAuthTokens = {
|
||||
access_token: "test-access-token",
|
||||
token_type: "Bearer",
|
||||
expires_in: 3600,
|
||||
};
|
||||
|
||||
await storage.saveTokens(testServerUrl, tokens);
|
||||
const result = await storage.getTokens(testServerUrl);
|
||||
|
||||
expect(result).toEqual(tokens);
|
||||
});
|
||||
|
||||
it("should persist and return refresh_token", async () => {
|
||||
const tokens: OAuthTokens = {
|
||||
access_token: "test-access-token",
|
||||
token_type: "Bearer",
|
||||
expires_in: 3600,
|
||||
refresh_token: "test-refresh-token",
|
||||
};
|
||||
|
||||
await storage.saveTokens(testServerUrl, tokens);
|
||||
const result = await storage.getTokens(testServerUrl);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.access_token).toBe(tokens.access_token);
|
||||
expect(result?.refresh_token).toBe(tokens.refresh_token);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveTokens", () => {
|
||||
it("should save tokens", async () => {
|
||||
const tokens: OAuthTokens = {
|
||||
access_token: "test-access-token",
|
||||
token_type: "Bearer",
|
||||
};
|
||||
|
||||
await storage.saveTokens(testServerUrl, tokens);
|
||||
const result = await storage.getTokens(testServerUrl);
|
||||
|
||||
expect(result).toEqual(tokens);
|
||||
});
|
||||
|
||||
it("should overwrite existing tokens", async () => {
|
||||
const firstTokens: OAuthTokens = {
|
||||
access_token: "first-token",
|
||||
token_type: "Bearer",
|
||||
};
|
||||
|
||||
const secondTokens: OAuthTokens = {
|
||||
access_token: "second-token",
|
||||
token_type: "Bearer",
|
||||
};
|
||||
|
||||
await storage.saveTokens(testServerUrl, firstTokens);
|
||||
await storage.saveTokens(testServerUrl, secondTokens);
|
||||
const result = await storage.getTokens(testServerUrl);
|
||||
|
||||
expect(result).toEqual(secondTokens);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getCodeVerifier", () => {
|
||||
it("should return undefined when no code verifier is stored", async () => {
|
||||
const result = await storage.getCodeVerifier(testServerUrl);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return stored code verifier", async () => {
|
||||
const codeVerifier = "test-code-verifier";
|
||||
|
||||
await storage.saveCodeVerifier(testServerUrl, codeVerifier);
|
||||
const result = await storage.getCodeVerifier(testServerUrl);
|
||||
|
||||
expect(result).toBe(codeVerifier);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveCodeVerifier", () => {
|
||||
it("should save code verifier", async () => {
|
||||
const codeVerifier = "test-code-verifier";
|
||||
|
||||
await storage.saveCodeVerifier(testServerUrl, codeVerifier);
|
||||
const result = await storage.getCodeVerifier(testServerUrl);
|
||||
|
||||
expect(result).toBe(codeVerifier);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getScope", () => {
|
||||
it("should return undefined when no scope is stored", async () => {
|
||||
const result = await storage.getScope(testServerUrl);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return stored scope", async () => {
|
||||
const scope = "read write";
|
||||
|
||||
await storage.saveScope(testServerUrl, scope);
|
||||
const result = await storage.getScope(testServerUrl);
|
||||
|
||||
expect(result).toBe(scope);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveScope", () => {
|
||||
it("should save scope", async () => {
|
||||
const scope = "read write";
|
||||
|
||||
await storage.saveScope(testServerUrl, scope);
|
||||
const result = await storage.getScope(testServerUrl);
|
||||
|
||||
expect(result).toBe(scope);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getServerMetadata", () => {
|
||||
it("should return null when no metadata is stored", async () => {
|
||||
const result = await storage.getServerMetadata(testServerUrl);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should return stored metadata", async () => {
|
||||
const metadata: OAuthMetadata = {
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
};
|
||||
|
||||
await storage.saveServerMetadata(testServerUrl, metadata);
|
||||
const result = await storage.getServerMetadata(testServerUrl);
|
||||
|
||||
expect(result).toEqual(metadata);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveServerMetadata", () => {
|
||||
it("should save server metadata", async () => {
|
||||
const metadata: OAuthMetadata = {
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
};
|
||||
|
||||
await storage.saveServerMetadata(testServerUrl, metadata);
|
||||
const result = await storage.getServerMetadata(testServerUrl);
|
||||
|
||||
expect(result).toEqual(metadata);
|
||||
});
|
||||
});
|
||||
|
||||
describe("clearClientInformation", () => {
|
||||
it("removes the dynamically-registered client information by default", async () => {
|
||||
await storage.saveClientInformation(testServerUrl, {
|
||||
client_id: "dyn",
|
||||
});
|
||||
expect(await storage.getClientInformation(testServerUrl)).toEqual({
|
||||
client_id: "dyn",
|
||||
});
|
||||
storage.clearClientInformation(testServerUrl);
|
||||
expect(await storage.getClientInformation(testServerUrl)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("removes the preregistered client information when isPreregistered=true", async () => {
|
||||
await storage.savePreregisteredClientInformation(testServerUrl, {
|
||||
client_id: "pre",
|
||||
});
|
||||
expect(await storage.getClientInformation(testServerUrl, true)).toEqual({
|
||||
client_id: "pre",
|
||||
});
|
||||
storage.clearClientInformation(testServerUrl, true);
|
||||
expect(
|
||||
await storage.getClientInformation(testServerUrl, true),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("individual clear methods", () => {
|
||||
it("clearTokens removes only tokens", async () => {
|
||||
await storage.saveTokens(testServerUrl, {
|
||||
access_token: "t",
|
||||
token_type: "Bearer",
|
||||
});
|
||||
expect(await storage.getTokens(testServerUrl)).toBeDefined();
|
||||
storage.clearTokens(testServerUrl);
|
||||
expect(await storage.getTokens(testServerUrl)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("clearCodeVerifier removes only the PKCE verifier", async () => {
|
||||
await storage.saveCodeVerifier(testServerUrl, "verifier");
|
||||
expect(storage.getCodeVerifier(testServerUrl)).toBe("verifier");
|
||||
storage.clearCodeVerifier(testServerUrl);
|
||||
expect(storage.getCodeVerifier(testServerUrl)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("clearScope removes only the scope", async () => {
|
||||
await storage.saveScope(testServerUrl, "read write");
|
||||
expect(storage.getScope(testServerUrl)).toBe("read write");
|
||||
storage.clearScope(testServerUrl);
|
||||
expect(storage.getScope(testServerUrl)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("clearServerMetadata removes only the cached metadata", async () => {
|
||||
const metadata: OAuthMetadata = {
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
};
|
||||
await storage.saveServerMetadata(testServerUrl, metadata);
|
||||
expect(storage.getServerMetadata(testServerUrl)).toEqual(metadata);
|
||||
storage.clearServerMetadata(testServerUrl);
|
||||
expect(storage.getServerMetadata(testServerUrl)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("clearServerState", () => {
|
||||
it("should clear all state for a server", async () => {
|
||||
const clientInfo: OAuthClientInformation = {
|
||||
client_id: "test-client-id",
|
||||
};
|
||||
const tokens: OAuthTokens = {
|
||||
access_token: "test-token",
|
||||
token_type: "Bearer",
|
||||
};
|
||||
|
||||
await storage.saveClientInformation(testServerUrl, clientInfo);
|
||||
await storage.saveTokens(testServerUrl, tokens);
|
||||
|
||||
storage.clear(testServerUrl);
|
||||
|
||||
expect(await storage.getClientInformation(testServerUrl)).toBeUndefined();
|
||||
expect(await storage.getTokens(testServerUrl)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should not affect state for other servers", async () => {
|
||||
const otherServerUrl = "http://localhost:4000";
|
||||
const clientInfo: OAuthClientInformation = {
|
||||
client_id: "test-client-id",
|
||||
};
|
||||
|
||||
await storage.saveClientInformation(testServerUrl, clientInfo);
|
||||
await storage.saveClientInformation(otherServerUrl, clientInfo);
|
||||
|
||||
storage.clear(testServerUrl);
|
||||
|
||||
expect(await storage.getClientInformation(testServerUrl)).toBeUndefined();
|
||||
const otherResult = await storage.getClientInformation(otherServerUrl);
|
||||
expect(otherResult).toBeDefined();
|
||||
expect(otherResult?.client_id).toBe(clientInfo.client_id);
|
||||
expect(otherResult).toEqual(clientInfo);
|
||||
});
|
||||
});
|
||||
|
||||
describe("multiple servers", () => {
|
||||
it("should store separate state for different servers", async () => {
|
||||
const server1Url = "http://localhost:3000";
|
||||
const server2Url = "http://localhost:4000";
|
||||
|
||||
const clientInfo1: OAuthClientInformation = {
|
||||
client_id: "client-1",
|
||||
};
|
||||
|
||||
const clientInfo2: OAuthClientInformation = {
|
||||
client_id: "client-2",
|
||||
};
|
||||
|
||||
storage.saveClientInformation(server1Url, clientInfo1);
|
||||
storage.saveClientInformation(server2Url, clientInfo2);
|
||||
|
||||
const result1 = await storage.getClientInformation(server1Url);
|
||||
const result2 = await storage.getClientInformation(server2Url);
|
||||
expect(result1).toEqual(clientInfo1);
|
||||
expect(result2).toEqual(clientInfo2);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("OAuth Store (Zustand)", () => {
|
||||
const stateFilePath = testStatePath;
|
||||
|
||||
beforeEach(async () => {
|
||||
try {
|
||||
await fs.unlink(stateFilePath);
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
try {
|
||||
await fs.unlink(stateFilePath);
|
||||
} catch {
|
||||
// Ignore if file doesn't exist
|
||||
}
|
||||
});
|
||||
|
||||
it("should create a new store", () => {
|
||||
const store = getOAuthStore(testStatePath);
|
||||
expect(store).toBeDefined();
|
||||
expect(store.getState).toBeDefined();
|
||||
expect(store.setState).toBeDefined();
|
||||
});
|
||||
|
||||
it("should return the same store instance via getOAuthStore", () => {
|
||||
const store1 = getOAuthStore(testStatePath);
|
||||
const store2 = getOAuthStore(testStatePath);
|
||||
expect(store1).toBe(store2);
|
||||
});
|
||||
|
||||
it("should persist state to file", async () => {
|
||||
// Use a unique path so no other test (e.g. "should overwrite..." with second-id) can
|
||||
// write to the same file; Zustand persist is async and can race with shared paths.
|
||||
const persistTestPath = path.join(
|
||||
os.tmpdir(),
|
||||
`mcp-inspector-oauth-persist-${Date.now()}-${Math.random().toString(36).slice(2)}.json`,
|
||||
);
|
||||
try {
|
||||
if (process.env.DEBUG_WAIT_FOR_STATE_FILE === "1") {
|
||||
console.error("[storage-node.test] state file path:", persistTestPath);
|
||||
}
|
||||
const store = getOAuthStore(persistTestPath);
|
||||
const serverUrl = "http://localhost:3000";
|
||||
const clientInfo: OAuthClientInformation = {
|
||||
client_id: "test-client-id",
|
||||
};
|
||||
|
||||
store.getState().setServerState(serverUrl, {
|
||||
clientInformation: clientInfo,
|
||||
});
|
||||
|
||||
type StateShape = {
|
||||
state: {
|
||||
servers: Record<
|
||||
string,
|
||||
{ clientInformation?: OAuthClientInformation }
|
||||
>;
|
||||
};
|
||||
};
|
||||
const parsed = await waitForStateFile<StateShape>(
|
||||
persistTestPath,
|
||||
(p) => {
|
||||
const s = (p as StateShape)?.state?.servers?.[serverUrl];
|
||||
return !!s?.clientInformation;
|
||||
},
|
||||
{ timeout: 2000, interval: 50 },
|
||||
);
|
||||
expect(parsed.state.servers[serverUrl]?.clientInformation).toEqual(
|
||||
clientInfo,
|
||||
);
|
||||
} finally {
|
||||
try {
|
||||
await fs.unlink(persistTestPath);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("NodeOAuthStorage with custom storagePath", () => {
|
||||
const testServerUrl = "http://localhost:3999";
|
||||
|
||||
it("should use custom path for state file", async () => {
|
||||
const customPath = path.join(
|
||||
os.tmpdir(),
|
||||
`mcp-inspector-oauth-test-${Date.now()}-${Math.random().toString(36).slice(2)}.json`,
|
||||
);
|
||||
|
||||
try {
|
||||
const storage = new NodeOAuthStorage(customPath);
|
||||
const tokens: OAuthTokens = {
|
||||
access_token: "custom-path-token",
|
||||
token_type: "Bearer",
|
||||
refresh_token: "custom-refresh",
|
||||
};
|
||||
await storage.saveTokens(testServerUrl, tokens);
|
||||
|
||||
type StateShape = {
|
||||
state: {
|
||||
servers: Record<string, { tokens?: { access_token?: string } }>;
|
||||
};
|
||||
};
|
||||
const parsed = await waitForStateFile<StateShape>(
|
||||
customPath,
|
||||
(p) => {
|
||||
const t = (p as StateShape)?.state?.servers?.[testServerUrl]?.tokens;
|
||||
return t?.access_token === tokens.access_token;
|
||||
},
|
||||
{ timeout: 2000, interval: 50 },
|
||||
);
|
||||
|
||||
expect(parsed.state.servers[testServerUrl]?.tokens?.access_token).toBe(
|
||||
tokens.access_token,
|
||||
);
|
||||
|
||||
const stored = await storage.getTokens(testServerUrl);
|
||||
expect(stored?.access_token).toBe(tokens.access_token);
|
||||
expect(stored?.refresh_token).toBe(tokens.refresh_token);
|
||||
} finally {
|
||||
try {
|
||||
await fs.unlink(customPath);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("clearAllOAuthClientState clears every server in the default store", async () => {
|
||||
const defaultStore = getOAuthStore();
|
||||
defaultStore.getState().setServerState("http://server-a.test", {
|
||||
tokens: { access_token: "a", token_type: "Bearer" },
|
||||
});
|
||||
defaultStore.getState().setServerState("http://server-b.test", {
|
||||
tokens: { access_token: "b", token_type: "Bearer" },
|
||||
});
|
||||
clearAllOAuthClientState();
|
||||
const all = defaultStore.getState();
|
||||
expect(all.getServerState("http://server-a.test").tokens).toBeUndefined();
|
||||
expect(all.getServerState("http://server-b.test").tokens).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should isolate state from default store", async () => {
|
||||
const customPath = path.join(
|
||||
os.tmpdir(),
|
||||
`mcp-inspector-oauth-isolate-${Date.now()}-${Math.random().toString(36).slice(2)}.json`,
|
||||
);
|
||||
|
||||
try {
|
||||
const defaultStore = getOAuthStore();
|
||||
defaultStore.getState().setServerState(testServerUrl, {
|
||||
tokens: {
|
||||
access_token: "default-token",
|
||||
token_type: "Bearer",
|
||||
},
|
||||
});
|
||||
|
||||
const customStorage = new NodeOAuthStorage(customPath);
|
||||
await customStorage.saveTokens(testServerUrl, {
|
||||
access_token: "custom-token",
|
||||
token_type: "Bearer",
|
||||
});
|
||||
|
||||
const fromCustom = await customStorage.getTokens(testServerUrl);
|
||||
expect(fromCustom?.access_token).toBe("custom-token");
|
||||
|
||||
const defaultStorage = new NodeOAuthStorage();
|
||||
const fromDefault = await defaultStorage.getTokens(testServerUrl);
|
||||
expect(fromDefault?.access_token).toBe("default-token");
|
||||
|
||||
defaultStore.getState().clearServerState(testServerUrl);
|
||||
} finally {
|
||||
try {
|
||||
await fs.unlink(customPath);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
441
clients/web/src/test/integration/auth/state-machine.test.ts
Normal file
441
clients/web/src/test/integration/auth/state-machine.test.ts
Normal file
|
|
@ -0,0 +1,441 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import {
|
||||
OAuthStateMachine,
|
||||
oauthTransitions,
|
||||
} from "@inspector/core/auth/state-machine.js";
|
||||
import type { AuthGuidedState, OAuthStep } from "@inspector/core/auth/types.js";
|
||||
import { EMPTY_GUIDED_STATE } from "@inspector/core/auth/types.js";
|
||||
import type { BaseOAuthClientProvider } from "@inspector/core/auth/providers.js";
|
||||
import type {
|
||||
OAuthMetadata,
|
||||
OAuthProtectedResourceMetadata,
|
||||
} from "@modelcontextprotocol/sdk/shared/auth.js";
|
||||
|
||||
// Mock SDK functions
|
||||
vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
|
||||
discoverAuthorizationServerMetadata: vi.fn(),
|
||||
discoverOAuthProtectedResourceMetadata: vi.fn(),
|
||||
registerClient: vi.fn(),
|
||||
startAuthorization: vi.fn(),
|
||||
exchangeAuthorization: vi.fn(),
|
||||
selectResourceURL: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("OAuthStateMachine", () => {
|
||||
let mockProvider: BaseOAuthClientProvider;
|
||||
let updateState: (updates: Partial<AuthGuidedState>) => void;
|
||||
let state: AuthGuidedState;
|
||||
|
||||
beforeEach(() => {
|
||||
state = { ...EMPTY_GUIDED_STATE };
|
||||
updateState = vi.fn((updates: Partial<AuthGuidedState>) => {
|
||||
state = { ...state, ...updates };
|
||||
});
|
||||
|
||||
mockProvider = {
|
||||
serverUrl: "http://localhost:3000",
|
||||
redirectUrl: "http://localhost:3000/callback",
|
||||
scope: "read write",
|
||||
clientMetadata: {
|
||||
redirect_uris: ["http://localhost:3000/callback"],
|
||||
token_endpoint_auth_method: "none",
|
||||
grant_types: ["authorization_code"],
|
||||
response_types: ["code"],
|
||||
client_name: "Test Client",
|
||||
scope: "read write",
|
||||
},
|
||||
clientInformation: vi.fn(),
|
||||
saveClientInformation: vi.fn(),
|
||||
tokens: vi.fn(),
|
||||
saveTokens: vi.fn(),
|
||||
codeVerifier: vi.fn(() => "test-code-verifier"),
|
||||
clear: vi.fn(),
|
||||
state: vi.fn(() => "test-state"),
|
||||
getServerMetadata: vi.fn(() => null),
|
||||
saveServerMetadata: vi.fn(),
|
||||
} as unknown as BaseOAuthClientProvider;
|
||||
});
|
||||
|
||||
describe("oauthTransitions", () => {
|
||||
it("should have transitions for all OAuth steps", () => {
|
||||
const steps: OAuthStep[] = [
|
||||
"metadata_discovery",
|
||||
"client_registration",
|
||||
"authorization_redirect",
|
||||
"authorization_code",
|
||||
"token_request",
|
||||
"complete",
|
||||
];
|
||||
|
||||
steps.forEach((step) => {
|
||||
expect(oauthTransitions[step]).toBeDefined();
|
||||
expect(oauthTransitions[step].canTransition).toBeDefined();
|
||||
expect(oauthTransitions[step].execute).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("OAuthStateMachine", () => {
|
||||
it("should create state machine instance", () => {
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
"http://localhost:3000",
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
|
||||
expect(stateMachine).toBeDefined();
|
||||
});
|
||||
|
||||
it("should update state when executeStep is called", async () => {
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
"http://localhost:3000",
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
} as OAuthMetadata);
|
||||
|
||||
await stateMachine.executeStep(state);
|
||||
|
||||
expect(updateState).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Resource metadata discovery and selection", () => {
|
||||
const serverUrl = "http://localhost:3000";
|
||||
const resourceMetadata = {
|
||||
resource: "http://localhost:3000",
|
||||
authorization_servers: ["http://localhost:3000"],
|
||||
scopes_supported: ["read", "write"],
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const {
|
||||
discoverAuthorizationServerMetadata,
|
||||
discoverOAuthProtectedResourceMetadata,
|
||||
selectResourceURL,
|
||||
} = await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
} as OAuthMetadata);
|
||||
vi.mocked(discoverOAuthProtectedResourceMetadata).mockReset();
|
||||
vi.mocked(selectResourceURL).mockReset();
|
||||
});
|
||||
|
||||
it("should discover resource metadata from well-known and use first authorization server", async () => {
|
||||
const selectedResource = new URL("http://localhost:3000");
|
||||
const { discoverOAuthProtectedResourceMetadata, selectResourceURL } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverOAuthProtectedResourceMetadata).mockResolvedValue(
|
||||
resourceMetadata as OAuthProtectedResourceMetadata,
|
||||
);
|
||||
vi.mocked(selectResourceURL).mockResolvedValue(selectedResource);
|
||||
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
await stateMachine.executeStep(state);
|
||||
|
||||
expect(discoverOAuthProtectedResourceMetadata).toHaveBeenCalledWith(
|
||||
serverUrl,
|
||||
);
|
||||
expect(selectResourceURL).toHaveBeenCalledWith(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
resourceMetadata,
|
||||
);
|
||||
expect(updateState).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
resourceMetadata,
|
||||
resource: selectedResource,
|
||||
resourceMetadataError: null,
|
||||
authServerUrl: new URL("http://localhost:3000"),
|
||||
oauthStep: "client_registration",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should use authorization_servers URL from resource metadata for auth server discovery", async () => {
|
||||
const authServerUrl = "https://auth-server.com/";
|
||||
const resourceMetaDifferentAuth: OAuthProtectedResourceMetadata = {
|
||||
resource: serverUrl,
|
||||
authorization_servers: [authServerUrl],
|
||||
scopes_supported: ["read", "write"],
|
||||
};
|
||||
const selectedResource = new URL(serverUrl);
|
||||
const {
|
||||
discoverOAuthProtectedResourceMetadata,
|
||||
discoverAuthorizationServerMetadata,
|
||||
selectResourceURL,
|
||||
} = await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverOAuthProtectedResourceMetadata).mockResolvedValue(
|
||||
resourceMetaDifferentAuth,
|
||||
);
|
||||
vi.mocked(selectResourceURL).mockResolvedValue(selectedResource);
|
||||
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
await stateMachine.executeStep(state);
|
||||
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL(authServerUrl),
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(updateState).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
resourceMetadata: resourceMetaDifferentAuth,
|
||||
authServerUrl: new URL(authServerUrl),
|
||||
oauthStep: "client_registration",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should call selectResourceURL only when resource metadata is present", async () => {
|
||||
const { discoverOAuthProtectedResourceMetadata, selectResourceURL } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverOAuthProtectedResourceMetadata).mockRejectedValue(
|
||||
new Error(
|
||||
"Resource server does not implement OAuth 2.0 Protected Resource Metadata.",
|
||||
),
|
||||
);
|
||||
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
await stateMachine.executeStep(state);
|
||||
|
||||
expect(selectResourceURL).not.toHaveBeenCalled();
|
||||
expect(updateState).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
resourceMetadata: null,
|
||||
resourceMetadataError: expect.any(Error),
|
||||
oauthStep: "client_registration",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should use default auth server URL when discovery fails", async () => {
|
||||
const {
|
||||
discoverOAuthProtectedResourceMetadata,
|
||||
discoverAuthorizationServerMetadata,
|
||||
} = await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
vi.mocked(discoverOAuthProtectedResourceMetadata).mockRejectedValue(
|
||||
new Error("Discovery failed"),
|
||||
);
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
} as OAuthMetadata);
|
||||
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
await stateMachine.executeStep(state);
|
||||
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL("/", serverUrl),
|
||||
{}, // No fetchFn when not provided (conditional spread omits it)
|
||||
);
|
||||
expect(updateState).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
authServerUrl: new URL("/", serverUrl),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should use default auth server when metadata has empty authorization_servers", async () => {
|
||||
const { discoverOAuthProtectedResourceMetadata, selectResourceURL } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
const metaNoServers = {
|
||||
...resourceMetadata,
|
||||
authorization_servers: [] as string[],
|
||||
};
|
||||
vi.mocked(discoverOAuthProtectedResourceMetadata).mockResolvedValue(
|
||||
metaNoServers as OAuthProtectedResourceMetadata,
|
||||
);
|
||||
vi.mocked(selectResourceURL).mockResolvedValue(
|
||||
new URL("http://localhost:3000"),
|
||||
);
|
||||
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
await stateMachine.executeStep(state);
|
||||
|
||||
expect(selectResourceURL).toHaveBeenCalledWith(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
metaNoServers,
|
||||
);
|
||||
expect(updateState).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
resourceMetadata: metaNoServers,
|
||||
authServerUrl: new URL("/", serverUrl),
|
||||
oauthStep: "client_registration",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should pass fetchFn to registerClient when provided", async () => {
|
||||
const { registerClient } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
const mockFetchFn = vi.fn();
|
||||
vi.mocked(registerClient).mockResolvedValue({
|
||||
redirect_uris: ["http://localhost/callback"],
|
||||
client_id: "registered-client-id",
|
||||
});
|
||||
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
serverUrl,
|
||||
mockProvider,
|
||||
updateState,
|
||||
mockFetchFn,
|
||||
);
|
||||
await stateMachine.executeStep(state);
|
||||
expect(state.oauthStep).toBe("client_registration");
|
||||
|
||||
await stateMachine.executeStep(state);
|
||||
|
||||
expect(registerClient).toHaveBeenCalledWith(
|
||||
serverUrl,
|
||||
expect.objectContaining({
|
||||
fetchFn: mockFetchFn,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should pass fetchFn to exchangeAuthorization when provided", async () => {
|
||||
const { exchangeAuthorization } =
|
||||
await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
const mockFetchFn = vi.fn();
|
||||
const metadata = {
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
};
|
||||
vi.mocked(exchangeAuthorization).mockResolvedValue({
|
||||
access_token: "test-token",
|
||||
token_type: "Bearer",
|
||||
});
|
||||
|
||||
const providerWithMetadata = {
|
||||
...mockProvider,
|
||||
getServerMetadata: vi.fn(() => metadata),
|
||||
} as unknown as BaseOAuthClientProvider;
|
||||
|
||||
const tokenRequestState: AuthGuidedState = {
|
||||
...EMPTY_GUIDED_STATE,
|
||||
oauthStep: "token_request",
|
||||
oauthMetadata: metadata as OAuthMetadata,
|
||||
oauthClientInfo: { client_id: "test-client" },
|
||||
authorizationCode: "test-code",
|
||||
};
|
||||
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
serverUrl,
|
||||
providerWithMetadata,
|
||||
updateState,
|
||||
mockFetchFn,
|
||||
);
|
||||
await stateMachine.executeStep(tokenRequestState);
|
||||
|
||||
expect(exchangeAuthorization).toHaveBeenCalledWith(
|
||||
serverUrl,
|
||||
expect.objectContaining({
|
||||
fetchFn: mockFetchFn,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("token_request execute throws when client information cannot be obtained", async () => {
|
||||
const metadata = {
|
||||
issuer: "http://localhost:3000",
|
||||
authorization_endpoint: "http://localhost:3000/authorize",
|
||||
token_endpoint: "http://localhost:3000/token",
|
||||
response_types_supported: ["code"],
|
||||
};
|
||||
const providerNoClient = {
|
||||
...mockProvider,
|
||||
getServerMetadata: vi.fn(() => metadata),
|
||||
clientInformation: vi.fn(async () => undefined),
|
||||
} as unknown as BaseOAuthClientProvider;
|
||||
|
||||
const tokenState: AuthGuidedState = {
|
||||
...EMPTY_GUIDED_STATE,
|
||||
oauthStep: "token_request",
|
||||
oauthMetadata: metadata as OAuthMetadata,
|
||||
authorizationCode: "code-without-client",
|
||||
};
|
||||
|
||||
await expect(
|
||||
oauthTransitions.token_request.execute({
|
||||
state: tokenState,
|
||||
serverUrl: "http://localhost:3000",
|
||||
provider: providerNoClient,
|
||||
updateState,
|
||||
}),
|
||||
).rejects.toThrow("Client information not available for token exchange");
|
||||
});
|
||||
|
||||
it("complete.canTransition always returns false (terminal state)", async () => {
|
||||
const result = await oauthTransitions.complete.canTransition({
|
||||
state: { ...EMPTY_GUIDED_STATE, oauthStep: "complete" },
|
||||
serverUrl: "http://localhost:3000",
|
||||
provider: mockProvider,
|
||||
updateState,
|
||||
});
|
||||
expect(result).toBe(false);
|
||||
// execute is a no-op
|
||||
await expect(
|
||||
oauthTransitions.complete.execute({
|
||||
state: { ...EMPTY_GUIDED_STATE, oauthStep: "complete" },
|
||||
serverUrl: "http://localhost:3000",
|
||||
provider: mockProvider,
|
||||
updateState,
|
||||
}),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("executeStep throws when the current step cannot transition", async () => {
|
||||
// metadata_discovery.canTransition is unconditional (returns true), but
|
||||
// token_request requires authorizationCode + metadata + clientInfo; an
|
||||
// empty state will refuse to transition.
|
||||
const stateMachine = new OAuthStateMachine(
|
||||
"http://localhost:3000",
|
||||
mockProvider,
|
||||
updateState,
|
||||
);
|
||||
const blockedState: AuthGuidedState = {
|
||||
...EMPTY_GUIDED_STATE,
|
||||
oauthStep: "token_request",
|
||||
};
|
||||
await expect(stateMachine.executeStep(blockedState)).rejects.toThrow(
|
||||
/Cannot transition from token_request/,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Reference in a new issue