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): harden agent share listing and align full-access API key routes

wizardchen50b8c0a72e69
diff --git a/internal/application/service/agent_share.go b/internal/application/service/agent_share.go
index 27b94ae1b..f462f2ace 100644
--- a/internal/application/service/agent_share.go
+++ b/internal/application/service/agent_share.go
@@ -188,8 +188,23 @@ func (s *agentShareService) RemoveShare(ctx context.Context, shareID string, use
return ErrAgentSharePermission
}
-// ListSharesByAgent lists all shares for an agent
-func (s *agentShareService) ListSharesByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error) {
+// ListSharesByAgent lists all shares for an agent owned by tenantID.
+//
+// Ownership is enforced here (not only at the route layer): the caller must
+// own the agent, mirroring ListSharesByKnowledgeBase. This is the sole guard
+// for API-key principals, whose route-level OwnedAgentOrAdmin check
+// short-circuits — without this, a full-access key could enumerate any
+// tenant's agent shares by ID (cross-tenant IDOR).
+func (s *agentShareService) ListSharesByAgent(
+ ctx context.Context, agentID string, tenantID uint64,
+) ([]*types.AgentShare, error) {
+ agent, err := s.agentRepo.GetAgentByID(ctx, agentID, tenantID)
+ if err != nil || agent == nil {
+ return nil, ErrAgentNotFoundForShare
+ }
+ if agent.TenantID != tenantID {
+ return nil, ErrNotAgentOwner
+ }
return s.shareRepo.ListByAgent(ctx, agentID)
}
diff --git a/internal/handler/organization.go b/internal/handler/organization.go
index c83dcf80e..45af99a44 100644
--- a/internal/handler/organization.go
+++ b/internal/handler/organization.go
@@ -1356,8 +1356,21 @@ func (h *OrganizationHandler) ShareAgent(c *gin.Context) {
func (h *OrganizationHandler) ListAgentShares(c *gin.Context) {
ctx := c.Request.Context()
agentID := c.Param("id")
- shares, err := h.agentShareService.ListSharesByAgent(ctx, agentID)
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+ if tenantID == 0 {
+ c.Error(apperrors.NewUnauthorizedError("Unauthorized"))
+ return
+ }
+ shares, err := h.agentShareService.ListSharesByAgent(ctx, agentID, tenantID)
if err != nil {
+ if errors.Is(err, service.ErrAgentNotFoundForShare) {
+ c.Error(apperrors.NewNotFoundError("Agent not found"))
+ return
+ }
+ if errors.Is(err, service.ErrNotAgentOwner) {
+ c.Error(apperrors.NewForbiddenError("Only the agent owner can list its shares"))
+ return
+ }
logger.Errorf(ctx, "Failed to list agent shares: %v", err)
c.Error(apperrors.NewInternalServerError("Failed to list shares"))
return
diff --git a/internal/middleware/kb_access_test.go b/internal/middleware/kb_access_test.go
index 6e5d2ec94..5c709397f 100644
--- a/internal/middleware/kb_access_test.go
+++ b/internal/middleware/kb_access_test.go
@@ -123,7 +123,7 @@ func (s *stubAgentShareForGuard) ShareAgent(context.Context, string, string, str
func (s *stubAgentShareForGuard) RemoveShare(context.Context, string, string, uint64) error {
panic("not implemented")
}
-func (s *stubAgentShareForGuard) ListSharesByAgent(context.Context, string) ([]*types.AgentShare, error) {
+func (s *stubAgentShareForGuard) ListSharesByAgent(context.Context, string, uint64) ([]*types.AgentShare, error) {
panic("not implemented")
}
func (s *stubAgentShareForGuard) ListSharesByOrganization(context.Context, string) ([]*types.AgentShare, error) {
diff --git a/internal/router/router.go b/internal/router/router.go
index 217ad2f29..9d0dacbb6 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -406,13 +406,16 @@ func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeB
// 知识库路由组。Scoped API key 需要 retrieve 能力读取(限 KB 范围);KB 内容写入
// 由 RegisterKnowledgeRoutes/FAQ/Tag/Wiki 等子路由的 ingest 能力控制;
// KB 自身的元数据/生命周期管理需要 full access 或 manage_kbs。创建/拷贝
- // KB 没有单个目标 KB 可约束,继续不对 scoped API key 开放。
+ // KB 没有单个目标 KB 可约束,因此不对 scoped key 开放(capability 无法
+ // 把它约束到某个 KB 上);但 full-access key 是租户级全权,与它已能
+ // 更新/删除/管理 KB 对齐,允许其创建 KB,消除"能删不能建"的不一致。
kbgrp := r.Group("/knowledge-bases")
kb := g.apiKeyGroup(kbgrp, apiKeyRetrieve(apiKeyFullAccess()))
kbManagement := kb.With(apiKeyManageKnowledgeBases(apiKeyFullAccess()))
{
- // 创建知识库 — Contributor+ for JWT callers; API keys may not create KBs.
- kbgrp.POST("", g.Contributor(), handler.CreateKnowledgeBase)
+ // 创建知识库 — Contributor+ for JWT callers; full-access API keys may
+ // create KBs (scoped keys stay default-deny: no KB to bound against).
+ kb.With(apiKeyFullAccess()).POST("", g.Contributor(), handler.CreateKnowledgeBase)
// 获取知识库列表 — Viewer+ for JWT callers; retrieve-capable API keys pass via the gate.
kb.GET("", g.Viewer(), handler.ListKnowledgeBases)
// 获取知识库详情 — Viewer+ 且对 KB 有 read 权限
@@ -1189,8 +1192,9 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
// 分享 KB 到组织 = 让组织里所有人能读这个 KB;这跟"修改 KB 元信息"
// 同等敏感,所以挂同款 OwnedKBOrAdmin 矩阵。Viewer 在自己租户里
// 也不能私自把 KB 暴露出去。
- // KB share management is JWT-only; not declared for API keys.
- kbShares := r.Group("/knowledge-bases/:id/shares")
+ // 分享管理不通过 capability 授予(manage_spaces 也不含);仅 full-access
+ // key(租户级全权)可管理分享,scoped key 保持 default-deny。
+ kbShares := g.apiKeyGroup(r.Group("/knowledge-bases/:id/shares"), apiKeyFullAccess())
{
// Share knowledge base
kbShares.POST("", g.OwnedKBOrAdmin(), orgHandler.ShareKnowledgeBase)
@@ -1205,12 +1209,13 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
// Agent sharing routes — same rationale as KB shares: 分享/取消分享
// 跟修改 agent 同等敏感,挂 OwnedAgentOrAdmin。
//
- // GET 同样走 OwnedAgentOrAdmin:service.ListSharesByAgent 没有 owner
- // 校验(与 ListSharesByKnowledgeBase 不对称),如果路由层只挂 Viewer
- // 任何同租户成员都能枚举他人 agent 的分享去向——这里把 owner 校验
- // 兜底到路由层,匹配 POST/DELETE 的矩阵。
- // Agent share management is JWT-only; not declared for API keys.
- agentShares := r.Group("/agents/:id/shares")
+ // GET 走 OwnedAgentOrAdmin 作为 JWT 侧的 owner 校验;service 层
+ // ListSharesByAgent 现在也强制 tenant 归属(与 ListSharesByKnowledgeBase
+ // 对齐),这样 full-access API key(会短路路由 guard)也无法跨租户
+ // 枚举他人 agent 的分享。
+ // 同 KB 分享:分享管理不通过 capability 授予;仅 full-access key
+ // (租户级全权)可管理 agent 分享,scoped key 保持 default-deny。
+ agentShares := g.apiKeyGroup(r.Group("/agents/:id/shares"), apiKeyFullAccess())
{
agentShares.POST("", g.OwnedAgentOrAdmin(), orgHandler.ShareAgent)
agentShares.GET("", g.OwnedAgentOrAdmin(), orgHandler.ListAgentShares)
diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.go
index 46b0c989b..b6f73cfd7 100644
--- a/internal/router/router_api_key_capabilities_test.go
+++ b/internal/router/router_api_key_capabilities_test.go
@@ -179,7 +179,26 @@ func TestKnowledgeBaseManagementRoutesDeclareManageKBsCapability(t *testing.T) {
}
}
-func TestKnowledgeBaseCreateAndCopyRoutesRemainDefaultDenyForAPIKeys(t *testing.T) {
+func TestKnowledgeBaseCreateRouteRequiresFullAccessForAPIKeys(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ g := &rbacGuards{}
+ v1 := gin.New().Group("/api/v1")
+
+ RegisterKnowledgeBaseRoutes(v1, &handler.KnowledgeBaseHandler{}, g)
+
+ // Creating a KB is open to full-access keys (tenant-wide authority),
+ // matching KB update/delete, but carries no capability so scoped keys
+ // stay denied.
+ policy := mustLookupAPIKeyPolicy(t, g, http.MethodPost, "/api/v1/knowledge-bases")
+ if !policy.RequireFullAccess {
+ t.Fatal("KB create should require full access for API keys")
+ }
+ if len(policy.Capabilities) != 0 {
+ t.Fatalf("KB create must not be granted by any capability: %#v", policy.Capabilities)
+ }
+}
+
+func TestKnowledgeBaseCopyRoutesRemainDefaultDenyForAPIKeys(t *testing.T) {
gin.SetMode(gin.TestMode)
g := &rbacGuards{}
v1 := gin.New().Group("/api/v1")
@@ -190,7 +209,6 @@ func TestKnowledgeBaseCreateAndCopyRoutesRemainDefaultDenyForAPIKeys(t *testing.
method string
path string
}{
- {http.MethodPost, "/api/v1/knowledge-bases"},
{http.MethodPost, "/api/v1/knowledge-bases/copy"},
{http.MethodPost, "/api/v1/knowledge-bases/:id/duplicate"},
}
@@ -368,17 +386,30 @@ func TestOrganizationRoutesDeclareManageSpacesCapability(t *testing.T) {
})
}
- defaultDeny := []struct {
+ // KB/agent share management is open to full-access keys (tenant-wide
+ // authority) but never via a capability.
+ shareRoutes := []struct {
method string
path string
}{
{http.MethodPost, "/api/v1/knowledge-bases/:id/shares"},
+ {http.MethodGet, "/api/v1/knowledge-bases/:id/shares"},
+ {http.MethodPut, "/api/v1/knowledge-bases/:id/shares/:share_id"},
+ {http.MethodDelete, "/api/v1/knowledge-bases/:id/shares/:share_id"},
{http.MethodPost, "/api/v1/agents/:id/shares"},
+ {http.MethodGet, "/api/v1/agents/:id/shares"},
+ {http.MethodDelete, "/api/v1/agents/:id/shares/:share_id"},
}
- for _, tc := range defaultDeny {
- if _, ok := g.apiKeyAuthorizer.Lookup(tc.method, tc.path); ok {
- t.Fatalf("resource share route should remain default-deny for API keys: %s %s", tc.method, tc.path)
- }
+ for _, tc := range shareRoutes {
+ t.Run("share "+tc.method+" "+tc.path, func(t *testing.T) {
+ policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path)
+ if !policy.RequireFullAccess {
+ t.Fatal("share route should require full access for API keys")
+ }
+ if len(policy.Capabilities) != 0 {
+ t.Fatalf("share route must not be granted by any capability: %#v", policy.Capabilities)
+ }
+ })
}
}
diff --git a/internal/types/interfaces/organization.go b/internal/types/interfaces/organization.go
index dd07a15bd..9f1927332 100644
--- a/internal/types/interfaces/organization.go
+++ b/internal/types/interfaces/organization.go
@@ -172,7 +172,7 @@ type KBShareRepository interface {
type AgentShareService interface {
ShareAgent(ctx context.Context, agentID string, orgID string, userID string, tenantID uint64, permission types.OrgMemberRole) (*types.AgentShare, error)
RemoveShare(ctx context.Context, shareID string, userID string, tenantID uint64) error
- ListSharesByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error)
+ ListSharesByAgent(ctx context.Context, agentID string, tenantID uint64) ([]*types.AgentShare, error)
ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error)
ListSharedAgents(ctx context.Context, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.SharedAgentInfo, error)
ListSharedAgentsInOrganization(ctx context.Context, orgID string, tenantID uint64, callerTenantRole types.TenantRole) ([]*types.OrganizationSharedAgentItem, error)
diff --git a/internal/types/tenant_api_key.go b/internal/types/tenant_api_key.go
index 7730c9364..e0033ba93 100644
--- a/internal/types/tenant_api_key.go
+++ b/internal/types/tenant_api_key.go
@@ -103,8 +103,9 @@ const (
APIKeyCapabilityManageMembers APIKeyCapability = "manage_members"
// APIKeyCapabilityManageSpaces lets a key manage organization/space
// collaboration surfaces such as space membership and join flows. It does
- // not grant KB/agent share management, which still depends on resource
- // ownership and remains JWT-only/default-deny for API keys.
+ // not grant KB/agent share management: share management is reserved for
+ // full-access keys (and JWT) and scoped keys stay default-deny. This
+ // capability never lifts it.
APIKeyCapabilityManageSpaces APIKeyCapability = "manage_spaces"
// APIKeyCapabilityManageTenantSettings lets a key read and update
// tenant-scoped integration settings exposed under /tenants, such as API