Browse Source

refactor(api): address review comments on mcp oauth discovery

pull/8401/head
KenTandrian 3 weeks ago
parent
commit
e64267ae9b
  1. 2
      CHANGELOG.md
  2. 4
      apps/api/src/app/app.module.ts
  3. 15
      apps/api/src/app/endpoints/oauth/oauth-metadata.controller.spec.ts
  4. 30
      apps/api/src/app/endpoints/oauth/oauth-metadata.controller.ts
  5. 69
      apps/api/src/helper/mcp-oauth.helper.spec.ts
  6. 31
      apps/api/src/helper/mcp-oauth.helper.ts
  7. 17
      apps/api/src/middlewares/mcp-authorization.middleware.spec.ts
  8. 22
      apps/api/src/middlewares/mcp-authorization.middleware.ts
  9. 2
      apps/api/src/services/configuration/configuration.service.ts

2
CHANGELOG.md

@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added ### Added
- Added discovery and metadata endpoints for Model Context Protocol (MCP) OAuth 2.1 (RFC 8414 & RFC 9728) - Added discovery and metadata endpoints for Model Context Protocol (MCP) OAuth 2.1 (RFC 8414 & RFC 9728) (experimental)
### Changed ### Changed

4
apps/api/src/app/app.module.ts

@ -147,10 +147,6 @@ 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'
}), }),

15
apps/api/src/app/endpoints/oauth/oauth-metadata.controller.spec.ts

@ -7,14 +7,15 @@ import { OAuthMetadataController } from './oauth-metadata.controller';
describe('OAuthMetadataController', () => { describe('OAuthMetadataController', () => {
let configurationService: ConfigurationService; let configurationService: ConfigurationService;
let controller: OAuthMetadataController; let controller: OAuthMetadataController;
let mockConfig: Record<string, any>;
const mockConfig: Record<string, any> = {
ENABLE_FEATURE_MCP: true,
ENABLE_FEATURE_MCP_OAUTH: true,
ROOT_URL: 'http://localhost:3333'
};
beforeEach(() => { beforeEach(() => {
mockConfig = {
ENABLE_FEATURE_MCP: true,
ENABLE_FEATURE_MCP_OAUTH: true,
ROOT_URL: 'http://localhost:3333'
};
configurationService = { configurationService = {
get: jest.fn((key: string) => { get: jest.fn((key: string) => {
return mockConfig[key]; return mockConfig[key];
@ -102,7 +103,6 @@ describe('OAuthMetadataController', () => {
expect(result).toEqual({ expect(result).toEqual({
authorization_endpoint: 'http://localhost:3333/oauth/authorize', authorization_endpoint: 'http://localhost:3333/oauth/authorize',
authorization_response_iss_parameter_supported: true,
client_id_metadata_document_supported: true, client_id_metadata_document_supported: true,
code_challenge_methods_supported: ['S256'], code_challenge_methods_supported: ['S256'],
grant_types_supported: ['authorization_code', 'refresh_token'], grant_types_supported: ['authorization_code', 'refresh_token'],
@ -122,7 +122,6 @@ describe('OAuthMetadataController', () => {
expect(result).toEqual({ expect(result).toEqual({
authorization_endpoint: 'https://ghostfol.io/oauth/authorize', authorization_endpoint: 'https://ghostfol.io/oauth/authorize',
authorization_response_iss_parameter_supported: true,
client_id_metadata_document_supported: true, client_id_metadata_document_supported: true,
code_challenge_methods_supported: ['S256'], code_challenge_methods_supported: ['S256'],
grant_types_supported: ['authorization_code', 'refresh_token'], grant_types_supported: ['authorization_code', 'refresh_token'],

30
apps/api/src/app/endpoints/oauth/oauth-metadata.controller.ts

@ -1,10 +1,13 @@
import {
getMcpOAuthBaseUrl,
isMcpOAuthEnabled
} from '@ghostfolio/api/helper/mcp-oauth.helper';
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import { MCP_ENDPOINT } from '@ghostfolio/common/config'; import { MCP_ENDPOINT } from '@ghostfolio/common/config';
import { import {
Controller, Controller,
Get, Get,
Header,
NotFoundException, NotFoundException,
VERSION_NEUTRAL, VERSION_NEUTRAL,
Version Version
@ -16,21 +19,14 @@ export class OAuthMetadataController {
private readonly configurationService: ConfigurationService private readonly configurationService: ConfigurationService
) {} ) {}
@Get('oauth-protected-resource/mcp') @Get(`oauth-protected-resource${MCP_ENDPOINT}`)
@Header('Cache-Control', 'public, max-age=3600')
@Version(VERSION_NEUTRAL) @Version(VERSION_NEUTRAL)
public getProtectedResourceMetadata() { public getProtectedResourceMetadata() {
if ( if (!isMcpOAuthEnabled(this.configurationService)) {
!this.configurationService.get('ENABLE_FEATURE_MCP') ||
!this.configurationService.get('ENABLE_FEATURE_MCP_OAUTH')
) {
throw new NotFoundException(); throw new NotFoundException();
} }
const rootUrl = (this.configurationService.get('ROOT_URL') || '').replace( const rootUrl = getMcpOAuthBaseUrl(this.configurationService);
/\/+$/,
''
);
return { return {
authorization_servers: [rootUrl], authorization_servers: [rootUrl],
@ -41,24 +37,16 @@ export class OAuthMetadataController {
} }
@Get('oauth-authorization-server') @Get('oauth-authorization-server')
@Header('Cache-Control', 'public, max-age=3600')
@Version(VERSION_NEUTRAL) @Version(VERSION_NEUTRAL)
public getAuthorizationServerMetadata() { public getAuthorizationServerMetadata() {
if ( if (!isMcpOAuthEnabled(this.configurationService)) {
!this.configurationService.get('ENABLE_FEATURE_MCP') ||
!this.configurationService.get('ENABLE_FEATURE_MCP_OAUTH')
) {
throw new NotFoundException(); throw new NotFoundException();
} }
const rootUrl = (this.configurationService.get('ROOT_URL') || '').replace( const rootUrl = getMcpOAuthBaseUrl(this.configurationService);
/\/+$/,
''
);
return { return {
authorization_endpoint: `${rootUrl}/oauth/authorize`, authorization_endpoint: `${rootUrl}/oauth/authorize`,
authorization_response_iss_parameter_supported: true,
client_id_metadata_document_supported: true, client_id_metadata_document_supported: true,
code_challenge_methods_supported: ['S256'], code_challenge_methods_supported: ['S256'],
grant_types_supported: ['authorization_code', 'refresh_token'], grant_types_supported: ['authorization_code', 'refresh_token'],

69
apps/api/src/helper/mcp-oauth.helper.spec.ts

@ -0,0 +1,69 @@
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import {
getMcpOAuthBaseUrl,
getMcpProtectedResourceMetadataUrl,
isMcpOAuthEnabled
} from './mcp-oauth.helper';
describe('mcp-oauth.helper', () => {
let configurationService: ConfigurationService;
let mockConfig: Record<string, any>;
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('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('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);
});
});
});

31
apps/api/src/helper/mcp-oauth.helper.ts

@ -0,0 +1,31 @@
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import { MCP_ENDPOINT } from '@ghostfolio/common/config';
/**
* 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 `${getMcpOAuthBaseUrl(configurationService)}/.well-known/oauth-protected-resource${MCP_ENDPOINT}`;
}
/**
* Tells if the authorization with OAuth 2.1 is enabled. It depends on the
* server of the Model Context Protocol (MCP).
*/
export function isMcpOAuthEnabled(configurationService: ConfigurationService) {
return (
configurationService.get('ENABLE_FEATURE_MCP') &&
configurationService.get('ENABLE_FEATURE_MCP_OAUTH')
);
}

17
apps/api/src/middlewares/mcp-authorization.middleware.spec.ts

@ -11,19 +11,20 @@ import { createMcpAuthorizationMiddleware } from './mcp-authorization.middleware
describe('createMcpAuthorizationMiddleware', () => { describe('createMcpAuthorizationMiddleware', () => {
let configurationService: ConfigurationService; let configurationService: ConfigurationService;
let impersonationService: ImpersonationService; let impersonationService: ImpersonationService;
let userService: UserService; let mockConfig: Record<string, any>;
let mockRequest: Partial<Request>; let mockRequest: Partial<Request>;
let mockResponse: Partial<Response>; let mockResponse: Partial<Response>;
let nextFunction: jest.Mock; let nextFunction: jest.Mock;
let userService: UserService;
const mockConfig: Record<string, any> = {
ENABLE_FEATURE_MCP: true,
ENABLE_FEATURE_MCP_OAUTH: false,
ENABLE_FEATURE_SUBSCRIPTION: false,
ROOT_URL: 'http://localhost:3333'
};
beforeEach(() => { beforeEach(() => {
mockConfig = {
ENABLE_FEATURE_MCP: true,
ENABLE_FEATURE_MCP_OAUTH: false,
ENABLE_FEATURE_SUBSCRIPTION: false,
ROOT_URL: 'http://localhost:3333'
};
configurationService = { configurationService = {
get: jest.fn((key: string) => { get: jest.fn((key: string) => {
return mockConfig[key]; return mockConfig[key];

22
apps/api/src/middlewares/mcp-authorization.middleware.ts

@ -1,12 +1,12 @@
import { getAccessIdOfBearerToken } from '@ghostfolio/api/helper/bearer-token.helper'; 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 { 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 { import { HEADER_KEY_TOKEN, MCP_REALM } from '@ghostfolio/common/config';
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';
@ -115,17 +115,9 @@ function sendUnauthorizedResponse({
}) { }) {
const parameters = [`realm="${MCP_REALM}"`]; const parameters = [`realm="${MCP_REALM}"`];
if ( if (isMcpOAuthEnabled(configurationService)) {
configurationService.get('ENABLE_FEATURE_MCP') &&
configurationService.get('ENABLE_FEATURE_MCP_OAUTH')
) {
const rootUrl = (configurationService.get('ROOT_URL') || '').replace(
/\/+$/,
''
);
parameters.push( parameters.push(
`resource_metadata="${rootUrl}/.well-known/oauth-protected-resource${MCP_ENDPOINT}"` `resource_metadata="${getMcpProtectedResourceMetadataUrl(configurationService)}"`
); );
} }

2
apps/api/src/services/configuration/configuration.service.ts

@ -75,6 +75,8 @@ 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 }),
// 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_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 }),

Loading…
Cancel
Save