Browse Source

feat(api): support mcp oauth discovery and metadata endpoints

pull/8401/head
KenTandrian 4 weeks ago
parent
commit
cc04d94509
  1. 4
      CHANGELOG.md
  2. 8
      apps/api/src/app/__snapshots__/app.module.spec.ts.snap
  3. 2
      apps/api/src/app/app.module.spec.ts
  4. 6
      apps/api/src/app/app.module.ts
  5. 136
      apps/api/src/app/endpoints/oauth/oauth-metadata.controller.spec.ts
  6. 71
      apps/api/src/app/endpoints/oauth/oauth-metadata.controller.ts
  7. 11
      apps/api/src/app/endpoints/oauth/oauth.module.ts
  8. 1
      apps/api/src/main.ts
  9. 167
      apps/api/src/middlewares/mcp-authorization.middleware.spec.ts
  10. 44
      apps/api/src/middlewares/mcp-authorization.middleware.ts
  11. 1
      apps/api/src/services/configuration/configuration.service.ts
  12. 1
      apps/api/src/services/interfaces/environment.interface.ts

4
CHANGELOG.md

@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## Unreleased ## Unreleased
### Added
- Added discovery and metadata endpoints for Model Context Protocol (MCP) OAuth 2.1 (RFC 8414 & RFC 9728)
### Changed ### Changed
- Improved the language localization for Spanish (`es`) - Improved the language localization for Spanish (`es`)

8
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", "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": { "GET /access": {
"allowDuringImpersonation": true, "allowDuringImpersonation": true,
"guards": [ "guards": [

2
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 * are not served by a controller
*/ */
const PUBLIC_ROUTES = [ const PUBLIC_ROUTES = [
'GET /.well-known/oauth-authorization-server',
'GET /.well-known/oauth-protected-resource/mcp',
'GET /assets/:languageCode/site.webmanifest', 'GET /assets/:languageCode/site.webmanifest',
'GET /auth/google', 'GET /auth/google',
'GET /auth/google/callback', 'GET /auth/google/callback',

6
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 { LogoModule } from './endpoints/logo/logo.module';
import { MarketDataModule } from './endpoints/market-data/market-data.module'; import { MarketDataModule } from './endpoints/market-data/market-data.module';
import { McpModule } from './endpoints/mcp/mcp.module'; import { McpModule } from './endpoints/mcp/mcp.module';
import { OAuthModule } from './endpoints/oauth/oauth.module';
import { PlatformsModule } from './endpoints/platforms/platforms.module'; import { PlatformsModule } from './endpoints/platforms/platforms.module';
import { PublicModule } from './endpoints/public/public.module'; import { PublicModule } from './endpoints/public/public.module';
import { SitemapModule } from './endpoints/sitemap/sitemap.module'; import { SitemapModule } from './endpoints/sitemap/sitemap.module';
@ -127,6 +128,7 @@ import { PortfolioModule } from './portfolio/portfolio.module';
LogoModule, LogoModule,
MarketDataModule, MarketDataModule,
McpModule, McpModule,
OAuthModule,
PlatformsModule, PlatformsModule,
PortfolioModule, PortfolioModule,
PortfolioSnapshotQueueModule, PortfolioSnapshotQueueModule,
@ -145,6 +147,10 @@ import { PortfolioModule } from './portfolio/portfolio.module';
rootPath: join(__dirname, '..', 'client') rootPath: join(__dirname, '..', 'client')
}), }),
ServeStaticModule.forRoot({ ServeStaticModule.forRoot({
exclude: [
'/.well-known/oauth-authorization-server',
'/.well-known/oauth-protected-resource/*wildcard'
],
rootPath: join(__dirname, '..', 'client', '.well-known'), rootPath: join(__dirname, '..', 'client', '.well-known'),
serveRoot: '/.well-known' serveRoot: '/.well-known'
}), }),

136
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<string, any> = {
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']
});
});
});
});

71
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']
};
}
}

11
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 {}

1
apps/api/src/main.ts

@ -83,6 +83,7 @@ async function bootstrap() {
app.setGlobalPrefix('api', { app.setGlobalPrefix('api', {
exclude: [ exclude: [
`${BULL_BOARD_ROUTE.substring(1)}{/*wildcard}`, `${BULL_BOARD_ROUTE.substring(1)}{/*wildcard}`,
'.well-known{/*wildcard}',
'sitemap.xml', 'sitemap.xml',
...SUPPORTED_LANGUAGE_CODES.map((languageCode) => { ...SUPPORTED_LANGUAGE_CODES.map((languageCode) => {
// Exclude language-specific routes with an optional wildcard // Exclude language-specific routes with an optional wildcard

167
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<Request>;
let mockResponse: Partial<Response>;
let nextFunction: jest.Mock;
const mockConfig: Record<string, any> = {
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);
});
});

44
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 { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import { ImpersonationService } from '@ghostfolio/api/services/impersonation/impersonation.service'; import { ImpersonationService } from '@ghostfolio/api/services/impersonation/impersonation.service';
import { UserService } from '@ghostfolio/api/services/user/user.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 { hasRole } from '@ghostfolio/common/permissions';
import type { ImpersonationContext } from '@ghostfolio/common/types'; 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 * cannot come from a guard: a guard runs while the transport dispatches the
* message and can no longer set the status of the response. * message and can no longer set the status of the response.
* *
* The challenge names no resource metadata, because Ghostfolio has no * If MCP OAuth is disabled, the challenge names no resource metadata, because
* authorization server. A client which reads the challenge asks the user for * Ghostfolio has no authorization server in that mode. A client which reads
* the identifier of the access instead of starting a flow which would fail. * 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 * 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 * 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) { if (!impersonation.isActive) {
return sendUnauthorizedResponse({ accessId, response }); return sendUnauthorizedResponse({
accessId,
configurationService,
response
});
} }
if (configurationService.get('ENABLE_FEATURE_SUBSCRIPTION')) { if (configurationService.get('ENABLE_FEATURE_SUBSCRIPTION')) {
const user = await userService.user({ id: impersonation.userId }); const user = await userService.user({ id: impersonation.userId });
if (!user) { if (!user) {
return sendUnauthorizedResponse({ accessId, response }); return sendUnauthorizedResponse({
accessId,
configurationService,
response
});
} }
const isRequestLimitExceeded = const isRequestLimitExceeded =
@ -90,13 +106,29 @@ export function createMcpAuthorizationMiddleware({
function sendUnauthorizedResponse({ function sendUnauthorizedResponse({
accessId, accessId,
configurationService,
response response
}: { }: {
accessId?: string; accessId?: string;
configurationService: ConfigurationService;
response: Response; response: Response;
}) { }) {
const parameters = [`realm="${MCP_REALM}"`]; 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) { if (accessId) {
parameters.push( parameters.push(
'error="invalid_token"', 'error="invalid_token"',

1
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 // TODO: Change the default to true, when the server of the Model Context
// Protocol (MCP) was moved from experimental to general availability // Protocol (MCP) was moved from experimental to general availability
ENABLE_FEATURE_MCP: bool({ default: false }), ENABLE_FEATURE_MCP: bool({ default: false }),
ENABLE_FEATURE_MCP_OAUTH: bool({ default: false }),
ENABLE_FEATURE_RATE_LIMITING: bool({ default: false }), ENABLE_FEATURE_RATE_LIMITING: bool({ default: false }),
ENABLE_FEATURE_READ_ONLY_MODE: bool({ default: false }), ENABLE_FEATURE_READ_ONLY_MODE: bool({ default: false }),
// TODO: Change the default to true, when the security headers were // TODO: Change the default to true, when the security headers were

1
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_FEAR_AND_GREED_INDEX: boolean;
ENABLE_FEATURE_GATHER_NEW_EXCHANGE_RATES: boolean; ENABLE_FEATURE_GATHER_NEW_EXCHANGE_RATES: boolean;
ENABLE_FEATURE_MCP: boolean; ENABLE_FEATURE_MCP: boolean;
ENABLE_FEATURE_MCP_OAUTH: boolean;
ENABLE_FEATURE_RATE_LIMITING: boolean; ENABLE_FEATURE_RATE_LIMITING: boolean;
ENABLE_FEATURE_READ_ONLY_MODE: boolean; ENABLE_FEATURE_READ_ONLY_MODE: boolean;
ENABLE_FEATURE_SECURITY_HEADERS: boolean; ENABLE_FEATURE_SECURITY_HEADERS: boolean;

Loading…
Cancel
Save