Skip to content

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

feat(rbac): per-KB ownership for knowledge / chunks / wiki pages (#1303)

wizardchend42a41b784e8
diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.go
index 5c905ea46..ed484cb95 100644
--- a/internal/application/service/knowledge.go
+++ b/internal/application/service/knowledge.go
@@ -8,6 +8,7 @@ import (
"strings"
"sync"
+ "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service/retriever"
"github.com/Tencent/WeKnora/internal/config"
werrors "github.com/Tencent/WeKnora/internal/errors"
@@ -203,6 +204,29 @@ func (s *knowledgeService) GetKnowledgeByIDOnly(ctx context.Context, id string)
return s.repo.GetKnowledgeByIDOnly(ctx, id)
}
+// GetOwningKBCreatorID walks knowledge_id -> kb_id -> KB.CreatorID for
+// the per-KB ownership lookups in handler/rbac_lookups.go (PR 5, #1303).
+// Both fetches are tenant-scoped (GetKnowledgeByID reads tenant from
+// ctx; GetKnowledgeBaseByID is then constrained to the same tenant by
+// the KB service), so a cross-tenant id surfaces as the underlying
+// "not found" error and the caller maps it to ErrResourceNotFound. The
+// KB row itself is not returned so callers can't accidentally widen
+// their scope past "needed the creator id".
+func (s *knowledgeService) GetOwningKBCreatorID(ctx context.Context, knowledgeID string) (string, error) {
+ knowledge, err := s.GetKnowledgeByID(ctx, knowledgeID)
+ if err != nil {
+ return "", err
+ }
+ kb, err := s.kbService.GetKnowledgeBaseByID(ctx, knowledge.KnowledgeBaseID)
+ if err != nil {
+ return "", err
+ }
+ if kb == nil {
+ return "", repository.ErrKnowledgeBaseNotFound
+ }
+ return kb.CreatorID, nil
+}
+
// ListKnowledgeByKnowledgeBaseID returns all knowledge entries in a knowledge base
func (s *knowledgeService) ListKnowledgeByKnowledgeBaseID(ctx context.Context,
kbID string,
diff --git a/internal/application/service/knowledge_owner_chain_test.go b/internal/application/service/knowledge_owner_chain_test.go
new file mode 100644
index 000000000..30a13421b
--- /dev/null
+++ b/internal/application/service/knowledge_owner_chain_test.go
@@ -0,0 +1,173 @@
+package service
+
+import (
+ "context"
+ stderrors "errors"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/application/repository"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+// PR 5 (#1303) — service-layer chain helper for the per-KB ownership
+// lookups. The handler-level adapters in internal/handler/rbac_lookups.go
+// translate this method's repository sentinels into
+// middleware.ErrResourceNotFound; this file pins the contract on the
+// service side so a future refactor can't quietly drop a sentinel.
+
+// stubKnowledgeRepoForChain implements just GetKnowledgeByID; everything
+// else panics so a test that reaches outside the contract fails loudly.
+type stubKnowledgeRepoForChain struct {
+ interfaces.KnowledgeRepository
+ getByID func(ctx context.Context, tenantID uint64, id string) (*types.Knowledge, error)
+}
+
+func (s *stubKnowledgeRepoForChain) GetKnowledgeByID(
+ ctx context.Context, tenantID uint64, id string,
+) (*types.Knowledge, error) {
+ return s.getByID(ctx, tenantID, id)
+}
+
+// stubKBServiceForChain mirrors the handler-side stub but lives in the
+// service test package — embedding the interface keeps untouched
+// methods nil-panicky on purpose.
+type stubKBServiceForChain struct {
+ interfaces.KnowledgeBaseService
+ getByID func(ctx context.Context, id string) (*types.KnowledgeBase, error)
+}
+
+func (s *stubKBServiceForChain) GetKnowledgeBaseByID(
+ ctx context.Context, id string,
+) (*types.KnowledgeBase, error) {
+ return s.getByID(ctx, id)
+}
+
+func newKnowledgeServiceForChain(
+ repo interfaces.KnowledgeRepository, kb interfaces.KnowledgeBaseService,
+) *knowledgeService {
+ return &knowledgeService{repo: repo, kbService: kb}
+}
+
+func chainCtx(tenantID uint64) context.Context {
+ return context.WithValue(context.Background(), types.TenantIDContextKey, tenantID)
+}
+
+func TestGetOwningKBCreatorID_KnowledgeNotFound(t *testing.T) {
+ // Repository sentinel passes through unchanged so the handler-level
+ // translator can map it to middleware.ErrResourceNotFound.
+ s := newKnowledgeServiceForChain(
+ &stubKnowledgeRepoForChain{
+ getByID: func(_ context.Context, _ uint64, _ string) (*types.Knowledge, error) {
+ return nil, repository.ErrKnowledgeNotFound
+ },
+ },
+ &stubKBServiceForChain{
+ getByID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
+ t.Fatalf("KB service must not be called when knowledge lookup fails")
+ return nil, nil
+ },
+ },
+ )
+ _, err := s.GetOwningKBCreatorID(chainCtx(1), "kn-missing")
+ if !stderrors.Is(err, repository.ErrKnowledgeNotFound) {
+ t.Fatalf("expected ErrKnowledgeNotFound, got %v", err)
+ }
+}
+
+func TestGetOwningKBCreatorID_KBNotFound(t *testing.T) {
+ // Knowledge resolves but its KB has been deleted (or was never
+ // created — defence-in-depth). The KB sentinel must surface so the
+ // handler can render 404 rather than 503/500.
+ s := newKnowledgeServiceForChain(
+ &stubKnowledgeRepoForChain{
+ getByID: func(_ context.Context, _ uint64, _ string) (*types.Knowledge, error) {
+ return &types.Knowledge{ID: "kn-1", KnowledgeBaseID: "kb-missing"}, nil
+ },
+ },
+ &stubKBServiceForChain{
+ getByID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
+ return nil, repository.ErrKnowledgeBaseNotFound
+ },
+ },
+ )
+ _, err := s.GetOwningKBCreatorID(chainCtx(1), "kn-1")
+ if !stderrors.Is(err, repository.ErrKnowledgeBaseNotFound) {
+ t.Fatalf("expected ErrKnowledgeBaseNotFound, got %v", err)
+ }
+}
+
+func TestGetOwningKBCreatorID_KBNilWithoutErrSurfacesAsNotFound(t *testing.T) {
+ // Some KB-service implementations return (nil, nil) for "not found"
+ // instead of a sentinel error. The chain must treat that as
+ // ErrKnowledgeBaseNotFound rather than dereferencing nil.
+ s := newKnowledgeServiceForChain(
+ &stubKnowledgeRepoForChain{
+ getByID: func(_ context.Context, _ uint64, _ string) (*types.Knowledge, error) {
+ return &types.Knowledge{ID: "kn-1", KnowledgeBaseID: "kb-1"}, nil
+ },
+ },
+ &stubKBServiceForChain{
+ getByID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
+ return nil, nil
+ },
+ },
+ )
+ _, err := s.GetOwningKBCreatorID(chainCtx(1), "kn-1")
+ if !stderrors.Is(err, repository.ErrKnowledgeBaseNotFound) {
+ t.Fatalf("nil KB without error must surface as ErrKnowledgeBaseNotFound, got %v", err)
+ }
+}
+
+func TestGetOwningKBCreatorID_HappyPathReturnsKBCreator(t *testing.T) {
+ s := newKnowledgeServiceForChain(
+ &stubKnowledgeRepoForChain{
+ getByID: func(_ context.Context, tenantID uint64, _ string) (*types.Knowledge, error) {
+ if tenantID != 1 {
+ t.Fatalf("expected tenant context to flow into repo (got %d)", tenantID)
+ }
+ return &types.Knowledge{ID: "kn-1", KnowledgeBaseID: "kb-1"}, nil
+ },
+ },
+ &stubKBServiceForChain{
+ getByID: func(_ context.Context, id string) (*types.KnowledgeBase, error) {
+ if id != "kb-1" {
+ t.Fatalf("KB lookup must use the knowledge's KnowledgeBaseID, got %q", id)
+ }
+ return &types.KnowledgeBase{ID: "kb-1", TenantID: 1, CreatorID: "u-creator"}, nil
+ },
+ },
+ )
+ creator, err := s.GetOwningKBCreatorID(chainCtx(1), "kn-1")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if creator != "u-creator" {
+ t.Fatalf("expected creator=u-creator, got %q", creator)
+ }
+}
+
+func TestGetOwningKBCreatorID_LegacyKBHasEmptyCreatorID(t *testing.T) {
+ // Legacy KBs created before PR 1 have CreatorID == ""; the chain
+ // helper must surface that empty string unchanged so the
+ // middleware's "" -> tenant-owned branch fires (Admin+ only).
+ s := newKnowledgeServiceForChain(
+ &stubKnowledgeRepoForChain{
+ getByID: func(_ context.Context, _ uint64, _ string) (*types.Knowledge, error) {
+ return &types.Knowledge{ID: "kn-1", KnowledgeBaseID: "kb-legacy"}, nil
+ },
+ },
+ &stubKBServiceForChain{
+ getByID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
+ return &types.KnowledgeBase{ID: "kb-legacy", TenantID: 1, CreatorID: ""}, nil
+ },
+ },
+ )
+ creator, err := s.GetOwningKBCreatorID(chainCtx(1), "kn-1")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if creator != "" {
+ t.Fatalf("legacy KB must surface empty creator id, got %q", creator)
+ }
+}
diff --git a/internal/handler/rbac_lookups.go b/internal/handler/rbac_lookups.go
index 5fd7bceaf..28152fbc7 100644
--- a/internal/handler/rbac_lookups.go
+++ b/internal/handler/rbac_lookups.go
@@ -7,6 +7,7 @@ import (
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
@@ -105,4 +106,98 @@ func (h *CustomAgentHandler) AgentCreatorLookup(c *gin.Context) (string, error)
var (
_ middleware.CreatorLookup = (*KnowledgeBaseHandler)(nil).KBCreatorLookup
_ middleware.CreatorLookup = (*CustomAgentHandler)(nil).AgentCreatorLookup
+ _ middleware.CreatorLookup = (*KnowledgeHandler)(nil).KBCreatorLookupFromKnowledgeID
+ _ middleware.CreatorLookup = (*ChunkHandler)(nil).KBCreatorLookupFromKnowledgeIDParam
+ _ middleware.CreatorLookup = (*WikiPageHandler)(nil).KBCreatorLookupFromKBPath
)
+
+// KBCreatorLookupFromKnowledgeID resolves :id (a Knowledge ID) to the
+// CreatorID of the *owning KB*, scoped to the caller's tenant. Used by
+// per-knowledge mutating routes (PR 5, #1303) so a Contributor who owns
+// the KB can edit/delete any of its documents while a Contributor who
+// merely belongs to the tenant cannot. Built-in / legacy KBs without a
+// CreatorID surface as ("", nil) and stay Admin-gated.
+//
+// The chain (knowledge_id -> kb_id -> KB.CreatorID) lives in the
+// service layer (KnowledgeService.GetOwningKBCreatorID) so this lookup
+// stays a pure adapter — same shape as KBCreatorLookup.
+func (h *KnowledgeHandler) KBCreatorLookupFromKnowledgeID(c *gin.Context) (string, error) {
+ knowledgeID := c.Param("id")
+ if knowledgeID == "" {
+ return "", errors.New("missing :id param for knowledge owner lookup")
+ }
+ return resolveKBCreatorByKnowledgeID(c, h.kgService, knowledgeID)
+}
+
+// KBCreatorLookupFromKnowledgeIDParam mirrors KBCreatorLookupFromKnowledgeID
+// for chunk routes, which use :knowledge_id rather than :id. The
+// chunks.DELETE("/by-id/:id/questions") route addresses a chunk by its
+// own id (not a knowledge id), so it stays Contributor-gated and is
+// not wired through this lookup — see router.go for the carve-out.
+func (h *ChunkHandler) KBCreatorLookupFromKnowledgeIDParam(c *gin.Context) (string, error) {
+ knowledgeID := c.Param("knowledge_id")
+ if knowledgeID == "" {
+ return "", errors.New("missing :knowledge_id param for chunk owner lookup")
+ }
+ return resolveKBCreatorByKnowledgeID(c, h.kgService, knowledgeID)
+}
+
+// KBCreatorLookupFromKBPath resolves :kb_id (used by wiki routes) to
+// KnowledgeBase.CreatorID. No chain hop — the wiki page URL already
+// carries the owning KB id, so we go straight to the KB service. The
+// tenant defence-in-depth re-check stays the same as KBCreatorLookup:
+// repo.GetKnowledgeBaseByID is unscoped, so we explicitly compare
+// against the context tenant.
+func (h *WikiPageHandler) KBCreatorLookupFromKBPath(c *gin.Context) (string, error) {
+ kbID := c.Param("kb_id")
+ if kbID == "" {
+ return "", errors.New("missing :kb_id param for wiki owner lookup")
+ }
+ ctx := c.Request.Context()
+ tenantID, ok := types.TenantIDFromContext(ctx)
+ if !ok {
+ return "", errors.New("tenant context missing")
+ }
+ kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbID)
+ if err != nil {
+ if errors.Is(err, apprepo.ErrKnowledgeBaseNotFound) {
+ return "", middleware.ErrResourceNotFound
+ }
+ return "", err
+ }
+ if kb == nil {
+ return "", middleware.ErrResourceNotFound
+ }
+ if kb.TenantID != tenantID {
+ return "", middleware.ErrResourceNotFound
+ }
+ return kb.CreatorID, nil
+}
+
+// resolveKBCreatorByKnowledgeID is the shared body for the knowledge /
+// chunk lookups. The service-layer chain helper does the tenant-scoped
+// fetch (knowledge -> KB) and returns repository sentinel errors;
+// translating those to middleware.ErrResourceNotFound is the lookup's
+// job, mirroring what KBCreatorLookup does for plain :id routes.
+func resolveKBCreatorByKnowledgeID(
+ c *gin.Context,
+ kgService interfaces.KnowledgeService,
+ knowledgeID string,
+) (string, error) {
+ ctx := c.Request.Context()
+ if _, ok := types.TenantIDFromContext(ctx); !ok {
+ // Same fail-closed reasoning as KBCreatorLookup: no tenant
+ // context means auth didn't complete, and we'd rather have the
+ // caller see a 503 than a silent fail-open.
+ return "", errors.New("tenant context missing")
+ }
+ creatorID, err := kgService.GetOwningKBCreatorID(ctx, knowledgeID)
+ if err != nil {
+ if errors.Is(err, apprepo.ErrKnowledgeNotFound) ||
+ errors.Is(err, apprepo.ErrKnowledgeBaseNotFound) {
+ return "", middleware.ErrResourceNotFound
+ }
+ return "", err
+ }
+ return creatorID, nil
+}
diff --git a/internal/handler/rbac_lookups_test.go b/internal/handler/rbac_lookups_test.go
index c5be81137..0f7de7ab4 100644
--- a/internal/handler/rbac_lookups_test.go
+++ b/internal/handler/rbac_lookups_test.go
@@ -169,3 +169,200 @@ func TestAgentCreatorLookup_CrossTenantIsHiddenAsNotFound(t *testing.T) {
t.Fatalf("cross-tenant agent must surface as not-found, got %v", err)
}
}
+
+// PR 5 (#1303) per-KB ownership lookups. The chain helper lives in the
+// service layer; the lookups here are pure adapters that translate the
+// repository sentinels into middleware.ErrResourceNotFound. Tests focus
+// on those translations — the service-side chain has its own tests in
+// internal/application/service.
+
+// stubKgService stands in for interfaces.KnowledgeService for the
+// knowledge / chunk lookups. Embedding the interface keeps every
+// non-stubbed method nil-panicky on purpose: a future refactor that
+// reaches outside GetOwningKBCreatorID should fail loudly, not silently.
+type stubKgService struct {
+ interfaces.KnowledgeService
+ getOwningKBCreatorID func(ctx context.Context, knowledgeID string) (string, error)
+}
+
+func (s *stubKgService) GetOwningKBCreatorID(ctx context.Context, knowledgeID string) (string, error) {
+ return s.getOwningKBCreatorID(ctx, knowledgeID)
+}
+
+// newKnowledgeLookupCtx builds a gin.Context shaped like the
+// /knowledge/:id route — :id holds a knowledge id.
+func newKnowledgeLookupCtx(t *testing.T, tenantID uint64, knowledgeID string) *gin.Context {
+ return newKBLookupCtx(t, tenantID, knowledgeID)
+}
+
+// newChunkLookupCtx builds a gin.Context shaped like the
+// /chunks/:knowledge_id/:id route — only :knowledge_id is set since
+// that's all the lookup reads.
+func newChunkLookupCtx(t *testing.T, tenantID uint64, knowledgeID string) *gin.Context {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodGet, "/x", nil)
+ ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, tenantID)
+ c.Request = c.Request.WithContext(ctx)
+ c.Params = gin.Params{{Key: "knowledge_id", Value: knowledgeID}}
+ return c
+}
+
+// newWikiLookupCtx builds a gin.Context shaped like the
+// /knowledgebase/:kb_id/wiki/... routes.
+func newWikiLookupCtx(t *testing.T, tenantID uint64, kbID string) *gin.Context {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodGet, "/x", nil)
+ ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, tenantID)
+ c.Request = c.Request.WithContext(ctx)
+ c.Params = gin.Params{{Key: "kb_id", Value: kbID}}
+ return c
+}
+
+func TestKBCreatorLookupFromKnowledgeID_NotFoundMapsToSentinel(t *testing.T) {
+ // Either sentinel from the repo (knowledge missing OR its KB missing)
+ // must surface as ErrResourceNotFound — same behaviour as the
+ // KB-level lookup so middleware translates uniformly.
+ for _, tc := range []struct {
+ name string
+ err error
+ }{
+ {"knowledge-not-found", apprepo.ErrKnowledgeNotFound},
+ {"kb-not-found", apprepo.ErrKnowledgeBaseNotFound},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ h := &KnowledgeHandler{kgService: &stubKgService{
+ getOwningKBCreatorID: func(_ context.Context, _ string) (string, error) {
+ return "", tc.err
+ },
+ }}
+ _, err := h.KBCreatorLookupFromKnowledgeID(newKnowledgeLookupCtx(t, 1, "kn-1"))
+ if !errors.Is(err, middleware.ErrResourceNotFound) {
+ t.Fatalf("expected ErrResourceNotFound, got %v", err)
+ }
+ })
+ }
+}
+
+func TestKBCreatorLookupFromKnowledgeID_OwnerMatchReturnsCreatorID(t *testing.T) {
+ h := &KnowledgeHandler{kgService: &stubKgService{
+ getOwningKBCreatorID: func(_ context.Context, _ string) (string, error) {
+ return "u-kb-creator", nil
+ },
+ }}
+ creator, err := h.KBCreatorLookupFromKnowledgeID(newKnowledgeLookupCtx(t, 1, "kn-1"))
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if creator != "u-kb-creator" {
+ t.Fatalf("expected creator=u-kb-creator, got %q", creator)
+ }
+}
+
+func TestKBCreatorLookupFromKnowledgeID_MissingTenantContext(t *testing.T) {
+ // Mirror KBCreatorLookup_MissingTenantContext: no tenant context
+ // means auth didn't complete; the lookup must NOT call the service
+ // and must NOT return ErrResourceNotFound (which would silently turn
+ // into a "fail open" pass).
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodGet, "/x", nil)
+ c.Params = gin.Params{{Key: "id", Value: "kn-1"}}
+ h := &KnowledgeHandler{kgService: &stubKgService{
+ getOwningKBCreatorID: func(_ context.Context, _ string) (string, error) {
+ t.Fatalf("service must not be called without tenant context")
+ return "", nil
+ },
+ }}
+ _, err := h.KBCreatorLookupFromKnowledgeID(c)
+ if err == nil {
+ t.Fatalf("expected error when tenant context missing")
+ }
+ if errors.Is(err, middleware.ErrResourceNotFound) {
+ t.Fatalf("missing tenant must not be reported as not-found: %v", err)
+ }
+}
+
+func TestKBCreatorLookupFromKnowledgeIDParam_ChunkRouteShape(t *testing.T) {
+ // Chunk routes use :knowledge_id rather than :id; the lookup must
+ // read from the right param name. A bug here would silently break
+ // chunk delete/update on rollout.
+ h := &ChunkHandler{kgService: &stubKgService{
+ getOwningKBCreatorID: func(_ context.Context, knowledgeID string) (string, error) {
+ if knowledgeID != "kn-from-chunk-route" {
+ t.Fatalf("lookup must read :knowledge_id, got %q", knowledgeID)
+ }
+ return "u-kb-creator", nil
+ },
+ }}
+ creator, err := h.KBCreatorLookupFromKnowledgeIDParam(
+ newChunkLookupCtx(t, 1, "kn-from-chunk-route"),
+ )
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if creator != "u-kb-creator" {
+ t.Fatalf("expected creator=u-kb-creator, got %q", creator)
+ }
+}
+
+func TestKBCreatorLookupFromKnowledgeIDParam_NotFoundMapsToSentinel(t *testing.T) {
+ h := &ChunkHandler{kgService: &stubKgService{
+ getOwningKBCreatorID: func(_ context.Context, _ string) (string, error) {
+ return "", apprepo.ErrKnowledgeNotFound
+ },
+ }}
+ _, err := h.KBCreatorLookupFromKnowledgeIDParam(newChunkLookupCtx(t, 1, "kn-1"))
+ if !errors.Is(err, middleware.ErrResourceNotFound) {
+ t.Fatalf("expected ErrResourceNotFound, got %v", err)
+ }
+}
+
+func TestKBCreatorLookupFromKBPath_NotFoundMapsToSentinel(t *testing.T) {
+ // Wiki lookup path goes straight to the KB service (no chain hop),
+ // so its translation behaviour mirrors KBCreatorLookup.
+ h := &WikiPageHandler{kbService: &stubKBService{
+ get: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
+ return nil, apprepo.ErrKnowledgeBaseNotFound
+ },
+ }}
+ _, err := h.KBCreatorLookupFromKBPath(newWikiLookupCtx(t, 1, "kb-1"))
+ if !errors.Is(err, middleware.ErrResourceNotFound) {
+ t.Fatalf("expected ErrResourceNotFound, got %v", err)
+ }
+}
+
+func TestKBCreatorLookupFromKBPath_CrossTenantIsHiddenAsNotFound(t *testing.T) {
+ // Same security boundary as KBCreatorLookup_CrossTenantIsHiddenAsNotFound.
+ // repo.GetKnowledgeBaseByID is unscoped, so the lookup MUST re-check
+ // TenantID; otherwise a probed cross-tenant kb_id whose CreatorID
+ // happens to match the caller's user id would slip past the
+ // ownership shortcut.
+ h := &WikiPageHandler{kbService: &stubKBService{
+ get: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
+ return &types.KnowledgeBase{ID: "kb-1", TenantID: 999, CreatorID: "u1"}, nil
+ },
+ }}
+ _, err := h.KBCreatorLookupFromKBPath(newWikiLookupCtx(t, 1, "kb-1"))
+ if !errors.Is(err, middleware.ErrResourceNotFound) {
+ t.Fatalf("cross-tenant KB must surface as not-found, got %v", err)
+ }
+}
+
+func TestKBCreatorLookupFromKBPath_OwnerMatchReturnsCreatorID(t *testing.T) {
+ h := &WikiPageHandler{kbService: &stubKBService{
+ get: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
+ return &types.KnowledgeBase{ID: "kb-1", TenantID: 1, CreatorID: "u-creator"}, nil
+ },
+ }}
+ creator, err := h.KBCreatorLookupFromKBPath(newWikiLookupCtx(t, 1, "kb-1"))
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if creator != "u-creator" {
+ t.Fatalf("expected creator=u-creator, got %q", creator)
+ }
+}
diff --git a/internal/router/rbac.go b/internal/router/rbac.go
index 4ad9c6ccf..ede80c6b4 100644
--- a/internal/router/rbac.go
+++ b/internal/router/rbac.go
@@ -31,11 +31,26 @@ type rbacGuards struct {
// to be exported into every Register* function as well.
kbCreator middleware.CreatorLookup
agentCreator middleware.CreatorLookup
+ // Per-KB-ownership lookups for knowledge / chunk / wiki page routes
+ // (PR 5, #1303). They walk the URL param back to KB.CreatorID so a
+ // Contributor who owns the KB can edit/delete its sub-resources
+ // (documents, chunks, wiki pages); a Contributor who merely belongs
+ // to the tenant gets 403 unless they're also Admin+.
+ knowledgeKBCreator middleware.CreatorLookup
+ chunkKBCreator middleware.CreatorLookup
+ wikiKBCreator middleware.CreatorLookup
}
// newRBACGuards wires the guards from the live configuration and the
// already-built handlers. Called once from NewRouter.
-func newRBACGuards(cfg *config.Config, kbHandler *handler.KnowledgeBaseHandler, agentHandler *handler.CustomAgentHandler) *rbacGuards {
+func newRBACGuards(
+ cfg *config.Config,
+ kbHandler *handler.KnowledgeBaseHandler,
+ agentHandler *handler.CustomAgentHandler,
+ knowledgeHandler *handler.KnowledgeHandler,
+ chunkHandler *handler.ChunkHandler,
+ wikiHandler *handler.WikiPageHandler,
+) *rbacGuards {
g := &rbacGuards{cfg: cfg}
if kbHandler != nil {
g.kbCreator = kbHandler.KBCreatorLookup
@@ -43,6 +58,15 @@ func newRBACGuards(cfg *config.Config, kbHandler *handler.KnowledgeBaseHandler,
if agentHandler != nil {
g.agentCreator = agentHandler.AgentCreatorLookup
}
+ if knowledgeHandler != nil {
+ g.knowledgeKBCreator = knowledgeHandler.KBCreatorLookupFromKnowledgeID
+ }
+ if chunkHandler != nil {
+ g.chunkKBCreator = chunkHandler.KBCreatorLookupFromKnowledgeIDParam
+ }
+ if wikiHandler != nil {
+ g.wikiKBCreator = wikiHandler.KBCreatorLookupFromKBPath
+ }
return g
}
@@ -83,6 +107,31 @@ func (g *rbacGuards) OwnedAgentOrAdmin() gin.HandlerFunc {
return middleware.RequireOwnershipOrRole(types.TenantRoleAdmin, g.agentCreator, g.cfg)
}
+// OwnedKnowledgeKBOrAdmin: per-knowledge mutations (update / delete /
+// reparse / image edit) — the URL :id is a knowledge id, the lookup
+// walks it back to the owning KB's CreatorID. Same "creator OR Admin+"
+// rule as OwnedKBOrAdmin, just one chain hop deeper. PR 5 (#1303).
+func (g *rbacGuards) OwnedKnowledgeKBOrAdmin() gin.HandlerFunc {
+ return middleware.RequireOwnershipOrRole(types.TenantRoleAdmin, g.knowledgeKBCreator, g.cfg)
+}
+
+// OwnedChunkKBOrAdmin: chunk mutations addressed via :knowledge_id.
+// Reuses the same chain helper as OwnedKnowledgeKBOrAdmin so a
+// Contributor with KB ownership can manage all chunks under any of
+// their documents. The chunks.DELETE("/by-id/:id/questions") route
+// addresses chunks by :id (no knowledge id), so it is intentionally
+// not wired through this guard — see router.go for the carve-out.
+func (g *rbacGuards) OwnedChunkKBOrAdmin() gin.HandlerFunc {
+ return middleware.RequireOwnershipOrRole(types.TenantRoleAdmin, g.chunkKBCreator, g.cfg)
+}
+
+// OwnedWikiKBOrAdmin: wiki page CRUD and maintenance ops. Wiki routes
+// use :kb_id directly so the lookup is a single hop into the KB
+// service — no knowledge chain. Same matrix as OwnedKBOrAdmin.
+func (g *rbacGuards) OwnedWikiKBOrAdmin() gin.HandlerFunc {
+ return middleware.RequireOwnershipOrRole(types.TenantRoleAdmin, g.wikiKBCreator, g.cfg)
+}
+
// Tenant-access guards. Distinct from the role guards above: these
// answer the orthogonal question "may this caller touch this tenant
// at all", before role membership inside the tenant is even
diff --git a/internal/router/router.go b/internal/router/router.go
index 445cdedee..2fb4ef0f9 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -147,7 +147,14 @@ func NewRouter(params RouterParams) *gin.Engine {
// taking a *config.Config dependency directly. The guards honour
// cfg.Tenant.EnableRBAC: when false, they log but pass through,
// preserving today's behaviour during the rollout window.
- rbacGuards := newRBACGuards(params.Config, params.KBHandler, params.CustomAgentHandler)
+ rbacGuards := newRBACGuards(
+ params.Config,
+ params.KBHandler,
+ params.CustomAgentHandler,
+ params.KnowledgeHandler,
+ params.ChunkHandler,
+ params.WikiPageHandler,
+ )
RegisterAuthRoutes(v1, params.AuthHandler)
RegisterTenantRoutes(v1, params.TenantHandler, params.TenantMemberHandler, rbacGuards)
@@ -187,6 +194,11 @@ func RegisterChunkerDebugRoutes(r *gin.RouterGroup) {
}
// RegisterChunkRoutes 注册分块相关的路由
+//
+// Mutating routes addressed via :knowledge_id inherit per-KB ownership
+// from the owning knowledge entry's KB (PR 5, #1303); the chain hop is
+// shared with RegisterKnowledgeRoutes via OwnedChunkKBOrAdmin so the
+// same "creator-of-the-KB OR Admin+" rule applies to chunk edits.
func RegisterChunkRoutes(r *gin.RouterGroup, handler *handler.ChunkHandler, g *rbacGuards) {
// 分块路由组
chunks := r.Group("/chunks")
@@ -195,31 +207,40 @@ func RegisterChunkRoutes(r *gin.RouterGroup, handler *handler.ChunkHandler, g *r
chunks.GET("/:knowledge_id", g.Viewer(), handler.ListKnowledgeChunks)
// 通过chunk_id获取单个chunk(不需要knowledge_id) — Viewer+
chunks.GET("/by-id/:id", g.Viewer(), handler.GetChunkByIDOnly)
- // 删除分块 — Contributor+ (per-KB ownership granularity is a follow-up; PR 2 v1 keeps tenant-wide edit for chunks)
- chunks.DELETE("/:knowledge_id/:id", g.Contributor(), handler.DeleteChunk)
- // 删除知识下的所有分块 — Contributor+
- chunks.DELETE("/:knowledge_id", g.Contributor(), handler.DeleteChunksByKnowledgeID)
- // 更新分块信息 — Contributor+
- chunks.PUT("/:knowledge_id/:id", g.Contributor(), handler.UpdateChunk)
- // 删除单个生成的问题(通过问题ID) — Contributor+
+ // 删除分块 — KB owner OR Admin+
+ chunks.DELETE("/:knowledge_id/:id", g.OwnedChunkKBOrAdmin(), handler.DeleteChunk)
+ // 删除知识下的所有分块 — KB owner OR Admin+
+ chunks.DELETE("/:knowledge_id", g.OwnedChunkKBOrAdmin(), handler.DeleteChunksByKnowledgeID)
+ // 更新分块信息 — KB owner OR Admin+
+ chunks.PUT("/:knowledge_id/:id", g.OwnedChunkKBOrAdmin(), handler.UpdateChunk)
+ // 删除单个生成的问题(通过问题ID) — Contributor+. This route
+ // addresses a chunk by its own id (no knowledge id in the URL)
+ // so the per-KB ownership chain isn't reachable from the
+ // request alone; staying Contributor-gated here is a deliberate
+ // carve-out, not an oversight. A future PR could add a
+ // chunk-id -> knowledge-id -> KB lookup if the granularity
+ // difference becomes a problem in practice.
chunks.DELETE("/by-id/:id/questions", g.Contributor(), handler.DeleteGeneratedQuestion)
}
}
// RegisterKnowledgeRoutes 注册知识相关的路由
//
-// PR 2 attaches role-only guards here (Viewer for reads, Contributor for
-// writes). Per-KB-ownership granularity for knowledge entries (so that
-// Contributor X cannot edit Contributor Y's documents within the same
-// KB) is a follow-up — it requires a knowledge-id -> KB chain lookup
-// that's noisy enough to be worth its own PR.
+// Per-KB ownership applies on the per-:id mutating routes (PR 5,
+// #1303): the URL :id is a knowledge id, OwnedKnowledgeKBOrAdmin
+// walks it back to KB.CreatorID so a Contributor who owns the KB can
+// edit/delete any of its documents while a non-owner Contributor gets
+// 403. KB-scoped upload routes (`/knowledge-bases/:id/knowledge/...`)
+// reuse OwnedKBOrAdmin because the URL :id is the KB id directly.
+// Cross-:id batch operations stay Contributor-gated — they don't have
+// a single owning KB to check against.
func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandler, g *rbacGuards) {
// 知识库下的知识路由组
kb := r.Group("/knowledge-bases/:id/knowledge")
{
- kb.POST("/file", g.Contributor(), handler.CreateKnowledgeFromFile)
- kb.POST("/url", g.Contributor(), handler.CreateKnowledgeFromURL)
- kb.POST("/manual", g.Contributor(), handler.CreateManualKnowledge)
+ kb.POST("/file", g.OwnedKBOrAdmin(), handler.CreateKnowledgeFromFile)
+ kb.POST("/url", g.OwnedKBOrAdmin(), handler.CreateKnowledgeFromURL)
+ kb.POST("/manual", g.OwnedKBOrAdmin(), handler.CreateManualKnowledge)
kb.GET("", g.Viewer(), handler.ListKnowledge)
// Clearing all contents under a KB is a destructive op; gate
// behind Admin instead of Contributor.
@@ -231,13 +252,17 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandl
{
k.GET("/batch", g.Viewer(), handler.GetKnowledgeBatch)
k.GET("/:id", g.Viewer(), handler.GetKnowledge)
- k.DELETE("/:id", g.Contributor(), handler.DeleteKnowledge)
- k.PUT("/:id", g.Contributor(), handler.UpdateKnowledge)
- k.PUT("/manual/:id", g.Contributor(), handler.UpdateManualKnowledge)
- k.POST("/:id/reparse", g.Contributor(), handler.ReparseKnowledge)
+ k.DELETE("/:id", g.OwnedKnowledgeKBOrAdmin(), handler.DeleteKnowledge)
+ k.PUT("/:id", g.OwnedKnowledgeKBOrAdmin(), handler.UpdateKnowledge)
+ k.PUT("/manual/:id", g.OwnedKnowledgeKBOrAdmin(), handler.UpdateManualKnowledge)
+ k.POST("/:id/reparse", g.OwnedKnowledgeKBOrAdmin(), handler.ReparseKnowledge)
k.GET("/:id/download", g.Viewer(), handler.DownloadKnowledgeFile)
k.GET("/:id/preview", g.Viewer(), handler.PreviewKnowledgeFile)
- k.PUT("/image/:id/:chunk_id", g.Contributor(), handler.UpdateImageInfo)
+ k.PUT("/image/:id/:chunk_id", g.OwnedKnowledgeKBOrAdmin(), handler.UpdateImageInfo)
+ // Batch / cross-KB ops stay Contributor-gated: there is no
+ // single owning KB to walk back to. A future PR could add a
+ // "must own every targeted KB" guard if the requirement
+ // surfaces.
k.PUT("/tags", g.Contributor(), handler.UpdateKnowledgeTagBatch)
k.GET("/search", g.Viewer(), handler.SearchKnowledge)
k.POST("/batch-delete", g.Contributor(), handler.BatchDeleteKnowledge)
@@ -1162,18 +1187,19 @@ func RegisterWeKnoraCloudRoutes(r *gin.RouterGroup, handler *handler.WeKnoraClou
//
// Wiki pages are KB content (wiki mode): reads are Viewer+, content
// mutations (create/update/delete) and maintenance actions
-// (rebuild-links, auto-fix, change issue status) are Contributor+.
-// Per-KB ownership granularity for individual pages is a follow-up,
-// same as plain knowledge entries.
+// (rebuild-links, auto-fix, change issue status) honour per-KB
+// ownership via OwnedWikiKBOrAdmin (PR 5, #1303): the URL :kb_id
+// resolves directly to the owning KB so a Contributor who owns the KB
+// can manage its wiki, while a non-owner Contributor gets 403.
func RegisterWikiPageRoutes(r *gin.RouterGroup, wikiHandler *handler.WikiPageHandler, g *rbacGuards) {
wiki := r.Group("/knowledgebase/:kb_id/wiki")
{
// Page CRUD
wiki.GET("/pages", g.Viewer(), wikiHandler.ListPages)
- wiki.POST("/pages", g.Contributor(), wikiHandler.CreatePage)
+ wiki.POST("/pages", g.OwnedWikiKBOrAdmin(), wikiHandler.CreatePage)
wiki.GET("/pages/*slug", g.Viewer(), wikiHandler.GetPage)
- wiki.PUT("/pages/*slug", g.Contributor(), wikiHandler.UpdatePage)
- wiki.DELETE("/pages/*slug", g.Contributor(), wikiHandler.DeletePage)
+ wiki.PUT("/pages/*slug", g.OwnedWikiKBOrAdmin(), wikiHandler.UpdatePage)
+ wiki.DELETE("/pages/*slug", g.OwnedWikiKBOrAdmin(), wikiHandler.DeletePage)
// Special pages
wiki.GET("/index", g.Viewer(), wikiHandler.GetIndex)
@@ -1185,12 +1211,12 @@ func RegisterWikiPageRoutes(r *gin.RouterGroup, wikiHandler *handler.WikiPageHan
// Search and maintenance
wiki.GET("/search", g.Viewer(), wikiHandler.SearchPages)
- wiki.POST("/rebuild-links", g.Contributor(), wikiHandler.RebuildLinks)
+ wiki.POST("/rebuild-links", g.OwnedWikiKBOrAdmin(), wikiHandler.RebuildLinks)
wiki.GET("/lint", g.Viewer(), wikiHandler.Lint)
- wiki.POST("/auto-fix", g.Contributor(), wikiHandler.AutoFix)
+ wiki.POST("/auto-fix", g.OwnedWikiKBOrAdmin(), wikiHandler.AutoFix)
// Issues
wiki.GET("/issues", g.Viewer(), wikiHandler.ListIssues)
- wiki.PUT("/issues/:issue_id/status", g.Contributor(), wikiHandler.UpdateIssueStatus)
+ wiki.PUT("/issues/:issue_id/status", g.OwnedWikiKBOrAdmin(), wikiHandler.UpdateIssueStatus)
}
}
diff --git a/internal/types/interfaces/knowledge.go b/internal/types/interfaces/knowledge.go
index e0ea0515e..3a2b2f565 100644
--- a/internal/types/interfaces/knowledge.go
+++ b/internal/types/interfaces/knowledge.go
@@ -55,6 +55,14 @@ type KnowledgeService interface {
GetKnowledgeByID(ctx context.Context, id string) (*types.Knowledge, error)
// GetKnowledgeByIDOnly retrieves knowledge by ID without tenant filter (for permission resolution).
GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error)
+ // GetOwningKBCreatorID resolves a knowledge ID to the CreatorID of its
+ // owning KnowledgeBase, scoped to the caller's tenant. Used by the
+ // per-KB ownership lookups in handler/rbac_lookups.go (PR 5, #1303) so
+ // chunk and knowledge sub-resource routes can inherit the same
+ // "creator-of-the-KB OR Admin+" gate that KB-level routes already use.
+ // Returns the underlying repository sentinel errors unchanged so
+ // callers can map them to middleware.ErrResourceNotFound.
+ GetOwningKBCreatorID(ctx context.Context, knowledgeID string) (string, error)
// GetKnowledgeBatch retrieves a batch of knowledge by IDs.
GetKnowledgeBatch(ctx context.Context, tenantID uint64, ids []string) ([]*types.Knowledge, error)
// GetKnowledgeBatchWithSharedAccess retrieves knowledge by IDs including items from shared KBs the user has access to.