-
Notifications
You must be signed in to change notification settings - Fork 703
fix(core): return OAuth discovery 401 for unauthenticated MCP POSTs #371
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
pejmanjohn
wants to merge
8
commits into
emdash-cms:main
Choose a base branch
from
pejmanjohn:contrib/emdash-cms-emdash-mcp-post-oauth-discovery
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+217
−20
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
deb7084
fix(core): return OAuth discovery 401 for MCP POSTs
pejmanjohn 2d47dd1
chore: add changeset for MCP OAuth discovery fix
pejmanjohn 81b366c
style: format
emdashbot[bot] 7a8089f
Merge branch 'main' into contrib/emdash-cms-emdash-mcp-post-oauth-dis…
ascorbic f676da5
fix(core): centralize MCP discovery auth handling
pejmanjohn 59ee1fb
style: format
emdashbot[bot] 56ce798
fix(core): make MCP auth bearer-only
pejmanjohn f80b9cd
Merge branch 'main' into contrib/emdash-cms-emdash-mcp-post-oauth-dis…
ascorbic File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "emdash": patch | ||
| --- | ||
|
|
||
| Fix MCP OAuth discovery for unauthenticated POST requests. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
172 changes: 172 additions & 0 deletions
172
packages/core/tests/unit/auth/mcp-discovery-post.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; | ||
|
|
||
| vi.mock("virtual:emdash/auth", () => ({ authenticate: vi.fn() })); | ||
| vi.mock("astro:middleware", () => ({ | ||
| defineMiddleware: (handler: unknown) => handler, | ||
| })); | ||
| vi.mock("@emdash-cms/auth", () => ({ | ||
| TOKEN_PREFIXES: {}, | ||
| generatePrefixedToken: vi.fn(), | ||
| hashPrefixedToken: vi.fn(), | ||
| VALID_SCOPES: [], | ||
| validateScopes: vi.fn(), | ||
| hasScope: vi.fn(() => false), | ||
| computeS256Challenge: vi.fn(), | ||
| Role: { ADMIN: 50 }, | ||
| })); | ||
| vi.mock("@emdash-cms/auth/adapters/kysely", () => ({ | ||
| createKyselyAdapter: vi.fn(() => ({ | ||
| getUserById: vi.fn(async (id: string) => ({ | ||
| id, | ||
| email: "admin@test.com", | ||
| name: "Admin", | ||
| role: 50, | ||
| disabled: 0, | ||
| })), | ||
| getUserByEmail: vi.fn(), | ||
| })), | ||
| })); | ||
|
|
||
| type AuthMiddlewareModule = typeof import("../../../src/astro/middleware/auth.js"); | ||
|
|
||
| let onRequest: AuthMiddlewareModule["onRequest"]; | ||
|
|
||
| beforeAll(async () => { | ||
| ({ onRequest } = await import("../../../src/astro/middleware/auth.js")); | ||
| }); | ||
|
|
||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| async function runAuthMiddleware(opts: { | ||
| pathname: string; | ||
| method?: string; | ||
| headers?: HeadersInit; | ||
| sessionUserId?: string | null; | ||
| }) { | ||
| const url = new URL(opts.pathname, "https://example.com"); | ||
| const session = { | ||
| get: vi.fn().mockResolvedValue(opts.sessionUserId ? { id: opts.sessionUserId } : null), | ||
| set: vi.fn(), | ||
| destroy: vi.fn(), | ||
| }; | ||
| const next = vi.fn(async () => new Response("ok")); | ||
| const response = await onRequest( | ||
| { | ||
| url, | ||
| request: new Request(url, { | ||
| method: opts.method ?? "POST", | ||
| headers: opts.headers, | ||
| body: JSON.stringify({ | ||
| jsonrpc: "2.0", | ||
| id: 1, | ||
| method: "initialize", | ||
| params: { | ||
| protocolVersion: "2025-03-26", | ||
| capabilities: {}, | ||
| clientInfo: { name: "debug", version: "1.0" }, | ||
| }, | ||
| }), | ||
| }), | ||
| locals: { | ||
| emdash: { | ||
| db: {}, | ||
| config: {}, | ||
| }, | ||
| }, | ||
| session, | ||
| redirect: (location: string) => | ||
| new Response(null, { | ||
| status: 302, | ||
| headers: { Location: location }, | ||
| }), | ||
| } as Parameters<AuthMiddlewareModule["onRequest"]>[0], | ||
| next, | ||
| ); | ||
|
|
||
| return { response, next, session }; | ||
| } | ||
|
|
||
| describe("MCP discovery auth middleware", () => { | ||
| it("returns 401 with discovery metadata for unauthenticated MCP POST requests", async () => { | ||
| const { response, next } = await runAuthMiddleware({ | ||
| pathname: "/_emdash/api/mcp", | ||
| headers: { "Content-Type": "application/json" }, | ||
| }); | ||
|
|
||
| expect(next).not.toHaveBeenCalled(); | ||
| expect(response.status).toBe(401); | ||
| expect(response.headers.get("WWW-Authenticate")).toBe( | ||
| 'Bearer resource_metadata="https://example.com/.well-known/oauth-protected-resource"', | ||
| ); | ||
| await expect(response.json()).resolves.toEqual({ | ||
| error: { code: "NOT_AUTHENTICATED", message: "Not authenticated" }, | ||
| }); | ||
| }); | ||
|
|
||
| it("does not read the session for anonymous MCP POST discovery requests", async () => { | ||
| const { response, next, session } = await runAuthMiddleware({ | ||
| pathname: "/_emdash/api/mcp", | ||
| headers: { "Content-Type": "application/json" }, | ||
| }); | ||
|
|
||
| expect(next).not.toHaveBeenCalled(); | ||
| expect(response.status).toBe(401); | ||
| expect(session.get).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns 401 with discovery metadata for invalid bearer tokens on MCP POST", async () => { | ||
| const { response, next } = await runAuthMiddleware({ | ||
| pathname: "/_emdash/api/mcp", | ||
| headers: { | ||
| Authorization: "Bearer invalid", | ||
| "Content-Type": "application/json", | ||
| }, | ||
| }); | ||
|
|
||
| expect(next).not.toHaveBeenCalled(); | ||
| expect(response.status).toBe(401); | ||
| expect(response.headers.get("WWW-Authenticate")).toBe( | ||
| 'Bearer resource_metadata="https://example.com/.well-known/oauth-protected-resource"', | ||
| ); | ||
| await expect(response.json()).resolves.toEqual({ | ||
| error: { code: "INVALID_TOKEN", message: "Invalid or expired token" }, | ||
| }); | ||
| }); | ||
|
|
||
| it("rejects MCP POST requests that only have session auth", async () => { | ||
| const { response, next, session } = await runAuthMiddleware({ | ||
| pathname: "/_emdash/api/mcp", | ||
| headers: { | ||
| "Content-Type": "application/json", | ||
| "X-EmDash-Request": "1", | ||
| }, | ||
| sessionUserId: "user_1", | ||
| }); | ||
|
|
||
| expect(next).not.toHaveBeenCalled(); | ||
| expect(response.status).toBe(401); | ||
| expect(session.get).not.toHaveBeenCalled(); | ||
| await expect(response.json()).resolves.toEqual({ | ||
| error: { code: "NOT_AUTHENTICATED", message: "Not authenticated" }, | ||
| }); | ||
| }); | ||
|
|
||
| it("still rejects non-MCP API POST requests without the CSRF header", async () => { | ||
| const { response, next } = await runAuthMiddleware({ | ||
| pathname: "/_emdash/api/content/posts", | ||
| headers: { "Content-Type": "application/json" }, | ||
| }); | ||
|
|
||
| expect(next).not.toHaveBeenCalled(); | ||
| expect(response.status).toBe(403); | ||
| await expect(response.json()).resolves.toEqual({ | ||
| error: { code: "CSRF_REJECTED", message: "Missing required header" }, | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This will need to use
getPublicOrigininstead ofurl.origin, meaningmcpUnauthorizedResponseneeds to be passed the config.