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
+6 -8
View File
@@ -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)
}
}