Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(security): close cross-workspace access paths in shared spaces (#3408)

lyingbugdb8e7611be76
diff --git a/frontend/src/components/AgentShareSettings.vue b/frontend/src/components/AgentShareSettings.vue
index 90ad5344f..d505961cf 100644
--- a/frontend/src/components/AgentShareSettings.vue
+++ b/frontend/src/components/AgentShareSettings.vue
@@ -21,6 +21,8 @@
</div>
</div>
<p class="share-panel-desc">{{ $t('organization.share.agentShareDesc') }}</p>
+ <t-alert v-if="sharesSkillSecrets" theme="warning" class="share-panel-alert"
+ :message="$t('agent.shareScope.skillSecretsWarning')" />
</div>
<div class="share-panel-list-wrap">
@@ -142,6 +144,16 @@ interface Props {
const props = defineProps<Props>()
+// Members run this agent's skills in this workspace's sandbox, with the
+// environment values its admins configured for them, and can have the model
+// print those values. Sharing stays allowed; the owner is told before sharing.
+const sharesSkillSecrets = computed(() => {
+ const config = props.agent?.config
+ if (!config?.sandbox_config_id) return false
+ return config.skills_selection_mode === 'all'
+ || (config.skills_selection_mode === 'selected' && (config.selected_skills?.length ?? 0) > 0)
+})
+
const shareHintPopupInnerStyle = {
boxSizing: 'border-box' as const,
padding: '0',
diff --git a/frontend/src/components/share-to-space-panel.less b/frontend/src/components/share-to-space-panel.less
index 1b8cdf3b0..e6805c8e4 100644
--- a/frontend/src/components/share-to-space-panel.less
+++ b/frontend/src/components/share-to-space-panel.less
@@ -212,3 +212,7 @@
gap: 2px;
}
}
+
+.share-panel-alert {
+ margin-top: 12px;
+}
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 8207b3966..44fb0afc2 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -1058,6 +1058,7 @@ export default {
shareScope: {
title: 'Share Scope',
desc: 'Space members have read-only access to this agent and will use it according to your current configuration; your changes to the agent will sync to shared spaces. To allow space members to edit knowledge base content, share the knowledge base to the space.',
+ skillSecretsWarning: 'This agent uses skills. When space members use it, the skills run in this workspace\'s sandbox with the environment variables admins configured for them (such as API keys), and members can have the agent reveal those values. Share it only if that is acceptable.',
knowledgeBase: 'Knowledge bases',
chatModel: 'Chat model',
rerankModel: 'Rerank model',
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index ef8825e78..12d7aecf6 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -1058,6 +1058,7 @@ export default {
shareScope: {
title: '共有範囲',
desc: 'スペースのメンバーはこのエージェントを読み取り専用で利用し、現在の設定がそのまま適用されます。エージェントへの変更は共有先のスペースにも反映されます。スペースのメンバーがナレッジベースの内容を編集できるようにするには、ナレッジベースをスペースに共有してください。',
+ skillSecretsWarning: 'このエージェントはスキルを使用します。スペースのメンバーが利用すると、スキルはこのワークスペースのサンドボックスで、管理者が設定した環境変数(API キーなど)とともに実行され、メンバーはエージェントにその値を出力させることができます。これを許容できる場合にのみ共有してください。',
knowledgeBase: 'ナレッジベース',
chatModel: 'チャットモデル',
rerankModel: 'リランクモデル',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index bbc05e7e6..7ab5e03fe 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -6510,6 +6510,7 @@ export default {
shareScope: {
title: '공유 범위 설명',
desc: '스페이스 구성원은 읽기 전용 모드로 에이전트를 사용하며 현재 구성된 기능과 리소스를 따릅니다. 에이전트에 대한 수정 사항은 공유 공간에 동기화됩니다. 스페이스 구성원이 지식베이스 콘텐츠를 편집할 수 있도록 허용하려면 지식베이스를 스페이스에 공유하세요.',
+ skillSecretsWarning: '이 에이전트는 스킬을 사용합니다. 스페이스 구성원이 사용하면 스킬이 이 워크스페이스의 샌드박스에서 관리자가 설정한 환경 변수(API 키 등)와 함께 실행되며, 구성원은 에이전트가 그 값을 출력하게 할 수 있습니다. 이를 허용할 수 있는 경우에만 공유하세요.',
knowledgeBase: '지식베이스',
chatModel: '대화 모델',
rerankModel: '모델을 재배열하다',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 0b85266c4..b37e6a511 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -6510,6 +6510,7 @@ export default {
shareScope: {
title: 'Share Scope',
desc: 'Space members have read-only access to this agent and will use it according to your current configuration; your changes to the agent will sync to shared spaces. To allow space members to edit knowledge base content, share the knowledge base to the space.',
+ skillSecretsWarning: 'This agent uses skills. When space members use it, the skills run in this workspace\'s sandbox with the environment variables admins configured for them (such as API keys), and members can have the agent reveal those values. Share it only if that is acceptable.',
knowledgeBase: 'Knowledge bases',
chatModel: 'Chat model',
rerankModel: 'Rerank model',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 99a91b5c8..a7ec1bfce 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -6512,6 +6512,7 @@ export default {
shareScope: {
title: '共享范围说明',
desc: '空间成员以只读方式使用该智能体,将遵循您当前配置的能力与资源;您对智能体的修改会同步给已共享的空间。如需允许空间成员编辑知识库内容,请将知识库共享到空间。',
+ skillSecretsWarning: '该智能体启用了技能:空间成员使用时,技能会在本空间的沙箱中运行,并带上管理员为技能配置的环境变量(如 API Key),成员可以让智能体读出这些值。请在可以接受这一点时再共享。',
knowledgeBase: '知识库',
chatModel: '对话模型',
rerankModel: '重排模型',
diff --git a/internal/application/repository/agent_share.go b/internal/application/repository/agent_share.go
index 0e2b789ac..d62931b56 100644
--- a/internal/application/repository/agent_share.go
+++ b/internal/application/repository/agent_share.go
@@ -88,6 +88,22 @@ func (r *agentShareRepository) DeleteByOrganizationID(ctx context.Context, orgID
return r.db.WithContext(ctx).Where("organization_id = ?", orgID).Delete(&types.AgentShare{}).Error
}
+// DeleteByOrganizationAndSourceTenant soft deletes the shares a tenant made
+// into an organization (e.g. when the tenant leaves or is removed from it).
+func (r *agentShareRepository) DeleteByOrganizationAndSourceTenant(
+ ctx context.Context, orgID string, sourceTenantID uint64,
+) error {
+ return r.db.WithContext(ctx).
+ Where("organization_id = ? AND source_tenant_id = ?", orgID, sourceTenantID).
+ Delete(&types.AgentShare{}).Error
+}
+
+// agentShareSourceMemberJoin keeps a share effective only while its source
+// tenant is still a member of the organization; see kbShareSourceMemberJoin.
+const agentShareSourceMemberJoin = "JOIN organization_tenant_members src_member " +
+ "ON src_member.organization_id = agent_shares.organization_id " +
+ "AND src_member.tenant_id = agent_shares.source_tenant_id"
+
// ListByAgent lists all share records for an agent
func (r *agentShareRepository) ListByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error) {
var shares []*types.AgentShare
@@ -107,6 +123,7 @@ func (r *agentShareRepository) ListByOrganization(ctx context.Context, orgID str
var shares []*types.AgentShare
err := r.db.WithContext(ctx).
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
+ Joins(agentShareSourceMemberJoin).
Preload("Agent").
Preload("Organization").
Where("agent_shares.organization_id = ? AND agent_shares.deleted_at IS NULL", orgID).
@@ -126,6 +143,7 @@ func (r *agentShareRepository) ListByOrganizations(ctx context.Context, orgIDs [
var shares []*types.AgentShare
err := r.db.WithContext(ctx).
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
+ Joins(agentShareSourceMemberJoin).
Preload("Agent").
Preload("Organization").
Where("agent_shares.organization_id IN ? AND agent_shares.deleted_at IS NULL", orgIDs).
@@ -149,6 +167,7 @@ func (r *agentShareRepository) CountByOrganizations(ctx context.Context, orgIDs
var rows []row
err := r.db.WithContext(ctx).Model(&types.AgentShare{}).
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
+ Joins(agentShareSourceMemberJoin).
Select("agent_shares.organization_id as organization_id, COUNT(*) as count").
Where("agent_shares.organization_id IN ? AND agent_shares.deleted_at IS NULL", orgIDs).
Group("agent_shares.organization_id").
@@ -173,6 +192,7 @@ func (r *agentShareRepository) ListSharedAgentsForTenant(ctx context.Context, te
var shares []*types.AgentShare
err := r.db.WithContext(ctx).
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
+ Joins(agentShareSourceMemberJoin).
Preload("Agent").
Preload("Organization").
Joins("JOIN organization_tenant_members otm ON otm.organization_id = agent_shares.organization_id").
@@ -194,6 +214,9 @@ func (r *agentShareRepository) GetShareByAgentIDForTenant(ctx context.Context, t
var share types.AgentShare
tx := r.db.WithContext(ctx).
Joins("JOIN organization_tenant_members otm ON otm.organization_id = agent_shares.organization_id").
+ Joins("JOIN organizations ON organizations.id = agent_shares.organization_id "+
+ "AND organizations.deleted_at IS NULL").
+ Joins(agentShareSourceMemberJoin).
Where("agent_shares.agent_id = ?", agentID).
Where("otm.tenant_id = ?", tenantID).
Where("agent_shares.source_tenant_id != ?", excludeTenantID).
@@ -224,6 +247,7 @@ func (r *agentShareRepository) GetShareByAgentIDAndSourceForTenant(
Joins("JOIN organization_tenant_members otm ON otm.organization_id = agent_shares.organization_id").
Joins("JOIN organizations ON organizations.id = agent_shares.organization_id AND organizations.deleted_at IS NULL").
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
+ Joins(agentShareSourceMemberJoin).
Where("agent_shares.agent_id = ?", agentID).
Where("agent_shares.source_tenant_id = ?", sourceTenantID).
Where("otm.tenant_id = ?", tenantID).
diff --git a/internal/application/repository/agent_share_source_test.go b/internal/application/repository/agent_share_source_test.go
index b73d67e8f..889e46d2f 100644
--- a/internal/application/repository/agent_share_source_test.go
+++ b/internal/application/repository/agent_share_source_test.go
@@ -22,7 +22,8 @@ func TestGetShareByAgentIDAndSourceForTenantDisambiguatesSource(t *testing.T) {
`CREATE TABLE organizations (id TEXT PRIMARY KEY, deleted_at DATETIME)`,
`CREATE TABLE custom_agents (id TEXT, tenant_id INTEGER, deleted_at DATETIME)`,
`INSERT INTO organizations(id) VALUES ('org')`,
- `INSERT INTO organization_tenant_members(organization_id, tenant_id) VALUES ('org', 7)`,
+ `INSERT INTO organization_tenant_members(organization_id, tenant_id)
+ VALUES ('org', 7), ('org', 42), ('org', 84)`,
`INSERT INTO custom_agents(id, tenant_id) VALUES ('builtin-smart-reasoning', 42), ('builtin-smart-reasoning', 84)`,
`INSERT INTO agent_shares(id, agent_id, organization_id, source_tenant_id) VALUES
('share-42', 'builtin-smart-reasoning', 'org', 42),
@@ -44,4 +45,19 @@ func TestGetShareByAgentIDAndSourceForTenantDisambiguatesSource(t *testing.T) {
context.Background(), 8, "builtin-smart-reasoning", 84,
)
require.ErrorIs(t, err, ErrAgentShareNotFound)
+
+ // A share lapses once its source tenant leaves the organization, even if
+ // the row itself was left behind.
+ require.NoError(t, db.Exec(
+ `DELETE FROM organization_tenant_members WHERE organization_id = 'org' AND tenant_id = 84`).Error)
+ _, err = repo.GetShareByAgentIDAndSourceForTenant(
+ context.Background(), 7, "builtin-smart-reasoning", 84,
+ )
+ require.ErrorIs(t, err, ErrAgentShareNotFound)
+ _, err = repo.GetShareByAgentIDForTenant(context.Background(), 7, "builtin-smart-reasoning", 7)
+ require.NoError(t, err, "the share of the remaining member still resolves")
+ shares, err := repo.ListSharedAgentsForTenant(context.Background(), 7)
+ require.NoError(t, err)
+ require.Len(t, shares, 1)
+ require.Equal(t, uint64(42), shares[0].SourceTenantID)
}
diff --git a/internal/application/repository/kbshare.go b/internal/application/repository/kbshare.go
index 59183528a..1883735a3 100644
--- a/internal/application/repository/kbshare.go
+++ b/internal/application/repository/kbshare.go
@@ -93,6 +93,23 @@ func (r *kbShareRepository) DeleteByOrganizationID(ctx context.Context, orgID st
return r.db.WithContext(ctx).Where("organization_id = ?", orgID).Delete(&types.KnowledgeBaseShare{}).Error
}
+// DeleteByOrganizationAndSourceTenant soft deletes the shares a tenant made
+// into an organization (e.g. when the tenant leaves or is removed from it).
+func (r *kbShareRepository) DeleteByOrganizationAndSourceTenant(
+ ctx context.Context, orgID string, sourceTenantID uint64,
+) error {
+ return r.db.WithContext(ctx).
+ Where("organization_id = ? AND source_tenant_id = ?", orgID, sourceTenantID).
+ Delete(&types.KnowledgeBaseShare{}).Error
+}
+
+// kbShareSourceMemberJoin keeps a share effective only while its source tenant
+// is still a member of the organization. Leaving or removal deletes the
+// tenant's shares; the join also covers rows left behind by older versions.
+const kbShareSourceMemberJoin = "JOIN organization_tenant_members src_member " +
+ "ON src_member.organization_id = kb_shares.organization_id " +
+ "AND src_member.tenant_id = kb_shares.source_tenant_id"
+
// ListByKnowledgeBase lists all share records for a knowledge base
func (r *kbShareRepository) ListByKnowledgeBase(ctx context.Context, kbID string) ([]*types.KnowledgeBaseShare, error) {
var shares []*types.KnowledgeBaseShare
@@ -114,6 +131,7 @@ func (r *kbShareRepository) ListByOrganization(ctx context.Context, orgID string
var shares []*types.KnowledgeBaseShare
err := r.db.WithContext(ctx).
Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
+ Joins(kbShareSourceMemberJoin).
Preload("KnowledgeBase").
Preload("Organization").
Where("kb_shares.organization_id = ? AND kb_shares.deleted_at IS NULL", orgID).
@@ -134,6 +152,7 @@ func (r *kbShareRepository) ListByOrganizations(ctx context.Context, orgIDs []st
var shares []*types.KnowledgeBaseShare
err := r.db.WithContext(ctx).
Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
+ Joins(kbShareSourceMemberJoin).
Preload("KnowledgeBase").
Preload("Organization").
Where("kb_shares.organization_id IN ? AND kb_shares.deleted_at IS NULL", orgIDs).
@@ -153,6 +172,7 @@ func (r *kbShareRepository) ListSharedKBsForTenant(ctx context.Context, tenantID
// Get shares for organizations the tenant is a member of; exclude deleted orgs and deleted KBs.
err := r.db.WithContext(ctx).
Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
+ Joins(kbShareSourceMemberJoin).
Preload("KnowledgeBase").
Preload("Organization").
Joins("JOIN organization_tenant_members otm ON otm.organization_id = kb_shares.organization_id").
@@ -221,6 +241,7 @@ func (r *kbShareRepository) CountByOrganizations(ctx context.Context, orgIDs []s
var rows []row
err := r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
+ Joins(kbShareSourceMemberJoin).
Select("kb_shares.organization_id as organization_id, COUNT(*) as count").
Where("kb_shares.organization_id IN ? AND kb_shares.deleted_at IS NULL", orgIDs).
Group("kb_shares.organization_id").
diff --git a/internal/application/service/agent_memory_config_test.go b/internal/application/service/agent_memory_config_test.go
index 2cc5cf7fa..561b33f17 100644
--- a/internal/application/service/agent_memory_config_test.go
+++ b/internal/application/service/agent_memory_config_test.go
@@ -67,3 +67,26 @@ func TestAgentConfigCarriesMaxCompletionTokens(t *testing.T) {
}
func boolPtr(v bool) *bool { return &v }
+
+// An unset MCP mode runs as "all" for the owner, but the share scope shows it
+// as none; a shared run must not expose the owner's MCP services.
+func TestAgentConfigUnsetMCPModeIsNoneForSharedRuns(t *testing.T) {
+ svc := &sessionService{
+ cfg: &config.Config{},
+ webSearchProviderRepo: &sharedAgentWebSearchRepo{},
+ }
+ for _, shared := range []bool{false, true} {
+ req := &types.QARequest{
+ Session: &types.Session{ID: "session-1", TenantID: 1},
+ CustomAgent: &types.CustomAgent{TenantID: 1, Config: types.CustomAgentConfig{MaxIterations: 5}},
+ SharedAgentReadOnly: shared,
+ }
+ agentConfig, err := svc.buildAgentConfig(t.Context(), req, &types.Tenant{ID: 1}, 1)
+ require.NoError(t, err)
+ if shared {
+ require.Equal(t, "none", agentConfig.MCPSelectionMode)
+ } else {
+ require.Empty(t, agentConfig.MCPSelectionMode, "the owner's own runs keep the default")
+ }
+ }
+}
diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.go
index da08feb4c..9639ec310 100644
--- a/internal/application/service/agent_service.go
+++ b/internal/application/service/agent_service.go
@@ -863,7 +863,7 @@ func (s *agentService) registerTools(
logger.Infof(ctx, "Using default allowed tools: %v", allowedTools)
}
if config.SharedAgentReadOnly {
- allowedTools = filterSharedAgentWriteTools(allowedTools)
+ allowedTools = withoutWikiWriteTools(allowedTools)
}
// ---- Capability detection from SearchTargets ----
@@ -900,6 +900,13 @@ func (s *agentService) registerTools(
}
wikiKBIDs = scopedWikiKBIDs
hasWikiKB := len(wikiKBIDs) > 0
+ // Search targets only need read access. Wiki mutations stay on the KBs the
+ // caller may edit, so a viewer share (or the caller's own agent pointed at
+ // one) cannot become a write path into another workspace's wiki.
+ writableWikiKBIDs := intersectStrings(wikiKBIDs, config.WritableKBIDs)
+ if len(writableWikiKBIDs) == 0 {
+ allowedTools = withoutWikiWriteTools(allowedTools)
+ }
// Filter out knowledge base tools if no knowledge scope is configured for this turn.
hasKnowledge := agentHasKnowledgeScope(config)
@@ -1109,22 +1116,24 @@ func (s *agentService) registerTools(
case tools.ToolWikiSearch:
toolToRegister = tools.NewWikiSearchTool(s.wikiPageService, s.knowledgeService, wikiScopes, wikiRoutes)
case tools.ToolWikiFlagIssue:
- toolToRegister = tools.NewWikiFlagIssueTool(s.wikiPageService, wikiKBIDs, wikiRoutes).
+ toolToRegister = tools.NewWikiFlagIssueTool(s.wikiPageService, writableWikiKBIDs, wikiRoutes).
WithKnowledgeScope(s.knowledgeService, config.SearchTargets)
case tools.ToolWikiReadIssue:
toolToRegister = tools.NewWikiReadIssueTool(s.wikiPageService, wikiKBIDs)
case tools.ToolWikiUpdateIssue:
- toolToRegister = tools.NewWikiUpdateIssueTool(s.wikiPageService, wikiKBIDs)
+ toolToRegister = tools.NewWikiUpdateIssueTool(s.wikiPageService, writableWikiKBIDs)
case tools.ToolWikiWritePage:
- toolToRegister = tools.NewWikiWritePageTool(s.wikiPageService, wikiKBIDs, s.knowledgeService, wikiRoutes).
- WithSearchTargets(config.SearchTargets)
+ toolToRegister = tools.NewWikiWritePageTool(
+ s.wikiPageService, writableWikiKBIDs, s.knowledgeService, wikiRoutes,
+ ).WithSearchTargets(config.SearchTargets)
case tools.ToolWikiReplaceText:
- toolToRegister = tools.NewWikiReplaceTextTool(s.wikiPageService, wikiKBIDs, s.knowledgeService, wikiRoutes).
- WithSearchTargets(config.SearchTargets)
+ toolToRegister = tools.NewWikiReplaceTextTool(
+ s.wikiPageService, writableWikiKBIDs, s.knowledgeService, wikiRoutes,
+ ).WithSearchTargets(config.SearchTargets)
case tools.ToolWikiRenamePage:
- toolToRegister = tools.NewWikiRenamePageTool(s.wikiPageService, wikiKBIDs, wikiRoutes)
+ toolToRegister = tools.NewWikiRenamePageTool(s.wikiPageService, writableWikiKBIDs, wikiRoutes)
case tools.ToolWikiDeletePage:
- toolToRegister = tools.NewWikiDeletePageTool(s.wikiPageService, wikiKBIDs, wikiRoutes)
+ toolToRegister = tools.NewWikiDeletePageTool(s.wikiPageService, writableWikiKBIDs, wikiRoutes)
case tools.ToolShellExec, tools.ToolReadFile, tools.LegacyToolReadSkill, tools.LegacyToolExecuteSkillScript,
tools.ToolListSandboxFiles, tools.LegacyToolReadSandboxFile, tools.ToolWriteSandboxFile,
@@ -1151,11 +1160,12 @@ func (s *agentService) registerTools(
return nil
}
-// filterSharedAgentWriteTools enforces the read-only contract of AgentShare.
-// These tools write source-workspace Wiki state and otherwise bypass the HTTP
-// KB permission middleware because they execute inside the agent engine.
-func filterSharedAgentWriteTools(allowed []string) []string {
- sourceWorkspaceWrites := map[string]bool{
+// withoutWikiWriteTools drops the tools that write Wiki state. They execute
+// inside the agent engine and so bypass the HTTP KB permission middleware; they
+// are removed for shared agents (read-only by contract) and whenever no
+// writable wiki KB is in scope.
+func withoutWikiWriteTools(allowed []string) []string {
+ wikiWrites := map[string]bool{
tools.ToolWikiFlagIssue: true,
tools.ToolWikiUpdateIssue: true,
tools.ToolWikiWritePage: true,
@@ -1165,7 +1175,7 @@ func filterSharedAgentWriteTools(allowed []string) []string {
}
filtered := make([]string, 0, len(allowed))
for _, name := range allowed {
- if !sourceWorkspaceWrites[name] {
+ if !wikiWrites[name] {
filtered = append(filtered, name)
}
}
diff --git a/internal/application/service/agent_share.go b/internal/application/service/agent_share.go
index 6284689d2..98e5f3305 100644
--- a/internal/application/service/agent_share.go
+++ b/internal/application/service/agent_share.go
@@ -20,7 +20,11 @@ var (
ErrAgentNotFoundForShare = errors.New("agent not found")
ErrNotAgentOwner = errors.New("only agent owner can share")
ErrOrgRoleCannotShareAgent = errors.New("only editors and admins can share agents to this organization")
- ErrAgentNotConfigured = errors.New(
+ // ErrBuiltinAgentNotShareable is returned for built-in agents: every
+ // workspace has its own copy under the same ID, so a shared built-in would
+ // be indistinguishable from the receiver's own agent.
+ ErrBuiltinAgentNotShareable = errors.New("built-in agents cannot be shared")
+ ErrAgentNotConfigured = errors.New(
"agent is not fully configured (missing required chat model, or rerank model when the search_knowledge " +
"tool is enabled)",
)
@@ -59,6 +63,14 @@ func agentRequiresRerankModel(agent *types.CustomAgent) bool {
return false
}
+// isBuiltinAgent guards sharing. Shares of built-in agents created before
+// ErrBuiltinAgentNotShareable are hidden from receivers and never resolved,
+// since the ID collides with the receiver's own built-in agent; the source
+// tenant still lists its row so it can remove it.
+func isBuiltinAgent(agent *types.CustomAgent) bool {
+ return agent != nil && (agent.IsBuiltin || types.IsBuiltinAgentID(agent.ID))
+}
+
// agentShareService implements AgentShareService.
//
// Plan 3 of #1303: visibility and access checks key on the caller's
@@ -71,6 +83,7 @@ type agentShareService struct {
agentRepo interfaces.CustomAgentRepository
userRepo interfaces.UserRepository
webSearchProviderRepo interfaces.WebSearchProviderRepository
+ kbRepo interfaces.KnowledgeBaseRepository
}
// NewAgentShareService creates a new agent share service
@@ -81,6 +94,7 @@ func NewAgentShareService(
agentRepo interfaces.CustomAgentRepository,
userRepo interfaces.UserRepository,
webSearchProviderRepo interfaces.WebSearchProviderRepository,
+ kbRepo interfaces.KnowledgeBaseRepository,
) interfaces.AgentShareService {
return &agentShareService{
shareRepo: shareRepo,
@@ -89,6 +103,7 @@ func NewAgentShareService(
agentRepo: agentRepo,
userRepo: userRepo,
webSearchProviderRepo: webSearchProviderRepo,
+ kbRepo: kbRepo,
}
}
@@ -161,6 +176,12 @@ func (s *agentShareService) ShareAgent(ctx context.Context, agentID string, orgI
if agent.TenantID != tenantID {
return nil, ErrNotAgentOwner
}
+ if isBuiltinAgent(agent) {
+ return nil, ErrBuiltinAgentNotShareable
+ }
+ if err := checkAgentKBScopeShareable(ctx, s.kbRepo.GetKnowledgeBaseByIDs, nil, agent, userID); err != nil {
+ return nil, err
+ }
if agent.Config.ModelID == "" {
return nil, ErrAgentNotConfigured
@@ -223,9 +244,8 @@ func (s *agentShareService) ShareAgent(ctx context.Context, agentID string, orgI
return share, nil
}
-// RemoveShare removes an agent share.
-// Same authz envelope as KB-share remove (see kbshare.callerCanManageShare):
-// original sharer, OR source-tenant Admin+, OR target-org admin.
+// RemoveShare removes an agent share. Same authorization as KB shares; see
+// canManageShare.
func (s *agentShareService) RemoveShare(ctx context.Context, shareID string, userID string, tenantID uint64) error {
share, err := s.shareRepo.GetByID(ctx, shareID)
if err != nil {
@@ -234,21 +254,14 @@ func (s *agentShareService) RemoveShare(ctx context.Context, shareID string, use
}
return err
}
- // (1) Original sharer.
- if share.SharedByUserID == userID {
- return s.shareRepo.Delete(ctx, shareID)
+ record := shareRecord{
+ sharedByUserID: share.SharedByUserID, sourceTenantID: share.SourceTenantID,
+ orgID: share.OrganizationID, permission: share.Permission,
}
- // (2) Source-tenant Admin+ — Plan 3 ownership is tenant-level.
- if tenantID != 0 && tenantID == share.SourceTenantID {
- if types.TenantRoleFromContext(ctx).HasPermission(types.TenantRoleAdmin) {
- return s.shareRepo.Delete(ctx, shareID)
- }
- }
- // (3) Org admin in the target org (governance / sharer-left repair).
- if tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, tenantID); err == nil && tm.Role == types.OrgRoleAdmin {
- return s.shareRepo.Delete(ctx, shareID)
+ if !canManageShare(ctx, s.orgRepo, record, "", userID, tenantID) {
+ return ErrAgentSharePermission
}
- return ErrAgentSharePermission
+ return s.shareRepo.Delete(ctx, shareID)
}
// ListSharesByAgent lists all shares for an agent owned by tenantID.
@@ -289,7 +302,7 @@ func (s *agentShareService) ListSharedAgents(ctx context.Context, tenantID uint6
if share.SourceTenantID == tenantID {
continue
}
- if share.Agent == nil {
+ if share.Agent == nil || isBuiltinAgent(share.Agent) {
continue
}
tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, tenantID)
@@ -351,7 +364,7 @@ func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context,
result := make([]*types.OrganizationSharedAgentItem, 0, len(shares))
webSearchReadyCache := make(map[string]bool)
for _, share := range shares {
- if share.Agent == nil {
+ if share.Agent == nil || (share.SourceTenantID != tenantID && isBuiltinAgent(share.Agent)) {
continue
}
@@ -415,7 +428,7 @@ func (s *agentShareService) ListSharedAgentsInOrganizations(ctx context.Context,
tm := members[orgID]
result := make([]*types.OrganizationSharedAgentItem, 0, len(list))
for _, share := range list {
- if share.Agent == nil {
+ if share.Agent == nil || (share.SourceTenantID != tenantID && isBuiltinAgent(share.Agent)) {
continue
}
effective := types.MinOrgRole(share.Permission, tm.Role)
@@ -462,7 +475,7 @@ func (s *agentShareService) GetSharedAgentForTenant(
agentID string,
sourceTenantID ...uint64,
) (*types.CustomAgent, error) {
- if agentID == "" {
+ if agentID == "" || types.IsBuiltinAgentID(agentID) {
return nil, ErrAgentShareNotFound
}
if len(sourceTenantID) > 0 && sourceTenantID[0] != 0 {
@@ -477,7 +490,7 @@ func (s *agentShareService) GetSharedAgentForTenant(
return nil, err
}
agent, err := s.agentRepo.GetAgentByID(ctx, agentID, share.SourceTenantID)
- if err != nil || agent == nil {
+ if err != nil || agent == nil || isBuiltinAgent(agent) {
return nil, ErrAgentNotFoundForShare
}
types.ApplyBuiltinAgentLocalization(ctx, agent)
@@ -498,6 +511,9 @@ func (s *agentShareService) GetSharedAgentForTenant(
}
return nil, err
}
+ if isBuiltinAgent(agent) {
+ return nil, ErrAgentNotFoundForShare
+ }
types.ApplyBuiltinAgentLocalization(ctx, agent)
_ = callerTenantRole
return agent, nil
diff --git a/internal/application/service/agent_share_builtin_test.go b/internal/application/service/agent_share_builtin_test.go
new file mode 100644
index 000000000..47b386306
--- /dev/null
+++ b/internal/application/service/agent_share_builtin_test.go
@@ -0,0 +1,65 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/stretchr/testify/require"
+)
+
+type builtinShareAgentRepo struct {
+ interfaces.CustomAgentRepository
+ agent *types.CustomAgent
+}
+
+func (r *builtinShareAgentRepo) GetAgentByID(context.Context, string, uint64) (*types.CustomAgent, error) {
+ return r.agent, nil
+}
+
+type builtinShareRepo struct {
+ interfaces.AgentShareRepository
+}
+
+func (builtinShareRepo) GetShareByAgentIDForTenant(
+ _ context.Context, _ uint64, agentID string, _ uint64,
+) (*types.AgentShare, error) {
+ return &types.AgentShare{AgentID: agentID, SourceTenantID: 84}, nil
+}
+
+func (builtinShareRepo) GetShareByAgentIDAndSourceForTenant(
+ _ context.Context, _ uint64, agentID string, sourceTenantID uint64,
+) (*types.AgentShare, error) {
+ return &types.AgentShare{AgentID: agentID, SourceTenantID: sourceTenantID}, nil
+}
+
+// Every workspace owns a copy of each built-in agent under the same ID, so a
+// shared one would be indistinguishable from the receiver's own agent.
+func TestShareAgentRejectsBuiltinAgent(t *testing.T) {
+ svc := &agentShareService{agentRepo: &builtinShareAgentRepo{agent: &types.CustomAgent{
+ ID: types.BuiltinQuickAnswerID, TenantID: 84, IsBuiltin: true,
+ Config: types.CustomAgentConfig{ModelID: "model-1", KBSelectionMode: "none"},
+ }}}
+
+ _, err := svc.ShareAgent(
+ context.Background(), types.BuiltinQuickAnswerID, "org-1", "user-1", 84, types.OrgRoleViewer)
+ require.ErrorIs(t, err, ErrBuiltinAgentNotShareable)
+}
+
+// Shares of built-in agents made before sharing them was refused must not
+// resolve, with or without a source selector.
+func TestGetSharedAgentForTenantRefusesBuiltinAgents(t *testing.T) {
+ svc := &agentShareService{
+ shareRepo: builtinShareRepo{},
+ agentRepo: &builtinShareAgentRepo{agent: &types.CustomAgent{
+ ID: "legacy-builtin-row", TenantID: 84, IsBuiltin: true,
+ }},
+ }
+ for _, source := range []uint64{0, 84} {
+ agent, err := svc.GetSharedAgentForTenant(
+ context.Background(), 7, types.TenantRoleAdmin, "legacy-builtin-row", source)
+ require.Error(t, err, "source=%d", source)
+ require.Nil(t, agent)
+ }
+}
diff --git a/internal/application/service/agent_share_runtime_test.go b/internal/application/service/agent_share_runtime_test.go
index d8f5f9135..999fe46ff 100644
--- a/internal/application/service/agent_share_runtime_test.go
+++ b/internal/application/service/agent_share_runtime_test.go
@@ -72,7 +72,7 @@ func TestSharedAgentWebSearchReadyUsesSourceDefault(t *testing.T) {
}
func TestFilterSharedAgentWriteTools(t *testing.T) {
- got := filterSharedAgentWriteTools([]string{
+ got := withoutWikiWriteTools([]string{
tools.ToolWikiReadPage,
tools.ToolWikiFlagIssue,
tools.ToolWikiWritePage,
@@ -103,7 +103,7 @@ func TestFilterSharedAgentWriteToolsCoversAllWikiMutations(t *testing.T) {
if !strings.HasPrefix(definition.Name, "wiki_") {
continue
}
- filtered := filterSharedAgentWriteTools([]string{definition.Name})
+ filtered := withoutWikiWriteTools([]string{definition.Name})
if readOnlyWikiTools[definition.Name] {
require.Equal(t, []string{definition.Name}, filtered, "read-only wiki tool %q should remain available", definition.Name)
continue
diff --git a/internal/application/service/agent_share_scope.go b/internal/application/service/agent_share_scope.go
new file mode 100644
index 000000000..07e1ea950
--- /dev/null
+++ b/internal/application/service/agent_share_scope.go
@@ -0,0 +1,75 @@
+package service
+
+import (
+ "context"
+ "errors"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// ErrAgentKBScopeNotShareable is returned when an agent share would expose
+// knowledge bases its sharer could not share directly.
+var ErrAgentKBScopeNotShareable = errors.New(
+ "the agent's knowledge bases include ones you cannot share; only their creators or workspace admins can",
+)
+
+// kbBatchLookup loads knowledge bases by ID without a tenant filter.
+type kbBatchLookup func(ctx context.Context, ids []string) ([]*types.KnowledgeBase, error)
+
+// checkAgentKBScopeShareable applies the KB share rule (the KB's creator or a
+// workspace Admin+, as on POST /knowledge-bases/:id/shares) to the KBs an
+// agent share exposes: every member of the organization gets read access to
+// the agent's KB scope, so sharing the agent must not reach KBs the sharer
+// could not share on their own. "all" also covers KBs created later, so only
+// an Admin may share it.
+//
+// Only KBs that after adds to before are checked, so editing a shared agent
+// without widening its scope never fails; before is nil when the agent is
+// being shared.
+func checkAgentKBScopeShareable(
+ ctx context.Context, lookup kbBatchLookup, before, after *types.CustomAgent, userID string,
+) error {
+ if canShareAnyKB(ctx) {
+ return nil
+ }
+ previous := types.NewSharedAgentKBScope(before)
+ next := types.NewSharedAgentKBScope(after)
+ if next.IsAll() {
+ if previous.IsAll() {
+ return nil
+ }
+ return ErrAgentKBScopeNotShareable
+ }
+ var added []string
+ for _, id := range next.IDs() {
+ if !previous.Allows(id, after.TenantID) {
+ added = append(added, id)
+ }
+ }
+ if len(added) == 0 {
+ return nil
+ }
+ kbs, err := lookup(ctx, added)
+ if err != nil {
+ return err
+ }
+ for _, kb := range kbs {
+ // A KB of another workspace is outside an agent share's scope.
+ if kb == nil || kb.TenantID != after.TenantID {
+ continue
+ }
+ if kb.CreatorID == "" || kb.CreatorID != userID {
+ return ErrAgentKBScopeNotShareable
+ }
+ }
+ return nil
+}
+
+// canShareAnyKB mirrors the Admin branch of the KB share route guard; share
+// management is limited to full-access API keys.
+func canShareAnyKB(ctx context.Context) bool {
+ if scope, ok := types.TenantAPIKeyScopeFromContext(ctx); ok {
+ return scope.FullAccess
+ }
+ return types.TenantRoleFromContext(ctx).HasPermission(types.TenantRoleAdmin)
+}
diff --git a/internal/application/service/agent_share_scope_test.go b/internal/application/service/agent_share_scope_test.go
new file mode 100644
index 000000000..8e2fdd211
--- /dev/null
+++ b/internal/application/service/agent_share_scope_test.go
@@ -0,0 +1,123 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/stretchr/testify/require"
+)
+
+// Workspace 42: "mine" was created by the sharer, "colleague" by someone else,
+// "legacy" has no creator; "foreign" belongs to another workspace.
+func scopeTestLookup(_ context.Context, ids []string) ([]*types.KnowledgeBase, error) {
+ all := map[string]*types.KnowledgeBase{
+ "mine": {ID: "mine", TenantID: 42, CreatorID: "sharer"},
+ "colleague": {ID: "colleague", TenantID: 42, CreatorID: "someone-else"},
+ "legacy": {ID: "legacy", TenantID: 42},
+ "foreign": {ID: "foreign", TenantID: 7, CreatorID: "someone-else"},
+ }
+ var out []*types.KnowledgeBase
+ for _, id := range ids {
+ if kb, ok := all[id]; ok {
+ out = append(out, kb)
+ }
+ }
+ return out, nil
+}
+
+func scopedAgent(mode string, kbs ...string) *types.CustomAgent {
+ return &types.CustomAgent{
+ ID: "agent-1", TenantID: 42,
+ Config: types.CustomAgentConfig{KBSelectionMode: mode, KnowledgeBases: kbs},
+ }
+}
+
+func TestCheckAgentKBScopeShareable(t *testing.T) {
+ role := func(r types.TenantRole) context.Context {
+ return context.WithValue(context.Background(), types.TenantRoleContextKey, r)
+ }
+ contributor := role(types.TenantRoleContributor)
+ fullAccess := types.WithTenantAPIKeyScope(contributor, types.TenantAPIKeyScope{FullAccess: true})
+ cases := []struct {
+ name string
+ ctx context.Context
+ before, after *types.CustomAgent
+ wantErr bool
+ }{
+ {name: "own KBs", ctx: contributor, after: scopedAgent("selected", "mine")},
+ {
+ name: "another workspace's KB is outside the scope", ctx: contributor,
+ after: scopedAgent("selected", "mine", "foreign"),
+ },
+ {name: "colleague's KB", ctx: contributor, after: scopedAgent("selected", "mine", "colleague"), wantErr: true},
+ {name: "KB without a creator", ctx: contributor, after: scopedAgent("selected", "legacy"), wantErr: true},
+ {name: "all KBs", ctx: contributor, after: scopedAgent("all"), wantErr: true},
+ {name: "no KBs", ctx: contributor, after: scopedAgent("none")},
+ {name: "admin shares anything", ctx: role(types.TenantRoleAdmin), after: scopedAgent("all")},
+ {name: "full-access key", ctx: fullAccess, after: scopedAgent("all")},
+ {
+ name: "edit keeps an admin-shared all scope", ctx: contributor,
+ before: scopedAgent("all"), after: scopedAgent("all"),
+ },
+ {
+ name: "edit narrows the scope", ctx: contributor,
+ before: scopedAgent("selected", "colleague", "mine"), after: scopedAgent("selected", "colleague"),
+ },
+ {
+ name: "edit adds a colleague's KB", ctx: contributor,
+ before: scopedAgent("selected", "mine"), after: scopedAgent("selected", "mine", "colleague"), wantErr: true,
+ },
+ {
+ name: "edit widens to all", ctx: contributor,
+ before: scopedAgent("selected", "mine"), after: scopedAgent("all"), wantErr: true,
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ err := checkAgentKBScopeShareable(tc.ctx, scopeTestLookup, tc.before, tc.after, "sharer")
+ if tc.wantErr {
+ require.ErrorIs(t, err, ErrAgentKBScopeNotShareable)
+ } else {
+ require.NoError(t, err)
+ }
+ })
+ }
+}
+
+type scopeTestAgentShareRepo struct {
+ interfaces.AgentShareRepository
+ shares []*types.AgentShare
+}
+
+func (r *scopeTestAgentShareRepo) ListByAgent(context.Context, string) ([]*types.AgentShare, error) {
+ return r.shares, nil
+}
+
+type scopeTestKBService struct {
+ interfaces.KnowledgeBaseService
+}
+
+func (scopeTestKBService) GetKnowledgeBasesByIDsOnly(
+ ctx context.Context, ids []string,
+) ([]*types.KnowledgeBase, error) {
+ return scopeTestLookup(ctx, ids)
+}
+
+// Only a shared agent is held to the share rule when it is edited.
+func TestUpdateAgentChecksSharedAgentKBScope(t *testing.T) {
+ ctx := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleContributor)
+ ctx = context.WithValue(ctx, types.UserIDContextKey, "sharer")
+ widened := types.CustomAgentConfig{KBSelectionMode: "selected", KnowledgeBases: []string{"mine", "colleague"}}
+
+ unshared := &customAgentService{agentShareRepo: &scopeTestAgentShareRepo{}, kbService: scopeTestKBService{}}
+ require.NoError(t, unshared.checkSharedAgentKBScope(ctx, scopedAgent("selected", "mine"), widened))
+
+ shared := &customAgentService{
+ agentShareRepo: &scopeTestAgentShareRepo{shares: []*types.AgentShare{{AgentID: "agent-1", SourceTenantID: 42}}},
+ kbService: scopeTestKBService{},
+ }
+ require.ErrorIs(t, shared.checkSharedAgentKBScope(ctx, scopedAgent("selected", "mine"), widened),
+ ErrAgentKBScopeNotShareable)
+}
diff --git a/internal/application/service/agent_tool_surface_test.go b/internal/application/service/agent_tool_surface_test.go
index ae87ca55d..401046414 100644
--- a/internal/application/service/agent_tool_surface_test.go
+++ b/internal/application/service/agent_tool_surface_test.go
@@ -130,3 +130,34 @@ func TestRegisterToolsKeepsDocumentReadersForWikiOnlyScope(t *testing.T) {
}
require.NotContains(t, names, tools.ToolSearchKnowledge, "chunk search needs a vector or keyword index")
}
+
+// Search targets only need read access, so wiki mutation tools are registered
+// only when a wiki KB in scope is writable for this caller.
+func TestRegisterToolsOffersWikiWritesOnlyForWritableKBs(t *testing.T) {
+ kb := &types.KnowledgeBase{ID: "kb"}
+ kb.IndexingStrategy.WikiEnabled = true
+ writeTools := []string{
+ tools.ToolWikiWritePage, tools.ToolWikiReplaceText, tools.ToolWikiRenamePage,
+ tools.ToolWikiDeletePage, tools.ToolWikiFlagIssue, tools.ToolWikiUpdateIssue,
+ }
+ allowed := append([]string{tools.ToolWikiReadPage, tools.ToolWikiReadIssue}, writeTools...)
+
+ readOnly := toolSurfaceConfig(allowed...)
+ registry := tools.NewToolRegistry()
+ require.NoError(t, newToolSurfaceService(kb).registerTools(t.Context(), registry, readOnly, nil, nil, "s"))
+ names := registry.ListTools()
+ require.Contains(t, names, tools.ToolWikiReadPage)
+ require.Contains(t, names, tools.ToolWikiReadIssue)
+ for _, name := range writeTools {
+ require.NotContains(t, names, name)
+ }
+
+ writable := toolSurfaceConfig(allowed...)
+ writable.WritableKBIDs = []string{"kb"}
+ registry = tools.NewToolRegistry()
+ require.NoError(t, newToolSurfaceService(kb).registerTools(t.Context(), registry, writable, nil, nil, "s"))
+ names = registry.ListTools()
+ for _, name := range writeTools {
+ require.Contains(t, names, name)
+ }
+}
diff --git a/internal/application/service/custom_agent.go b/internal/application/service/custom_agent.go
index f41cdcbb1..b2ed591f5 100644
--- a/internal/application/service/custom_agent.go
+++ b/internal/application/service/custom_agent.go
@@ -43,6 +43,7 @@ type customAgentService struct {
wikiPageRepo interfaces.WikiPageRepository
tagRepo interfaces.KnowledgeTagRepository
knowledgeRepo interfaces.KnowledgeRepository
+ agentShareRepo interfaces.AgentShareRepository
}
// NewCustomAgentService creates a new custom agent service
@@ -54,6 +55,7 @@ func NewCustomAgentService(
wikiPageRepo interfaces.WikiPageRepository,
tagRepo interfaces.KnowledgeTagRepository,
knowledgeRepo interfaces.KnowledgeRepository,
+ agentShareRepo interfaces.AgentShareRepository,
) interfaces.CustomAgentService {
return &customAgentService{
repo: repo,
@@ -63,6 +65,7 @@ func NewCustomAgentService(
wikiPageRepo: wikiPageRepo,
tagRepo: tagRepo,
knowledgeRepo: knowledgeRepo,
+ agentShareRepo: agentShareRepo,
}
}
@@ -304,6 +307,9 @@ func (s *customAgentService) UpdateAgent(
}
existingAgent.Avatar = *avatar
}
+ if err := s.checkSharedAgentKBScope(ctx, existingAgent, agent.Config); err != nil {
+ return nil, err
+ }
existingAgent.Config = agent.Config
existingAgent.UpdatedAt = time.Now()
@@ -326,6 +332,35 @@ func (s *customAgentService) UpdateAgent(
return existingAgent, nil
}
+// checkSharedAgentKBScope keeps an edit from widening a shared agent's KB
+// scope beyond what the editor could share: the share was checked when it was
+// made, and receivers see the agent's current scope.
+func (s *customAgentService) checkSharedAgentKBScope(
+ ctx context.Context, existing *types.CustomAgent, config types.CustomAgentConfig,
+) error {
+ if s.agentShareRepo == nil || s.kbService == nil {
+ return nil
+ }
+ shares, err := s.agentShareRepo.ListByAgent(ctx, existing.ID)
+ if err != nil {
+ return err
+ }
+ shared := false
+ for _, share := range shares {
+ if share != nil && share.SourceTenantID == existing.TenantID {
+ shared = true
+ break
+ }
+ }
+ if !shared {
+ return nil
+ }
+ updated := *existing
+ updated.Config = config
+ userID, _ := types.UserIDFromContext(ctx)
+ return checkAgentKBScopeShareable(ctx, s.kbService.GetKnowledgeBasesByIDsOnly, existing, &updated, userID)
+}
+
// updateBuiltinAgent updates a built-in agent's configuration (but not basic info)
func (s *customAgentService) updateBuiltinAgent(ctx context.Context, agent *types.CustomAgent, tenantID uint64) (*types.CustomAgent, error) {
// Persist locale-independent display fields (the YAML "default" locale) so
diff --git a/internal/application/service/kb_writable_test.go b/internal/application/service/kb_writable_test.go
new file mode 100644
index 000000000..28ca0c7fc
--- /dev/null
+++ b/internal/application/service/kb_writable_test.go
@@ -0,0 +1,56 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+// writableShareLookup mimics CheckTenantKBPermission: editor shares are capped
+// at viewer for a tenant Viewer caller.
+type writableShareLookup map[string]types.OrgMemberRole
+
+func (l writableShareLookup) CheckTenantKBPermission(
+ _ context.Context, kbID string, _ uint64, role types.TenantRole,
+) (types.OrgMemberRole, bool, error) {
+ permission, ok := l[kbID]
+ if ok && role == types.TenantRoleViewer {
+ permission = types.OrgRoleViewer
+ }
+ return permission, ok, nil
+}
+
+func TestKBWritableIDs(t *testing.T) {
+ targets := types.SearchTargets{
+ {KnowledgeBaseID: "own", TenantID: 42},
+ {KnowledgeBaseID: "shared-editor", TenantID: 7},
+ {KnowledgeBaseID: "shared-viewer", TenantID: 7},
+ {KnowledgeBaseID: "agent-scope", TenantID: 7},
+ }
+ shares := writableShareLookup{"shared-editor": types.OrgRoleEditor, "shared-viewer": types.OrgRoleViewer}
+ caller := func(role types.TenantRole, userID string) context.Context {
+ return types.WithCaller(context.Background(), types.Caller{TenantID: 42, UserID: userID, Role: role})
+ }
+ apiKey := func(scope types.TenantAPIKeyScope) context.Context {
+ return types.WithTenantAPIKeyScope(caller(types.TenantRoleViewer, "system-42"), scope)
+ }
+
+ require.Equal(t, []string{"own", "shared-editor"},
+ kbWritableIDs(caller(types.TenantRoleContributor, "u"), shares, targets, true))
+ require.Equal(t, []string{"own"}, kbWritableIDs(caller(types.TenantRoleContributor, ""), shares, targets, true),
+ "callers without a user do not expand through org shares")
+
+ // A tenant Viewer (also the IM / embed / MCP endpoint principals) is
+ // read-only, like on the HTTP write routes; with RBAC enforcement off the
+ // role check only logs, but a share never grants a Viewer more than read.
+ require.Empty(t, kbWritableIDs(caller(types.TenantRoleViewer, "u"), shares, targets, true))
+ require.Equal(t, []string{"own"}, kbWritableIDs(caller(types.TenantRoleViewer, "u"), shares, targets, false))
+
+ // Scoped API keys write only with the ingest capability.
+ chatOnly := types.TenantAPIKeyScope{Capabilities: types.StringArray{string(types.APIKeyCapabilityChat)}}
+ require.Empty(t, kbWritableIDs(apiKey(chatOnly), shares, targets, true))
+ ingest := types.TenantAPIKeyScope{Capabilities: types.StringArray{string(types.APIKeyCapabilityIngest)}}
+ require.Equal(t, []string{"own"}, kbWritableIDs(apiKey(ingest), shares, targets, true))
+}
diff --git a/internal/application/service/kbshare.go b/internal/application/service/kbshare.go
index a17676cbf..05b7b390b 100644
--- a/internal/application/service/kbshare.go
+++ b/internal/application/service/kbshare.go
@@ -148,17 +148,8 @@ func (s *kbShareService) ShareKnowledgeBase(ctx context.Context, kbID string, or
return share, nil
}
-// UpdateSharePermission updates a share's permission.
-// Allowed if any one of:
-//
-// (1) the caller is the original sharer (same user id);
-// (2) the caller's tenant IS the source tenant and the caller is
-// Admin+ in their tenant — Plan 3 says ownership of a shared
-// resource is tenant-level, so any Admin in the source tenant
-// can manage what their tenant has shared, even if the original
-// sharer user has left or moved tenants;
-// (3) the caller's tenant is admin in the target org. The latter
-// lets org admins repair shares when the original sharer leaves.
+// UpdateSharePermission updates a share's permission. See canManageShare for
+// who may do so; an org admin outside the source tenant may only lower it.
func (s *kbShareService) UpdateSharePermission(ctx context.Context, shareID string, permission types.OrgMemberRole, userID string, tenantID uint64) error {
share, err := s.shareRepo.GetByID(ctx, shareID)
if err != nil {
@@ -168,14 +159,18 @@ func (s *kbShareService) UpdateSharePermission(ctx context.Context, shareID stri
return err
}
- if !s.callerCanManageShare(ctx, share.SharedByUserID, share.SourceTenantID, share.OrganizationID, userID, tenantID) {
- return ErrSharePermissionDenied
- }
-
if !permission.IsValid() {
return ErrInvalidRole
}
+ record := shareRecord{
+ sharedByUserID: share.SharedByUserID, sourceTenantID: share.SourceTenantID,
+ orgID: share.OrganizationID, permission: share.Permission,
+ }
+ if !canManageShare(ctx, s.orgRepo, record, permission, userID, tenantID) {
+ return ErrSharePermissionDenied
+ }
+
share.Permission = permission
share.UpdatedAt = time.Now()
@@ -188,8 +183,7 @@ func (s *kbShareService) UpdateSharePermission(ctx context.Context, shareID stri
return nil
}
-// RemoveShare removes a share.
-// Same authz envelope as UpdateSharePermission — see callerCanManageShare.
+// RemoveShare removes a share. See canManageShare for who may do so.
func (s *kbShareService) RemoveShare(ctx context.Context, shareID string, userID string, tenantID uint64) error {
share, err := s.shareRepo.GetByID(ctx, shareID)
if err != nil {
@@ -199,48 +193,73 @@ func (s *kbShareService) RemoveShare(ctx context.Context, shareID string, userID
return err
}
- if s.callerCanManageShare(ctx, share.SharedByUserID, share.SourceTenantID, share.OrganizationID, userID, tenantID) {
- if err := s.shareRepo.Delete(ctx, shareID); err != nil {
- return err
- }
- recordKBActivity(ctx, s.audit, share.SourceTenantID, share.KnowledgeBaseID, types.AuditActionKBShareRemoved,
- "knowledge_base_share", share.ID, types.AuditOutcomeSuccess,
- map[string]any{"organization_id": share.OrganizationID, "permission": share.Permission})
- return nil
+ record := shareRecord{
+ sharedByUserID: share.SharedByUserID, sourceTenantID: share.SourceTenantID,
+ orgID: share.OrganizationID, permission: share.Permission,
}
+ if !canManageShare(ctx, s.orgRepo, record, "", userID, tenantID) {
+ return ErrSharePermissionDenied
+ }
+ if err := s.shareRepo.Delete(ctx, shareID); err != nil {
+ return err
+ }
+ recordKBActivity(ctx, s.audit, share.SourceTenantID, share.KnowledgeBaseID, types.AuditActionKBShareRemoved,
+ "knowledge_base_share", share.ID, types.AuditOutcomeSuccess,
+ map[string]any{"organization_id": share.OrganizationID, "permission": share.Permission})
+ return nil
+}
- return ErrSharePermissionDenied
+// shareRecord is the part of a KB or agent share that decides who may
+// mutate it.
+type shareRecord struct {
+ sharedByUserID string
+ sourceTenantID uint64
+ orgID string
+ permission types.OrgMemberRole
}
-// callerCanManageShare encapsulates the "who can mutate this share" rule
-// reused by Update/RemoveShare. See UpdateSharePermission's doc for the
-// three accepted shapes. callerTenantRole is read from ctx so callers
-// don't need to thread it explicitly; missing role defaults to Viewer
-// (fail-closed) via TenantRoleFromContext.
-func (s *kbShareService) callerCanManageShare(
+// canManageShare is the "who can mutate this share" rule for KB and agent
+// shares. requested is the new permission of an update and empty for a
+// removal. The caller's tenant role comes from ctx; a missing role counts as
+// Viewer (fail-closed). Allowed callers:
+//
+// (1) the original sharer, acting from the source tenant as Contributor+
+// — the user ID alone is not proof once they left or were demoted;
+// (2) a source-tenant Admin+: Plan 3 ownership is tenant-level, so any
+// Admin can manage what the tenant shared after the sharer has gone;
+// (3) an Admin+ of a tenant that is admin in the target org, for
+// governance (e.g. repairing shares whose sharer left). It may remove a
+// share or lower its permission, but never grant more than the source
+// tenant did: that would hand every editor member write access to
+// another tenant's KB. The tenant-role floor matches the
+// /organizations management routes.
+func canManageShare(
ctx context.Context,
- shareSharedByUserID string,
- shareSourceTenantID uint64,
- shareOrgID string,
+ orgRepo interfaces.OrganizationRepository,
+ share shareRecord,
+ requested types.OrgMemberRole,
callerUserID string,
callerTenantID uint64,
) bool {
- // (1) Original sharer.
- if shareSharedByUserID == callerUserID {
- return true
- }
- // (2) Source-tenant Admin+ — Plan 3 ownership is tenant-level.
- if callerTenantID != 0 && callerTenantID == shareSourceTenantID {
- role := types.TenantRoleFromContext(ctx)
- if role.HasPermission(types.TenantRoleAdmin) {
+ if callerTenantID == 0 {
+ return false
+ }
+ role := types.TenantRoleFromContext(ctx)
+ if callerTenantID == share.sourceTenantID {
+ isSharer := callerUserID != "" && share.sharedByUserID == callerUserID &&
+ role.HasPermission(types.TenantRoleContributor)
+ if isSharer || role.HasPermission(types.TenantRoleAdmin) {
return true
}
}
- // (3) Org admin in the target org (governance / sharer-left repair).
- if tm, err := s.orgRepo.GetTenantMember(ctx, shareOrgID, callerTenantID); err == nil && tm.Role == types.OrgRoleAdmin {
- return true
+ if !role.HasPermission(types.TenantRoleAdmin) {
+ return false
}
- return false
+ if requested != "" && !share.permission.HasPermission(requested) {
+ return false
+ }
+ tm, err := orgRepo.GetTenantMember(ctx, share.orgID, callerTenantID)
+ return err == nil && tm.Role == types.OrgRoleAdmin
}
// ListSharesByKnowledgeBase lists shares for a knowledge base; caller's tenant must own the KB.
@@ -469,6 +488,14 @@ func (s *kbShareService) CheckTenantKBPermission(ctx context.Context, kbID strin
isShared := false
for _, share := range shares {
+ // A share lapses with its organization and with its source tenant's
+ // membership (see kbShareSourceMemberJoin).
+ if share.Organization == nil {
+ continue
+ }
+ if _, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, share.SourceTenantID); err != nil {
+ continue
+ }
tm, err := s.orgRepo.GetTenantMember(ctx, share.OrganizationID, callerTenantID)
if err != nil {
continue
diff --git a/internal/application/service/knowledgebase_access.go b/internal/application/service/knowledgebase_access.go
index b7d4a8a7a..b08bf99df 100644
--- a/internal/application/service/knowledgebase_access.go
+++ b/internal/application/service/knowledgebase_access.go
@@ -18,6 +18,49 @@ func kbReadPermissions(ctx context.Context, shares access.KBShareLookup) *access
return access.NewKBPermissions(ctx, shares)
}
+// kbWritableIDs returns the target KBs the caller may modify: those of its own
+// workspace, and those shared to it with at least editor permission (capped by
+// the caller's tenant role). A read grant — a viewer share or a shared agent's
+// scope — never makes a KB writable.
+//
+// The caller must also be allowed to write KB content at all, as on the HTTP
+// write routes: Contributor+ (a tenant Viewer, and the IM, embed and MCP
+// endpoint principals that run as Viewer, stay read-only), or for a scoped API
+// key the ingest capability, as in access.RequireKBWrite. roleEnforced mirrors
+// the RBAC rollout switch, under which role checks only log.
+func kbWritableIDs(
+ ctx context.Context, shares access.KBShareLookup, targets types.SearchTargets, roleEnforced bool,
+) []string {
+ caller := types.CallerFromContext(ctx)
+ if scope, ok := types.TenantAPIKeyScopeFromContext(ctx); ok {
+ if !scope.FullAccess && !scope.HasCapability(types.APIKeyCapabilityIngest) {
+ return nil
+ }
+ } else if roleEnforced && !caller.Role.HasPermission(types.TenantRoleContributor) {
+ return nil
+ }
+ if caller.UserID == "" {
+ shares = nil
+ }
+ permissions := access.NewKBSharePermissions(ctx, shares, caller.TenantID, caller.Role)
+ seen := make(map[string]bool, len(targets))
+ var ids []string
+ for _, target := range targets {
+ if target == nil || target.KnowledgeBaseID == "" || seen[target.KnowledgeBaseID] {
+ continue
+ }
+ seen[target.KnowledgeBaseID] = true
+ writable := caller.TenantID != 0 && target.TenantID == caller.TenantID
+ if !writable {
+ writable, _ = permissions.Check(target.KnowledgeBaseID, types.OrgRoleEditor)
+ }
+ if writable {
+ ids = append(ids, target.KnowledgeBaseID)
+ }
+ }
+ return ids
+}
+
func resolveKBReadTenant(ctx context.Context, kb *types.KnowledgeBase, shares access.KBShareLookup) (uint64, error) {
if kb != nil {
allowed, err := kbReadPermissions(ctx, shares).Check(kb.ID, kb.TenantID, types.OrgRoleViewer)
diff --git a/internal/application/service/mcp_endpoint.go b/internal/application/service/mcp_endpoint.go
index 53a0ab8bb..c354dad23 100644
--- a/internal/application/service/mcp_endpoint.go
+++ b/internal/application/service/mcp_endpoint.go
@@ -124,6 +124,9 @@ func (s *mcpEndpointService) Create(
DefaultAgentID: agentID,
RateLimitPerMinute: rate,
}
+ if err := requireKeyCoversEndpoint(ctx, row); err != nil {
+ return nil, "", err
+ }
if err := s.repo.Create(ctx, row); err != nil {
return nil, "", err
}
@@ -189,6 +192,9 @@ func (s *mcpEndpointService) Update(
}
ep.RateLimitPerMinute = rate
}
+ if err := requireKeyCoversEndpoint(ctx, ep); err != nil {
+ return nil, err
+ }
if err := s.repo.Update(ctx, ep); err != nil {
return nil, err
}
@@ -209,6 +215,9 @@ func (s *mcpEndpointService) RotateToken(
if err != nil {
return nil, "", err
}
+ if err := requireKeyCoversEndpoint(ctx, ep); err != nil {
+ return nil, "", err
+ }
token, err := generateMCPEndpointToken()
if err != nil {
return nil, "", err
@@ -221,6 +230,40 @@ func (s *mcpEndpointService) RotateToken(
return ep, token, nil
}
+// requireKeyCoversEndpoint keeps a scoped API key from minting an endpoint
+// token with more authority than the key holds. The token is a new credential
+// whose scope comes from the endpoint, so the endpoint's KBs must lie inside
+// the key's allow-list (an empty list means the whole workspace) and its tools
+// may need only capabilities the key has. Rotating counts too: it hands out
+// the existing endpoint's authority.
+func requireKeyCoversEndpoint(ctx context.Context, ep *types.MCPEndpoint) error {
+ scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
+ if !ok || scope.FullAccess {
+ return nil
+ }
+ if len(scope.KnowledgeBaseIDs) > 0 {
+ if len(ep.KnowledgeBaseIDs) == 0 {
+ return apperrors.NewForbiddenError("this API key may only create endpoints limited to its knowledge bases")
+ }
+ allowed := make(map[string]bool, len(scope.KnowledgeBaseIDs))
+ for _, id := range scope.KnowledgeBaseIDs {
+ allowed[id] = true
+ }
+ for _, id := range ep.KnowledgeBaseIDs {
+ if !allowed[id] {
+ return apperrors.NewForbiddenError("knowledge base is outside this API key's scope: " + id)
+ }
+ }
+ }
+ for _, capability := range types.MCPEndpointCapabilitiesForTools(ep.Tools) {
+ if !scope.HasCapability(types.APIKeyCapability(capability)) {
+ return apperrors.NewForbiddenError(
+ "this API key lacks the " + capability + " capability the endpoint's tools need")
+ }
+ }
+ return nil
+}
+
func (s *mcpEndpointService) Authenticate(
ctx context.Context, endpointID, token string,
) (*types.MCPEndpoint, error) {
diff --git a/internal/application/service/mcp_endpoint_test.go b/internal/application/service/mcp_endpoint_test.go
index 6a066a12f..e7ca9e3f3 100644
--- a/internal/application/service/mcp_endpoint_test.go
+++ b/internal/application/service/mcp_endpoint_test.go
@@ -269,3 +269,54 @@ func TestMCPEndpointRejectsInternalBuiltinAgent(t *testing.T) {
t.Fatalf("internal builtin agent must be rejected, got %v", err)
}
}
+
+// A scoped API key must not mint an endpoint token with more authority than
+// it holds: neither a wider KB scope nor tools needing capabilities it lacks.
+func TestMCPEndpointScopedKeyCannotExceedItsOwnScope(t *testing.T) {
+ requireForbidden := func(t *testing.T, err error) {
+ t.Helper()
+ if appErr, ok := apperrors.IsAppError(err); !ok || appErr.Code != apperrors.ErrForbidden {
+ t.Fatalf("want forbidden, got %v", err)
+ }
+ }
+ keyCtx := func(kbIDs []string, capabilities ...types.APIKeyCapability) context.Context {
+ caps := types.StringArray{string(types.APIKeyCapabilityManageChannels)}
+ for _, c := range capabilities {
+ caps = append(caps, string(c))
+ }
+ return types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
+ KnowledgeBaseIDs: types.StringArray(kbIDs), Capabilities: caps,
+ })
+ }
+ search := types.StringArray{types.MCPEndpointToolSearchKnowledge}
+ ingest := types.StringArray{types.MCPEndpointToolSearchKnowledge, types.MCPEndpointToolDeleteDocument}
+
+ svc := newMCPEndpointServiceForTest(newStubMCPEndpointRepo(), nil)
+ // A KB-restricted key cannot create a workspace-wide endpoint.
+ _, _, err := svc.Create(keyCtx([]string{"kb-a"}, types.APIKeyCapabilityRetrieve), 7,
+ &types.MCPEndpoint{Name: "wide", Tools: search})
+ requireForbidden(t, err)
+ // Nor tools needing a capability the key lacks.
+ _, _, err = svc.Create(keyCtx(nil, types.APIKeyCapabilityRetrieve), 7,
+ &types.MCPEndpoint{Name: "writer", Tools: ingest})
+ requireForbidden(t, err)
+ // Within its own scope it may.
+ ep, _, err := svc.Create(keyCtx(nil, types.APIKeyCapabilityRetrieve), 7,
+ &types.MCPEndpoint{Name: "reader", Tools: search})
+ if err != nil {
+ t.Fatalf("create within scope: %v", err)
+ }
+
+ // Widening an endpoint, or taking over one created by an admin, is checked
+ // against the endpoint the key would end up holding.
+ ingestTools := []string(ingest)
+ _, err = svc.Update(keyCtx(nil, types.APIKeyCapabilityRetrieve), 7, ep.ID,
+ interfaces.MCPEndpointUpdate{Tools: &ingestTools})
+ requireForbidden(t, err)
+ adminEP, _, err := svc.Create(context.Background(), 7, &types.MCPEndpoint{Name: "admin", Tools: ingest})
+ if err != nil {
+ t.Fatalf("admin create: %v", err)
+ }
+ _, _, err = svc.RotateToken(keyCtx(nil, types.APIKeyCapabilityRetrieve), 7, adminEP.ID)
+ requireForbidden(t, err)
+}
diff --git a/internal/application/service/organization.go b/internal/application/service/organization.go
index 14a74f7c3..3e1fcf870 100644
--- a/internal/application/service/organization.go
+++ b/internal/application/service/organization.go
@@ -402,21 +402,37 @@ func (s *organizationService) RemoveTenantMember(ctx context.Context, orgID stri
return ErrCannotRemoveOwner
}
- if operatorTenantID == memberTenantID {
- // Self-removal: any tenant can leave on their own behalf.
- return s.orgRepo.RemoveTenantMember(ctx, orgID, memberTenantID)
+ if operatorTenantID != memberTenantID {
+ // Removing another tenant requires org admin; any tenant may leave on
+ // its own behalf.
+ isAdmin, err := s.IsTenantOrgAdmin(ctx, orgID, operatorTenantID)
+ if err != nil {
+ return err
+ }
+ if !isAdmin {
+ return ErrOrgPermissionDenied
+ }
}
+ _ = operatorUserID
- isAdmin, err := s.IsTenantOrgAdmin(ctx, orgID, operatorTenantID)
- if err != nil {
+ if err := s.orgRepo.RemoveTenantMember(ctx, orgID, memberTenantID); err != nil {
return err
}
- if !isAdmin {
- return ErrOrgPermissionDenied
- }
- _ = operatorUserID
+ s.revokeTenantShares(ctx, orgID, memberTenantID)
+ return nil
+}
- return s.orgRepo.RemoveTenantMember(ctx, orgID, memberTenantID)
+// revokeTenantShares withdraws what a departing tenant shared into the org:
+// otherwise the remaining members keep reading (or editing) its KBs and
+// running its agents on its models. Share reads also require the source
+// tenant's membership, so a failure here cannot leave the shares effective.
+func (s *organizationService) revokeTenantShares(ctx context.Context, orgID string, tenantID uint64) {
+ if err := s.shareRepo.DeleteByOrganizationAndSourceTenant(ctx, orgID, tenantID); err != nil {
+ logger.Warnf(ctx, "Failed to revoke KB shares of tenant %d in organization %s: %v", tenantID, orgID, err)
+ }
+ if err := s.agentShareRepo.DeleteByOrganizationAndSourceTenant(ctx, orgID, tenantID); err != nil {
+ logger.Warnf(ctx, "Failed to revoke agent shares of tenant %d in organization %s: %v", tenantID, orgID, err)
+ }
}
// UpdateTenantMemberRole updates the role for a (org, tenant) membership.
diff --git a/internal/application/service/session_agent_qa.go b/internal/application/service/session_agent_qa.go
index f15cc2782..af890c7a5 100644
--- a/internal/application/service/session_agent_qa.go
+++ b/internal/application/service/session_agent_qa.go
@@ -326,6 +326,13 @@ func (s *sessionService) buildAgentConfig(
RetainRetrievalHistory: customAgent.Config.RetainRetrievalHistory,
SharedAgentReadOnly: req.SharedAgentReadOnly,
}
+ // An unset MCP mode means "all" at runtime, but the share scope and the
+ // agent UI both present it as none. A shared run must not hand receivers
+ // every MCP service (with the owner's credentials) that its owner believes
+ // is off.
+ if req.SharedAgentReadOnly && agentConfig.MCPSelectionMode == "" {
+ agentConfig.MCPSelectionMode = "none"
+ }
// Falls back to global configuration if no specific timeout is set for the agent.
if agentConfig.LLMCallTimeout == 0 && s.cfg.Agent != nil && s.cfg.Agent.LLMCallTimeout > 0 {
@@ -419,6 +426,10 @@ func (s *sessionService) buildAgentConfig(
return nil, fmt.Errorf("build search targets: %w", err)
}
agentConfig.SearchTargets = searchTargets
+ if !req.SharedAgentReadOnly {
+ roleEnforced := s.cfg != nil && s.cfg.Tenant.IsRBACEnforced()
+ agentConfig.WritableKBIDs = kbWritableIDs(ctx, s.kbShareService, searchTargets, roleEnforced)
+ }
agentConfig.QuestionOrigin = questionOriginInTargets(ctx, req.QuestionOrigin, searchTargets)
// Document tags are stored in knowledge_tag_relations, so document-KB tag
// scopes are resolved to concrete knowledge IDs before retrieval. Preserve
diff --git a/internal/application/service/session_knowledge_qa.go b/internal/application/service/session_knowledge_qa.go
index 6cdfe06fd..1b886157d 100644
--- a/internal/application/service/session_knowledge_qa.go
+++ b/internal/application/service/session_knowledge_qa.go
@@ -25,12 +25,13 @@ func (s *sessionService) KnowledgeQA(
req *types.QARequest,
eventBus *event.EventBus,
) error {
+ webSearchEnabled := resolveWebSearchEnabled(req)
logger.Infof(
ctx,
"Knowledge base question answering parameters, session ID: %s, query: %s, webSearchEnabled: %v",
req.Session.ID,
req.Query,
- req.WebSearchEnabled,
+ webSearchEnabled,
)
// Span the request setup (KB / model resolution, search target building,
@@ -125,7 +126,7 @@ func (s *sessionService) KnowledgeQA(
EnableQueryExpansion: s.cfg.Conversation.EnableQueryExpansion,
RewritePromptSystem: s.cfg.Conversation.RewritePromptSystem,
RewritePromptUser: s.cfg.Conversation.RewritePromptUser,
- WebSearchEnabled: req.WebSearchEnabled,
+ WebSearchEnabled: webSearchEnabled,
WebSearchProviderID: s.resolveWebSearchProviderID(ctx, req, retrievalTenantID),
WebSearchMaxResults: s.resolveWebSearchMaxResults(ctx, req),
WebFetchEnabled: s.resolveWebFetchEnabled(req),
@@ -165,7 +166,7 @@ func (s *sessionService) KnowledgeQA(
// empty but produce SearchTargets, so the unified targets must participate in
// this decision or the request is incorrectly downgraded to pure chat.
hasKB := types.HasKnowledgeRetrievalScope(searchTargets, knowledgeBaseIDs, knowledgeIDs)
- needsRAG := hasKB || req.WebSearchEnabled
+ needsRAG := hasKB || webSearchEnabled
hasHistory := chatManage.MaxRounds > 0
var pipeline []types.EventType
@@ -197,7 +198,7 @@ func (s *sessionService) KnowledgeQA(
Add(types.QUERY_UNDERSTAND).
Add(types.CHUNK_SEARCH_PARALLEL).
Add(types.CHUNK_RERANK).
- AddIf(req.WebSearchEnabled, types.WEB_FETCH).
+ AddIf(webSearchEnabled, types.WEB_FETCH).
Add(types.CHUNK_MERGE).
Add(types.FILTER_TOP_K).
AddIf(chatManage.DataAnalysisEnabled, types.DATA_ANALYSIS).
@@ -207,7 +208,7 @@ func (s *sessionService) KnowledgeQA(
}
logger.Infof(ctx, "Assembled pipeline (%d stages), hasKB=%v, webSearch=%v, history=%v",
- len(pipeline), hasKB, req.WebSearchEnabled, hasHistory)
+ len(pipeline), hasKB, webSearchEnabled, hasHistory)
// Start knowledge QA event processing (set session tenant so pipeline session/message lookups use session owner)
ctx = context.WithValue(ctx, types.SessionTenantIDContextKey, req.Session.TenantID)
@@ -1264,6 +1265,17 @@ func (s *sessionService) resolveWebSearchProviderID(ctx context.Context, req *ty
return ""
}
+// resolveWebSearchEnabled combines the request switch with the agent's own
+// setting, as agent mode does: the switch only opts a turn in, so a client
+// cannot turn on a search (and spend the agent workspace's provider quota)
+// that the agent disables. Requests without an agent keep the switch.
+func resolveWebSearchEnabled(req *types.QARequest) bool {
+ if req.CustomAgent != nil {
+ return req.CustomAgent.Config.WebSearchEnabled && req.WebSearchEnabled
+ }
+ return req.WebSearchEnabled
+}
+
// resolveWebFetchEnabled returns whether auto web fetch is enabled for this request.
func (s *sessionService) resolveWebFetchEnabled(req *types.QARequest) bool {
if req.CustomAgent != nil {
diff --git a/internal/application/service/session_model_requirement_test.go b/internal/application/service/session_model_requirement_test.go
index bda571830..00a993229 100644
--- a/internal/application/service/session_model_requirement_test.go
+++ b/internal/application/service/session_model_requirement_test.go
@@ -201,3 +201,42 @@ func TestResolveChatModelIDWikiFixerFallsBackToAvailableModel(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, "system-chat", modelID)
}
+
+// A shared agent executes in its owner's workspace; the override would pick
+// any of the owner's models there, so the configured model is used instead.
+func TestResolveChatModelIDIgnoresOverrideForSharedAgents(t *testing.T) {
+ svc := &sessionService{
+ modelService: &stubModelService{
+ modelsByID: map[string]*types.Model{
+ "agent-chat": {ID: "agent-chat", Type: types.ModelTypeKnowledgeQA},
+ "owner-other-model": {ID: "owner-other-model", Type: types.ModelTypeKnowledgeQA},
+ },
+ },
+ }
+ req := &types.QARequest{
+ Session: &types.Session{},
+ CustomAgent: &types.CustomAgent{
+ ID: "agent-1",
+ Config: types.CustomAgentConfig{ModelID: "agent-chat"},
+ },
+ SummaryModelID: "owner-other-model",
+ SharedAgentReadOnly: true,
+ }
+
+ modelID, err := svc.resolveChatModelID(context.Background(), req, nil, nil)
+
+ require.NoError(t, err)
+ assert.Equal(t, "agent-chat", modelID)
+}
+
+// Quick-answer mode follows the same rule as agent mode: the request switch
+// only opts a turn in and cannot enable search the agent turns off.
+func TestResolveWebSearchEnabled(t *testing.T) {
+ agent := func(enabled bool) *types.CustomAgent {
+ return &types.CustomAgent{Config: types.CustomAgentConfig{WebSearchEnabled: enabled}}
+ }
+ assert.False(t, resolveWebSearchEnabled(&types.QARequest{CustomAgent: agent(false), WebSearchEnabled: true}))
+ assert.False(t, resolveWebSearchEnabled(&types.QARequest{CustomAgent: agent(true), WebSearchEnabled: false}))
+ assert.True(t, resolveWebSearchEnabled(&types.QARequest{CustomAgent: agent(true), WebSearchEnabled: true}))
+ assert.True(t, resolveWebSearchEnabled(&types.QARequest{WebSearchEnabled: true}), "no agent keeps the switch")
+}
diff --git a/internal/application/service/session_qa_helpers.go b/internal/application/service/session_qa_helpers.go
index 65eccaff4..65786c407 100644
--- a/internal/application/service/session_qa_helpers.go
+++ b/internal/application/service/session_qa_helpers.go
@@ -132,6 +132,12 @@ func (s *sessionService) resolveChatModelID(
customAgent := req.CustomAgent
session := req.Session
configuredAgentModelID := ""
+ // A shared agent runs in its owner's workspace, where an override could
+ // pick any of the owner's models rather than the one the agent was
+ // configured with.
+ if req.SharedAgentReadOnly {
+ summaryModelID = ""
+ }
if customAgent != nil {
configuredAgentModelID = strings.TrimSpace(customAgent.Config.ModelID)
diff --git a/internal/application/service/share_management_test.go b/internal/application/service/share_management_test.go
new file mode 100644
index 000000000..e8a3bddfb
--- /dev/null
+++ b/internal/application/service/share_management_test.go
@@ -0,0 +1,173 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/application/repository"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/stretchr/testify/require"
+)
+
+// Tenant 10 shared the KB (as user "sharer") into org-1; tenant 20 is an org
+// admin; tenant 30 is a plain org editor.
+type shareMgmtOrgRepo struct {
+ interfaces.OrganizationRepository
+}
+
+func (shareMgmtOrgRepo) GetTenantMember(
+ _ context.Context, _ string, tenantID uint64,
+) (*types.OrganizationTenantMember, error) {
+ switch tenantID {
+ case 10:
+ return &types.OrganizationTenantMember{TenantID: 10, Role: types.OrgRoleEditor}, nil
+ case 20:
+ return &types.OrganizationTenantMember{TenantID: 20, Role: types.OrgRoleAdmin}, nil
+ case 30:
+ return &types.OrganizationTenantMember{TenantID: 30, Role: types.OrgRoleEditor}, nil
+ }
+ return nil, repository.ErrOrgMemberNotFound
+}
+
+type shareMgmtKBShareRepo struct {
+ interfaces.KBShareRepository
+ share *types.KnowledgeBaseShare
+ updated bool
+}
+
+func (r *shareMgmtKBShareRepo) GetByID(context.Context, string) (*types.KnowledgeBaseShare, error) {
+ copied := *r.share
+ return &copied, nil
+}
+
+func (r *shareMgmtKBShareRepo) Update(context.Context, *types.KnowledgeBaseShare) error {
+ r.updated = true
+ return nil
+}
+
+func shareMgmtCtx(role types.TenantRole) context.Context {
+ return context.WithValue(context.Background(), types.TenantRoleContextKey, role)
+}
+
+func TestCanManageShare(t *testing.T) {
+ record := shareRecord{sharedByUserID: "sharer", sourceTenantID: 10, orgID: "org-1", permission: types.OrgRoleEditor}
+ cases := []struct {
+ name string
+ role types.TenantRole
+ userID string
+ tenantID uint64
+ requested types.OrgMemberRole
+ want bool
+ }{
+ {"sharer raises from source tenant", types.TenantRoleContributor, "sharer", 10, types.OrgRoleAdmin, true},
+ {"sharer demoted to viewer", types.TenantRoleViewer, "sharer", 10, types.OrgRoleAdmin, false},
+ {"sharer acting from another tenant", types.TenantRoleOwner, "sharer", 30, "", false},
+ {"source tenant admin", types.TenantRoleAdmin, "someone", 10, types.OrgRoleAdmin, true},
+ {"source tenant contributor", types.TenantRoleContributor, "someone", 10, "", false},
+ {"org admin removes", types.TenantRoleAdmin, "org-admin", 20, "", true},
+ {"org admin lowers", types.TenantRoleAdmin, "org-admin", 20, types.OrgRoleViewer, true},
+ {"org admin keeps level", types.TenantRoleAdmin, "org-admin", 20, types.OrgRoleEditor, true},
+ {"org admin raises", types.TenantRoleAdmin, "org-admin", 20, types.OrgRoleAdmin, false},
+ {"viewer inside org-admin tenant", types.TenantRoleViewer, "viewer", 20, "", false},
+ {"org editor tenant admin", types.TenantRoleAdmin, "editor-admin", 30, "", false},
+ {"non-member", types.TenantRoleOwner, "outsider", 40, "", false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx := shareMgmtCtx(tc.role)
+ got := canManageShare(ctx, shareMgmtOrgRepo{}, record, tc.requested, tc.userID, tc.tenantID)
+ require.Equal(t, tc.want, got)
+ })
+ }
+}
+
+// An org admin that does not own the KB must not escalate a viewer share: that
+// would give every editor member write access to the owner's KB.
+func TestUpdateSharePermissionRejectsOrgAdminEscalation(t *testing.T) {
+ repo := &shareMgmtKBShareRepo{share: &types.KnowledgeBaseShare{
+ ID: "share-1", KnowledgeBaseID: "kb-1", OrganizationID: "org-1",
+ SharedByUserID: "sharer", SourceTenantID: 10, Permission: types.OrgRoleViewer,
+ }}
+ svc := &kbShareService{shareRepo: repo, orgRepo: shareMgmtOrgRepo{}}
+
+ ctx := shareMgmtCtx(types.TenantRoleAdmin)
+ err := svc.UpdateSharePermission(ctx, "share-1", types.OrgRoleEditor, "org-admin", 20)
+ require.ErrorIs(t, err, ErrSharePermissionDenied)
+ require.False(t, repo.updated)
+}
+
+type revokeOrgRepo struct {
+ shareMgmtOrgRepo
+ removed uint64
+}
+
+func (*revokeOrgRepo) GetByID(context.Context, string) (*types.Organization, error) {
+ return &types.Organization{ID: "org-1", OwnerTenantID: 99}, nil
+}
+
+func (r *revokeOrgRepo) RemoveTenantMember(_ context.Context, _ string, tenantID uint64) error {
+ r.removed = tenantID
+ return nil
+}
+
+type revokeKBShareRepo struct {
+ interfaces.KBShareRepository
+ revoked []uint64
+}
+
+func (r *revokeKBShareRepo) DeleteByOrganizationAndSourceTenant(_ context.Context, _ string, tenantID uint64) error {
+ r.revoked = append(r.revoked, tenantID)
+ return nil
+}
+
+type revokeAgentShareRepo struct {
+ interfaces.AgentShareRepository
+ revoked []uint64
+}
+
+func (r *revokeAgentShareRepo) DeleteByOrganizationAndSourceTenant(_ context.Context, _ string, tenantID uint64) error {
+ r.revoked = append(r.revoked, tenantID)
+ return nil
+}
+
+// A departing tenant's shares must not keep serving its KBs and agents to the
+// remaining members, whether it left or was removed by an org admin.
+func TestRemoveTenantMemberRevokesItsShares(t *testing.T) {
+ for _, operator := range []uint64{10, 20} {
+ orgRepo := &revokeOrgRepo{}
+ kbShares := &revokeKBShareRepo{}
+ agentShares := &revokeAgentShareRepo{}
+ svc := &organizationService{orgRepo: orgRepo, shareRepo: kbShares, agentShareRepo: agentShares}
+
+ require.NoError(t, svc.RemoveTenantMember(context.Background(), "org-1", 10, "user", operator))
+ require.Equal(t, uint64(10), orgRepo.removed)
+ require.Equal(t, []uint64{10}, kbShares.revoked)
+ require.Equal(t, []uint64{10}, agentShares.revoked)
+ }
+}
+
+type lapsedShareRepo struct {
+ interfaces.KBShareRepository
+ shares []*types.KnowledgeBaseShare
+}
+
+func (r *lapsedShareRepo) ListByKnowledgeBase(context.Context, string) ([]*types.KnowledgeBaseShare, error) {
+ return r.shares, nil
+}
+
+// Shares left behind by a departed source tenant, or in a deleted
+// organization, grant nothing.
+func TestCheckTenantKBPermissionIgnoresLapsedShares(t *testing.T) {
+ org := &types.Organization{ID: "org-1"}
+ svc := &kbShareService{orgRepo: shareMgmtOrgRepo{}, shareRepo: &lapsedShareRepo{shares: []*types.KnowledgeBaseShare{
+ {OrganizationID: "org-1", SourceTenantID: 50, Permission: types.OrgRoleAdmin, Organization: org},
+ {OrganizationID: "org-1", SourceTenantID: 10, Permission: types.OrgRoleAdmin},
+ {OrganizationID: "org-1", SourceTenantID: 10, Permission: types.OrgRoleViewer, Organization: org},
+ }}}
+
+ permission, shared, err := svc.CheckTenantKBPermission(context.Background(), "kb-1", 30, types.TenantRoleAdmin)
+ require.NoError(t, err)
+ require.True(t, shared)
+ require.Equal(t, types.OrgRoleViewer, permission)
+}
diff --git a/internal/handler/custom_agent.go b/internal/handler/custom_agent.go
index 36bea15a7..c4881903b 100644
--- a/internal/handler/custom_agent.go
+++ b/internal/handler/custom_agent.go
@@ -415,6 +415,8 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {
c.Error(errors.NewForbiddenError("Cannot modify built-in agent"))
case service.ErrAgentNameRequired:
c.Error(errors.NewBadRequestError(err.Error()))
+ case service.ErrAgentKBScopeNotShareable:
+ _ = c.Error(errors.NewForbiddenError(err.Error()))
default:
// Reached only after the typed sentinels and *errors.AppError above, so
// whatever lands here is a raw repository/driver error. Its text
diff --git a/internal/handler/custom_agent_avatar_test.go b/internal/handler/custom_agent_avatar_test.go
index bd7d4581a..749cad10b 100644
--- a/internal/handler/custom_agent_avatar_test.go
+++ b/internal/handler/custom_agent_avatar_test.go
@@ -68,7 +68,7 @@ func TestCustomAgentAvatarAndErrorResponses(t *testing.T) {
agent: &types.CustomAgent{ID: "custom-1", Name: "old", Avatar: "🤖", TenantID: 1},
err: tc.repoErr,
}
- svc := service.NewCustomAgentService(repo, nil, nil, nil, nil, nil, nil)
+ svc := service.NewCustomAgentService(repo, nil, nil, nil, nil, nil, nil, nil)
h := &CustomAgentHandler{service: svc}
router := gin.New()
router.Use(middleware.ErrorHandler())
diff --git a/internal/handler/embed_channel.go b/internal/handler/embed_channel.go
index beb0b67c5..a0aa6323a 100644
--- a/internal/handler/embed_channel.go
+++ b/internal/handler/embed_channel.go
@@ -697,6 +697,9 @@ func patchEmbedChatPayload(body io.Reader, ch *types.EmbedChannel, agentMode boo
payload = make(map[string]any)
}
payload["agent_id"] = ch.AgentID
+ // The channel's agent belongs to the channel's workspace; a visitor-supplied
+ // source workspace would switch it to another workspace's share of that ID.
+ delete(payload, types.AgentSourceTenantIDParam)
payload["knowledge_base_ids"] = []string{}
clientWebSearch := false
if v, ok := payload["web_search_enabled"].(bool); ok {
diff --git a/internal/handler/embed_flow_test.go b/internal/handler/embed_flow_test.go
index 9c13cd289..93694eca9 100644
--- a/internal/handler/embed_flow_test.go
+++ b/internal/handler/embed_flow_test.go
@@ -184,7 +184,7 @@ func TestEmbedExchangeFlowIntegration(t *testing.T) {
func TestPatchEmbedChatPayloadInjectsAgentID(t *testing.T) {
ch := &types.EmbedChannel{AgentID: "agent-embed-42"}
- body := `{"query":"hello","agent_id":"client-override","web_search_enabled":true}`
+ body := `{"query":"hello","agent_id":"client-override","agent_source_tenant_id":84,"web_search_enabled":true}`
patched, err := patchEmbedChatPayload(strings.NewReader(body), ch, false)
if err != nil {
@@ -200,6 +200,10 @@ func TestPatchEmbedChatPayloadInjectsAgentID(t *testing.T) {
if payload["query"] != "hello" {
t.Fatalf("query = %v, want preserved client field", payload["query"])
}
+ if _, ok := payload[types.AgentSourceTenantIDParam]; ok {
+ t.Fatalf("agent_source_tenant_id = %v, want dropped so the channel agent stays local",
+ payload[types.AgentSourceTenantIDParam])
+ }
if payload["web_search_enabled"] != false {
t.Fatalf("web_search_enabled = %v, want false", payload["web_search_enabled"])
}
diff --git a/internal/handler/initialization.go b/internal/handler/initialization.go
index 9b9edf556..2cfd3b21e 100644
--- a/internal/handler/initialization.go
+++ b/internal/handler/initialization.go
@@ -21,6 +21,7 @@ import (
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/handler/dto"
"github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/models/asr"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/embedding"
@@ -253,6 +254,11 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {
c.Error(errors.NewNotFoundError("知识库不存在"))
return
}
+ ownWorkspace, err := kbSettingsAccess(c, kb)
+ if err != nil {
+ _ = c.Error(err)
+ return
+ }
// 检查Embedding模型是否可以修改
if kb.EmbeddingModelID != "" && req.EmbeddingModelID != "" && kb.EmbeddingModelID != req.EmbeddingModelID {
@@ -366,50 +372,18 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {
kb.VLMConfig.CustomInstructions = strings.TrimSpace(req.VLMConfig.CustomInstructions)
}
- // Bind the concrete storage instance. Provider remains a compatibility
- // projection for older clients and historical rows.
- if strings.TrimSpace(req.StorageBackendID) != "" {
- tenant, _ := types.TenantInfoFromContext(ctx)
- backend, resolveErr := h.storageResolver.ResolveBackend(ctx, tenant, req.StorageBackendID, "")
- if resolveErr != nil || backend == nil {
- c.Error(errors.NewBadRequestError("Storage backend is unavailable"))
+ // Storage backends resolve per workspace and belong to the owner's
+ // infrastructure: another workspace can neither see the owner's backends
+ // nor bind the KB to one of its own, so it may only leave them unchanged.
+ if ownWorkspace {
+ if err := h.applyKBStorageBinding(ctx, kb, kbIdStr, &req); err != nil {
+ _ = c.Error(err)
return
}
- oldID := ""
- if kb.StorageBackendID != nil {
- oldID = *kb.StorageBackendID
- }
- if oldID != "" && oldID != backend.ID {
- knowledgeList, listErr := h.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbIdStr, &types.Pagination{Page: 1, PageSize: 1}, types.KnowledgeListFilter{})
- if listErr == nil && knowledgeList != nil && knowledgeList.Total > 0 {
- c.Error(errors.NewBadRequestError("Storage backend cannot be changed while the knowledge base contains files; migrate storage first"))
- return
- }
- }
- kb.StorageBackendID = &backend.ID
- req.StorageProvider = backend.Provider
- }
- // Legacy provider projection.
- provider := strings.ToLower(strings.TrimSpace(req.StorageProvider))
- if provider == "" {
- provider = "local"
- }
- if !isStorageProviderAllowed(provider) {
- c.Error(errors.NewBadRequestError("Storage provider is not allowed by STORAGE_ALLOW_LIST"))
+ } else if kbStorageBindingChanged(kb, req.StorageBackendID, req.StorageProvider) {
+ _ = c.Error(errors.NewForbiddenError("只有知识库所属空间可以修改存储配置"))
return
}
- oldProvider := kb.GetStorageProvider()
- if oldProvider == "" {
- oldProvider = "local"
- }
- if oldProvider != provider {
- knowledgeList, err := h.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx,
- kbIdStr, &types.Pagination{Page: 1, PageSize: 1}, types.KnowledgeListFilter{})
- if err == nil && knowledgeList != nil && knowledgeList.Total > 0 {
- logger.Warn(ctx, "Storage engine changed with existing files, old files may become inaccessible")
- }
- }
- kb.SetStorageProvider(provider)
// 更新知识图谱配置
if req.NodeExtract.Enabled {
@@ -481,6 +455,95 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {
})
}
+// kbSettingsAccess reports whether the caller's workspace owns kb. Another
+// workspace may change KB settings only through an admin share: the frontend
+// offers KB settings to share admins alone, and OrgRoleEditor edits content,
+// not settings. KBAccessWrite on the route also admits share editors, so the
+// grant's effective share permission is checked here.
+func kbSettingsAccess(c *gin.Context, kb *types.KnowledgeBase) (bool, error) {
+ if kb.TenantID == types.CallerFromContext(c.Request.Context()).TenantID {
+ return true, nil
+ }
+ grant, ok := middleware.KBAccessFromContext(c)
+ if !ok || grant.KnowledgeBase == nil || grant.KnowledgeBase.ID != kb.ID ||
+ !grant.Permission.HasPermission(types.OrgRoleAdmin) {
+ return false, errors.NewForbiddenError("修改共享知识库的设置需要管理员共享权限")
+ }
+ return false, nil
+}
+
+// kbStorageBindingChanged reports whether a config request would rebind the
+// KB's storage. A backend ID that matches the current one leaves the binding
+// alone (its provider is only a projection); without one, an empty current
+// provider means the default, which clients echo back as "local".
+func kbStorageBindingChanged(kb *types.KnowledgeBase, backendID, provider string) bool {
+ backendID = strings.TrimSpace(backendID)
+ current := ""
+ if kb.StorageBackendID != nil {
+ current = *kb.StorageBackendID
+ }
+ if backendID != "" {
+ return backendID != current
+ }
+ provider = strings.ToLower(strings.TrimSpace(provider))
+ currentProvider := kb.GetStorageProvider()
+ if currentProvider == "" {
+ currentProvider = "local"
+ }
+ return provider != "" && provider != currentProvider
+}
+
+// applyKBStorageBinding binds the owner's storage instance to the KB. The
+// caller's workspace must own the KB: backends resolve against TenantInfo.
+func (h *InitializationHandler) applyKBStorageBinding(
+ ctx context.Context, kb *types.KnowledgeBase, kbID string, req *KBModelConfigRequest,
+) error {
+ // Bind the concrete storage instance. Provider remains a compatibility
+ // projection for older clients and historical rows.
+ if strings.TrimSpace(req.StorageBackendID) != "" {
+ tenant, _ := types.TenantInfoFromContext(ctx)
+ backend, resolveErr := h.storageResolver.ResolveBackend(ctx, tenant, req.StorageBackendID, "")
+ if resolveErr != nil || backend == nil {
+ return errors.NewBadRequestError("Storage backend is unavailable")
+ }
+ oldID := ""
+ if kb.StorageBackendID != nil {
+ oldID = *kb.StorageBackendID
+ }
+ if oldID != "" && oldID != backend.ID {
+ knowledgeList, listErr := h.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx,
+ kbID, &types.Pagination{Page: 1, PageSize: 1}, types.KnowledgeListFilter{})
+ if listErr == nil && knowledgeList != nil && knowledgeList.Total > 0 {
+ return errors.NewBadRequestError(
+ "Storage backend cannot be changed while the knowledge base contains files; migrate storage first")
+ }
+ }
+ kb.StorageBackendID = &backend.ID
+ req.StorageProvider = backend.Provider
+ }
+ // Legacy provider projection.
+ provider := strings.ToLower(strings.TrimSpace(req.StorageProvider))
+ if provider == "" {
+ provider = "local"
+ }
+ if !isStorageProviderAllowed(provider) {
+ return errors.NewBadRequestError("Storage provider is not allowed by STORAGE_ALLOW_LIST")
+ }
+ oldProvider := kb.GetStorageProvider()
+ if oldProvider == "" {
+ oldProvider = "local"
+ }
+ if oldProvider != provider {
+ knowledgeList, err := h.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx,
+ kbID, &types.Pagination{Page: 1, PageSize: 1}, types.KnowledgeListFilter{})
+ if err == nil && knowledgeList != nil && knowledgeList.Total > 0 {
+ logger.Warn(ctx, "Storage engine changed with existing files, old files may become inaccessible")
+ }
+ }
+ kb.SetStorageProvider(provider)
+ return nil
+}
+
// InitializeByKB godoc
// @Summary 初始化知识库配置
// @Description 根据知识库ID执行完整配置更新
@@ -572,9 +635,32 @@ func (h *InitializationHandler) getKnowledgeBaseForInitialization(ctx context.Co
logger.Error(ctx, "Knowledge base not found")
return nil, errors.NewNotFoundError("知识库不存在")
}
+ // Initialization rewrites the models the KB points at, and those rows
+ // belong to the KB's workspace. A shared-KB editor passes the route's
+ // KBAccessWrite guard (which moves execution into that workspace), so
+ // without this check it could repoint the owner's models at its own
+ // endpoint and key.
+ if kb.TenantID != types.CallerFromContext(ctx).TenantID {
+ return nil, errors.NewForbiddenError("只有知识库所属空间可以初始化知识库")
+ }
return kb, nil
}
+// canUpdateTenantModels mirrors the PUT /models/:id guard: rewriting a stored
+// model changes every KB and agent that uses it, so initializing a KB must not
+// let a KB creator do what the model settings page reserves for admins.
+func (h *InitializationHandler) canUpdateTenantModels(ctx context.Context) bool {
+ if scope, ok := types.TenantAPIKeyScopeFromContext(ctx); ok {
+ return scope.FullAccess || scope.HasCapability(types.APIKeyCapabilityManageModels)
+ }
+ if types.CallerFromContext(ctx).Role.HasPermission(types.TenantRoleAdmin) || types.IsSystemAdminFromContext(ctx) {
+ return true
+ }
+ // Same rollout switch as the route guards: role checks only log while
+ // RBAC enforcement is off.
+ return h.config == nil || !h.config.Tenant.IsRBACEnforced()
+}
+
func (h *InitializationHandler) validateInitializationConfigs(ctx context.Context, req *InitializationRequest) error {
// SSRF validation for all user-supplied BaseURLs
urlsToCheck := []struct {
@@ -763,6 +849,9 @@ func (h *InitializationHandler) processInitializationModels(
}
if existingModel != nil {
+ if !h.canUpdateTenantModels(ctx) {
+ return nil, errors.NewForbiddenError("修改已有模型配置需要空间管理员权限")
+ }
existingModel.Name = model.Name
existingModel.Source = model.Source
existingModel.Description = model.Description
@@ -1433,7 +1522,11 @@ func (h *InitializationHandler) buildConfigResponse(ctx context.Context, models
config := map[string]interface{}{
"hasFiles": hasFiles,
}
- includeIntegrationDetail := dto.CanViewIntegrationSecrets(ctx)
+ // Integration details describe the owning workspace's infrastructure. A
+ // share receiver — even an admin of its own workspace — only learns
+ // whether credentials are configured.
+ ownWorkspace := kb != nil && kb.TenantID == types.CallerFromContext(ctx).TenantID
+ includeIntegrationDetail := ownWorkspace && dto.CanViewIntegrationSecrets(ctx)
// 按类型分组模型
for _, model := range models {
@@ -1582,6 +1675,16 @@ func (h *InitializationHandler) buildConfigResponse(ctx context.Context, models
"pathPrefix": kb.StorageConfig.PathPrefix,
}
}
+ if !ownWorkspace {
+ // Bucket locations are the owner's infrastructure too.
+ for _, provider := range []string{"cos", "minio"} {
+ if detail, ok := multimodal[provider].(map[string]interface{}); ok {
+ for _, field := range []string{"region", "bucketName", "appId", "pathPrefix"} {
+ delete(detail, field)
+ }
+ }
+ }
+ }
}
}
diff --git a/internal/handler/initialization_config_redaction_test.go b/internal/handler/initialization_config_redaction_test.go
index bafc250c0..2d12d0e1f 100644
--- a/internal/handler/initialization_config_redaction_test.go
+++ b/internal/handler/initialization_config_redaction_test.go
@@ -37,6 +37,7 @@ func TestBuildConfigResponse_ViewerOmitsModelBaseURL(t *testing.T) {
func TestBuildConfigResponse_AdminKeepsModelBaseURL(t *testing.T) {
h := &InitializationHandler{}
ctx := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleAdmin)
+ ctx = types.WithCaller(ctx, types.Caller{TenantID: 42, UserID: "u", Role: types.TenantRoleAdmin})
models := []*types.Model{{
Type: types.ModelTypeKnowledgeQA,
Name: "custom-llm",
@@ -45,7 +46,7 @@ func TestBuildConfigResponse_AdminKeepsModelBaseURL(t *testing.T) {
APIKey: "sk-secret-do-not-leak",
},
}}
- kb := &types.KnowledgeBase{}
+ kb := &types.KnowledgeBase{TenantID: 42}
config := h.buildConfigResponse(ctx, models, kb, false)
llm, ok := config["llm"].(map[string]interface{})
@@ -56,3 +57,34 @@ func TestBuildConfigResponse_AdminKeepsModelBaseURL(t *testing.T) {
require.NoError(t, err)
assert.NotContains(t, string(body), "sk-secret-do-not-leak")
}
+
+// A share receiver's admin is an admin of its own workspace, not of the KB's:
+// it sees whether credentials exist, never the owner's endpoints or buckets.
+func TestBuildConfigResponse_ShareReceiverAdminSeesPresenceOnly(t *testing.T) {
+ h := &InitializationHandler{}
+ ctx := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleAdmin)
+ ctx = types.WithCaller(ctx, types.Caller{TenantID: 42, UserID: "u", Role: types.TenantRoleAdmin})
+ ctx = types.WithExecutionTenant(ctx, 7)
+ models := []*types.Model{{
+ Type: types.ModelTypeKnowledgeQA,
+ Name: "owner-llm",
+ Parameters: types.ModelParameters{BaseURL: "https://owner-private.example.com"},
+ }}
+ kb := &types.KnowledgeBase{TenantID: 7}
+ legacy := &kb.StorageConfig //nolint:staticcheck // old KBs still carry the legacy COS config
+ legacy.Provider = "cos"
+ legacy.BucketName = "owner-bucket"
+ legacy.Region = "ap-owner"
+ legacy.AppID = "owner-app"
+ legacy.SecretID = "id"
+ legacy.SecretKey = "key"
+
+ config := h.buildConfigResponse(ctx, models, kb, false)
+ body, err := json.Marshal(config)
+ require.NoError(t, err)
+ for _, detail := range []string{"owner-private.example.com", "owner-bucket", "ap-owner", "owner-app"} {
+ assert.NotContains(t, string(body), detail)
+ }
+ cos := config["multimodal"].(map[string]interface{})["cos"].(map[string]interface{})
+ assert.Equal(t, map[string]bool{"secretId": true, "secretKey": true}, cos["credentials"])
+}
diff --git a/internal/handler/initialization_owner_test.go b/internal/handler/initialization_owner_test.go
new file mode 100644
index 000000000..5dcae28d9
--- /dev/null
+++ b/internal/handler/initialization_owner_test.go
@@ -0,0 +1,189 @@
+package handler
+
+import (
+ "context"
+ stderrors "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/application/access"
+ "github.com/Tencent/WeKnora/internal/config"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/middleware"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+type stubInitializationKBService struct {
+ interfaces.KnowledgeBaseService
+ kb *types.KnowledgeBase
+}
+
+func (s *stubInitializationKBService) GetKnowledgeBaseByID(context.Context, string) (*types.KnowledgeBase, error) {
+ return s.kb, nil
+}
+
+func requireForbidden(t *testing.T, err error) {
+ t.Helper()
+ var appErr *apperrors.AppError
+ if !stderrors.As(err, &appErr) || appErr.HTTPCode != http.StatusForbidden {
+ t.Fatalf("err = %v, want 403", err)
+ }
+}
+
+// A shared-KB editor reaches the handler with execution moved into the owner
+// workspace; the KB must still be refused because the caller does not own it.
+func TestInitializationRejectsKBOfAnotherWorkspace(t *testing.T) {
+ h := &InitializationHandler{kbService: &stubInitializationKBService{
+ kb: &types.KnowledgeBase{ID: "kb-1", TenantID: 7},
+ }}
+ ctx := types.WithCaller(context.Background(), types.Caller{TenantID: 42, UserID: "u", Role: types.TenantRoleOwner})
+ ctx = types.WithExecutionTenant(ctx, 7)
+
+ _, err := h.getKnowledgeBaseForInitialization(ctx, "kb-1")
+ requireForbidden(t, err)
+}
+
+func TestInitializationAllowsOwnKB(t *testing.T) {
+ h := &InitializationHandler{kbService: &stubInitializationKBService{
+ kb: &types.KnowledgeBase{ID: "kb-1", TenantID: 42},
+ }}
+ ctx := types.WithCaller(context.Background(),
+ types.Caller{TenantID: 42, UserID: "u", Role: types.TenantRoleContributor})
+
+ if _, err := h.getKnowledgeBaseForInitialization(ctx, "kb-1"); err != nil {
+ t.Fatalf("own KB rejected: %v", err)
+ }
+}
+
+// Rewriting an already-stored model needs the same authority as PUT
+// /models/:id; creating the KB's first models does not.
+func TestInitializationExistingModelUpdateRequiresModelAuthority(t *testing.T) {
+ enforced := true
+ stored := &types.Model{ID: "m-existing", Type: types.ModelTypeKnowledgeQA, TenantID: 42}
+ kb := &types.KnowledgeBase{ID: "kb-1", TenantID: 42, SummaryModelID: "m-existing"}
+ caller := func(role types.TenantRole) context.Context {
+ return types.WithCaller(context.Background(), types.Caller{TenantID: 42, UserID: "u", Role: role})
+ }
+ scopedKey := func(capability types.APIKeyCapability) context.Context {
+ scope := types.TenantAPIKeyScope{Capabilities: types.StringArray{string(capability)}}
+ return types.WithTenantAPIKeyScope(caller(types.TenantRoleViewer), scope)
+ }
+
+ cases := []struct {
+ name string
+ ctx context.Context
+ allowed bool
+ }{
+ {"contributor", caller(types.TenantRoleContributor), false},
+ {"admin", caller(types.TenantRoleAdmin), true},
+ {"scoped key without manage_models", scopedKey(types.APIKeyCapabilityManageKnowledgeBases), false},
+ {"scoped key with manage_models", scopedKey(types.APIKeyCapabilityManageModels), true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ svc := &stubTenantStampModelService{getModelByID: func(_ context.Context, id string) (*types.Model, error) {
+ if id == stored.ID {
+ copied := *stored
+ return &copied, nil
+ }
+ return nil, nil
+ }}
+ h := &InitializationHandler{
+ modelService: svc,
+ config: &config.Config{Tenant: &config.TenantConfig{EnableRBAC: &enforced}},
+ }
+ _, err := h.processInitializationModels(tc.ctx, kb, "kb-1", newTenantStampRequest())
+ if tc.allowed {
+ if err != nil || len(svc.updated) != 1 {
+ t.Fatalf("err = %v, updated = %d, want one update", err, len(svc.updated))
+ }
+ return
+ }
+ requireForbidden(t, err)
+ if len(svc.updated) != 0 {
+ t.Fatalf("model was updated despite missing authority")
+ }
+ })
+ }
+}
+
+type stubInitializationKBRepo struct {
+ interfaces.KnowledgeBaseRepository
+ updated *types.KnowledgeBase
+}
+
+func (r *stubInitializationKBRepo) UpdateKnowledgeBase(_ context.Context, kb *types.KnowledgeBase) error {
+ r.updated = kb
+ return nil
+}
+
+// PUT /initialization/config shares the route guard (KBAccessWrite) that
+// admits share editors. KB settings belong to the owner and to admin shares
+// only, and a share admin still cannot rebind the owner's storage.
+func TestUpdateKBConfigFromAnotherWorkspace(t *testing.T) {
+ backend := "backend-of-owner"
+ cases := []struct {
+ name string
+ permission types.OrgMemberRole
+ body string
+ wantStatus int
+ }{
+ {
+ name: "share editor", permission: types.OrgRoleEditor,
+ body: `{"llmModelId":"m-llm"}`, wantStatus: http.StatusForbidden,
+ },
+ {
+ name: "share admin rebinding storage", permission: types.OrgRoleAdmin,
+ body: `{"llmModelId":"m-llm","storageBackendId":"backend-of-receiver"}`, wantStatus: http.StatusForbidden,
+ },
+ {
+ name: "share admin keeping storage", permission: types.OrgRoleAdmin,
+ body: `{"llmModelId":"m-llm","storageBackendId":"backend-of-owner","storageProvider":"minio"}`,
+ wantStatus: http.StatusOK,
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ kb := &types.KnowledgeBase{ID: "kb-1", TenantID: 7, StorageBackendID: &backend}
+ repo := &stubInitializationKBRepo{}
+ models := &stubTenantStampModelService{getModelByID: func(context.Context, string) (*types.Model, error) {
+ return &types.Model{ID: "m-llm", TenantID: 7}, nil
+ }}
+ h := &InitializationHandler{
+ kbService: &stubInitializationKBService{kb: kb},
+ kbRepository: repo,
+ modelService: models,
+ }
+
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Params = gin.Params{{Key: "kbId", Value: "kb-1"}}
+ req := httptest.NewRequest(http.MethodPut, "/", strings.NewReader(tc.body))
+ req.Header.Set("Content-Type", "application/json")
+ caller := types.Caller{TenantID: 42, UserID: "u", Role: types.TenantRoleAdmin}
+ ctx := types.WithExecutionTenant(types.WithCaller(req.Context(), caller), 7)
+ c.Request = req.WithContext(ctx)
+ c.Set(middleware.KBAccessContextKey, &access.KBAccess{
+ KnowledgeBase: kb, Caller: caller, EffectiveTenantID: 7, Permission: tc.permission,
+ })
+
+ h.UpdateKBConfig(c)
+
+ if tc.wantStatus == http.StatusOK {
+ require.Empty(t, c.Errors)
+ require.NotNil(t, repo.updated)
+ require.Equal(t, backend, *repo.updated.StorageBackendID)
+ return
+ }
+ require.Len(t, c.Errors, 1)
+ requireForbidden(t, c.Errors[0].Err)
+ require.Nil(t, repo.updated, "KB must not be written")
+ })
+ }
+}
diff --git a/internal/handler/organization.go b/internal/handler/organization.go
index 49b7fd64d..a12d24f2a 100644
--- a/internal/handler/organization.go
+++ b/internal/handler/organization.go
@@ -1171,6 +1171,9 @@ func (h *OrganizationHandler) UpdateSharePermission(c *gin.Context) {
c.Error(apperrors.NewValidationError("Invalid request parameters").WithDetails(err.Error()))
return
}
+ if !h.kbShareOnPath(c, shareID) {
+ return
+ }
if err := h.shareService.UpdateSharePermission(ctx, shareID, req.Permission, userID, tenantID); err != nil {
logger.Errorf(ctx, "Failed to update share permission: %v", err)
@@ -1184,6 +1187,38 @@ func (h *OrganizationHandler) UpdateSharePermission(c *gin.Context) {
})
}
+// kbShareOnPath binds share_id to the route's :id. The route's ownership guard
+// is evaluated against :id, so a share of another KB must not be reachable
+// through an unrelated (or nonexistent) KB path.
+func (h *OrganizationHandler) kbShareOnPath(c *gin.Context, shareID string) bool {
+ share, err := h.shareService.GetShare(c.Request.Context(), shareID)
+ if err != nil && !errors.Is(err, service.ErrShareNotFound) {
+ logger.Errorf(c.Request.Context(), "Failed to load share: %v", err)
+ _ = c.Error(apperrors.NewInternalServerError("Failed to load share"))
+ return false
+ }
+ if share == nil || share.KnowledgeBaseID != c.Param("id") {
+ _ = c.Error(apperrors.NewNotFoundError("Share not found"))
+ return false
+ }
+ return true
+}
+
+// agentShareOnPath is kbShareOnPath for /agents/:id/shares/:share_id.
+func (h *OrganizationHandler) agentShareOnPath(c *gin.Context, shareID string) bool {
+ share, err := h.agentShareService.GetShare(c.Request.Context(), shareID)
+ if err != nil && !errors.Is(err, service.ErrAgentShareNotFound) {
+ logger.Errorf(c.Request.Context(), "Failed to load agent share: %v", err)
+ _ = c.Error(apperrors.NewInternalServerError("Failed to load share"))
+ return false
+ }
+ if share == nil || share.AgentID != c.Param("id") {
+ _ = c.Error(apperrors.NewNotFoundError("Share not found"))
+ return false
+ }
+ return true
+}
+
// RemoveShare removes a share
// @Summary 取消共享
// @Description 取消知识库的共享
@@ -1200,6 +1235,9 @@ func (h *OrganizationHandler) RemoveShare(c *gin.Context) {
shareID := c.Param("share_id")
userID := c.GetString(types.UserIDContextKey.String())
tenantID := c.GetUint64(types.TenantIDContextKey.String())
+ if !h.kbShareOnPath(c, shareID) {
+ return
+ }
if err := h.shareService.RemoveShare(ctx, shareID, userID, tenantID); err != nil {
logger.Errorf(ctx, "Failed to remove share: %v", err)
@@ -1352,6 +1390,14 @@ func (h *OrganizationHandler) ShareAgent(c *gin.Context) {
c.Error(apperrors.NewValidationError("Agent is not fully configured. Please set the chat model, and set the rerank model if the knowledge_search tool is enabled in agent settings."))
return
}
+ if errors.Is(err, service.ErrBuiltinAgentNotShareable) {
+ _ = c.Error(apperrors.NewValidationError("Built-in agents cannot be shared"))
+ return
+ }
+ if errors.Is(err, service.ErrAgentKBScopeNotShareable) {
+ _ = c.Error(apperrors.NewForbiddenError(err.Error()))
+ return
+ }
c.Error(apperrors.NewForbiddenError("Permission denied or invalid operation"))
return
}
@@ -1415,6 +1461,9 @@ func (h *OrganizationHandler) RemoveAgentShare(c *gin.Context) {
shareID := c.Param("share_id")
userID := c.GetString(types.UserIDContextKey.String())
tenantID := c.GetUint64(types.TenantIDContextKey.String())
+ if !h.agentShareOnPath(c, shareID) {
+ return
+ }
if err := h.agentShareService.RemoveShare(ctx, shareID, userID, tenantID); err != nil {
logger.Errorf(ctx, "Failed to remove agent share: %v", err)
c.Error(apperrors.NewForbiddenError("Permission denied"))
diff --git a/internal/handler/organization_share_path_test.go b/internal/handler/organization_share_path_test.go
new file mode 100644
index 000000000..e10aa6d70
--- /dev/null
+++ b/internal/handler/organization_share_path_test.go
@@ -0,0 +1,102 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/application/service"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+type sharePathKBShares struct {
+ interfaces.KBShareService
+ mutated bool
+}
+
+func (*sharePathKBShares) GetShare(_ context.Context, shareID string) (*types.KnowledgeBaseShare, error) {
+ if shareID != "share-1" {
+ return nil, service.ErrShareNotFound
+ }
+ return &types.KnowledgeBaseShare{ID: "share-1", KnowledgeBaseID: "kb-owned-elsewhere"}, nil
+}
+
+func (s *sharePathKBShares) UpdateSharePermission(context.Context, string, types.OrgMemberRole, string, uint64) error {
+ s.mutated = true
+ return nil
+}
+
+func (s *sharePathKBShares) RemoveShare(context.Context, string, string, uint64) error {
+ s.mutated = true
+ return nil
+}
+
+type sharePathAgentShares struct {
+ interfaces.AgentShareService
+ mutated bool
+}
+
+func (*sharePathAgentShares) GetShare(context.Context, string) (*types.AgentShare, error) {
+ return &types.AgentShare{ID: "share-1", AgentID: "agent-owned-elsewhere"}, nil
+}
+
+func (s *sharePathAgentShares) RemoveShare(context.Context, string, string, uint64) error {
+ s.mutated = true
+ return nil
+}
+
+func sharePathContext(pathID, shareID, body string) (*gin.Context, *httptest.ResponseRecorder) {
+ gin.SetMode(gin.TestMode)
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Params = gin.Params{{Key: "id", Value: pathID}, {Key: "share_id", Value: shareID}}
+ c.Request = httptest.NewRequest(http.MethodPut, "/", strings.NewReader(body))
+ c.Request.Header.Set("Content-Type", "application/json")
+ return c, recorder
+}
+
+func requireNotFoundError(t *testing.T, c *gin.Context) {
+ t.Helper()
+ require.Len(t, c.Errors, 1)
+ appErr, ok := c.Errors[0].Err.(*apperrors.AppError)
+ require.True(t, ok)
+ require.Equal(t, http.StatusNotFound, appErr.HTTPCode)
+}
+
+// The share routes' ownership guard evaluates :id, so a share of another KB or
+// agent must not be managed through an unrelated path.
+func TestShareManagementRequiresShareOfPathResource(t *testing.T) {
+ kbShares := &sharePathKBShares{}
+ agentShares := &sharePathAgentShares{}
+ h := &OrganizationHandler{shareService: kbShares, agentShareService: agentShares}
+
+ c, _ := sharePathContext("kb-bogus", "share-1", `{"permission":"editor"}`)
+ h.UpdateSharePermission(c)
+ requireNotFoundError(t, c)
+
+ c, _ = sharePathContext("kb-bogus", "share-1", "")
+ h.RemoveShare(c)
+ requireNotFoundError(t, c)
+
+ c, _ = sharePathContext("kb-owned-elsewhere", "missing-share", "")
+ h.RemoveShare(c)
+ requireNotFoundError(t, c)
+
+ c, _ = sharePathContext("agent-bogus", "share-1", "")
+ h.RemoveAgentShare(c)
+ requireNotFoundError(t, c)
+
+ require.False(t, kbShares.mutated)
+ require.False(t, agentShares.mutated)
+
+ c, _ = sharePathContext("kb-owned-elsewhere", "share-1", `{"permission":"viewer"}`)
+ h.UpdateSharePermission(c)
+ require.Empty(t, c.Errors)
+ require.True(t, kbShares.mutated)
+}
diff --git a/internal/handler/session/chat_history_tenant_test.go b/internal/handler/session/chat_history_tenant_test.go
new file mode 100644
index 000000000..a212f39f3
--- /dev/null
+++ b/internal/handler/session/chat_history_tenant_test.go
@@ -0,0 +1,51 @@
+package session
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/stretchr/testify/require"
+)
+
+type chatHistoryTenantStub struct {
+ interfaces.TenantService
+ tenants map[uint64]*types.Tenant
+}
+
+func (s *chatHistoryTenantStub) GetTenantByID(_ context.Context, id uint64) (*types.Tenant, error) {
+ if tenant, ok := s.tenants[id]; ok {
+ return tenant, nil
+ }
+ return nil, errors.New("tenant not found")
+}
+
+// A shared agent's run carries the agent workspace's tenant info; the chat
+// history must still be indexed with the session owner's configuration.
+func TestSessionTenantInfoContextUsesTheSessionOwner(t *testing.T) {
+ owner := &types.Tenant{ID: 84}
+ session := &types.Tenant{ID: 7}
+ h := &Handler{tenantService: &chatHistoryTenantStub{tenants: map[uint64]*types.Tenant{7: session}}}
+
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
+ ctx = context.WithValue(ctx, types.TenantInfoContextKey, owner)
+ got, ok := h.sessionTenantInfoContext(ctx)
+ require.True(t, ok)
+ info, _ := types.TenantInfoFromContext(got)
+ require.Same(t, session, info)
+
+ // Already the session owner's: unchanged.
+ own := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
+ own = context.WithValue(own, types.TenantInfoContextKey, session)
+ got, ok = h.sessionTenantInfoContext(own)
+ require.True(t, ok)
+ require.Equal(t, own, got)
+
+ // Unknown session tenant: skip indexing rather than use the owner's KB.
+ missing := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(9))
+ missing = context.WithValue(missing, types.TenantInfoContextKey, owner)
+ _, ok = h.sessionTenantInfoContext(missing)
+ require.False(t, ok)
+}
diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go
index 0234d64a5..394fdd298 100644
--- a/internal/handler/session/qa.go
+++ b/internal/handler/session/qa.go
@@ -219,6 +219,14 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
}
}
+ // A per-request model override resolves in the workspace the run executes
+ // in. For a shared agent, or the wiki fixer moved into a shared KB's
+ // workspace, that is the owner's, where it could select any of the owner's
+ // models; it would also be stored as the message's model for follow-ups.
+ if effectiveTenantID != 0 && effectiveTenantID != c.GetUint64(types.TenantIDContextKey.String()) {
+ request.SummaryModelID = ""
+ }
+
if request.LocalBrowserEnabled && (customAgent == nil || !customAgent.IsAgentMode()) {
return nil, nil, errors.NewBadRequestError("Local browser requires an agent with tool calling enabled")
}
@@ -548,7 +556,8 @@ func cloneTagScopes(scopes []types.TagScope) []types.TagScope {
return cloned
}
-// resolveAgent resolves the custom agent by ID, trying shared agent first, then own agent.
+// resolveAgent resolves the custom agent by ID: the caller's own agent unless a
+// source workspace is given, otherwise (or when no own agent matches) a share.
// Returns (nil, 0) if agentID is empty or not found.
func (h *Handler) resolveAgent(
ctx context.Context,
@@ -562,44 +571,41 @@ func (h *Handler) resolveAgent(
logger.Infof(ctx, "Resolving agent, agent ID: %s", secutils.SanitizeForLog(agentID))
- // Try shared agent first
- var customAgent *types.CustomAgent
- var effectiveTenantID uint64
- var sharedAgentReadOnly bool
+ // Without a source workspace the ID names the caller's own agent first.
+ // Built-in IDs exist in every workspace, so trying shares first would let
+ // any org member that shares an agent under such an ID take over the
+ // caller's default agent (and run the caller's chats in its workspace).
+ // A rejected shared selector (sourceTenantID != 0) must likewise never
+ // fall back to a same-ID local agent.
+ var ownErr error
+ if sourceTenantID == 0 {
+ agent, err := h.customAgentService.GetAgentByID(ctx, agentID)
+ if err == nil && agent != nil {
+ logger.Infof(ctx, "Using own agent: ID=%s, Name=%s, AgentMode=%s",
+ agent.ID, agent.Name, agent.Config.AgentMode)
+ return agent, 0, false
+ }
+ ownErr = err
+ }
+
+ var shareErr error
userIDVal, _ := c.Get(types.UserIDContextKey.String())
currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
if h.agentShareService != nil && userIDVal != nil && currentTenantID != 0 {
callerTenantRole := types.TenantRoleFromContext(ctx)
- var agent *types.CustomAgent
- var err error
- agent, err = h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID, sourceTenantID)
+ agent, err := h.agentShareService.GetSharedAgentForTenant(
+ ctx, currentTenantID, callerTenantRole, agentID, sourceTenantID)
if err == nil && agent != nil {
- effectiveTenantID = agent.TenantID
- customAgent = agent
- sharedAgentReadOnly = true
- logger.Infof(ctx, "Using shared agent: ID=%s, Name=%s, effectiveTenantID=%d (retrieval scope)",
- customAgent.ID, customAgent.Name, effectiveTenantID)
+ logger.Infof(ctx, "Using shared agent: ID=%s, Name=%s, IsBuiltin=%v, AgentMode=%s, effectiveTenantID=%d",
+ agent.ID, agent.Name, agent.IsBuiltin, agent.Config.AgentMode, agent.TenantID)
+ return agent, agent.TenantID, true
}
+ shareErr = err
}
- // Fall back to an own agent only when no source workspace was requested.
- // A rejected shared selector must not silently run a same-ID local builtin.
- if customAgent == nil && sourceTenantID == 0 {
- agent, err := h.customAgentService.GetAgentByID(ctx, agentID)
- if err == nil {
- customAgent = agent
- logger.Infof(ctx, "Using own agent: ID=%s, Name=%s, AgentMode=%s",
- customAgent.ID, customAgent.Name, customAgent.Config.AgentMode)
- } else {
- logger.Warnf(ctx, "Failed to get custom agent, agent ID: %s, error: %v, using default config",
- secutils.SanitizeForLog(agentID), err)
- }
- } else if customAgent != nil {
- logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, IsBuiltin=%v, AgentMode=%s, effectiveTenantID=%d",
- customAgent.ID, customAgent.Name, customAgent.IsBuiltin, customAgent.Config.AgentMode, effectiveTenantID)
- }
-
- return customAgent, effectiveTenantID, sharedAgentReadOnly
+ logger.Warnf(ctx, "Failed to get agent, agent ID: %s, source tenant: %d, own error: %v, share error: %v, "+
+ "using default config", secutils.SanitizeForLog(agentID), sourceTenantID, ownErr, shareErr)
+ return nil, 0, false
}
// mergeKnowledgeTargets merges request KB/knowledge IDs with @mentioned items into deduplicated slices.
@@ -1697,6 +1703,27 @@ func (h *Handler) completeQuickAnswerTurn(
h.completeAssistantMessage(ctx, streamCtx.assistantMessage, query, userMessageID)
}
+// sessionTenantInfoContext makes the tenant info match the session owner (the
+// context's tenant here). The chat history KB is read from the tenant info,
+// and a shared agent's run carries the agent workspace's: the receiver's
+// conversation would be indexed into the owner's chat history KB. When the
+// session tenant cannot be loaded the message is not indexed at all.
+func (h *Handler) sessionTenantInfoContext(ctx context.Context) (context.Context, bool) {
+ tenantID, _ := types.TenantIDFromContext(ctx)
+ if info, ok := types.TenantInfoFromContext(ctx); ok && info != nil && info.ID == tenantID {
+ return ctx, true
+ }
+ if tenantID == 0 || h.tenantService == nil {
+ return ctx, false
+ }
+ tenant, err := h.tenantService.GetTenantByID(ctx, tenantID)
+ if err != nil || tenant == nil {
+ logger.Warnf(ctx, "Skipping chat history index: session tenant %d unavailable: %v", tenantID, err)
+ return ctx, false
+ }
+ return context.WithValue(ctx, types.TenantInfoContextKey, tenant), true
+}
+
// completeAssistantMessage marks an assistant message as complete, updates it,
// and asynchronously indexes the Q&A pair into the chat history knowledge base.
func (h *Handler) completeAssistantMessage(
@@ -1709,7 +1736,10 @@ func (h *Handler) completeAssistantMessage(
// Asynchronously index the Q&A pair into the chat history knowledge base for vector search.
// Use WithoutCancel so the goroutine survives after the HTTP request context is done.
bgCtx := context.WithoutCancel(ctx)
- go h.messageService.IndexMessageToKB(bgCtx, userQuery, assistantMessage.Content, assistantMessage.ID, assistantMessage.SessionID)
+ if indexCtx, ok := h.sessionTenantInfoContext(bgCtx); ok {
+ go h.messageService.IndexMessageToKB(
+ indexCtx, userQuery, assistantMessage.Content, assistantMessage.ID, assistantMessage.SessionID)
+ }
if userQuery != "" && h.suggestionService != nil {
go func() {
if _, err := h.suggestionService.EnsureFollowUps(
diff --git a/internal/handler/session/resolve_agent_test.go b/internal/handler/session/resolve_agent_test.go
index d520f6283..0988cda92 100644
--- a/internal/handler/session/resolve_agent_test.go
+++ b/internal/handler/session/resolve_agent_test.go
@@ -2,6 +2,7 @@ package session
import (
"context"
+ "errors"
"net/http"
"net/http/httptest"
"testing"
@@ -159,6 +160,42 @@ func TestResolveAgent_FallsBackToLocalAgentWithoutSourceSelector(t *testing.T) {
require.False(t, sharedReadOnly)
}
+// Built-in IDs exist in every workspace. Without a source selector a share of
+// the same ID must not replace the caller's own agent.
+func TestResolveAgent_PrefersOwnAgentOverSameIDShareWithoutSourceSelector(t *testing.T) {
+ c, ctx := newResolveAgentTestContext(7)
+ localAgent := &types.CustomAgent{ID: "builtin-quick-answer", TenantID: 7, Name: "Local"}
+ h := &Handler{
+ agentShareService: &resolveAgentShareStub{
+ agent: &types.CustomAgent{ID: "builtin-quick-answer", TenantID: 84, Name: "Shared"},
+ },
+ customAgentService: &resolveOwnAgentStub{agent: localAgent},
+ }
+
+ agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, "builtin-quick-answer", 0)
+
+ require.Equal(t, localAgent, agent)
+ require.Equal(t, uint64(0), effectiveTenantID)
+ require.False(t, sharedReadOnly)
+}
+
+// A shared agent without the source selector (e.g. a restored selection) still
+// resolves when the caller has no agent of that ID.
+func TestResolveAgent_UsesShareWhenNoOwnAgentMatches(t *testing.T) {
+ c, ctx := newResolveAgentTestContext(7)
+ sharedAgent := &types.CustomAgent{ID: "3f0c2d9e-shared", TenantID: 84, Name: "Shared"}
+ h := &Handler{
+ agentShareService: &resolveAgentShareStub{agent: sharedAgent},
+ customAgentService: &resolveOwnAgentStub{err: errors.New("agent not found")},
+ }
+
+ agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, sharedAgent.ID, 0)
+
+ require.Equal(t, sharedAgent, agent)
+ require.Equal(t, uint64(84), effectiveTenantID)
+ require.True(t, sharedReadOnly)
+}
+
func TestTerminalProvisionConfigID_UsesSharedAgentSandboxConfig(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
diff --git a/internal/handler/session/wiki_fixer_scope.go b/internal/handler/session/wiki_fixer_scope.go
index 0f4871bc5..872ccc580 100644
--- a/internal/handler/session/wiki_fixer_scope.go
+++ b/internal/handler/session/wiki_fixer_scope.go
@@ -75,6 +75,25 @@ func resolveBuiltinWikiFixerTenantScope(
scopedAgent := *agent
scopedAgent.TenantID = kb.TenantID
+ // The run now executes in the KB owner's workspace, where every ID and
+ // selection mode in the config resolves. The caller's own customizations
+ // (an "all" KB or MCP scope, skills, sandbox, models) would reach the
+ // owner's other resources, so start from the built-in defaults and pin
+ // the config to this one KB. Models fall back to the KB's own.
+ if builtin := types.GetBuiltinAgent(types.BuiltinWikiFixerID, kb.TenantID); builtin != nil {
+ scopedAgent.Config = builtin.Config
+ }
+ scopedAgent.Config.KBSelectionMode = "selected"
+ scopedAgent.Config.KnowledgeBases = []string{kb.ID}
+ scopedAgent.Config.MCPSelectionMode = "none"
+ scopedAgent.Config.MCPServices = nil
+ scopedAgent.Config.SkillsSelectionMode = "none"
+ scopedAgent.Config.SelectedSkills = nil
+ scopedAgent.Config.SandboxConfigID = ""
+ scopedAgent.Config.WebSearchEnabled = false
+ scopedAgent.Config.ModelID = ""
+ scopedAgent.Config.RerankModelID = ""
+ scopedAgent.Config.VLMModelID = ""
logger.Infof(ctx, "wiki fixer: using shared KB source tenant %d for KB %s", kb.TenantID, secutils.SanitizeForLog(kb.ID))
return &scopedAgent, kb.TenantID
}
diff --git a/internal/handler/session/wiki_fixer_scope_test.go b/internal/handler/session/wiki_fixer_scope_test.go
index e906ec212..7e255b033 100644
--- a/internal/handler/session/wiki_fixer_scope_test.go
+++ b/internal/handler/session/wiki_fixer_scope_test.go
@@ -71,6 +71,38 @@ func TestResolveBuiltinWikiFixerTenantScope_SharedEditorUsesSourceTenant(t *test
require.Equal(t, types.TenantRoleContributor, kbShare.checkedTenantRole)
}
+// The scoped run executes in the owner's workspace, so the caller's own fixer
+// customizations must not select the owner's other KBs, MCP services, skills
+// or models there.
+func TestResolveBuiltinWikiFixerTenantScope_PinsConfigToTheSharedKB(t *testing.T) {
+ agent := &types.CustomAgent{ID: types.BuiltinWikiFixerID, TenantID: 10, Config: types.CustomAgentConfig{
+ KBSelectionMode: "all",
+ MCPSelectionMode: "",
+ SkillsSelectionMode: "all",
+ SandboxConfigID: "caller-sandbox",
+ WebSearchEnabled: true,
+ ModelID: "caller-model",
+ }}
+ kbLookup := &wikiFixerKBLookupStub{kb: &types.KnowledgeBase{ID: "kb-shared", TenantID: 20}}
+ kbShare := &wikiFixerKBShareStub{permission: types.OrgRoleEditor, isShared: true}
+
+ gotAgent, _ := resolveBuiltinWikiFixerTenantScope(
+ context.Background(), agent, 10, types.TenantRoleContributor, []string{"kb-shared"}, kbLookup, kbShare,
+ )
+
+ cfg := gotAgent.Config
+ require.Equal(t, "selected", cfg.KBSelectionMode)
+ require.Equal(t, []string{"kb-shared"}, cfg.KnowledgeBases)
+ require.Equal(t, "none", cfg.MCPSelectionMode)
+ require.Equal(t, "none", cfg.SkillsSelectionMode)
+ require.Empty(t, cfg.SandboxConfigID)
+ require.False(t, cfg.WebSearchEnabled)
+ require.Empty(t, cfg.ModelID)
+ require.True(t, types.NewSharedAgentKBScope(gotAgent).Allows("kb-shared", 20))
+ require.False(t, types.NewSharedAgentKBScope(gotAgent).Allows("kb-other", 20))
+ require.Equal(t, "all", agent.Config.KBSelectionMode, "must not mutate the caller's agent")
+}
+
func TestResolveBuiltinWikiFixerTenantScope_SharedViewerDoesNotSwitchTenant(t *testing.T) {
agent := &types.CustomAgent{ID: types.BuiltinWikiFixerID, TenantID: 10}
kbLookup := &wikiFixerKBLookupStub{
diff --git a/internal/router/files.go b/internal/router/files.go
index a00b58c81..b41127eaa 100644
--- a/internal/router/files.go
+++ b/internal/router/files.go
@@ -627,9 +627,18 @@ func presignedFileHandler(tenantService interfaces.TenantService, absDir string,
// into a 4G/mobile browser to verify public reachability without having to
// send a real message through an IM bot.
//
+// The path must belong to the calling tenant, exactly as on /files: signing
+// is a read, and an unconfined signer would turn any known resource handle or
+// tenant path into an anonymous URL.
+//
// Route:
// - GET /api/v1/files/presigned-preview?file_path=<provider://...>
-func servePresignedPreview(r *gin.Engine, cfg *config.Config, storageResolver interfaces.StorageBackendResolver) {
+func servePresignedPreview(
+ r getRouteRegistrar,
+ cfg *config.Config,
+ storageResolver interfaces.StorageBackendResolver,
+ resourceCatalog interfaces.ResourceCatalog,
+) {
absDir := localStorageAbsDir()
// This route is registered on the engine root, NOT the /api/v1 group,
@@ -652,6 +661,19 @@ func servePresignedPreview(r *gin.Engine, cfg *config.Config, storageResolver in
return
}
+ // Sign the original reference so a resource keeps its /r/ grant
+ // form; the resolved physical path is only used for the check.
+ _, resourceResolved, ok := resolveCatalogResource(c, resourceCatalog, filePath, tenant.ID)
+ if !ok {
+ return
+ }
+ if !resourceResolved {
+ if err := secutils.ValidateStoragePathTenant(filePath, tenant.ID); err != nil {
+ c.JSON(http.StatusForbidden, gin.H{"error": "forbidden: file path not accessible"})
+ return
+ }
+ }
+
backendID, provider := parseStorageTarget(filePath)
fileSvc, resolvedProvider, err := resolveFileService(ctx, tenant, backendID, provider, absDir, storageResolver)
if err != nil {
diff --git a/internal/router/router.go b/internal/router/router.go
index 9eb920e31..c9bd8ac0f 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -210,7 +210,7 @@ func NewRouter(params RouterParams) *gin.Engine {
servePresignedFiles(r, params.TenantService, params.StorageBackendResolver)
// Diagnostic preview of presigned URLs (Admin only, behind auth middleware).
- servePresignedPreview(r, params.Config, params.StorageBackendResolver)
+ servePresignedPreview(r, params.Config, params.StorageBackendResolver, params.ResourceCatalog)
// Langfuse observability — only active when LANGFUSE_* env vars are set.
// The middleware is registered unconditionally; when disabled it's a no-op.
diff --git a/internal/router/router_presigned_preview_test.go b/internal/router/router_presigned_preview_test.go
new file mode 100644
index 000000000..7518d754c
--- /dev/null
+++ b/internal/router/router_presigned_preview_test.go
@@ -0,0 +1,64 @@
+package router
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+)
+
+func servePresignedPreviewForTest(t *testing.T, catalog interfaces.ResourceCatalog, filePath string) int {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ t.Setenv("LOCAL_STORAGE_BASE_DIR", t.TempDir())
+ engine := gin.New()
+ servePresignedPreview(engine, nil, nil, catalog)
+
+ req := httptest.NewRequest(http.MethodGet,
+ "/api/v1/files/presigned-preview?file_path="+url.QueryEscape(filePath), nil)
+ ctx := context.WithValue(req.Context(), types.TenantInfoContextKey, &types.Tenant{ID: 42})
+ ctx = types.WithCaller(ctx, types.Caller{TenantID: 42, UserID: "admin", Role: types.TenantRoleAdmin})
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, req.WithContext(ctx))
+ return recorder.Code
+}
+
+// A known handle of another tenant's resource must not be exchangeable for an
+// anonymous /r/ grant (the stub catalog panics if a grant is minted).
+func TestPresignedPreviewRejectsCrossTenantResource(t *testing.T) {
+ catalog := &stubResourceCatalog{resource: &types.StoredResource{
+ TenantID: 7, PhysicalPath: "local://7/exports/a.png",
+ }}
+ code := servePresignedPreviewForTest(t, catalog, "resource://AbCdEfGhIjKlMnOpQrStUv")
+ if code != http.StatusForbidden {
+ t.Fatalf("status = %d, want %d", code, http.StatusForbidden)
+ }
+}
+
+func TestPresignedPreviewRejectsCrossTenantPath(t *testing.T) {
+ for _, filePath := range []string{"local://7/knowledge/secret.pdf", "local://docs/example.txt"} {
+ if code := servePresignedPreviewForTest(t, &stubResourceCatalog{}, filePath); code != http.StatusForbidden {
+ t.Fatalf("%s: status = %d, want %d", filePath, code, http.StatusForbidden)
+ }
+ }
+}
+
+// Without a catalog a resource reference cannot be attributed to a tenant, so
+// it is refused rather than signed.
+func TestPresignedPreviewRejectsUnresolvableResource(t *testing.T) {
+ if code := servePresignedPreviewForTest(t, nil, "resource://AbCdEfGhIjKlMnOpQrStUv"); code != http.StatusForbidden {
+ t.Fatalf("status = %d, want %d", code, http.StatusForbidden)
+ }
+}
+
+func TestPresignedPreviewAllowsOwnTenantPath(t *testing.T) {
+ code := servePresignedPreviewForTest(t, &stubResourceCatalog{}, "local://42/exports/a.png")
+ if code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", code, http.StatusOK)
+ }
+}
diff --git a/internal/types/agent.go b/internal/types/agent.go
index 9558d5fe6..fd33d3d7f 100644
--- a/internal/types/agent.go
+++ b/internal/types/agent.go
@@ -165,6 +165,11 @@ type AgentConfig struct {
// its source workspace. It is set from the verified share relation, never
// inferred from a client-provided tenant ID.
SharedAgentReadOnly bool `json:"-"`
+ // WritableKBIDs are the SearchTargets KBs this caller may modify (its own
+ // workspace's, or shared to it as editor+). Search targets only need read
+ // access, so tools that write (wiki pages and issues) are limited to this
+ // set; empty means read-only. Runtime only, derived per turn.
+ WritableKBIDs []string `json:"-"`
// LLM call timeout in seconds (default: 120). Controls the maximum time for a single LLM call.
LLMCallTimeout int `json:"llm_call_timeout,omitempty"`
diff --git a/internal/types/interfaces/organization.go b/internal/types/interfaces/organization.go
index 20eaacd3b..8fa5cbc10 100644
--- a/internal/types/interfaces/organization.go
+++ b/internal/types/interfaces/organization.go
@@ -149,6 +149,9 @@ type KBShareRepository interface {
DeleteByKnowledgeBaseID(ctx context.Context, kbID string) error
// DeleteByOrganizationID soft-deletes all shares for an organization (e.g. when the org is deleted)
DeleteByOrganizationID(ctx context.Context, orgID string) error
+ // DeleteByOrganizationAndSourceTenant soft-deletes the shares a tenant made
+ // into an organization (e.g. when the tenant leaves or is removed)
+ DeleteByOrganizationAndSourceTenant(ctx context.Context, orgID string, sourceTenantID uint64) error
// List
ListByKnowledgeBase(ctx context.Context, kbID string) ([]*types.KnowledgeBaseShare, error)
@@ -201,6 +204,7 @@ type AgentShareRepository interface {
Delete(ctx context.Context, id string) error
DeleteByAgentIDAndSourceTenant(ctx context.Context, agentID string, sourceTenantID uint64) error
DeleteByOrganizationID(ctx context.Context, orgID string) error
+ DeleteByOrganizationAndSourceTenant(ctx context.Context, orgID string, sourceTenantID uint64) error
ListByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error)
ListByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error)
ListByOrganizations(ctx context.Context, orgIDs []string) ([]*types.AgentShare, error)
diff --git a/internal/types/knowledgebase.go b/internal/types/knowledgebase.go
index e0681756c..14a1618b9 100644
--- a/internal/types/knowledgebase.go
+++ b/internal/types/knowledgebase.go
@@ -815,14 +815,25 @@ func (kb *KnowledgeBase) Capabilities() KBCapabilities {
// MarshalJSON augments the default JSON encoding of KnowledgeBase with a computed
// `capabilities` field so clients (agent editor) can filter KBs by feature.
-// It preserves all existing fields verbatim.
+//
+// The legacy inline credentials (storage_config secret_id / secret_key and
+// vlm_config api_key) are withheld. Their DB columns are written by
+// StorageConfig.Value / VLMConfig.Value, so persistence is unaffected, while
+// every JSON rendering of a KB is an API or tool response — including the
+// lists shown to org-share receivers, who must never see the owner's keys.
+// Clients only need these fields' presence, which /initialization/config
+// reports separately.
func (kb *KnowledgeBase) MarshalJSON() ([]byte, error) {
type alias KnowledgeBase
+ redacted := *kb
+ redacted.StorageConfig.SecretID = ""
+ redacted.StorageConfig.SecretKey = ""
+ redacted.VLMConfig.APIKey = ""
aux := struct {
*alias
Capabilities KBCapabilities `json:"capabilities"`
}{
- alias: (*alias)(kb),
+ alias: (*alias)(&redacted),
Capabilities: kb.Capabilities(),
}
return json.Marshal(aux)
diff --git a/internal/types/knowledgebase_test.go b/internal/types/knowledgebase_test.go
index 62febaed4..943fa9752 100644
--- a/internal/types/knowledgebase_test.go
+++ b/internal/types/knowledgebase_test.go
@@ -376,3 +376,40 @@ func TestChunkingConfigResolveParserEngineDefaults(t *testing.T) {
t.Fatalf("configured ResolveParserEngine(pptx) = %q, want mineru", got)
}
}
+
+// KB JSON is what API responses (including org-share listings) carry, so the
+// legacy inline credentials must not appear there; their DB columns still do.
+func TestKnowledgeBase_MarshalJSONWithholdsInlineCredentials(t *testing.T) {
+ kb := &KnowledgeBase{
+ ID: "kb-1",
+ StorageConfig: StorageConfig{
+ Provider: "minio", BucketName: "bucket", SecretID: "root-id", SecretKey: "root-secret",
+ },
+ VLMConfig: VLMConfig{ModelName: "vlm", BaseURL: "https://vlm.example", APIKey: "vlm-key"},
+ }
+
+ data, err := json.Marshal(kb)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ for _, secret := range []string{"root-id", "root-secret", "vlm-key"} {
+ if strings.Contains(string(data), secret) {
+ t.Fatalf("KB JSON leaks %q: %s", secret, data)
+ }
+ }
+ if !strings.Contains(string(data), `"bucket_name":"bucket"`) || !strings.Contains(string(data), `"capabilities"`) {
+ t.Fatalf("KB JSON lost non-secret fields: %s", data)
+ }
+ if kb.StorageConfig.SecretKey != "root-secret" || kb.VLMConfig.APIKey != "vlm-key" {
+ t.Fatal("MarshalJSON mutated the knowledge base")
+ }
+
+ storageColumn, err := kb.StorageConfig.Value()
+ if err != nil || !strings.Contains(string(storageColumn.([]byte)), "root-secret") {
+ t.Fatalf("storage column lost its secret: %v %s", err, storageColumn)
+ }
+ vlmColumn, err := kb.VLMConfig.Value()
+ if err != nil || !strings.Contains(string(vlmColumn.([]byte)), "vlm-key") {
+ t.Fatalf("VLM column lost its key: %v %s", err, vlmColumn)
+ }
+}
diff --git a/website-docs/03-features/01-tenant-auth.md b/website-docs/03-features/01-tenant-auth.md
index 7b9362f1f..7c47d6d7a 100644
--- a/website-docs/03-features/01-tenant-auth.md
+++ b/website-docs/03-features/01-tenant-auth.md
@@ -208,11 +208,15 @@ type KnowledgeBaseShare struct {
**共享的前置条件**(`ShareKnowledgeBase`):调用者租户必须**拥有**该 KB(`kb.TenantID == tenantID`),且在目标组织中角色为 **editor+**。重复共享转为更新权限。
-**管理共享的三条豁免路径**(`callerCanManageShare`,用于改权限 / 撤销共享):
+**谁能管理共享**(`canManageShare`,KB 共享与 Agent 共享共用,用于改权限 / 撤销共享):
-1. 调用者就是原共享人(同 user id);
-2. 调用者租户是来源租户且调用者是租户 Admin+(所有权是租户级的,原共享人离开后租户 Admin 仍可管理);
-3. 调用者租户是目标组织的 admin(org admin 可在原共享人离开后修复共享)。
+1. 原共享人,且仍在来源租户内操作、租户角色为 Contributor+;
+2. 来源租户的 Admin+(所有权是租户级的,原共享人离开后租户 Admin 仍可管理);
+3. 目标组织中角色为 admin 的租户,其 Admin+ 用户可以撤销共享或**降低**权限,但不能把权限提升到超过当前值,否则等于把别人的 KB 写权限交给全体 editor 成员。
+
+路由上的 `share_id` 必须属于路径中的 KB / Agent,否则返回 404。
+
+**共享何时失效**:共享只在组织未删除、且来源租户仍是组织成员时生效。来源租户退出或被移除时,它共享进该组织的 KB 与 Agent 会被一并撤销;查询侧也会按来源租户的成员关系过滤,旧版本遗留的共享同样不再生效。
**有效权限 = 多层交集(取最小)**:
@@ -230,6 +234,13 @@ func applyTenantRoleCap(p types.OrgMemberRole, callerTenantRole types.TenantRole
共享相关操作会写入 KB 活动流:`kb.share_added` / `kb.share_permission_changed` / `kb.share_removed`。
+**Agent 共享的额外规则**(`internal/application/service/agent_share.go`、`agent_share_scope.go`):
+
+- 内置智能体不能共享:每个空间都有同 ID 的内置智能体,共享后接收方无法区分。未指定来源空间的对话请求总是先使用自己空间的智能体。
+- 共享 Agent 会把它的 KB 范围以只读方式开放给组织成员,因此共享人必须有权直接共享这些 KB,即 KB 创建者或租户 Admin+。`kb_selection_mode: all` 会自动包含之后新建的 KB,只有 Admin+ 可以共享。已共享的 Agent 被编辑时,新加入范围的 KB 适用同一规则。
+- 共享运行时,Agent 未设置 MCP 选择模式按「不使用」处理,与共享范围里的展示一致。
+- 启用了技能的 Agent 共享后,技能在来源空间的沙箱中运行,并带上管理员为技能配置的环境变量(如 API Key);成员可以让智能体读出这些值。共享设置页会对此给出提示。
+
```mermaid
flowchart LR
subgraph srcT["来源租户 (SourceTenant)"]
diff --git a/website-docs/03-features/02-knowledge-base.md b/website-docs/03-features/02-knowledge-base.md
index 06f3d0e38..bdbf8f34e 100644
--- a/website-docs/03-features/02-knowledge-base.md
+++ b/website-docs/03-features/02-knowledge-base.md
@@ -386,6 +386,8 @@ type KnowledgeTagRelation struct { KnowledgeID, TagID string } // 多对多
测试用例明确验证:即使文件内容是 `<script>alert(1)</script>`,也只会作为二进制附件传输。下载端点(`/knowledge/:id/download`)要求更高的 Contributor+ 且走 KBAccessWrite 门禁。
+预览返回的是原始文件本身,通过只读共享(组织共享的 viewer、经共享智能体可见)访问时同样可以预览。「只有 Editor 及以上才能下载」是产品上的便利性限制,不是访问控制边界:能读到一个 KB 的人,就能拿到其中的原文件。
+
### 知识库复制与知识移动 {#_4-知识库复制与知识移动}
#### 复制(Copy / Duplicate)与 Preflight {#_4-1-复制-copy-duplicate-与-preflight}
diff --git a/website-docs/03-features/07-agent.md b/website-docs/03-features/07-agent.md
index 25ee6bf6d..9c4a4d301 100644
--- a/website-docs/03-features/07-agent.md
+++ b/website-docs/03-features/07-agent.md
@@ -36,7 +36,13 @@
智能体可以使用全部、指定或禁用的知识库及技能范围。对话中的提及用于选择本轮资料或提示优先技能,不能绕过已有授权。联网搜索同时受智能体配置和本轮请求开关约束。
-通过组织共享智能体后,接收方在授权范围内使用来源空间的模型与资料。共享智能体为只读,接收方不能修改其配置。
+通过组织共享智能体后,接收方在授权范围内使用来源空间的模型与资料。共享智能体为只读,接收方不能修改其配置。接收方使用时:
+
+- 始终使用智能体配置的模型,请求里的 `summary_model_id` 会被忽略;
+- 未设置 MCP 选择模式的智能体不使用 MCP 服务;
+- 对话记录写入接收方自己空间的对话记录知识库,不会写入来源空间。
+
+启用了技能的智能体共享后,技能在来源空间的沙箱中运行,并带上管理员为技能配置的环境变量,成员可以让智能体读出这些值。共享规则见[空间与权限](01-tenant-auth.md)。
## 处理工具审批与授权
diff --git a/website-docs/03-features/08-mcp.md b/website-docs/03-features/08-mcp.md
index 0177d62fd..db5fff2f9 100644
--- a/website-docs/03-features/08-mcp.md
+++ b/website-docs/03-features/08-mcp.md
@@ -381,6 +381,8 @@ flowchart LR
| GET / PUT / DELETE | `/mcp-endpoints/:endpoint_id` | 详情 / 更新 / 删除 |
| POST | `/mcp-endpoints/:endpoint_id/rotate-token` | 轮换令牌,响应含新 `token` |
+端点令牌是一个新的凭证,因此受限 API Key 只能创建、修改或轮换不超出自身权限的端点:端点的知识库必须在 Key 的知识库白名单之内(Key 有白名单时,端点不能留空,留空表示空间内全部),端点工具所需的能力(retrieve / chat / ingest 等)也必须是 Key 已有的,否则返回 403。
+
#### 请求链路
```mermaid
diff --git a/website-docs/03-features/14-wiki.md b/website-docs/03-features/14-wiki.md
index 9b337f193..18deff619 100644
--- a/website-docs/03-features/14-wiki.md
+++ b/website-docs/03-features/14-wiki.md
@@ -186,7 +186,8 @@ migration `000061_wiki_page_hierarchy.up.sql` 引入独立的 `wiki_folders` 表
配套机制:
- **Wiki Scope**:Agent 会话内维护 wiki KB 白名单,支持通过 `@mention` 把范围收窄到特定文档/标签,工具执行时自动过滤 `source_refs`(`internal/agent/tools/wiki_tools.go`);
-- **Wiki Fixer**:内置 Agent(`types.BuiltinWikiFixerID`),负责自动修复 wiki 问题(死链、实体混淆等)。跨租户访问共享 KB 时要求租户角色 ≥ Editor,并自动提升到源租户上下文(`internal/handler/session/wiki_fixer_scope.go`);
+- **写权限**:检索范围只需要读权限,而改写类工具(`wiki_write_page`、`wiki_replace_text`、`wiki_rename_page`、`wiki_delete_page`、`wiki_flag_issue`、`wiki_update_issue`)只作用于调用方可编辑的知识库,即本空间的知识库,或通过组织分享获得 editor 及以上权限的知识库。调用方本身还要有写权限:空间角色 Contributor 及以上,受限 API key 需要 `ingest` 能力。以 Viewer 身份运行的 IM、网页嵌入和 MCP 端点因此只读。范围内没有可编辑的 wiki 知识库时,这些工具不会注册。共享智能体始终只读;
+- **Wiki Fixer**:内置 Agent(`types.BuiltinWikiFixerID`),负责自动修复 wiki 问题(死链、实体混淆等)。跨租户访问共享 KB 时要求租户角色 ≥ Editor,并自动提升到源租户上下文(`internal/handler/session/wiki_fixer_scope.go`)。提升后使用内置默认配置,只针对这一个 KB,不启用 MCP、技能、沙箱和联网搜索,模型回退到该 KB 自己的模型,调用方对 fixer 的自定义配置不会带进源空间;
- **问题闭环**:`wiki_page_issues` 表 + lint 接口 + `auto-fix`,人和 Agent 都可以报告/处理问题。
### 生成流程
diff --git a/website-docs/04-api/02-api-agent-mcp.md b/website-docs/04-api/02-api-agent-mcp.md
index 655f623f9..e4d8543c0 100644
--- a/website-docs/04-api/02-api-agent-mcp.md
+++ b/website-docs/04-api/02-api-agent-mcp.md
@@ -68,7 +68,7 @@ curl $BASE/api/v1/agents/agent-1 -H "Authorization: Bearer $TOKEN"
### PUT /api/v1/agents/:id
-用途:更新 Agent。权限:创建者 OR Admin+。请求体:`name/description/avatar/config`(均可选)。
+用途:更新 Agent。权限:创建者 OR Admin+。请求体:`name/description/avatar/config`(均可选)。Agent 已分享到组织时,新加入知识库范围的知识库须是调用者可分享的(知识库创建者或 Admin+,改为 `all` 需要 Admin+),否则 403。
响应:200 `{"success":true,"data":{Agent}}`
diff --git a/website-docs/04-api/02-api-channels.md b/website-docs/04-api/02-api-channels.md
index 919663290..7ed5ce753 100644
--- a/website-docs/04-api/02-api-channels.md
+++ b/website-docs/04-api/02-api-channels.md
@@ -428,6 +428,8 @@ curl "$BASE/api/v1/files/presigned?file_path=local://1/x.png&tenant_id=1&expires
用途:诊断端点:返回给定路径将生成的预签名 HTTP URL。权限:Admin+,显式拒绝 API key(`DenyAPIKeyPrincipal`)。查询参数:`file_path`(必填)。
+`file_path` 必须属于当前空间,与 `/files` 相同:`resource://` 句柄要求资源归属本空间,存储路径要求租户段为本空间 ID;否则 403,不会签发任何 URL。
+
响应:200 `{"file_path","provider","url","rewritten":bool,"hint"}`
```bash
diff --git a/website-docs/04-api/02-api-chat.md b/website-docs/04-api/02-api-chat.md
index 4adf8c8f2..b6202d2c3 100644
--- a/website-docs/04-api/02-api-chat.md
+++ b/website-docs/04-api/02-api-chat.md
@@ -259,8 +259,8 @@ Handler: `internal/handler/session/qa.go`。API key:聊天需 `chat`/full;`k
| `knowledge_ids` | []string | 否 | 限定知识文件 |
| `agent_enabled` | bool | 否 | 是否启用 Agent 模式 |
| `agent_id` | string | 否 | 自定义 Agent ID |
-| `web_search_enabled` | bool | 否 | 联网搜索 |
-| `summary_model_id` | string | 否 | 总结模型 |
+| `web_search_enabled` | bool | 否 | 联网搜索;只在智能体本身开启联网搜索时生效 |
+| `summary_model_id` | string | 否 | 总结模型;使用共享智能体时忽略,始终使用智能体配置的模型 |
| `mcp_service_ids` | []string | 否 | @提及的 MCP 服务 |
| `skill_names` | []string | 否 | @提及的技能 |
| `tag_ids` | []string | 否 | 标签过滤 |
diff --git a/website-docs/04-api/02-api-model-system.md b/website-docs/04-api/02-api-model-system.md
index 831a6d980..f0e5eda41 100644
--- a/website-docs/04-api/02-api-model-system.md
+++ b/website-docs/04-api/02-api-model-system.md
@@ -172,6 +172,8 @@ Handler: `internal/handler/initialization.go`。KB 配置类:API key `manage_k
用途:读取 KB 当前模型/解析配置。权限:Viewer+,KB read。
+模型 `baseUrl` 仅对 KB 所属空间的 Admin+(或 full-access / `manage_tenant_settings` API key)返回。通过组织分享访问的空间只能看到凭证是否已配置(`credentials.*`),看不到来源空间的模型地址和存储桶信息。
+
响应:200 `{"success":true,"data":{"hasFiles",llm,embedding,rerank,multimodal,documentSplitting,nodeExtract,questionGeneration}}`
```bash
@@ -182,6 +184,8 @@ curl $BASE/api/v1/initialization/config/kb-1 -H "Authorization: Bearer $TOKEN"
用途:初始化 KB 的模型与解析配置(首次配置向导)。权限:KB 创建者 OR Admin+,KB write。
+只有 KB 所属空间可以调用;通过组织分享获得编辑权限的空间会被拒绝(403)。KB 已绑定模型时,该接口会原地更新这些模型的配置,这一步需要与 `PUT /models/:id` 相同的权限(Admin+,或拥有 `manage_models` 能力的 API key),否则 403。
+
主要字段(`InitializationRequest`):
| 字段 | 类型 | 必填 | 说明 |
@@ -209,6 +213,8 @@ curl -X POST $BASE/api/v1/initialization/initialize/kb-1 -H "Authorization: Bear
用途:更新 KB 模型/分块配置(`KBModelConfigRequest`:`llmModelId` 必填,`embeddingModelId`、`vlm_config`、`asr_config`、`documentSplitting.*`、`multimodal.enabled`、`storageProvider`、`storageBackendId`、`nodeExtract.*`、`questionGeneration.*` 可选)。权限:KB 创建者 OR Admin+,KB write。
+通过组织分享访问时,需要有效分享权限为 admin;editor 只能编辑内容,不能改设置(403)。存储绑定(`storageBackendId` / `storageProvider`)只有 KB 所属空间可以修改,其他空间提交与当前不同的值会返回 403。
+
响应:200 `{"success":true,"message":"配置更新成功"}`
```bash
diff --git a/website-docs/04-api/02-api-org.md b/website-docs/04-api/02-api-org.md
index ed4cbe537..7228f1c46 100644
--- a/website-docs/04-api/02-api-org.md
+++ b/website-docs/04-api/02-api-org.md
@@ -140,7 +140,7 @@ curl -X DELETE $BASE/api/v1/organizations/org-1 -H "Authorization: Bearer $TOKEN
### POST /api/v1/organizations/:id/leave
-用途:本空间退出组织。权限:Admin+。无请求体。
+用途:本空间退出组织。权限:Admin+。无请求体。本空间分享进该组织的知识库和 Agent 会被一并撤销。
响应:200 `{"success":true,"message":"Left organization successfully"}`
@@ -238,7 +238,7 @@ curl -X PUT $BASE/api/v1/organizations/org-1/members/2 -H "Authorization: Bearer
### DELETE /api/v1/organizations/:id/members/:tenant_id
-用途:移除成员空间(含自移除)。权限:Admin+。
+用途:移除成员空间(含自移除)。权限:Admin+。被移除空间分享进该组织的知识库和 Agent 会被一并撤销。
响应:200 `{"success":true,"message":"Member removed successfully"}`
@@ -347,6 +347,14 @@ curl $BASE/api/v1/knowledge-bases/kb-1/shares -H "Authorization: Bearer $TOKEN"
用途:修改分享权限。权限:KB 创建者 OR Admin+。请求体:`{"permission":"editor"}`(必填)。
+服务层规则(与取消分享共用):
+
+- 原分享人需在 KB 所属空间内操作,且空间角色为 Contributor+;
+- KB 所属空间的 Admin+ 可以管理本空间的全部分享;
+- 目标组织中角色为 admin 的空间,其 Admin+ 用户只能**降低**权限或取消分享,不能把权限提升到超过当前值。
+
+`share_id` 必须属于路径中的 KB,否则 404。
+
响应:200 `{"success":true,"message":"Share permission updated successfully"}`
```bash
@@ -356,7 +364,7 @@ curl -X PUT $BASE/api/v1/knowledge-bases/kb-1/shares/s-1 -H "Authorization: Bear
### DELETE /api/v1/knowledge-bases/:id/shares/:share_id
-用途:取消分享。权限:KB 创建者 OR Admin+。
+用途:取消分享。权限:KB 创建者 OR Admin+,服务层规则同上。`share_id` 必须属于路径中的 KB,否则 404。
响应:200 `{"success":true,"message":"Share removed successfully"}`
@@ -370,7 +378,7 @@ API key:仅 full-access。Handler: `internal/handler/organization.go`
### POST /api/v1/agents/:id/shares
-用途:把 Agent 分享到组织。权限:Agent 创建者 OR Admin+。请求体同 KB 分享(`organization_id` + `permission`,必填)。
+用途:把 Agent 分享到组织。权限:Agent 创建者 OR Admin+。请求体同 KB 分享(`organization_id` + `permission`,必填)。内置智能体不能分享(400):每个空间都有同 ID 的内置智能体,分享后接收方无法区分。Agent 的知识库范围会开放给组织成员,因此调用者必须有权直接分享其中每个知识库(知识库创建者或 Admin+),`kb_selection_mode: all` 只有 Admin+ 可以分享,否则 403。
响应:201 `{"success":true,"data":{AgentShare}}`
@@ -391,7 +399,7 @@ curl $BASE/api/v1/agents/agent-1/shares -H "Authorization: Bearer $TOKEN"
### DELETE /api/v1/agents/:id/shares/:share_id
-用途:取消 Agent 分享。权限:Agent 创建者 OR Admin+。
+用途:取消 Agent 分享。权限:Agent 创建者 OR Admin+,服务层规则同 KB 取消分享。`share_id` 必须属于路径中的 Agent,否则 404。
响应:200 `{"success":true,"message":"Share removed successfully"}`