feat: scope API MCP OAuth by principal

This commit is contained in:
wizardchen
2026-06-30 09:21:49 +08:00
committed by lyingbug
parent 77e4f93e3e
commit cb99736d72
39 changed files with 1566 additions and 108 deletions
+45
View File
@@ -17,6 +17,22 @@ export interface TenantInfo {
updated_at: string
}
export type APIPrincipalMode = 'tenant' | 'direct_header' | 'signed_token'
export interface APIPrincipalConfig {
mode: APIPrincipalMode
direct_header_name: string
signed_token_header_name: string
has_hmac_secret: boolean
}
export interface UpdateAPIPrincipalConfigPayload {
mode: APIPrincipalMode
direct_header_name?: string
signed_token_header_name?: string
hmac_secret?: string
}
// 搜索租户参数
export interface SearchTenantsParams {
keyword?: string
@@ -70,6 +86,35 @@ export async function resetTenantApiKey(
}
}
export async function getAPIPrincipalConfig(
tenantId: number,
): Promise<{ success: boolean; data?: APIPrincipalConfig; message?: string }> {
try {
const response = await get(`/api/v1/tenants/${tenantId}/api-principal-config`)
return response as unknown as { success: boolean; data?: APIPrincipalConfig; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.getApiPrincipalConfigFailed'),
}
}
}
export async function updateAPIPrincipalConfig(
tenantId: number,
payload: UpdateAPIPrincipalConfigPayload,
): Promise<{ success: boolean; data?: APIPrincipalConfig; message?: string }> {
try {
const response = await put(`/api/v1/tenants/${tenantId}/api-principal-config`, payload)
return response as unknown as { success: boolean; data?: APIPrincipalConfig; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.updateApiPrincipalConfigFailed'),
}
}
}
/**
* 更新租户信息(目前暴露名称、描述两个字段的编辑入口)。
* 后端 `PUT /tenants/:id` 用指针字段区分"未传"和"显式空串",未传的列不会
+3 -2
View File
@@ -3,9 +3,9 @@ export const CHROME_EXTENSION_URL =
export const CLAWHUB_SKILL_URL = 'https://clawhub.ai/lyingbug/weknora'
export type IntegrationTab = 'im' | 'embed' | 'chrome' | 'claw'
export type IntegrationTab = 'im' | 'embed' | 'api' | 'chrome' | 'claw'
export const INTEGRATION_TABS: IntegrationTab[] = ['im', 'embed', 'chrome', 'claw']
export const INTEGRATION_TABS: IntegrationTab[] = ['im', 'embed', 'api', 'chrome', 'claw']
export type IntegrationPreviewIcon =
| { type: 'icon'; name: string }
@@ -18,6 +18,7 @@ export const INTEGRATION_PREVIEW_ITEMS: Array<{
}> = [
{ key: 'im', icon: { type: 'icon', name: 'chat-message' } },
{ key: 'embed', icon: { type: 'icon', name: 'code' } },
{ key: 'api', icon: { type: 'icon', name: 'api' } },
{ key: 'chrome', icon: { type: 'icon', name: 'extension' } },
{ key: 'claw', icon: { type: 'emoji', value: '🦞' } },
]
+32
View File
@@ -3635,6 +3635,8 @@ export default {
listFailed: 'Failed to list tenants',
searchFailed: 'Failed to search tenants',
resetApiKeyFailed: 'Failed to reset API Key',
getApiPrincipalConfigFailed: 'Failed to get API principal config',
updateApiPrincipalConfigFailed: 'Failed to update API principal config',
updateFailed: 'Failed to update tenant information',
deleteFailed: 'Failed to delete tenant',
},
@@ -5737,9 +5739,39 @@ export default {
tabs: {
im: 'IM Integration',
embed: 'Web Embed',
api: 'API Key',
chrome: 'Chrome Extension',
claw: 'Claw Skill',
},
api: {
title: 'API Key Integration',
subtitle: 'Use the tenant API key for server-side integrations, and choose how API requests identify the terminal user.',
loading: 'Loading API integration settings...',
retry: 'Retry',
copy: 'Copy',
copySuccess: 'Copied',
save: 'Save',
baseUrl: 'API Base URL',
baseUrlDesc: 'Use this base URL with REST API paths.',
apiKey: 'Tenant API Key',
apiKeyDesc: 'The API key is still tenant-level. User identity is supplied by the principal mode below.',
principalMode: 'User identity mode',
principalModeDesc: 'Controls how X-API-Key requests map to a principal for OAuth MCP tokens and other per-user features.',
modeTenant: 'Tenant only',
modeDirect: 'Direct user ID',
modeSigned: 'Signed token',
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',
tokenHeader: 'Token header',
hmacSecret: 'HMAC secret',
secretConfigured: 'Secret configured; enter a new value to rotate',
generateSecret: 'Generate secret',
requestExample: 'Request example',
loadFailed: 'Failed to load API integration settings',
saveFailed: 'Failed to save API integration settings',
saveSuccess: 'API integration settings saved',
},
manageSectionTitle: 'Channel configuration',
manageSectionDesc: 'Select an agent to create or edit integration channels for that agent',
selectAgent: 'Select agent',
+32
View File
@@ -2643,6 +2643,8 @@ export default {
listFailed: '테넌트 목록 조회 실패',
searchFailed: '테넌트 검색 실패',
resetApiKeyFailed: 'API 키 재설정 실패',
getApiPrincipalConfigFailed: 'API principal config 조회 실패',
updateApiPrincipalConfigFailed: 'API principal config 업데이트 실패',
updateFailed: '테넌트 정보 업데이트 실패',
},
initialization: {
@@ -5748,9 +5750,39 @@ export default {
tabs: {
im: "IM 통합",
embed: "웹 임베드",
api: "API Key",
chrome: "Chrome 확장",
claw: "Claw Skill",
},
api: {
title: "API Key 통합",
subtitle: "테넌트 API Key로 서버 연동을 구성하고, API 요청이 최종 사용자 ID를 전달하는 방식을 선택합니다.",
loading: "API 통합 설정을 불러오는 중...",
retry: "다시 시도",
copy: "복사",
copySuccess: "복사되었습니다",
save: "저장",
baseUrl: "API Base URL",
baseUrlDesc: "REST API 경로와 함께 사용하세요.",
apiKey: "테넌트 API Key",
apiKeyDesc: "API Key는 계속 테넌트 단위입니다. 사용자 ID는 아래 모드로 전달합니다.",
principalMode: "사용자 ID 모드",
principalModeDesc: "X-API-Key 요청을 Principal로 매핑하는 방식입니다. OAuth MCP 토큰 및 사용자별 기능에 사용됩니다.",
modeTenant: "테넌트만",
modeDirect: "사용자 ID 직접 전달",
modeSigned: "서명 토큰",
directWarning: "직접 사용자 ID 모드는 요청 헤더를 신뢰합니다. 신뢰된 서버 간 호출에만 사용하세요.",
signedRecommended: "사용자 대상 앱에는 권장됩니다. 비즈니스 백엔드가 외부 사용자용 단기 HS256 JWT를 서명합니다.",
directHeader: "사용자 ID 헤더",
tokenHeader: "토큰 헤더",
hmacSecret: "HMAC secret",
secretConfigured: "Secret configured; enter a new value to rotate",
generateSecret: "Secret 생성",
requestExample: "요청 예시",
loadFailed: "API 통합 설정을 불러오지 못했습니다",
saveFailed: "API 통합 설정 저장 실패",
saveSuccess: "API 통합 설정이 저장되었습니다",
},
manageSectionTitle: "채널 구성",
manageSectionDesc: "에이전트를 선택한 후 해당 에이전트의 통합 채널을 생성하거나 편집할 수 있습니다",
selectAgent: "에이전트 선택",
+32
View File
@@ -2653,6 +2653,8 @@ export default {
listFailed: "获取空间列表失败",
searchFailed: "搜索空间失败",
resetApiKeyFailed: "重置 API Key 失败",
getApiPrincipalConfigFailed: "获取 API 用户身份配置失败",
updateApiPrincipalConfigFailed: "更新 API 用户身份配置失败",
updateFailed: "更新空间信息失败",
deleteFailed: "删除空间失败",
},
@@ -5750,9 +5752,39 @@ export default {
tabs: {
im: "IM 集成",
embed: "网页嵌入",
api: "API Key",
chrome: "Chrome 插件",
claw: "Claw Skill",
},
api: {
title: "API Key 集成",
subtitle: "使用租户级 API Key 接入服务,并选择 API 请求如何携带终端用户身份。",
loading: "正在加载 API 集成设置...",
retry: "重试",
copy: "复制",
copySuccess: "已复制",
save: "保存",
baseUrl: "API 地址",
baseUrlDesc: "与 REST API 路径拼接使用。",
apiKey: "租户 API Key",
apiKeyDesc: "API Key 仍按租户级管理;终端用户身份由下方模式提供。",
principalMode: "用户身份模式",
principalModeDesc: "决定 X-API-Key 请求如何映射为 Principal,用于 OAuth MCP token 和其他按用户隔离的能力。",
modeTenant: "仅租户",
modeDirect: "直接传用户 ID",
modeSigned: "签名 Token",
directWarning: "直接传用户 ID 会信任调用方请求头,仅建议用于可信服务端到服务端调用。",
signedRecommended: "推荐给面向用户的应用:业务方后端为外部用户签发短期 HS256 JWT。",
directHeader: "用户 ID 请求头",
tokenHeader: "Token 请求头",
hmacSecret: "HMAC 密钥",
secretConfigured: "已配置密钥;输入新值可轮换",
generateSecret: "生成密钥",
requestExample: "请求示例",
loadFailed: "加载 API 集成设置失败",
saveFailed: "保存 API 集成设置失败",
saveSuccess: "API 集成设置已保存",
},
manageSectionTitle: "渠道配置",
manageSectionDesc: "选择智能体后,可创建或编辑该智能体下的集成渠道",
selectAgent: "选择智能体",
@@ -0,0 +1,372 @@
<template>
<div class="api-integration section">
<div class="section-header">
<h2>{{ $t('integrations.api.title') }}</h2>
<p class="section-description">{{ $t('integrations.api.subtitle') }}</p>
</div>
<div v-if="loading" class="state-row">
<t-loading size="small" />
<span>{{ $t('integrations.api.loading') }}</span>
</div>
<t-alert v-else-if="error" theme="error" :message="error">
<template #operation>
<t-button size="small" @click="load">{{ $t('integrations.api.retry') }}</t-button>
</template>
</t-alert>
<div v-else class="api-settings">
<section class="settings-band">
<div class="row">
<div class="row-info">
<label>{{ $t('integrations.api.baseUrl') }}</label>
<p>{{ $t('integrations.api.baseUrlDesc') }}</p>
</div>
<div class="row-control copy-field">
<t-input :model-value="apiBaseUrl" readonly class="mono-input" />
<t-button variant="text" :title="$t('integrations.api.copy')" @click="copy(apiBaseUrl)">
<t-icon name="file-copy" />
</t-button>
</div>
</div>
<div class="row">
<div class="row-info">
<label>{{ $t('integrations.api.apiKey') }}</label>
<p>{{ $t('integrations.api.apiKeyDesc') }}</p>
</div>
<div class="row-control copy-field">
<t-input :model-value="displayApiKey" readonly class="mono-input" />
<t-button variant="text" @click="showApiKey = !showApiKey">
<t-icon :name="showApiKey ? 'browse-off' : 'browse'" />
</t-button>
<t-button variant="text" :title="$t('integrations.api.copy')" @click="copy(apiKey)">
<t-icon name="file-copy" />
</t-button>
</div>
</div>
</section>
<section class="settings-band">
<div class="row row--stack">
<div class="row-info">
<label>{{ $t('integrations.api.principalMode') }}</label>
<p>{{ $t('integrations.api.principalModeDesc') }}</p>
</div>
<div class="mode-panel">
<t-radio-group v-model="form.mode">
<t-radio-button value="tenant">{{ $t('integrations.api.modeTenant') }}</t-radio-button>
<t-radio-button value="direct_header">{{ $t('integrations.api.modeDirect') }}</t-radio-button>
<t-radio-button value="signed_token">{{ $t('integrations.api.modeSigned') }}</t-radio-button>
</t-radio-group>
<t-alert
v-if="form.mode === 'direct_header'"
theme="warning"
:message="$t('integrations.api.directWarning')"
/>
<t-alert
v-if="form.mode === 'signed_token'"
theme="success"
:message="$t('integrations.api.signedRecommended')"
/>
<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" />
</div>
<div v-if="form.mode === 'signed_token'" class="field-grid">
<label>{{ $t('integrations.api.tokenHeader') }}</label>
<t-input v-model="form.signed_token_header_name" class="mono-input" />
<label>{{ $t('integrations.api.hmacSecret') }}</label>
<div class="copy-field">
<t-input
v-model="secretInput"
type="password"
class="mono-input"
:placeholder="config?.has_hmac_secret ? $t('integrations.api.secretConfigured') : ''"
/>
<t-button variant="text" :title="$t('integrations.api.generateSecret')" @click="generateSecret">
<t-icon name="refresh" />
</t-button>
</div>
</div>
<div class="example-box">
<div class="example-title">{{ $t('integrations.api.requestExample') }}</div>
<pre>{{ requestExample }}</pre>
</div>
<div class="actions">
<t-button theme="primary" :loading="saving" :disabled="!canSave" @click="save">
{{ $t('integrations.api.save') }}
</t-button>
</div>
</div>
</div>
</section>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { getCurrentUser } from '@/api/auth'
import {
getAPIPrincipalConfig,
updateAPIPrincipalConfig,
type APIPrincipalConfig,
type APIPrincipalMode,
} from '@/api/tenant'
import { getApiBaseUrl } from '@/utils/api-base'
const { t } = useI18n()
const loading = ref(true)
const saving = ref(false)
const error = ref('')
const tenantId = ref(0)
const apiKey = ref('')
const showApiKey = ref(false)
const config = ref<APIPrincipalConfig | null>(null)
const secretInput = ref('')
const form = reactive({
mode: 'tenant' as APIPrincipalMode,
direct_header_name: 'X-External-User-ID',
signed_token_header_name: 'X-External-User-Token',
})
const apiBaseUrl = computed(() => {
const configured = getApiBaseUrl().trim().replace(/\/$/, '')
const origin = typeof window !== 'undefined' && window.location.origin !== 'null' ? window.location.origin : ''
return `${configured || origin}/api/v1`
})
const displayApiKey = computed(() => {
if (!apiKey.value) return ''
if (showApiKey.value) return apiKey.value
return '•'.repeat(apiKey.value.length)
})
const canSave = computed(() => {
if (!tenantId.value) return false
if (form.mode === 'signed_token') {
return config.value?.has_hmac_secret === true || secretInput.value.trim() !== ''
}
return true
})
const requestExample = computed(() => {
const lines = [
`curl -X POST ${apiBaseUrl.value}/session/qa`,
` -H "X-API-Key: ${apiKey.value ? '<API_KEY>' : '<YOUR_API_KEY>'}"`,
` -H "Content-Type: application/json"`,
]
if (form.mode === 'direct_header') {
lines.push(` -H "${form.direct_header_name || 'X-External-User-ID'}: user_123"`)
}
if (form.mode === 'signed_token') {
lines.push(` -H "${form.signed_token_header_name || 'X-External-User-Token'}: <HS256_JWT>"`)
}
lines.push(` -d '{"query":"hello"}'`)
return lines.join(' \\\n')
})
async function load() {
loading.value = true
error.value = ''
try {
const userResp = await getCurrentUser()
const tenant = (userResp as any)?.data?.tenant
if (!tenant?.id) {
throw new Error(t('integrations.api.loadFailed'))
}
tenantId.value = Number(tenant.id)
apiKey.value = tenant.api_key || ''
const cfgResp = await getAPIPrincipalConfig(tenantId.value)
if (!cfgResp.success || !cfgResp.data) {
throw new Error(cfgResp.message || t('integrations.api.loadFailed'))
}
config.value = cfgResp.data
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'
secretInput.value = ''
} catch (err: any) {
error.value = err?.message || t('integrations.api.loadFailed')
} finally {
loading.value = false
}
}
function generateSecret() {
const bytes = new Uint8Array(32)
window.crypto.getRandomValues(bytes)
secretInput.value = btoa(String.fromCharCode(...bytes))
}
async function save() {
if (!tenantId.value) return
saving.value = true
try {
const payload: Parameters<typeof updateAPIPrincipalConfig>[1] = {
mode: form.mode,
direct_header_name: form.direct_header_name.trim(),
signed_token_header_name: form.signed_token_header_name.trim(),
}
if (secretInput.value.trim()) {
payload.hmac_secret = secretInput.value.trim()
}
const resp = await updateAPIPrincipalConfig(tenantId.value, payload)
if (!resp.success || !resp.data) {
throw new Error(resp.message || t('integrations.api.saveFailed'))
}
config.value = resp.data
secretInput.value = ''
MessagePlugin.success(t('integrations.api.saveSuccess'))
} catch (err: any) {
MessagePlugin.error(err?.message || t('integrations.api.saveFailed'))
} finally {
saving.value = false
}
}
async function copy(text: string) {
if (!text) return
await navigator.clipboard.writeText(text)
MessagePlugin.success(t('integrations.api.copySuccess'))
}
onMounted(load)
</script>
<style scoped lang="less">
.api-integration {
width: 100%;
}
.state-row {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
min-height: 160px;
color: var(--td-text-color-secondary);
}
.api-settings,
.settings-band {
display: flex;
flex-direction: column;
}
.settings-band {
border-top: 1px solid var(--td-component-stroke);
}
.row {
display: grid;
grid-template-columns: minmax(220px, 0.8fr) minmax(320px, 1fr);
gap: 24px;
padding: 20px 0;
border-bottom: 1px solid var(--td-component-stroke);
}
.row--stack {
grid-template-columns: minmax(220px, 0.8fr) minmax(420px, 1fr);
}
.row-info {
label {
display: block;
margin-bottom: 4px;
color: var(--td-text-color-primary);
font-size: 15px;
font-weight: 600;
}
p {
margin: 0;
color: var(--td-text-color-secondary);
font-size: 13px;
line-height: 1.5;
}
}
.row-control,
.copy-field {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.mode-panel {
display: flex;
flex-direction: column;
gap: 14px;
min-width: 0;
}
.field-grid {
display: grid;
grid-template-columns: 130px minmax(0, 1fr);
gap: 10px 12px;
align-items: center;
label {
color: var(--td-text-color-secondary);
font-size: 13px;
}
}
.example-box {
border: 1px solid var(--td-component-stroke);
border-radius: 6px;
background: var(--td-bg-color-page);
overflow: hidden;
}
.example-title {
padding: 10px 12px;
border-bottom: 1px solid var(--td-component-stroke);
color: var(--td-text-color-secondary);
font-size: 12px;
}
pre {
margin: 0;
padding: 12px;
overflow: auto;
font-family: var(--app-font-family-mono);
font-size: 12px;
line-height: 1.6;
}
.actions {
display: flex;
justify-content: flex-end;
}
.mono-input :deep(input) {
font-family: var(--app-font-family-mono);
font-size: 12px;
}
@media (max-width: 780px) {
.row,
.row--stack {
grid-template-columns: 1fr;
}
.field-grid {
grid-template-columns: 1fr;
}
}
</style>
@@ -57,6 +57,7 @@
<AgentEmbedChannelPanel v-model:filter-agent-id="filterAgentId" />
</div>
<ApiIntegrationSettings v-if="currentSection === 'api'" />
<ChromeExtensionLanding v-if="currentSection === 'chrome'" />
<ClawSkillLanding v-if="currentSection === 'claw'" />
</div>
@@ -74,6 +75,7 @@ import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import IMChannelPanel from '@/components/IMChannelPanel.vue';
import AgentEmbedChannelPanel from '@/components/AgentEmbedChannelPanel.vue';
import ApiIntegrationSettings from '@/views/integrations/ApiIntegrationSettings.vue';
import ChromeExtensionLanding from '@/views/integrations/ChromeExtensionLanding.vue';
import ClawSkillLanding from '@/views/integrations/ClawSkillLanding.vue';
import { INTEGRATION_PREVIEW_ITEMS, INTEGRATION_TABS, type IntegrationTab } from '@/config/integrations';
+2 -2
View File
@@ -392,13 +392,13 @@ func (e *AgentEngine) runToolCall(
},
})
userID, _ := types.UserIDFromContext(ctx)
principal, _ := types.PrincipalFromContext(ctx)
toolExecCtx := agenttools.WithToolExecContext(toolCtx, &agenttools.ToolExecContext{
SessionID: sessionID,
AssistantMessageID: assistantMessageID,
EventBus: e.eventBus,
ToolCallID: tc.ID,
UserID: userID,
UserID: principal.StorageID(),
// ApprovalCtx keeps the round-level ctx without the per-tool 60s timeout,
// so MCP tool human-approval (issue #1173) can legitimately block longer.
ApprovalCtx: toolCtx,
+1 -1
View File
@@ -15,7 +15,7 @@ type ToolExecContext struct {
AssistantMessageID string
RequestID string
ToolCallID string
UserID string // owner of the originating session; used by HITL gates for authorization (issue #1173)
UserID string // principal storage ID of the originating session; used by HITL gates for authorization (issue #1173)
EventBus *event.EventBus
// ApprovalCtx is the parent ctx WITHOUT defaultToolExecTimeout; used when the tool
// must wait for human approval that may exceed normal tool exec timeout (issue #1173).
+4 -2
View File
@@ -65,7 +65,8 @@ func oauthSessionForRegistration(ctx context.Context, sess *MCPOAuthSession, ret
}
userID := sess.UserID
if userID == "" {
userID, _ = types.UserIDFromContext(ctx)
principal, _ := types.PrincipalFromContext(ctx)
userID = principal.StorageID()
}
requestID := sess.RequestID
if requestID == "" {
@@ -141,7 +142,8 @@ func waitForMCPOAuthAuthorization(
tenantID, _ := types.TenantIDFromContext(ctx)
userID := sess.UserID
if userID == "" {
userID, _ = types.UserIDFromContext(ctx)
principal, _ := types.PrincipalFromContext(ctx)
userID = principal.StorageID()
}
requestID := sess.RequestID
if requestID == "" {
+55 -4
View File
@@ -56,9 +56,25 @@ func (r *mcpOAuthRepository) DeleteClient(ctx context.Context, tenantID uint64,
func (r *mcpOAuthRepository) GetToken(
ctx context.Context, tenantID uint64, userID, serviceID string,
) (*types.MCPOAuthToken, error) {
return r.GetTokenForPrincipal(ctx, tenantID, types.Principal{
Type: types.PrincipalWebUser,
ID: userID,
}, serviceID)
}
func (r *mcpOAuthRepository) GetTokenForPrincipal(
ctx context.Context, tenantID uint64, principal types.Principal, serviceID string,
) (*types.MCPOAuthToken, error) {
principal = principal.Normalize()
if !principal.Valid() {
return nil, nil
}
var token types.MCPOAuthToken
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND user_id = ? AND service_id = ?", tenantID, userID, serviceID).
Where(
"tenant_id = ? AND principal_type = ? AND principal_id = ? AND service_id = ?",
tenantID, principal.Type, principal.ID, serviceID,
).
First(&token).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -70,12 +86,31 @@ func (r *mcpOAuthRepository) GetToken(
}
func (r *mcpOAuthRepository) SaveToken(ctx context.Context, token *types.MCPOAuthToken) error {
if token.PrincipalType == "" || token.PrincipalID == "" {
token.PrincipalType = types.PrincipalWebUser
token.PrincipalID = token.UserID
}
return r.SaveTokenForPrincipal(ctx, token)
}
func (r *mcpOAuthRepository) SaveTokenForPrincipal(ctx context.Context, token *types.MCPOAuthToken) error {
if token.PrincipalType == "" || token.PrincipalID == "" {
return nil
}
if token.UserID == "" {
token.UserID = (types.Principal{Type: token.PrincipalType, ID: token.PrincipalID}).StorageID()
}
token.UpdatedAt = time.Now()
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "tenant_id"}, {Name: "user_id"}, {Name: "service_id"}},
Columns: []clause.Column{
{Name: "tenant_id"},
{Name: "principal_type"},
{Name: "principal_id"},
{Name: "service_id"},
},
DoUpdates: clause.AssignmentColumns([]string{
"access_token", "refresh_token", "token_type", "expires_at", "updated_at",
"user_id", "access_token", "refresh_token", "token_type", "expires_at", "updated_at",
}),
}).
Create(token).Error
@@ -84,7 +119,23 @@ func (r *mcpOAuthRepository) SaveToken(ctx context.Context, token *types.MCPOAut
func (r *mcpOAuthRepository) DeleteToken(
ctx context.Context, tenantID uint64, userID, serviceID string,
) error {
return r.DeleteTokenForPrincipal(ctx, tenantID, types.Principal{
Type: types.PrincipalWebUser,
ID: userID,
}, serviceID)
}
func (r *mcpOAuthRepository) DeleteTokenForPrincipal(
ctx context.Context, tenantID uint64, principal types.Principal, serviceID string,
) error {
principal = principal.Normalize()
if !principal.Valid() {
return nil
}
return r.db.WithContext(ctx).
Where("tenant_id = ? AND user_id = ? AND service_id = ?", tenantID, userID, serviceID).
Where(
"tenant_id = ? AND principal_type = ? AND principal_id = ? AND service_id = ?",
tenantID, principal.Type, principal.ID, serviceID,
).
Delete(&types.MCPOAuthToken{}).Error
}
@@ -0,0 +1,81 @@
package repository
import (
"context"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func newMCPOAuthTestRepo(t *testing.T) *mcpOAuthRepository {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.MCPOAuthClient{}, &types.MCPOAuthToken{}))
return NewMCPOAuthRepository(db).(*mcpOAuthRepository)
}
func TestMCPOAuthRepositoryTokenForPrincipalIsolated(t *testing.T) {
repo := newMCPOAuthTestRepo(t)
ctx := context.Background()
expiresAt := time.Now().Add(time.Hour).UTC()
webPrincipal := types.Principal{Type: types.PrincipalWebUser, ID: "u1"}
apiPrincipal := types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:external-u1"}
require.NoError(t, repo.SaveTokenForPrincipal(ctx, &types.MCPOAuthToken{
TenantID: 7,
UserID: webPrincipal.StorageID(),
PrincipalType: webPrincipal.Type,
PrincipalID: webPrincipal.ID,
ServiceID: "svc1",
AccessToken: "web-token",
RefreshToken: "web-refresh",
TokenType: "Bearer",
ExpiresAt: expiresAt,
}))
require.NoError(t, repo.SaveTokenForPrincipal(ctx, &types.MCPOAuthToken{
TenantID: 7,
UserID: apiPrincipal.StorageID(),
PrincipalType: apiPrincipal.Type,
PrincipalID: apiPrincipal.ID,
ServiceID: "svc1",
AccessToken: "api-token",
RefreshToken: "api-refresh",
TokenType: "Bearer",
ExpiresAt: expiresAt,
}))
webToken, err := repo.GetTokenForPrincipal(ctx, 7, webPrincipal, "svc1")
require.NoError(t, err)
require.Equal(t, "web-token", webToken.AccessToken)
apiToken, err := repo.GetTokenForPrincipal(ctx, 7, apiPrincipal, "svc1")
require.NoError(t, err)
require.Equal(t, "api-token", apiToken.AccessToken)
}
func TestMCPOAuthRepositoryLegacyUserTokenUsesWebPrincipal(t *testing.T) {
repo := newMCPOAuthTestRepo(t)
ctx := context.Background()
require.NoError(t, repo.SaveToken(ctx, &types.MCPOAuthToken{
TenantID: 7,
UserID: "u1",
ServiceID: "svc1",
AccessToken: "legacy-token",
RefreshToken: "legacy-refresh",
TokenType: "Bearer",
ExpiresAt: time.Now().Add(time.Hour).UTC(),
}))
token, err := repo.GetTokenForPrincipal(ctx, 7, types.Principal{Type: types.PrincipalWebUser, ID: "u1"}, "svc1")
require.NoError(t, err)
require.Equal(t, "legacy-token", token.AccessToken)
}
+1 -1
View File
@@ -389,7 +389,7 @@ func (s *mcpServiceService) TestMCPService(
if service.AuthConfig.IsOAuth() {
config.OAuthRepo = s.oauthRepo
config.TenantID, _ = types.TenantIDFromContext(ctx)
config.UserID, _ = types.UserIDFromContext(ctx)
config.Principal, _ = types.PrincipalFromContext(ctx)
}
client, err := mcp.NewMCPClient(config)
+6
View File
@@ -553,6 +553,12 @@ func (h *EmbedChannelHandler) ensureEmbedSession(c *gin.Context) error {
c.JSON(http.StatusForbidden, gin.H{"error": "session signature invalid"})
return apperrors.NewForbiddenError("session signature invalid")
}
principal := types.Principal{
Type: types.PrincipalEmbedSession,
ID: fmt.Sprintf("%d:%s:%s", ch.TenantID, ch.ID, sessionID),
}
c.Set(types.PrincipalContextKey.String(), principal)
c.Request = c.Request.WithContext(types.WithPrincipal(c.Request.Context(), principal))
return nil
}
+23 -17
View File
@@ -36,6 +36,12 @@ func NewMCPOAuthHandler(
return &MCPOAuthHandler{oauth: oauth, mcpManager: mcpManager, svc: svc, gate: gate}
}
func mcpOAuthPrincipalFromContext(ctx *gin.Context) (types.Principal, string) {
principal, _ := types.PrincipalFromContext(ctx.Request.Context())
principal = principal.Normalize()
return principal, principal.StorageID()
}
type mcpOAuthAuthorizeRequest struct {
// RedirectURI is the absolute backend callback URL registered with the
// authorization server (e.g. https://host/api/v1/mcp-services/oauth/callback).
@@ -63,8 +69,8 @@ func (h *MCPOAuthHandler) AuthorizeURL(c *gin.Context) {
ctx := c.Request.Context()
serviceID := c.Param("id")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
userID, _ := types.UserIDFromContext(ctx)
if tenantID == 0 || userID == "" {
principal, _ := mcpOAuthPrincipalFromContext(c)
if tenantID == 0 || !principal.Valid() {
c.Error(errors.NewUnauthorizedError("authentication required"))
return
}
@@ -93,7 +99,7 @@ func (h *MCPOAuthHandler) AuthorizeURL(c *gin.Context) {
return
}
authURL, err := h.oauth.StartAuthorization(ctx, service, tenantID, userID, req.RedirectURI, req.FrontendRedirect)
authURL, err := h.oauth.StartAuthorization(ctx, service, tenantID, principal, req.RedirectURI, req.FrontendRedirect)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"service_id": secutils.SanitizeForLog(serviceID),
@@ -163,13 +169,13 @@ func (h *MCPOAuthHandler) Status(c *gin.Context) {
ctx := c.Request.Context()
serviceID := c.Param("id")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
userID, _ := types.UserIDFromContext(ctx)
if tenantID == 0 || userID == "" {
principal, _ := mcpOAuthPrincipalFromContext(c)
if tenantID == 0 || !principal.Valid() {
c.Error(errors.NewUnauthorizedError("authentication required"))
return
}
authorized, err := h.oauth.IsAuthorized(ctx, tenantID, userID, serviceID)
authorized, err := h.oauth.IsAuthorized(ctx, tenantID, principal, serviceID)
if err != nil {
c.Error(errors.NewInternalServerError("failed to query authorization status: " + err.Error()))
return
@@ -192,13 +198,13 @@ func (h *MCPOAuthHandler) Revoke(c *gin.Context) {
ctx := c.Request.Context()
serviceID := c.Param("id")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
userID, _ := types.UserIDFromContext(ctx)
if tenantID == 0 || userID == "" {
principal, _ := mcpOAuthPrincipalFromContext(c)
if tenantID == 0 || !principal.Valid() {
c.Error(errors.NewUnauthorizedError("authentication required"))
return
}
if err := h.oauth.Revoke(ctx, tenantID, userID, serviceID); err != nil {
if err := h.oauth.Revoke(ctx, tenantID, principal, serviceID); err != nil {
c.Error(errors.NewInternalServerError("failed to revoke authorization: " + err.Error()))
return
}
@@ -238,8 +244,8 @@ func (h *MCPOAuthHandler) ResolveMCPOAuth(c *gin.Context) {
ctx := c.Request.Context()
pendingID := c.Param("pending_id")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
userID, _ := types.UserIDFromContext(ctx)
if tenantID == 0 || strings.TrimSpace(userID) == "" {
principal, gateUserID := mcpOAuthPrincipalFromContext(c)
if tenantID == 0 || !principal.Valid() || gateUserID == "" {
c.Error(errors.NewUnauthorizedError("authentication required"))
return
}
@@ -266,7 +272,7 @@ func (h *MCPOAuthHandler) ResolveMCPOAuth(c *gin.Context) {
switch decision {
case "cancel", "reject", "skip":
if err := h.gate.Resolve(tenantID, userID, pendingID, approval.Decision{
if err := h.gate.Resolve(tenantID, gateUserID, pendingID, approval.Decision{
Approved: false,
Reason: "user canceled",
}); err != nil {
@@ -298,7 +304,7 @@ func (h *MCPOAuthHandler) ResolveMCPOAuth(c *gin.Context) {
// Only resume once the user genuinely holds a token; otherwise the retry
// would just fail again with another authorization-required error.
authorized, err := h.oauth.IsAuthorized(ctx, tenantID, userID, serviceID)
authorized, err := h.oauth.IsAuthorized(ctx, tenantID, principal, serviceID)
if err != nil {
c.Error(errors.NewInternalServerError("failed to verify authorization: " + err.Error()))
return
@@ -308,7 +314,7 @@ func (h *MCPOAuthHandler) ResolveMCPOAuth(c *gin.Context) {
return
}
if err := h.gate.Resolve(tenantID, userID, pendingID, approval.Decision{Approved: true}); err != nil {
if err := h.gate.Resolve(tenantID, gateUserID, pendingID, approval.Decision{Approved: true}); err != nil {
switch {
case stderrors.Is(err, approval.ErrPendingNotFound):
c.Error(errors.NewNotFoundError("pending authorization not found or already completed"))
@@ -346,8 +352,8 @@ func (h *MCPOAuthHandler) CancelMCPOAuth(c *gin.Context) {
ctx := c.Request.Context()
pendingID := c.Param("pending_id")
tenantID := c.GetUint64(types.TenantIDContextKey.String())
userID, _ := types.UserIDFromContext(ctx)
if tenantID == 0 || strings.TrimSpace(userID) == "" {
_, gateUserID := mcpOAuthPrincipalFromContext(c)
if tenantID == 0 || strings.TrimSpace(gateUserID) == "" {
c.Error(errors.NewUnauthorizedError("authentication required"))
return
}
@@ -356,7 +362,7 @@ func (h *MCPOAuthHandler) CancelMCPOAuth(c *gin.Context) {
return
}
if err := h.gate.Resolve(tenantID, userID, pendingID, approval.Decision{
if err := h.gate.Resolve(tenantID, gateUserID, pendingID, approval.Decision{
Approved: false,
Reason: "user canceled",
}); err != nil {
+6 -6
View File
@@ -645,16 +645,16 @@ func (h *MCPServiceHandler) ResolveToolApproval(c *gin.Context) {
c.Error(errors.NewBadRequestError("decision must be approve or reject"))
return
}
userID, _ := c.Get(types.UserIDContextKey.String())
userIDStr, _ := userID.(string)
// Reject calls without an authenticated user up front. The gate's
// per-user authorization is fail-close, but surfacing 401 here gives
principal, _ := types.PrincipalFromContext(ctx)
gateUserID := principal.StorageID()
// Reject calls without an authenticated principal up front. The gate's
// per-principal authorization is fail-close, but surfacing 401 here gives
// a clearer signal that auth middleware did not populate the context.
if strings.TrimSpace(userIDStr) == "" {
if strings.TrimSpace(gateUserID) == "" {
c.Error(errors.NewUnauthorizedError("authenticated user required to resolve tool approval"))
return
}
if err := h.toolApprovalGate.Resolve(tenantID, userIDStr, pendingID, dec); err != nil {
if err := h.toolApprovalGate.Resolve(tenantID, gateUserID, pendingID, dec); err != nil {
switch {
case stderrors.Is(err, approval.ErrPendingNotFound):
c.Error(errors.NewNotFoundError("pending approval not found or already completed"))
+140
View File
@@ -96,6 +96,25 @@ type updateTenantRequest struct {
Description *string `json:"description" binding:"omitempty,max=512"`
}
type apiPrincipalConfigRequest struct {
Mode types.APIPrincipalMode `json:"mode"`
DirectHeaderName string `json:"direct_header_name"`
SignedTokenHeaderName string `json:"signed_token_header_name"`
HMACSecret *string `json:"hmac_secret"`
}
type apiPrincipalConfigResponse struct {
Mode types.APIPrincipalMode `json:"mode"`
DirectHeaderName string `json:"direct_header_name"`
SignedTokenHeaderName string `json:"signed_token_header_name"`
HasHMACSecret bool `json:"has_hmac_secret"`
}
const (
defaultAPIPrincipalDirectHeader = "X-External-User-ID"
defaultAPIPrincipalTokenHeader = "X-External-User-Token"
)
// defaultMaxOwnedTenantsPerUser is the cap applied when
// config.Tenant.MaxOwnedPerUser is left at zero. Picked to comfortably
// cover legitimate "personal + a couple of side-projects" use while
@@ -510,6 +529,127 @@ func (h *TenantHandler) ResetAPIKey(c *gin.Context) {
})
}
func apiPrincipalConfigForResponse(cfg *types.APIPrincipalConfig) apiPrincipalConfigResponse {
if cfg == nil {
cfg = &types.APIPrincipalConfig{}
}
mode := cfg.Mode
if mode == "" {
mode = types.APIPrincipalModeTenant
}
directHeader := strings.TrimSpace(cfg.DirectHeaderName)
if directHeader == "" {
directHeader = defaultAPIPrincipalDirectHeader
}
tokenHeader := strings.TrimSpace(cfg.SignedTokenHeaderName)
if tokenHeader == "" {
tokenHeader = defaultAPIPrincipalTokenHeader
}
return apiPrincipalConfigResponse{
Mode: mode,
DirectHeaderName: directHeader,
SignedTokenHeaderName: tokenHeader,
HasHMACSecret: strings.TrimSpace(cfg.HMACSecret) != "",
}
}
// GetAPIPrincipalConfig returns the tenant API-key principal mapping config.
func (h *TenantHandler) GetAPIPrincipalConfig(c *gin.Context) {
ctx := c.Request.Context()
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
return
}
tenant, err := h.service.GetTenantByID(ctx, id)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
} else {
c.Error(errors.NewInternalServerError("Failed to load tenant").WithDetails(err.Error()))
}
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": apiPrincipalConfigForResponse(tenant.APIPrincipalConfig),
})
}
// UpdateAPIPrincipalConfig updates how tenant API-key requests resolve principals.
func (h *TenantHandler) UpdateAPIPrincipalConfig(c *gin.Context) {
ctx := c.Request.Context()
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
return
}
var req apiPrincipalConfigRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))
return
}
if req.Mode == "" {
req.Mode = types.APIPrincipalModeTenant
}
switch req.Mode {
case types.APIPrincipalModeTenant, types.APIPrincipalModeDirect, types.APIPrincipalModeSignedToken:
default:
c.Error(errors.NewValidationError("mode must be tenant, direct_header, or signed_token"))
return
}
tenant, err := h.service.GetTenantByID(ctx, id)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
} else {
c.Error(errors.NewInternalServerError("Failed to load tenant").WithDetails(err.Error()))
}
return
}
existingSecret := ""
if tenant.APIPrincipalConfig != nil {
existingSecret = tenant.APIPrincipalConfig.HMACSecret
}
hmacSecret := existingSecret
if req.HMACSecret != nil {
hmacSecret = strings.TrimSpace(*req.HMACSecret)
}
cfg := &types.APIPrincipalConfig{
Mode: req.Mode,
DirectHeaderName: strings.TrimSpace(req.DirectHeaderName),
SignedTokenHeaderName: strings.TrimSpace(req.SignedTokenHeaderName),
HMACSecret: hmacSecret,
}
if cfg.DirectHeaderName == "" {
cfg.DirectHeaderName = defaultAPIPrincipalDirectHeader
}
if cfg.SignedTokenHeaderName == "" {
cfg.SignedTokenHeaderName = defaultAPIPrincipalTokenHeader
}
if cfg.Mode == types.APIPrincipalModeSignedToken && strings.TrimSpace(cfg.HMACSecret) == "" {
c.Error(errors.NewValidationError("hmac_secret is required for signed_token mode"))
return
}
tenant.APIPrincipalConfig = cfg
updatedTenant, err := h.service.UpdateTenant(ctx, tenant)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
} else {
c.Error(errors.NewInternalServerError("Failed to update API principal config").WithDetails(err.Error()))
}
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": apiPrincipalConfigForResponse(updatedTenant.APIPrincipalConfig),
})
}
// DeleteTenant godoc
// @Summary 删除租户
// @Description 删除指定的租户
+10 -1
View File
@@ -9,7 +9,8 @@ import (
func TestWithIMIdentity(t *testing.T) {
const tenantID uint64 = 42
ctx := withIMIdentity(context.Background(), tenantID)
msg := &IncomingMessage{Platform: PlatformFeishu, UserID: "open-id-1"}
ctx := withIMIdentity(context.Background(), tenantID, "channel-1", msg)
gotTenant, ok := types.TenantIDFromContext(ctx)
if !ok || gotTenant != tenantID {
@@ -35,4 +36,12 @@ func TestWithIMIdentity(t *testing.T) {
if role := types.TenantRoleFromContext(ctx); role != types.TenantRoleViewer {
t.Fatalf("TenantRole = %v, want %v", role, types.TenantRoleViewer)
}
principal, ok := types.PrincipalFromContext(ctx)
if !ok {
t.Fatalf("Principal missing")
}
if principal.Type != types.PrincipalIMUser || principal.ID != "42:channel-1:feishu:open-id-1" {
t.Fatalf("Principal = %#v, want im_user for the external IM user", principal)
}
}
+6 -2
View File
@@ -468,9 +468,13 @@ func formatQuotedContext(quote *QuotedMessage) string {
// knowledge bases be merged and resolved correctly, since the shared-KB code
// gates on a non-empty UserID. Viewer is the least privilege sufficient to
// retrieve shared KBs.
func withIMIdentity(ctx context.Context, tenantID uint64) context.Context {
func withIMIdentity(ctx context.Context, tenantID uint64, channelID string, msg *IncomingMessage) context.Context {
ctx = context.WithValue(ctx, types.TenantIDContextKey, tenantID)
ctx = context.WithValue(ctx, types.UserIDContextKey, fmt.Sprintf("system-%d", tenantID))
if msg != nil {
principalID := fmt.Sprintf("%d:%s:%s:%s", tenantID, channelID, msg.Platform, msg.UserID)
ctx = types.WithPrincipal(ctx, types.Principal{Type: types.PrincipalIMUser, ID: principalID})
}
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
return ctx
}
@@ -1263,7 +1267,7 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
return fmt.Errorf("get tenant: %w", err)
}
sessionCtx := context.WithValue(ctx, types.TenantInfoContextKey, tenant)
sessionCtx = withIMIdentity(sessionCtx, tenantID)
sessionCtx = withIMIdentity(sessionCtx, tenantID, channelID, msg)
// 2. Resolve or create a WeKnora session
channelSession, err := s.resolveSession(sessionCtx, msg, tenantID, agentID, channelID, channel.SessionMode)
+12 -5
View File
@@ -52,9 +52,12 @@ type ClientConfig struct {
Service *types.MCPService
// OAuth wiring (only used when Service.AuthConfig.AuthType == oauth).
// The token store is scoped to (TenantID, UserID, Service.ID) so each
// user connects with their own access/refresh token.
// The token store is scoped to (TenantID, Principal, Service.ID) so each
// identity connects with its own access/refresh token.
TenantID uint64
Principal types.Principal
// UserID is kept for compatibility with older call sites/tests. New code
// should pass Principal.
UserID string
OAuthRepo interfaces.MCPOAuthRepository
}
@@ -236,13 +239,17 @@ func buildOAuthConfig(config *ClientConfig, httpClient *http.Client) (transport.
if config.OAuthRepo == nil {
return transport.OAuthConfig{}, false, fmt.Errorf("OAuth repository is required for OAuth MCP services")
}
if config.UserID == "" {
return transport.OAuthConfig{}, false, fmt.Errorf("user context is required to connect to an OAuth MCP service")
principal := config.Principal.Normalize()
if !principal.Valid() && config.UserID != "" {
principal = types.Principal{Type: types.PrincipalWebUser, ID: config.UserID}.Normalize()
}
if !principal.Valid() {
return transport.OAuthConfig{}, false, fmt.Errorf("principal context is required to connect to an OAuth MCP service")
}
oauthCfg := transport.OAuthConfig{
Scopes: svc.AuthConfig.Scopes,
TokenStore: newDBTokenStore(config.OAuthRepo, config.TenantID, config.UserID, svc.ID),
TokenStore: newDBTokenStore(config.OAuthRepo, config.TenantID, principal, svc.ID),
PKCEEnabled: true,
AuthServerMetadataURL: svc.AuthConfig.AuthServerMetadataURL,
HTTPClient: httpClient,
+15 -15
View File
@@ -40,11 +40,11 @@ func NewMCPManager(oauthRepo interfaces.MCPOAuthRepository) *MCPManager {
}
// cacheKey computes the connection-cache key for a service. OAuth services are
// keyed per user (each user connects with their own token); all other services
// share a single connection per service ID.
func cacheKey(service *types.MCPService, userID string) string {
// keyed per principal (each identity connects with its own token); all other
// services share a single connection per service ID.
func cacheKey(service *types.MCPService, principal types.Principal) string {
if service.AuthConfig.IsOAuth() {
return service.ID + "\x00" + userID
return service.ID + "\x00" + principal.Normalize().StorageID()
}
return service.ID
}
@@ -53,8 +53,8 @@ func cacheKey(service *types.MCPService, userID string) string {
// Caches and reuses existing connections for SSE/HTTP Streamable
// Note: Stdio transport is disabled for security reasons
//
// For OAuth-enabled services the connection is keyed per user (derived from
// ctx) so each user connects with their own token.
// For OAuth-enabled services the connection is keyed per principal (derived from
// ctx) so each identity connects with its own token.
func (m *MCPManager) GetOrCreateClient(ctx context.Context, service *types.MCPService) (MCPClient, error) {
// Check if service is enabled
if !service.Enabled {
@@ -67,15 +67,15 @@ func (m *MCPManager) GetOrCreateClient(ctx context.Context, service *types.MCPSe
}
var tenantID uint64
var userID string
var principal types.Principal
if service.AuthConfig.IsOAuth() {
tenantID, _ = types.TenantIDFromContext(ctx)
userID, _ = types.UserIDFromContext(ctx)
if userID == "" {
return nil, fmt.Errorf("user context is required to connect to OAuth MCP service %s", service.Name)
principal, _ = types.PrincipalFromContext(ctx)
if !principal.Valid() {
return nil, fmt.Errorf("principal context is required to connect to OAuth MCP service %s", service.Name)
}
}
key := cacheKey(service, userID)
key := cacheKey(service, principal)
// For SSE/HTTP Streamable, check if client already exists and reuse
m.clientsMu.RLock()
@@ -100,7 +100,7 @@ func (m *MCPManager) GetOrCreateClient(ctx context.Context, service *types.MCPSe
config := &ClientConfig{
Service: service,
TenantID: tenantID,
UserID: userID,
Principal: principal,
OAuthRepo: m.oauthRepo,
}
@@ -161,15 +161,15 @@ func (m *MCPManager) GetClient(serviceID string) (MCPClient, bool) {
}
// CloseClient closes and removes all cached connections for a service. For
// OAuth services this spans every per-user connection (keys are prefixed with
// OAuth services this spans every per-principal connection (keys are prefixed with
// the service ID).
func (m *MCPManager) CloseClient(serviceID string) error {
m.clientsMu.Lock()
defer m.clientsMu.Unlock()
for key, client := range m.clients {
// Match the plain service-ID key as well as per-user OAuth keys
// ("<serviceID>\x00<userID>").
// Match the plain service-ID key as well as per-principal OAuth keys
// ("<serviceID>\x00<principal>").
if key != serviceID && !strings.HasPrefix(key, serviceID+"\x00") {
continue
}
+28 -15
View File
@@ -17,7 +17,7 @@ const clientRegistrationName = "WeKnora"
// OAuthManager orchestrates the MCP OAuth2 authorization-code flow:
// discovery, dynamic client registration, the authorize redirect, and the
// callback code exchange. Tokens are persisted per (tenant, user, service);
// callback code exchange. Tokens are persisted per (tenant, principal, service);
// the registered client is persisted per (tenant, service) and reused.
type OAuthManager struct {
repo interfaces.MCPOAuthRepository
@@ -39,9 +39,9 @@ func NewOAuthManager(
}
}
// newHandler builds an OAuth handler bound to a service + per-user token store.
// newHandler builds an OAuth handler bound to a service + per-principal token store.
func (m *OAuthManager) newHandler(
ctx context.Context, service *types.MCPService, tenantID uint64, userID, redirectURI string,
ctx context.Context, service *types.MCPService, tenantID uint64, principal types.Principal, redirectURI string,
) (*transport.OAuthHandler, error) {
if service.URL == nil || *service.URL == "" {
return nil, fmt.Errorf("MCP service URL is required for OAuth")
@@ -49,7 +49,7 @@ func (m *OAuthManager) newHandler(
cfg := transport.OAuthConfig{
RedirectURI: redirectURI,
Scopes: service.AuthConfig.Scopes,
TokenStore: newDBTokenStore(m.repo, tenantID, userID, service.ID),
TokenStore: newDBTokenStore(m.repo, tenantID, principal, service.ID),
PKCEEnabled: true,
AuthServerMetadataURL: service.AuthConfig.AuthServerMetadataURL,
}
@@ -70,13 +70,18 @@ func (m *OAuthManager) StartAuthorization(
ctx context.Context,
service *types.MCPService,
tenantID uint64,
userID, redirectURI, frontendRedirect string,
principal types.Principal,
redirectURI, frontendRedirect string,
) (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)
}
h, err := m.newHandler(ctx, service, tenantID, userID, redirectURI)
h, err := m.newHandler(ctx, service, tenantID, principal, redirectURI)
if err != nil {
return "", err
}
@@ -118,7 +123,8 @@ func (m *OAuthManager) StartAuthorization(
if err := m.states.Put(ctx, state, OAuthState{
TenantID: tenantID,
UserID: userID,
UserID: principal.StorageID(),
Principal: principal,
ServiceID: service.ID,
CodeVerifier: verifier,
ClientID: h.GetClientID(),
@@ -142,6 +148,13 @@ func (m *OAuthManager) CompleteAuthorization(
return "", err
}
frontendRedirect = st.FrontendRedirect
principal := st.Principal.Normalize()
if !principal.Valid() && st.UserID != "" {
principal = types.Principal{Type: types.PrincipalWebUser, ID: st.UserID}.Normalize()
}
if !principal.Valid() {
return frontendRedirect, fmt.Errorf("principal context is missing from OAuth state")
}
service, err := m.serviceRepo.GetByID(ctx, st.TenantID, st.ServiceID)
if err != nil {
@@ -151,7 +164,7 @@ func (m *OAuthManager) CompleteAuthorization(
return frontendRedirect, fmt.Errorf("MCP service not found")
}
h, err := m.newHandler(ctx, service, st.TenantID, st.UserID, st.RedirectURI)
h, err := m.newHandler(ctx, service, st.TenantID, principal, st.RedirectURI)
if err != nil {
return frontendRedirect, err
}
@@ -164,26 +177,26 @@ func (m *OAuthManager) CompleteAuthorization(
}
// ProcessAuthorizationResponse persists the token via the TokenStore.
logger.GetLogger(ctx).Infof(
"MCP OAuth authorized: service=%s user=%s", st.ServiceID, st.UserID,
"MCP OAuth authorized: service=%s principal=%s", st.ServiceID, principal.StorageID(),
)
return frontendRedirect, nil
}
// IsAuthorized reports whether the given user has a stored (non-empty) token
// IsAuthorized reports whether the given principal has a stored (non-empty) token
// for the service.
func (m *OAuthManager) IsAuthorized(
ctx context.Context, tenantID uint64, userID, serviceID string,
ctx context.Context, tenantID uint64, principal types.Principal, serviceID string,
) (bool, error) {
tok, err := m.repo.GetToken(ctx, tenantID, userID, serviceID)
tok, err := m.repo.GetTokenForPrincipal(ctx, tenantID, principal, serviceID)
if err != nil {
return false, err
}
return tok != nil && tok.AccessToken != "", nil
}
// Revoke removes the user's stored token for the service.
// Revoke removes the principal's stored token for the service.
func (m *OAuthManager) Revoke(
ctx context.Context, tenantID uint64, userID, serviceID string,
ctx context.Context, tenantID uint64, principal types.Principal, serviceID string,
) error {
return m.repo.DeleteToken(ctx, tenantID, userID, serviceID)
return m.repo.DeleteTokenForPrincipal(ctx, tenantID, principal, serviceID)
}
+125
View File
@@ -0,0 +1,125 @@
package mcp
import (
"context"
"fmt"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/mark3labs/mcp-go/client/transport"
"github.com/stretchr/testify/require"
)
type fakeOAuthRepo struct {
clients map[string]*types.MCPOAuthClient
tokens map[string]*types.MCPOAuthToken
}
func newFakeOAuthRepo() *fakeOAuthRepo {
return &fakeOAuthRepo{
clients: map[string]*types.MCPOAuthClient{},
tokens: map[string]*types.MCPOAuthToken{},
}
}
func fakeOAuthKey(tenantID uint64, principal types.Principal, serviceID string) string {
return fmt.Sprintf("%d|%s|%s", tenantID, principal.Normalize().StorageID(), serviceID)
}
func (r *fakeOAuthRepo) GetClient(
_ context.Context, tenantID uint64, serviceID string,
) (*types.MCPOAuthClient, error) {
return r.clients[fmt.Sprintf("%d|%s", tenantID, serviceID)], nil
}
func (r *fakeOAuthRepo) SaveClient(_ context.Context, client *types.MCPOAuthClient) error {
r.clients[fmt.Sprintf("%d|%s", client.TenantID, client.ServiceID)] = client
return nil
}
func (r *fakeOAuthRepo) DeleteClient(_ context.Context, tenantID uint64, serviceID string) error {
delete(r.clients, fmt.Sprintf("%d|%s", tenantID, serviceID))
return nil
}
func (r *fakeOAuthRepo) GetToken(
ctx context.Context, tenantID uint64, userID, serviceID string,
) (*types.MCPOAuthToken, error) {
return r.GetTokenForPrincipal(ctx, tenantID, types.Principal{Type: types.PrincipalWebUser, ID: userID}, serviceID)
}
func (r *fakeOAuthRepo) GetTokenForPrincipal(
_ context.Context, tenantID uint64, principal types.Principal, serviceID string,
) (*types.MCPOAuthToken, error) {
return r.tokens[fakeOAuthKey(tenantID, principal, serviceID)], nil
}
func (r *fakeOAuthRepo) SaveToken(_ context.Context, token *types.MCPOAuthToken) error {
return r.SaveTokenForPrincipal(context.Background(), token)
}
func (r *fakeOAuthRepo) SaveTokenForPrincipal(_ context.Context, token *types.MCPOAuthToken) error {
principal := types.Principal{Type: token.PrincipalType, ID: token.PrincipalID}.Normalize()
if !principal.Valid() {
principal = types.Principal{Type: types.PrincipalWebUser, ID: token.UserID}.Normalize()
}
r.tokens[fakeOAuthKey(token.TenantID, principal, token.ServiceID)] = token
return nil
}
func (r *fakeOAuthRepo) DeleteToken(
ctx context.Context, tenantID uint64, userID, serviceID string,
) error {
return r.DeleteTokenForPrincipal(ctx, tenantID, types.Principal{Type: types.PrincipalWebUser, ID: userID}, serviceID)
}
func (r *fakeOAuthRepo) DeleteTokenForPrincipal(
_ context.Context, tenantID uint64, principal types.Principal, serviceID string,
) error {
delete(r.tokens, fakeOAuthKey(tenantID, principal, serviceID))
return nil
}
func TestDBTokenStoreUsesPrincipal(t *testing.T) {
repo := newFakeOAuthRepo()
principal := types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:external-42"}
store := newDBTokenStore(repo, 7, principal, "svc-1")
expiresAt := time.Now().Add(time.Hour).UTC()
require.NoError(t, store.SaveToken(context.Background(), &transport.Token{
AccessToken: "access",
RefreshToken: "refresh",
TokenType: "Bearer",
ExpiresAt: expiresAt,
}))
row, err := repo.GetTokenForPrincipal(context.Background(), 7, principal, "svc-1")
require.NoError(t, err)
require.NotNil(t, row)
require.Equal(t, types.PrincipalAPIExternalUser, row.PrincipalType)
require.Equal(t, "7:external-42", row.PrincipalID)
require.Equal(t, principal.StorageID(), row.UserID)
token, err := store.GetToken(context.Background())
require.NoError(t, err)
require.Equal(t, "access", token.AccessToken)
require.Equal(t, "refresh", token.RefreshToken)
require.Equal(t, expiresAt, token.ExpiresAt)
}
func TestOAuthCacheKeyUsesPrincipalForOAuthServices(t *testing.T) {
service := &types.MCPService{
ID: "svc-1",
AuthConfig: &types.MCPAuthConfig{AuthType: types.MCPAuthOAuth},
}
alice := types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:alice"}
bob := types.Principal{Type: types.PrincipalAPIExternalUser, ID: "7:bob"}
require.NotEqual(t, cacheKey(service, alice), cacheKey(service, bob))
require.Contains(t, cacheKey(service, alice), alice.StorageID())
service.AuthConfig.AuthType = types.MCPAuthAPIKey
require.Equal(t, "svc-1", cacheKey(service, alice))
require.Equal(t, cacheKey(service, alice), cacheKey(service, bob))
}
+8 -6
View File
@@ -9,6 +9,7 @@ import (
"sync"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/redis/go-redis/v9"
)
@@ -22,12 +23,13 @@ const oauthStateTTL = 10 * time.Minute
// authorization server — hence server-side storage rather than encoding it
// into the state parameter.
type OAuthState struct {
TenantID uint64 `json:"tenant_id"`
UserID string `json:"user_id"`
ServiceID string `json:"service_id"`
CodeVerifier string `json:"code_verifier"`
ClientID string `json:"client_id"`
RedirectURI string `json:"redirect_uri"`
TenantID uint64 `json:"tenant_id"`
UserID string `json:"user_id"`
Principal types.Principal `json:"principal"`
ServiceID string `json:"service_id"`
CodeVerifier string `json:"code_verifier"`
ClientID string `json:"client_id"`
RedirectURI string `json:"redirect_uri"`
// FrontendRedirect is where the backend callback redirects the browser
// after completing (or failing) the exchange.
FrontendRedirect string `json:"frontend_redirect"`
+22 -14
View File
@@ -10,22 +10,27 @@ import (
)
// dbTokenStore is a transport.TokenStore backed by the MCPOAuthRepository,
// scoped to a single (tenant, user, service) tuple. The mcp-go OAuth handler
// scoped to a single (tenant, principal, service) tuple. The mcp-go OAuth handler
// calls GetToken before each request (refreshing via refresh_token when
// expired) and SaveToken after a successful authorization or refresh, so this
// store transparently persists refreshed tokens back to the database.
type dbTokenStore struct {
repo interfaces.MCPOAuthRepository
tenantID uint64
userID string
principal types.Principal
serviceID string
}
// newDBTokenStore creates a per-user, per-service token store.
// newDBTokenStore creates a per-principal, per-service token store.
func newDBTokenStore(
repo interfaces.MCPOAuthRepository, tenantID uint64, userID, serviceID string,
repo interfaces.MCPOAuthRepository, tenantID uint64, principal types.Principal, serviceID string,
) *dbTokenStore {
return &dbTokenStore{repo: repo, tenantID: tenantID, userID: userID, serviceID: serviceID}
return &dbTokenStore{
repo: repo,
tenantID: tenantID,
principal: principal.Normalize(),
serviceID: serviceID,
}
}
// GetToken returns the persisted token, or transport.ErrNoToken when the user
@@ -34,7 +39,7 @@ func (s *dbTokenStore) GetToken(ctx context.Context) (*transport.Token, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
row, err := s.repo.GetToken(ctx, s.tenantID, s.userID, s.serviceID)
row, err := s.repo.GetTokenForPrincipal(ctx, s.tenantID, s.principal, s.serviceID)
if err != nil {
return nil, err
}
@@ -58,13 +63,16 @@ func (s *dbTokenStore) SaveToken(ctx context.Context, token *transport.Token) er
if expiresAt.IsZero() && token.ExpiresIn > 0 {
expiresAt = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second)
}
return s.repo.SaveToken(ctx, &types.MCPOAuthToken{
TenantID: s.tenantID,
UserID: s.userID,
ServiceID: s.serviceID,
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
TokenType: token.TokenType,
ExpiresAt: expiresAt,
principal := s.principal.Normalize()
return s.repo.SaveTokenForPrincipal(ctx, &types.MCPOAuthToken{
TenantID: s.tenantID,
PrincipalType: principal.Type,
PrincipalID: principal.ID,
UserID: principal.StorageID(),
ServiceID: s.serviceID,
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
TokenType: token.TokenType,
ExpiresAt: expiresAt,
})
}
+139 -1
View File
@@ -3,6 +3,7 @@ package middleware
import (
"context"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
"log"
@@ -16,6 +17,12 @@ import (
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
const (
defaultExternalUserIDHeader = "X-External-User-ID"
defaultExternalUserTokenHeader = "X-External-User-Token"
)
// 无需认证的API列表
@@ -40,7 +47,7 @@ var noAuthAPI = map[string][]string{
// redirects the browser here without a WeKnora bearer token. The request
// is authenticated by the opaque, single-use `state` parameter instead.
"/api/v1/mcp-oauth/callback": {"GET"},
"/api/v1/auth/refresh": {"POST"},
"/api/v1/auth/refresh": {"POST"},
// IM platforms (Feishu, Slack, etc.) commonly issue a HEAD request
// before GET to validate Content-Type / Content-Length when rendering
// image previews — both verbs must be allowed for image links to work.
@@ -181,8 +188,11 @@ func Auth(
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenant)
ctx = context.WithValue(ctx, types.UserContextKey, user)
ctx = context.WithValue(ctx, types.UserIDContextKey, user.ID)
principal := types.Principal{Type: types.PrincipalWebUser, ID: user.ID}
ctx = types.WithPrincipal(ctx, principal)
ctx = context.WithValue(ctx, types.TenantRoleContextKey, role)
ctx = context.WithValue(ctx, types.SystemAdminContextKey, user.IsSystemAdmin)
c.Set(types.PrincipalContextKey.String(), principal)
c.Request = c.Request.WithContext(ctx)
c.Next()
return
@@ -259,10 +269,20 @@ func Auth(
// 平台管理必须走交互式 JWT 登录,留下可追责的人类身份。
c.Set(types.UserContextKey.String(), user)
c.Set(types.UserIDContextKey.String(), user.ID)
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",
})
c.Abort()
return
}
c.Set(types.PrincipalContextKey.String(), principal)
c.Set(types.TenantRoleContextKey.String(), types.TenantRoleAdmin)
c.Set(types.SystemAdminContextKey.String(), false)
ctx = context.WithValue(ctx, types.UserContextKey, user)
ctx = context.WithValue(ctx, types.UserIDContextKey, user.ID)
ctx = types.WithPrincipal(ctx, principal)
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleAdmin)
ctx = context.WithValue(ctx, types.SystemAdminContextKey, false)
@@ -277,6 +297,124 @@ func Auth(
}
}
func resolveAPIPrincipal(ctx context.Context, tenant *types.Tenant, header http.Header) (types.Principal, error) {
tenantID := uint64(0)
if tenant != nil {
tenantID = tenant.ID
}
fallback := types.Principal{
Type: types.PrincipalAPITenant,
ID: strconv.FormatUint(tenantID, 10),
}
if tenant == nil || tenantID == 0 {
return fallback, nil
}
cfg := tenant.APIPrincipalConfig
if cfg == nil || cfg.Mode == "" || cfg.Mode == types.APIPrincipalModeTenant {
return fallback, nil
}
switch cfg.Mode {
case types.APIPrincipalModeDirect:
name := strings.TrimSpace(cfg.DirectHeaderName)
if name == "" {
name = defaultExternalUserIDHeader
}
externalUserID := strings.TrimSpace(header.Get(name))
if externalUserID == "" {
return fallback, nil
}
return types.Principal{
Type: types.PrincipalAPIExternalUser,
ID: strconv.FormatUint(tenantID, 10) + ":" + externalUserID,
}, nil
case types.APIPrincipalModeSignedToken:
name := strings.TrimSpace(cfg.SignedTokenHeaderName)
if name == "" {
name = defaultExternalUserTokenHeader
}
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{
Type: types.PrincipalAPIExternalUser,
ID: strconv.FormatUint(tenantID, 10) + ":" + externalUserID,
}, nil
default:
return fallback, nil
}
}
func verifyExternalUserJWT(tokenString string, tenantID uint64, secret string) (string, error) {
tokenString = strings.TrimSpace(tokenString)
secret = strings.TrimSpace(secret)
if tokenString == "" {
return "", errors.New("missing external user token")
}
if secret == "" {
return "", errors.New("external user token secret is not configured")
}
claims := jwt.MapClaims{}
parser := jwt.NewParser(jwt.WithAudience("weknora"), jwt.WithExpirationRequired())
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"])
}
return []byte(secret), nil
})
if err != nil {
return "", err
}
if token == nil || !token.Valid {
return "", errors.New("invalid external user token")
}
if got := principalTenantIDFromClaims(claims); got != tenantID {
return "", fmt.Errorf("tenant mismatch: got %d want %d", got, tenantID)
}
sub, _ := claims["sub"].(string)
sub = strings.TrimSpace(sub)
if sub == "" {
return "", errors.New("missing subject")
}
return sub, nil
}
func principalTenantIDFromClaims(claims jwt.MapClaims) uint64 {
v, ok := claims["tenant_id"]
if !ok {
return 0
}
switch t := v.(type) {
case float64:
if t <= 0 {
return 0
}
return uint64(t)
case int64:
if t <= 0 {
return 0
}
return uint64(t)
case uint64:
return t
case json.Number:
n, err := strconv.ParseUint(t.String(), 10, 64)
if err != nil {
return 0
}
return n
case string:
n, err := strconv.ParseUint(strings.TrimSpace(t), 10, 64)
if err != nil {
return 0
}
return n
default:
return 0
}
}
// resolveTenantRole determines the caller's TenantRole inside targetTenantID.
//
// Order of resolution:
@@ -0,0 +1,123 @@
package middleware
import (
"context"
"net/http"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/golang-jwt/jwt/v5"
)
func signedExternalUserToken(t *testing.T, secret string, claims jwt.MapClaims) string {
t.Helper()
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(secret))
if err != nil {
t.Fatalf("sign token: %v", err)
}
return token
}
func TestResolveAPIPrincipalDefaultsToTenant(t *testing.T) {
p, err := resolveAPIPrincipal(context.Background(), &types.Tenant{ID: 7}, http.Header{})
if err != nil {
t.Fatalf("resolveAPIPrincipal error = %v", err)
}
if p.Type != types.PrincipalAPITenant || p.ID != "7" {
t.Fatalf("principal = %#v", p)
}
}
func TestResolveAPIPrincipalDirectHeader(t *testing.T) {
header := http.Header{}
header.Set("X-External-User-ID", "external-u1")
p, err := resolveAPIPrincipal(context.Background(), &types.Tenant{
ID: 7,
APIPrincipalConfig: &types.APIPrincipalConfig{
Mode: types.APIPrincipalModeDirect,
},
}, header)
if err != nil {
t.Fatalf("resolveAPIPrincipal error = %v", err)
}
if p.Type != types.PrincipalAPIExternalUser || p.ID != "7:external-u1" {
t.Fatalf("principal = %#v", p)
}
}
func TestResolveAPIPrincipalSignedToken(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(time.Minute).Unix(),
}))
p, err := resolveAPIPrincipal(context.Background(), &types.Tenant{
ID: 7,
APIPrincipalConfig: &types.APIPrincipalConfig{
Mode: types.APIPrincipalModeSignedToken,
HMACSecret: secret,
},
}, header)
if err != nil {
t.Fatalf("resolveAPIPrincipal error = %v", err)
}
if p.Type != types.PrincipalAPIExternalUser || p.ID != "7:external-u1" {
t.Fatalf("principal = %#v", p)
}
}
func TestResolveAPIPrincipalSignedTokenRejectsWrongTenant(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(8),
"aud": "weknora",
"exp": time.Now().Add(time.Minute).Unix(),
}))
p, 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")
}
_ = p
}
func TestResolveAPIPrincipalSignedTokenRejectsExpired(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(-time.Minute).Unix(),
}))
p, 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")
}
_ = p
}
+6
View File
@@ -162,11 +162,16 @@ func EmbedAuth(
TenantID: ch.TenantID,
IsActive: true,
}
principal := types.Principal{
Type: types.PrincipalEmbedChannel,
ID: fmt.Sprintf("%d:%s", ch.TenantID, ch.ID),
}
c.Set(types.TenantIDContextKey.String(), ch.TenantID)
c.Set(types.TenantInfoContextKey.String(), tenant)
c.Set(types.UserContextKey.String(), user)
c.Set(types.UserIDContextKey.String(), user.ID)
c.Set(types.PrincipalContextKey.String(), principal)
c.Set(types.TenantRoleContextKey.String(), types.TenantRoleViewer)
c.Set(types.SystemAdminContextKey.String(), false)
c.Set(string(EmbedChannelContextKey), ch)
@@ -176,6 +181,7 @@ func EmbedAuth(
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenant)
ctx = context.WithValue(ctx, types.UserContextKey, user)
ctx = context.WithValue(ctx, types.UserIDContextKey, user.ID)
ctx = types.WithPrincipal(ctx, principal)
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
ctx = context.WithValue(ctx, types.SystemAdminContextKey, false)
ctx = context.WithValue(ctx, EmbedChannelContextKey, ch)
+2
View File
@@ -571,6 +571,8 @@ func RegisterTenantRoutes(
tenantByID.PUT("", g.Owner(), handler.UpdateTenant)
tenantByID.DELETE("", g.Owner(), handler.DeleteTenant)
tenantByID.POST("/api-key", g.Owner(), handler.ResetAPIKey)
tenantByID.GET("/api-principal-config", g.Owner(), handler.GetAPIPrincipalConfig)
tenantByID.PUT("/api-principal-config", g.Owner(), handler.UpdateAPIPrincipalConfig)
// Tenant member management (PR 3 of #1303). Listing is
// Viewer+ so any active member can see the roster; mutation
+2
View File
@@ -16,6 +16,8 @@ const (
UserContextKey ContextKey = "User"
// UserIDContextKey is the context key for user ID
UserIDContextKey ContextKey = "UserID"
// PrincipalContextKey is the context key for the terminal caller principal.
PrincipalContextKey ContextKey = "Principal"
// TenantRoleContextKey is the context key for the caller's TenantRole
// in the currently active tenant (loaded by the auth middleware from
// the tenant_members table). See TenantRoleFromContext.
+13 -1
View File
@@ -7,7 +7,7 @@ import (
)
// MCPOAuthRepository persists OAuth clients (per service) and tokens
// (per user + service) for the MCP OAuth2 authorization-code flow.
// (per principal + service) for the MCP OAuth2 authorization-code flow.
type MCPOAuthRepository interface {
// GetClient returns the registered OAuth client for a service, or
// (nil, nil) when none has been registered yet.
@@ -23,10 +23,22 @@ type MCPOAuthRepository interface {
// (nil, nil) when the user has not authorized yet.
GetToken(ctx context.Context, tenantID uint64, userID, serviceID string) (*types.MCPOAuthToken, error)
// GetTokenForPrincipal returns the stored token for (tenant, principal, service),
// or (nil, nil) when the principal has not authorized yet.
GetTokenForPrincipal(
ctx context.Context, tenantID uint64, principal types.Principal, serviceID string,
) (*types.MCPOAuthToken, error)
// SaveToken creates or updates the per-user token for a service.
SaveToken(ctx context.Context, token *types.MCPOAuthToken) error
// SaveTokenForPrincipal creates or updates the per-principal token for a service.
SaveTokenForPrincipal(ctx context.Context, token *types.MCPOAuthToken) error
// DeleteToken removes the per-user token for a service (revoke /
// re-authorize).
DeleteToken(ctx context.Context, tenantID uint64, userID, serviceID string) error
// DeleteTokenForPrincipal removes the per-principal token for a service.
DeleteTokenForPrincipal(ctx context.Context, tenantID uint64, principal types.Principal, serviceID string) error
}
+15 -13
View File
@@ -68,23 +68,25 @@ func (m *MCPOAuthClient) encryptSecret() {
}
}
// MCPOAuthToken stores a per-user OAuth token for an MCP service. The agent
// connects to the MCP server on behalf of the invoking user, so tokens are
// isolated by (tenant_id, user_id, service_id).
// MCPOAuthToken stores a per-principal OAuth token for an MCP service. The
// agent connects to the MCP server on behalf of the invoking principal, so
// tokens are isolated by (tenant_id, principal_type, principal_id, service_id).
//
// AccessToken and RefreshToken are encrypted at rest (AES-256-GCM) when
// SYSTEM_AES_KEY is configured.
type MCPOAuthToken struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_user_svc"`
UserID string `json:"user_id" gorm:"type:varchar(64);not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_user_svc;index"`
ServiceID string `json:"service_id" gorm:"type:varchar(36);not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_user_svc;index"`
AccessToken string `json:"-" gorm:"type:text"`
RefreshToken string `json:"-" gorm:"type:text"`
TokenType string `json:"token_type" gorm:"type:varchar(32)"`
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_principal_svc"`
UserID string `json:"user_id" gorm:"type:varchar(512);not null;index"`
PrincipalType string `json:"principal_type" gorm:"type:varchar(32);not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_principal_svc;index"`
PrincipalID string `json:"principal_id" gorm:"type:varchar(512);not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_principal_svc;index"`
ServiceID string `json:"service_id" gorm:"type:varchar(36);not null;uniqueIndex:idx_mcp_oauth_tokens_tenant_principal_svc;index"`
AccessToken string `json:"-" gorm:"type:text"`
RefreshToken string `json:"-" gorm:"type:text"`
TokenType string `json:"token_type" gorm:"type:varchar(32)"`
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// TableName pins the table name (see MCPOAuthClient.TableName); the default
+65
View File
@@ -0,0 +1,65 @@
package types
import (
"context"
"strings"
)
const (
PrincipalWebUser = "web_user"
PrincipalAPITenant = "api_tenant"
PrincipalAPIUser = "api_user"
PrincipalAPIExternalUser = "api_external_user"
PrincipalIMUser = "im_user"
PrincipalEmbedChannel = "embed_channel"
PrincipalEmbedSession = "embed_session"
)
// Principal represents the terminal caller for per-subject isolation features.
// It is intentionally separate from UserID: many principals, such as IM users
// or embed visitors, are not WeKnora accounts and must not imply RBAC rights.
type Principal struct {
Type string
ID string
}
func (p Principal) Normalize() Principal {
return Principal{
Type: strings.TrimSpace(p.Type),
ID: strings.TrimSpace(p.ID),
}
}
func (p Principal) Valid() bool {
p = p.Normalize()
return p.Type != "" && p.ID != ""
}
func (p Principal) StorageID() string {
p = p.Normalize()
if !p.Valid() {
return ""
}
return p.Type + ":" + p.ID
}
func WithPrincipal(ctx context.Context, principal Principal) context.Context {
principal = principal.Normalize()
if !principal.Valid() {
return ctx
}
return context.WithValue(ctx, PrincipalContextKey, principal)
}
func PrincipalFromContext(ctx context.Context) (Principal, bool) {
if ctx == nil {
return Principal{}, false
}
if p, ok := ctx.Value(PrincipalContextKey).(Principal); ok && p.Valid() {
return p.Normalize(), true
}
if uid, ok := UserIDFromContext(ctx); ok && strings.TrimSpace(uid) != "" {
return Principal{Type: PrincipalWebUser, ID: uid}, true
}
return Principal{}, false
}
+34
View File
@@ -0,0 +1,34 @@
package types
import (
"context"
"testing"
)
func TestPrincipalFromContextFallsBackToWebUser(t *testing.T) {
ctx := context.WithValue(context.Background(), UserIDContextKey, "u1")
p, ok := PrincipalFromContext(ctx)
if !ok {
t.Fatal("expected principal")
}
if p.Type != PrincipalWebUser || p.ID != "u1" {
t.Fatalf("principal = %#v", p)
}
}
func TestWithPrincipalRejectsBlankValues(t *testing.T) {
ctx := WithPrincipal(context.Background(), Principal{Type: " ", ID: "x"})
if _, ok := PrincipalFromContext(ctx); ok {
t.Fatal("blank principal type should not be stored")
}
}
func TestPrincipalStorageID(t *testing.T) {
p := Principal{Type: PrincipalIMUser, ID: "wecom:ch1:u1"}
if got := p.StorageID(); got != "im_user:wecom:ch1:u1" {
t.Fatalf("StorageID() = %q", got)
}
}
+55
View File
@@ -116,6 +116,8 @@ type Tenant struct {
ChatHistoryConfig *ChatHistoryConfig `yaml:"chat_history_config" json:"chat_history_config" gorm:"type:jsonb"`
// Retrieval config: global search/retrieval parameters shared by knowledge search and message search
RetrievalConfig *RetrievalConfig `yaml:"retrieval_config" json:"retrieval_config" gorm:"type:jsonb"`
// API principal config: controls how X-API-Key requests map to terminal principals.
APIPrincipalConfig *APIPrincipalConfig `yaml:"api_principal_config" json:"-" gorm:"type:jsonb"`
// Creation time
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// Last updated time
@@ -215,6 +217,59 @@ type WeKnoraCloudCredentials struct {
AppSecret string `json:"app_secret"`
}
type APIPrincipalMode string
const (
APIPrincipalModeTenant APIPrincipalMode = "tenant"
APIPrincipalModeDirect APIPrincipalMode = "direct_header"
APIPrincipalModeSignedToken APIPrincipalMode = "signed_token"
)
// APIPrincipalConfig controls how tenant API-key requests map to terminal
// principals. Direct header mode is low-assurance and should only be used for
// trusted server-to-server calls; signed-token mode verifies the user claim.
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"`
}
func (c *APIPrincipalConfig) Value() (driver.Value, error) {
if c == nil {
return nil, nil
}
cp := *c
if cp.HMACSecret != "" {
if key := utils.GetAESKey(); key != nil {
if encrypted, err := utils.EncryptAESGCM(cp.HMACSecret, key); err == nil {
cp.HMACSecret = encrypted
}
}
}
return json.Marshal(&cp)
}
func (c *APIPrincipalConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
if err := json.Unmarshal(b, c); err != nil {
return err
}
if plain, ok := utils.DecryptStoredSecretLenient(c.HMACSecret); ok {
c.HMACSecret = plain
} else {
log.Printf("[crypto] tenant api_principal_config.hmac_secret: decrypt failed (SYSTEM_AES_KEY missing/rotated?), treating as unconfigured")
c.HMACSecret = ""
}
return nil
}
// GetWeKnoraCloud returns the WeKnoraCloud credentials, or nil if not configured.
func (c *CredentialsConfig) GetWeKnoraCloud() *WeKnoraCloudCredentials {
if c == nil || c.WeKnoraCloud == nil {
@@ -0,0 +1,12 @@
DROP INDEX IF EXISTS idx_mcp_oauth_tokens_principal;
DROP INDEX IF EXISTS idx_mcp_oauth_tokens_tenant_principal_svc;
ALTER TABLE mcp_oauth_tokens
ALTER COLUMN user_id TYPE VARCHAR(64) USING LEFT(user_id, 64);
CREATE UNIQUE INDEX IF NOT EXISTS idx_mcp_oauth_tokens_tenant_user_svc
ON mcp_oauth_tokens(tenant_id, user_id, service_id);
ALTER TABLE mcp_oauth_tokens
DROP COLUMN IF EXISTS principal_id,
DROP COLUMN IF EXISTS principal_type;
@@ -0,0 +1,29 @@
DO $$ BEGIN RAISE NOTICE '[Migration 000064] Adding principal columns to MCP OAuth tokens...'; END $$;
ALTER TABLE mcp_oauth_tokens
ADD COLUMN IF NOT EXISTS principal_type VARCHAR(32),
ADD COLUMN IF NOT EXISTS principal_id VARCHAR(512);
ALTER TABLE mcp_oauth_tokens
ALTER COLUMN user_id TYPE VARCHAR(512);
UPDATE mcp_oauth_tokens
SET principal_type = 'web_user',
principal_id = user_id
WHERE (principal_type IS NULL OR principal_type = '')
AND user_id IS NOT NULL
AND user_id <> '';
ALTER TABLE mcp_oauth_tokens
ALTER COLUMN principal_type SET NOT NULL,
ALTER COLUMN principal_id SET NOT NULL;
DROP INDEX IF EXISTS idx_mcp_oauth_tokens_tenant_user_svc;
CREATE UNIQUE INDEX IF NOT EXISTS idx_mcp_oauth_tokens_tenant_principal_svc
ON mcp_oauth_tokens(tenant_id, principal_type, principal_id, service_id);
CREATE INDEX IF NOT EXISTS idx_mcp_oauth_tokens_principal
ON mcp_oauth_tokens(principal_type, principal_id);
DO $$ BEGIN RAISE NOTICE '[Migration 000064] MCP OAuth principal columns ready'; END $$;
@@ -0,0 +1,2 @@
ALTER TABLE tenants
DROP COLUMN IF EXISTS api_principal_config;
@@ -0,0 +1,6 @@
DO $$ BEGIN RAISE NOTICE '[Migration 000065] Adding tenant API principal config...'; END $$;
ALTER TABLE tenants
ADD COLUMN IF NOT EXISTS api_principal_config JSONB;
DO $$ BEGIN RAISE NOTICE '[Migration 000065] tenant API principal config ready'; END $$;