Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix: harden API principal config after review

wizardchen97bca74a3105
diff --git a/client/tenant.go b/client/tenant.go
index 266489ca0..878ce96c1 100644
--- a/client/tenant.go
+++ b/client/tenant.go
@@ -228,3 +228,67 @@ func (c *Client) UpdateTenantKV(ctx context.Context, key string, value any) (jso
}
return result.Data, nil
}
+
+// APIPrincipalMode controls how X-API-Key requests map to terminal principals.
+type APIPrincipalMode string
+
+const (
+ APIPrincipalModeTenant APIPrincipalMode = "tenant"
+ APIPrincipalModeDirect APIPrincipalMode = "direct_header"
+ APIPrincipalModeSignedToken APIPrincipalMode = "signed_token"
+)
+
+// APIPrincipalConfig describes tenant API-key principal mapping settings.
+type APIPrincipalConfig struct {
+ Mode APIPrincipalMode `json:"mode"`
+ DirectHeaderName string `json:"direct_header_name"`
+ SignedTokenHeaderName string `json:"signed_token_header_name"`
+ RequireDirectHeader bool `json:"require_direct_header"`
+ HasHMACSecret bool `json:"has_hmac_secret"`
+}
+
+type apiPrincipalConfigResponse struct {
+ Success bool `json:"success"`
+ Data APIPrincipalConfig `json:"data"`
+}
+
+// UpdateAPIPrincipalConfigRequest updates tenant API-key principal mapping.
+type UpdateAPIPrincipalConfigRequest struct {
+ Mode APIPrincipalMode `json:"mode"`
+ DirectHeaderName string `json:"direct_header_name,omitempty"`
+ SignedTokenHeaderName string `json:"signed_token_header_name,omitempty"`
+ RequireDirectHeader bool `json:"require_direct_header,omitempty"`
+ HMACSecret string `json:"hmac_secret,omitempty"`
+}
+
+// GetAPIPrincipalConfig returns how X-API-Key requests map to principals for a tenant.
+func (c *Client) GetAPIPrincipalConfig(ctx context.Context, tenantID uint64) (*APIPrincipalConfig, error) {
+ path := fmt.Sprintf("/api/v1/tenants/%d/api-principal-config", tenantID)
+ resp, err := c.doRequest(ctx, http.MethodGet, path, nil, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ var response apiPrincipalConfigResponse
+ if err := parseResponse(resp, &response); err != nil {
+ return nil, err
+ }
+ return &response.Data, nil
+}
+
+// UpdateAPIPrincipalConfig updates how X-API-Key requests map to principals for a tenant.
+func (c *Client) UpdateAPIPrincipalConfig(
+ ctx context.Context, tenantID uint64, req *UpdateAPIPrincipalConfigRequest,
+) (*APIPrincipalConfig, error) {
+ path := fmt.Sprintf("/api/v1/tenants/%d/api-principal-config", tenantID)
+ resp, err := c.doRequest(ctx, http.MethodPut, path, req, nil)
+ if err != nil {
+ return nil, err
+ }
+
+ var response apiPrincipalConfigResponse
+ if err := parseResponse(resp, &response); err != nil {
+ return nil, err
+ }
+ return &response.Data, nil
+}
diff --git a/docs/api/tenant.md b/docs/api/tenant.md
index 91e8ddadb..22d35d776 100644
--- a/docs/api/tenant.md
+++ b/docs/api/tenant.md
@@ -16,6 +16,8 @@
| PUT | `/tenants/:id` | 更新租户信息 |
| DELETE | `/tenants/:id` | 删除租户 |
| POST | `/tenants/:id/api-key` | 重置租户 API Key |
+| GET | `/tenants/:id/api-principal-config` | 获取 API Key 用户身份配置(Owner) |
+| PUT | `/tenants/:id/api-principal-config` | 更新 API Key 用户身份配置(Owner) |
| GET | `/tenants` | 获取当前用户可见的租户列表 |
| GET | `/tenants/kv/:key` | 获取当前租户的 KV 配置(tenant 由认证上下文确定) |
| PUT | `/tenants/kv/:key` | 更新当前租户的 KV 配置(tenant 由认证上下文确定) |
@@ -354,6 +356,73 @@ curl --location --request POST 'http://localhost:8080/api/v1/tenants/10000/api-k
}
```
+## GET `/tenants/:id/api-principal-config` - 获取 API Key 用户身份配置
+
+返回租户级 API Key 请求如何映射为终端 Principal 的配置。**需要 Owner 权限**。
+
+**响应字段**:
+
+| 字段 | 类型 | 说明 |
+| ---- | ---- | ---- |
+| mode | string | `tenant` / `direct_header` / `signed_token` |
+| direct_header_name | string | 直接传用户 ID 时的请求头名,默认 `X-External-User-ID` |
+| signed_token_header_name | string | 签名 token 模式请求头名,默认 `X-External-User-Token` |
+| require_direct_header | bool | `direct_header` 模式下是否强制要求用户 ID 请求头 |
+| has_hmac_secret | bool | 是否已配置 HMAC secret(不返回明文) |
+
+**请求**:
+
+```curl
+curl --location 'http://localhost:8080/api/v1/tenants/10000/api-principal-config' \
+--header 'Authorization: Bearer <token>'
+```
+
+**响应**:
+
+```json
+{
+ "success": true,
+ "data": {
+ "mode": "signed_token",
+ "direct_header_name": "X-External-User-ID",
+ "signed_token_header_name": "X-External-User-Token",
+ "require_direct_header": false,
+ "has_hmac_secret": true
+ }
+}
+```
+
+## PUT `/tenants/:id/api-principal-config` - 更新 API Key 用户身份配置
+
+更新 API Key 请求的 Principal 映射方式。**需要 Owner 权限**。
+
+**请求体**:
+
+| 字段 | 类型 | 说明 |
+| ---- | ---- | ---- |
+| mode | string | 必填,`tenant` / `direct_header` / `signed_token` |
+| direct_header_name | string | 可选 |
+| signed_token_header_name | string | 可选 |
+| require_direct_header | bool | 可选,`direct_header` 模式下缺 header 是否 401 |
+| hmac_secret | string | 可选,`signed_token` 模式 HMAC 密钥;省略则保留现有值 |
+
+`signed_token` 模式首次启用时必须提供 `hmac_secret`。
+
+外部用户 JWT 要求:HS256 签名、`aud=weknora`、包含 `sub` 与 `tenant_id`、有效期不超过 24 小时。
+
+**请求**:
+
+```curl
+curl --location --request PUT 'http://localhost:8080/api/v1/tenants/10000/api-principal-config' \
+--header 'Authorization: Bearer <token>' \
+--header 'Content-Type: application/json' \
+--data '{
+ "mode": "direct_header",
+ "direct_header_name": "X-External-User-ID",
+ "require_direct_header": true
+}'
+```
+
## GET `/tenants` - 获取租户列表
返回当前认证上下文对应的租户(普通用户为单条;管理员仍只返回自身租户)。
diff --git a/docs/docs.go b/docs/docs.go
index b728451ac..254275af9 100644
--- a/docs/docs.go
+++ b/docs/docs.go
@@ -19,6 +19,107 @@ const docTemplate = `{
"host": "{{.Host}}",
"basePath": "{{.BasePath}}",
"paths": {
+ "/agent/mcp-oauth-resolutions/{pending_id}": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "用户在对话中完成 OAuth 授权后调用,校验令牌存在后恢复被暂停的 Agent 工具调用",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP服务"
+ ],
+ "summary": "完成对话内 MCP OAuth 授权",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "待授权 ID",
+ "name": "pending_id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "{service_id: string}",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "Bad Request",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "409": {
+ "description": "用户尚未完成授权",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
+ "/agent/mcp-oauth-resolutions/{pending_id}/cancel": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "用户主动跳过 OAuth 授权,解除 Agent 阻塞",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP服务"
+ ],
+ "summary": "跳过对话内 MCP OAuth 授权",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "待授权 ID",
+ "name": "pending_id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
"/agent/tool-approvals/{pending_id}": {
"post": {
"security": [
@@ -11906,6 +12007,113 @@ const docTemplate = `{
}
}
},
+ "/tenants/{id}/api-principal-config": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "返回 X-API-Key 请求如何映射为终端 Principal 的配置(Owner)",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "租户管理"
+ ],
+ "summary": "获取租户 API Key 用户身份配置",
+ "parameters": [
+ {
+ "type": "integer",
+ "description": "租户ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "API principal 配置",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "请求参数错误",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "403": {
+ "description": "权限不足",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ },
+ "put": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "配置 X-API-Key 请求如何映射为终端 Principal(Owner)",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "租户管理"
+ ],
+ "summary": "更新租户 API Key 用户身份配置",
+ "parameters": [
+ {
+ "type": "integer",
+ "description": "租户ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "API principal 配置",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/internal_handler.apiPrincipalConfigRequest"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "更新后的配置",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "请求参数错误",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "403": {
+ "description": "权限不足",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
"/tenants/{id}/audit-log": {
"get": {
"security": [
@@ -13604,6 +13812,19 @@ const docTemplate = `{
}
}
},
+ "github_com_Tencent_WeKnora_internal_types.APIPrincipalMode": {
+ "type": "string",
+ "enum": [
+ "tenant",
+ "direct_header",
+ "signed_token"
+ ],
+ "x-enum-varnames": [
+ "APIPrincipalModeTenant",
+ "APIPrincipalModeDirect",
+ "APIPrincipalModeSignedToken"
+ ]
+ },
"github_com_Tencent_WeKnora_internal_types.ASRConfig": {
"type": "object",
"properties": {
@@ -15474,6 +15695,10 @@ const docTemplate = `{
"api_key": {
"type": "string"
},
+ "api_key_header": {
+ "description": "APIKeyHeader is the header name that carries APIKey when AuthType is\napi_key. Empty defaults to \"X-API-Key\". This is non-secret structural\nconfig (the secret is APIKey), so it is not encrypted and is safe to echo\nback in responses. It lets services that expect the key in a different\nheader (e.g. the raw token directly in \"Authorization\") work without\nresorting to plaintext custom headers.",
+ "type": "string"
+ },
"auth_server_metadata_url": {
"description": "AuthServerMetadataURL optionally pins the OAuth authorization server\nmetadata URL. When empty, the server is discovered automatically from\nthe MCP URL (RFC 9728 / RFC 8414).",
"type": "string"
@@ -15727,6 +15952,14 @@ const docTemplate = `{
"id": {
"type": "string"
},
+ "kb_id": {
+ "description": "Parent knowledge base for file/tag mentions",
+ "type": "string"
+ },
+ "kb_name": {
+ "description": "Display name for parent KB",
+ "type": "string"
+ },
"kb_type": {
"description": "\"document\" or \"faq\" (only for kb type)",
"type": "string"
@@ -15734,8 +15967,16 @@ const docTemplate = `{
"name": {
"type": "string"
},
+ "service_id": {
+ "description": "Parent MCP service for MCP tool mentions",
+ "type": "string"
+ },
+ "skill_name": {
+ "description": "Preloaded agent skill name",
+ "type": "string"
+ },
"type": {
- "description": "\"kb\" for knowledge base, \"file\" for file",
+ "description": "\"kb\", \"file\", \"tag\", \"mcp\", \"skill\"",
"type": "string"
}
}
@@ -16932,9 +17173,33 @@ const docTemplate = `{
"type": "string"
}
},
+ "mcp_service_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "mentioned_items": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MentionedItem"
+ }
+ },
"model_id": {
"type": "string"
},
+ "skill_names": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "tag_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
"web_search_enabled": {
"type": "boolean"
}
@@ -19632,6 +19897,26 @@ const docTemplate = `{
}
}
},
+ "internal_handler.apiPrincipalConfigRequest": {
+ "type": "object",
+ "properties": {
+ "direct_header_name": {
+ "type": "string"
+ },
+ "hmac_secret": {
+ "type": "string"
+ },
+ "mode": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.APIPrincipalMode"
+ },
+ "require_direct_header": {
+ "type": "boolean"
+ },
+ "signed_token_header_name": {
+ "type": "string"
+ }
+ }
+ },
"internal_handler.auditLogListResponse": {
"type": "object",
"properties": {
@@ -19891,6 +20176,13 @@ const docTemplate = `{
"type": "string"
}
},
+ "mcp_service_ids": {
+ "description": "Per-request MCP services selected via @mention",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
"mentioned_items": {
"description": "@mentioned knowledge bases and files",
"type": "array",
@@ -19902,10 +20194,24 @@ const docTemplate = `{
"description": "Query text for knowledge base search",
"type": "string"
},
+ "skill_names": {
+ "description": "Per-request Skills selected via @mention",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
"summary_model_id": {
"description": "Optional summary model ID for this request (overrides session default)",
"type": "string"
},
+ "tag_ids": {
+ "description": "@mentioned tag IDs (display/debug; scoped via MentionedItems)",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
"web_search_enabled": {
"description": "Whether web search is enabled for this request",
"type": "boolean"
@@ -19963,6 +20269,14 @@ const docTemplate = `{
"id": {
"type": "string"
},
+ "kb_id": {
+ "description": "Parent knowledge base for file/tag mentions",
+ "type": "string"
+ },
+ "kb_name": {
+ "description": "Display name for parent KB",
+ "type": "string"
+ },
"kb_type": {
"description": "\"document\" or \"faq\" (only for kb type)",
"type": "string"
@@ -19970,8 +20284,16 @@ const docTemplate = `{
"name": {
"type": "string"
},
+ "service_id": {
+ "description": "Parent MCP service for MCP tool mentions",
+ "type": "string"
+ },
+ "skill_name": {
+ "description": "Preloaded agent skill name",
+ "type": "string"
+ },
"type": {
- "description": "\"kb\" for knowledge base, \"file\" for file",
+ "description": "\"kb\", \"file\", \"tag\", \"mcp\", \"skill\"",
"type": "string"
}
}
diff --git a/docs/swagger.json b/docs/swagger.json
index 5b656d99e..165b85f17 100644
--- a/docs/swagger.json
+++ b/docs/swagger.json
@@ -12,6 +12,107 @@
},
"basePath": "/api/v1",
"paths": {
+ "/agent/mcp-oauth-resolutions/{pending_id}": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "用户在对话中完成 OAuth 授权后调用,校验令牌存在后恢复被暂停的 Agent 工具调用",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP服务"
+ ],
+ "summary": "完成对话内 MCP OAuth 授权",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "待授权 ID",
+ "name": "pending_id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "{service_id: string}",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "Bad Request",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "409": {
+ "description": "用户尚未完成授权",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
+ "/agent/mcp-oauth-resolutions/{pending_id}/cancel": {
+ "post": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "用户主动跳过 OAuth 授权,解除 Agent 阻塞",
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "MCP服务"
+ ],
+ "summary": "跳过对话内 MCP OAuth 授权",
+ "parameters": [
+ {
+ "type": "string",
+ "description": "待授权 ID",
+ "name": "pending_id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "404": {
+ "description": "Not Found",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
"/agent/tool-approvals/{pending_id}": {
"post": {
"security": [
@@ -11899,6 +12000,113 @@
}
}
},
+ "/tenants/{id}/api-principal-config": {
+ "get": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "返回 X-API-Key 请求如何映射为终端 Principal 的配置(Owner)",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "租户管理"
+ ],
+ "summary": "获取租户 API Key 用户身份配置",
+ "parameters": [
+ {
+ "type": "integer",
+ "description": "租户ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "API principal 配置",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "请求参数错误",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "403": {
+ "description": "权限不足",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ },
+ "put": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "description": "配置 X-API-Key 请求如何映射为终端 Principal(Owner)",
+ "consumes": [
+ "application/json"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "租户管理"
+ ],
+ "summary": "更新租户 API Key 用户身份配置",
+ "parameters": [
+ {
+ "type": "integer",
+ "description": "租户ID",
+ "name": "id",
+ "in": "path",
+ "required": true
+ },
+ {
+ "description": "API principal 配置",
+ "name": "request",
+ "in": "body",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/internal_handler.apiPrincipalConfigRequest"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "更新后的配置",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ },
+ "400": {
+ "description": "请求参数错误",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ },
+ "403": {
+ "description": "权限不足",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
+ }
+ }
+ }
+ },
"/tenants/{id}/audit-log": {
"get": {
"security": [
@@ -13597,6 +13805,19 @@
}
}
},
+ "github_com_Tencent_WeKnora_internal_types.APIPrincipalMode": {
+ "type": "string",
+ "enum": [
+ "tenant",
+ "direct_header",
+ "signed_token"
+ ],
+ "x-enum-varnames": [
+ "APIPrincipalModeTenant",
+ "APIPrincipalModeDirect",
+ "APIPrincipalModeSignedToken"
+ ]
+ },
"github_com_Tencent_WeKnora_internal_types.ASRConfig": {
"type": "object",
"properties": {
@@ -15467,6 +15688,10 @@
"api_key": {
"type": "string"
},
+ "api_key_header": {
+ "description": "APIKeyHeader is the header name that carries APIKey when AuthType is\napi_key. Empty defaults to \"X-API-Key\". This is non-secret structural\nconfig (the secret is APIKey), so it is not encrypted and is safe to echo\nback in responses. It lets services that expect the key in a different\nheader (e.g. the raw token directly in \"Authorization\") work without\nresorting to plaintext custom headers.",
+ "type": "string"
+ },
"auth_server_metadata_url": {
"description": "AuthServerMetadataURL optionally pins the OAuth authorization server\nmetadata URL. When empty, the server is discovered automatically from\nthe MCP URL (RFC 9728 / RFC 8414).",
"type": "string"
@@ -15720,6 +15945,14 @@
"id": {
"type": "string"
},
+ "kb_id": {
+ "description": "Parent knowledge base for file/tag mentions",
+ "type": "string"
+ },
+ "kb_name": {
+ "description": "Display name for parent KB",
+ "type": "string"
+ },
"kb_type": {
"description": "\"document\" or \"faq\" (only for kb type)",
"type": "string"
@@ -15727,8 +15960,16 @@
"name": {
"type": "string"
},
+ "service_id": {
+ "description": "Parent MCP service for MCP tool mentions",
+ "type": "string"
+ },
+ "skill_name": {
+ "description": "Preloaded agent skill name",
+ "type": "string"
+ },
"type": {
- "description": "\"kb\" for knowledge base, \"file\" for file",
+ "description": "\"kb\", \"file\", \"tag\", \"mcp\", \"skill\"",
"type": "string"
}
}
@@ -16925,9 +17166,33 @@
"type": "string"
}
},
+ "mcp_service_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "mentioned_items": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.MentionedItem"
+ }
+ },
"model_id": {
"type": "string"
},
+ "skill_names": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "tag_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
"web_search_enabled": {
"type": "boolean"
}
@@ -19625,6 +19890,26 @@
}
}
},
+ "internal_handler.apiPrincipalConfigRequest": {
+ "type": "object",
+ "properties": {
+ "direct_header_name": {
+ "type": "string"
+ },
+ "hmac_secret": {
+ "type": "string"
+ },
+ "mode": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.APIPrincipalMode"
+ },
+ "require_direct_header": {
+ "type": "boolean"
+ },
+ "signed_token_header_name": {
+ "type": "string"
+ }
+ }
+ },
"internal_handler.auditLogListResponse": {
"type": "object",
"properties": {
@@ -19884,6 +20169,13 @@
"type": "string"
}
},
+ "mcp_service_ids": {
+ "description": "Per-request MCP services selected via @mention",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
"mentioned_items": {
"description": "@mentioned knowledge bases and files",
"type": "array",
@@ -19895,10 +20187,24 @@
"description": "Query text for knowledge base search",
"type": "string"
},
+ "skill_names": {
+ "description": "Per-request Skills selected via @mention",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
"summary_model_id": {
"description": "Optional summary model ID for this request (overrides session default)",
"type": "string"
},
+ "tag_ids": {
+ "description": "@mentioned tag IDs (display/debug; scoped via MentionedItems)",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
"web_search_enabled": {
"description": "Whether web search is enabled for this request",
"type": "boolean"
@@ -19956,6 +20262,14 @@
"id": {
"type": "string"
},
+ "kb_id": {
+ "description": "Parent knowledge base for file/tag mentions",
+ "type": "string"
+ },
+ "kb_name": {
+ "description": "Display name for parent KB",
+ "type": "string"
+ },
"kb_type": {
"description": "\"document\" or \"faq\" (only for kb type)",
"type": "string"
@@ -19963,8 +20277,16 @@
"name": {
"type": "string"
},
+ "service_id": {
+ "description": "Parent MCP service for MCP tool mentions",
+ "type": "string"
+ },
+ "skill_name": {
+ "description": "Preloaded agent skill name",
+ "type": "string"
+ },
"type": {
- "description": "\"kb\" for knowledge base, \"file\" for file",
+ "description": "\"kb\", \"file\", \"tag\", \"mcp\", \"skill\"",
"type": "string"
}
}
diff --git a/docs/swagger.yaml b/docs/swagger.yaml
index 0b72877a9..d91b3a6b8 100644
--- a/docs/swagger.yaml
+++ b/docs/swagger.yaml
@@ -205,6 +205,16 @@ definitions:
tier:
$ref: '#/definitions/github_com_Tencent_WeKnora_internal_infrastructure_chunker.StrategyTier'
type: object
+ github_com_Tencent_WeKnora_internal_types.APIPrincipalMode:
+ enum:
+ - tenant
+ - direct_header
+ - signed_token
+ type: string
+ x-enum-varnames:
+ - APIPrincipalModeTenant
+ - APIPrincipalModeDirect
+ - APIPrincipalModeSignedToken
github_com_Tencent_WeKnora_internal_types.ASRConfig:
properties:
enabled:
@@ -1674,6 +1684,15 @@ definitions:
properties:
api_key:
type: string
+ api_key_header:
+ description: |-
+ APIKeyHeader is the header name that carries APIKey when AuthType is
+ api_key. Empty defaults to "X-API-Key". This is non-secret structural
+ config (the secret is APIKey), so it is not encrypted and is safe to echo
+ back in responses. It lets services that expect the key in a different
+ header (e.g. the raw token directly in "Authorization") work without
+ resorting to plaintext custom headers.
+ type: string
auth_server_metadata_url:
description: |-
AuthServerMetadataURL optionally pins the OAuth authorization server
@@ -1859,13 +1878,25 @@ definitions:
properties:
id:
type: string
+ kb_id:
+ description: Parent knowledge base for file/tag mentions
+ type: string
+ kb_name:
+ description: Display name for parent KB
+ type: string
kb_type:
description: '"document" or "faq" (only for kb type)'
type: string
name:
type: string
+ service_id:
+ description: Parent MCP service for MCP tool mentions
+ type: string
+ skill_name:
+ description: Preloaded agent skill name
+ type: string
type:
- description: '"kb" for knowledge base, "file" for file'
+ description: '"kb", "file", "tag", "mcp", "skill"'
type: string
type: object
github_com_Tencent_WeKnora_internal_types.Message:
@@ -2774,8 +2805,24 @@ definitions:
items:
type: string
type: array
+ mcp_service_ids:
+ items:
+ type: string
+ type: array
+ mentioned_items:
+ items:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.MentionedItem'
+ type: array
model_id:
type: string
+ skill_names:
+ items:
+ type: string
+ type: array
+ tag_ids:
+ items:
+ type: string
+ type: array
web_search_enabled:
type: boolean
type: object
@@ -4746,6 +4793,19 @@ definitions:
required:
- similar_questions
type: object
+ internal_handler.apiPrincipalConfigRequest:
+ properties:
+ direct_header_name:
+ type: string
+ hmac_secret:
+ type: string
+ mode:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.APIPrincipalMode'
+ require_direct_header:
+ type: boolean
+ signed_token_header_name:
+ type: string
+ type: object
internal_handler.auditLogListResponse:
properties:
data:
@@ -4937,6 +4997,11 @@ definitions:
items:
type: string
type: array
+ mcp_service_ids:
+ description: Per-request MCP services selected via @mention
+ items:
+ type: string
+ type: array
mentioned_items:
description: '@mentioned knowledge bases and files'
items:
@@ -4945,10 +5010,20 @@ definitions:
query:
description: Query text for knowledge base search
type: string
+ skill_names:
+ description: Per-request Skills selected via @mention
+ items:
+ type: string
+ type: array
summary_model_id:
description: Optional summary model ID for this request (overrides session
default)
type: string
+ tag_ids:
+ description: '@mentioned tag IDs (display/debug; scoped via MentionedItems)'
+ items:
+ type: string
+ type: array
web_search_enabled:
description: Whether web search is enabled for this request
type: boolean
@@ -4990,13 +5065,25 @@ definitions:
properties:
id:
type: string
+ kb_id:
+ description: Parent knowledge base for file/tag mentions
+ type: string
+ kb_name:
+ description: Display name for parent KB
+ type: string
kb_type:
description: '"document" or "faq" (only for kb type)'
type: string
name:
type: string
+ service_id:
+ description: Parent MCP service for MCP tool mentions
+ type: string
+ skill_name:
+ description: Preloaded agent skill name
+ type: string
type:
- description: '"kb" for knowledge base, "file" for file'
+ description: '"kb", "file", "tag", "mcp", "skill"'
type: string
type: object
internal_handler_session.SearchKnowledgeRequest:
@@ -5045,6 +5132,71 @@ info:
title: WeKnora API
version: "1.0"
paths:
+ /agent/mcp-oauth-resolutions/{pending_id}:
+ post:
+ consumes:
+ - application/json
+ description: 用户在对话中完成 OAuth 授权后调用,校验令牌存在后恢复被暂停的 Agent 工具调用
+ parameters:
+ - description: 待授权 ID
+ in: path
+ name: pending_id
+ required: true
+ type: string
+ - description: '{service_id: string}'
+ in: body
+ name: request
+ required: true
+ schema:
+ additionalProperties: true
+ type: object
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ additionalProperties: true
+ type: object
+ "400":
+ description: Bad Request
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ "409":
+ description: 用户尚未完成授权
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ summary: 完成对话内 MCP OAuth 授权
+ tags:
+ - MCP服务
+ /agent/mcp-oauth-resolutions/{pending_id}/cancel:
+ post:
+ description: 用户主动跳过 OAuth 授权,解除 Agent 阻塞
+ parameters:
+ - description: 待授权 ID
+ in: path
+ name: pending_id
+ required: true
+ type: string
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ additionalProperties: true
+ type: object
+ "404":
+ description: Not Found
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ summary: 跳过对话内 MCP OAuth 授权
+ tags:
+ - MCP服务
/agent/tool-approvals/{pending_id}:
post:
consumes:
@@ -12465,6 +12617,75 @@ paths:
summary: 重置租户 API Key
tags:
- 租户管理
+ /tenants/{id}/api-principal-config:
+ get:
+ consumes:
+ - application/json
+ description: 返回 X-API-Key 请求如何映射为终端 Principal 的配置(Owner)
+ parameters:
+ - description: 租户ID
+ in: path
+ name: id
+ required: true
+ type: integer
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: API principal 配置
+ schema:
+ additionalProperties: true
+ type: object
+ "400":
+ description: 请求参数错误
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ "403":
+ description: 权限不足
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ summary: 获取租户 API Key 用户身份配置
+ tags:
+ - 租户管理
+ put:
+ consumes:
+ - application/json
+ description: 配置 X-API-Key 请求如何映射为终端 Principal(Owner)
+ parameters:
+ - description: 租户ID
+ in: path
+ name: id
+ required: true
+ type: integer
+ - description: API principal 配置
+ in: body
+ name: request
+ required: true
+ schema:
+ $ref: '#/definitions/internal_handler.apiPrincipalConfigRequest'
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: 更新后的配置
+ schema:
+ additionalProperties: true
+ type: object
+ "400":
+ description: 请求参数错误
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ "403":
+ description: 权限不足
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ security:
+ - Bearer: []
+ summary: 更新租户 API Key 用户身份配置
+ tags:
+ - 租户管理
/tenants/{id}/audit-log:
get:
description: 返回该租户最近的审计事件,按 id 倒序。游标分页:将上次响应的 next_cursor 作为下一次请求的 after_id。
diff --git a/frontend/src/api/tenant/index.ts b/frontend/src/api/tenant/index.ts
index 0a0df9591..2758832b5 100644
--- a/frontend/src/api/tenant/index.ts
+++ b/frontend/src/api/tenant/index.ts
@@ -23,6 +23,7 @@ export interface APIPrincipalConfig {
mode: APIPrincipalMode
direct_header_name: string
signed_token_header_name: string
+ require_direct_header: boolean
has_hmac_secret: boolean
}
@@ -30,6 +31,7 @@ export interface UpdateAPIPrincipalConfigPayload {
mode: APIPrincipalMode
direct_header_name?: string
signed_token_header_name?: string
+ require_direct_header?: boolean
hmac_secret?: string
}
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 73f2419a2..98057f2e6 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -5763,6 +5763,8 @@ export default {
directWarning: 'Direct user ID trusts the caller-supplied header. Use only for trusted server-to-server calls.',
signedRecommended: 'Recommended for user-facing apps: your backend signs a short-lived HS256 JWT for the external user.',
directHeader: 'User ID header',
+ requireDirectHeader: 'Require user ID header',
+ requireDirectHeaderDesc: 'When enabled, API Key requests without the user ID header are rejected; when disabled they fall back to the tenant principal.',
tokenHeader: 'Token header',
hmacSecret: 'HMAC secret',
secretConfigured: 'Secret configured; enter a new value to rotate',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index f1cddd4df..aa1e9ecf6 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -5774,6 +5774,8 @@ export default {
directWarning: "직접 사용자 ID 모드는 요청 헤더를 신뢰합니다. 신뢰된 서버 간 호출에만 사용하세요.",
signedRecommended: "사용자 대상 앱에는 권장됩니다. 비즈니스 백엔드가 외부 사용자용 단기 HS256 JWT를 서명합니다.",
directHeader: "사용자 ID 헤더",
+ requireDirectHeader: "사용자 ID 헤더 필수",
+ requireDirectHeaderDesc: "켜면 사용자 ID 헤더가 없는 API Key 요청을 거부하고, 끄면 테넌트 Principal로 처리합니다.",
tokenHeader: "토큰 헤더",
hmacSecret: "HMAC secret",
secretConfigured: "Secret configured; enter a new value to rotate",
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 245eeb8c0..012560283 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -2358,6 +2358,8 @@ export default {
listFailed: 'Не удалось получить список тенантов',
searchFailed: 'Не удалось выполнить поиск тенантов',
resetApiKeyFailed: 'Не удалось сбросить API Key',
+ getApiPrincipalConfigFailed: 'Не удалось получить конфигурацию API principal',
+ updateApiPrincipalConfigFailed: 'Не удалось обновить конфигурацию API principal',
updateFailed: 'Не удалось обновить информацию об арендаторе'
},
initialization: {
@@ -5570,9 +5572,41 @@ export default {
tabs: {
im: 'IM-интеграция',
embed: 'Веб-встраивание',
+ api: 'API Key',
chrome: 'Расширение Chrome',
claw: 'Claw Skill',
},
+ api: {
+ title: 'Интеграция API Key',
+ subtitle: 'Используйте API Key арендатора для серверной интеграции и выберите, как передавать идентификатор конечного пользователя.',
+ loading: 'Загрузка настроек API-интеграции...',
+ retry: 'Повторить',
+ copy: 'Копировать',
+ copySuccess: 'Скопировано',
+ save: 'Сохранить',
+ baseUrl: 'Базовый URL API',
+ baseUrlDesc: 'Используйте с путями REST API.',
+ apiKey: 'API Key арендатора',
+ apiKeyDesc: 'API Key остаётся на уровне арендатора; идентификатор пользователя задаётся режимом ниже.',
+ principalMode: 'Режим идентификации пользователя',
+ principalModeDesc: 'Определяет, как запросы с X-API-Key сопоставляются с Principal для OAuth MCP и других per-user функций.',
+ modeTenant: 'Только арендатор',
+ modeDirect: 'Прямой ID пользователя',
+ modeSigned: 'Подписанный token',
+ directWarning: 'Прямой ID доверяет заголовку вызывающей стороны. Используйте только для доверенных server-to-server вызовов.',
+ signedRecommended: 'Рекомендуется для пользовательских приложений: ваш backend подписывает краткоживущий HS256 JWT для внешнего пользователя.',
+ directHeader: 'Заголовок ID пользователя',
+ requireDirectHeader: 'Требовать заголовок ID пользователя',
+ requireDirectHeaderDesc: 'Если включено, запросы без заголовка ID пользователя отклоняются; иначе используется Principal уровня арендатора.',
+ tokenHeader: 'Заголовок token',
+ hmacSecret: 'HMAC secret',
+ secretConfigured: 'Secret настроен; введите новое значение для ротации',
+ generateSecret: 'Сгенерировать secret',
+ requestExample: 'Пример запроса',
+ loadFailed: 'Не удалось загрузить настройки API-интеграции',
+ saveFailed: 'Не удалось сохранить настройки API-интеграции',
+ saveSuccess: 'Настройки API-интеграции сохранены',
+ },
manageSectionTitle: 'Настройка каналов',
manageSectionDesc: 'Выберите агента, чтобы создать или изменить каналы интеграции для него',
selectAgent: 'Выберите агента',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 7b03adae7..745f4c304 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -5776,6 +5776,8 @@ export default {
directWarning: "直接传用户 ID 会信任调用方请求头,仅建议用于可信服务端到服务端调用。",
signedRecommended: "推荐给面向用户的应用:业务方后端为外部用户签发短期 HS256 JWT。",
directHeader: "用户 ID 请求头",
+ requireDirectHeader: "必须携带用户 ID",
+ requireDirectHeaderDesc: "开启后,缺少用户 ID 请求头的 API Key 请求将被拒绝;关闭则回退为租户级 Principal。",
tokenHeader: "Token 请求头",
hmacSecret: "HMAC 密钥",
secretConfigured: "已配置密钥;输入新值可轮换",
diff --git a/frontend/src/views/integrations/ApiIntegrationSettings.vue b/frontend/src/views/integrations/ApiIntegrationSettings.vue
index be2c88a14..fb9cad530 100644
--- a/frontend/src/views/integrations/ApiIntegrationSettings.vue
+++ b/frontend/src/views/integrations/ApiIntegrationSettings.vue
@@ -75,6 +75,9 @@
<div v-if="form.mode === 'direct_header'" class="field-grid">
<label>{{ $t('integrations.api.directHeader') }}</label>
<t-input v-model="form.direct_header_name" class="mono-input" />
+ <label>{{ $t('integrations.api.requireDirectHeader') }}</label>
+ <t-switch v-model="form.require_direct_header" />
+ <p class="field-hint span-all">{{ $t('integrations.api.requireDirectHeaderDesc') }}</p>
</div>
<div v-if="form.mode === 'signed_token'" class="field-grid">
@@ -139,6 +142,7 @@ const form = reactive({
mode: 'tenant' as APIPrincipalMode,
direct_header_name: 'X-External-User-ID',
signed_token_header_name: 'X-External-User-Token',
+ require_direct_header: false,
})
const apiBaseUrl = computed(() => {
@@ -197,6 +201,7 @@ async function load() {
form.mode = cfgResp.data.mode || 'tenant'
form.direct_header_name = cfgResp.data.direct_header_name || 'X-External-User-ID'
form.signed_token_header_name = cfgResp.data.signed_token_header_name || 'X-External-User-Token'
+ form.require_direct_header = cfgResp.data.require_direct_header === true
secretInput.value = ''
} catch (err: any) {
error.value = err?.message || t('integrations.api.loadFailed')
@@ -219,6 +224,7 @@ async function save() {
mode: form.mode,
direct_header_name: form.direct_header_name.trim(),
signed_token_header_name: form.signed_token_header_name.trim(),
+ require_direct_header: form.require_direct_header,
}
if (secretInput.value.trim()) {
payload.hmac_secret = secretInput.value.trim()
@@ -324,6 +330,14 @@ onMounted(load)
color: var(--td-text-color-secondary);
font-size: 13px;
}
+
+ .field-hint.span-all {
+ grid-column: 1 / -1;
+ margin: 0;
+ color: var(--td-text-color-placeholder);
+ font-size: 12px;
+ line-height: 1.5;
+ }
}
.example-box {
diff --git a/internal/application/repository/mcp_oauth.go b/internal/application/repository/mcp_oauth.go
index 4be1b13f5..be0a2349a 100644
--- a/internal/application/repository/mcp_oauth.go
+++ b/internal/application/repository/mcp_oauth.go
@@ -3,6 +3,7 @@ package repository
import (
"context"
"errors"
+ "fmt"
"time"
"github.com/Tencent/WeKnora/internal/types"
@@ -95,7 +96,7 @@ func (r *mcpOAuthRepository) SaveToken(ctx context.Context, token *types.MCPOAut
func (r *mcpOAuthRepository) SaveTokenForPrincipal(ctx context.Context, token *types.MCPOAuthToken) error {
if token.PrincipalType == "" || token.PrincipalID == "" {
- return nil
+ return fmt.Errorf("mcp oauth token requires principal_type and principal_id")
}
if token.UserID == "" {
token.UserID = (types.Principal{Type: token.PrincipalType, ID: token.PrincipalID}).StorageID()
diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go
index be50e73eb..879f42d63 100644
--- a/internal/handler/tenant.go
+++ b/internal/handler/tenant.go
@@ -100,6 +100,7 @@ type apiPrincipalConfigRequest struct {
Mode types.APIPrincipalMode `json:"mode"`
DirectHeaderName string `json:"direct_header_name"`
SignedTokenHeaderName string `json:"signed_token_header_name"`
+ RequireDirectHeader bool `json:"require_direct_header"`
HMACSecret *string `json:"hmac_secret"`
}
@@ -107,6 +108,7 @@ type apiPrincipalConfigResponse struct {
Mode types.APIPrincipalMode `json:"mode"`
DirectHeaderName string `json:"direct_header_name"`
SignedTokenHeaderName string `json:"signed_token_header_name"`
+ RequireDirectHeader bool `json:"require_direct_header"`
HasHMACSecret bool `json:"has_hmac_secret"`
}
@@ -549,11 +551,23 @@ func apiPrincipalConfigForResponse(cfg *types.APIPrincipalConfig) apiPrincipalCo
Mode: mode,
DirectHeaderName: directHeader,
SignedTokenHeaderName: tokenHeader,
+ RequireDirectHeader: cfg.RequireDirectHeader,
HasHMACSecret: strings.TrimSpace(cfg.HMACSecret) != "",
}
}
-// GetAPIPrincipalConfig returns the tenant API-key principal mapping config.
+// GetAPIPrincipalConfig godoc
+// @Summary 获取租户 API Key 用户身份配置
+// @Description 返回 X-API-Key 请求如何映射为终端 Principal 的配置(Owner)
+// @Tags 租户管理
+// @Accept json
+// @Produce json
+// @Param id path int true "租户ID"
+// @Success 200 {object} map[string]interface{} "API principal 配置"
+// @Failure 400 {object} errors.AppError "请求参数错误"
+// @Failure 403 {object} errors.AppError "权限不足"
+// @Security Bearer
+// @Router /tenants/{id}/api-principal-config [get]
func (h *TenantHandler) GetAPIPrincipalConfig(c *gin.Context) {
ctx := c.Request.Context()
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
@@ -576,7 +590,19 @@ func (h *TenantHandler) GetAPIPrincipalConfig(c *gin.Context) {
})
}
-// UpdateAPIPrincipalConfig updates how tenant API-key requests resolve principals.
+// UpdateAPIPrincipalConfig godoc
+// @Summary 更新租户 API Key 用户身份配置
+// @Description 配置 X-API-Key 请求如何映射为终端 Principal(Owner)
+// @Tags 租户管理
+// @Accept json
+// @Produce json
+// @Param id path int true "租户ID"
+// @Param request body handler.apiPrincipalConfigRequest true "API principal 配置"
+// @Success 200 {object} map[string]interface{} "更新后的配置"
+// @Failure 400 {object} errors.AppError "请求参数错误"
+// @Failure 403 {object} errors.AppError "权限不足"
+// @Security Bearer
+// @Router /tenants/{id}/api-principal-config [put]
func (h *TenantHandler) UpdateAPIPrincipalConfig(c *gin.Context) {
ctx := c.Request.Context()
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
@@ -621,6 +647,7 @@ func (h *TenantHandler) UpdateAPIPrincipalConfig(c *gin.Context) {
Mode: req.Mode,
DirectHeaderName: strings.TrimSpace(req.DirectHeaderName),
SignedTokenHeaderName: strings.TrimSpace(req.SignedTokenHeaderName),
+ RequireDirectHeader: req.RequireDirectHeader,
HMACSecret: hmacSecret,
}
if cfg.DirectHeaderName == "" {
diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go
index 303bf7613..cd37059be 100644
--- a/internal/middleware/auth.go
+++ b/internal/middleware/auth.go
@@ -11,6 +11,7 @@ import (
"slices"
"strconv"
"strings"
+ "time"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
@@ -23,6 +24,14 @@ import (
const (
defaultExternalUserIDHeader = "X-External-User-ID"
defaultExternalUserTokenHeader = "X-External-User-Token"
+ maxExternalUserIDLen = 128
+ maxExternalUserTokenTTL = 24 * time.Hour
+)
+
+var (
+ errMissingDirectHeader = errors.New("missing external user id header")
+ errInvalidExternalUserID = errors.New("invalid external user id")
+ errInvalidExternalUserToken = errors.New("invalid external user token")
)
// 无需认证的API列表
@@ -272,7 +281,7 @@ func Auth(
principal, principalErr := resolveAPIPrincipal(c.Request.Context(), t, c.Request.Header)
if principalErr != nil {
c.JSON(http.StatusUnauthorized, gin.H{
- "error": "Unauthorized: invalid external user token",
+ "error": apiPrincipalAuthErrorMessage(principalErr),
})
c.Abort()
return
@@ -321,8 +330,14 @@ func resolveAPIPrincipal(ctx context.Context, tenant *types.Tenant, header http.
}
externalUserID := strings.TrimSpace(header.Get(name))
if externalUserID == "" {
+ if cfg.RequireDirectHeader {
+ return types.Principal{}, errMissingDirectHeader
+ }
return fallback, nil
}
+ if err := validateExternalUserID(externalUserID); err != nil {
+ return types.Principal{}, fmt.Errorf("%w: %v", errInvalidExternalUserID, err)
+ }
return types.Principal{
Type: types.PrincipalAPIExternalUser,
ID: strconv.FormatUint(tenantID, 10) + ":" + externalUserID,
@@ -335,7 +350,10 @@ func resolveAPIPrincipal(ctx context.Context, tenant *types.Tenant, header http.
externalUserID, err := verifyExternalUserJWT(header.Get(name), tenantID, cfg.HMACSecret)
if err != nil || externalUserID == "" {
logger.Warnf(ctx, "invalid external user token for tenant=%d: %v", tenantID, err)
- return types.Principal{}, fmt.Errorf("invalid external user token: %w", err)
+ return types.Principal{}, fmt.Errorf("%w: %w", errInvalidExternalUserToken, err)
+ }
+ if err := validateExternalUserID(externalUserID); err != nil {
+ return types.Principal{}, fmt.Errorf("%w: %v", errInvalidExternalUserID, err)
}
return types.Principal{
Type: types.PrincipalAPIExternalUser,
@@ -356,7 +374,11 @@ func verifyExternalUserJWT(tokenString string, tenantID uint64, secret string) (
return "", errors.New("external user token secret is not configured")
}
claims := jwt.MapClaims{}
- parser := jwt.NewParser(jwt.WithAudience("weknora"), jwt.WithExpirationRequired())
+ parser := jwt.NewParser(
+ jwt.WithAudience("weknora"),
+ jwt.WithExpirationRequired(),
+ jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}),
+ )
token, err := parser.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
@@ -369,6 +391,16 @@ func verifyExternalUserJWT(tokenString string, tenantID uint64, secret string) (
if token == nil || !token.Valid {
return "", errors.New("invalid external user token")
}
+ exp, err := claims.GetExpirationTime()
+ if err != nil || exp == nil {
+ return "", errors.New("missing expiration")
+ }
+ if time.Until(exp.Time) > maxExternalUserTokenTTL {
+ return "", fmt.Errorf("token lifetime exceeds %s", maxExternalUserTokenTTL)
+ }
+ if nbf, nbfErr := claims.GetNotBefore(); nbfErr == nil && nbf != nil && time.Now().Before(nbf.Time) {
+ return "", errors.New("token not yet valid")
+ }
if got := principalTenantIDFromClaims(claims); got != tenantID {
return "", fmt.Errorf("tenant mismatch: got %d want %d", got, tenantID)
}
@@ -380,6 +412,35 @@ func verifyExternalUserJWT(tokenString string, tenantID uint64, secret string) (
return sub, nil
}
+func validateExternalUserID(id string) error {
+ id = strings.TrimSpace(id)
+ if id == "" {
+ return errors.New("empty external user id")
+ }
+ if len(id) > maxExternalUserIDLen {
+ return fmt.Errorf("external user id too long (max %d)", maxExternalUserIDLen)
+ }
+ for _, r := range id {
+ if r < 0x20 || r == 0x7f {
+ return errors.New("external user id contains invalid characters")
+ }
+ }
+ return nil
+}
+
+func apiPrincipalAuthErrorMessage(err error) string {
+ switch {
+ case errors.Is(err, errMissingDirectHeader):
+ return "Unauthorized: missing external user id header"
+ case errors.Is(err, errInvalidExternalUserID):
+ return "Unauthorized: invalid external user id"
+ case errors.Is(err, errInvalidExternalUserToken):
+ return "Unauthorized: invalid external user token"
+ default:
+ return "Unauthorized: invalid external user token"
+ }
+}
+
func principalTenantIDFromClaims(claims jwt.MapClaims) uint64 {
v, ok := claims["tenant_id"]
if !ok {
diff --git a/internal/middleware/auth_api_principal_test.go b/internal/middleware/auth_api_principal_test.go
index c8517ec2c..4e6361ed7 100644
--- a/internal/middleware/auth_api_principal_test.go
+++ b/internal/middleware/auth_api_principal_test.go
@@ -2,7 +2,9 @@ package middleware
import (
"context"
+ "errors"
"net/http"
+ "strings"
"testing"
"time"
@@ -121,3 +123,53 @@ func TestResolveAPIPrincipalSignedTokenRejectsExpired(t *testing.T) {
}
_ = p
}
+
+func TestResolveAPIPrincipalDirectHeaderRequired(t *testing.T) {
+ _, err := resolveAPIPrincipal(context.Background(), &types.Tenant{
+ ID: 7,
+ APIPrincipalConfig: &types.APIPrincipalConfig{
+ Mode: types.APIPrincipalModeDirect,
+ RequireDirectHeader: true,
+ },
+ }, http.Header{})
+ if !errors.Is(err, errMissingDirectHeader) {
+ t.Fatalf("resolveAPIPrincipal error = %v, want errMissingDirectHeader", err)
+ }
+}
+
+func TestResolveAPIPrincipalDirectHeaderRejectsInvalidUserID(t *testing.T) {
+ header := http.Header{}
+ header.Set("X-External-User-ID", strings.Repeat("a", maxExternalUserIDLen+1))
+
+ _, err := resolveAPIPrincipal(context.Background(), &types.Tenant{
+ ID: 7,
+ APIPrincipalConfig: &types.APIPrincipalConfig{
+ Mode: types.APIPrincipalModeDirect,
+ },
+ }, header)
+ if !errors.Is(err, errInvalidExternalUserID) {
+ t.Fatalf("resolveAPIPrincipal error = %v, want errInvalidExternalUserID", err)
+ }
+}
+
+func TestResolveAPIPrincipalSignedTokenRejectsLongLifetime(t *testing.T) {
+ secret := "test-secret"
+ header := http.Header{}
+ header.Set("X-External-User-Token", signedExternalUserToken(t, secret, jwt.MapClaims{
+ "sub": "external-u1",
+ "tenant_id": float64(7),
+ "aud": "weknora",
+ "exp": time.Now().Add(48 * time.Hour).Unix(),
+ }))
+
+ _, err := resolveAPIPrincipal(context.Background(), &types.Tenant{
+ ID: 7,
+ APIPrincipalConfig: &types.APIPrincipalConfig{
+ Mode: types.APIPrincipalModeSignedToken,
+ HMACSecret: secret,
+ },
+ }, header)
+ if err == nil {
+ t.Fatalf("resolveAPIPrincipal error = nil, want error")
+ }
+}
diff --git a/internal/types/principal.go b/internal/types/principal.go
index ad02edd00..e5ac66e10 100644
--- a/internal/types/principal.go
+++ b/internal/types/principal.go
@@ -8,7 +8,6 @@ import (
const (
PrincipalWebUser = "web_user"
PrincipalAPITenant = "api_tenant"
- PrincipalAPIUser = "api_user"
PrincipalAPIExternalUser = "api_external_user"
PrincipalIMUser = "im_user"
PrincipalEmbedChannel = "embed_channel"
diff --git a/internal/types/tenant.go b/internal/types/tenant.go
index 37980074d..0cccfe0cb 100644
--- a/internal/types/tenant.go
+++ b/internal/types/tenant.go
@@ -232,7 +232,11 @@ type APIPrincipalConfig struct {
Mode APIPrincipalMode `json:"mode"`
DirectHeaderName string `json:"direct_header_name,omitempty"`
SignedTokenHeaderName string `json:"signed_token_header_name,omitempty"`
- HMACSecret string `json:"hmac_secret,omitempty"`
+ // RequireDirectHeader, when true in direct_header mode, rejects API-key
+ // requests that omit the configured user-id header instead of falling
+ // back to the tenant-level principal.
+ RequireDirectHeader bool `json:"require_direct_header,omitempty"`
+ HMACSecret string `json:"hmac_secret,omitempty"`
}
func (c *APIPrincipalConfig) Value() (driver.Value, error) {