Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(rbac): role-aware UI gates leaked write affordances after tenant switch
wizardchen1a46fcf8cac4
diff --git a/frontend/src/App.vue b/frontend/src/App.vueindex ac9c7286a..aa40b0c89 100644--- a/frontend/src/App.vue+++ b/frontend/src/App.vue@@ -46,7 +46,7 @@ const syncOIDCUserContext = async () => {throw new Error(currentUserResponse.message || 'Failed to get user information')}- const { user, tenant } = currentUserResponse.data+ const { user, tenant, memberships } = currentUserResponse.dataauthStore.setUser({id: user.id || '',username: user.username || '',@@ -72,6 +72,13 @@ const syncOIDCUserContext = async () => {updated_at: tenant.updated_at || new Date().toISOString()})}+ // Refresh memberships so currentTenantRole reflects any role change+ // since the last login (e.g. an Owner demoted us to Viewer in a+ // peer tenant). Without this, memberships stay frozen at the+ // login-time snapshot and the UI silently lies about our authority.+ if (Array.isArray(memberships)) {+ authStore.setMemberships(memberships)+ }}const persistOIDCLoginResponse = async (response: any) => {diff --git a/frontend/src/api/auth/index.ts b/frontend/src/api/auth/index.tsindex 2ec1ebcb4..5a28361aa 100644--- a/frontend/src/api/auth/index.ts+++ b/frontend/src/api/auth/index.ts@@ -111,6 +111,10 @@ export interface KnowledgeBaseInfo {name: stringdescription: stringtenant_id: string+ // creator_id is the user id of whoever originally created the KB.+ // Set by PR 5 of the multi-tenant RBAC series; nullable for legacy+ // KBs created before that migration backfilled the column.+ creator_id?: stringcreated_at: stringupdated_at: stringdocument_count?: number@@ -228,13 +232,26 @@ export async function autoSetup(): Promise<LoginResponse> {}}+/**+ * Membership row returned alongside /auth/me. Mirrors the LoginResponse+ * shape so the frontend can refresh `currentTenantRole` on every page+ * load — without it, role changes after login (e.g. an Owner demoting+ * us in a peer tenant) stay invisible until the user logs out and back+ * in.+ */+export interface MembershipInfo {+ tenant_id: number+ tenant_name?: string+ role: string+}+/*** 获取当前用户信息*/-export async function getCurrentUser(): Promise<{ success: boolean; data?: { user: UserInfo; tenant?: TenantInfo | null }; message?: string }> {+export async function getCurrentUser(): Promise<{ success: boolean; data?: { user: UserInfo; tenant?: TenantInfo | null; memberships?: MembershipInfo[] }; message?: string }> {try {const response = await get('/api/v1/auth/me')- return response as unknown as { success: boolean; data?: { user: UserInfo; tenant?: TenantInfo | null }; message?: string }+ return response as unknown as { success: boolean; data?: { user: UserInfo; tenant?: TenantInfo | null; memberships?: MembershipInfo[] }; message?: string }} catch (error: any) {return {success: false,diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.tsindex ae9ced414..34b0b2d6b 100644--- a/frontend/src/router/index.ts+++ b/frontend/src/router/index.ts@@ -228,6 +228,16 @@ async function hydrateSessionFromToken(authStore: ReturnType<typeof useAuthStore})}+ // Refresh memberships on every page load — same reason as+ // App.vue's syncOIDCUserContext: without this the auth store+ // would only ever see the snapshot from the original /auth/login+ // call, so role changes (and tenant-switch role lookups) would+ // be silently stale until the user logged out and back in.+ const memberships = response.data?.memberships+ if (Array.isArray(memberships)) {+ authStore.setMemberships(memberships)+ }+return true} catch {return falsediff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.tsindex 8d9608d71..bed7c37d3 100644--- a/frontend/src/stores/auth.ts+++ b/frontend/src/stores/auth.ts@@ -60,6 +60,13 @@ export const useAuthStore = defineStore('auth', () => {// role-aware UI gating; PR 2 wires backend enforcement, PR 3 uses// this for menu/button visibility.//+ // It MUST read effectiveTenantId, not tenant.value.id. tenant.value is+ // the user's home tenant (set once on login from /auth/me's tenant+ // field); selectedTenantId is the active override applied by the+ // tenant switcher. Reading the wrong field used to leak Owner-level+ // UI to a Viewer who switched into a tenant where they were a Viewer+ // — every gate above (`hasRole(...)`) returned the home-tenant role.+ //// SECURITY: This value is read from localStorage (`weknora_memberships`)// and therefore MUST be treated as UI-rendering-only — any user can// tamper with localStorage and grant themselves "owner" here. All real@@ -67,7 +74,12 @@ export const useAuthStore = defineStore('auth', () => {// the role from tenant_members on every request). Never branch// security-sensitive logic on this value alone.const currentTenantRole = computed(() => {- const tid = tenant.value?.id ? String(tenant.value.id) : ''+ const tid =+ selectedTenantId.value !== null && selectedTenantId.value !== undefined+ ? String(selectedTenantId.value)+ : tenant.value?.id+ ? String(tenant.value.id)+ : ''if (!tid) return ''const match = memberships.value.find((m) => String(m.tenant_id) === tid)return match?.role || ''diff --git a/frontend/src/utils/request.ts b/frontend/src/utils/request.tsindex 767b5ebb7..31f548f92 100644--- a/frontend/src/utils/request.ts+++ b/frontend/src/utils/request.ts@@ -37,20 +37,18 @@ instance.interceptors.request.use(// 添加用户语言偏好config.headers["Accept-Language"] = getCurrentLanguage();- // 添加跨租户访问请求头(如果选择了其他租户)+ // 添加跨租户访问请求头:只要 setSelectedTenant 写过激活租户,+ // 每个请求都要附 X-Tenant-ID。早期版本会 short-circuit+ // "selectedTenantId === defaultTenantId 时不附"以减少 header 体积,+ // 但这条优化会被任何把 weknora_tenant 写成激活租户的代码(OIDC+ // 回调、UserMenu loadUserInfo、router hydrate)触发,导致后续请求+ // 静默丢失 header,前端"切换了"但实际仍跑在 home 租户里——把"切+ // 换之后只有第一批请求带 X-Tenant-ID"调成永久状态。+ // 后端 IsTenantAccessible 已经允许 header 指向 home 租户(自家),+ // 所以无脑附不会引入新风险。const selectedTenantId = localStorage.getItem('weknora_selected_tenant_id');- const defaultTenantId = localStorage.getItem('weknora_tenant');if (selectedTenantId) {- try {- const defaultTenant = defaultTenantId ? JSON.parse(defaultTenantId) : null;- const defaultId = defaultTenant?.id ? String(defaultTenant.id) : null;- // 如果选择的租户ID与默认租户ID不同,添加请求头- if (selectedTenantId !== defaultId) {- config.headers["X-Tenant-ID"] = selectedTenantId;- }- } catch (e) {- console.error('Failed to parse tenant info', e);- }+ config.headers["X-Tenant-ID"] = selectedTenantId;}config.headers["X-Request-ID"] = `${generateRandomString(12)}`;diff --git a/frontend/src/views/agent/AgentList.vue b/frontend/src/views/agent/AgentList.vueindex 98f1f4a46..435642d71 100644--- a/frontend/src/views/agent/AgentList.vue+++ b/frontend/src/views/agent/AgentList.vue@@ -103,13 +103,13 @@</div><template #content><div class="popup-menu">- <div class="popup-menu-item" @click="handleEdit(agent)"><t-icon class="menu-icon" name="edit" /><span>{{ $t('common.edit') }}</span></div>- <div class="popup-menu-item" @click="handleCopy(agent)"><t-icon class="menu-icon" name="file-copy" /><span>{{ $t('common.copy') }}</span></div>+ <div v-if="canManageAgent(agent)" class="popup-menu-item" @click="handleEdit(agent)"><t-icon class="menu-icon" name="edit" /><span>{{ $t('common.edit') }}</span></div>+ <div v-if="authStore.hasRole('contributor')" class="popup-menu-item" @click="handleCopy(agent)"><t-icon class="menu-icon" name="file-copy" /><span>{{ $t('common.copy') }}</span></div><div v-if="!agent.is_builtin" class="popup-menu-item" @click="handleToggleDisabled(agent)"><t-icon class="menu-icon" name="poweroff" /><span>{{ agent.disabled_by_me ? $t('agent.enable') : $t('agent.disable') }}</span></div>- <div v-if="!agent.is_builtin" class="popup-menu-item delete" @click="handleDelete(agent)"><t-icon class="menu-icon" name="delete" /><span>{{ $t('common.delete') }}</span></div>+ <div v-if="!agent.is_builtin && canManageAgent(agent)" class="popup-menu-item delete" @click="handleDelete(agent)"><t-icon class="menu-icon" name="delete" /><span>{{ $t('common.delete') }}</span></div></div></template></t-popup>@@ -243,11 +243,11 @@</div><template #content><div class="popup-menu">- <div class="popup-menu-item" @click="handleEdit(agent)">+ <div v-if="canManageAgent(agent)" class="popup-menu-item" @click="handleEdit(agent)"><t-icon class="menu-icon" name="edit" /><span>{{ $t('common.edit') }}</span></div>- <div class="popup-menu-item" @click="handleCopy(agent)">+ <div v-if="authStore.hasRole('contributor')" class="popup-menu-item" @click="handleCopy(agent)"><t-icon class="menu-icon" name="file-copy" /><span>{{ $t('common.copy') }}</span></div>@@ -255,7 +255,7 @@<t-icon class="menu-icon" name="poweroff" /><span>{{ agent.disabled_by_me ? $t('agent.enable') : $t('agent.disable') }}</span></div>- <div v-if="!agent.is_builtin" class="popup-menu-item delete" @click="handleDelete(agent)">+ <div v-if="!agent.is_builtin && canManageAgent(agent)" class="popup-menu-item delete" @click="handleDelete(agent)"><t-icon class="menu-icon" name="delete" /><span>{{ $t('common.delete') }}</span></div>@@ -845,6 +845,20 @@ const handleEdit = (agent: AgentWithUI) => {editorVisible.value = true}+// canManageAgent mirrors the server-side OwnedAgentOrAdmin guard+// (PR 5 #1303): the agent's creator may always edit / delete; otherwise+// Admin+ is required. Built-in agents have created_by="" → only Admin++// matches, which lines up with the "Admin can mutate tenant-owned+// agents" rule. The server still enforces the same matrix on every+// mutation; this gate just hides buttons the user has no authority+// to use.+function canManageAgent(agent: AgentWithUI): boolean {+ const userId = authStore.user?.id || ''+ const creatorId = (agent as any).created_by || ''+ if (creatorId && userId && creatorId === userId) return true+ return authStore.hasRole('admin')+}+const handleDelete = (agent: AgentWithUI) => {openMoreAgentId.value = nulldeletingAgent.value = agentdiff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vueindex 6f300c7e9..923f37e51 100644--- a/frontend/src/views/knowledge/KnowledgeBase.vue+++ b/frontend/src/views/knowledge/KnowledgeBase.vue@@ -193,21 +193,42 @@ const goToParserSettings = () => {}// Permission control: check if current user owns this KB or has edit/manage permission+//+// "Owner" here is "the original creator of this KB" (PR 5 introduced+// CreatorID). The previous version compared kb.tenant_id to the active+// tenant id, which only answers "is this KB inside our tenant" — that+// is true even for a Viewer in someone else's tenant, so the gate+// silently bypassed every role check below. Now we require an explicit+// creator match, and the role-aware fallbacks below decide whether a+// non-creator may edit / manage.const isOwner = computed(() => {if (!kbInfo.value) return false;- // Check if the current user's tenant ID matches the KB's tenant ID- const userTenantId = authStore.effectiveTenantId;- return kbInfo.value.tenant_id === userTenantId;+ const creatorId = (kbInfo.value as any).creator_id || '';+ const userId = authStore.user?.id || '';+ // creator_id may be empty for legacy KBs created before PR 5; treat+ // those as tenant-owned so the role gate applies (Admin+ can manage,+ // Viewer cannot).+ if (!creatorId) return false;+ return creatorId === userId;});-// Can edit: owner, admin, or editor+// Can edit: KB creator (any role), or tenant Admin+, or org-share-grant.+// The hasRole('contributor') branch is intentionally NOT here — being a+// Contributor in a tenant does not by itself grant edit on someone+// else's KB. Org shares (orgStore.canEditKB) carry their own grant.const canEdit = computed(() => {- return orgStore.canEditKB(kbId.value, isOwner.value);+ if (isOwner.value) return true;+ if (authStore.hasRole('admin')) return true;+ return orgStore.canEditKB(kbId.value, false);});-// Can manage (delete, settings, etc.): owner or admin+// Can manage (delete, settings, etc.): KB creator or tenant Admin+.+// Org shares are intentionally excluded here — sharing a KB grants+// read/edit, never delete or settings access.const canManage = computed(() => {- return orgStore.canManageKB(kbId.value, isOwner.value);+ if (isOwner.value) return true;+ if (authStore.hasRole('admin')) return true;+ return orgStore.canManageKB(kbId.value, false);});// Current KB's shared record (when accessed via organization share)diff --git a/frontend/src/views/knowledge/KnowledgeBaseList.vue b/frontend/src/views/knowledge/KnowledgeBaseList.vueindex 9eaa45120..63ee044b0 100644--- a/frontend/src/views/knowledge/KnowledgeBaseList.vue+++ b/frontend/src/views/knowledge/KnowledgeBaseList.vue@@ -328,22 +328,22 @@><img class="more-icon" src="@/assets/img/more.png" alt="" /></div>- <template #content>- <div class="popup-menu" @click.stop>- <div class="popup-menu-item" @click.stop="handleTogglePin(kb)">- <t-icon class="menu-icon" :name="kb.is_pinned ? 'pin-filled' : 'pin'" />- <span>{{ kb.is_pinned ? $t('knowledgeList.pin.unpin') : $t('knowledgeList.pin.pin') }}</span>- </div>- <div class="popup-menu-item" @click.stop="handleSettings(kb)">- <t-icon class="menu-icon" name="setting" />- <span>{{ $t('knowledgeBase.settings') }}</span>- </div>- <div class="popup-menu-item delete" @click.stop="handleDelete(kb)">- <t-icon class="menu-icon" name="delete" />- <span>{{ $t('common.delete') }}</span>+ <template #content>+ <div class="popup-menu" @click.stop>+ <div class="popup-menu-item" @click.stop="handleTogglePin(kb)">+ <t-icon class="menu-icon" :name="kb.is_pinned ? 'pin-filled' : 'pin'" />+ <span>{{ kb.is_pinned ? $t('knowledgeList.pin.unpin') : $t('knowledgeList.pin.pin') }}</span>+ </div>+ <div v-if="canManageKBCard(kb)" class="popup-menu-item" @click.stop="handleSettings(kb)">+ <t-icon class="menu-icon" name="setting" />+ <span>{{ $t('knowledgeBase.settings') }}</span>+ </div>+ <div v-if="canManageKBCard(kb)" class="popup-menu-item delete" @click.stop="handleDelete(kb)">+ <t-icon class="menu-icon" name="delete" />+ <span>{{ $t('common.delete') }}</span>+ </div></div>- </div>- </template>+ </template></t-popup></div>@@ -670,10 +670,10 @@ const { t } = useI18n()// 左侧空间选择:我的 / 空间 ID(已去掉「全部」)const spaceSelection = ref<'all' | 'mine' | 'shared' | string>('mine')-interface KB {- id: string;- name: string;- description?: string;+interface KB {+ id: string;+ name: string;+ description?: string;updated_at?: string;embedding_model_id?: string;summary_model_id?: string;@@ -690,6 +690,10 @@ interface KB {processing_count?: number;share_count?: number;is_pinned?: boolean;+ // creator_id is the owner-id matched against authStore.user.id when+ // gating the per-card more-menu (Settings / Delete). Empty for legacy+ // KBs created before PR 5; those fall back to the role gate.+ creator_id?: string;}const kbs = ref<KB[]>([])@@ -903,6 +907,21 @@ const handleSettings = (kb: KB) => {goSettings(kb.id)}+// canManageKBCard mirrors KnowledgeBase.vue's `canManage` for the+// per-card more-menu so a Viewer cannot click into Settings or Delete+// for a KB they don't own. The server still rejects the call (PR 5+// guards every mutation with OwnedKBOrAdmin) but the UI shouldn't+// surface buttons the user has no authority to use.+//+// Legacy KBs created before PR 5 have an empty creator_id; treat+// those as tenant-owned (Admin+ may manage) so existing KBs aren't+// suddenly unmanageable for everyone.+function canManageKBCard(kb: KB): boolean {+ const userId = authStore.user?.id || ''+ if (kb.creator_id && userId && kb.creator_id === userId) return true+ return authStore.hasRole('admin')+}+// 通过 ID 处理设置(用于全部 Tab 下的知识库)const handleSettingsById = (id: string) => {goSettings(id)diff --git a/internal/handler/auth.go b/internal/handler/auth.goindex 0eb0f9388..c82a45a87 100644--- a/internal/handler/auth.go+++ b/internal/handler/auth.go@@ -454,12 +454,24 @@ func (h *AuthHandler) GetCurrentUser(c *gin.Context) {return}- // Get tenant information+ // Get tenant information for the *active* tenant (the one the+ // auth middleware resolved against the X-Tenant-ID header), not+ // the user's home tenant. user.TenantID is the row stored on the+ // users table at signup time and never changes; reading it here+ // would make /auth/me always return the home tenant even after+ // the user switched into a peer tenant. The frontend then re-keys+ // `authStore.tenant.id` to the home tenant, and every UI gate+ // computed against it (currentTenantRole, isOwner, ...) leaks+ // the wrong role. Pull the active tenant id from context instead.var tenant *types.Tenant- if user.TenantID > 0 {- tenant, err = h.tenantService.GetTenantByID(ctx, user.TenantID)+ activeTenantID, _ := types.TenantIDFromContext(ctx)+ if activeTenantID == 0 {+ activeTenantID = user.TenantID+ }+ if activeTenantID > 0 {+ tenant, err = h.tenantService.GetTenantByID(ctx, activeTenantID)if err != nil {- logger.Warnf(ctx, "Failed to get tenant info for user %s, tenant ID %d: %v", user.Email, user.TenantID, err)+ logger.Warnf(ctx, "Failed to get tenant info for user %s, tenant ID %d: %v", user.Email, activeTenantID, err)// Don't fail the request if tenant info is not available}}