fix(rbac): wire chunk-id ownership chain for generated-question delete

DELETE /chunks/by-id/:id/questions used to be gated at flat
Contributor+ as a deliberate carve-out: the URL only carries the
chunk's own id, so the chunk -> knowledge -> KB ownership chain
wasn't reachable from request params alone. The carve-out had two
problems:

  - Inconsistent with every other chunk mutation. PUT
    /chunks/:knowledge_id/:id is OwnedKBOrAdmin (KB creator OR
    Admin+); a Contributor with no KB ownership can't update a
    chunk but COULD delete a generated question on the same chunk.
  - User-visible: a Contributor in tenant A who never created any
    KB still saw the 'delete question' button work, while every
    other chunk control 403'd.

Wire the missing hop:

  KBCreatorLookupFromChunkIDParam (handler) reads :id, fetches the
  chunk via the existing GetChunkByIDOnly (unscoped repo call),
  re-checks chunk.TenantID against the caller's tenant context to
  block cross-tenant chunk-id probing, then defers to the existing
  resolveKBCreatorByKnowledgeID helper for the rest of the chain.

  OwnedChunkKBOrAdminFromChunkID (router) wraps it in
  RequireOwnershipOrRole(Admin, ...) — same matrix as every other
  chunk/knowledge/wiki mutation guard.

  chunks.DELETE switches from g.Contributor() to the new guard.

4 unit tests cover happy path, chunk-not-found, cross-tenant
chunk-id probing, and KB-not-found upstream — same edge-case shape
as the existing KBCreatorLookup_* tests so future refactors get
caught loudly.
This commit is contained in:
wizardchen
2026-05-15 12:15:56 +08:00
committed by lyingbug
parent f7a264ca93
commit 619e14a2eb
4 changed files with 182 additions and 18 deletions
+43 -4
View File
@@ -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
+114
View File
@@ -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)
}
}