From 043e0485e2b5cceb6584b83401c96e242270554a Mon Sep 17 00:00:00 2001 From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com> Date: Fri, 27 Nov 2026 14:49:06 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E6=9D=83=E9=99=90=E4=BC=98=E5=8C=96)1.AI?= =?UTF-8?q?=E5=AF=B9=E8=AF=9D=E4=B8=AD=E7=82=B9=E5=87=BB=E5=BF=AB=E6=8D=B7?= =?UTF-8?q?=E6=A0=87=E7=AD=BE=E9=97=AE=E9=A2=98=E6=97=B6=EF=BC=8C=E6=98=8E?= =?UTF-8?q?=E6=98=8E=E5=B7=B2=E7=BB=8F=E9=85=8D=E7=BD=AE=E4=BA=86=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E9=BB=98=E5=86=99=E4=B8=BA=E4=BB=80=E4=B9=88=E8=BF=98?= =?UTF-8?q?=E4=BC=9A=E6=8F=90=E7=A4=BA=E9=85=8D=E7=BD=AE=EF=BC=9F=E5=BF=85?= =?UTF-8?q?=E9=A1=BB=E7=82=B9=E5=87=BB=E4=B8=80=E4=B8=8B=E4=BF=9D=E5=AD=98?= =?UTF-8?q?=E5=B9=B6=E5=85=B3=E9=97=AD=E6=89=8D=E5=8F=AF=E4=BB=A5=E8=BF=99?= =?UTF-8?q?=E4=B8=AA=E4=B8=8D=E5=AF=B9=EF=BC=8C=E5=8F=AA=E8=A6=81=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E4=BA=86=E5=B0=B1=E5=8F=AF=E4=BB=A5=E9=97=AE=E7=AD=94?= =?UTF-8?q?=E4=B8=8D=E9=9C=80=E8=A6=81=E5=86=8D=E8=AE=A9=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E8=BF=87=E6=9D=A5=E7=82=B9=E5=87=BB=E4=B8=80=E6=AC=A1=EF=BC=81?= =?UTF-8?q?=E5=A6=82=E5=9B=BE=E4=B8=80=E3=80=81=E4=BA=8C=E6=89=80=E7=A4=BA?= =?UTF-8?q?=202.=E7=9F=A5=E8=AF=86=E5=BA=93=E4=B8=AD=E7=9A=84=E4=BC=81?= =?UTF-8?q?=E4=B8=9A=E5=9F=B9=E8=AE=AD=EF=BC=88=E8=AF=BE=E4=BB=B6=EF=BC=89?= =?UTF-8?q?=E3=80=81=E4=BC=81=E4=B8=9A=E5=9F=B9=E8=AE=AD=EF=BC=88=E8=AF=95?= =?UTF-8?q?=E9=A2=98=EF=BC=89=E3=80=81=E9=85=8D=E7=BD=AE=E4=B8=AD=E5=BF=83?= =?UTF-8?q?=E3=80=81=E7=BB=84=E7=BB=87=E6=9E=B6=E6=9E=84=E3=80=81=E5=85=B1?= =?UTF-8?q?=E4=BA=AB=E7=A9=BA=E9=97=B4=E5=A6=82=E5=9B=BE=E4=B8=89=E6=89=80?= =?UTF-8?q?=E7=A4=BA=E5=8F=AF=E6=9F=A5=E7=9C=8B=E6=9D=83=E9=99=90=E5=BD=92?= =?UTF-8?q?=E5=B1=9E=E5=88=B0=E8=B6=85=E7=BA=A7=E7=AE=A1=E7=90=86=E5=91=98?= =?UTF-8?q?=E6=9D=83=E9=99=90=E4=B8=AD=EF=BC=81=E5=A6=82=E4=BD=95=E5=AF=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/components/AgentSelector.vue | 1 + frontend/src/components/Input-field.vue | 1 + frontend/src/components/menu.vue | 8 +- frontend/src/router/index.ts | 13 +- frontend/src/stores/menu.ts | 7 +- frontend/src/utils/agent-readiness.test.mjs | 68 +++++++- frontend/src/utils/agent-readiness.ts | 53 ++++-- frontend/src/views/org-center/OrgCenter.vue | 6 +- frontend/src/views/training/Training.vue | 6 +- internal/application/service/user.go | 77 +++++---- .../service/user_oidc_shared_space_test.go | 155 ++++++++++++++++++ .../service/user_oidc_verify_test.go | 11 +- internal/handler/knowledgebase.go | 20 +++ internal/types/custom_agent.go | 16 +- 14 files changed, 368 insertions(+), 74 deletions(-) diff --git a/frontend/src/components/AgentSelector.vue b/frontend/src/components/AgentSelector.vue index 2a3ef49..57c3e94 100644 --- a/frontend/src/components/AgentSelector.vue +++ b/frontend/src/components/AgentSelector.vue @@ -393,6 +393,7 @@ const getAgentNotReadyReasonKeysFor = (agent: CustomAgent, sourceTenantId?: stri return getAgentNotReadyReasonKeys(agent.config, modelsList.value, { isAgentMode, isSharedAgent, + isBuiltin: agent.is_builtin, }); }; diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue index 7f0ec83..3a2c86e 100644 --- a/frontend/src/components/Input-field.vue +++ b/frontend/src/components/Input-field.vue @@ -2598,6 +2598,7 @@ const collectAgentNotReadyReasons = ( const keys = getAgentNotReadyReasonKeys(agent.config, allModels.value, { isAgentMode, isSharedAgent, + isBuiltin: agent.is_builtin, }); return { keys, diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue index 7f77e01..933d50f 100644 --- a/frontend/src/components/menu.vue +++ b/frontend/src/components/menu.vue @@ -605,12 +605,14 @@ const moreToolItems = computed(() => { const items = MORE_TOOLS_ORDER .map(path => all.find((item: MenuItem) => item.path === path)) .filter((item): item is MenuItem => !!item); - // 末位固定追加「配置中心」「组织架构」;「共享空间」还原至最底 - // (入口定义与显隐规则仍在 menu store:仅空间 admin/owner 可见,随能力清单显隐) + // 末位追加「配置中心」「组织架构」(000163 权限收口:仅平台超级管理员可见, + // 页面另由路由 requiresSystemAdmin 守卫兜底);「共享空间」还原至最底 + // (入口定义与显隐规则仍在 menu store:仅超管可见,随能力清单显隐) // 职称角色入口已移除:职称角色/企微账号维护并入「组织架构」页,旧路由 // /platform/training/members 由路由重定向兜底 const orgShareItem = all.find((item: MenuItem) => item.path === 'organizations'); - return [...items, RULES_TOOL_ITEM, ORG_CENTER_TOOL_ITEM, ...(orgShareItem ? [orgShareItem] : [])]; + const adminOnlyItems = authStore.isSystemAdmin ? [RULES_TOOL_ITEM, ORG_CENTER_TOOL_ITEM] : []; + return [...items, ...adminOnlyItems, ...(orgShareItem ? [orgShareItem] : [])]; }); // 菜单图标统一映射:顶层项与「更多工具」子项共用 diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 4de6db5..f6eccd1 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -208,10 +208,11 @@ const router = createRouter({ { // 组织架构:租户级共享组织架构(部门 + 员工档案), // 业务模块(企业培训等)按需引用,部门岗位只维护一份。 + // 000163 权限收口:仅平台超级管理员可查看(菜单入口同步收口)。 path: "org-center", name: "orgCenter", component: () => import("../views/org-center/OrgCenter.vue"), - meta: { requiresInit: true, requiresAuth: true } + meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true } }, { path: "agents", @@ -258,7 +259,8 @@ const router = createRouter({ path: "organizations", name: "organizationList", component: () => import("../views/organization/OrganizationList.vue"), - meta: { requiresInit: true, requiresAuth: true, requiredCapability: 'organizations' } + // 000163 权限收口:共享空间仅平台超级管理员可查看(菜单入口同步收口)。 + meta: { requiresInit: true, requiresAuth: true, requiredCapability: 'organizations', requiresSystemAdmin: true } }, // Compatibility redirects for /platform/system/* URLs. System // administration surfaces live as dedicated sections inside the @@ -468,6 +470,13 @@ router.beforeEach(async (to, from, next) => { } } + // 培训路由按 tab 共用(training/:tab),「配置中心」(rules) 页签单独收口: + // 仅平台超级管理员可查看,其余用户弹回培训工作台(000163)。 + if (to.name === 'trainingTab' && String(to.params.tab) === 'rules' && !authStore.isSystemAdmin) { + next('/platform/training/dashboard') + return + } + next() }) diff --git a/frontend/src/stores/menu.ts b/frontend/src/stores/menu.ts index cf3afcf..9506eec 100644 --- a/frontend/src/stores/menu.ts +++ b/frontend/src/stores/menu.ts @@ -76,9 +76,8 @@ export const useMenuStore = defineStore('menuStore', () => { const liteHiddenPaths = new Set(['logout', 'organizations']) - // 共享空间 (organizations) 仅对当前空间的 admin / owner 暴露入口。 - // viewer / contributor 即便在共享空间里拥有资源,也无需自行管理共享关系, - // 入口在侧栏只会徒增噪音;后端 RBAC 才是权限的最终来源(见 middleware/rbac.go)。 + // 共享空间 (organizations) 仅对平台超级管理员暴露入口(000163 权限收口: + // 原为空间 admin/owner 可见)。后端 RBAC 才是权限的最终来源(见 middleware/rbac.go)。 const visibleMenuArr = computed(() => { const authStore = useAuthStore() const deploymentCapabilities = useDeploymentCapabilitiesStore() @@ -86,7 +85,7 @@ export const useMenuStore = defineStore('menuStore', () => { if (authStore.isLiteMode && liteHiddenPaths.has(item.path)) { return false } - if (item.path === 'organizations' && !authStore.hasRole('admin')) { + if (item.path === 'organizations' && !authStore.isSystemAdmin) { return false } if (!deploymentCapabilities.isSupported(item.requiredCapability)) { diff --git a/frontend/src/utils/agent-readiness.test.mjs b/frontend/src/utils/agent-readiness.test.mjs index 748e4ea..08243f5 100644 --- a/frontend/src/utils/agent-readiness.test.mjs +++ b/frontend/src/utils/agent-readiness.test.mjs @@ -9,10 +9,29 @@ import { resolveAgentNotReadyHighlight, } from './agent-readiness.ts' -test('does not treat an unrelated built-in chat model as agent configuration', () => { +test('an empty model_id falls back to the workspace default chat model', () => { + // Built-in agents are seeded without model_id; the run resolves the + // workspace default, so they are ready as long as one exists. assert.equal(agentHasConfiguredChatModel( {}, [{ id: 'builtin-chat', type: 'KnowledgeQA' }], + ), true) +}) + +test('an empty model_id is not ready when the workspace has no KnowledgeQA model', () => { + assert.equal(agentHasConfiguredChatModel( + {}, + [{ id: 'embed-1', type: 'Embedding' }], + ), false) + assert.equal(agentHasConfiguredChatModel({}, []), false) +}) + +test('an empty model_id stays unready for shared agents', () => { + // The model belongs to the source tenant; existence is validated backend-side. + assert.equal(agentHasConfiguredChatModel( + {}, + [{ id: 'builtin-chat', type: 'KnowledgeQA' }], + true, ), false) }) @@ -110,25 +129,62 @@ test('resolveAgentNotReadyHighlight returns the first missing item', () => { assert.equal(resolveAgentNotReadyHighlight([]), undefined) }) -test('getAgentNotReadyReasonKeys flags missing chat model', () => { +test('getAgentNotReadyReasonKeys flags a missing chat model only without a workspace default', () => { + // No KnowledgeQA model in the workspace: nothing to fall back to. + assert.deepEqual(getAgentNotReadyReasonKeys( + {}, + [], + { isAgentMode: false, isSharedAgent: false }, + ), ['summary_model']) + // Workspace default exists: the empty model_id resolves at run time. assert.deepEqual(getAgentNotReadyReasonKeys( {}, [{ id: 'chat-1', type: 'KnowledgeQA' }], { isAgentMode: false, isSharedAgent: false }, + ), []) + // Shared agents must declare an explicit model; cannot validate locally. + assert.deepEqual(getAgentNotReadyReasonKeys( + {}, + [{ id: 'chat-1', type: 'KnowledgeQA' }], + { isAgentMode: false, isSharedAgent: true }, ), ['summary_model']) }) test('getAgentNotReadyReasonKeys requires rerank only in agent mode with KB search', () => { assert.deepEqual(getAgentNotReadyReasonKeys( - { kb_selection_mode: 'all', allowed_tools: ['search_knowledge'] }, + { model_id: 'chat-1', kb_selection_mode: 'all', allowed_tools: ['search_knowledge'] }, [{ id: 'chat-1', type: 'KnowledgeQA' }, { id: 'rerank-1', type: 'Rerank' }], { isAgentMode: true, isSharedAgent: false }, - ), ['summary_model', 'rerank_model']) + ), ['rerank_model']) assert.deepEqual(getAgentNotReadyReasonKeys( - { kb_selection_mode: 'all', allowed_tools: ['knowledge_search'] }, + { model_id: 'chat-1', kb_selection_mode: 'all', allowed_tools: ['knowledge_search'] }, [{ id: 'chat-1', type: 'KnowledgeQA' }, { id: 'rerank-1', type: 'Rerank' }], { isAgentMode: true, isSharedAgent: false }, - ), ['summary_model', 'rerank_model']) + ), ['rerank_model']) +}) + +test('built-in agents fall back to the workspace rerank without a reason', () => { + // Mirrors session_agent_qa.go: empty rerank on a builtin resolves from the + // workspace (or searches without reranking) instead of blocking the run. + assert.deepEqual(getAgentNotReadyReasonKeys( + { model_id: 'chat-1', kb_selection_mode: 'all', allowed_tools: ['search_knowledge'] }, + [{ id: 'chat-1', type: 'KnowledgeQA' }, { id: 'rerank-1', type: 'Rerank' }], + { isAgentMode: true, isSharedAgent: false, isBuiltin: true }, + ), []) + // Even with no rerank model at all: builtin searches without reranking. + assert.deepEqual(getAgentNotReadyReasonKeys( + { model_id: 'chat-1', kb_selection_mode: 'all', allowed_tools: ['search_knowledge'] }, + [{ id: 'chat-1', type: 'KnowledgeQA' }], + { isAgentMode: true, isSharedAgent: false, isBuiltin: true }, + ), []) +}) + +test('custom agents without a rerank model stay flagged', () => { + assert.deepEqual(getAgentNotReadyReasonKeys( + { model_id: 'chat-1', kb_selection_mode: 'all', allowed_tools: ['search_knowledge'] }, + [{ id: 'chat-1', type: 'KnowledgeQA' }, { id: 'rerank-1', type: 'Rerank' }], + { isAgentMode: true, isSharedAgent: false, isBuiltin: false }, + ), ['rerank_model']) }) test('getAgentNotReadyReasonKeys does not treat current shared context as shared without sourceTenantId', () => { diff --git a/frontend/src/utils/agent-readiness.ts b/frontend/src/utils/agent-readiness.ts index 518c1e4..cec3587 100644 --- a/frontend/src/utils/agent-readiness.ts +++ b/frontend/src/utils/agent-readiness.ts @@ -1,28 +1,47 @@ import type { CustomAgentConfig } from '@/api/agent' import type { ModelConfig } from '@/api/model' import { allowedToolsInclude } from './legacy-tool-names' +import { selectInitialModelId } from './modelDefaults' export type AgentNotReadyReasonKey = 'summary_model' | 'rerank_model' | 'allowed_tools' /** - * An agent is chat-ready only when it explicitly references a usable chat - * model. Merely having some built-in/default model in the tenant must not hide - * incomplete agent configuration. + * An agent is chat-ready when it references a usable chat model, or when it + * may fall back to the workspace default: an empty model_id is resolved at run + * time from the agent's knowledge base or the workspace's default KnowledgeQA + * model (backend UsesWorkspaceModelFallback + selectChatModelID), so a local + * agent without an explicit model is ready as long as the workspace has a + * usable default. Only a model_id that points at a missing/non-KnowledgeQA + * model counts as incomplete configuration. * * For shared agents the model belongs to the source tenant, so the caller can * require a non-empty ID but must leave existence validation to the backend. */ export function agentHasConfiguredChatModel( config: Pick | undefined, - models: Pick[], + models: Pick[], sourceModelIsRemote = false, ): boolean { const modelID = config?.model_id?.trim() - if (!modelID) return false + if (!modelID) { + if (sourceModelIsRemote) return false + return hasWorkspaceDefaultChatModel(models) + } if (sourceModelIsRemote) return true return models.some(model => model.type === 'KnowledgeQA' && model.id === modelID) } +/** + * Workspace default chat model: the declared KnowledgeQA default, else the + * first active KnowledgeQA model — same rule as the backend's + * PickDefaultModelID and the agent editor's auto pre-fill. + */ +export function hasWorkspaceDefaultChatModel( + models: Pick[], +): boolean { + return selectInitialModelId(models, 'KnowledgeQA') != null +} + /** * Keep this aligned with backend agentRequiresRerankModel. * @@ -50,8 +69,8 @@ export function getAgentNotReadyReasonKeys( CustomAgentConfig, 'model_id' | 'rerank_model_id' | 'kb_selection_mode' | 'allowed_tools' | 'agent_mode' > | undefined, - models: Pick[], - options: { isAgentMode: boolean; isSharedAgent: boolean }, + models: Pick[], + options: { isAgentMode: boolean; isSharedAgent: boolean; isBuiltin?: boolean }, ): AgentNotReadyReasonKey[] { const reasons: AgentNotReadyReasonKey[] = [] @@ -61,12 +80,20 @@ export function getAgentNotReadyReasonKeys( if (options.isAgentMode && agentRequiresRerankModel(config)) { const rerankModelID = config?.rerank_model_id?.trim() - const rerankExists = !!rerankModelID && ( - options.isSharedAgent - || models.some(model => model.type === 'Rerank' && model.id === rerankModelID) - ) - if (!rerankExists) { - reasons.push('rerank_model') + if (!rerankModelID) { + // Built-in agents are seeded without a rerank model; the run falls back + // to the workspace rerank (or searches without reranking) instead of + // blocking, mirroring session_agent_qa.go's UsesWorkspaceModelFallback + // branch. Custom agents must declare their own rerank model. + if (!options.isBuiltin || options.isSharedAgent) { + reasons.push('rerank_model') + } + } else { + const rerankExists = options.isSharedAgent + || models.some(model => model.type === 'Rerank' && model.id === rerankModelID) + if (!rerankExists) { + reasons.push('rerank_model') + } } } diff --git a/frontend/src/views/org-center/OrgCenter.vue b/frontend/src/views/org-center/OrgCenter.vue index 1687708..617130d 100644 --- a/frontend/src/views/org-center/OrgCenter.vue +++ b/frontend/src/views/org-center/OrgCenter.vue @@ -367,9 +367,9 @@ const roleDict = ref([]) // 本人职称角色(权限门控口径与培训页一致:人事/经理/空间管理员可维护) const rawRoles = ref([]) const myRoles = computed(() => expandRoles(rawRoles.value, roleDict.value)) -const canManage = computed( - () => authStore.hasRole('admin') || myRoles.value.some((r) => r === 'hr' || r === 'exec'), -) +// 000163 权限收口:组织架构页仅平台超级管理员可查看/维护 +// (路由 requiresSystemAdmin 守卫为主,此处为页面内兜底)。 +const canManage = computed(() => authStore.isSystemAdmin) const rolesVisible = ref(false) const activeEmployee = ref(null) diff --git a/frontend/src/views/training/Training.vue b/frontend/src/views/training/Training.vue index 4259d56..fc5eba4 100644 --- a/frontend/src/views/training/Training.vue +++ b/frontend/src/views/training/Training.vue @@ -130,9 +130,9 @@ const canManageTabs = computed(() => isAdmin.value || myRoles.value.some((r) => ['hr', 'supervisor', 'exec', 'lecturer', 'super_admin'].includes(r))) -// 配置中心门槛(000158):人事/空间管理员之外,经理职称角色同权查看与维护。 -const canManageConfig = computed(() => - isAdmin.value || myRoles.value.some((r) => r === 'exec')) +// 配置中心门槛(000163 权限收口):仅平台超级管理员可查看与维护 +// (菜单入口/路由守卫同步收口,此处为页面内兜底)。 +const canManageConfig = computed(() => authStore.isSystemAdmin) // 页头角色标签:展示实际分配的角色(非权限展开),文案取自配置中心字典 const myRoleLabel = computed(() => diff --git a/internal/application/service/user.go b/internal/application/service/user.go index c414b3d..5ee39cd 100644 --- a/internal/application/service/user.go +++ b/internal/application/service/user.go @@ -579,11 +579,10 @@ func (s *userService) finishOIDCLogin( } isNewUser := false if isUserLookupNotFound(err) || user == nil { - // 老账号自愈:占位邮箱曾按 sub(可能是长 UUID)合成,规则已改为 - // 工号优先。同一 Casdoor 用户下次登录时按 email 查不到,会落到 - // 这里——先按 username(工号)找回老账号,把它改成新短邮箱,避免 - // 重复开户。仅当命中账号确属 OIDC 开户且现邮箱是同域占位邮箱时 - // 才收编。 + // 老账号自愈:按 email 查不到时(占位邮箱规则变更,或导入/手建 + // 账号与 IdP 邮箱前缀不一致),先按 username(工号)收编活跃老 + // 账号并归一邮箱,避免重复开户分裂出 26040006-1 式账号。收编 + // 条件见 adoptOIDCUserByUsername。 user = s.adoptOIDCUserByUsername(ctx, userInfo) if user == nil { user, err = s.provisionOIDCUser(ctx, userInfo, provisioning) @@ -2188,27 +2187,22 @@ func (s *userService) provisionOIDCUser( return user, nil } -// adoptOIDCUserByUsername 收编按旧规则开户的 OIDC 老账号。占位邮箱曾按 -// sub(可能是长 UUID)合成;规则改为工号优先后,同一 Casdoor 用户下次 -// 登录按 email 查不到,这里按 username(工号)找回老账号并改写为短邮箱, -// 避免重复开户。收编条件全部满足才生效: +// adoptOIDCUserByUsername 工号收编:按 email 查不到时(占位邮箱规则变更, +// 或导入/手建账号与 IdP 邮箱前缀不一致),按 username(工号)找回本地老 +// 账号,根治同一工号分裂出 "26040006-1" 式重复账号——OIDC 首登自动开户 +// 撞上已占用工号后会顺延 -1/-2 后缀。收编条件全部满足才生效: // 1. username 精确命中本地账号且账号活跃; -// 2. 该账号是 OIDC 开户(OidcOnlyLogin); -// 3. 现邮箱是同兜底域的占位邮箱; -// 4. 新邮箱(本次登录刚按新规则合成,查询未命中)必然未被占用。 +// 2. 本地邮箱可信:是同兜底域的占位邮箱,或与 IdP 邮箱同域(同一企业 +// 的两种邮箱形态,如 26040006@corp ↔ sun.kai@corp);完全无关的 +// 外部邮箱不收编; +// 3. 新邮箱(本次登录 IdP 返回/合成,finishOIDCLogin 已查询未命中)必然 +// 未被占用,直接改写本地邮箱完成归一。 // -// 返回 nil 表示无可收编账号,调用方按新用户正常开户。失败仅告警,不阻塞登录。 +// 收编不再要求账号是 OIDC 开户(OidcOnlyLogin):导入开户与手工开户的 +// 工号账号同样认回。返回 nil 表示无可收编账号,调用方按新用户正常开户。 +// 失败仅告警,不阻塞登录。 func (s *userService) adoptOIDCUserByUsername(ctx context.Context, info *types.OIDCUserInfo) *types.User { - if s.config == nil || s.config.OIDCAuth == nil || s.userRepo == nil { - return nil - } - fallbackDomain := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(s.config.OIDCAuth.EmailFallbackDomain), "@")) - if fallbackDomain == "" { - return nil - } - if strings.Contains(info.Email, "@") && - !strings.HasSuffix(strings.ToLower(info.Email), "@"+fallbackDomain) { - // IdP 返回了真实邮箱,不涉及占位邮箱改写。 + if s.userRepo == nil { return nil } candidate := sanitizeUsernameCandidate(info.Username) @@ -2219,10 +2213,11 @@ func (s *userService) adoptOIDCUserByUsername(ctx context.Context, info *types.O if err != nil || existing == nil || !existing.IsActive { return nil } - if existing.Preferences.OidcOnlyLogin == nil || !*existing.Preferences.OidcOnlyLogin { - return nil + fallbackDomain := "" + if s.config != nil && s.config.OIDCAuth != nil { + fallbackDomain = strings.ToLower(strings.TrimPrefix(strings.TrimSpace(s.config.OIDCAuth.EmailFallbackDomain), "@")) } - if !strings.HasSuffix(strings.ToLower(existing.Email), "@"+fallbackDomain) { + if !adoptableOIDCEmail(existing.Email, info.Email, fallbackDomain) { return nil } if info.Email == "" || info.Email == existing.Email { @@ -2234,13 +2229,39 @@ func (s *userService) adoptOIDCUserByUsername(ctx context.Context, info *types.O existing.DisplayName = displayName } if err := s.userRepo.UpdateUser(ctx, existing); err != nil { - logger.Warnf(ctx, "OIDC placeholder-email adoption failed for user %s: %v", existing.ID, err) + logger.Warnf(ctx, "OIDC username adoption failed for user %s: %v", existing.ID, err) return nil } - logger.Infof(ctx, "OIDC placeholder email rewritten: user %s email → %s", existing.ID, existing.Email) + logger.Infof(ctx, "OIDC account adopted by username: user %s email → %s", existing.ID, existing.Email) return existing } +// adoptableOIDCEmail 判断本地账号邮箱是否可信、可被 OIDC 工号收编: +// - 同兜底域的占位邮箱(OIDC/导入开户按 <工号>@兜底域 合成);或 +// - 与 IdP 邮箱同域。 +// +// 其余(无关外部邮箱)不收编,避免把陌生账号错认给登录者。 +func adoptableOIDCEmail(existingEmail, idpEmail, fallbackDomain string) bool { + existingDomain := emailDomain(existingEmail) + if existingDomain == "" { + return false + } + if fallbackDomain != "" && existingDomain == fallbackDomain { + return true + } + return existingDomain == emailDomain(idpEmail) +} + +// emailDomain 取小写域名;无 @、@ 顶头/收尾视为畸形,返回空串。 +func emailDomain(value string) string { + value = strings.ToLower(strings.TrimSpace(value)) + at := strings.LastIndex(value, "@") + if at <= 0 || at == len(value)-1 { + return "" + } + return value[at+1:] +} + // refreshOIDCDisplayName 让姓名跟随 IdP:登录时若 claim 姓名变化则更新。 // 失败仅告警,不阻塞登录。 func (s *userService) refreshOIDCDisplayName(ctx context.Context, user *types.User, info *types.OIDCUserInfo) { diff --git a/internal/application/service/user_oidc_shared_space_test.go b/internal/application/service/user_oidc_shared_space_test.go index c5e192b..de5603a 100644 --- a/internal/application/service/user_oidc_shared_space_test.go +++ b/internal/application/service/user_oidc_shared_space_test.go @@ -457,3 +457,158 @@ func TestFinishOIDCLoginRefreshesDisplayName(t *testing.T) { t.Fatalf("UpdateUser calls = %d, want 1 (refresh persisted)", len(repo.updated)) } } + +// Regression for the 192-environment duplicate: a roster-imported 工号 account +// (real email, NOT OIDC-marked) whose email prefix differs from the IdP email +// must be adopted on first SSO login — not split into a fresh 26040006-1. +func TestFinishOIDCLoginAdoptsImportedAccountWithSameDomainEmail(t *testing.T) { + imported := &types.User{ + ID: "26040006", + Username: "26040006", + Email: "26040006@hxzh.com", // 导入开户的真实邮箱,前缀与 IdP 不同 + TenantID: 6, + IsActive: true, + } + + repo := &sharedSpaceUserRepo{ + getUserByEmail: nil, // IdP 邮箱按 email 查未命中 + byUsername: map[string]*types.User{"26040006": imported}, + } + memberSvc := &sharedSpaceMemberSvc{membersByUser: []*types.TenantMember{ + {UserID: "26040006", TenantID: 6, Role: types.TenantRoleOwner, Status: types.TenantMemberStatusActive}, + }} + svc := newSharedSpaceService(t, false, repo, memberSvc, &sharedSpaceInvitationSvc{}, &sharedSpaceTenantSvc{}) + svc.config = oidcTestConfig() + svc.tokenRepo = &stubAuthTokenRepo{} + + resp, err := svc.finishOIDCLogin(context.Background(), &types.OIDCUserInfo{ + Username: "26040006", + Email: "sun.kai@hxzh.com", // IdP 真实邮箱,同域不同前缀 + DisplayName: "孙凯", + }, types.TenantProvisioningCreatePersonal) + if err != nil { + t.Fatalf("finishOIDCLogin: %v", err) + } + if !resp.Success || resp.User == nil || resp.User.ID != "26040006" { + t.Fatalf("expected imported account adoption, got resp=%+v", resp) + } + if resp.IsNewUser { + t.Fatal("adoption must not be reported as a new user (26040006-1 regression)") + } + if resp.User.Email != "sun.kai@hxzh.com" { + t.Fatalf("email not normalized to IdP value: %s", resp.User.Email) + } + if len(repo.updated) == 0 { + t.Fatal("adoption must persist the rewritten account") + } +} + +func TestAdoptOIDCUserByUsernamePlaceholderWithoutOidcMark(t *testing.T) { + // 占位邮箱但从未标过 OidcOnlyLogin(早期手工开户):工号命中即可收编。 + existing := &types.User{ + ID: "26040006", Username: "26040006", + Email: "26040006@casdoor.local", IsActive: true, + } + repo := &sharedSpaceUserRepo{ + byUsername: map[string]*types.User{"26040006": existing}, + } + svc := &userService{userRepo: repo, config: oidcTestConfig()} + + adopted := svc.adoptOIDCUserByUsername(context.Background(), &types.OIDCUserInfo{ + Username: "26040006", + Email: "sun.kai@hxzh.com", + }) + if adopted == nil || adopted.ID != "26040006" { + t.Fatalf("expected adoption, got %+v", adopted) + } + if len(repo.updated) != 1 || repo.updated[0].Email != "sun.kai@hxzh.com" { + t.Fatalf("email rewrite not persisted: %+v", repo.updated) + } +} + +func TestAdoptOIDCUserByUsernameRejectsUnrelatedEmail(t *testing.T) { + // 本地邮箱是完全无关的外部邮箱(不同域、非占位):不收编,避免把 + // 陌生账号错认给登录者。 + existing := &types.User{ + ID: "26040006", Username: "26040006", + Email: "someone@gmail.com", IsActive: true, + } + repo := &sharedSpaceUserRepo{ + byUsername: map[string]*types.User{"26040006": existing}, + } + svc := &userService{userRepo: repo, config: oidcTestConfig()} + + adopted := svc.adoptOIDCUserByUsername(context.Background(), &types.OIDCUserInfo{ + Username: "26040006", + Email: "sun.kai@hxzh.com", + }) + if adopted != nil { + t.Fatalf("unrelated email must not be adopted, got %+v", adopted) + } + if len(repo.updated) != 0 { + t.Fatalf("no writes expected, got %+v", repo.updated) + } +} + +func TestAdoptOIDCUserByUsernameRejectsInactiveAccount(t *testing.T) { + existing := &types.User{ + ID: "26040006", Username: "26040006", + Email: "26040006@hxzh.com", IsActive: false, + } + repo := &sharedSpaceUserRepo{ + byUsername: map[string]*types.User{"26040006": existing}, + } + svc := &userService{userRepo: repo, config: oidcTestConfig()} + + adopted := svc.adoptOIDCUserByUsername(context.Background(), &types.OIDCUserInfo{ + Username: "26040006", + Email: "sun.kai@hxzh.com", + }) + if adopted != nil { + t.Fatalf("inactive account must not be adopted, got %+v", adopted) + } +} + +func TestAdoptOIDCUserByUsernameSameDomainWithoutFallbackDomain(t *testing.T) { + // 未配置兜底域时占位邮箱分支不可用,但同域收编仍然生效。 + existing := &types.User{ + ID: "26040006", Username: "26040006", + Email: "26040006@hxzh.com", IsActive: true, + } + repo := &sharedSpaceUserRepo{ + byUsername: map[string]*types.User{"26040006": existing}, + } + svc := &userService{userRepo: repo} // config 为 nil + + adopted := svc.adoptOIDCUserByUsername(context.Background(), &types.OIDCUserInfo{ + Username: "26040006", + Email: "sun.kai@hxzh.com", + }) + if adopted == nil || adopted.ID != "26040006" { + t.Fatalf("same-domain adoption must work without fallback domain, got %+v", adopted) + } +} + +func TestAdoptableOIDCEmail(t *testing.T) { + cases := []struct { + name string + existingEmail string + idpEmail string + fallback string + want bool + }{ + {"placeholder in fallback domain", "26040006@casdoor.local", "sun.kai@hxzh.com", "casdoor.local", true}, + {"same domain as idp", "26040006@hxzh.com", "sun.kai@hxzh.com", "casdoor.local", true}, + {"same domain without fallback config", "26040006@hxzh.com", "sun.kai@hxzh.com", "", true}, + {"unrelated external email", "someone@gmail.com", "sun.kai@hxzh.com", "casdoor.local", false}, + {"malformed existing email", "not-an-email", "sun.kai@hxzh.com", "casdoor.local", false}, + {"empty existing email", "", "sun.kai@hxzh.com", "casdoor.local", false}, + {"case-insensitive domain match", "26040006@HXZH.com", "sun.kai@hxzh.com", "", true}, + } + for _, tc := range cases { + if got := adoptableOIDCEmail(tc.existingEmail, tc.idpEmail, tc.fallback); got != tc.want { + t.Errorf("%s: adoptableOIDCEmail(%q, %q, %q) = %v, want %v", + tc.name, tc.existingEmail, tc.idpEmail, tc.fallback, got, tc.want) + } + } +} diff --git a/internal/application/service/user_oidc_verify_test.go b/internal/application/service/user_oidc_verify_test.go index 49327f8..eec59b1 100644 --- a/internal/application/service/user_oidc_verify_test.go +++ b/internal/application/service/user_oidc_verify_test.go @@ -405,9 +405,10 @@ func TestResolveOIDCUserInfo_VerifiedIDTokenUsedWhenUserinfoFails(t *testing.T) } } -// 工号式 IdP(邮箱选填):id_token 无 email claim 时,配置了兜底域则用已验签 -// 的 sub 合成稳定占位邮箱,工号(name claim)继续作为 username。 -func TestResolveOIDCUserInfo_EmailFallbackSynthesizedFromSub(t *testing.T) { +// 工号式 IdP(邮箱选填):id_token 无 email claim 时,配置了兜底域则合成 +// 稳定占位邮箱。合成 local part 工号(username claim)优先、sub 仅在 +// username 为空时回落——工号比 Casdoor 可能的长 UUID sub 更短更稳定。 +func TestResolveOIDCUserInfo_EmailFallbackSynthesizedFromUsername(t *testing.T) { withOIDCSSRFWhitelist(t, "127.0.0.1") key, err := rsa.GenerateKey(rand.Reader, 2048) @@ -430,8 +431,8 @@ func TestResolveOIDCUserInfo_EmailFallbackSynthesizedFromSub(t *testing.T) { if err != nil { t.Fatalf("resolveOIDCUserInfo: %v", err) } - if info.Email != "built-in_10001@casdoor.local" { - t.Fatalf("email = %q, want synthesized from sub", info.Email) + if info.Email != "10001@casdoor.local" { + t.Fatalf("email = %q, want synthesized from 工号 username", info.Email) } if info.Username != "10001" { t.Fatalf("username = %q, want 工号 from name claim", info.Username) diff --git a/internal/handler/knowledgebase.go b/internal/handler/knowledgebase.go index 6583063..ece3cf5 100644 --- a/internal/handler/knowledgebase.go +++ b/internal/handler/knowledgebase.go @@ -582,6 +582,12 @@ func (h *KnowledgeBaseHandler) GetKnowledgeBase(c *gin.Context) { c.Error(err) return } + // 企业培训系统默认库(课件/题库)仅超级管理员可查看,防止绕过列表过滤 + // 直连详情接口。普通用户的课件/题库读写走培训业务接口(服务端同步)。 + if kb.IsTrainingDefaultKB() && !types.IsSystemAdminFromContext(c.Request.Context()) { + c.Error(apperrors.NewForbiddenError("企业培训系统知识库仅超级管理员可查看")) + return + } // Fill counts (knowledge_count, chunk_count, is_processing) so hover/detail shows correct numbers if fillErr := h.service.FillKnowledgeBaseCounts(c.Request.Context(), kb); fillErr != nil { logger.Warnf(c.Request.Context(), "Failed to fill KB counts for %s: %v", kb.ID, fillErr) @@ -660,6 +666,20 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) { return } + // 企业培训系统默认库(课件/题库)仅超级管理员可见:普通用户走业务模块 + // (课程上传/题库导入)由服务端同步,无需在知识库列表直接浏览这两个库。 + // 列表计数(@提及/智能体编辑器的知识库选择同源)随本过滤一并收口。 + if !types.IsSystemAdminFromContext(ctx) { + filtered := make([]*types.KnowledgeBase, 0, len(kbs)) + for _, kb := range kbs { + if kb.IsTrainingDefaultKB() { + continue + } + filtered = append(filtered, kb) + } + kbs = filtered + } + // Optional creator filter — drives the [All | Mine | Others] segmented // control on the list page. We filter in-process rather than pushing // down into SQL because the tenant-bounded KB list is small (typically diff --git a/internal/types/custom_agent.go b/internal/types/custom_agent.go index 6a7b5f8..ab69ead 100644 --- a/internal/types/custom_agent.go +++ b/internal/types/custom_agent.go @@ -51,14 +51,16 @@ func GrantsProductDocs(agent *CustomAgent) bool { return agent != nil && agent.IsBuiltin && agent.ID == BuiltinAcademyAssistantID } -// UsesWorkspaceModelFallback reports whether a built-in agent runs without -// its own model_id and rerank_model_id. These agents are hidden from agent -// management, so a user cannot configure them; the run resolves the chat -// model from its knowledge base or the system KnowledgeQA default, and the -// rerank model from the workspace. +// UsesWorkspaceModelFallback reports whether an agent may run without its own +// model_id and rerank_model_id. Built-in agents are seeded from +// config/builtin_agents.yaml with no model ids; the agent editor only +// pre-fills the workspace default into the form, so until the user saves once +// the persisted config stays empty. Rather than blocking the first chat with +// "chat model is not configured", the run resolves the chat model from the +// agent's knowledge base or the system KnowledgeQA default, and the rerank +// model from the workspace. func UsesWorkspaceModelFallback(agent *CustomAgent) bool { - return agent != nil && agent.IsBuiltin && - (agent.ID == BuiltinWikiFixerID || agent.ID == BuiltinAcademyAssistantID) + return agent != nil && agent.IsBuiltin } // RunsInSharedKBWorkspace reports whether a built-in agent opened on one