From 1a46fcf8cac40d906193dfdb4e6b93420217fe3c Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 14 May 2026 21:55:22 +0800 Subject: [PATCH] fix(rbac): role-aware UI gates leaked write affordances after tenant switch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When an Owner of tenant A invited user B as a Viewer, B could log in, switch the active tenant from B's home to A via the user menu, and still see every write button — Create KB, Upload Document, Edit/Delete agent — because the role-gate plumbing on the client was wired to the wrong tenant. The server's RBAC enforcement (PR 2 / PR 5) still blocked the actual mutations with 403, so no data leaked, but the UI presented authority the user did not have, which is a confusing and embarrassing defect. Five distinct root causes, all on the client / server boundary: 1. `currentTenantRole` (frontend/src/stores/auth.ts) read `tenant.value.id` — the user's *home* tenant — instead of the active tenant id. After switching to A, the helper still returned B's home role (Owner), so every `hasRole(...)` gate in the codebase silently short-circuited. Fix: read `selectedTenantId` first, fall back to `tenant.id`. 2. `setMemberships` was only called once, on /auth/login. Hard reloads (which the tenant switcher triggers) re-ran `getCurrentUser()` via `App.vue` and `router/index.ts`, but those callers discarded the `memberships` field of the response, so the auth store kept the login-time snapshot forever. Role changes between sessions stayed invisible. Fix: extract memberships in both /auth/me consumers and feed them into `setMemberships`. 3. `KnowledgeBase.vue`'s `isOwner` compared `kb.tenant_id` to the active tenant id, so any KB inside the current tenant was treated as "owned by the caller" — bypassing every role gate below. Fix: compare against `kb.creator_id` (the field PR 5 introduced) and require an actual creator match. `canEdit` / `canManage` now layer `hasRole('admin')` on top so a non-creator with sufficient role can still manage. 4. `KnowledgeBaseList.vue` and `AgentList.vue` rendered the per-card more-menu (Settings, Delete, Edit) unconditionally. With the ownership column from PR 5 this is straightforward to gate on the client: Settings/Delete now require creator-match or `hasRole('admin')` per the server's `OwnedKBOrAdmin` / `OwnedAgentOrAdmin` matrix. 5. The axios interceptor (frontend/src/utils/request.ts) had a "selectedTenantId === defaultTenantId → don't attach X-Tenant-ID" short-circuit. Any code that wrote the active tenant into `weknora_tenant` (UserMenu's loadUserInfo, OIDC sync, router hydrate) made the two values equal, after which the header silently stopped attaching and subsequent navigation requests landed on the home tenant. Fix: drop the short-circuit; always attach when selectedTenantId is set. Server-side, /auth/me read `user.TenantID` (the immutable home tenant id stamped at signup) when fetching the tenant for the response, so the `tenant` field always pointed at home even after the auth middleware had already resolved an active tenant from X-Tenant-ID. The frontend then re-keyed `authStore.tenant` to the home tenant on every refresh, undoing the switch. Fix: read the active tenant id from context (`types.TenantIDFromContext(ctx)`) and only fall back to user.TenantID when context is unset. The server-side enforcement was correct throughout — every fix here is purely about not lying to the user with the rendered UI. --- frontend/src/App.vue | 9 ++- frontend/src/api/auth/index.ts | 21 ++++++- frontend/src/router/index.ts | 10 ++++ frontend/src/stores/auth.ts | 14 ++++- frontend/src/utils/request.ts | 22 ++++--- frontend/src/views/agent/AgentList.vue | 26 +++++++-- .../src/views/knowledge/KnowledgeBase.vue | 35 +++++++++--- .../src/views/knowledge/KnowledgeBaseList.vue | 57 ++++++++++++------- internal/handler/auth.go | 20 +++++-- 9 files changed, 162 insertions(+), 52 deletions(-) diff --git a/frontend/src/App.vue b/frontend/src/App.vue index ac9c7286..aa40b0c8 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.data authStore.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.ts index 2ec1ebcb..5a28361a 100644 --- a/frontend/src/api/auth/index.ts +++ b/frontend/src/api/auth/index.ts @@ -111,6 +111,10 @@ export interface KnowledgeBaseInfo { name: string description: string tenant_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?: string created_at: string updated_at: string document_count?: number @@ -228,13 +232,26 @@ export async function autoSetup(): Promise { } } +/** + * 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.ts index ae9ced41..34b0b2d6 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -228,6 +228,16 @@ async function hydrateSessionFromToken(authStore: ReturnType { // 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.ts index 767b5ebb..31f548f9 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.vue index 98f1f4a4..435642d7 100644 --- a/frontend/src/views/agent/AgentList.vue +++ b/frontend/src/views/agent/AgentList.vue @@ -103,13 +103,13 @@ @@ -243,11 +243,11 @@