fix(security): enforce KB access on wiki reads and related IDOR paths
Gate wiki GET routes and initialization config reads with KBAccessRead, and bind async task progress endpoints to the caller tenant via task ID parsing. Closes cross-tenant read paths reported in GHSA-ph8f-4qwx-89rr and related initialization/progress leaks.
This commit is contained in:
@@ -462,6 +462,10 @@ func (h *FAQHandler) GetEntry(c *gin.Context) {
|
||||
func (h *FAQHandler) GetImportProgress(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
taskID := secutils.SanitizeForLog(c.Param("task_id"))
|
||||
if err := requireTaskProgressTenant(ctx, taskID); err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
progress, err := h.knowledgeService.GetFAQImportProgress(ctx, taskID)
|
||||
if err != nil {
|
||||
|
||||
@@ -2197,6 +2197,10 @@ func (h *KnowledgeHandler) GetKnowledgeMoveProgress(c *gin.Context) {
|
||||
c.Error(errors.NewBadRequestError("Task ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
if err := requireTaskProgressTenant(ctx, taskID); err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
progress, err := h.kgService.GetKnowledgeMoveProgress(ctx, taskID)
|
||||
if err != nil {
|
||||
|
||||
@@ -1107,6 +1107,10 @@ func (h *KnowledgeBaseHandler) GetKBCloneProgress(c *gin.Context) {
|
||||
c.Error(apperrors.NewBadRequestError("Task ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
if err := requireTaskProgressTenant(ctx, taskID); err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
progress, err := h.knowledgeService.GetKBCloneProgress(ctx, taskID)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
// requireTaskProgressTenant ensures async task progress endpoints only
|
||||
// return data for tasks created under the caller's tenant. Cross-tenant
|
||||
// probes are hidden as not-found to avoid confirming task existence.
|
||||
func requireTaskProgressTenant(ctx context.Context, taskID string) error {
|
||||
taskTenantID, err := utils.TaskTenantID(taskID)
|
||||
if err != nil {
|
||||
return apperrors.NewBadRequestError("invalid task ID")
|
||||
}
|
||||
callerTenantID, ok := types.TenantIDFromContext(ctx)
|
||||
if !ok || callerTenantID == 0 {
|
||||
return apperrors.NewUnauthorizedError("Unauthorized")
|
||||
}
|
||||
if taskTenantID != callerTenantID {
|
||||
return apperrors.NewNotFoundError("task not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
func TestRequireTaskProgressTenant_RejectsCrossTenant(t *testing.T) {
|
||||
taskID := utils.GenerateTaskID("faq_import", 999, "kb-victim")
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
|
||||
|
||||
err := requireTaskProgressTenant(ctx, taskID)
|
||||
if err == nil {
|
||||
t.Fatal("expected cross-tenant task to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireTaskProgressTenant_AllowsOwnTenant(t *testing.T) {
|
||||
taskID := utils.GenerateTaskID("kb_clone", 1, "kb-source")
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
|
||||
|
||||
if err := requireTaskProgressTenant(ctx, taskID); err != nil {
|
||||
t.Fatalf("expected own-tenant task to pass, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireTaskProgressTenant_InvalidTaskID(t *testing.T) {
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
|
||||
err := requireTaskProgressTenant(ctx, "not-a-task")
|
||||
if err == nil {
|
||||
t.Fatal("expected invalid task ID to fail")
|
||||
}
|
||||
if got := err.Error(); got == "" {
|
||||
t.Fatal("expected error message")
|
||||
}
|
||||
_ = http.StatusBadRequest
|
||||
}
|
||||
+18
-17
@@ -720,7 +720,7 @@ func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
|
||||
func RegisterInitializationRoutes(r *gin.RouterGroup, handler *handler.InitializationHandler, g *rbacGuards) {
|
||||
// 初始化接口
|
||||
// GetCurrentConfigByKB 是只读,Viewer+ 即可。
|
||||
r.GET("/initialization/config/:kbId", g.Viewer(), handler.GetCurrentConfigByKB)
|
||||
r.GET("/initialization/config/:kbId", g.Viewer(), g.KBAccessRead("kbId"), handler.GetCurrentConfigByKB)
|
||||
// InitializeByKB / UpdateKBConfig 都是改 KB 的核心模型/storage 配置 —
|
||||
// 跟 PUT /knowledge-bases/:id 同等敏感,挂同款 OwnedKB 矩阵。
|
||||
r.POST("/initialization/initialize/:kbId", g.OwnedKBOrAdminFromKbIDParam(), handler.InitializeByKB)
|
||||
@@ -1770,45 +1770,46 @@ func RegisterWeKnoraCloudRoutes(r *gin.RouterGroup, handler *handler.WeKnoraClou
|
||||
|
||||
// RegisterWikiPageRoutes registers wiki page related routes.
|
||||
//
|
||||
// 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) 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.
|
||||
// Wiki pages are KB content (wiki mode): reads are Viewer+ and gated by
|
||||
// KBAccessRead (own / org-shared / via shared agent), matching FAQ /
|
||||
// chunk / tag read routes. Content mutations (create/update/delete) and
|
||||
// maintenance actions (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.GET("/pages", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListPages)
|
||||
wiki.POST("/pages", g.OwnedWikiKBOrAdmin(), wikiHandler.CreatePage)
|
||||
wiki.PUT("/move-page", g.OwnedWikiKBOrAdmin(), wikiHandler.MovePage)
|
||||
wiki.GET("/pages/*slug", g.Viewer(), wikiHandler.GetPage)
|
||||
wiki.GET("/pages/*slug", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetPage)
|
||||
wiki.PUT("/pages/*slug", g.OwnedWikiKBOrAdmin(), wikiHandler.UpdatePage)
|
||||
wiki.DELETE("/pages/*slug", g.OwnedWikiKBOrAdmin(), wikiHandler.DeletePage)
|
||||
|
||||
// Folder tree (directory nodes)
|
||||
wiki.GET("/folders", g.Viewer(), wikiHandler.ListFolders)
|
||||
wiki.GET("/folders", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListFolders)
|
||||
wiki.POST("/folders", g.OwnedWikiKBOrAdmin(), wikiHandler.CreateFolder)
|
||||
wiki.PUT("/folders/:folder_id", g.OwnedWikiKBOrAdmin(), wikiHandler.UpdateFolder)
|
||||
wiki.DELETE("/folders/:folder_id", g.OwnedWikiKBOrAdmin(), wikiHandler.DeleteFolder)
|
||||
|
||||
// Special pages
|
||||
wiki.GET("/index", g.Viewer(), wikiHandler.GetIndex)
|
||||
wiki.GET("/log", g.Viewer(), wikiHandler.GetLog)
|
||||
wiki.GET("/index", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetIndex)
|
||||
wiki.GET("/log", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetLog)
|
||||
|
||||
// Graph and stats
|
||||
wiki.GET("/graph", g.Viewer(), wikiHandler.GetGraph)
|
||||
wiki.GET("/stats", g.Viewer(), wikiHandler.GetStats)
|
||||
wiki.GET("/graph", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetGraph)
|
||||
wiki.GET("/stats", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetStats)
|
||||
|
||||
// Search and maintenance
|
||||
wiki.GET("/search", g.Viewer(), wikiHandler.SearchPages)
|
||||
wiki.GET("/search", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.SearchPages)
|
||||
wiki.POST("/rebuild-links", g.OwnedWikiKBOrAdmin(), wikiHandler.RebuildLinks)
|
||||
wiki.GET("/lint", g.Viewer(), wikiHandler.Lint)
|
||||
wiki.GET("/lint", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.Lint)
|
||||
wiki.POST("/auto-fix", g.OwnedWikiKBOrAdmin(), wikiHandler.AutoFix)
|
||||
|
||||
// Issues
|
||||
wiki.GET("/issues", g.Viewer(), wikiHandler.ListIssues)
|
||||
wiki.GET("/issues", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListIssues)
|
||||
wiki.PUT("/issues/:issue_id/status", g.OwnedWikiKBOrAdmin(), wikiHandler.UpdateIssueStatus)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
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/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type stubWikiKBLookup struct {
|
||||
kbs map[string]*types.KnowledgeBase
|
||||
}
|
||||
|
||||
func (s *stubWikiKBLookup) GetKnowledgeBaseByID(_ context.Context, id string) (*types.KnowledgeBase, error) {
|
||||
if kb, ok := s.kbs[id]; ok {
|
||||
return kb, nil
|
||||
}
|
||||
return nil, apprepo.ErrKnowledgeBaseNotFound
|
||||
}
|
||||
|
||||
func newWikiRouteTestEngine(t *testing.T, callerTenantID uint64, kbLookup *stubWikiKBLookup) *gin.Engine {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
enabled := true
|
||||
cfg := &config.Config{
|
||||
Tenant: &config.TenantConfig{EnableRBAC: &enabled},
|
||||
}
|
||||
guards := &rbacGuards{
|
||||
cfg: cfg,
|
||||
kbService: kbLookup,
|
||||
}
|
||||
|
||||
r := gin.New()
|
||||
r.Use(middleware.ErrorHandler())
|
||||
r.Use(func(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, callerTenantID)
|
||||
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Set(types.TenantIDContextKey.String(), callerTenantID)
|
||||
c.Next()
|
||||
})
|
||||
|
||||
RegisterWikiPageRoutes(r.Group("/api/v1"), &handler.WikiPageHandler{}, guards)
|
||||
return r
|
||||
}
|
||||
|
||||
func newInitializationRouteTestEngine(t *testing.T, callerTenantID uint64, kbLookup *stubWikiKBLookup) *gin.Engine {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
enabled := true
|
||||
cfg := &config.Config{
|
||||
Tenant: &config.TenantConfig{EnableRBAC: &enabled},
|
||||
}
|
||||
guards := &rbacGuards{
|
||||
cfg: cfg,
|
||||
kbService: kbLookup,
|
||||
}
|
||||
|
||||
r := gin.New()
|
||||
r.Use(middleware.ErrorHandler())
|
||||
r.Use(func(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, callerTenantID)
|
||||
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Set(types.TenantIDContextKey.String(), callerTenantID)
|
||||
c.Next()
|
||||
})
|
||||
|
||||
RegisterInitializationRoutes(r.Group("/api/v1"), &handler.InitializationHandler{}, guards)
|
||||
return r
|
||||
}
|
||||
|
||||
func TestInitializationConfigRouteDenyCrossTenantKB(t *testing.T) {
|
||||
kbLookup := &stubWikiKBLookup{
|
||||
kbs: map[string]*types.KnowledgeBase{
|
||||
"kb-victim": {ID: "kb-victim", TenantID: 999},
|
||||
},
|
||||
}
|
||||
engine := newInitializationRouteTestEngine(t, 1, kbLookup)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/initialization/config/kb-victim", nil)
|
||||
engine.ServeHTTP(rec, req)
|
||||
require.Equal(t, http.StatusForbidden, rec.Code, "body=%s", rec.Body.String())
|
||||
}
|
||||
|
||||
func TestWikiReadRoutesDenyCrossTenantKB(t *testing.T) {
|
||||
kbLookup := &stubWikiKBLookup{
|
||||
kbs: map[string]*types.KnowledgeBase{
|
||||
"kb-victim": {
|
||||
ID: "kb-victim",
|
||||
TenantID: 999,
|
||||
Type: types.KnowledgeBaseTypeWiki,
|
||||
},
|
||||
},
|
||||
}
|
||||
engine := newWikiRouteTestEngine(t, 1, kbLookup)
|
||||
|
||||
paths := []string{
|
||||
"/api/v1/knowledgebase/kb-victim/wiki/pages",
|
||||
"/api/v1/knowledgebase/kb-victim/wiki/pages/secret-page",
|
||||
"/api/v1/knowledgebase/kb-victim/wiki/folders",
|
||||
"/api/v1/knowledgebase/kb-victim/wiki/index",
|
||||
"/api/v1/knowledgebase/kb-victim/wiki/log",
|
||||
"/api/v1/knowledgebase/kb-victim/wiki/graph",
|
||||
"/api/v1/knowledgebase/kb-victim/wiki/stats",
|
||||
"/api/v1/knowledgebase/kb-victim/wiki/search?q=test",
|
||||
"/api/v1/knowledgebase/kb-victim/wiki/lint",
|
||||
"/api/v1/knowledgebase/kb-victim/wiki/issues",
|
||||
}
|
||||
|
||||
for _, path := range paths {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
engine.ServeHTTP(rec, req)
|
||||
require.Equal(t, http.StatusForbidden, rec.Code, "body=%s", rec.Body.String())
|
||||
})
|
||||
}
|
||||
}
|
||||
+33
-18
@@ -63,36 +63,51 @@ func GenerateTaskIDWithPrefix(prefix string, tenantID uint64, businessID ...stri
|
||||
|
||||
// ParseTaskID parses a task ID generated by GenerateTaskID and returns its components.
|
||||
// Returns taskType, tenantID, timestamp, uuid, businessID, and error.
|
||||
//
|
||||
// Task types may contain underscores (e.g. "faq_import", "kb_clone"), so the
|
||||
// parser locates the tenant/timestamp pair rather than assuming parts[0] is
|
||||
// the full task type.
|
||||
func ParseTaskID(taskID string) (taskType string, tenantID uint64, timestamp int64, uuidPart string, businessID string, err error) {
|
||||
parts := strings.Split(taskID, "_")
|
||||
if len(parts) < 4 {
|
||||
err = fmt.Errorf("invalid task ID format: %s", taskID)
|
||||
return
|
||||
}
|
||||
|
||||
taskType = parts[0]
|
||||
|
||||
tenantID, err = strconv.ParseUint(parts[1], 10, 64)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("invalid tenant ID in task ID: %s", parts[1])
|
||||
|
||||
tenantIdx := -1
|
||||
for i := 1; i < len(parts)-2; i++ {
|
||||
candidateTenant, parseErr := strconv.ParseUint(parts[i], 10, 64)
|
||||
if parseErr != nil || candidateTenant == 0 {
|
||||
continue
|
||||
}
|
||||
candidateTS, parseErr := strconv.ParseInt(parts[i+1], 10, 64)
|
||||
if parseErr != nil || candidateTS < 1_000_000_000_000 {
|
||||
continue
|
||||
}
|
||||
tenantID = candidateTenant
|
||||
timestamp = candidateTS
|
||||
tenantIdx = i
|
||||
break
|
||||
}
|
||||
if tenantIdx < 0 {
|
||||
err = fmt.Errorf("invalid task ID format: %s", taskID)
|
||||
return
|
||||
}
|
||||
|
||||
timestamp, err = strconv.ParseInt(parts[2], 10, 64)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("invalid timestamp in task ID: %s", parts[2])
|
||||
return
|
||||
|
||||
taskType = strings.Join(parts[:tenantIdx], "_")
|
||||
uuidPart = parts[tenantIdx+2]
|
||||
if len(parts) > tenantIdx+3 {
|
||||
businessID = strings.Join(parts[tenantIdx+3:], "_")
|
||||
}
|
||||
|
||||
uuidPart = parts[3]
|
||||
|
||||
if len(parts) > 4 {
|
||||
businessID = parts[4]
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// TaskTenantID extracts the tenant ID embedded in a GenerateTaskID task ID.
|
||||
func TaskTenantID(taskID string) (uint64, error) {
|
||||
_, tenantID, _, _, _, err := ParseTaskID(taskID)
|
||||
return tenantID, err
|
||||
}
|
||||
|
||||
// sanitizeTaskType ensures task type is safe for use in task ID
|
||||
func sanitizeTaskType(taskType string) string {
|
||||
// Replace colons and other special characters with underscores
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package utils
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParseTaskID_CompoundTaskType(t *testing.T) {
|
||||
taskID := GenerateTaskID("faq_import", 42, "kb-abc-123")
|
||||
taskType, tenantID, _, uuidPart, businessID, err := ParseTaskID(taskID)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseTaskID failed: %v", err)
|
||||
}
|
||||
if taskType != "faq_import" {
|
||||
t.Fatalf("taskType = %q, want faq_import", taskType)
|
||||
}
|
||||
if tenantID != 42 {
|
||||
t.Fatalf("tenantID = %d, want 42", tenantID)
|
||||
}
|
||||
if uuidPart == "" {
|
||||
t.Fatal("expected uuid part")
|
||||
}
|
||||
if businessID == "" {
|
||||
t.Fatal("expected business ID")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskTenantID(t *testing.T) {
|
||||
taskID := GenerateTaskID("kb_clone", 7, "source-kb")
|
||||
got, err := TaskTenantID(taskID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskTenantID failed: %v", err)
|
||||
}
|
||||
if got != 7 {
|
||||
t.Fatalf("TaskTenantID = %d, want 7", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user