diff --git a/CHANGELOG.md b/CHANGELOG.md index a603d8407f..3ec22cda08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased +### Added + +- Added discovery and metadata endpoints for Model Context Protocol (MCP) OAuth 2.1 (RFC 8414 & RFC 9728) + ### Changed - Improved the language localization for Spanish (`es`) diff --git a/apps/api/src/app/__snapshots__/app.module.spec.ts.snap b/apps/api/src/app/__snapshots__/app.module.spec.ts.snap index 7701f430eb..546628c267 100644 --- a/apps/api/src/app/__snapshots__/app.module.spec.ts.snap +++ b/apps/api/src/app/__snapshots__/app.module.spec.ts.snap @@ -254,6 +254,14 @@ exports[`AppModule should keep the security of each route 1`] = ` "watchlist:delete", ], }, + "GET /.well-known/oauth-authorization-server (version neutral)": { + "guards": [], + "interceptors": [], + }, + "GET /.well-known/oauth-protected-resource/mcp (version neutral)": { + "guards": [], + "interceptors": [], + }, "GET /access": { "allowDuringImpersonation": true, "guards": [ diff --git a/apps/api/src/app/app.module.spec.ts b/apps/api/src/app/app.module.spec.ts index f146398d20..cab95bd302 100644 --- a/apps/api/src/app/app.module.spec.ts +++ b/apps/api/src/app/app.module.spec.ts @@ -60,6 +60,8 @@ const AUTHENTICATION_STRATEGIES = ['api-key', 'google', 'jwt', 'oidc']; * are not served by a controller */ const PUBLIC_ROUTES = [ + 'GET /.well-known/oauth-authorization-server', + 'GET /.well-known/oauth-protected-resource/mcp', 'GET /assets/:languageCode/site.webmanifest', 'GET /auth/google', 'GET /auth/google/callback', diff --git a/apps/api/src/app/app.module.ts b/apps/api/src/app/app.module.ts index e4e6d7368b..639cd97e11 100644 --- a/apps/api/src/app/app.module.ts +++ b/apps/api/src/app/app.module.ts @@ -57,6 +57,7 @@ import { InfoModule } from './endpoints/info/info.module'; import { LogoModule } from './endpoints/logo/logo.module'; import { MarketDataModule } from './endpoints/market-data/market-data.module'; import { McpModule } from './endpoints/mcp/mcp.module'; +import { OAuthModule } from './endpoints/oauth/oauth.module'; import { PlatformsModule } from './endpoints/platforms/platforms.module'; import { PublicModule } from './endpoints/public/public.module'; import { SitemapModule } from './endpoints/sitemap/sitemap.module'; @@ -127,6 +128,7 @@ import { PortfolioModule } from './portfolio/portfolio.module'; LogoModule, MarketDataModule, McpModule, + OAuthModule, PlatformsModule, PortfolioModule, PortfolioSnapshotQueueModule, @@ -145,6 +147,10 @@ import { PortfolioModule } from './portfolio/portfolio.module'; rootPath: join(__dirname, '..', 'client') }), ServeStaticModule.forRoot({ + exclude: [ + '/.well-known/oauth-authorization-server', + '/.well-known/oauth-protected-resource/*wildcard' + ], rootPath: join(__dirname, '..', 'client', '.well-known'), serveRoot: '/.well-known' }), diff --git a/apps/api/src/app/endpoints/oauth/oauth-metadata.controller.spec.ts b/apps/api/src/app/endpoints/oauth/oauth-metadata.controller.spec.ts new file mode 100644 index 0000000000..eec1ee7879 --- /dev/null +++ b/apps/api/src/app/endpoints/oauth/oauth-metadata.controller.spec.ts @@ -0,0 +1,136 @@ +import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; + +import { NotFoundException } from '@nestjs/common'; + +import { OAuthMetadataController } from './oauth-metadata.controller'; + +describe('OAuthMetadataController', () => { + let configurationService: ConfigurationService; + let controller: OAuthMetadataController; + + const mockConfig: Record = { + ENABLE_FEATURE_MCP: true, + ENABLE_FEATURE_MCP_OAUTH: true, + ROOT_URL: 'http://localhost:3333' + }; + + beforeEach(() => { + configurationService = { + get: jest.fn((key: string) => { + return mockConfig[key]; + }) + } as unknown as ConfigurationService; + + controller = new OAuthMetadataController(configurationService); + }); + + describe('getProtectedResourceMetadata', () => { + it('throws NotFoundException when ENABLE_FEATURE_MCP is false', () => { + mockConfig.ENABLE_FEATURE_MCP = false; + mockConfig.ENABLE_FEATURE_MCP_OAUTH = true; + + expect(() => { + return controller.getProtectedResourceMetadata(); + }).toThrow(NotFoundException); + }); + + it('throws NotFoundException when ENABLE_FEATURE_MCP_OAUTH is false', () => { + mockConfig.ENABLE_FEATURE_MCP = true; + mockConfig.ENABLE_FEATURE_MCP_OAUTH = false; + + expect(() => { + return controller.getProtectedResourceMetadata(); + }).toThrow(NotFoundException); + }); + + it('returns RFC 9728 protected resource metadata when feature flags are enabled', () => { + mockConfig.ENABLE_FEATURE_MCP = true; + mockConfig.ENABLE_FEATURE_MCP_OAUTH = true; + mockConfig.ROOT_URL = 'http://localhost:3333'; + + const result = controller.getProtectedResourceMetadata(); + + expect(result).toEqual({ + authorization_servers: ['http://localhost:3333'], + bearer_methods_supported: ['header'], + resource: 'http://localhost:3333/mcp', + resource_name: 'Ghostfolio' + }); + }); + + it('normalizes ROOT_URL with trailing slash', () => { + mockConfig.ENABLE_FEATURE_MCP = true; + mockConfig.ENABLE_FEATURE_MCP_OAUTH = true; + mockConfig.ROOT_URL = 'https://ghostfol.io///'; + + const result = controller.getProtectedResourceMetadata(); + + expect(result).toEqual({ + authorization_servers: ['https://ghostfol.io'], + bearer_methods_supported: ['header'], + resource: 'https://ghostfol.io/mcp', + resource_name: 'Ghostfolio' + }); + }); + }); + + describe('getAuthorizationServerMetadata', () => { + it('throws NotFoundException when ENABLE_FEATURE_MCP is false', () => { + mockConfig.ENABLE_FEATURE_MCP = false; + mockConfig.ENABLE_FEATURE_MCP_OAUTH = true; + + expect(() => { + return controller.getAuthorizationServerMetadata(); + }).toThrow(NotFoundException); + }); + + it('throws NotFoundException when ENABLE_FEATURE_MCP_OAUTH is false', () => { + mockConfig.ENABLE_FEATURE_MCP = true; + mockConfig.ENABLE_FEATURE_MCP_OAUTH = false; + + expect(() => { + return controller.getAuthorizationServerMetadata(); + }).toThrow(NotFoundException); + }); + + it('returns RFC 8414 authorization server metadata when feature flags are enabled', () => { + mockConfig.ENABLE_FEATURE_MCP = true; + mockConfig.ENABLE_FEATURE_MCP_OAUTH = true; + mockConfig.ROOT_URL = 'http://localhost:3333'; + + const result = controller.getAuthorizationServerMetadata(); + + expect(result).toEqual({ + authorization_endpoint: 'http://localhost:3333/oauth/authorize', + authorization_response_iss_parameter_supported: true, + client_id_metadata_document_supported: true, + code_challenge_methods_supported: ['S256'], + grant_types_supported: ['authorization_code', 'refresh_token'], + issuer: 'http://localhost:3333', + response_types_supported: ['code'], + token_endpoint: 'http://localhost:3333/api/v1/oauth/token', + token_endpoint_auth_methods_supported: ['none'] + }); + }); + + it('normalizes ROOT_URL with trailing slash', () => { + mockConfig.ENABLE_FEATURE_MCP = true; + mockConfig.ENABLE_FEATURE_MCP_OAUTH = true; + mockConfig.ROOT_URL = 'https://ghostfol.io/'; + + const result = controller.getAuthorizationServerMetadata(); + + expect(result).toEqual({ + authorization_endpoint: 'https://ghostfol.io/oauth/authorize', + authorization_response_iss_parameter_supported: true, + client_id_metadata_document_supported: true, + code_challenge_methods_supported: ['S256'], + grant_types_supported: ['authorization_code', 'refresh_token'], + issuer: 'https://ghostfol.io', + response_types_supported: ['code'], + token_endpoint: 'https://ghostfol.io/api/v1/oauth/token', + token_endpoint_auth_methods_supported: ['none'] + }); + }); + }); +}); diff --git a/apps/api/src/app/endpoints/oauth/oauth-metadata.controller.ts b/apps/api/src/app/endpoints/oauth/oauth-metadata.controller.ts new file mode 100644 index 0000000000..76635bf5e7 --- /dev/null +++ b/apps/api/src/app/endpoints/oauth/oauth-metadata.controller.ts @@ -0,0 +1,71 @@ +import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; +import { MCP_ENDPOINT } from '@ghostfolio/common/config'; + +import { + Controller, + Get, + Header, + NotFoundException, + VERSION_NEUTRAL, + Version +} from '@nestjs/common'; + +@Controller('.well-known') +export class OAuthMetadataController { + public constructor( + private readonly configurationService: ConfigurationService + ) {} + + @Get('oauth-protected-resource/mcp') + @Header('Cache-Control', 'public, max-age=3600') + @Version(VERSION_NEUTRAL) + public getProtectedResourceMetadata() { + if ( + !this.configurationService.get('ENABLE_FEATURE_MCP') || + !this.configurationService.get('ENABLE_FEATURE_MCP_OAUTH') + ) { + throw new NotFoundException(); + } + + const rootUrl = (this.configurationService.get('ROOT_URL') || '').replace( + /\/+$/, + '' + ); + + return { + authorization_servers: [rootUrl], + bearer_methods_supported: ['header'], + resource: `${rootUrl}${MCP_ENDPOINT}`, + resource_name: 'Ghostfolio' + }; + } + + @Get('oauth-authorization-server') + @Header('Cache-Control', 'public, max-age=3600') + @Version(VERSION_NEUTRAL) + public getAuthorizationServerMetadata() { + if ( + !this.configurationService.get('ENABLE_FEATURE_MCP') || + !this.configurationService.get('ENABLE_FEATURE_MCP_OAUTH') + ) { + throw new NotFoundException(); + } + + const rootUrl = (this.configurationService.get('ROOT_URL') || '').replace( + /\/+$/, + '' + ); + + return { + authorization_endpoint: `${rootUrl}/oauth/authorize`, + authorization_response_iss_parameter_supported: true, + client_id_metadata_document_supported: true, + code_challenge_methods_supported: ['S256'], + grant_types_supported: ['authorization_code', 'refresh_token'], + issuer: rootUrl, + response_types_supported: ['code'], + token_endpoint: `${rootUrl}/api/v1/oauth/token`, + token_endpoint_auth_methods_supported: ['none'] + }; + } +} diff --git a/apps/api/src/app/endpoints/oauth/oauth.module.ts b/apps/api/src/app/endpoints/oauth/oauth.module.ts new file mode 100644 index 0000000000..b025ac5c45 --- /dev/null +++ b/apps/api/src/app/endpoints/oauth/oauth.module.ts @@ -0,0 +1,11 @@ +import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module'; + +import { Module } from '@nestjs/common'; + +import { OAuthMetadataController } from './oauth-metadata.controller'; + +@Module({ + controllers: [OAuthMetadataController], + imports: [ConfigurationModule] +}) +export class OAuthModule {} diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index 6b60d49c05..c3acd4361e 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -83,6 +83,7 @@ async function bootstrap() { app.setGlobalPrefix('api', { exclude: [ `${BULL_BOARD_ROUTE.substring(1)}{/*wildcard}`, + '.well-known{/*wildcard}', 'sitemap.xml', ...SUPPORTED_LANGUAGE_CODES.map((languageCode) => { // Exclude language-specific routes with an optional wildcard diff --git a/apps/api/src/middlewares/mcp-authorization.middleware.spec.ts b/apps/api/src/middlewares/mcp-authorization.middleware.spec.ts new file mode 100644 index 0000000000..f69e4b1d84 --- /dev/null +++ b/apps/api/src/middlewares/mcp-authorization.middleware.spec.ts @@ -0,0 +1,167 @@ +import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; +import { ImpersonationService } from '@ghostfolio/api/services/impersonation/impersonation.service'; +import { UserService } from '@ghostfolio/api/services/user/user.service'; +import { HEADER_KEY_TOKEN } from '@ghostfolio/common/config'; + +import { Request, Response } from 'express'; +import { StatusCodes } from 'http-status-codes'; + +import { createMcpAuthorizationMiddleware } from './mcp-authorization.middleware'; + +describe('createMcpAuthorizationMiddleware', () => { + let configurationService: ConfigurationService; + let impersonationService: ImpersonationService; + let userService: UserService; + let mockRequest: Partial; + let mockResponse: Partial; + let nextFunction: jest.Mock; + + const mockConfig: Record = { + ENABLE_FEATURE_MCP: true, + ENABLE_FEATURE_MCP_OAUTH: false, + ENABLE_FEATURE_SUBSCRIPTION: false, + ROOT_URL: 'http://localhost:3333' + }; + + beforeEach(() => { + configurationService = { + get: jest.fn((key: string) => { + return mockConfig[key]; + }) + } as unknown as ConfigurationService; + + impersonationService = { + resolve: jest.fn() + } as unknown as ImpersonationService; + + userService = { + isDailyRequestLimitExceeded: jest.fn(), + updateAnalytics: jest.fn(), + user: jest.fn() + } as unknown as UserService; + + mockRequest = { + headers: {} + }; + + mockResponse = { + json: jest.fn().mockReturnThis(), + setHeader: jest.fn().mockReturnThis(), + status: jest.fn().mockReturnThis() + }; + + nextFunction = jest.fn(); + }); + + it('returns 401 challenge with only realm when token is missing and OAuth is disabled', async () => { + mockConfig.ENABLE_FEATURE_MCP_OAUTH = false; + jest.mocked(impersonationService.resolve).mockResolvedValueOnce({ + isActive: false + } as any); + + const middleware = createMcpAuthorizationMiddleware({ + configurationService, + impersonationService, + userService + }); + + await middleware( + mockRequest as Request, + mockResponse as Response, + nextFunction + ); + + expect(mockResponse.status).toHaveBeenCalledWith(StatusCodes.UNAUTHORIZED); + expect(mockResponse.setHeader).toHaveBeenCalledWith( + 'WWW-Authenticate', + 'Bearer realm="Ghostfolio"' + ); + expect(nextFunction).not.toHaveBeenCalled(); + }); + + it('returns 401 challenge with resource_metadata when token is missing and OAuth is enabled', async () => { + mockConfig.ENABLE_FEATURE_MCP_OAUTH = true; + jest.mocked(impersonationService.resolve).mockResolvedValueOnce({ + isActive: false + } as any); + + const middleware = createMcpAuthorizationMiddleware({ + configurationService, + impersonationService, + userService + }); + + await middleware( + mockRequest as Request, + mockResponse as Response, + nextFunction + ); + + expect(mockResponse.status).toHaveBeenCalledWith(StatusCodes.UNAUTHORIZED); + expect(mockResponse.setHeader).toHaveBeenCalledWith( + 'WWW-Authenticate', + 'Bearer realm="Ghostfolio", resource_metadata="http://localhost:3333/.well-known/oauth-protected-resource/mcp"' + ); + expect(nextFunction).not.toHaveBeenCalled(); + }); + + it('returns 401 with invalid_token when token is invalid and OAuth is enabled', async () => { + mockConfig.ENABLE_FEATURE_MCP_OAUTH = true; + mockRequest.headers = { + [HEADER_KEY_TOKEN.toLowerCase()]: 'Bearer invalid-token' + }; + + jest.mocked(impersonationService.resolve).mockResolvedValueOnce({ + isActive: false + } as any); + + const middleware = createMcpAuthorizationMiddleware({ + configurationService, + impersonationService, + userService + }); + + await middleware( + mockRequest as Request, + mockResponse as Response, + nextFunction + ); + + expect(mockResponse.status).toHaveBeenCalledWith(StatusCodes.UNAUTHORIZED); + expect(mockResponse.setHeader).toHaveBeenCalledWith( + 'WWW-Authenticate', + 'Bearer realm="Ghostfolio", resource_metadata="http://localhost:3333/.well-known/oauth-protected-resource/mcp", error="invalid_token", error_description="The access cannot be resolved"' + ); + expect(nextFunction).not.toHaveBeenCalled(); + }); + + it('calls next() when access resolves successfully', async () => { + const impersonation = { + isActive: true, + userId: 'test-user-id' + }; + + mockRequest.headers = { + [HEADER_KEY_TOKEN.toLowerCase()]: 'Bearer valid-access-id' + }; + + jest + .mocked(impersonationService.resolve) + .mockResolvedValueOnce(impersonation as any); + + const middleware = createMcpAuthorizationMiddleware({ + configurationService, + impersonationService, + userService + }); + + await middleware( + mockRequest as any, + mockResponse as Response, + nextFunction + ); + + expect(nextFunction).toHaveBeenCalled(); + expect((mockRequest as any).impersonationOfBearerToken).toBe(impersonation); + }); +}); diff --git a/apps/api/src/middlewares/mcp-authorization.middleware.ts b/apps/api/src/middlewares/mcp-authorization.middleware.ts index 42c999a794..8b99083d12 100644 --- a/apps/api/src/middlewares/mcp-authorization.middleware.ts +++ b/apps/api/src/middlewares/mcp-authorization.middleware.ts @@ -2,7 +2,11 @@ import { getAccessIdOfBearerToken } from '@ghostfolio/api/helper/bearer-token.he import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; import { ImpersonationService } from '@ghostfolio/api/services/impersonation/impersonation.service'; import { UserService } from '@ghostfolio/api/services/user/user.service'; -import { HEADER_KEY_TOKEN, MCP_REALM } from '@ghostfolio/common/config'; +import { + HEADER_KEY_TOKEN, + MCP_ENDPOINT, + MCP_REALM +} from '@ghostfolio/common/config'; import { hasRole } from '@ghostfolio/common/permissions'; import type { ImpersonationContext } from '@ghostfolio/common/types'; @@ -17,9 +21,13 @@ import { getReasonPhrase, StatusCodes } from 'http-status-codes'; * cannot come from a guard: a guard runs while the transport dispatches the * message and can no longer set the status of the response. * - * The challenge names no resource metadata, because Ghostfolio has no - * authorization server. A client which reads the challenge asks the user for - * the identifier of the access instead of starting a flow which would fail. + * If MCP OAuth is disabled, the challenge names no resource metadata, because + * Ghostfolio has no authorization server in that mode. A client which reads + * the challenge asks the user for the identifier of the access instead of + * starting a flow which would fail. + * + * When ENABLE_FEATURE_MCP_OAUTH is enabled, the challenge includes the RFC 9728 + * resource_metadata parameter pointing to the protected resource metadata document. * * With the subscription, the user who granted the access has the same limits * as with the other clients: an inactive user and a user who exceeds the daily @@ -52,14 +60,22 @@ export function createMcpAuthorizationMiddleware({ }); if (!impersonation.isActive) { - return sendUnauthorizedResponse({ accessId, response }); + return sendUnauthorizedResponse({ + accessId, + configurationService, + response + }); } if (configurationService.get('ENABLE_FEATURE_SUBSCRIPTION')) { const user = await userService.user({ id: impersonation.userId }); if (!user) { - return sendUnauthorizedResponse({ accessId, response }); + return sendUnauthorizedResponse({ + accessId, + configurationService, + response + }); } const isRequestLimitExceeded = @@ -90,13 +106,29 @@ export function createMcpAuthorizationMiddleware({ function sendUnauthorizedResponse({ accessId, + configurationService, response }: { accessId?: string; + configurationService: ConfigurationService; response: Response; }) { const parameters = [`realm="${MCP_REALM}"`]; + if ( + configurationService.get('ENABLE_FEATURE_MCP') && + configurationService.get('ENABLE_FEATURE_MCP_OAUTH') + ) { + const rootUrl = (configurationService.get('ROOT_URL') || '').replace( + /\/+$/, + '' + ); + + parameters.push( + `resource_metadata="${rootUrl}/.well-known/oauth-protected-resource${MCP_ENDPOINT}"` + ); + } + if (accessId) { parameters.push( 'error="invalid_token"', diff --git a/apps/api/src/services/configuration/configuration.service.ts b/apps/api/src/services/configuration/configuration.service.ts index bbd1a319b6..056db13edc 100644 --- a/apps/api/src/services/configuration/configuration.service.ts +++ b/apps/api/src/services/configuration/configuration.service.ts @@ -75,6 +75,7 @@ export class ConfigurationService { // TODO: Change the default to true, when the server of the Model Context // Protocol (MCP) was moved from experimental to general availability ENABLE_FEATURE_MCP: bool({ default: false }), + ENABLE_FEATURE_MCP_OAUTH: bool({ default: false }), ENABLE_FEATURE_RATE_LIMITING: bool({ default: false }), ENABLE_FEATURE_READ_ONLY_MODE: bool({ default: false }), // TODO: Change the default to true, when the security headers were diff --git a/apps/api/src/services/interfaces/environment.interface.ts b/apps/api/src/services/interfaces/environment.interface.ts index 7f9d7813cc..c20abeb79a 100644 --- a/apps/api/src/services/interfaces/environment.interface.ts +++ b/apps/api/src/services/interfaces/environment.interface.ts @@ -24,6 +24,7 @@ export interface Environment extends CleanedEnvAccessors { ENABLE_FEATURE_FEAR_AND_GREED_INDEX: boolean; ENABLE_FEATURE_GATHER_NEW_EXCHANGE_RATES: boolean; ENABLE_FEATURE_MCP: boolean; + ENABLE_FEATURE_MCP_OAUTH: boolean; ENABLE_FEATURE_RATE_LIMITING: boolean; ENABLE_FEATURE_READ_ONLY_MODE: boolean; ENABLE_FEATURE_SECURITY_HEADERS: boolean;