From 8cb43473e60132469b1164faddf6f151e7755c60 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Thu, 23 Jul 2026 21:11:37 +0800 Subject: [PATCH] fix(knowledge): restrict source file download to Editor and above Downloading exposes the original source file, which is more sensitive than viewing parsed content or previews. Align backend route guards, handler checks, and frontend UI so tenant Viewers and org-shared read-only access cannot download. --- frontend/src/components/doc-content.vue | 4 +- .../src/views/knowledge/KnowledgeBase.vue | 13 ++- internal/handler/knowledge.go | 5 +- internal/router/router.go | 8 +- .../router_api_key_capabilities_test.go | 1 + .../router/router_knowledge_download_test.go | 110 ++++++++++++++++++ 6 files changed, 136 insertions(+), 5 deletions(-) create mode 100644 internal/router/router_knowledge_download_test.go diff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vue index 5ab335d8..4a78607f 100644 --- a/frontend/src/components/doc-content.vue +++ b/frontend/src/components/doc-content.vue @@ -84,7 +84,7 @@ mermaid.initialize({ topPadding: 50 } }); -const props = defineProps(["visible", "details", "knowledgeType", "sourceInfo", "canEditKB", "parse_status", "kbId"]); +const props = defineProps(["visible", "details", "knowledgeType", "sourceInfo", "canEditKB", "canDownloadKB", "parse_status", "kbId"]); const emit = defineEmits(["closeDoc", "getDoc", "questionDeleted"]); const hasTimelineSpans = ref(false); @@ -1095,7 +1095,7 @@ const handleDetailsScroll = () => {
{{ getDisplayTitle() }}
- -
diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.go index 6fd32ea4..32e56a4b 100644 --- a/internal/handler/knowledge.go +++ b/internal/handler/knowledge.go @@ -1276,7 +1276,10 @@ func (h *KnowledgeHandler) DownloadKnowledgeFile(c *gin.Context) { return } - _, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleViewer) + // Keep a handler-level Editor check in addition to the route guard. The + // original file is more sensitive than parsed-content reads and must not + // be downloadable through a read-only organization share. + _, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, id, types.OrgRoleEditor) if err != nil { c.Error(err) return diff --git a/internal/router/router.go b/internal/router/router.go index b4934f47..4e41f89d 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -374,7 +374,13 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandl k.PUT("/manual/:id", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.UpdateManualKnowledge) k.POST("/:id/reparse", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.ReparseKnowledge) k.POST("/:id/cancel-parse", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.CancelKnowledgeParse) - kRead.GET("/:id/download", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.DownloadKnowledgeFile) + // Downloading exposes the original source file, so it has a stricter + // boundary than viewing parsed content or previewing it: tenant Viewers + // cannot download from their own workspace, and org-shared Viewer access + // cannot download from the source workspace. API keys still follow the + // retrieve capability declared by kRead; role guards intentionally defer + // machine-principal authorization to the API-key gate. + kRead.GET("/:id/download", g.Contributor(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.DownloadKnowledgeFile) kRead.GET("/:id/preview", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.PreviewKnowledgeFile) k.PUT("/image/:id/:chunk_id", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.UpdateImageInfo) kRead.GET("/search", g.Viewer(), handler.SearchKnowledge) diff --git a/internal/router/router_api_key_capabilities_test.go b/internal/router/router_api_key_capabilities_test.go index 68ebe321..5127a606 100644 --- a/internal/router/router_api_key_capabilities_test.go +++ b/internal/router/router_api_key_capabilities_test.go @@ -308,6 +308,7 @@ func TestKnowledgeReadRoutesDeclareRetrieveCapability(t *testing.T) { {http.MethodPost, "/api/v1/knowledge-bases/:id/hybrid-search"}, {http.MethodGet, "/api/v1/knowledge-bases/:id/knowledge"}, {http.MethodGet, "/api/v1/knowledge/:id"}, + {http.MethodGet, "/api/v1/knowledge/:id/download"}, {http.MethodPost, "/api/v1/knowledge-bases/:id/faq/search"}, {http.MethodGet, "/api/v1/knowledge-bases/:id/tags"}, {http.MethodPost, "/api/v1/knowledge-search"}, diff --git a/internal/router/router_knowledge_download_test.go b/internal/router/router_knowledge_download_test.go new file mode 100644 index 00000000..0d0438a2 --- /dev/null +++ b/internal/router/router_knowledge_download_test.go @@ -0,0 +1,110 @@ +package router + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + apprepo "github.com/Tencent/WeKnora/internal/application/repository" + "github.com/Tencent/WeKnora/internal/config" + "github.com/Tencent/WeKnora/internal/handler" + "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 downloadKnowledgeLookup struct { + knowledge *types.Knowledge +} + +func (s *downloadKnowledgeLookup) GetKnowledgeByIDOnly(_ context.Context, id string) (*types.Knowledge, error) { + if s.knowledge != nil && s.knowledge.ID == id { + return s.knowledge, nil + } + return nil, apprepo.ErrKnowledgeNotFound +} + +type downloadKBShareStub struct { + interfaces.KBShareService + permission types.OrgMemberRole + source uint64 +} + +func (s *downloadKBShareStub) CheckTenantKBPermission( + _ context.Context, + _ string, + _ uint64, + _ types.TenantRole, +) (types.OrgMemberRole, bool, error) { + return s.permission, true, nil +} + +func (s *downloadKBShareStub) GetKBSourceTenant(_ context.Context, _ string) (uint64, error) { + return s.source, nil +} + +func newKnowledgeDownloadRouteTestEngine( + t *testing.T, + role types.TenantRole, + knowledge *types.Knowledge, + kb *types.KnowledgeBase, + share interfaces.KBShareService, +) *gin.Engine { + t.Helper() + gin.SetMode(gin.TestMode) + + enabled := true + guards := &rbacGuards{ + cfg: &config.Config{Tenant: &config.TenantConfig{EnableRBAC: &enabled}}, + knowledgeService: &downloadKnowledgeLookup{knowledge: knowledge}, + kbService: &stubWikiKBLookup{kbs: map[string]*types.KnowledgeBase{kb.ID: kb}}, + kbShareService: share, + } + + r := gin.New() + r.Use(middleware.ErrorHandler()) + r.Use(func(c *gin.Context) { + ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(1)) + ctx = context.WithValue(ctx, types.TenantRoleContextKey, role) + c.Request = c.Request.WithContext(ctx) + c.Set(types.TenantIDContextKey.String(), uint64(1)) + c.Next() + }) + RegisterKnowledgeRoutes(r.Group("/api/v1"), &handler.KnowledgeHandler{}, guards) + return r +} + +func TestKnowledgeDownloadRejectsTenantViewer(t *testing.T) { + engine := newKnowledgeDownloadRouteTestEngine( + t, + types.TenantRoleViewer, + &types.Knowledge{ID: "knowledge-own", KnowledgeBaseID: "kb-own", TenantID: 1}, + &types.KnowledgeBase{ID: "kb-own", TenantID: 1}, + nil, + ) + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/v1/knowledge/knowledge-own/download", nil) + engine.ServeHTTP(rec, req) + + require.Equal(t, http.StatusForbidden, rec.Code, "body=%s", rec.Body.String()) +} + +func TestKnowledgeDownloadRejectsReadOnlySharedKB(t *testing.T) { + engine := newKnowledgeDownloadRouteTestEngine( + t, + types.TenantRoleContributor, + &types.Knowledge{ID: "knowledge-shared", KnowledgeBaseID: "kb-shared", TenantID: 2}, + &types.KnowledgeBase{ID: "kb-shared", TenantID: 2}, + &downloadKBShareStub{permission: types.OrgRoleViewer, source: 2}, + ) + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/v1/knowledge/knowledge-shared/download", nil) + engine.ServeHTTP(rec, req) + + require.Equal(t, http.StatusForbidden, rec.Code, "body=%s", rec.Body.String()) +}