Remove OAuth authorization flows and use API key authentication for MCP
This commit is contained in:
1 parent
16acac5530
commit
b185837063
85 files changed
+383
-4631
No files matched your search
+46
-85
@@ -1,7 +1,5 @@
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import { checkApiKeyAuth } from '@/lib/auth';
|
||||
import { createAccessToken } from '@/lib/oauth/tokens';
|
||||
import { getUser } from '@/queries/prisma/user';
|
||||
import { authenticateMcpRequest, mcpAuthErrorResponse } from './auth';
|
||||
|
||||
vi.mock('@/lib/auth', () => ({
|
||||
@@ -9,115 +7,78 @@ vi.mock('@/lib/auth', () => ({
|
||||
checkApiKeyAuth: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/queries/prisma/user', () => ({
|
||||
getUser: vi.fn(),
|
||||
}));
|
||||
|
||||
const checkApiKeyAuthMock = vi.mocked(checkApiKeyAuth);
|
||||
const getUserMock = vi.mocked(getUser);
|
||||
const ISSUER = 'https://analytics.example.com';
|
||||
const USER = { id: 'user-1', username: 'admin', role: 'user', password: 'pw' };
|
||||
|
||||
function request(token?: string) {
|
||||
return new Request(`${ISSUER}/mcp`, {
|
||||
return new Request('https://analytics.example.com/mcp', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
host: 'analytics.example.com',
|
||||
'x-forwarded-proto': 'https',
|
||||
...(token ? { authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
headers: token ? { authorization: `Bearer ${token}` } : {},
|
||||
});
|
||||
}
|
||||
|
||||
function accessToken(overrides: Record<string, unknown> = {}) {
|
||||
return createAccessToken({
|
||||
userId: USER.id,
|
||||
clientId: 'https://app.example.com/client.json',
|
||||
scopes: ['websites:read', 'analytics:read'],
|
||||
issuer: ISSUER,
|
||||
resource: `${ISSUER}/mcp`,
|
||||
passwordHash: USER.password,
|
||||
...overrides,
|
||||
}).token;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.APP_SECRET = 'test';
|
||||
delete process.env.OAUTH_ISSUER;
|
||||
delete process.env.CLOUD_MODE;
|
||||
vi.unstubAllEnvs();
|
||||
vi.stubEnv('CLOUD_MODE', '');
|
||||
checkApiKeyAuthMock.mockReset();
|
||||
getUserMock.mockReset();
|
||||
getUserMock.mockResolvedValue({ ...USER } as never);
|
||||
});
|
||||
|
||||
describe('authenticateMcpRequest', () => {
|
||||
test('rejects missing tokens with a resource metadata challenge', async () => {
|
||||
test('rejects missing tokens with an API key challenge', async () => {
|
||||
const result = await authenticateMcpRequest(request());
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
|
||||
const response = mcpAuthErrorResponse(result as never, request().headers);
|
||||
const response = mcpAuthErrorResponse(result);
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
expect(response.headers.get('www-authenticate')).toContain(
|
||||
`resource_metadata="${ISSUER}/.well-known/oauth-protected-resource/mcp"`,
|
||||
);
|
||||
expect(response.headers.get('www-authenticate')).toContain(
|
||||
'scope="websites:read analytics:read"',
|
||||
expect(response.headers.get('www-authenticate')).toBe(
|
||||
'Bearer realm="Umami MCP", error="invalid_request"',
|
||||
);
|
||||
expect(response.headers.get('cache-control')).toBe('no-store');
|
||||
});
|
||||
|
||||
test('accepts OAuth access tokens issued for this resource', async () => {
|
||||
const result = await authenticateMcpRequest(request(accessToken()));
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
|
||||
if (result.ok) {
|
||||
expect(result.userId).toBe(USER.id);
|
||||
expect(result.authInfo).toMatchObject({
|
||||
clientId: 'https://app.example.com/client.json',
|
||||
scopes: ['analytics:read', 'websites:read'],
|
||||
test.each(['not-a-token', 'eyJhbGciOiJIUzI1NiJ9.eyJ0eXBlIjoib2F1dGhfYWNjZXNzIn0.signature'])(
|
||||
'rejects non-API-key credentials: %s',
|
||||
async token => {
|
||||
await expect(authenticateMcpRequest(request(token))).resolves.toMatchObject({
|
||||
ok: false,
|
||||
status: 401,
|
||||
});
|
||||
expect(result.authInfo.extra).toMatchObject({ userId: USER.id, authType: 'oauth' });
|
||||
}
|
||||
});
|
||||
expect(checkApiKeyAuthMock).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
test('rejects tokens issued for another deployment', async () => {
|
||||
const foreign = createAccessToken({
|
||||
userId: USER.id,
|
||||
clientId: 'c',
|
||||
scopes: ['websites:read'],
|
||||
issuer: 'https://other.example.com',
|
||||
resource: 'https://other.example.com/mcp',
|
||||
}).token;
|
||||
|
||||
const result = await authenticateMcpRequest(request(foreign));
|
||||
|
||||
expect(result).toMatchObject({ ok: false, status: 401, error: 'invalid_token' });
|
||||
});
|
||||
|
||||
test('rejects session tokens and garbage', async () => {
|
||||
await expect(authenticateMcpRequest(request('not-a-token'))).resolves.toMatchObject({
|
||||
ok: false,
|
||||
status: 401,
|
||||
});
|
||||
});
|
||||
|
||||
test('accepts self-hosted API keys', async () => {
|
||||
test('accepts self-hosted API keys and preserves owner identity', async () => {
|
||||
checkApiKeyAuthMock.mockResolvedValue({
|
||||
token: 'umami_key',
|
||||
user: { id: USER.id, username: 'admin', role: 'user', isAdmin: false },
|
||||
authType: 'api-key',
|
||||
user: { id: 'user-1' },
|
||||
apiKey: { id: 'key-1', name: 'MCP' },
|
||||
} as never);
|
||||
|
||||
const result = await authenticateMcpRequest(request('umami_key'));
|
||||
await expect(authenticateMcpRequest(request('umami_key'))).resolves.toMatchObject({
|
||||
ok: true,
|
||||
userId: 'user-1',
|
||||
authInfo: {
|
||||
token: 'umami_key',
|
||||
clientId: 'api-key:key-1',
|
||||
scopes: [],
|
||||
extra: { userId: 'user-1', authType: 'api-key' },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
test('rejects revoked or unknown keys', async () => {
|
||||
checkApiKeyAuthMock.mockResolvedValue(null);
|
||||
await expect(authenticateMcpRequest(request('umami_revoked'))).resolves.toMatchObject({
|
||||
ok: false,
|
||||
status: 401,
|
||||
error: 'invalid_token',
|
||||
});
|
||||
});
|
||||
|
||||
if (result.ok) {
|
||||
expect(result.authInfo.clientId).toBe('api-key:key-1');
|
||||
expect(result.authInfo.scopes).toEqual(['websites:read', 'analytics:read']);
|
||||
}
|
||||
test('rejects self-hosted keys in Cloud mode', async () => {
|
||||
vi.stubEnv('CLOUD_MODE', '1');
|
||||
await expect(authenticateMcpRequest(request('umami_key'))).resolves.toMatchObject({
|
||||
ok: false,
|
||||
status: 401,
|
||||
});
|
||||
expect(checkApiKeyAuthMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+13
-88
@@ -1,24 +1,12 @@
|
||||
import type { AuthInfo } from '@umami/mcp';
|
||||
import { isApiKey, isApiKeyEnabled } from '@/lib/api-key';
|
||||
import { checkApiKeyAuth, getBearerToken } from '@/lib/auth';
|
||||
import { getIssuer, getOAuthEndpoints, isOAuthEnabled } from '@/lib/oauth/config';
|
||||
import { OAUTH_SCOPES } from '@/lib/oauth/scopes';
|
||||
import { looksLikeAccessToken, verifyAccessToken } from '@/lib/oauth/tokens';
|
||||
import { buildOAuthAuth } from '@/lib/oauth/verify';
|
||||
|
||||
export type McpAuthResult =
|
||||
| { ok: true; authInfo: AuthInfo; userId: string }
|
||||
| { ok: false; status: 401 | 403; error: string; description: string; scope?: string };
|
||||
| { ok: false; status: 401; error: string; description: string };
|
||||
|
||||
/**
|
||||
* Authenticates a request to the embedded MCP endpoint.
|
||||
*
|
||||
* Accepted credentials:
|
||||
* - OAuth access tokens issued by this deployment for the `/mcp` resource (primary).
|
||||
* - Self-hosted API keys (`umami_…`), so a remote MCP client can be configured without OAuth.
|
||||
*
|
||||
* Browser session tokens are deliberately rejected.
|
||||
*/
|
||||
/** The embedded MCP endpoint accepts self-hosted API keys only. */
|
||||
export async function authenticateMcpRequest(request: Request): Promise<McpAuthResult> {
|
||||
const token = getBearerToken(request);
|
||||
|
||||
@@ -27,65 +15,18 @@ export async function authenticateMcpRequest(request: Request): Promise<McpAuthR
|
||||
ok: false,
|
||||
status: 401,
|
||||
error: 'invalid_request',
|
||||
description: 'Missing bearer token.',
|
||||
description: 'Missing bearer API key.',
|
||||
};
|
||||
}
|
||||
|
||||
if (isApiKeyEnabled() && isApiKey(token)) {
|
||||
const auth = await checkApiKeyAuth(request, token);
|
||||
|
||||
if (!auth?.user?.id) {
|
||||
return { ok: false, status: 401, error: 'invalid_token', description: 'Invalid API key.' };
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
userId: auth.user.id,
|
||||
authInfo: {
|
||||
token,
|
||||
clientId: `api-key:${auth.apiKey.id}`,
|
||||
scopes: [...OAUTH_SCOPES],
|
||||
extra: { userId: auth.user.id, authType: 'api-key' },
|
||||
},
|
||||
};
|
||||
if (!isApiKeyEnabled() || !isApiKey(token)) {
|
||||
return { ok: false, status: 401, error: 'invalid_token', description: 'Invalid API key.' };
|
||||
}
|
||||
|
||||
if (!looksLikeAccessToken(token) || !isOAuthEnabled()) {
|
||||
return { ok: false, status: 401, error: 'invalid_token', description: 'Invalid bearer token.' };
|
||||
}
|
||||
const auth = await checkApiKeyAuth(request, token);
|
||||
|
||||
const verified = verifyAccessToken(token);
|
||||
|
||||
if (!verified) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 401,
|
||||
error: 'invalid_token',
|
||||
description: 'Access token is invalid or expired.',
|
||||
};
|
||||
}
|
||||
|
||||
// Audience binding: the token must have been issued for this deployment's MCP resource.
|
||||
const endpoints = getOAuthEndpoints(request.headers);
|
||||
|
||||
if (verified.resource !== endpoints.resource || verified.issuer !== getIssuer(request.headers)) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 401,
|
||||
error: 'invalid_token',
|
||||
description: 'Access token was not issued for this resource.',
|
||||
};
|
||||
}
|
||||
|
||||
const auth = await buildOAuthAuth(token, verified);
|
||||
|
||||
if (!auth) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 401,
|
||||
error: 'invalid_token',
|
||||
description: 'Access token is no longer valid.',
|
||||
};
|
||||
if (!auth?.user?.id) {
|
||||
return { ok: false, status: 401, error: 'invalid_token', description: 'Invalid API key.' };
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -93,42 +34,26 @@ export async function authenticateMcpRequest(request: Request): Promise<McpAuthR
|
||||
userId: auth.user.id,
|
||||
authInfo: {
|
||||
token,
|
||||
clientId: verified.clientId,
|
||||
scopes: verified.scopes,
|
||||
expiresAt: Math.floor(verified.expiresAt / 1000),
|
||||
resource: new URL(verified.resource),
|
||||
extra: { userId: auth.user.id, authType: 'oauth', tokenId: verified.tokenId },
|
||||
clientId: `api-key:${auth.apiKey.id}`,
|
||||
scopes: [],
|
||||
extra: { userId: auth.user.id, authType: 'api-key' },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function mcpAuthErrorResponse(result: McpAuthResult, headers: Pick<Headers, 'get'>) {
|
||||
export function mcpAuthErrorResponse(result: McpAuthResult) {
|
||||
if (result.ok) {
|
||||
throw new Error('mcpAuthErrorResponse called with a successful result.');
|
||||
}
|
||||
|
||||
// Explicit narrowing: the project compiles without strictNullChecks, so the guard above does
|
||||
// not narrow the union automatically.
|
||||
const failure = result as Extract<McpAuthResult, { ok: false }>;
|
||||
const endpoints = getOAuthEndpoints(headers);
|
||||
const parts = [
|
||||
`Bearer error="${failure.error}"`,
|
||||
`error_description="${failure.description.replace(/"/g, "'")}"`,
|
||||
`resource_metadata="${endpoints.protectedResourceMetadata}"`,
|
||||
];
|
||||
|
||||
if (failure.scope) {
|
||||
parts.push(`scope="${failure.scope}"`);
|
||||
} else if (failure.status === 401) {
|
||||
parts.push(`scope="${OAUTH_SCOPES.join(' ')}"`);
|
||||
}
|
||||
|
||||
return Response.json(
|
||||
{ error: failure.error, error_description: failure.description },
|
||||
{
|
||||
status: failure.status,
|
||||
headers: {
|
||||
'www-authenticate': parts.join(', '),
|
||||
'www-authenticate': `Bearer realm="Umami MCP", error="${failure.error}"`,
|
||||
'cache-control': 'no-store',
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,17 +1,7 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { OAUTH_ROUTE_SCOPES } from '@/lib/oauth/scopes';
|
||||
import { MCP_DISPATCH_ROUTES, matchDispatchRoute } from './dispatch';
|
||||
import { matchDispatchRoute } from './dispatch';
|
||||
|
||||
describe('MCP dispatch table', () => {
|
||||
test('covers exactly the OAuth-allowlisted routes', () => {
|
||||
const dispatch = MCP_DISPATCH_ROUTES.map(route => `${route.method} ${route.path}`).sort();
|
||||
const allowlist = OAUTH_ROUTE_SCOPES.map(
|
||||
route => `${route.method.toUpperCase()} ${route.path}`,
|
||||
).sort();
|
||||
|
||||
expect(dispatch).toEqual(allowlist);
|
||||
});
|
||||
|
||||
test('matches concrete paths and extracts parameters', () => {
|
||||
const match = matchDispatchRoute('GET', '/api/websites/abc/sessions/def/activity');
|
||||
|
||||
|
||||
@@ -13,8 +13,7 @@ export interface DispatchRoute {
|
||||
|
||||
/**
|
||||
* The API routes the embedded MCP server may call, dispatched in-process (no loopback HTTP).
|
||||
* This list must stay identical to `OAUTH_ROUTE_SCOPES` in `src/lib/oauth/scopes.ts`;
|
||||
* `dispatch.test.ts` enforces that. Anything not listed here is unreachable from MCP.
|
||||
* Anything not listed here is unreachable from MCP.
|
||||
*/
|
||||
export const MCP_DISPATCH_ROUTES: readonly DispatchRoute[] = [
|
||||
{ method: 'GET', path: '/api/me', load: () => import('@/app/api/me/route') },
|
||||
|
||||
Reference in new issue
Block a user