From e0712df3e020c3b9744a333cfa102b5a6e6371f7 Mon Sep 17 00:00:00 2001 From: Ochan Kwon Date: Tue, 13 Oct 2026 17:37:24 +0900 Subject: [PATCH] feat(mcp): let callers without a browser obtain MCP OAuth tokens (#4229) WeKnora runs behind other applications: they sign their users in and call WeKnora with a tenant API key and X-External-User-ID, and WeKnora keeps sessions and MCP OAuth tokens per external user. When an agent uses an OAuth-protected MCP service, the only way to get that user's token is the browser authorization code flow, and in this deployment the user never sees WeKnora, so there is no browser to complete it. Independently, an OAuth MCP service can only get its client through dynamic client registration (RFC 7591), so authorization servers without a registration endpoint cannot be used at all ("server does not support dynamic client registration"), and servers that allow a grant only to clients an administrator registered refuse a dynamic one. JWT bearer grant. The application in front already knows who the user is. POST /api/v1/mcp-services/:id/oauth/assertion lets it present a signed assertion of that identity, such as the Identity Assertion JWT Authorization Grant (ID-JAG) used by MCP's Enterprise-Managed Authorization extension. WeKnora sends it to the service's authorization server with the JWT bearer grant (RFC 7523) and stores the token exactly like the callback does, so status, revoke, runtime connections and, when the response carries a refresh token, refresh use it unchanged. The assertion is forwarded unread; validating it is up to the authorization server. The request reuses the principal from authorize-url, the SSRF-safe HTTP client and the callback's connection recycling, and the client the service already has. It does not run dynamic client registration, which describes a redirect-based client; without a client it answers 400. The token request outlives the caller, so a token issued for an assertion that can only be used once is not lost. A 4xx response other than 408 and 429, or a 2xx response carrying an OAuth error, answers 400 with the OAuth error code and is logged; a 5xx, 408 or 429 response or a network failure answers 500. Request logging masks the assertion field. Pre-registered client. auth_config.client_id names a client registered with the authorization server in advance, and client_secret is its secret for a confidential client. When client_id is set it takes the place of dynamic registration everywhere a client is read: the authorization URL, the code exchange, the assertion grant and runtime connections with their token refreshes. The values live on the service rather than in mcp_oauth_clients, because a refresh rejected with invalid_client deletes that row so the next authorization registers again; an administrator's client would silently disappear. client_id is non-secret: it is set through the main PUT, where an empty value clears it, and returned in auth_config. client_secret follows api_key and token: encrypted at rest, never returned, accepted in the create body, and changed afterwards through the credentials subresource. Changing client_id rebuilds the service's connections, and a connection built with a pre-registered client is not treated as holding a replaced registration when an authorization recycles connections. The MCP service dialog adds optional Client ID and Client Secret fields to the OAuth section, in all six locales. Nothing changes for existing services: with client_id empty every existing path reads the stored registration and registers dynamically as before, and the authorization code flow, its state, the callback and the dynamic registration request are untouched. The authorization server HTTP client is moved into a function that both paths call. --- docs/docs.go | 72 ++++- docs/swagger.json | 72 ++++- docs/swagger.yaml | 58 +++- frontend/src/api/mcp-service.ts | 8 +- frontend/src/i18n/locales/en-US.ts | 3 + frontend/src/i18n/locales/ja-JP.ts | 3 + frontend/src/i18n/locales/ko-KR.ts | 3 + frontend/src/i18n/locales/ru-RU.ts | 3 + frontend/src/i18n/locales/zh-CN.ts | 3 + frontend/src/i18n/locales/zh-TW.ts | 3 + .../components/McpServiceDialog.test.ts | 42 +++ .../settings/components/McpServiceDialog.vue | 51 +++- internal/application/service/mcp_service.go | 27 +- .../application/service/mcp_service_test.go | 98 ++++++- internal/handler/dto/mcp.go | 16 +- internal/handler/dto/mcp_test.go | 18 ++ internal/handler/mcp_credentials.go | 27 +- internal/handler/mcp_oauth.go | 101 +++++++ internal/handler/mcp_oauth_test.go | 182 +++++++++++- internal/handler/mcp_service.go | 10 +- .../handler/mcp_service_client_id_test.go | 71 +++++ internal/mcp/client.go | 23 +- internal/mcp/oauth_assertion.go | 173 +++++++++++ internal/mcp/oauth_assertion_test.go | 274 ++++++++++++++++++ internal/mcp/oauth_manager.go | 35 ++- .../mcp/oauth_preregistered_client_test.go | 115 ++++++++ internal/middleware/logger.go | 2 +- internal/middleware/logger_test.go | 5 + .../router_api_key_capabilities_test.go | 1 + internal/router/routes_infra.go | 7 +- internal/types/interfaces/mcp_service.go | 5 +- internal/types/mcp.go | 23 +- internal/types/mcp_test.go | 16 + website-docs/03-features/08-mcp.md | 13 +- website-docs/04-api/02-api-agent-mcp.md | 25 +- 35 files changed, 1510 insertions(+), 78 deletions(-) create mode 100644 internal/handler/mcp_service_client_id_test.go create mode 100644 internal/mcp/oauth_assertion.go create mode 100644 internal/mcp/oauth_assertion_test.go create mode 100644 internal/mcp/oauth_preregistered_client_test.go diff --git a/docs/docs.go b/docs/docs.go index bc63e854..156d80be 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -8957,7 +8957,7 @@ const docTemplate = `{ "required": true }, { - "description": "{api_key?: string, token?: string}", + "description": "{api_key?, token?, client_secret?: string}", "name": "request", "in": "body", "required": true, @@ -9018,7 +9018,7 @@ const docTemplate = `{ }, { "type": "string", - "description": "字段名(api_key | token)", + "description": "字段名(api_key | token | client_secret)", "name": "field", "in": "path", "required": true @@ -9179,6 +9179,66 @@ const docTemplate = `{ } } }, + "/mcp-services/{id}/oauth/assertion": { + "post": { + "security": [ + { + "Bearer": [] + } + ], + "description": "以 JWT Bearer 授权(RFC 7523)提交调用方签发的断言(如 ID-JAG),为当前用户获取并保存令牌,\n无需浏览器跳转。使用该服务已注册的 OAuth 客户端", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "MCP服务" + ], + "summary": "使用断言获取 MCP OAuth 令牌", + "parameters": [ + { + "type": "string", + "description": "MCP 服务 ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "{assertion: string}", + "name": "request", + "in": "body", + "required": true, + "schema": { + "type": "object", + "additionalProperties": true + } + } + ], + "responses": { + "200": { + "description": "与 oauth/status 相同", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "断言无效或被授权服务器拒绝", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + } + } + } + }, "/mcp-services/{id}/oauth/authorize-url": { "post": { "security": [ @@ -20454,6 +20514,14 @@ const docTemplate = `{ } ] }, + "client_id": { + "description": "ClientID optionally names an OAuth client registered with the\nauthorization server in advance. When set it is used instead of dynamic\nclient registration, for servers that offer no registration endpoint or\nallow grants only to clients an administrator registered. Non-secret.", + "type": "string" + }, + "client_secret": { + "description": "ClientSecret is the secret of ClientID for a confidential client.\nSecret: encrypted at rest like APIKey and Token, never returned, and\nchanged only through the credentials subresource after creation.", + "type": "string" + }, "custom_headers": { "type": "object", "additionalProperties": { diff --git a/docs/swagger.json b/docs/swagger.json index 657eb48a..458c7edd 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -8950,7 +8950,7 @@ "required": true }, { - "description": "{api_key?: string, token?: string}", + "description": "{api_key?, token?, client_secret?: string}", "name": "request", "in": "body", "required": true, @@ -9011,7 +9011,7 @@ }, { "type": "string", - "description": "字段名(api_key | token)", + "description": "字段名(api_key | token | client_secret)", "name": "field", "in": "path", "required": true @@ -9172,6 +9172,66 @@ } } }, + "/mcp-services/{id}/oauth/assertion": { + "post": { + "security": [ + { + "Bearer": [] + } + ], + "description": "以 JWT Bearer 授权(RFC 7523)提交调用方签发的断言(如 ID-JAG),为当前用户获取并保存令牌,\n无需浏览器跳转。使用该服务已注册的 OAuth 客户端", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "MCP服务" + ], + "summary": "使用断言获取 MCP OAuth 令牌", + "parameters": [ + { + "type": "string", + "description": "MCP 服务 ID", + "name": "id", + "in": "path", + "required": true + }, + { + "description": "{assertion: string}", + "name": "request", + "in": "body", + "required": true, + "schema": { + "type": "object", + "additionalProperties": true + } + } + ], + "responses": { + "200": { + "description": "与 oauth/status 相同", + "schema": { + "type": "object", + "additionalProperties": true + } + }, + "400": { + "description": "断言无效或被授权服务器拒绝", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + } + } + } + }, "/mcp-services/{id}/oauth/authorize-url": { "post": { "security": [ @@ -20447,6 +20507,14 @@ } ] }, + "client_id": { + "description": "ClientID optionally names an OAuth client registered with the\nauthorization server in advance. When set it is used instead of dynamic\nclient registration, for servers that offer no registration endpoint or\nallow grants only to clients an administrator registered. Non-secret.", + "type": "string" + }, + "client_secret": { + "description": "ClientSecret is the secret of ClientID for a confidential client.\nSecret: encrypted at rest like APIKey and Token, never returned, and\nchanged only through the credentials subresource after creation.", + "type": "string" + }, "custom_headers": { "type": "object", "additionalProperties": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index fa6d9b0d..8b9136b0 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -2020,6 +2020,19 @@ definitions: description: |- AuthType selects the authentication strategy. Empty ("") is treated as none for backward compatibility with rows that pre-date this field. + client_id: + description: |- + ClientID optionally names an OAuth client registered with the + authorization server in advance. When set it is used instead of dynamic + client registration, for servers that offer no registration endpoint or + allow grants only to clients an administrator registered. Non-secret. + type: string + client_secret: + description: |- + ClientSecret is the secret of ClientID for a confidential client. + Secret: encrypted at rest like APIKey and Token, never returned, and + changed only through the credentials subresource after creation. + type: string custom_headers: additionalProperties: type: string @@ -12441,7 +12454,7 @@ paths: name: id required: true type: string - - description: '{api_key?: string, token?: string}' + - description: '{api_key?, token?, client_secret?: string}' in: body name: request required: true @@ -12479,7 +12492,7 @@ paths: name: id required: true type: string - - description: 字段名(api_key | token) + - description: 字段名(api_key | token | client_secret) in: path name: field required: true @@ -12590,6 +12603,47 @@ paths: summary: 同步 MCP 工具目录 tags: - MCP服务 + /mcp-services/{id}/oauth/assertion: + post: + consumes: + - application/json + description: |- + 以 JWT Bearer 授权(RFC 7523)提交调用方签发的断言(如 ID-JAG),为当前用户获取并保存令牌, + 无需浏览器跳转。使用该服务已注册的 OAuth 客户端 + parameters: + - description: MCP 服务 ID + in: path + name: id + required: true + type: string + - description: '{assertion: string}' + in: body + name: request + required: true + schema: + additionalProperties: true + type: object + produces: + - application/json + responses: + "200": + description: 与 oauth/status 相同 + schema: + additionalProperties: true + type: object + "400": + description: 断言无效或被授权服务器拒绝 + schema: + $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + "404": + description: Not Found + schema: + $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' + security: + - Bearer: [] + summary: 使用断言获取 MCP OAuth 令牌 + tags: + - MCP服务 /mcp-services/{id}/oauth/authorize-url: post: consumes: diff --git a/frontend/src/api/mcp-service.ts b/frontend/src/api/mcp-service.ts index 106446d8..2dd75841 100644 --- a/frontend/src/api/mcp-service.ts +++ b/frontend/src/api/mcp-service.ts @@ -29,6 +29,12 @@ export interface MCPService { // OAuth-only, non-secret configuration. scopes?: string[] auth_server_metadata_url?: string + // OAuth client registered with the authorization server ahead of time. + // Empty means dynamic client registration. Non-secret. + client_id?: string + // Secret of client_id. Like api_key it is never returned; edits go + // through the /credentials subresource. + client_secret?: string } advanced_config?: { timeout?: number @@ -187,7 +193,7 @@ export async function setMCPToolEnabled(serviceId: string, toolName: string, ena // client reconnect server-side. // ---------------------------------------------------------------------------- -export type McpCredentialField = 'api_key' | 'token' +export type McpCredentialField = 'api_key' | 'token' | 'client_secret' export interface CredentialFieldMetadata { configured: boolean diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 5ee732bb..80a17599 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -5684,6 +5684,9 @@ export default { authTypeApiKey: 'API Key / Token', authTypeOAuth: 'OAuth 2.0 (authorize on first connect)', oauthScopes: 'Scopes (optional, space-separated)', + oauthClientId: 'Client ID (optional)', + oauthClientIdDesc: 'A client registered with the authorization server in advance. Leave empty to register one automatically (dynamic client registration). When you change the Client ID, update the Client Secret too.', + oauthClientSecret: 'Client Secret (optional)', oauthAuthorization: 'Authorization Status', oauthAuthorized: 'Authorized', oauthRefreshable: 'Token expired; it will refresh automatically on next use', diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index dc843148..f07d5dc1 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -5684,6 +5684,9 @@ export default { authTypeApiKey: 'APIキー/トークン', authTypeOAuth: 'OAuth 2.0(初回接続時に認可)', oauthScopes: 'スコープ(任意、スペース区切り)', + oauthClientId: 'クライアント ID(任意)', + oauthClientIdDesc: '認可サーバーに事前登録したクライアントを指定します。空欄の場合は動的クライアント登録で自動登録します。クライアント ID を変更する場合はシークレットも更新してください。', + oauthClientSecret: 'クライアントシークレット(任意)', oauthAuthorization: '認可状態', oauthAuthorized: '認可済み', oauthRefreshable: 'トークンの有効期限が切れています。次回利用時に自動的に更新されます', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index ad8cc101..7f290077 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -2464,6 +2464,9 @@ export default { authTypeApiKey: 'API Key / Token', authTypeOAuth: 'OAuth 2.0(최초 연결 시 인증)', oauthScopes: '스코프(선택, 공백으로 구분)', + oauthClientId: '클라이언트 ID(선택)', + oauthClientIdDesc: '인가 서버에 미리 등록한 클라이언트입니다. 비워 두면 동적 클라이언트 등록으로 자동 등록합니다. 클라이언트 ID를 바꾸면 시크릿도 함께 바꿔 주세요.', + oauthClientSecret: '클라이언트 시크릿(선택)', oauthAuthorization: '인증 상태', oauthAuthorized: '인증됨', oauthRefreshable: '토큰이 만료되었습니다. 다음 사용 시 자동으로 갱신됩니다', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index d1f704ee..4c3594c1 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -2464,6 +2464,9 @@ export default { authTypeApiKey: 'API Key / Token', authTypeOAuth: 'OAuth 2.0 (авторизация при первом подключении)', oauthScopes: 'Области (необязательно, через пробел)', + oauthClientId: 'Client ID (необязательно)', + oauthClientIdDesc: 'Клиент, заранее зарегистрированный на сервере авторизации. Оставьте пустым, чтобы зарегистрировать клиента автоматически (динамическая регистрация). При смене Client ID обновите и Client Secret.', + oauthClientSecret: 'Client Secret (необязательно)', oauthAuthorization: 'Статус авторизации', oauthAuthorized: 'Авторизовано', oauthRefreshable: 'Срок действия токена истёк; он будет автоматически обновлён при следующем использовании', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 06b0640d..5dc856c6 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -2466,6 +2466,9 @@ export default { authTypeApiKey: 'API Key / Token', authTypeOAuth: 'OAuth 2.0(首次连接授权)', oauthScopes: 'Scopes(可选,空格分隔)', + oauthClientId: 'Client ID(可选)', + oauthClientIdDesc: '填写在授权服务器预先注册的客户端;留空则自动进行动态客户端注册。更换 Client ID 时请同时更新 Client Secret。', + oauthClientSecret: 'Client Secret(可选)', oauthAuthorization: '授权状态', oauthAuthorized: '已授权', oauthRefreshable: 'Token 已过期,将在下次使用时自动刷新', diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts index 94cba1c0..8a36b5b8 100644 --- a/frontend/src/i18n/locales/zh-TW.ts +++ b/frontend/src/i18n/locales/zh-TW.ts @@ -2466,6 +2466,9 @@ export default { authTypeApiKey: 'API Key / Token', authTypeOAuth: 'OAuth 2.0(首次連結授權)', oauthScopes: 'Scopes(可選,空格分隔)', + oauthClientId: 'Client ID(可選)', + oauthClientIdDesc: '填寫在授權伺服器預先註冊的用戶端;留空則自動進行動態用戶端註冊。更換 Client ID 時請同時更新 Client Secret。', + oauthClientSecret: 'Client Secret(可選)', oauthAuthorization: '授權狀態', oauthAuthorized: '已授權', oauthRefreshable: 'Token 已過期,將在下次使用時自動重新整理', diff --git a/frontend/src/views/settings/components/McpServiceDialog.test.ts b/frontend/src/views/settings/components/McpServiceDialog.test.ts index 206335d8..1563a68d 100644 --- a/frontend/src/views/settings/components/McpServiceDialog.test.ts +++ b/frontend/src/views/settings/components/McpServiceDialog.test.ts @@ -133,3 +133,45 @@ test('closing or switching service prevents a late AI result from overwriting th } finally { f.close() } } }) + +test('OAuth payload always carries the client ID and sends its secret only on create', () => { + const f = fixture() + try { + f.vm.formData.auth_config.auth_type = 'oauth' + f.vm.formData.auth_config.client_id = ' pre-registered ' + f.vm.formData.auth_config.client_secret = 'shh' + const created = f.vm.buildPayload(true) + assert.equal(created.auth_config.client_id, 'pre-registered') + assert.equal(created.auth_config.client_secret, 'shh') + const edited = f.vm.buildPayload(false) + assert.equal(edited.auth_config.client_id, 'pre-registered') + assert.equal('client_secret' in edited.auth_config, false) + + f.vm.formData.auth_config.client_id = '' + assert.equal(f.vm.buildPayload(false).auth_config.client_id, '', 'clearing returns to dynamic registration') + } finally { f.close() } +}) + +test('OAuth client secret is edited through the credentials card', () => { + const f = fixture() + try { + f.vm.formData.auth_config.auth_type = 'oauth' + assert.deepEqual(Array.from(f.vm.credentialFields, (field: { key: string }) => field.key), ['client_secret']) + f.vm.formData.auth_config.auth_type = 'api_key' + assert.deepEqual(Array.from(f.vm.credentialFields, (field: { key: string }) => field.key), ['api_key']) + f.vm.formData.auth_config.auth_type = '' + assert.equal(f.vm.credentialFields.length, 0) + } finally { f.close() } +}) + +test('API key payload never carries OAuth client fields', () => { + const f = fixture() + try { + f.vm.formData.auth_config.auth_type = 'api_key' + f.vm.formData.auth_config.client_id = 'left-over' + f.vm.formData.auth_config.client_secret = 'left-over' + const body = f.vm.buildPayload(true) + assert.equal('client_id' in body.auth_config, false) + assert.equal('client_secret' in body.auth_config, false) + } finally { f.close() } +}) diff --git a/frontend/src/views/settings/components/McpServiceDialog.vue b/frontend/src/views/settings/components/McpServiceDialog.vue index 2e33c08d..e8a0afe7 100644 --- a/frontend/src/views/settings/components/McpServiceDialog.vue +++ b/frontend/src/views/settings/components/McpServiceDialog.vue @@ -192,12 +192,34 @@ - +