import { createSign, generateKeyPairSync } from "node:crypto"; import Fastify from "fastify"; import { describe, expect, it } from "vitest"; import { FullTextStore } from "./fulltext.js"; import { agentsTools, createAgentsMcpAuth, handleMcpRequest, jwtVerifier, McpAuthError, registerAgentsMcp, type AgentsMcpSettings } from "./mcp-agents.js"; const ISS = "https://keycloak.example/realms/khbuild"; const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 }); const jwk = { ...publicKey.export({ format: "jwk" }), kid: "k1", alg: "RS256", use: "sig" }; const b64 = (o: unknown) => Buffer.from(typeof o === "string" ? o : JSON.stringify(o)).toString("base64url"); function jwt(claims: Record, key = privateKey): string { const head = b64({ alg: "RS256", kid: "k1", typ: "JWT" }); const body = b64({ iss: ISS, exp: Math.floor(Date.now() / 1000) + 600, ...claims }); const sig = createSign("RSA-SHA256").update(`${head}.${body}`).sign(key).toString("base64url"); return `${head}.${body}.${sig}`; } const settings: AgentsMcpSettings = { enabled: true, publicUrl: "https://x/api/agents", issuer: ISS, allowedEmails: ["Agents@khbuild.pro"], staticTokens: ["static-token-0123456789abcdef"] }; const verify = jwtVerifier(ISS, async () => ({ keys: [jwk as never] })); describe("mcp_for_agents: аутентификация", () => { const auth = createAgentsMcpAuth(settings, verify); it("статический токен и JWT разрешённого email проходят", async () => { await expect(auth("Bearer static-token-0123456789abcdef")).resolves.toMatchObject({ who: "static-token" }); await expect(auth(`Bearer ${jwt({ email: "agents@khbuild.pro", email_verified: true })}`)).resolves.toMatchObject({ who: "agents@khbuild.pro" }); }); it("чужой email - 403, нет токена / плохая подпись / просрочен - 401", async () => { await expect(auth(`Bearer ${jwt({ email: "other@khbuild.pro" })}`)).rejects.toMatchObject({ status: 403 }); await expect(auth(undefined)).rejects.toBeInstanceOf(McpAuthError); const other = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey; await expect(auth(`Bearer ${jwt({ email: "agents@khbuild.pro" }, other)}`)).rejects.toMatchObject({ status: 401 }); await expect(auth(`Bearer ${jwt({ email: "agents@khbuild.pro", exp: 1 })}`)).rejects.toMatchObject({ status: 401 }); await expect(auth(`Bearer ${jwt({ email: "agents@khbuild.pro", iss: "https://evil" })}`)).rejects.toMatchObject({ status: 401 }); }); }); describe("mcp_for_agents: инструменты и маршрут", () => { it("read_full_text читает любой длины частями, read_slack_message отдаёт текст целиком", async () => { const store = new FullTextStore(); store.put("a".repeat(30000), "slack:C1:1.1"); const tools = agentsTools({ pool: {} as never, store, slackMessage: async (c, t) => (c === "C1" && t === "1.1" ? "полный текст".repeat(1000) : null) }); expect(tools.map((t) => t.name)).toEqual(["read_full_text", "agent_issues", "read_slack_message"]); const r1 = (await handleMcpRequest({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "read_full_text", arguments: { ref: "slack:C1:1.1", offset: 20000 } } }, tools, "t")) as { result: { content: { text: string }[] } }; expect(r1.result.content[0]!.text).toContain("символы 20000..30000 из 30000"); const r2 = (await handleMcpRequest({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "read_slack_message", arguments: { channel: "C1", ts: "1.1" } } }, tools, "t")) as { result: { content: { text: string }[] } }; expect(r2.result.content[0]!.text.length).toBe(12000); const r3 = (await handleMcpRequest({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "read_slack_message", arguments: { channel: "C9", ts: "9" } } }, tools, "t")) as { result: { isError: boolean } }; expect(r3.result.isError).toBe(true); }); it("POST /mcp/agents: 401 с подсказкой OAuth без токена, 200 с токеном", async () => { const app = Fastify(); registerAgentsMcp(app, settings, { pool: {} as never, store: new FullTextStore() }, createAgentsMcpAuth(settings, verify)); await app.listen({ port: 0, host: "127.0.0.1" }); try { const base = `http://127.0.0.1:${(app.server.address() as { port: number }).port}`; const body = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }); const no = await fetch(base + "/mcp/agents", { method: "POST", headers: { "content-type": "application/json" }, body }); expect(no.status).toBe(401); expect(no.headers.get("www-authenticate")).toContain("resource_metadata="); const ok = await fetch(base + "/mcp/agents", { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer static-token-0123456789abcdef" }, body }); expect(ok.status).toBe(200); expect(((await ok.json()) as { result: { tools: unknown[] } }).result.tools.length).toBeGreaterThan(0); const meta = await fetch(base + "/.well-known/oauth-protected-resource"); expect(await meta.json()).toMatchObject({ resource: "https://x/api/agents/mcp", authorization_servers: [ISS] }); } finally { await app.close(); } }); });