diff --git a/CHANGELOG.md b/CHANGELOG.md index c3261e3dfc..239a21e0cd 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 the discovery endpoints of OAuth 2.1 to the server of the Model Context Protocol (MCP) (experimental) + ### 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..cd3d1e43da 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, 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..853b3ef3d1 --- /dev/null +++ b/apps/api/src/app/endpoints/oauth/oauth-metadata.controller.spec.ts @@ -0,0 +1,153 @@ +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; + let mockConfig: Record; + + beforeEach(() => { + mockConfig = { + ENABLE_FEATURE_MCP: true, + ENABLE_FEATURE_MCP_OAUTH: true, + ROOT_URL: 'http://localhost:3333' + }; + + 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('throws NotFoundException when ROOT_URL is not valid as the issuer', () => { + mockConfig.ENABLE_FEATURE_MCP = true; + mockConfig.ENABLE_FEATURE_MCP_OAUTH = true; + mockConfig.ROOT_URL = 'http://0.0.0.0:3333'; + + 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'], + 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'], + 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('throws NotFoundException when ROOT_URL is not valid as the issuer', () => { + mockConfig.ENABLE_FEATURE_MCP = true; + mockConfig.ENABLE_FEATURE_MCP_OAUTH = true; + mockConfig.ROOT_URL = 'http://0.0.0.0:3333'; + + 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', + 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', + 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..b91855ba48 --- /dev/null +++ b/apps/api/src/app/endpoints/oauth/oauth-metadata.controller.ts @@ -0,0 +1,49 @@ +import { + getMcpAuthorizationServerMetadata, + getMcpResourceUrl, + isMcpOAuthEnabled +} from '@ghostfolio/api/helper/mcp-oauth.helper'; +import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; +import { MCP_ENDPOINT } from '@ghostfolio/common/config'; + +import { buildOAuthProtectedResourceMetadata } from '@modelcontextprotocol/server'; +import { + Controller, + Get, + NotFoundException, + VERSION_NEUTRAL, + Version +} from '@nestjs/common'; + +@Controller('.well-known') +export class OAuthMetadataController { + public constructor( + private readonly configurationService: ConfigurationService + ) {} + + @Get(`oauth-protected-resource${MCP_ENDPOINT}`) + @Version(VERSION_NEUTRAL) + public getProtectedResourceMetadata() { + if (!isMcpOAuthEnabled(this.configurationService)) { + throw new NotFoundException(); + } + + return buildOAuthProtectedResourceMetadata({ + oauthMetadata: getMcpAuthorizationServerMetadata( + this.configurationService + ), + resourceName: 'Ghostfolio', + resourceServerUrl: getMcpResourceUrl(this.configurationService) + }); + } + + @Get('oauth-authorization-server') + @Version(VERSION_NEUTRAL) + public getAuthorizationServerMetadata() { + if (!isMcpOAuthEnabled(this.configurationService)) { + throw new NotFoundException(); + } + + return getMcpAuthorizationServerMetadata(this.configurationService); + } +} 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/helper/mcp-oauth.helper.spec.ts b/apps/api/src/helper/mcp-oauth.helper.spec.ts new file mode 100644 index 0000000000..32d8f78d1c --- /dev/null +++ b/apps/api/src/helper/mcp-oauth.helper.spec.ts @@ -0,0 +1,131 @@ +import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; + +import { + getMcpAuthorizationServerMetadata, + getMcpOAuthBaseUrl, + getMcpProtectedResourceMetadataUrl, + getMcpResourceUrl, + isMcpOAuthEnabled, + isValidMcpOAuthIssuerUrl +} from './mcp-oauth.helper'; + +describe('mcp-oauth.helper', () => { + let configurationService: ConfigurationService; + let mockConfig: Record; + + beforeEach(() => { + mockConfig = { + ENABLE_FEATURE_MCP: true, + ENABLE_FEATURE_MCP_OAUTH: true, + ROOT_URL: 'http://localhost:3333' + }; + + configurationService = { + get: jest.fn((key: string) => { + return mockConfig[key]; + }) + } as unknown as ConfigurationService; + }); + + describe('getMcpAuthorizationServerMetadata', () => { + it('returns RFC 8414 authorization server metadata', () => { + mockConfig.ROOT_URL = 'http://localhost:3333/'; + + expect(getMcpAuthorizationServerMetadata(configurationService)).toEqual({ + authorization_endpoint: 'http://localhost:3333/oauth/authorize', + 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'] + }); + }); + }); + + describe('getMcpOAuthBaseUrl', () => { + it('returns the root URL without trailing slashes', () => { + mockConfig.ROOT_URL = 'https://ghostfol.io///'; + + expect(getMcpOAuthBaseUrl(configurationService)).toBe( + 'https://ghostfol.io' + ); + }); + }); + + describe('getMcpProtectedResourceMetadataUrl', () => { + it('returns the full protected resource metadata URL', () => { + mockConfig.ROOT_URL = 'http://localhost:3333/'; + + expect(getMcpProtectedResourceMetadataUrl(configurationService)).toBe( + 'http://localhost:3333/.well-known/oauth-protected-resource/mcp' + ); + }); + }); + + describe('getMcpResourceUrl', () => { + it('returns the resource URL as a URL instance', () => { + mockConfig.ROOT_URL = 'http://localhost:3333/'; + + expect(getMcpResourceUrl(configurationService)).toEqual( + new URL('http://localhost:3333/mcp') + ); + }); + }); + + describe('isMcpOAuthEnabled', () => { + it('returns true when both ENABLE_FEATURE_MCP and ENABLE_FEATURE_MCP_OAUTH are true', () => { + mockConfig.ENABLE_FEATURE_MCP = true; + mockConfig.ENABLE_FEATURE_MCP_OAUTH = true; + + expect(isMcpOAuthEnabled(configurationService)).toBe(true); + }); + + it('returns false when ENABLE_FEATURE_MCP is false', () => { + mockConfig.ENABLE_FEATURE_MCP = false; + mockConfig.ENABLE_FEATURE_MCP_OAUTH = true; + + expect(isMcpOAuthEnabled(configurationService)).toBe(false); + }); + + it('returns false when ENABLE_FEATURE_MCP_OAUTH is false', () => { + mockConfig.ENABLE_FEATURE_MCP = true; + mockConfig.ENABLE_FEATURE_MCP_OAUTH = false; + + expect(isMcpOAuthEnabled(configurationService)).toBe(false); + }); + + it('returns false when ROOT_URL is not valid as the issuer', () => { + mockConfig.ENABLE_FEATURE_MCP = true; + mockConfig.ENABLE_FEATURE_MCP_OAUTH = true; + mockConfig.ROOT_URL = 'http://192.168.1.10:3333'; + + expect(isMcpOAuthEnabled(configurationService)).toBe(false); + }); + }); + + describe('isValidMcpOAuthIssuerUrl', () => { + it.each([ + 'http://127.0.0.1:3333', + 'http://localhost:3333/', + 'https://192.168.1.10:3333', + 'https://ghostfol.io' + ])('returns true for %s', (rootUrl) => { + mockConfig.ROOT_URL = rootUrl; + + expect(isValidMcpOAuthIssuerUrl(configurationService)).toBe(true); + }); + + it.each([ + 'http://0.0.0.0:3333', + 'http://192.168.1.10:3333', + 'http://[::1]:3333', + 'http://ghostfolio.local' + ])('returns false for %s', (rootUrl) => { + mockConfig.ROOT_URL = rootUrl; + + expect(isValidMcpOAuthIssuerUrl(configurationService)).toBe(false); + }); + }); +}); diff --git a/apps/api/src/helper/mcp-oauth.helper.ts b/apps/api/src/helper/mcp-oauth.helper.ts new file mode 100644 index 0000000000..b331bdc420 --- /dev/null +++ b/apps/api/src/helper/mcp-oauth.helper.ts @@ -0,0 +1,88 @@ +import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; +import { MCP_ENDPOINT } from '@ghostfolio/common/config'; + +import { + getOAuthProtectedResourceMetadataUrl, + OAuthMetadata +} from '@modelcontextprotocol/server'; + +/** + * Gives the metadata of the authorization server (RFC 8414). The protected + * resource metadata (RFC 9728) names its issuer. + */ +export function getMcpAuthorizationServerMetadata( + configurationService: ConfigurationService +): OAuthMetadata { + const rootUrl = getMcpOAuthBaseUrl(configurationService); + + return { + authorization_endpoint: `${rootUrl}/oauth/authorize`, + 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'] + }; +} + +/** + * Gives the root URL without a trailing slash. The issuer and the resource in + * the metadata have to be identical to the URL which the client uses. + */ +export function getMcpOAuthBaseUrl(configurationService: ConfigurationService) { + return configurationService.get('ROOT_URL').replace(/\/+$/, ''); +} + +/** + * Gives the URL of the protected resource metadata (RFC 9728) which the + * challenge of the authorization middleware names + */ +export function getMcpProtectedResourceMetadataUrl( + configurationService: ConfigurationService +) { + return getOAuthProtectedResourceMetadataUrl( + getMcpResourceUrl(configurationService) + ); +} + +/** + * Gives the URL of the server of the Model Context Protocol (MCP), which is the + * resource of the protected resource metadata (RFC 9728) + */ +export function getMcpResourceUrl(configurationService: ConfigurationService) { + return new URL(`${getMcpOAuthBaseUrl(configurationService)}${MCP_ENDPOINT}`); +} + +/** + * Tells if the authorization with OAuth 2.1 is enabled. It depends on the + * server of the Model Context Protocol (MCP) and on a valid issuer URL. + */ +export function isMcpOAuthEnabled(configurationService: ConfigurationService) { + return ( + configurationService.get('ENABLE_FEATURE_MCP') && + configurationService.get('ENABLE_FEATURE_MCP_OAUTH') && + isValidMcpOAuthIssuerUrl(configurationService) + ); +} + +/** + * Tells if the root URL is valid as the issuer of the authorization server: + * OAuth 2.1 requires HTTPS, except for localhost. This is the same rule as in + * buildOAuthProtectedResourceMetadata() of @modelcontextprotocol/server, which + * throws an error for any other issuer. + */ +export function isValidMcpOAuthIssuerUrl( + configurationService: ConfigurationService +) { + const { hostname, protocol } = new URL( + getMcpOAuthBaseUrl(configurationService) + ); + + return ( + protocol === 'https:' || + hostname === '127.0.0.1' || + hostname === 'localhost' + ); +} diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index 6b60d49c05..16121c5adc 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -1,3 +1,4 @@ +import { isValidMcpOAuthIssuerUrl } from '@ghostfolio/api/helper/mcp-oauth.helper'; import { getHelmetOptions } from '@ghostfolio/api/helper/security-headers.helper'; import { languageRedirectMiddleware } from '@ghostfolio/api/middlewares/language-redirect.middleware'; import { createMcpAuthorizationMiddleware } from '@ghostfolio/api/middlewares/mcp-authorization.middleware'; @@ -83,6 +84,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 @@ -155,6 +157,15 @@ async function bootstrap() { ); } + if ( + configurationService.get('ENABLE_FEATURE_MCP_OAUTH') && + !isValidMcpOAuthIssuerUrl(configurationService) + ) { + logger.warn( + 'The authorization with OAuth 2.1 of the Model Context Protocol (MCP) is enabled, but ROOT_URL does not use HTTPS. The authorization stays disabled. Set ROOT_URL to the public HTTPS URL of the instance.' + ); + } + // The middleware has to be registered before the transport mounts its // route, so that an unauthorized request gets the status 401 of the // specification instead of an error of the protocol diff --git a/apps/api/src/middlewares/html-template.middleware.ts b/apps/api/src/middlewares/html-template.middleware.ts index 4f5ca433b0..70ec9f5f12 100644 --- a/apps/api/src/middlewares/html-template.middleware.ts +++ b/apps/api/src/middlewares/html-template.middleware.ts @@ -215,6 +215,7 @@ export class HtmlTemplateMiddleware implements NestMiddleware { const rootUrl = process.env.ROOT_URL || environment.rootUrl; if ( + path.startsWith('/.well-known/') || path.startsWith('/api/') || path.startsWith(STORYBOOK_PATH) || this.isFileRequest(path) || 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..1d8fe63860 --- /dev/null +++ b/apps/api/src/middlewares/mcp-authorization.middleware.spec.ts @@ -0,0 +1,168 @@ +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 mockConfig: Record; + let mockRequest: Partial; + let mockResponse: Partial; + let nextFunction: jest.Mock; + let userService: UserService; + + beforeEach(() => { + mockConfig = { + ENABLE_FEATURE_MCP: true, + ENABLE_FEATURE_MCP_OAUTH: false, + ENABLE_FEATURE_SUBSCRIPTION: false, + ROOT_URL: 'http://localhost:3333' + }; + + 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..27053fa562 100644 --- a/apps/api/src/middlewares/mcp-authorization.middleware.ts +++ b/apps/api/src/middlewares/mcp-authorization.middleware.ts @@ -1,4 +1,8 @@ import { getAccessIdOfBearerToken } from '@ghostfolio/api/helper/bearer-token.helper'; +import { + getMcpProtectedResourceMetadataUrl, + isMcpOAuthEnabled +} from '@ghostfolio/api/helper/mcp-oauth.helper'; 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'; @@ -17,9 +21,10 @@ 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. + * The challenge names the protected resource metadata (RFC 9728) only if the + * authorization with OAuth 2.1 is enabled. Otherwise, a client which reads the + * challenge asks the user for the identifier of the access instead of starting + * a flow which would fail. * * 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 +57,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 +103,21 @@ export function createMcpAuthorizationMiddleware({ function sendUnauthorizedResponse({ accessId, + configurationService, response }: { accessId?: string; + configurationService: ConfigurationService; response: Response; }) { const parameters = [`realm="${MCP_REALM}"`]; + if (isMcpOAuthEnabled(configurationService)) { + parameters.push( + `resource_metadata="${getMcpProtectedResourceMetadataUrl(configurationService)}"` + ); + } + 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..ea2312d5bf 100644 --- a/apps/api/src/services/configuration/configuration.service.ts +++ b/apps/api/src/services/configuration/configuration.service.ts @@ -75,6 +75,9 @@ 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 }), + // TODO: Change the default to true, when the authorization with OAuth 2.1 + // was moved from experimental to general availability + 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;