refactor(permissions): enhance role-based access controls across knowledge base and agent views

- Updated visibility conditions for various UI elements based on user roles, ensuring that only users with appropriate permissions (Admin, Contributor, or KB creator) can access certain actions.
- Introduced computed properties to manage permissions for sharing knowledge bases, managing data sources, and executing graph extraction.
- Adjusted the AgentList and KnowledgeBase components to reflect these changes, improving user experience by preventing unauthorized actions from being displayed.
- Ensured that the backend routes are aligned with the updated frontend role checks, enhancing security and clarity in user interactions.
This commit is contained in:
wizardchen
2026-05-15 17:56:58 +08:00
committed by lyingbug
parent e7f9a6580a
commit c6a2f6c8cc
9 changed files with 104 additions and 28 deletions
+1 -1
View File
@@ -352,7 +352,7 @@
<span v-if="shared.is_mine" class="shared-by-me-badge">{{ $t('listSpaceSidebar.mine') }}</span>
</div>
<t-popup
v-if="!shared.is_mine"
v-if="!shared.is_mine && authStore.hasRole('admin')"
:visible="openMoreAgentId === 'shared-tab-' + shared.share_id"
trigger="hover"
overlayClassName="card-more-popup"
+15 -3
View File
@@ -231,6 +231,18 @@ const canManage = computed(() => {
return orgStore.canManageKB(kbId.value, false);
});
// Can mutate knowledge (move / batch-delete): the backend gate for these
// two endpoints is g.Contributor(), so the caller MUST be Contributor+
// in their tenant on top of having KB edit permission. Without the extra
// role check, an org-share-editor whose tenant role is Viewer would see
// the "Move" / "Batch manage" entries and 403 on click.
const canMutateKnowledge = computed(() => {
if (!canEdit.value) return false;
if (isOwner.value) return true;
if (authStore.hasRole('admin')) return true;
return authStore.hasRole('contributor');
});
// Current KB's shared record (when accessed via organization share)
const currentSharedKb = computed(() =>
orgStore.sharedKnowledgeBases.find((s) => s.knowledge_base?.id === kbId.value) ?? null,
@@ -2036,7 +2048,7 @@ async function createNewSession(value: string): Promise<void> {
<!-- Wiki Browser / Graph (shown when wiki or graph tab is active) -->
<div v-if="isWiki && (activeKbTab === 'wiki' || activeKbTab === 'graph')" class="wiki-main-area">
<WikiBrowser v-if="kbId" :knowledge-base-id="kbId" :view="activeKbTab === 'graph' ? 'graph' : 'browser'" @open-source-doc="openSourceDoc" @status-change="onWikiStatusChange" />
<WikiBrowser v-if="kbId" :knowledge-base-id="kbId" :view="activeKbTab === 'graph' ? 'graph' : 'browser'" :can-edit="canEdit" @open-source-doc="openSourceDoc" @status-change="onWikiStatusChange" />
</div>
<template v-if="activeKbTab === 'documents' || !isWiki">
@@ -2390,11 +2402,11 @@ async function createNewSession(value: string): Promise<void> {
<t-icon class="icon" name="refresh" />
<span>{{ t('knowledgeBase.rebuildDocument') }}</span>
</div>
<div class="card-menu-item" @click.stop="handleMoveKnowledge(item)">
<div v-if="canMutateKnowledge" class="card-menu-item" @click.stop="handleMoveKnowledge(item)">
<t-icon class="icon" name="swap" />
<span>{{ t('knowledgeBase.moveDocument') }}</span>
</div>
<div class="card-menu-item" @click.stop="handleEnterBatchFromCard(item)">
<div v-if="canMutateKnowledge" class="card-menu-item" @click.stop="handleEnterBatchFromCard(item)">
<t-icon class="icon" name="queue" />
<span>{{ t('menu.batchManage') }}</span>
</div>
@@ -332,7 +332,7 @@
<!-- 共享设置(仅编辑模式) -->
<div v-if="mode === 'edit' && kbId" v-show="currentSection === 'share'" class="section">
<KBShareSettings :kb-id="kbId" />
<KBShareSettings :kb-id="kbId" :can-share="canShareKB" />
</div>
</div>
@@ -398,6 +398,21 @@ const hasFiles = ref(false)
const initialStorageProvider = ref<string>('')
const initialIndexingStrategy = ref<any>(null)
const dsCount = ref(0)
// KB.creator_id (added in PR 5). Empty for legacy KBs — those fall back
// to "no owner", so only tenant Admin+ can mutate share settings.
const kbCreatorId = ref<string>('')
// Backend gate for /knowledge-bases/:id/shares (POST/PUT/DELETE) is
// g.OwnedKBOrAdmin(): only the KB creator or tenant Admin+ may mutate
// shares. Org-admins on a shared KB do NOT pass this guard, so they
// would only see 403s if we let them try. Mirror the matrix here so
// the buttons disappear instead of failing.
const canShareKB = computed(() => {
if (!props.kbId) return false
const userId = authStore.user?.id || ''
if (kbCreatorId.value && userId && kbCreatorId.value === userId) return true
return authStore.hasRole('admin')
})
// 用户是否在分块设置中手动改过任何值。一旦为 true,就不再根据索引策略自动调整默认分块参数。
const chunkingDirty = ref(false)
@@ -573,7 +588,8 @@ const loadKBData = async () => {
const kb = kbInfo.data
hasFiles.value = (filesResult as any)?.total > 0
kbCreatorId.value = (kb as any).creator_id || ''
// 设置表单数据
const kbType = (kb.type as 'document' | 'faq') || 'document'
formData.value = {
@@ -1130,6 +1146,7 @@ const resetState = () => {
saving.value = false
loading.value = false
chunkingDirty.value = false
kbCreatorId.value = ''
}
// 关闭弹窗
@@ -1314,22 +1314,38 @@ const uiStore = useUIStore()
const authStore = useAuthStore()
const orgStore = useOrganizationStore()
// Permission control: check if current user owns this KB or has edit/manage permission
// Permission control: check if current user owns this KB or has edit/manage permission.
//
// isOwner used to compare kbInfo.tenant_id against the user's effective tenant id,
// which silently treated "any KB visible to me in my current tenant" as "I created
// it" — Viewer / Contributor in their home tenant ended up showing every FAQ
// CRUD entry on every KB and 403'ing when they clicked. Mirror the rule we settled
// on in KnowledgeBase.vue: explicit creator_id match, with role / org-share fallbacks
// inside canEdit / canManage. Legacy KBs with empty creator_id stay tenant-owned
// (Admin+ may 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 || ''
if (!creatorId) return false
return creatorId === userId
})
// Can edit: owner, admin, or editor
// Can edit: KB creator (any role), tenant Admin+, or org-share grant.
// hasRole('contributor') is intentionally NOT here — being a Contributor in the
// tenant does not by itself grant edit on someone else's KB.
const canEdit = computed(() => {
return orgStore.canEditKB(props.kbId, isOwner.value)
if (isOwner.value) return true
if (authStore.hasRole('admin')) return true
return orgStore.canEditKB(props.kbId, false)
})
// Can manage (delete, settings, etc.): owner or admin
// Can manage (delete, settings, share): KB creator or tenant Admin+. Org shares
// are intentionally excluded — sharing grants read/edit, never delete or settings.
const canManage = computed(() => {
return orgStore.canManageKB(props.kbId, isOwner.value)
if (isOwner.value) return true
if (authStore.hasRole('admin')) return true
return orgStore.canManageKB(props.kbId, false)
})
// Current KB's shared record (when accessed via organization share)
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import {
@@ -14,10 +14,17 @@ import { humanizeCron, relativeTime } from '@/utils/cronHumanize'
import DataSourceEditorDialog from './DataSourceEditorDialog.vue'
import DataSourceSyncLogs from './DataSourceSyncLogs.vue'
import DataSourceTypeIcon from './DataSourceTypeIcon.vue'
import { useAuthStore } from '@/stores/auth'
const props = defineProps<{ kbId: string }>()
const emit = defineEmits<{ (e: 'count', value: number): void }>()
const { t } = useI18n()
const authStore = useAuthStore()
// 后端 /datasource 的 list/logs 是 Viewer+,但所有写操作(POST/PUT/DELETE
// 以及 sync/pause/resume/validate)都是 Admin+。低权限用户保留只读视图,
// 增删改和触发同步全部隐藏,而不是按下去再撞 403。
const canManageDataSource = computed(() => authStore.hasRole('admin'))
const dataSources = ref<DataSource[]>([])
const loading = ref(false)
@@ -220,7 +227,7 @@ onBeforeUnmount(stopPolling)
<div class="ds-empty-text">
<p class="ds-empty-title">{{ t('datasource.empty') }}</p>
</div>
<t-button theme="primary" variant="outline" @click="openCreate">
<t-button v-if="canManageDataSource" theme="primary" variant="outline" @click="openCreate">
<template #icon><t-icon name="add" /></template>
{{ t('datasource.addFirst') }}
</t-button>
@@ -243,7 +250,7 @@ onBeforeUnmount(stopPolling)
</div>
<div class="ds-card-actions">
<t-tooltip :content="isSyncRunning(ds) ? t('datasource.logStatus.running') : t('datasource.syncNow')">
<t-tooltip v-if="canManageDataSource" :content="isSyncRunning(ds) ? t('datasource.logStatus.running') : t('datasource.syncNow')">
<t-button
size="small"
variant="text"
@@ -261,7 +268,7 @@ onBeforeUnmount(stopPolling)
<template #icon><t-icon name="root-list" /></template>
</t-button>
</t-tooltip>
<t-dropdown trigger="click" :min-column-width="120">
<t-dropdown v-if="canManageDataSource" trigger="click" :min-column-width="120">
<t-tooltip :content="t('datasource.moreActions')">
<t-button size="small" variant="text" shape="square">
<template #icon><t-icon name="ellipsis" /></template>
@@ -326,7 +333,7 @@ onBeforeUnmount(stopPolling)
</div>
</div>
<div class="ds-card-add" @click="openCreate">
<div v-if="canManageDataSource" class="ds-card-add" @click="openCreate">
<div class="ds-card-add-icon">
<t-icon name="add" size="20px" />
</div>
@@ -43,6 +43,7 @@
<div class="setting-control full-width">
<div class="tags-control-group">
<t-button
v-if="canRunGraphExtract"
theme="default"
size="medium"
:disabled="!modelStatus.llm.available"
@@ -79,6 +80,7 @@
<div class="setting-control full-width">
<div class="text-control-group">
<t-button
v-if="canRunGraphExtract"
theme="default"
size="medium"
:disabled="!modelStatus.llm.available"
@@ -266,6 +268,7 @@
<div class="setting-control">
<div class="action-buttons">
<t-button
v-if="canRunGraphExtract"
theme="primary"
:disabled="!modelStatus.llm.available || !localGraphExtract.text"
:loading="extracting"
@@ -298,8 +301,15 @@ import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { extractTextRelations, fabriText, fabriTag, type Node, type Relation } from '@/api/initialization'
import { getSystemInfo } from '@/api/system'
import { useAuthStore } from '@/stores/auth'
const { t } = useI18n()
const authStore = useAuthStore()
// canRunGraphExtract 对应后端 POST /initialization/extract/{fabri-tag,fabri-text,
// text-relation} 的 g.Admin() 守卫——这三个都是会调用大模型 + 写库的 admin
// 工具。Contributor 看到按钮点了只会撞 403。
const canRunGraphExtract = computed(() => authStore.hasRole('admin'))
interface GraphExtractConfig {
enabled: boolean
@@ -5,8 +5,8 @@
<p class="section-desc">{{ $t('knowledgeEditor.share.description') }}</p>
</div>
<div class="section-body">
<!-- 共享表单 -->
<div class="share-form">
<!-- 共享表单:仅 KB creator 或租户 Admin+ 可见,其他角色看到的是只读列表。 -->
<div v-if="canShare" class="share-form">
<div class="form-item">
<label class="form-label">{{ $t('organization.share.selectOrg') }}</label>
<div class="share-input-row">
@@ -127,7 +127,7 @@
</span>
</div>
</div>
<div class="share-actions">
<div v-if="canShare" class="share-actions">
<t-select
:value="share.permission"
size="small"
@@ -180,9 +180,15 @@ function getOrgForShare(organizationId: string) {
interface Props {
kbId: string
// 后端 POST/PUT/DELETE /knowledge-bases/:id/shares 受 OwnedKBOrAdmin
// 守卫:仅 KB creator 或租户 Admin+ 能改动共享。父组件根据 KB.creator_id
// 计算后传入,缺省 false 表示只读。
canShare?: boolean
}
const props = defineProps<Props>()
const props = withDefaults(defineProps<Props>(), {
canShare: false,
})
const loadingOrgs = ref(false)
const loadingShares = ref(false)
@@ -377,7 +377,7 @@
<div class="wiki-issue-popup-title">
<span>{{ $t('knowledgeEditor.wikiBrowser.issueFixSuggestions', { count: pageIssues.length }) }}</span>
</div>
<t-button size="small" theme="primary" variant="base" @click="triggerAutoFix">
<t-button v-if="props.canEdit" size="small" theme="primary" variant="base" @click="triggerAutoFix">
<template #icon><t-icon name="tools" /></template>
{{ $t('knowledgeEditor.wikiBrowser.issueFixBtn') }}
</t-button>
@@ -398,7 +398,7 @@
<span class="wiki-issue-popup-reporter">
{{ issue.reported_by === 'wiki-researcher-agent' ? $t('knowledgeEditor.wikiBrowser.issueAiLinter') : $t('knowledgeEditor.wikiBrowser.issueReportedBy', { reporter: issue.reported_by }) }}
</span>
<div class="wiki-issue-popup-actions">
<div v-if="props.canEdit" class="wiki-issue-popup-actions">
<span class="wiki-issue-popup-action" @click="triggerFixIssue(issue)" style="margin-right: 12px; font-weight: 500;">
<t-icon name="tools" style="margin-right: 4px;" />{{ $t('knowledgeEditor.wikiBrowser.issueFixSingle') }}
</span>
@@ -674,6 +674,11 @@ const { t } = useI18n()
const props = defineProps<{
knowledgeBaseId: string
view?: 'browser' | 'graph'
// canEdit 由父组件 KnowledgeBase.vue 透传(与 canEdit computed 同源)。
// 控制 AutoFix / FixIssue / IgnoreIssue 三个写操作按钮的可见性,
// 对应后端 g.OwnedWikiKBOrAdmin() 守卫(KB creator OR Admin+ OR
// org-share editor)。父组件没传时按 false 兜底,避免漏 gate。
canEdit?: boolean
}>()
const emit = defineEmits<{
+6 -3
View File
@@ -679,9 +679,12 @@ func RegisterMCPServiceRoutes(
agentTool := r.Group("/agent")
{
// Resolving a pending tool-approval lets the agent run a sensitive
// external command on this tenant's behalf — Admin+.
agentTool.POST("/tool-approvals/:pending_id", g.Admin(), handler.ResolveToolApproval)
// Resolving a pending tool-approval is gated to tenant members
// (Viewer+). The approval card surfaces inside an agent chat the
// caller initiated — restricting it to Admin+ blocks the only
// people who actually have context to approve, so the gate is
// kept at "anyone in the tenant" instead.
agentTool.POST("/tool-approvals/:pending_id", g.Viewer(), handler.ResolveToolApproval)
}
}