Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(mcp): let callers without a browser obtain MCP OAuth tokens (#4229)
Ochan Kwone0712df3e020
diff --git a/docs/docs.go b/docs/docs.goindex bc63e8547..156d80be9 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.jsonindex 657eb48ae..458c7edd6 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.yamlindex fa6d9b0d5..8b9136b05 100644--- a/docs/swagger.yaml+++ b/docs/swagger.yaml@@ -2020,6 +2020,19 @@ definitions:description: |-AuthType selects the authentication strategy. Empty ("") is treated asnone 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: stringcustom_headers:additionalProperties:type: string@@ -12441,7 +12454,7 @@ paths:name: idrequired: truetype: string- - description: '{api_key?: string, token?: string}'+ - description: '{api_key?, token?, client_secret?: string}'in: bodyname: requestrequired: true@@ -12479,7 +12492,7 @@ paths:name: idrequired: truetype: string- - description: 字段名(api_key | token)+ - description: 字段名(api_key | token | client_secret)in: pathname: fieldrequired: 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.tsindex 106446d86..2dd758419 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: booleandiff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 5ee732bbe..80a175992 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.tsindex dc843148f..f07d5dc1c 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.tsindex ad8cc1013..7f2900776 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.tsindex d1f704ee7..4c3594c19 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.tsindex 06b0640d4..5dc856c68 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.tsindex 94cba1c02..8a36b5b8e 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.tsindex 206335d8d..1563a68d9 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.vueindex 2e33c08d0..e8a0afe7e 100644--- a/frontend/src/views/settings/components/McpServiceDialog.vue+++ b/frontend/src/views/settings/components/McpServiceDialog.vue@@ -192,12 +192,34 @@</div></div>- <!-- OAuth 2.0:零配置(自动发现 + 动态客户端注册),按用户授权 -->+ <!-- OAuth 2.0:默认零配置(自动发现 + 动态客户端注册),也可填写预注册客户端;按用户授权 --><template v-if="isOAuth"><div class="form-item"><label class="form-label">{{ t('mcpServiceDialog.oauthScopes', 'Scopes(可选,空格分隔)') }}</label><t-input v-model="oauthScopesText" :placeholder="t('mcpServiceDialog.optional')" /></div>+ <div class="form-item">+ <label class="form-label">{{ t('mcpServiceDialog.oauthClientId', 'Client ID(可选)') }}</label>+ <t-input v-model="formData.auth_config.client_id" :placeholder="t('mcpServiceDialog.optional')" />+ <p class="form-desc">{{ t('mcpServiceDialog.oauthClientIdDesc', '填写在授权服务器预先注册的客户端;留空则自动进行动态客户端注册。更换 Client ID 时请同时更新 Client Secret。') }}</p>+ </div>+ <div class="form-item">+ <label class="form-label">{{ t('mcpServiceDialog.oauthClientSecret', 'Client Secret(可选)') }}</label>+ <CredentialResource+ v-if="mode === 'edit' && currentService?.id"+ :api="credentialApi"+ :fields="credentialFields"+ :meta="credentialMeta"+ />+ <t-input+ v-else+ v-model="formData.auth_config.client_secret"+ type="password"+ :placeholder="t('mcpServiceDialog.optional')"+ >+ <template #prefix-icon><t-icon name="lock-on" /></template>+ </t-input>+ </div><div class="form-item"><label class="form-label">{{ t('mcpServiceDialog.oauthAuthorization', '授权状态') }}</label><div class="oauth-status">@@ -439,6 +461,10 @@ const formData = ref({// OAuth-only, non-secret config.scopes: [] as string[],auth_server_metadata_url: '',+ // Pre-registered OAuth client; empty means dynamic client registration.+ client_id: '',+ // Only used in add-mode; in edit-mode the CredentialResource owns it.+ client_secret: '',},advanced_config: {timeout: 30,@@ -520,6 +546,8 @@ function applyServerConfig(name: string, cfg: Record<string, unknown>) {formData.value.auth_config.api_key = apiKeyformData.value.auth_config.api_key_header = apiKeyHeaderformData.value.auth_config.scopes = []+ formData.value.auth_config.client_id = ''+ formData.value.auth_config.client_secret = ''return true}@@ -705,12 +733,15 @@ const transportLabel = computed(() => {// MCP so other resources don't accidentally inherit "API Key" / "Bearer// Token" labels via the shared component.// The unified credential strategy stores its secret in the api_key field-// (placed verbatim into the configured header). None / OAuth carry no static-// secret, so the credential card is only shown for the api_key strategy.+// (placed verbatim into the configured header). OAuth's only static secret is+// the optional secret of a pre-registered client; none carries no secret.const credentialFields = computed<CredentialFieldDef<McpCredentialField>[]>(() => {if (formData.value.auth_config.auth_type === 'api_key') {return [{ key: 'api_key', label: t('mcpServiceDialog.credentialValue', '密钥值 / Token') }]}+ if (isOAuth.value) {+ return [{ key: 'client_secret', label: t('mcpServiceDialog.oauthClientSecret', 'Client Secret(可选)') }]+ }return []})@@ -736,6 +767,7 @@ const credentialApi = computed<CredentialResourceApi<McpCredentialField>>(() =>const credentialMeta = computed(() => currentService.value?.credentials ?? {api_key: { configured: false },token: { configured: false },+ client_secret: { configured: false },})const rules: Record<string, FormRule[]> = {@@ -817,7 +849,10 @@ const resetForm = () => {transport_type: 'sse',url: '',headers: [],- auth_config: { auth_type: '', api_key: '', api_key_header: '', token: '', scopes: [], auth_server_metadata_url: '' },+ auth_config: {+ auth_type: '', api_key: '', api_key_header: '', token: '', scopes: [], auth_server_metadata_url: '',+ client_id: '', client_secret: '',+ },advanced_config: { timeout: 30, retry_count: 3, retry_delay: 1 },}formRef.value?.clearValidate()@@ -865,6 +900,8 @@ watch(token: '',scopes: service.auth_config?.scopes ? [...service.auth_config.scopes] : [],auth_server_metadata_url: service.auth_config?.auth_server_metadata_url || '',+ client_id: service.auth_config?.client_id || '',+ client_secret: '',},advanced_config: {timeout: service.advanced_config?.timeout || 30,@@ -916,6 +953,12 @@ function buildPayload(asCreate: boolean): Partial<MCPService> {if (formData.value.auth_config.auth_server_metadata_url) {auth.auth_server_metadata_url = formData.value.auth_config.auth_server_metadata_url}+ // Always sent so clearing the field returns the service to dynamic+ // client registration.+ auth.client_id = formData.value.auth_config.client_id.trim()+ if (asCreate && formData.value.auth_config.client_secret) {+ auth.client_secret = formData.value.auth_config.client_secret+ }}if (asCreate && !isOAuth.value) {if (formData.value.auth_config.api_key) auth.api_key = formData.value.auth_config.api_keydiff --git a/internal/application/service/mcp_service.go b/internal/application/service/mcp_service.goindex 0516349a2..4af61f02a 100644--- a/internal/application/service/mcp_service.go+++ b/internal/application/service/mcp_service.go@@ -161,8 +161,8 @@ func (s *mcpServiceService) UpdateMCPService(// existing.URL = service.URL, after which any post-merge comparison// between service.URL and existing.URL would trivially match.//- // AuthConfig is intentionally NOT snapshotted/compared here — credential- // changes now flow through the dedicated /credentials subresource which+ // Only the non-secret AuthConfig fields below are snapshotted — credential+ // changes flow through the dedicated /credentials subresource which// handles its own CloseClient call. Main PUT does not accept secret// fields (see handler comment on UpdateMCPService).preURL := ""@@ -185,9 +185,11 @@ func (s *mcpServiceService) UpdateMCPService(preAuthType := types.MCPAuthNonepreAPIKeyHeader := ""+ preClientID := ""if existing.AuthConfig != nil {preAuthType = existing.AuthConfig.AuthTypepreAPIKeyHeader = existing.AuthConfig.APIKeyHeader+ preClientID = existing.AuthConfig.ClientID}// CustomHeaders flows through main PUT (it's structural, not a secret) —@@ -220,6 +222,11 @@ func (s *mcpServiceService) UpdateMCPService(if service.AuthConfig.AuthServerMetadataURL != "" {existing.AuthConfig.AuthServerMetadataURL = service.AuthConfig.AuthServerMetadataURL}+ // Empty means dynamic client registration, so only an explicitly+ // sent client_id may clear it.+ if updateFields["client_id"] {+ existing.AuthConfig.ClientID = service.AuthConfig.ClientID+ }}// Scalar zero values cannot distinguish omission from an explicit update,@@ -298,9 +305,12 @@ func (s *mcpServiceService) UpdateMCPService(if !maps.Equal(currHeaders, preHeaders) {configChanged = true}+ // Connections built with a pre-registered OAuth client hold its ID, so+ // they are rebuilt when it changes.if existing.AuthConfig != nil &&(existing.AuthConfig.AuthType != preAuthType ||- existing.AuthConfig.APIKeyHeader != preAPIKeyHeader) {+ existing.AuthConfig.APIKeyHeader != preAPIKeyHeader ||+ existing.AuthConfig.ClientID != preClientID) {configChanged = true}name := secutils.SanitizeForLog(existing.Name)@@ -500,7 +510,7 @@ func (s *mcpServiceService) GetMCPServiceTools(// - Always re-fetches existing AuthConfig before merge to avoid clobbering// CustomHeaders or the unrelated credential field.func (s *mcpServiceService) UpdateMCPCredentials(- ctx context.Context, tenantID uint64, id string, apiKey *string, token *string,+ ctx context.Context, tenantID uint64, id string, apiKey, token, clientSecret *string,) (*types.MCPService, error) {existing, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)if err != nil {@@ -525,6 +535,10 @@ func (s *mcpServiceService) UpdateMCPCredentials(existing.AuthConfig.Token = *tokenchanged = true}+ if clientSecret != nil && *clientSecret != "" && *clientSecret != existing.AuthConfig.ClientSecret {+ existing.AuthConfig.ClientSecret = *clientSecret+ changed = true+ }if !changed {return existing, nil}@@ -574,6 +588,11 @@ func (s *mcpServiceService) ClearMCPCredential(existing.AuthConfig.Token = ""changed = true}+ case "client_secret":+ if existing.AuthConfig.ClientSecret != "" {+ existing.AuthConfig.ClientSecret = ""+ changed = true+ }default:return fmt.Errorf("unknown credential field: %s", field)}diff --git a/internal/application/service/mcp_service_test.go b/internal/application/service/mcp_service_test.goindex 5ad6b6cda..bd943fb4a 100644--- a/internal/application/service/mcp_service_test.go+++ b/internal/application/service/mcp_service_test.go@@ -401,7 +401,7 @@ func TestUpdateMCPCredentials_WritesAPIKey(t *testing.T) {id := seedService(t, repo, "", "")newKey := "fresh-api-key"- got, err := svc.UpdateMCPCredentials(ctx, 1, id, &newKey, nil)+ got, err := svc.UpdateMCPCredentials(ctx, 1, id, &newKey, nil, nil)require.NoError(t, err)require.NotNil(t, got.AuthConfig)assert.Equal(t, "fresh-api-key", got.AuthConfig.APIKey)@@ -416,7 +416,7 @@ func TestUpdateMCPCredentials_NilPointerIsNoop(t *testing.T) {svc, repo := newTestService()id := seedService(t, repo, "stored-api", "stored-token")- got, err := svc.UpdateMCPCredentials(ctx, 1, id, nil, nil)+ got, err := svc.UpdateMCPCredentials(ctx, 1, id, nil, nil, nil)require.NoError(t, err)assert.Equal(t, "stored-api", got.AuthConfig.APIKey)assert.Equal(t, "stored-token", got.AuthConfig.Token)@@ -428,7 +428,7 @@ func TestUpdateMCPCredentials_EmptyStringIsNoop(t *testing.T) {id := seedService(t, repo, "stored-api", "stored-token")empty := ""- got, err := svc.UpdateMCPCredentials(ctx, 1, id, &empty, &empty)+ got, err := svc.UpdateMCPCredentials(ctx, 1, id, &empty, &empty, nil)require.NoError(t, err)assert.Equal(t, "stored-api", got.AuthConfig.APIKey,"empty string is treated as no-op; clearing goes through ClearMCPCredential")@@ -441,7 +441,7 @@ func TestUpdateMCPCredentials_ReplacesExisting(t *testing.T) {id := seedService(t, repo, "old-api", "old-token")newKey, newTok := "new-api", "new-tok"- got, err := svc.UpdateMCPCredentials(ctx, 1, id, &newKey, &newTok)+ got, err := svc.UpdateMCPCredentials(ctx, 1, id, &newKey, &newTok, nil)require.NoError(t, err)assert.Equal(t, "new-api", got.AuthConfig.APIKey)assert.Equal(t, "new-tok", got.AuthConfig.Token)@@ -454,7 +454,7 @@ func TestUpdateMCPCredentials_RejectsBuiltin(t *testing.T) {repo.store[id].IsBuiltin = truenewKey := "anything"- _, err := svc.UpdateMCPCredentials(ctx, 1, id, &newKey, nil)+ _, err := svc.UpdateMCPCredentials(ctx, 1, id, &newKey, nil, nil)require.Error(t, err)assert.Contains(t, strings.ToLower(err.Error()), "builtin")}@@ -463,7 +463,7 @@ func TestUpdateMCPCredentials_ServiceNotFound(t *testing.T) {ctx := context.Background()svc, _ := newTestService()newKey := "x"- _, err := svc.UpdateMCPCredentials(ctx, 1, "nope", &newKey, nil)+ _, err := svc.UpdateMCPCredentials(ctx, 1, "nope", &newKey, nil, nil)require.Error(t, err)}@@ -554,3 +554,89 @@ func TestListMCPServices_ReturnsRawCredentials(t *testing.T) {assert.Equal(t, "real-api", got[0].AuthConfig.APIKey)assert.Equal(t, "real-token", got[0].AuthConfig.Token)}++// ---- Pre-registered OAuth client ----++func TestUpdateMCPService_ClientIDNeedsAnExplicitField(t *testing.T) {+ ctx := context.Background()+ svc, repo := newTestService()+ id := seedService(t, repo, "", "")+ repo.store[id].AuthConfig.ClientID = "pre-registered"++ // A PUT that does not send client_id keeps it.+ require.NoError(t, svc.UpdateMCPService(ctx, &types.MCPService{+ ID: id, TenantID: 1, AuthConfig: &types.MCPAuthConfig{},+ }, map[string]bool{}))+ assert.Equal(t, "pre-registered", repo.store[id].AuthConfig.ClientID)++ // Sending an empty client_id returns the service to dynamic registration.+ require.NoError(t, svc.UpdateMCPService(ctx, &types.MCPService{+ ID: id, TenantID: 1, AuthConfig: &types.MCPAuthConfig{},+ }, map[string]bool{"client_id": true}))+ assert.Empty(t, repo.store[id].AuthConfig.ClientID)++ require.NoError(t, svc.UpdateMCPService(ctx, &types.MCPService{+ ID: id, TenantID: 1, AuthConfig: &types.MCPAuthConfig{ClientID: "another", ClientSecret: "ignored"},+ }, map[string]bool{"client_id": true}))+ assert.Equal(t, "another", repo.store[id].AuthConfig.ClientID)+ assert.Empty(t, repo.store[id].AuthConfig.ClientSecret, "main PUT never writes the secret")+}++func TestUpdateMCPCredentials_WritesClientSecret(t *testing.T) {+ ctx := context.Background()+ svc, repo := newTestService()+ id := seedService(t, repo, "stored-api", "stored-token")+ secret := "client-secret"++ got, err := svc.UpdateMCPCredentials(ctx, 1, id, nil, nil, &secret)+ require.NoError(t, err)+ assert.Equal(t, "client-secret", got.AuthConfig.ClientSecret)+ assert.Equal(t, "stored-api", repo.store[id].AuthConfig.APIKey, "other fields untouched")++ require.NoError(t, svc.ClearMCPCredential(ctx, 1, id, "client_secret"))+ assert.Empty(t, repo.store[id].AuthConfig.ClientSecret)+ assert.Equal(t, "stored-token", repo.store[id].AuthConfig.Token)+}++// Connections are built with the pre-registered client, so changing it+// rebuilds them, while a PUT that sends the same value (the dialog sends+// client_id on every OAuth save) keeps them.+func TestUpdateMCPService_ClientIDChangeRebuildsConnections(t *testing.T) {+ utils.SetSSRFWhitelistFromRaw("127.0.0.1")+ t.Cleanup(utils.ResetSSRFWhitelistForTest)+ upstream := sdkserver.NewStreamableHTTPServer(sdkserver.NewMCPServer("test", "1"), sdkserver.WithStateLess(true))+ server := httptest.NewServer(upstream)+ t.Cleanup(server.Close)++ ctx := context.Background()+ svc, repo := newTestService()+ t.Cleanup(svc.mcpManager.Shutdown)+ url := server.URL+ repo.store["svc"] = &types.MCPService{+ ID: "svc", TenantID: 1, Name: "test", Enabled: true, URL: &url,+ TransportType: types.MCPTransportHTTPStreamable,+ AuthConfig: &types.MCPAuthConfig{ClientID: "pre-registered"},+ }+ connect := func() {+ t.Helper()+ _, err := svc.mcpManager.GetOrCreateClient(ctx, repo.store["svc"])+ require.NoError(t, err)+ _, ok := svc.mcpManager.GetClient("svc")+ require.True(t, ok)+ }+ update := func(clientID string) {+ t.Helper()+ require.NoError(t, svc.UpdateMCPService(ctx, &types.MCPService{+ ID: "svc", TenantID: 1, AuthConfig: &types.MCPAuthConfig{ClientID: clientID},+ }, map[string]bool{"client_id": true}))+ }++ connect()+ update("pre-registered")+ _, ok := svc.mcpManager.GetClient("svc")+ assert.True(t, ok, "the same client_id keeps the connection")++ update("another")+ _, ok = svc.mcpManager.GetClient("svc")+ assert.False(t, ok, "a new client_id rebuilds the connection")+}diff --git a/internal/handler/dto/mcp.go b/internal/handler/dto/mcp.goindex 1ac08fd53..80b495ca0 100644--- a/internal/handler/dto/mcp.go+++ b/internal/handler/dto/mcp.go@@ -56,16 +56,18 @@ type MCPCatalogSummary struct {SyncedAt time.Time `json:"synced_at"`}-// MCPAuthConfigResponse intentionally has no APIKey or Token fields. Their-// presence is signalled via MCPServiceResponse.Credentials. AuthType, Scopes-// and AuthServerMetadataURL are non-secret OAuth configuration and are safe to-// echo back so the UI can render the current strategy.+// MCPAuthConfigResponse intentionally has no APIKey, Token or ClientSecret+// fields. Their presence is signalled via MCPServiceResponse.Credentials.+// AuthType, Scopes, AuthServerMetadataURL and ClientID are non-secret OAuth+// configuration and are safe to echo back so the UI can render the current+// strategy.type MCPAuthConfigResponse struct {AuthType types.MCPAuthType `json:"auth_type,omitempty"`APIKeyHeader string `json:"api_key_header,omitempty"`CustomHeaders map[string]string `json:"custom_headers,omitempty"`Scopes []string `json:"scopes,omitempty"`AuthServerMetadataURL string `json:"auth_server_metadata_url,omitempty"`+ ClientID string `json:"client_id,omitempty"`}// CredentialFieldMetadata reports whether a credential field has a value@@ -116,6 +118,7 @@ func NewMCPServiceResponse(ctx context.Context, svc *types.MCPService) *MCPServiCustomHeaders: svc.AuthConfig.CustomHeaders,Scopes: svc.AuthConfig.Scopes,AuthServerMetadataURL: svc.AuthConfig.AuthServerMetadataURL,+ ClientID: svc.AuthConfig.ClientID,}if !includeDetail {auth.CustomHeaders = nil@@ -132,8 +135,9 @@ func NewMCPServiceResponse(ctx context.Context, svc *types.MCPService) *MCPServiresp.AuthConfig = nil} else {resp.Credentials = map[string]CredentialFieldMetadata{- "api_key": {Configured: svc.AuthConfig != nil && svc.AuthConfig.APIKey != ""},- "token": {Configured: svc.AuthConfig != nil && svc.AuthConfig.Token != ""},+ "api_key": {Configured: svc.AuthConfig != nil && svc.AuthConfig.APIKey != ""},+ "token": {Configured: svc.AuthConfig != nil && svc.AuthConfig.Token != ""},+ "client_secret": {Configured: svc.AuthConfig != nil && svc.AuthConfig.ClientSecret != ""},}}return respdiff --git a/internal/handler/dto/mcp_test.go b/internal/handler/dto/mcp_test.goindex 34e72f8a6..247dd6706 100644--- a/internal/handler/dto/mcp_test.go+++ b/internal/handler/dto/mcp_test.go@@ -119,3 +119,21 @@ func TestAttachMCPCatalogs_MarksStaleWithoutCopyingTools(t *testing.T) {require.NotContains(string(body), `"tools"`)require.Contains(string(body), `"tool_count":3`)}++func TestMCPServiceResponse_EchoesClientIDButNotItsSecret(t *testing.T) {+ svc := &types.MCPService{+ ID: "svc-1",+ Name: "svc",+ AuthConfig: &types.MCPAuthConfig{+ AuthType: types.MCPAuthOAuth,+ ClientID: "pre-registered",+ ClientSecret: "client-secret-do-not-leak",+ },+ }+ body, err := json.Marshal(NewMCPServiceResponse(adminContext(), svc))+ assert.NoError(t, err)+ s := string(body)+ assert.NotContains(t, s, "client-secret-do-not-leak")+ assert.Contains(t, s, `"client_id":"pre-registered"`)+ assert.Contains(t, s, `"client_secret":{"configured":true}`)+}diff --git a/internal/handler/mcp_credentials.go b/internal/handler/mcp_credentials.goindex c8cf0d60a..e9dbe8ba6 100644--- a/internal/handler/mcp_credentials.go+++ b/internal/handler/mcp_credentials.go@@ -36,13 +36,15 @@ func NewMCPCredentialsHandler(svc interfaces.MCPServiceService) *MCPCredentialsHreturn &MCPCredentialsHandler{svc: svc}}-// mcpCredentialsPutRequest is the body shape for PUT /credentials. Both+// mcpCredentialsPutRequest is the body shape for PUT /credentials. The// fields are pointers so the handler can distinguish "absent" (preserve)// from "present and empty" (treat as no-op; clients should call DELETE to// remove a credential). Non-empty values replace the stored secret.type mcpCredentialsPutRequest struct {APIKey *string `json:"api_key,omitempty"`Token *string `json:"token,omitempty"`+ // ClientSecret is the secret of a pre-registered OAuth client.+ ClientSecret *string `json:"client_secret,omitempty"`}// Put writes (creates or replaces) one or more credential fields on the MCP@@ -56,7 +58,7 @@ type mcpCredentialsPutRequest struct {// @Accept json// @Produce json// @Param id path string true "MCP 服务 ID"-// @Param request body map[string]interface{} true "{api_key?: string, token?: string}"+// @Param request body map[string]interface{} true "{api_key?, token?, client_secret?: string}"// @Success 200 {object} map[string]interface{} "写入后的凭据状态"// @Failure 400 {object} errors.AppError "请求参数错误"// @Failure 404 {object} errors.AppError "服务不存在"@@ -80,7 +82,7 @@ func (h *MCPCredentialsHandler) Put(c *gin.Context) {// Nothing to do — but rather than 400 (benign no-op), look up current// state and return it. Client treats this identically to a real save.- if req.APIKey == nil && req.Token == nil {+ if req.APIKey == nil && req.Token == nil && req.ClientSecret == nil {svc, err := h.svc.GetMCPServiceByID(ctx, tenantID, serviceID)if err != nil || svc == nil {c.Error(errors.NewNotFoundError("MCP service not found"))@@ -88,14 +90,15 @@ func (h *MCPCredentialsHandler) Put(c *gin.Context) {}c.JSON(http.StatusOK, gin.H{"success": true, "data": dto.CredentialsResponse{Fields: map[string]dto.CredentialFieldMetadata{- "api_key": {Configured: svc.AuthConfig != nil && svc.AuthConfig.APIKey != ""},- "token": {Configured: svc.AuthConfig != nil && svc.AuthConfig.Token != ""},+ "api_key": {Configured: svc.AuthConfig != nil && svc.AuthConfig.APIKey != ""},+ "token": {Configured: svc.AuthConfig != nil && svc.AuthConfig.Token != ""},+ "client_secret": {Configured: svc.AuthConfig != nil && svc.AuthConfig.ClientSecret != ""},},}})return}- updated, err := h.svc.UpdateMCPCredentials(ctx, tenantID, serviceID, req.APIKey, req.Token)+ updated, err := h.svc.UpdateMCPCredentials(ctx, tenantID, serviceID, req.APIKey, req.Token, req.ClientSecret)if err != nil {logger.ErrorWithFields(ctx, err, map[string]interface{}{"service_id": secutils.SanitizeForLog(serviceID),@@ -106,15 +109,17 @@ func (h *MCPCredentialsHandler) Put(c *gin.Context) {resp := dto.CredentialsResponse{Fields: map[string]dto.CredentialFieldMetadata{- "api_key": {Configured: updated.AuthConfig != nil && updated.AuthConfig.APIKey != ""},- "token": {Configured: updated.AuthConfig != nil && updated.AuthConfig.Token != ""},+ "api_key": {Configured: updated.AuthConfig != nil && updated.AuthConfig.APIKey != ""},+ "token": {Configured: updated.AuthConfig != nil && updated.AuthConfig.Token != ""},+ "client_secret": {Configured: updated.AuthConfig != nil && updated.AuthConfig.ClientSecret != ""},},}c.JSON(http.StatusOK, gin.H{"success": true, "data": resp})}// DeleteField removes one credential field. Recognized fields: "api_key",-// "token". Returns 204 on success (even if the field was already empty).+// "token", "client_secret". Returns 204 on success (even if the field was+// already empty).//// DeleteField godoc// @Summary 移除 MCP 服务的单个凭据字段@@ -122,7 +127,7 @@ func (h *MCPCredentialsHandler) Put(c *gin.Context) {// @Tags MCP服务// @Produce json// @Param id path string true "MCP 服务 ID"-// @Param field path string true "字段名(api_key | token)"+// @Param field path string true "字段名(api_key | token | client_secret)"// @Success 204// @Failure 400 {object} errors.AppError "字段名非法"// @Failure 404 {object} errors.AppError "服务不存在"@@ -138,7 +143,7 @@ func (h *MCPCredentialsHandler) DeleteField(c *gin.Context) {c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))return}- if field != "api_key" && field != "token" {+ if field != "api_key" && field != "token" && field != "client_secret" {c.Error(errors.NewBadRequestError("unknown credential field: " + secutils.SanitizeForLog(field)))return}diff --git a/internal/handler/mcp_oauth.go b/internal/handler/mcp_oauth.goindex 49526a7ef..0d22aee5c 100644--- a/internal/handler/mcp_oauth.go+++ b/internal/handler/mcp_oauth.go@@ -126,6 +126,107 @@ func (h *MCPOAuthHandler) AuthorizeURL(c *gin.Context) {}})}+// mcpOAuthAssertionMaxBytes caps the assertion request body. Signed JWT+// assertions are a few kilobytes at most.+const mcpOAuthAssertionMaxBytes = 16 << 10++type mcpOAuthAssertionRequest struct {+ // Assertion is the signed JWT presented to the authorization server with+ // the JWT bearer grant, for example an ID-JAG issued for the current user.+ Assertion string `json:"assertion"`+}++// AssertionGrant obtains the current user's token with the JWT bearer grant+// (RFC 7523) instead of the browser authorization code flow. It is for+// applications that run WeKnora behind their own sign-in and call it for+// their users, where no browser can follow an authorization redirect. The+// grant uses the OAuth client already registered for the service, and the+// token is stored exactly like one obtained through the callback.+//+// AssertionGrant godoc+// @Summary 使用断言获取 MCP OAuth 令牌+// @Description 以 JWT Bearer 授权(RFC 7523)提交调用方签发的断言(如 ID-JAG),为当前用户获取并保存令牌,+// @Description 无需浏览器跳转。使用该服务已注册的 OAuth 客户端+// @Tags MCP服务+// @Accept json+// @Produce json+// @Param id path string true "MCP 服务 ID"+// @Param request body map[string]interface{} true "{assertion: string}"+// @Success 200 {object} map[string]interface{} "与 oauth/status 相同"+// @Failure 400 {object} errors.AppError "断言无效或被授权服务器拒绝"+// @Failure 404 {object} errors.AppError+// @Security Bearer+// @Router /mcp-services/{id}/oauth/assertion [post]+func (h *MCPOAuthHandler) AssertionGrant(c *gin.Context) {+ ctx := c.Request.Context()+ serviceID := c.Param("id")+ tenantID := c.GetUint64(types.TenantIDContextKey.String())+ principal, _ := mcpOAuthPrincipalsFromContext(c)+ if tenantID == 0 || !principal.Valid() {+ _ = c.Error(errors.NewUnauthorizedError("authentication required"))+ return+ }++ limitJSONBody(c, mcpOAuthAssertionMaxBytes)+ var req mcpOAuthAssertionRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ if isRequestBodyTooLarge(err) {+ _ = c.Error(errors.NewBadRequestError("request body is too large"))+ return+ }+ _ = c.Error(errors.NewBadRequestError("invalid request body"))+ return+ }+ req.Assertion = strings.TrimSpace(req.Assertion)+ if req.Assertion == "" {+ _ = c.Error(errors.NewValidationError("assertion is required"))+ return+ }++ service, err := h.svc.GetMCPServiceByID(ctx, tenantID, serviceID)+ if err != nil || service == nil {+ _ = c.Error(errors.NewNotFoundError("MCP service not found"))+ return+ }+ if !service.AuthConfig.IsOAuth() {+ _ = c.Error(errors.NewValidationError("MCP service is not configured to use OAuth"))+ return+ }++ err = h.oauth.AuthorizeWithAssertion(ctx, service, tenantID, principal, req.Assertion)+ if err != nil {+ var rejected *mcp.OAuthGrantRejectedError+ switch {+ case stderrors.Is(err, mcp.ErrOAuthClientNotRegistered):+ _ = c.Error(errors.NewValidationError(err.Error()))+ case stderrors.As(err, &rejected):+ logger.Warnf(ctx, "MCP OAuth assertion rejected: service=%s status=%d code=%s",+ secutils.SanitizeForLog(serviceID), rejected.StatusCode, secutils.SanitizeForLog(rejected.Code))+ _ = c.Error(errors.NewBadRequestError(rejected.Error()))+ default:+ logger.ErrorWithFields(ctx, err, map[string]interface{}{+ "service_id": secutils.SanitizeForLog(serviceID),+ })+ _ = c.Error(errors.NewInternalServerError("failed to obtain token with assertion: " + err.Error()))+ }+ return+ }+ // Recycle connections the same way the callback does, so the user's next+ // call reconnects with the new token.+ if h.mcpManager != nil {+ cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), oauthConnectionCleanupTimeout)+ _ = h.mcpManager.CloseClientsAfterAuthorization(cleanupCtx, tenantID, serviceID, principal)+ cancel()+ }++ status, err := h.oauth.AuthorizationStatus(ctx, tenantID, principal, serviceID)+ if err != nil {+ _ = c.Error(errors.NewInternalServerError("failed to query authorization status: " + err.Error()))+ return+ }+ c.JSON(http.StatusOK, gin.H{"success": true, "data": status})+}+// Callback receives the authorization-server redirect. It is registered as a// public (no-bearer) route; the opaque single-use `state` parameter// authenticates the request. On completion it redirects the browser back todiff --git a/internal/handler/mcp_oauth_test.go b/internal/handler/mcp_oauth_test.goindex 83a67f9b4..d39d5f236 100644--- a/internal/handler/mcp_oauth_test.go+++ b/internal/handler/mcp_oauth_test.go@@ -7,11 +7,13 @@ import ("net/http""net/http/httptest""net/url"+ "strings""sync""testing""time""github.com/Tencent/WeKnora/internal/mcp"+ "github.com/Tencent/WeKnora/internal/middleware""github.com/Tencent/WeKnora/internal/types""github.com/Tencent/WeKnora/internal/types/interfaces"secutils "github.com/Tencent/WeKnora/internal/utils"@@ -93,6 +95,11 @@ type mcpOAuthTestEnv struct {oauth *mcp.OAuthManagermanager *mcp.MCPManagerhandler *MCPOAuthHandler++ mu sync.Mutex+ tokenForms []url.Values+ // tokenReply, when set, answers token requests instead of a fixed token.+ tokenReply func(w http.ResponseWriter)}func newMCPOAuthTestEnv(t *testing.T) *mcpOAuthTestEnv {@@ -111,8 +118,18 @@ func newMCPOAuthTestEnv(t *testing.T) *mcpOAuthTestEnv {"token_endpoint": serverURL + "/token",})})- mux.HandleFunc("/token", func(w http.ResponseWriter, _ *http.Request) {+ env := &mcpOAuthTestEnv{}+ mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")+ _ = r.ParseForm()+ env.mu.Lock()+ env.tokenForms = append(env.tokenForms, r.PostForm)+ reply := env.tokenReply+ env.mu.Unlock()+ if reply != nil {+ reply(w)+ return+ }_ = json.NewEncoder(w).Encode(map[string]any{"access_token": "access-new","token_type": "Bearer",@@ -145,13 +162,25 @@ func newMCPOAuthTestEnv(t *testing.T) *mcpOAuthTestEnv {oauth := mcp.NewOAuthManager(repo, mcpOAuthTestServiceRepo{service: service}, nil)manager := mcp.NewMCPManager(repo)t.Cleanup(manager.Shutdown)- return &mcpOAuthTestEnv{- service: service,- repo: repo,- oauth: oauth,- manager: manager,- handler: NewMCPOAuthHandler(oauth, manager, nil, nil),+ env.service = service+ env.repo = repo+ env.oauth = oauth+ env.manager = manager+ env.handler = NewMCPOAuthHandler(oauth, manager, mcpOAuthTestServices{service: service}, nil)+ return env+}++// mcpOAuthTestServices serves the environment's single MCP service.+type mcpOAuthTestServices struct {+ interfaces.MCPServiceService+ service *types.MCPService+}++func (s mcpOAuthTestServices) GetMCPServiceByID(_ context.Context, _ uint64, id string) (*types.MCPService, error) {+ if s.service.ID == id {+ return s.service, nil}+ return nil, nil}func (e *mcpOAuthTestEnv) registerClient(t *testing.T, clientID string) {@@ -254,3 +283,142 @@ func TestMCPOAuthRevokeRecyclesOnlyTheRevokingUsersConnection(t *testing.T) {require.False(t, aliceConn.IsConnected())require.True(t, bobConn.IsConnected())}++// postAssertion calls AssertionGrant as principal with the given JSON body.+func (e *mcpOAuthTestEnv) postAssertion(+ t *testing.T, principal types.Principal, serviceID, body string,+) *httptest.ResponseRecorder {+ t.Helper()+ w := httptest.NewRecorder()+ c, engine := gin.CreateTestContext(w)+ engine.Use(middleware.ErrorHandler())+ engine.POST("/mcp-services/:id/oauth/assertion", func(c *gin.Context) {+ c.Request = c.Request.WithContext(types.WithPrincipal(c.Request.Context(), principal))+ c.Set(types.TenantIDContextKey.String(), mcpOAuthTestTenant)+ e.handler.AssertionGrant(c)+ })+ c.Request = httptest.NewRequest(+ http.MethodPost, "/mcp-services/"+serviceID+"/oauth/assertion", strings.NewReader(body),+ )+ c.Request.Header.Set("Content-Type", "application/json")+ engine.HandleContext(c)+ return w+}++func TestMCPOAuthAssertionGrantStoresTheTokenAndRecyclesTheUsersConnection(t *testing.T) {+ env := newMCPOAuthTestEnv(t)+ env.registerClient(t, "client-1")+ alice := types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:alice"}+ bob := types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:bob"}+ aliceConn, bobConn := env.connect(t, alice), env.connect(t, bob)++ w := env.postAssertion(t, alice, env.service.ID, `{"assertion":"signed.jwt.value"}`)++ require.Equal(t, http.StatusOK, w.Code, w.Body.String())+ var body struct {+ Data mcp.OAuthAuthorizationStatus `json:"data"`+ }+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))+ require.True(t, body.Data.Authorized)+ require.NotNil(t, body.Data.ExpiresAt)+ require.Len(t, env.tokenForms, 1)+ require.Equal(t, "urn:ietf:params:oauth:grant-type:jwt-bearer", env.tokenForms[0].Get("grant_type"))+ require.Equal(t, "signed.jwt.value", env.tokenForms[0].Get("assertion"))+ require.Equal(t, "client-1", env.tokenForms[0].Get("client_id"))+ token, err := env.repo.GetTokenForPrincipal(context.Background(), mcpOAuthTestTenant, alice, env.service.ID)+ require.NoError(t, err)+ require.Equal(t, "access-new", token.AccessToken)+ require.False(t, aliceConn.IsConnected())+ require.True(t, bobConn.IsConnected(), "another user's connection and its in-flight calls are left alone")+}++func TestMCPOAuthAssertionGrantReportsARejectedAssertion(t *testing.T) {+ env := newMCPOAuthTestEnv(t)+ env.registerClient(t, "client-1")+ env.tokenReply = func(w http.ResponseWriter) {+ w.WriteHeader(http.StatusBadRequest)+ _ = json.NewEncoder(w).Encode(map[string]any{"error": "invalid_grant"})+ }+ alice := types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:alice"}++ w := env.postAssertion(t, alice, env.service.ID, `{"assertion":"signed.jwt.value"}`)++ require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String())+ require.Contains(t, w.Body.String(), "invalid_grant")+ require.NotContains(t, w.Body.String(), "signed.jwt.value")+ token, err := env.repo.GetTokenForPrincipal(context.Background(), mcpOAuthTestTenant, alice, env.service.ID)+ require.NoError(t, err)+ require.Nil(t, token)+}++func TestMCPOAuthAssertionGrantReportsATemporaryFailure(t *testing.T) {+ env := newMCPOAuthTestEnv(t)+ env.registerClient(t, "client-1")+ env.tokenReply = func(w http.ResponseWriter) {+ w.WriteHeader(http.StatusServiceUnavailable)+ _ = json.NewEncoder(w).Encode(map[string]any{"error": "temporarily_unavailable"})+ }+ alice := types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:alice"}++ w := env.postAssertion(t, alice, env.service.ID, `{"assertion":"signed.jwt.value"}`)++ require.Equal(t, http.StatusInternalServerError, w.Code, w.Body.String())+}++func TestMCPOAuthAssertionGrantValidatesTheRequest(t *testing.T) {+ alice := types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:alice"}+ cases := []struct {+ name string+ principal types.Principal+ serviceID string+ body string+ oauth bool+ client bool+ status int+ }{+ {"no principal", types.Principal{}, "svc-1", `{"assertion":"a.b.c"}`, true, true, http.StatusUnauthorized},+ {"empty assertion", alice, "svc-1", `{"assertion":" "}`, true, true, http.StatusBadRequest},+ {"malformed body", alice, "svc-1", `{"assertion":`, true, true, http.StatusBadRequest},+ {+ "body over the limit", alice, "svc-1",+ `{"assertion":"` + strings.Repeat("a", mcpOAuthAssertionMaxBytes) + `"}`, true, true, http.StatusBadRequest,+ },+ {"unknown service", alice, "svc-x", `{"assertion":"a.b.c"}`, true, true, http.StatusNotFound},+ {"service without OAuth", alice, "svc-1", `{"assertion":"a.b.c"}`, false, true, http.StatusBadRequest},+ {"no registered client", alice, "svc-1", `{"assertion":"a.b.c"}`, true, false, http.StatusBadRequest},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ env := newMCPOAuthTestEnv(t)+ if tc.client {+ env.registerClient(t, "client-1")+ }+ if !tc.oauth {+ env.service.AuthConfig.AuthType = types.MCPAuthAPIKey+ }++ w := env.postAssertion(t, tc.principal, tc.serviceID, tc.body)++ require.Equal(t, tc.status, w.Code, w.Body.String())+ require.Empty(t, env.tokenForms, "an invalid request never reaches the authorization server")+ })+ }+}++// With a pre-registered client the authorization server needs no+// registration endpoint (this one has none), and an authorization recycles+// only the authorizing user's connection: a pre-registered client is never a+// replaced registration, even though no registration is stored.+func TestMCPOAuthCallbackWithAPreRegisteredClientRecyclesOnlyTheAuthorizingUsersConnection(t *testing.T) {+ env := newMCPOAuthTestEnv(t)+ env.service.AuthConfig.ClientID = "pre-registered"+ alice := types.Principal{Type: types.PrincipalWebUser, ID: "alice"}+ bob := types.Principal{Type: types.PrincipalWebUser, ID: "bob"}+ aliceConn, bobConn := env.connect(t, alice), env.connect(t, bob)++ env.authorize(t, alice)++ require.Equal(t, "pre-registered", env.tokenForms[len(env.tokenForms)-1].Get("client_id"))+ require.False(t, aliceConn.IsConnected())+ require.True(t, bobConn.IsConnected())+}diff --git a/internal/handler/mcp_service.go b/internal/handler/mcp_service.goindex f7aa0a422..d742d0d76 100644--- a/internal/handler/mcp_service.go+++ b/internal/handler/mcp_service.go@@ -376,8 +376,8 @@ func (h *MCPServiceHandler) UpdateMCPService(c *gin.Context) {}if authConfig, ok := updateData["auth_config"].(map[string]interface{}); ok {service.AuthConfig = &types.MCPAuthConfig{}- // Secret fields (api_key, token) are intentionally NOT read from the- // main PUT body — they live behind the /credentials subresource so+ // Secret fields (api_key, token, client_secret) are intentionally NOT+ // read from the main PUT body — they live behind the /credentials subresource so// editing unrelated config (timeout, enabled, etc.) cannot// accidentally clobber a stored credential. Log a warning when a// client still tries to send them so we can spot stale callers.@@ -427,6 +427,12 @@ func (h *MCPServiceHandler) UpdateMCPService(c *gin.Context) {if metaURL, ok := authConfig["auth_server_metadata_url"].(string); ok {service.AuthConfig.AuthServerMetadataURL = metaURL}+ // client_id is non-secret; present-and-empty returns the service to+ // dynamic client registration. Its secret goes through /credentials.+ if clientID, ok := authConfig["client_id"].(string); ok {+ service.AuthConfig.ClientID = strings.TrimSpace(clientID)+ updateFields["client_id"] = true+ }}if advancedConfig, ok := updateData["advanced_config"].(map[string]interface{}); ok {service.AdvancedConfig = &types.MCPAdvancedConfig{}diff --git a/internal/handler/mcp_service_client_id_test.go b/internal/handler/mcp_service_client_id_test.gonew file mode 100644index 000000000..26baf0ddf--- /dev/null+++ b/internal/handler/mcp_service_client_id_test.go@@ -0,0 +1,71 @@+package handler++import (+ "context"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+ "github.com/gin-gonic/gin"+ "github.com/stretchr/testify/require"+)++// updateCapturingMCPServices records what UpdateMCPService is asked to merge.+type updateCapturingMCPServices struct {+ interfaces.MCPServiceService+ service *types.MCPService+ fields map[string]bool+}++func (s *updateCapturingMCPServices) UpdateMCPService(+ _ context.Context, service *types.MCPService, fields map[string]bool,+) error {+ s.service, s.fields = service, fields+ return nil+}++func (s *updateCapturingMCPServices) GetMCPServiceByID(context.Context, uint64, string) (*types.MCPService, error) {+ return &types.MCPService{ID: "svc-1"}, nil+}++func (s *updateCapturingMCPServices) ListMCPMetadataSummaries(+ context.Context, uint64, []*types.MCPService,+) (map[string]*types.MCPMetadataSummary, error) {+ return nil, nil+}++func putMCPService(t *testing.T, body string) *updateCapturingMCPServices {+ t.Helper()+ gin.SetMode(gin.TestMode)+ svc := &updateCapturingMCPServices{}+ h := &MCPServiceHandler{mcpServiceService: svc}+ w := httptest.NewRecorder()+ c, _ := gin.CreateTestContext(w)+ c.Request = httptest.NewRequest(http.MethodPut, "/mcp-services/svc-1", strings.NewReader(body))+ c.Request.Header.Set("Content-Type", "application/json")+ c.Params = gin.Params{{Key: "id", Value: "svc-1"}}+ c.Set(types.TenantIDContextKey.String(), uint64(7))+ h.UpdateMCPService(c)+ require.Equal(t, http.StatusOK, w.Code, w.Body.String())+ return svc+}++func TestUpdateMCPServiceSendsClientIDOnlyWhenTheBodyHasIt(t *testing.T) {+ svc := putMCPService(t, `{"auth_config":{"auth_type":"oauth","client_id":" pre-registered "}}`)+ require.True(t, svc.fields["client_id"])+ require.Equal(t, "pre-registered", svc.service.AuthConfig.ClientID)++ svc = putMCPService(t, `{"auth_config":{"auth_type":"oauth","client_id":""}}`)+ require.True(t, svc.fields["client_id"], "an empty client_id clears it")++ svc = putMCPService(t, `{"auth_config":{"auth_type":"oauth"}}`)+ require.False(t, svc.fields["client_id"], "an absent client_id is kept")+}++func TestUpdateMCPServiceNeverTakesTheClientSecretFromTheMainBody(t *testing.T) {+ svc := putMCPService(t, `{"auth_config":{"auth_type":"oauth","client_secret":"from-main-body"}}`)+ require.Empty(t, svc.service.AuthConfig.ClientSecret)+}diff --git a/internal/mcp/client.go b/internal/mcp/client.goindex a01cdc2a7..b3c548b00 100644--- a/internal/mcp/client.go+++ b/internal/mcp/client.go@@ -316,9 +316,10 @@ func discoverProbeTimeout(service *types.MCPService) time.Duration {}// buildOAuthConfig returns the OAuth configuration for an OAuth-enabled MCP-// service, or (_, false, nil) when the service does not use OAuth. It loads-// the dynamically-registered client_id and wires a per-user token store so-// the transport injects the invoking user's bearer token and refreshes it.+// service, or (_, false, nil) when the service does not use OAuth. It uses the+// pre-registered client or loads the dynamically-registered client_id, and+// wires a per-user token store so the transport injects the invoking user's+// bearer token and refreshes it.func buildOAuthConfig(config *ClientConfig, httpClient *http.Client) (transport.OAuthConfig, bool, error) {svc := config.Serviceif !svc.AuthConfig.IsOAuth() {@@ -343,7 +344,11 @@ func buildOAuthConfig(config *ClientConfig, httpClient *http.Client) (transport.AuthServerMetadataURL: svc.AuthConfig.AuthServerMetadataURL,HTTPClient: httpClient,}- if regClient, err := config.OAuthRepo.GetClient(context.Background(), config.TenantID, svc.ID); err == nil && regClient != nil {+ if clientID, clientSecret, ok := preRegisteredClient(svc); ok {+ oauthCfg.ClientID, oauthCfg.ClientSecret = clientID, clientSecret+ } else if regClient, err := config.OAuthRepo.GetClient(+ context.Background(), config.TenantID, svc.ID,+ ); err == nil && regClient != nil {oauthCfg.ClientID = regClient.ClientIDoauthCfg.ClientSecret = regClient.ClientSecretoauthCfg.RedirectURI = regClient.RedirectURI@@ -919,12 +924,18 @@ func (c *mcpGoClient) IsConnected() bool {return c.connected.Load()}-// oauthClientRegistration reports the tenant and OAuth client ID the-// connection was built with; ok is false for a connection without OAuth.+// oauthClientRegistration reports the tenant and dynamically registered OAuth+// client ID the connection was built with; ok is false for a connection+// without OAuth or with a pre-registered client. A pre-registered client is+// service configuration, and changing it closes every connection of the+// service, so such a connection never holds a replaced registration.func (c *mcpGoClient) oauthClientRegistration() (tenantID uint64, clientID string, ok bool) {if c.oauth == nil {return 0, "", false}+ if _, _, preRegistered := preRegisteredClient(c.service); preRegistered {+ return 0, "", false+ }return c.oauth.tenantID, c.oauth.clientID, true}diff --git a/internal/mcp/oauth_assertion.go b/internal/mcp/oauth_assertion.gonew file mode 100644index 000000000..39e710599--- /dev/null+++ b/internal/mcp/oauth_assertion.go@@ -0,0 +1,173 @@+package mcp++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "strings"+ "time"++ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/mark3labs/mcp-go/client/transport"+)++// jwtBearerGrantType is the JWT bearer authorization grant (RFC 7523 section+// 2.1). MCP's Enterprise-Managed Authorization extension sends an Identity+// Assertion JWT Authorization Grant (ID-JAG) with it.+const jwtBearerGrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"++// oauthAssertionTimeout bounds the token request and storing its result. It+// is detached from the caller: once the authorization server has issued a+// token for an assertion that can only be used once, a caller that went away+// must not leave it unsaved.+const oauthAssertionTimeout = 60 * time.Second++// maxTokenResponseBytes caps the token endpoint response that is read.+const maxTokenResponseBytes = 1 << 20++// ErrOAuthClientNotRegistered is returned when the service has no OAuth client+// to send the assertion grant with: neither a pre-registered one nor a stored+// registration. The grant does not register one: dynamic client registration+// describes a redirect-based client, which is not what a server-to-server+// grant needs.+var ErrOAuthClientNotRegistered = errors.New("no OAuth client is registered for this MCP service")++// OAuthGrantRejectedError reports that the authorization server refused the+// grant: a 4xx response other than 408 and 429, or a 2xx response carrying an+// OAuth error. Sending the same request again does not help; the assertion or+// the client has to change.+type OAuthGrantRejectedError struct {+ StatusCode int+ Code string+}++func (e *OAuthGrantRejectedError) Error() string {+ if e.Code == "" {+ return fmt.Sprintf("authorization server rejected the assertion with status %d", e.StatusCode)+ }+ return fmt.Sprintf("authorization server rejected the assertion: %s", e.Code)+}++// AuthorizeWithAssertion obtains principal's token for service with the JWT+// bearer grant and stores it the way an authorization code callback does.+//+// It serves deployments where an application in front of WeKnora signs the+// user in and calls WeKnora for that user, so no browser can follow an+// authorization redirect. That application presents an assertion of the+// user's identity; WeKnora forwards it unread, because validating it is up to+// the authorization server. The grant is sent with the service's+// pre-registered client, or else the client already registered for it.+func (m *OAuthManager) AuthorizeWithAssertion(+ ctx context.Context,+ service *types.MCPService,+ tenantID uint64,+ principal types.Principal,+ assertion string,+) error {+ if !service.AuthConfig.IsOAuth() {+ return fmt.Errorf("MCP service %s does not use OAuth", service.ID)+ }+ principal = principal.Normalize()+ if !principal.Valid() {+ return fmt.Errorf("principal context is required to authorize OAuth MCP service %s", service.ID)+ }+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), oauthAssertionTimeout)+ defer cancel()++ if _, _, preRegistered := preRegisteredClient(service); !preRegistered {+ existing, err := m.repo.GetClient(ctx, tenantID, service.ID)+ if err != nil {+ return fmt.Errorf("failed to read MCP OAuth client registration: %w", err)+ }+ if existing == nil {+ return ErrOAuthClientNotRegistered+ }+ }+ h, err := m.newHandler(ctx, service, tenantID, principal, "")+ if err != nil {+ return err+ }+ metadata, err := h.GetServerMetadata(ctx)+ if err != nil {+ return fmt.Errorf("failed to get authorization server metadata: %w", err)+ }+ if metadata.TokenEndpoint == "" {+ return fmt.Errorf("authorization server metadata has no token_endpoint")+ }++ form := url.Values{}+ form.Set("grant_type", jwtBearerGrantType)+ form.Set("assertion", assertion)+ form.Set("client_id", h.GetClientID())+ if secret := h.GetClientSecret(); secret != "" {+ form.Set("client_secret", secret)+ }+ if len(service.AuthConfig.Scopes) > 0 {+ form.Set("scope", strings.Join(service.AuthConfig.Scopes, " "))+ }+ token, err := requestToken(ctx, newOAuthHTTPClient(), metadata.TokenEndpoint, form)+ if err != nil {+ return err+ }+ if err := newDBTokenStore(m.repo, tenantID, principal, service.ID).SaveToken(ctx, token); err != nil {+ return fmt.Errorf("failed to save MCP OAuth token: %w", err)+ }+ logger.GetLogger(ctx).Infof(+ "MCP OAuth authorized with assertion: service=%s principal=%s", service.ID, principal.StorageID(),+ )+ return nil+}++// requestToken posts a token request and reads the token response. A 5xx,+// 408 or 429 response is a temporary failure whatever its body says; another+// 4xx response, or a 2xx response whose body has an OAuth error, is an+// OAuthGrantRejectedError.+// Response bodies are not copied into errors, which callers may return to+// their own clients.+func requestToken(+ ctx context.Context, client *http.Client, endpoint string, form url.Values,+) (*transport.Token, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode()))+ if err != nil {+ return nil, fmt.Errorf("failed to create token request: %w", err)+ }+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")+ req.Header.Set("Accept", "application/json")+ resp, err := client.Do(req)+ if err != nil {+ return nil, fmt.Errorf("failed to send token request: %w", err)+ }+ defer func() { _ = resp.Body.Close() }()+ body, err := io.ReadAll(io.LimitReader(resp.Body, maxTokenResponseBytes))+ if err != nil {+ return nil, fmt.Errorf("failed to read token response: %w", err)+ }++ if resp.StatusCode >= http.StatusInternalServerError ||+ resp.StatusCode == http.StatusRequestTimeout || resp.StatusCode == http.StatusTooManyRequests {+ return nil, fmt.Errorf("token endpoint returned status %d", resp.StatusCode)+ }+ var oauthErr transport.OAuthError+ _ = json.Unmarshal(body, &oauthErr)+ if resp.StatusCode >= http.StatusBadRequest ||+ (resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices && oauthErr.ErrorCode != "") {+ return nil, &OAuthGrantRejectedError{StatusCode: resp.StatusCode, Code: oauthErr.ErrorCode}+ }+ if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {+ return nil, fmt.Errorf("token endpoint returned status %d", resp.StatusCode)+ }++ var token transport.Token+ if err := json.Unmarshal(body, &token); err != nil {+ return nil, fmt.Errorf("failed to decode token response: %w", err)+ }+ if token.ExpiresIn > 0 {+ token.ExpiresAt = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second)+ }+ return &token, nil+}diff --git a/internal/mcp/oauth_assertion_test.go b/internal/mcp/oauth_assertion_test.gonew file mode 100644index 000000000..93408ce64--- /dev/null+++ b/internal/mcp/oauth_assertion_test.go@@ -0,0 +1,274 @@+package mcp++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "net/url"+ "sync"+ "testing"+ "time"++ "github.com/Tencent/WeKnora/internal/types"+ secutils "github.com/Tencent/WeKnora/internal/utils"+ "github.com/stretchr/testify/require"+)++// assertionTestServer is an authorization server that records the requests it+// receives and answers token requests with reply.+type assertionTestServer struct {+ *httptest.Server+ mu sync.Mutex+ registrations int+ tokenForms []url.Values+ reply func(w http.ResponseWriter)+}++func newAssertionTestServer(t *testing.T) *assertionTestServer {+ t.Helper()+ t.Setenv("SSRF_WHITELIST", "127.0.0.1")+ secutils.ResetSSRFWhitelistForTest()+ t.Cleanup(secutils.ResetSSRFWhitelistForTest)++ s := &assertionTestServer{reply: func(w http.ResponseWriter) {+ _ = json.NewEncoder(w).Encode(map[string]any{+ "access_token": "issued-access", "token_type": "Bearer", "expires_in": 3600,+ })+ }}+ s.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch r.URL.Path {+ case "/.well-known/oauth-authorization-server":+ _ = json.NewEncoder(w).Encode(map[string]any{+ "issuer": s.URL,+ "authorization_endpoint": s.URL + "/authorize",+ "token_endpoint": s.URL + "/token",+ "registration_endpoint": s.URL + "/register",+ })+ case "/register":+ s.mu.Lock()+ s.registrations+++ s.mu.Unlock()+ w.WriteHeader(http.StatusCreated)+ _ = json.NewEncoder(w).Encode(map[string]any{"client_id": "registered-client"})+ case "/token":+ _ = r.ParseForm()+ s.mu.Lock()+ s.tokenForms = append(s.tokenForms, r.PostForm)+ reply := s.reply+ s.mu.Unlock()+ reply(w)+ default:+ w.WriteHeader(http.StatusNotFound)+ }+ }))+ t.Cleanup(s.Close)+ return s+}++func (s *assertionTestServer) service(scopes ...string) *types.MCPService {+ serviceURL := s.URL + "/mcp"+ return &types.MCPService{+ ID: "svc-1",+ TenantID: 7,+ TransportType: types.MCPTransportHTTPStreamable,+ URL: &serviceURL,+ AuthConfig: &types.MCPAuthConfig{+ AuthType: types.MCPAuthOAuth,+ Scopes: scopes,+ AuthServerMetadataURL: s.URL + "/.well-known/oauth-authorization-server",+ },+ }+}++func (s *assertionTestServer) lastTokenForm(t *testing.T) url.Values {+ t.Helper()+ s.mu.Lock()+ defer s.mu.Unlock()+ require.NotEmpty(t, s.tokenForms)+ return s.tokenForms[len(s.tokenForms)-1]+}++var assertionTestPrincipal = types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:user-1"}++func TestAuthorizeWithAssertionSendsAJWTBearerGrantAndStoresTheToken(t *testing.T) {+ server := newAssertionTestServer(t)+ service := server.service("tools.read", "tools.call")+ repo := newFakeOAuthRepo()+ require.NoError(t, repo.SaveClient(context.Background(), &types.MCPOAuthClient{+ TenantID: 7, ServiceID: service.ID, ClientID: "known-client", ClientSecret: "known-secret",+ }))+ manager := NewOAuthManager(repo, fakeMCPServiceRepo{service: service}, nil)++ before := time.Now()+ err := manager.AuthorizeWithAssertion(+ context.Background(), service, 7, assertionTestPrincipal, "signed.jwt.value",+ )+ require.NoError(t, err)++ form := server.lastTokenForm(t)+ require.Equal(t, "urn:ietf:params:oauth:grant-type:jwt-bearer", form.Get("grant_type"))+ require.Equal(t, "signed.jwt.value", form.Get("assertion"))+ require.Equal(t, "known-client", form.Get("client_id"))+ require.Equal(t, "known-secret", form.Get("client_secret"))+ require.Equal(t, "tools.read tools.call", form.Get("scope"))+ require.NotContains(t, form, "resource", "the assertion names the resource")+ require.Zero(t, server.registrations, "a stored client is reused")++ token, err := repo.GetTokenForPrincipal(context.Background(), 7, assertionTestPrincipal, service.ID)+ require.NoError(t, err)+ require.NotNil(t, token)+ require.Equal(t, "issued-access", token.AccessToken)+ require.WithinDuration(t, before.Add(time.Hour), token.ExpiresAt, time.Minute)++ status, err := manager.AuthorizationStatus(context.Background(), 7, assertionTestPrincipal, service.ID)+ require.NoError(t, err)+ require.True(t, status.Authorized)+}++func TestAuthorizeWithAssertionOmitsOptionalFields(t *testing.T) {+ server := newAssertionTestServer(t)+ service := server.service()+ repo := newFakeOAuthRepo()+ require.NoError(t, repo.SaveClient(context.Background(), &types.MCPOAuthClient{+ TenantID: 7, ServiceID: service.ID, ClientID: "public-client",+ }))+ manager := NewOAuthManager(repo, fakeMCPServiceRepo{service: service}, nil)++ require.NoError(t, manager.AuthorizeWithAssertion(+ context.Background(), service, 7, assertionTestPrincipal, "signed.jwt.value",+ ))++ form := server.lastTokenForm(t)+ require.NotContains(t, form, "client_secret")+ require.NotContains(t, form, "scope")+}++// The grant is sent with a client the service already has. It does not run+// dynamic registration, so without one nothing reaches the server.+func TestAuthorizeWithAssertionNeedsARegisteredClient(t *testing.T) {+ server := newAssertionTestServer(t)+ service := server.service()+ repo := newFakeOAuthRepo()+ manager := NewOAuthManager(repo, fakeMCPServiceRepo{service: service}, nil)++ err := manager.AuthorizeWithAssertion(context.Background(), service, 7, assertionTestPrincipal, "signed.jwt.value")++ require.ErrorIs(t, err, ErrOAuthClientNotRegistered)+ require.Zero(t, server.registrations)+ require.Empty(t, server.tokenForms)+}++func TestAuthorizeWithAssertionClassifiesTokenEndpointFailures(t *testing.T) {+ cases := []struct {+ name string+ status int+ body map[string]any+ rejected bool+ rejectCode string+ }{+ {"invalid grant", http.StatusBadRequest, map[string]any{"error": "invalid_grant"}, true, "invalid_grant"},+ {"invalid client", http.StatusUnauthorized, map[string]any{"error": "invalid_client"}, true, "invalid_client"},+ {+ "grant not allowed for the client", http.StatusBadRequest,+ map[string]any{"error": "unauthorized_client"},+ true, "unauthorized_client",+ },+ {"error in a 200 body", http.StatusOK, map[string]any{"error": "invalid_grant"}, true, "invalid_grant"},+ {"4xx without an OAuth body", http.StatusForbidden, map[string]any{"message": "no"}, true, ""},+ {+ "5xx carrying an OAuth error", http.StatusServiceUnavailable,+ map[string]any{"error": "temporarily_unavailable"},+ false, "",+ },+ {"empty access token", http.StatusOK, map[string]any{"token_type": "Bearer"}, false, ""},+ {"rate limited", http.StatusTooManyRequests, map[string]any{"error": "slow_down"}, false, ""},+ {"request timeout", http.StatusRequestTimeout, map[string]any{}, false, ""},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ server := newAssertionTestServer(t)+ server.reply = func(w http.ResponseWriter) {+ w.WriteHeader(tc.status)+ _ = json.NewEncoder(w).Encode(tc.body)+ }+ service := server.service()+ repo := newFakeOAuthRepo()+ require.NoError(t, repo.SaveClient(context.Background(), &types.MCPOAuthClient{+ TenantID: 7, ServiceID: service.ID, ClientID: "known-client",+ }))+ manager := NewOAuthManager(repo, fakeMCPServiceRepo{service: service}, nil)++ err := manager.AuthorizeWithAssertion(+ context.Background(), service, 7, assertionTestPrincipal, "signed.jwt.value",+ )++ require.Error(t, err)+ var rejected *OAuthGrantRejectedError+ require.Equal(t, tc.rejected, errors.As(err, &rejected), err.Error())+ if tc.rejected {+ require.Equal(t, tc.rejectCode, rejected.Code)+ }+ require.NotContains(t, err.Error(), "signed.jwt.value")+ token, getErr := repo.GetTokenForPrincipal(context.Background(), 7, assertionTestPrincipal, service.ID)+ require.NoError(t, getErr)+ require.Nil(t, token, "a failed grant stores nothing")+ })+ }+}++// The token request is detached from the caller: an authorization server may+// accept an assertion only once, so a token it has issued is kept even when+// the caller has already gone away.+func TestAuthorizeWithAssertionOutlivesTheCaller(t *testing.T) {+ server := newAssertionTestServer(t)+ service := server.service()+ repo := newFakeOAuthRepo()+ require.NoError(t, repo.SaveClient(context.Background(), &types.MCPOAuthClient{+ TenantID: 7, ServiceID: service.ID, ClientID: "known-client",+ }))+ manager := NewOAuthManager(repo, fakeMCPServiceRepo{service: service}, nil)+ ctx, cancel := context.WithCancel(context.Background())+ cancel()++ require.NoError(t, manager.AuthorizeWithAssertion(ctx, service, 7, assertionTestPrincipal, "signed.jwt.value"))++ token, err := repo.GetTokenForPrincipal(context.Background(), 7, assertionTestPrincipal, service.ID)+ require.NoError(t, err)+ require.NotNil(t, token)+}++func TestAuthorizeWithAssertionKeepsPrincipalsApart(t *testing.T) {+ server := newAssertionTestServer(t)+ service := server.service()+ repo := newFakeOAuthRepo()+ require.NoError(t, repo.SaveClient(context.Background(), &types.MCPOAuthClient{+ TenantID: 7, ServiceID: service.ID, ClientID: "known-client",+ }))+ manager := NewOAuthManager(repo, fakeMCPServiceRepo{service: service}, nil)+ other := types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:user-2"}++ require.NoError(t, manager.AuthorizeWithAssertion(+ context.Background(), service, 7, assertionTestPrincipal, "signed.jwt.value",+ ))++ status, err := manager.AuthorizationStatus(context.Background(), 7, other, service.ID)+ require.NoError(t, err)+ require.False(t, status.Authorized)+}++func TestAuthorizeWithAssertionRequiresAnOAuthService(t *testing.T) {+ server := newAssertionTestServer(t)+ service := server.service()+ service.AuthConfig.AuthType = types.MCPAuthAPIKey+ manager := NewOAuthManager(newFakeOAuthRepo(), fakeMCPServiceRepo{service: service}, nil)++ err := manager.AuthorizeWithAssertion(+ context.Background(), service, 7, assertionTestPrincipal, "signed.jwt.value",+ )++ require.Error(t, err)+ require.Empty(t, server.tokenForms)+}diff --git a/internal/mcp/oauth_manager.go b/internal/mcp/oauth_manager.goindex fc3cd42c2..0cfb5d759 100644--- a/internal/mcp/oauth_manager.go+++ b/internal/mcp/oauth_manager.go@@ -3,6 +3,7 @@ package mcpimport ("context""fmt"+ "net/http""net/url""os""strings"@@ -59,18 +60,17 @@ func (m *OAuthManager) newHandler(if err := ValidateServiceOutboundURLs(service); err != nil {return nil, err}- httpCfg := secutils.DefaultSSRFSafeHTTPClientConfig()- httpCfg.SameOriginRedirectsOnly = true- httpCfg.Timeout = 30 * time.Secondcfg := transport.OAuthConfig{RedirectURI: redirectURI,Scopes: service.AuthConfig.Scopes,TokenStore: newDBTokenStore(m.repo, tenantID, principal, service.ID),PKCEEnabled: true,AuthServerMetadataURL: service.AuthConfig.AuthServerMetadataURL,- HTTPClient: secutils.NewSSRFSafeHTTPClient(httpCfg),+ HTTPClient: newOAuthHTTPClient(),}- if existing, err := m.repo.GetClient(ctx, tenantID, service.ID); err == nil && existing != nil {+ if clientID, clientSecret, ok := preRegisteredClient(service); ok {+ cfg.ClientID, cfg.ClientSecret = clientID, clientSecret+ } else if existing, err := m.repo.GetClient(ctx, tenantID, service.ID); err == nil && existing != nil {cfg.ClientID = existing.ClientIDcfg.ClientSecret = existing.ClientSecret}@@ -79,6 +79,26 @@ func (m *OAuthManager) newHandler(return h, nil}+// newOAuthHTTPClient builds the client for every request sent to an+// authorization server: addresses are checked against SSRF rules when dialing+// and only same-origin redirects are followed.+func newOAuthHTTPClient() *http.Client {+ httpCfg := secutils.DefaultSSRFSafeHTTPClientConfig()+ httpCfg.SameOriginRedirectsOnly = true+ httpCfg.Timeout = 30 * time.Second+ return secutils.NewSSRFSafeHTTPClient(httpCfg)+}++// preRegisteredClient returns the OAuth client an administrator registered+// with the authorization server in advance and set on the service. It takes+// the place of dynamic client registration.+func preRegisteredClient(service *types.MCPService) (clientID, clientSecret string, ok bool) {+ if service == nil || service.AuthConfig == nil || service.AuthConfig.ClientID == "" {+ return "", "", false+ }+ return service.AuthConfig.ClientID, service.AuthConfig.ClientSecret, true+}+// StartAuthorization performs discovery + (one-time) dynamic client// registration, then returns the authorization URL and an opaque attempt ID.// redirectURI is the backend callback URL registered with the auth server;@@ -108,9 +128,10 @@ func (m *OAuthManager) StartAuthorization(return "", "", err}- // Register a client dynamically if we don't have one yet for this service.+ // Register a client dynamically if the service has no pre-registered client+ // and we don't have one yet.existing, _ := m.repo.GetClient(ctx, tenantID, service.ID)- if existing == nil {+ if _, _, preRegistered := preRegisteredClient(service); !preRegistered && existing == nil {if err := h.RegisterClient(ctx, clientRegistrationName); err != nil {return "", "", fmt.Errorf("dynamic client registration failed: %w", err)}diff --git a/internal/mcp/oauth_preregistered_client_test.go b/internal/mcp/oauth_preregistered_client_test.gonew file mode 100644index 000000000..9f3a9fa7e--- /dev/null+++ b/internal/mcp/oauth_preregistered_client_test.go@@ -0,0 +1,115 @@+package mcp++import (+ "context"+ "net/url"+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/require"+)++func preRegisteredService(server *assertionTestServer) *types.MCPService {+ service := server.service()+ service.AuthConfig.ClientID = "pre-registered"+ service.AuthConfig.ClientSecret = "pre-registered-secret"+ return service+}++// A pre-registered client replaces dynamic registration in the+// authorization code flow: the authorization URL and the code exchange carry+// it, and nothing is registered or stored.+func TestAuthorizationCodeFlowUsesThePreRegisteredClient(t *testing.T) {+ server := newAssertionTestServer(t)+ service := preRegisteredService(server)+ repo := newFakeOAuthRepo()+ manager := NewOAuthManager(repo, fakeMCPServiceRepo{service: service}, nil)+ principal := types.Principal{Type: types.PrincipalWebUser, ID: "42"}++ authURL, state, err := manager.StartAuthorization(+ context.Background(), service, 7, principal, "http://localhost/callback", "/",+ )+ require.NoError(t, err)+ parsed, err := url.Parse(authURL)+ require.NoError(t, err)+ require.Equal(t, "pre-registered", parsed.Query().Get("client_id"))++ _, err = manager.CompleteAuthorization(context.Background(), state, "code")+ require.NoError(t, err)+ form := server.lastTokenForm(t)+ require.Equal(t, "authorization_code", form.Get("grant_type"))+ require.Equal(t, "pre-registered", form.Get("client_id"))+ require.Equal(t, "pre-registered-secret", form.Get("client_secret"))+ require.Zero(t, server.registrations)+ stored, err := repo.GetClient(context.Background(), 7, service.ID)+ require.NoError(t, err)+ require.Nil(t, stored, "a pre-registered client is not copied into the registration table")+}++// The pre-registered client wins over a registration stored earlier.+func TestAssertionGrantUsesThePreRegisteredClient(t *testing.T) {+ server := newAssertionTestServer(t)+ service := preRegisteredService(server)+ repo := newFakeOAuthRepo()+ require.NoError(t, repo.SaveClient(context.Background(), &types.MCPOAuthClient{+ TenantID: 7, ServiceID: service.ID, ClientID: "registered-earlier",+ }))+ manager := NewOAuthManager(repo, fakeMCPServiceRepo{service: service}, nil)++ require.NoError(t, manager.AuthorizeWithAssertion(+ context.Background(), service, 7, assertionTestPrincipal, "signed.jwt.value",+ ))++ form := server.lastTokenForm(t)+ require.Equal(t, "pre-registered", form.Get("client_id"))+ require.Equal(t, "pre-registered-secret", form.Get("client_secret"))+ require.Zero(t, server.registrations)+}++// A pre-registered client is enough: no registration has to be stored first.+func TestAssertionGrantWithAPreRegisteredClientNeedsNoStoredRegistration(t *testing.T) {+ server := newAssertionTestServer(t)+ service := preRegisteredService(server)+ manager := NewOAuthManager(newFakeOAuthRepo(), fakeMCPServiceRepo{service: service}, nil)++ require.NoError(t, manager.AuthorizeWithAssertion(+ context.Background(), service, 7, assertionTestPrincipal, "signed.jwt.value",+ ))+ require.Zero(t, server.registrations)+}++// Runtime connections, and so their token refreshes, use the pre-registered+// client too.+func TestRuntimeOAuthConfigPrefersThePreRegisteredClient(t *testing.T) {+ server := newAssertionTestServer(t)+ service := preRegisteredService(server)+ repo := newFakeOAuthRepo()+ require.NoError(t, repo.SaveClient(context.Background(), &types.MCPOAuthClient{+ TenantID: 7, ServiceID: service.ID, ClientID: "registered-earlier", ClientSecret: "old-secret",+ }))++ cfg, useOAuth, err := buildOAuthConfig(&ClientConfig{+ Service: service, TenantID: 7, Principal: assertionTestPrincipal, OAuthRepo: repo,+ }, nil)++ require.NoError(t, err)+ require.True(t, useOAuth)+ require.Equal(t, "pre-registered", cfg.ClientID)+ require.Equal(t, "pre-registered-secret", cfg.ClientSecret)+}++func TestRuntimeOAuthConfigFallsBackToTheStoredRegistration(t *testing.T) {+ server := newAssertionTestServer(t)+ service := server.service()+ repo := newFakeOAuthRepo()+ require.NoError(t, repo.SaveClient(context.Background(), &types.MCPOAuthClient{+ TenantID: 7, ServiceID: service.ID, ClientID: "registered-earlier",+ }))++ cfg, _, err := buildOAuthConfig(&ClientConfig{+ Service: service, TenantID: 7, Principal: assertionTestPrincipal, OAuthRepo: repo,+ }, nil)++ require.NoError(t, err)+ require.Equal(t, "registered-earlier", cfg.ClientID)+}diff --git a/internal/middleware/logger.go b/internal/middleware/logger.goindex a65ef0f98..ae870757d 100644--- a/internal/middleware/logger.go+++ b/internal/middleware/logger.go@@ -56,7 +56,7 @@ var sensitiveFieldRegex = regexp.MustCompile(`refresh[_-]?token|next[_-]?token|device[_-]?token|pending[_-]?token|pairing[_-]?link|` +`id[_-]?token|authorization|auth[_-]?token|api[_-]?key|` +`api[_-]?secret|secret[_-]?key|client[_-]?secret|private[_-]?key|secret|` +- `authorization[_-]?url|authorization[_-]?attempt)")\s*:\s*"[^"]*"`,+ `authorization[_-]?url|authorization[_-]?attempt|assertion)")\s*:\s*"[^"]*"`,)// sanitizeBody 清理敏感信息diff --git a/internal/middleware/logger_test.go b/internal/middleware/logger_test.goindex 79fe6d814..6ffe80a23 100644--- a/internal/middleware/logger_test.go+++ b/internal/middleware/logger_test.go@@ -68,6 +68,11 @@ func TestSanitizeBody(t *testing.T) {in: `{"apiKey" : "leak"}`,want: `{"apiKey":"***"}`,},+ {+ name: "MCP OAuth JWT bearer assertion",+ in: `{"assertion":"eyJhbGciOiJFUzI1NiJ9.payload.signature","redirect_uri":"https://example.com/cb"}`,+ want: `{"assertion":"***","redirect_uri":"https://example.com/cb"}`,+ },{name: "non sensitive fields untouched",in: `{"baseUrl":"https://example.com","modelName":"gpt"}`,diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.goindex 893229a8f..089e78579 100644--- a/internal/router/router_api_key_capabilities_test.go+++ b/internal/router/router_api_key_capabilities_test.go@@ -372,6 +372,7 @@ func TestTenantInfrastructureRoutesDeclareSpecificCapabilities(t *testing.T) {http.MethodPost, "/api/v1/mcp-services/:id/usage-instructions/generate",types.APIKeyCapabilityManageMCPServices,},+ {http.MethodPost, "/api/v1/mcp-services/:id/oauth/assertion", types.APIKeyCapabilityManageMCPServices},{http.MethodGet, "/api/v1/web-search-providers", types.APIKeyCapabilityManageWebSearch},{http.MethodGet, "/api/v1/vector-stores", types.APIKeyCapabilityManageVectorStores},{http.MethodGet, "/api/v1/storage-backends", types.APIKeyCapabilityManageStorageBackends},diff --git a/internal/router/routes_infra.go b/internal/router/routes_infra.goindex 36fd2a11f..898b41459 100644--- a/internal/router/routes_infra.go+++ b/internal/router/routes_infra.go@@ -182,10 +182,11 @@ func RegisterMCPServiceRoutes(// MCP tool human approval (issue #1173) — Viewer+ to read, Admin+ to set policymcpServices.GET("/:id/tool-approvals", g.Viewer(), handler.ListMCPToolApprovals)mcpServices.PUT("/:id/tool-approvals/:tool_name", g.Admin(), handler.SetMCPToolApproval)- // Per-user OAuth authorization flow. Viewer+ may authorize/inspect/- // revoke their own token; the callback is the separate public route- // registered above.+ // Per-user OAuth authorization. Viewer+ may authorize/inspect/revoke+ // their own token, through the browser flow (authorize-url and the+ // public callback registered above) or with an assertion.mcpServices.POST("/:id/oauth/authorize-url", g.Viewer(), oauthHandler.AuthorizeURL)+ mcpServices.POST("/:id/oauth/assertion", g.Viewer(), oauthHandler.AssertionGrant)mcpServices.GET("/:id/oauth/status", g.Viewer(), oauthHandler.Status)mcpServices.DELETE("/:id/oauth/token", g.Viewer(), oauthHandler.Revoke)}diff --git a/internal/types/interfaces/mcp_service.go b/internal/types/interfaces/mcp_service.goindex c108aa849..d63eaced9 100644--- a/internal/types/interfaces/mcp_service.go+++ b/internal/types/interfaces/mcp_service.go@@ -78,11 +78,12 @@ type MCPServiceService interface {// Implementations MUST close any active MCP client connection for this// service so the next upstream call reconnects with the new credential.UpdateMCPCredentials(- ctx context.Context, tenantID uint64, id string, apiKey *string, token *string,+ ctx context.Context, tenantID uint64, id string, apiKey, token, clientSecret *string,) (*types.MCPService, error)// ClearMCPCredential removes a single credential field. field must be- // "api_key" or "token"; other values must be rejected by the caller.+ // "api_key", "token" or "client_secret"; other values must be rejected by+ // the caller.// Implementations MUST close any active MCP client connection for this// service. Clearing a field that is already empty is a no-op (no error).ClearMCPCredential(ctx context.Context, tenantID uint64, id, field string) errordiff --git a/internal/types/mcp.go b/internal/types/mcp.goindex 67fdb61f2..9e17920df 100644--- a/internal/types/mcp.go+++ b/internal/types/mcp.go@@ -104,6 +104,15 @@ type MCPAuthConfig struct {// metadata URL. When empty, the server is discovered automatically from// the MCP URL (RFC 9728 / RFC 8414).AuthServerMetadataURL string `json:"auth_server_metadata_url,omitempty"`+ // 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.+ ClientID string `json:"client_id,omitempty"`+ // 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.+ ClientSecret string `json:"client_secret,omitempty"`}// IsOAuth reports whether this service uses the OAuth strategy.@@ -223,7 +232,7 @@ func (h *MCPHeaders) Scan(value interface{}) error {// Value implements driver.Valuer for MCPAuthConfig.//-// When SYSTEM_AES_KEY is configured, APIKey and Token are AES-256-GCM+// When SYSTEM_AES_KEY is configured, APIKey, Token and ClientSecret are AES-256-GCM// encrypted before serialization — mirroring the ModelParameters /// WebSearchProviderParameters pattern so MCP secrets are not the odd// resource stored in plaintext. Encryption operates on a local copy to@@ -245,6 +254,11 @@ func (c *MCPAuthConfig) Value() (driver.Value, error) {out.Token = encrypted}}+ if out.ClientSecret != "" {+ if encrypted, err := utils.EncryptAESGCM(out.ClientSecret, key); err == nil {+ out.ClientSecret = encrypted+ }+ }}return json.Marshal(&out)}@@ -278,6 +292,13 @@ func (c *MCPAuthConfig) Scan(value interface{}) error {log.Printf("[crypto] mcp auth_config token: decrypt failed (SYSTEM_AES_KEY missing/rotated?), treating as unconfigured")c.Token = ""}+ if plain, ok := utils.DecryptStoredSecretLenient(c.ClientSecret); ok {+ c.ClientSecret = plain+ } else {+ log.Printf("[crypto] mcp auth_config client_secret: decrypt failed " ++ "(SYSTEM_AES_KEY missing/rotated?), treating as unconfigured")+ c.ClientSecret = ""+ }return nil}diff --git a/internal/types/mcp_test.go b/internal/types/mcp_test.goindex 49b86368a..4da39d71b 100644--- a/internal/types/mcp_test.go+++ b/internal/types/mcp_test.go@@ -105,3 +105,19 @@ func TestMCPAuthConfig_Scan_MissingKeyDegradesGracefully(t *testing.T) {assert.Empty(t, scanned.Token, "encrypted token must blank out when key is missing")assert.Equal(t, "b", scanned.CustomHeaders["a"], "non-secret fields must still load")}++func TestMCPAuthConfig_ClientSecretIsEncryptedAndClientIDIsNot(t *testing.T) {+ withAESKey(t, testAESKey32)+ cfg := &MCPAuthConfig{AuthType: MCPAuthOAuth, ClientID: "pre-registered", ClientSecret: "client-secret-value"}+ v, err := cfg.Value()+ assert.NoError(t, err)+ raw := v.([]byte)+ assert.NotContains(t, string(raw), "client-secret-value")+ assert.Contains(t, string(raw), `"client_id":"pre-registered"`)+ assert.Equal(t, "client-secret-value", cfg.ClientSecret, "the caller's struct is not mutated")++ var back MCPAuthConfig+ assert.NoError(t, back.Scan(raw))+ assert.Equal(t, "pre-registered", back.ClientID)+ assert.Equal(t, "client-secret-value", back.ClientSecret)+}diff --git a/website-docs/03-features/08-mcp.md b/website-docs/03-features/08-mcp.mdindex a907aa6bd..c59a5862a 100644--- a/website-docs/03-features/08-mcp.md+++ b/website-docs/03-features/08-mcp.md@@ -2,7 +2,7 @@MCP 用于智能体与外部工具之间的连接。WeKnora 支持接入外部 MCP 服务,也提供独立 MCP Server 供其他客户端调用:-1. **WeKnora 作为 MCP 客户端**:在「工具箱 → MCP服务」中接入任意外部 MCP server(SSE / Streamable HTTP),其工具通过目录按需加载,供 Agent 在对话中调用。支持 API Key / Bearer / OAuth 2.0(含动态客户端注册与 PKCE)三种认证策略、按工具粒度的启停与人工审批,以及会话内(in-conversation)OAuth 授权。+1. **WeKnora 作为 MCP 客户端**:在「工具箱 → MCP服务」中接入任意外部 MCP server(SSE / Streamable HTTP),其工具通过目录按需加载,供 Agent 在对话中调用。支持 API Key / Bearer / OAuth 2.0(含动态客户端注册与 PKCE,也可填写预注册客户端;支持以 JWT Bearer 断言代用户获取 token)三种认证策略、按工具粒度的启停与人工审批,以及会话内(in-conversation)OAuth 授权。2. **WeKnora 作为 MCP Server**:在「设置 → 发布集成 → MCP Server」中为当前空间创建一个或多个 MCP 端点,每个端点有独立的令牌、知识库范围和工具清单,Claude Desktop、Cursor、Claude Code、VS Code Copilot 等 MCP 客户端通过 Streamable HTTP 直接连接,无需额外部署进程。仓库 `mcp-server/` 目录下的 Python 服务是旧方案,已标记弃用。接入外部服务可扩展 WeKnora 智能体的工具;运行 WeKnora MCP Server 可让外部客户端使用知识库检索、问答和管理能力。@@ -199,16 +199,17 @@ ClientInfo: mcp.Implementation{ Name: "WeKnora", Version: "1.0.0" }| POST | `/mcp-services` | Admin+ | 创建 MCP 服务(URL 经 SSRF 校验 `secutils.ValidateURLForSSRF`) || GET | `/mcp-services` | Viewer+ | 列出当前空间的 MCP 服务(含 builtin) || GET | `/mcp-services/{id}` | Viewer+ | 服务详情(经 DTO 脱敏) |-| PUT | `/mcp-services/{id}` | Admin+ | 更新服务;主 PUT **忽略** `auth_config.api_key` / `auth_config.token`(打 deprecated 警告) |+| PUT | `/mcp-services/{id}` | Admin+ | 更新服务;主 PUT **忽略** `auth_config.api_key` / `auth_config.token`(打 deprecated 警告)与 `auth_config.client_secret`;`auth_config.client_id` 可在此设置或以空字符串清除 || DELETE | `/mcp-services/{id}` | Admin+ | 删除服务(软删除,先 `CloseClient`) || POST | `/mcp-services/{id}/test` | Admin+ | 连接测试:临时客户端 Connect + Initialize,并尝试读取工具与资源列表;读取失败且服务端声明支持该能力时返回失败结果,否则记录警告并按空列表继续。返回 `MCPTestResult`(含 `oauth_required` 标记) || GET | `/mcp-services/{id}/tools` | Viewer+ | 拉取 MCP 服务的工具列表 || GET | `/mcp-services/{id}/resources` | Viewer+ | 拉取 MCP 服务的资源列表 |-| PUT | `/mcp-services/{id}/credentials` | Admin+ | 写入 `api_key` / `token` 凭据(见下) |-| DELETE | `/mcp-services/{id}/credentials/{field}` | Admin+ | 清除单个凭据字段(`api_key` 或 `token`),幂等,成功返回 204 |+| PUT | `/mcp-services/{id}/credentials` | Admin+ | 写入 `api_key` / `token` / `client_secret` 凭据(见下) |+| DELETE | `/mcp-services/{id}/credentials/{field}` | Admin+ | 清除单个凭据字段(`api_key`、`token` 或 `client_secret`),幂等,成功返回 204 || GET | `/mcp-services/{id}/tool-approvals` | Viewer+ | 列出该服务的工具审批策略 || PUT | `/mcp-services/{id}/tool-approvals/{tool_name}` | Admin+ | 更新工具启停/审批:`{"enabled":bool,"require_approval":bool}`,至少一项 || POST | `/mcp-services/{id}/oauth/authorize-url` | Viewer+ | 发起当前用户的 OAuth 授权,返回 `authorization_url` 与 `authorization_attempt` |+| POST | `/mcp-services/{id}/oauth/assertion` | Viewer+ | 以 JWT Bearer 授权(RFC 7523)提交调用方签发的断言,为当前用户获取 token,无需浏览器;使用服务已有的 OAuth 客户端 || GET | `/mcp-services/{id}/oauth/status` | Viewer+ | 查询授权状态;带 `authorization_attempt` 参数时只认可本次授权流程 || DELETE | `/mcp-services/{id}/oauth/token` | Viewer+ | 撤销当前用户对该服务的 token,并回收连接 || GET | `/mcp-oauth/callback` | **公开** | 授权服务器回调(单次使用的 `state` 参数即鉴权),注册在 `/mcp-services` 组之外避免与 `:id` 路由冲突 |@@ -220,7 +221,7 @@ embed 渠道另有对应的会话级路由(`/embed/sessions/{session_id}/mcp-o##### 凭据子资源(mcp_credentials.go)-密钥(`api_key` / `token`)**不走主 PUT**,而是走独立的 `/credentials` 子资源,`internal/handler/mcp_credentials.go` 的注释给出了三点理由:+密钥(`api_key` / `token` / 预注册客户端的 `client_secret`)**不走主 PUT**,而是走独立的 `/credentials` 子资源,`internal/handler/mcp_credentials.go` 的注释给出了三点理由:1. 主 PUT body 从不携带密钥——在契约层面消灭「掩码值回写覆盖真实密钥」这类 bug;2. 保存编辑弹窗(改 timeout / enabled 等)不可能误伤已配置的凭据;@@ -272,7 +273,7 @@ sequenceDiagram##### 流程要点(对应源码)-- **发现与动态注册**(`internal/mcp/oauth_manager.go`):`StartAuthorization` 先构造 `transport.OAuthHandler`(`AuthServerMetadataURL` 为空时由 mcp-go 依据 MCP URL 自动发现授权服务器);若 `mcp_oauth_clients` 表中该 `(tenant, service)` 尚无客户端,调用 `h.RegisterClient(ctx, "WeKnora")` 做一次性 RFC 7591 注册并 `SaveClient` 持久化,之后所有用户复用同一 client_id。+- **发现与动态注册**(`internal/mcp/oauth_manager.go`):`StartAuthorization` 先构造 `transport.OAuthHandler`(`AuthServerMetadataURL` 为空时由 mcp-go 依据 MCP URL 自动发现授权服务器);服务配置了预注册客户端(`auth_config.client_id`)时直接使用它,否则若 `mcp_oauth_clients` 表中该 `(tenant, service)` 尚无客户端,调用 `h.RegisterClient(ctx, "WeKnora")` 做一次性 RFC 7591 注册并 `SaveClient` 持久化,之后所有用户复用同一 client_id。- **PKCE**:`transport.GenerateCodeVerifier()` / `GenerateCodeChallenge()` / `GenerateState()`;`code_verifier` 是秘密,**只存服务端 state**(`internal/mcp/oauth_state.go` 注释明确禁止编码进 state 参数)。- **State 存储**(`oauth_state.go`):有 Redis 时写 `weknora:mcp_oauth_state:<state>`(支持 `WEKNORA_REDIS_NAMESPACE` 命名空间,回调可落在任意后端副本);Lite 模式退化为带 GC 的内存 map。TTL 固定 10 分钟;`Take` 为**取即删**的单次消费。另存一份不含秘密的 `OAuthAttempt` 记录,`CompleteAttempt` 仅在 token 成功落库后置 `Completed=true`——因此新弹窗的授权状态查询(`status?authorization_attempt=`)**绝不会被历史 token 误判为已完成**。- **回调**(`oauth_manager.go` 的 `CompleteAuthorization` + `internal/handler/mcp_oauth.go` 的 `Callback`):回调路由公开无鉴权,靠单次 state 认证;由于浏览器收到重定向后 Gin 请求 ctx 即取消,token 交换用 `context.WithoutCancel + 60s` 超时(`oauthCallbackTimeout`)脱离请求生命周期。交换成功后 `CloseClient(serviceID)` 回收可能携带旧注册信息的连接,最后把结果编码在 URL fragment(`#mcp_oauth_result=success` / `#mcp_oauth_error=...`)重定向回前端。diff --git a/website-docs/04-api/02-api-agent-mcp.md b/website-docs/04-api/02-api-agent-mcp.mdindex f825301df..9e536afe0 100644--- a/website-docs/04-api/02-api-agent-mcp.md+++ b/website-docs/04-api/02-api-agent-mcp.md@@ -131,11 +131,11 @@ curl "$BASE/api/v1/agents/agent-1/suggested-questions?limit=6" -H "X-API-Key: $A| `transport_type` | string | 是 | `sse` / `http-streamable`;`stdio` 出于安全原因被拒绝 || `url` | *string | 否 | 服务 URL(SSE/HTTP) || `headers` | map[string]string | 否 | HTTP 头 |-| `auth_config` | object | 否 | `auth_type`(`api_key/bearer/oauth`)、`api_key_header`、`custom_headers`、`scopes`、`auth_server_metadata_url`(密钥走 credentials 子资源) |+| `auth_config` | object | 否 | `auth_type`(`api_key/bearer/oauth`)、`api_key_header`、`custom_headers`、`scopes`、`auth_server_metadata_url`、`client_id`(OAuth 预注册客户端,留空则动态客户端注册;空字符串清除)(密钥与 `client_secret` 走 credentials 子资源,创建时可随请求体提交) || `advanced_config` | object | 否 | `{timeout,retry_count,retry_delay}`,默认 30 秒 / 3 次 / 1 秒;`timeout` 大于 60 秒时也会延长 Agent 单次调用该服务工具的等待窗口 || `stdio_config` / `env_vars` | object | 否 | 仅为兼容旧数据保留;stdio 已禁用,不生效 |-响应:200 `{"success":true,"data":{MCPServiceResponse}}`(含 `credentials:{api_key:{configured},token:{configured}}`;已同步工具目录的服务还带 `catalog:{tool_count,stale,synced_at}`)+响应:200 `{"success":true,"data":{MCPServiceResponse}}`(含 `credentials:{api_key:{configured},token:{configured},client_secret:{configured}}`;已同步工具目录的服务还带 `catalog:{tool_count,stale,synced_at}`)```bashcurl -X POST $BASE/api/v1/mcp-services -H "Authorization: Bearer $TOKEN" \@@ -242,9 +242,9 @@ curl $BASE/api/v1/mcp-services/mcp-1/resources -H "Authorization: Bearer $TOKEN"### PUT /api/v1/mcp-services/:id/credentials-用途:设置密钥(`api_key`/`token`,指针字段,省略保留)。权限:Admin+。Handler: `internal/handler/mcp_credentials.go`+用途:设置密钥(`api_key`/`token`/`client_secret`,指针字段,省略保留)。权限:Admin+。Handler: `internal/handler/mcp_credentials.go`-响应:200 `{"success":true,"data":{"fields":{"api_key":{"configured"},"token":{"configured"}}}}`+响应:200 `{"success":true,"data":{"fields":{"api_key":{"configured"},"token":{"configured"},"client_secret":{"configured"}}}}````bashcurl -X PUT $BASE/api/v1/mcp-services/mcp-1/credentials -H "Authorization: Bearer $TOKEN" \@@ -253,7 +253,7 @@ curl -X PUT $BASE/api/v1/mcp-services/mcp-1/credentials -H "Authorization: Beare### DELETE /api/v1/mcp-services/:id/credentials/:field-用途:删除凭证字段(`api_key` 或 `token`)。权限:Admin+。响应:204。+用途:删除凭证字段(`api_key`、`token` 或 `client_secret`)。权限:Admin+。响应:204。```bashcurl -X DELETE $BASE/api/v1/mcp-services/mcp-1/credentials/token -H "Authorization: Bearer $TOKEN"@@ -308,6 +308,21 @@ curl -X POST $BASE/api/v1/mcp-services/mcp-1/oauth/authorize-url -H "Authorizati-H 'Content-Type: application/json' -d '{"redirect_uri":"'$BASE'/api/v1/mcp-oauth/callback"}'```+### POST /api/v1/mcp-services/:id/oauth/assertion++用途:以 JWT Bearer 授权(RFC 7523)为本人获取 OAuth token,无需浏览器跳转。适用于 WeKnora 部署在其他应用之后、由该应用负责登录并代用户调用 WeKnora 的场景:该应用签发代表当前用户的断言(如 MCP Enterprise-Managed Authorization 使用的 ID-JAG),WeKnora 原样提交给授权服务器,由授权服务器校验。使用该服务已注册的 OAuth 客户端(不会进行动态客户端注册;尚无客户端时返回 400)。获得的 token 与授权回调保存的 token 相同,后续刷新、状态查询与吊销不变。权限:Viewer+。++| 字段 | 类型 | 必填 | 说明 |+| --- | --- | --- | --- |+| `assertion` | string | 是 | 提交给授权服务器的 JWT 断言(请求体上限 16 KiB) |++响应:200,`data` 与 `oauth/status` 相同。授权服务器拒绝断言(4xx,或 2xx 响应体含 OAuth `error`)时返回 400 并附 OAuth 错误码;授权服务器 5xx 或网络错误返回 500。++```bash+curl -X POST $BASE/api/v1/mcp-services/mcp-1/oauth/assertion -H "X-API-Key: $API_KEY" \+ -H "X-External-User-ID: user-1" -H 'Content-Type: application/json' -d '{"assertion":"'$ASSERTION'"}'+```+### GET /api/v1/mcp-services/:id/oauth/status用途:查询本人授权状态。权限:Viewer+。查询参数:`authorization_attempt`(可选)。