The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(server): align OAuth discovery metadata with MCP / RFC 9728 spec (#19838)
Félix Malfait5223c4771df5
diff --git a/packages/twenty-server/src/engine/api/mcp/guards/__tests__/mcp-auth.guard.spec.ts b/packages/twenty-server/src/engine/api/mcp/guards/__tests__/mcp-auth.guard.spec.tsindex e5a87153b56..80d893cb4a0 100644--- a/packages/twenty-server/src/engine/api/mcp/guards/__tests__/mcp-auth.guard.spec.ts+++ b/packages/twenty-server/src/engine/api/mcp/guards/__tests__/mcp-auth.guard.spec.ts@@ -46,7 +46,7 @@ describe('McpAuthGuard', () => {expect(mockSetHeader).toHaveBeenCalledWith('WWW-Authenticate',- 'Bearer resource_metadata="https://acme.twenty.com/.well-known/oauth-protected-resource"',+ 'Bearer resource_metadata="https://acme.twenty.com/.well-known/oauth-protected-resource/mcp", scope="api profile"',);});});diff --git a/packages/twenty-server/src/engine/api/mcp/guards/mcp-auth.guard.ts b/packages/twenty-server/src/engine/api/mcp/guards/mcp-auth.guard.tsindex 5db8de024e7..8df66a919f5 100644--- a/packages/twenty-server/src/engine/api/mcp/guards/mcp-auth.guard.ts+++ b/packages/twenty-server/src/engine/api/mcp/guards/mcp-auth.guard.ts@@ -7,12 +7,13 @@ import {import { type Request, type Response } from 'express';+import { ALL_OAUTH_SCOPES } from 'src/engine/core-modules/application/application-oauth/constants/oauth-scopes';import { JwtAuthGuard } from 'src/engine/guards/jwt-auth.guard';-// RFC 9728: When the MCP endpoint returns 401, include a WWW-Authenticate-// header pointing to the Protected Resource Metadata URL on the same host-// the client connected to — otherwise discovery fails for any host other-// than SERVER_URL (app.twenty.com, workspace subdomains, custom domains).+// RFC 9728 / MCP authorization spec: when the MCP endpoint returns 401,+// include a WWW-Authenticate header pointing to the path-aware Protected+// Resource Metadata URL so the client discovers the correct resource+// identifier. The `scope` parameter tells the client which scopes to request.@Injectable()export class McpAuthGuard implements CanActivate {constructor(private readonly jwtAuthGuard: JwtAuthGuard) {}@@ -23,7 +24,8 @@ export class McpAuthGuard implements CanActivate {if (!isAuthenticated) {const request = context.switchToHttp().getRequest<Request>();const baseUrl = `${request.protocol}://${request.get('host')}`;- const resourceMetadataUrl = `${baseUrl}/.well-known/oauth-protected-resource`;+ const resourceMetadataUrl = `${baseUrl}/.well-known/oauth-protected-resource/mcp`;+ const scope = ALL_OAUTH_SCOPES.join(' ');// Set the header on the response before throwing, because exception// filters may not preserve custom headers from the exception payload.@@ -31,7 +33,7 @@ export class McpAuthGuard implements CanActivate {response.setHeader('WWW-Authenticate',- `Bearer resource_metadata="${resourceMetadataUrl}"`,+ `Bearer resource_metadata="${resourceMetadataUrl}", scope="${scope}"`,);throw new UnauthorizedException();diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/__tests__/oauth-discovery.controller.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/__tests__/oauth-discovery.controller.spec.tsindex dfb48f6f45a..b74494ab69f 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/__tests__/oauth-discovery.controller.spec.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/__tests__/oauth-discovery.controller.spec.ts@@ -1,4 +1,3 @@-import { PATH_METADATA } from '@nestjs/common/constants';import { Test, type TestingModule } from '@nestjs/testing';import { type Request } from 'express';@@ -46,31 +45,30 @@ describe('OAuthDiscoveryController', () => {controller = module.get(OAuthDiscoveryController);});+ // RFC 9728 §3.2 requires the `resource` value to match the identifier into+ // which the well-known path suffix was inserted — so the root maps to the+ // origin itself and the /mcp variant maps to <origin>/mcp.describe('getProtectedResourceMetadata', () => {- it('echoes the request host in the resource and authorization_servers', () => {+ it('root form returns the origin as the resource', () => {const request = buildMockRequest('workspace.twenty.com');- expect(controller.getProtectedResourceMetadata(request)).toEqual({- resource: 'https://workspace.twenty.com/mcp',+ expect(+ controller.getProtectedResourceMetadataRoot(request),+ ).toMatchObject({+ resource: 'https://workspace.twenty.com',authorization_servers: ['https://workspace.twenty.com'],- scopes_supported: ['api', 'profile'],- bearer_methods_supported: ['header'],});});- // RFC 9728 defines both a root and a resource-specific well-known- // URL; both must resolve to this handler so any conformant client- // can discover the metadata.- it('is registered at both the root and the /mcp path-aware URL', () => {- const paths = Reflect.getMetadata(- PATH_METADATA,- controller.getProtectedResourceMetadata,- );+ it('path-aware /mcp form returns origin/mcp as the resource', () => {+ const request = buildMockRequest('workspace.twenty.com');- expect(paths).toEqual([- 'oauth-protected-resource',- 'oauth-protected-resource/mcp',- ]);+ expect(controller.getProtectedResourceMetadataMcp(request)).toMatchObject(+ {+ resource: 'https://workspace.twenty.com/mcp',+ authorization_servers: ['https://workspace.twenty.com'],+ },+ );});});});diff --git a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.tsindex d1d4d1f22f7..48d28659f93 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-oauth/controllers/oauth-discovery.controller.ts@@ -54,24 +54,40 @@ export class OAuthDiscoveryController {token_endpoint_auth_methods_supported: ['client_secret_post', 'none'],revocation_endpoint_auth_methods_supported: ['client_secret_post'],introspection_endpoint_auth_methods_supported: ['client_secret_post'],+ // RFC 9207: advertise `iss` in authorization responses to defend against+ // OAuth mix-up attacks. Required by OAuth 2.1 security BCP.+ authorization_response_iss_parameter_supported: true,...(cliRegistration? { cli_client_id: cliRegistration.oAuthClientId }: {}),};}- // RFC 9728: OAuth 2.0 Protected Resource Metadata.- // Exposed at both the root and the resource-specific path (/mcp) because- // RFC 9728 defines the path-aware form and clients may probe either.- // The `resource` value echoes the host the request reached so the metadata- // matches the resource indicator the client used.- @Get(['oauth-protected-resource', 'oauth-protected-resource/mcp'])+ // RFC 9728 §3.2: the `resource` value MUST equal the resource identifier+ // into which the well-known path suffix was inserted. So the root form maps+ // to the origin as-a-resource, and the /mcp-suffixed form maps to+ // <origin>/mcp. Strict clients probing the path-aware variant will reject+ // mismatching metadata.++ @Get('oauth-protected-resource')+ @UseGuards(PublicEndpointGuard, NoPermissionGuard)+ getProtectedResourceMetadataRoot(@Req() request: Request) {+ const base = this.getRequestBaseUrl(request);++ return this.buildProtectedResourceMetadata(base, base);+ }++ @Get('oauth-protected-resource/mcp')@UseGuards(PublicEndpointGuard, NoPermissionGuard)- getProtectedResourceMetadata(@Req() request: Request) {+ getProtectedResourceMetadataMcp(@Req() request: Request) {const base = this.getRequestBaseUrl(request);+ return this.buildProtectedResourceMetadata(base, `${base}/mcp`);+ }++ private buildProtectedResourceMetadata(base: string, resource: string) {return {- resource: `${base}/mcp`,+ resource,authorization_servers: [base],scopes_supported: ALL_OAUTH_SCOPES,bearer_methods_supported: ['header'],