|
| 1 | +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; |
| 2 | + |
| 3 | +vi.mock("virtual:emdash/auth", () => ({ authenticate: vi.fn() })); |
| 4 | +vi.mock("astro:middleware", () => ({ |
| 5 | + defineMiddleware: (handler: unknown) => handler, |
| 6 | +})); |
| 7 | +vi.mock("@emdash-cms/auth", () => ({ |
| 8 | + TOKEN_PREFIXES: {}, |
| 9 | + generatePrefixedToken: vi.fn(), |
| 10 | + hashPrefixedToken: vi.fn(), |
| 11 | + VALID_SCOPES: [], |
| 12 | + validateScopes: vi.fn(), |
| 13 | + hasScope: vi.fn(() => false), |
| 14 | + computeS256Challenge: vi.fn(), |
| 15 | + Role: { ADMIN: 50 }, |
| 16 | +})); |
| 17 | +vi.mock("@emdash-cms/auth/adapters/kysely", () => ({ |
| 18 | + createKyselyAdapter: vi.fn(() => ({ |
| 19 | + getUserById: vi.fn(async (id: string) => ({ |
| 20 | + id, |
| 21 | + email: "admin@test.com", |
| 22 | + name: "Admin", |
| 23 | + role: 50, |
| 24 | + disabled: 0, |
| 25 | + })), |
| 26 | + getUserByEmail: vi.fn(), |
| 27 | + })), |
| 28 | +})); |
| 29 | + |
| 30 | +type AuthMiddlewareModule = typeof import("../../../src/astro/middleware/auth.js"); |
| 31 | + |
| 32 | +let onRequest: AuthMiddlewareModule["onRequest"]; |
| 33 | + |
| 34 | +beforeAll(async () => { |
| 35 | + ({ onRequest } = await import("../../../src/astro/middleware/auth.js")); |
| 36 | +}); |
| 37 | + |
| 38 | +beforeEach(() => { |
| 39 | + vi.clearAllMocks(); |
| 40 | +}); |
| 41 | + |
| 42 | +afterEach(() => { |
| 43 | + vi.clearAllMocks(); |
| 44 | +}); |
| 45 | + |
| 46 | +async function runAuthMiddleware(opts: { |
| 47 | + pathname: string; |
| 48 | + method?: string; |
| 49 | + headers?: HeadersInit; |
| 50 | + sessionUserId?: string | null; |
| 51 | + siteUrl?: string; |
| 52 | +}) { |
| 53 | + const url = new URL(opts.pathname, "https://example.com"); |
| 54 | + const session = { |
| 55 | + get: vi.fn().mockResolvedValue(opts.sessionUserId ? { id: opts.sessionUserId } : null), |
| 56 | + set: vi.fn(), |
| 57 | + destroy: vi.fn(), |
| 58 | + }; |
| 59 | + const next = vi.fn(async () => new Response("ok")); |
| 60 | + const response = await onRequest( |
| 61 | + { |
| 62 | + url, |
| 63 | + request: new Request(url, { |
| 64 | + method: opts.method ?? "POST", |
| 65 | + headers: opts.headers, |
| 66 | + body: JSON.stringify({ |
| 67 | + jsonrpc: "2.0", |
| 68 | + id: 1, |
| 69 | + method: "initialize", |
| 70 | + params: { |
| 71 | + protocolVersion: "2025-03-26", |
| 72 | + capabilities: {}, |
| 73 | + clientInfo: { name: "debug", version: "1.0" }, |
| 74 | + }, |
| 75 | + }), |
| 76 | + }), |
| 77 | + locals: { |
| 78 | + emdash: { |
| 79 | + db: {}, |
| 80 | + config: opts.siteUrl ? { siteUrl: opts.siteUrl } : {}, |
| 81 | + }, |
| 82 | + }, |
| 83 | + session, |
| 84 | + redirect: (location: string) => |
| 85 | + new Response(null, { |
| 86 | + status: 302, |
| 87 | + headers: { Location: location }, |
| 88 | + }), |
| 89 | + } as Parameters<AuthMiddlewareModule["onRequest"]>[0], |
| 90 | + next, |
| 91 | + ); |
| 92 | + |
| 93 | + return { response, next, session }; |
| 94 | +} |
| 95 | + |
| 96 | +describe("MCP discovery auth middleware", () => { |
| 97 | + it("returns 401 with discovery metadata for unauthenticated MCP POST requests", async () => { |
| 98 | + const { response, next } = await runAuthMiddleware({ |
| 99 | + pathname: "/_emdash/api/mcp", |
| 100 | + headers: { "Content-Type": "application/json" }, |
| 101 | + }); |
| 102 | + |
| 103 | + expect(next).not.toHaveBeenCalled(); |
| 104 | + expect(response.status).toBe(401); |
| 105 | + expect(response.headers.get("WWW-Authenticate")).toBe( |
| 106 | + 'Bearer resource_metadata="https://example.com/.well-known/oauth-protected-resource"', |
| 107 | + ); |
| 108 | + await expect(response.json()).resolves.toEqual({ |
| 109 | + error: { code: "NOT_AUTHENTICATED", message: "Not authenticated" }, |
| 110 | + }); |
| 111 | + }); |
| 112 | + |
| 113 | + it("does not read the session for anonymous MCP POST discovery requests", async () => { |
| 114 | + const { response, next, session } = await runAuthMiddleware({ |
| 115 | + pathname: "/_emdash/api/mcp", |
| 116 | + headers: { "Content-Type": "application/json" }, |
| 117 | + }); |
| 118 | + |
| 119 | + expect(next).not.toHaveBeenCalled(); |
| 120 | + expect(response.status).toBe(401); |
| 121 | + expect(session.get).not.toHaveBeenCalled(); |
| 122 | + }); |
| 123 | + |
| 124 | + it("uses the configured public origin for anonymous MCP POST discovery responses", async () => { |
| 125 | + const { response, next } = await runAuthMiddleware({ |
| 126 | + pathname: "/_emdash/api/mcp", |
| 127 | + headers: { "Content-Type": "application/json" }, |
| 128 | + siteUrl: "https://public.example.com", |
| 129 | + }); |
| 130 | + |
| 131 | + expect(next).not.toHaveBeenCalled(); |
| 132 | + expect(response.status).toBe(401); |
| 133 | + expect(response.headers.get("WWW-Authenticate")).toBe( |
| 134 | + 'Bearer resource_metadata="https://public.example.com/.well-known/oauth-protected-resource"', |
| 135 | + ); |
| 136 | + }); |
| 137 | + |
| 138 | + it("returns 401 with discovery metadata for invalid bearer tokens on MCP POST", async () => { |
| 139 | + const { response, next } = await runAuthMiddleware({ |
| 140 | + pathname: "/_emdash/api/mcp", |
| 141 | + headers: { |
| 142 | + Authorization: "Bearer invalid", |
| 143 | + "Content-Type": "application/json", |
| 144 | + }, |
| 145 | + }); |
| 146 | + |
| 147 | + expect(next).not.toHaveBeenCalled(); |
| 148 | + expect(response.status).toBe(401); |
| 149 | + expect(response.headers.get("WWW-Authenticate")).toBe( |
| 150 | + 'Bearer resource_metadata="https://example.com/.well-known/oauth-protected-resource"', |
| 151 | + ); |
| 152 | + await expect(response.json()).resolves.toEqual({ |
| 153 | + error: { code: "INVALID_TOKEN", message: "Invalid or expired token" }, |
| 154 | + }); |
| 155 | + }); |
| 156 | + |
| 157 | + it("rejects MCP POST requests that only have session auth", async () => { |
| 158 | + const { response, next, session } = await runAuthMiddleware({ |
| 159 | + pathname: "/_emdash/api/mcp", |
| 160 | + headers: { |
| 161 | + "Content-Type": "application/json", |
| 162 | + "X-EmDash-Request": "1", |
| 163 | + }, |
| 164 | + sessionUserId: "user_1", |
| 165 | + }); |
| 166 | + |
| 167 | + expect(next).not.toHaveBeenCalled(); |
| 168 | + expect(response.status).toBe(401); |
| 169 | + expect(session.get).not.toHaveBeenCalled(); |
| 170 | + await expect(response.json()).resolves.toEqual({ |
| 171 | + error: { code: "NOT_AUTHENTICATED", message: "Not authenticated" }, |
| 172 | + }); |
| 173 | + }); |
| 174 | + |
| 175 | + it("still rejects non-MCP API POST requests without the CSRF header", async () => { |
| 176 | + const { response, next } = await runAuthMiddleware({ |
| 177 | + pathname: "/_emdash/api/content/posts", |
| 178 | + headers: { "Content-Type": "application/json" }, |
| 179 | + }); |
| 180 | + |
| 181 | + expect(next).not.toHaveBeenCalled(); |
| 182 | + expect(response.status).toBe(403); |
| 183 | + await expect(response.json()).resolves.toEqual({ |
| 184 | + error: { code: "CSRF_REJECTED", message: "Missing required header" }, |
| 185 | + }); |
| 186 | + }); |
| 187 | +}); |
0 commit comments