diff --git a/internal/handler/rbac_lookups.go b/internal/handler/rbac_lookups.go index e40c6388..e586dbde 100644 --- a/internal/handler/rbac_lookups.go +++ b/internal/handler/rbac_lookups.go @@ -142,6 +142,7 @@ var ( _ middleware.CreatorLookup = (*CustomAgentHandler)(nil).AgentCreatorLookup _ middleware.CreatorLookup = (*KnowledgeHandler)(nil).KBCreatorLookupFromKnowledgeID _ middleware.CreatorLookup = (*ChunkHandler)(nil).KBCreatorLookupFromKnowledgeIDParam + _ middleware.CreatorLookup = (*ChunkHandler)(nil).KBCreatorLookupFromChunkIDParam _ middleware.CreatorLookup = (*WikiPageHandler)(nil).KBCreatorLookupFromKBPath ) @@ -164,10 +165,9 @@ func (h *KnowledgeHandler) KBCreatorLookupFromKnowledgeID(c *gin.Context) (strin } // 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. +// for chunk routes that use :knowledge_id rather than :id. Chunk routes +// addressed by :id (no knowledge id) instead use +// KBCreatorLookupFromChunkIDParam below. func (h *ChunkHandler) KBCreatorLookupFromKnowledgeIDParam(c *gin.Context) (string, error) { knowledgeID := c.Param("knowledge_id") if knowledgeID == "" { @@ -176,6 +176,45 @@ func (h *ChunkHandler) KBCreatorLookupFromKnowledgeIDParam(c *gin.Context) (stri return resolveKBCreatorByKnowledgeID(c, h.kgService, knowledgeID) } +// KBCreatorLookupFromChunkIDParam resolves :id (a chunk ID) to the +// CreatorID of the *owning KB*. The chain is: +// +// chunk_id -> chunk.KnowledgeID -> kb_id -> KB.CreatorID +// +// Used by chunks.DELETE("/by-id/:id/questions") so generated-question +// deletion follows the same OwnedKBOrAdmin matrix as every other +// chunk-level mutation, instead of the looser "any Contributor in the +// tenant" gate. The tenant scope is re-checked explicitly here even +// though the underlying GetChunkByIDOnly is unscoped — same defence- +// in-depth pattern as KBCreatorLookup. +func (h *ChunkHandler) KBCreatorLookupFromChunkIDParam(c *gin.Context) (string, error) { + chunkID := c.Param("id") + if chunkID == "" { + return "", errors.New("missing :id param for chunk owner lookup") + } + ctx := c.Request.Context() + tenantID, ok := types.TenantIDFromContext(ctx) + if !ok { + return "", errors.New("tenant context missing") + } + chunk, err := h.service.GetChunkByIDOnly(ctx, chunkID) + if err != nil { + if errors.Is(err, service.ErrChunkNotFound) { + return "", middleware.ErrResourceNotFound + } + return "", err + } + if chunk == nil { + return "", middleware.ErrResourceNotFound + } + // 显式重校验租户:GetChunkByIDOnly 无租户过滤,必须在此挡住跨租户 chunk + // id 撞库通过 ownership 匹配获取本不该有的访问。 + if chunk.TenantID != tenantID { + return "", middleware.ErrResourceNotFound + } + return resolveKBCreatorByKnowledgeID(c, h.kgService, chunk.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 diff --git a/internal/handler/rbac_lookups_test.go b/internal/handler/rbac_lookups_test.go index 0f7de7ab..790987e1 100644 --- a/internal/handler/rbac_lookups_test.go +++ b/internal/handler/rbac_lookups_test.go @@ -366,3 +366,117 @@ func TestKBCreatorLookupFromKBPath_OwnerMatchReturnsCreatorID(t *testing.T) { t.Fatalf("expected creator=u-creator, got %q", creator) } } + +// stubChunkService stands in for interfaces.ChunkService for the +// chunk-id-driven lookup. Only GetChunkByIDOnly is stubbed; everything +// else panics on contact so a future refactor that broadens the +// surface gets caught loudly. +type stubChunkService struct { + interfaces.ChunkService + getByIDOnly func(ctx context.Context, id string) (*types.Chunk, error) +} + +func (s *stubChunkService) GetChunkByIDOnly(ctx context.Context, id string) (*types.Chunk, error) { + return s.getByIDOnly(ctx, id) +} + +// newChunkIDLookupCtx is the gin.Context shape for routes that address +// chunks by their own id, e.g. DELETE /chunks/by-id/:id/questions. +func newChunkIDLookupCtx(t *testing.T, tenantID uint64, chunkID 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: "id", Value: chunkID}} + return c +} + +func TestKBCreatorLookupFromChunkIDParam_HappyPath(t *testing.T) { + h := &ChunkHandler{ + service: &stubChunkService{ + getByIDOnly: func(_ context.Context, id string) (*types.Chunk, error) { + if id != "ch-1" { + t.Fatalf("expected chunk id=ch-1, got %q", id) + } + return &types.Chunk{ID: id, TenantID: 1, KnowledgeID: "kn-1"}, nil + }, + }, + kgService: &stubKgService{ + getOwningKBCreatorID: func(_ context.Context, knowledgeID string) (string, error) { + if knowledgeID != "kn-1" { + t.Fatalf("expected knowledge id=kn-1, got %q", knowledgeID) + } + return "u-creator", nil + }, + }, + } + creator, err := h.KBCreatorLookupFromChunkIDParam(newChunkIDLookupCtx(t, 1, "ch-1")) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if creator != "u-creator" { + t.Fatalf("expected creator=u-creator, got %q", creator) + } +} + +func TestKBCreatorLookupFromChunkIDParam_ChunkNotFoundMapsToSentinel(t *testing.T) { + h := &ChunkHandler{ + service: &stubChunkService{ + getByIDOnly: func(_ context.Context, _ string) (*types.Chunk, error) { + return nil, service.ErrChunkNotFound + }, + }, + } + _, err := h.KBCreatorLookupFromChunkIDParam(newChunkIDLookupCtx(t, 1, "ch-1")) + if !errors.Is(err, middleware.ErrResourceNotFound) { + t.Fatalf("expected ErrResourceNotFound, got %v", err) + } +} + +func TestKBCreatorLookupFromChunkIDParam_CrossTenantIsHiddenAsNotFound(t *testing.T) { + // GetChunkByIDOnly is unscoped — a chunk from another tenant whose + // owning-KB-creator happens to match the caller's user id must NOT + // slip past the ownership shortcut. The lookup re-checks TenantID + // before walking up to the KB. + h := &ChunkHandler{ + service: &stubChunkService{ + getByIDOnly: func(_ context.Context, _ string) (*types.Chunk, error) { + return &types.Chunk{ID: "ch-1", TenantID: 999, KnowledgeID: "kn-1"}, nil + }, + }, + kgService: &stubKgService{ + getOwningKBCreatorID: func(_ context.Context, _ string) (string, error) { + t.Fatalf("kb chain must not be consulted on cross-tenant chunk") + return "", nil + }, + }, + } + _, err := h.KBCreatorLookupFromChunkIDParam(newChunkIDLookupCtx(t, 1, "ch-1")) + if !errors.Is(err, middleware.ErrResourceNotFound) { + t.Fatalf("cross-tenant chunk must surface as not-found, got %v", err) + } +} + +func TestKBCreatorLookupFromChunkIDParam_KBNotFoundFromChainMapsToSentinel(t *testing.T) { + // The chunk exists and is in-tenant, but the chain (knowledge_id -> + // kb) errors with KnowledgeBaseNotFound — that must become the + // middleware sentinel, same as every other lookup. + h := &ChunkHandler{ + service: &stubChunkService{ + getByIDOnly: func(_ context.Context, _ string) (*types.Chunk, error) { + return &types.Chunk{ID: "ch-1", TenantID: 1, KnowledgeID: "kn-1"}, nil + }, + }, + kgService: &stubKgService{ + getOwningKBCreatorID: func(_ context.Context, _ string) (string, error) { + return "", apprepo.ErrKnowledgeBaseNotFound + }, + }, + } + _, err := h.KBCreatorLookupFromChunkIDParam(newChunkIDLookupCtx(t, 1, "ch-1")) + if !errors.Is(err, middleware.ErrResourceNotFound) { + t.Fatalf("expected ErrResourceNotFound, got %v", err) + } +} diff --git a/internal/router/rbac.go b/internal/router/rbac.go index b8fc7344..1c219f06 100644 --- a/internal/router/rbac.go +++ b/internal/router/rbac.go @@ -121,9 +121,10 @@ type rbacGuards struct { // 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 + knowledgeKBCreator middleware.CreatorLookup + chunkKBCreator middleware.CreatorLookup + chunkKBCreatorFromID middleware.CreatorLookup // chunk routes that address chunks by :id (no knowledge id in URL) + wikiKBCreator middleware.CreatorLookup } // newRBACGuards wires the guards from the live configuration and the @@ -149,6 +150,7 @@ func newRBACGuards( } if chunkHandler != nil { g.chunkKBCreator = chunkHandler.KBCreatorLookupFromKnowledgeIDParam + g.chunkKBCreatorFromID = chunkHandler.KBCreatorLookupFromChunkIDParam } if wikiHandler != nil { g.wikiKBCreator = wikiHandler.KBCreatorLookupFromKBPath @@ -213,13 +215,24 @@ func (g *rbacGuards) OwnedKnowledgeKBOrAdmin() gin.HandlerFunc { // 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. +// their documents. For chunk routes addressed via :id (no knowledge +// id in the URL — only chunks.DELETE("/by-id/:id/questions") today), +// see OwnedChunkKBOrAdminFromChunkID below: same matrix, walks one +// extra hop (chunk_id -> knowledge_id) before reusing this chain. func (g *rbacGuards) OwnedChunkKBOrAdmin() gin.HandlerFunc { return middleware.RequireOwnershipOrRole(types.TenantRoleAdmin, g.chunkKBCreator, g.cfg) } +// OwnedChunkKBOrAdminFromChunkID: chunk mutations addressed via :id +// (the chunk's own id, no knowledge id in the URL). Used by +// chunks.DELETE("/by-id/:id/questions"). Same OwnedKBOrAdmin matrix +// as the rest of the chunk routes — earlier this endpoint stayed at +// flat Contributor because the chunk-id -> knowledge-id -> kb chain +// wasn't wired; that's now plumbed through KBCreatorLookupFromChunkIDParam. +func (g *rbacGuards) OwnedChunkKBOrAdminFromChunkID() gin.HandlerFunc { + return middleware.RequireOwnershipOrRole(types.TenantRoleAdmin, g.chunkKBCreatorFromID, 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. diff --git a/internal/router/router.go b/internal/router/router.go index 0423178d..9bb143e9 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -222,14 +222,12 @@ func RegisterChunkRoutes(r *gin.RouterGroup, handler *handler.ChunkHandler, g *r 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) + // 删除单个生成的问题(通过分块 id) — 与其它 chunk mutation 一致: + // KB owner OR Admin+。早期这里因为链路 (chunk_id -> knowledge_id -> + // kb -> creator_id) 还没接通,被临时降级成 Contributor,导致一个 + // 「能编辑所有 chunk 的同样规则在这条路由上反而更宽松」的不一致。 + // 现在通过 KBCreatorLookupFromChunkIDParam 把那一跳补上,统一矩阵。 + chunks.DELETE("/by-id/:id/questions", g.OwnedChunkKBOrAdminFromChunkID(), handler.DeleteGeneratedQuestion) } }