Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

refa: centralize agent canvas permissions (#20709)

buua436da1915f060ad
diff --git a/internal/agent/component/retrieval_permission_test.go b/internal/agent/component/retrieval_permission_test.go
new file mode 100644
index 0000000000..ce4dbe4cc2
--- /dev/null
+++ b/internal/agent/component/retrieval_permission_test.go
@@ -0,0 +1,68 @@
+package component
+
+import (
+ "errors"
+ "net/url"
+ "testing"
+
+ "ragflow/internal/agent/runtime"
+ "ragflow/internal/entity"
+ "ragflow/internal/permission"
+
+ "github.com/glebarez/sqlite"
+ "gorm.io/gorm"
+)
+
+func TestCheckCanvasRetrievalDependencies(t *testing.T) {
+ db, err := gorm.Open(sqlite.Open("file:"+url.QueryEscape(t.Name())+"?mode=memory&cache=shared"), &gorm.Config{})
+ if err != nil {
+ t.Fatalf("open sqlite: %v", err)
+ }
+ if err := db.AutoMigrate(&entity.UserCanvas{}, &entity.Knowledgebase{}, &entity.UserTenant{}); err != nil {
+ t.Fatalf("migrate permission tables: %v", err)
+ }
+
+ valid := string(entity.StatusValid)
+ canvas := entity.UserCanvas{ID: "canvas-1", UserID: "canvas-owner", Permission: string(entity.TenantPermissionTeam)}
+ dataset := entity.Knowledgebase{
+ ID: "dataset-1", TenantID: "canvas-owner", CreatedBy: "canvas-owner",
+ Permission: string(entity.TenantPermissionTeam), Status: &valid,
+ }
+ privateDataset := entity.Knowledgebase{
+ ID: "private-dataset", TenantID: "other-owner", CreatedBy: "other-owner",
+ Permission: string(entity.TenantPermissionMe), Status: &valid,
+ }
+ for _, row := range []any{&canvas, &dataset, &privateDataset} {
+ if err := db.Create(row).Error; err != nil {
+ t.Fatalf("create permission resource: %v", err)
+ }
+ }
+ memberships := []entity.UserTenant{
+ {ID: "canvas-owner-membership", UserID: "canvas-owner", TenantID: "canvas-owner", Role: string(permission.RoleOwner), Status: &valid},
+ {ID: "caller-membership", UserID: "caller", TenantID: "canvas-owner", Role: string(permission.RoleNormal), Status: &valid},
+ {ID: "dataset-owner-membership", UserID: "other-owner", TenantID: "other-owner", Role: string(permission.RoleOwner), Status: &valid},
+ }
+ for i := range memberships {
+ if err := db.Create(&memberships[i]).Error; err != nil {
+ t.Fatalf("create membership: %v", err)
+ }
+ }
+
+ state := runtime.NewCanvasState("run-1", "session-1")
+ state.Sys["canvas_id"] = canvas.ID
+ state.Sys["user_id"] = "caller"
+ ctx := runtime.WithState(t.Context(), state)
+
+ if err := checkCanvasRetrievalDependencies(ctx, db, map[string]any{"dataset_ids": []string{dataset.ID}}); err != nil {
+ t.Fatalf("check accessible dataset dependency: %v", err)
+ }
+ if err := checkCanvasRetrievalDependencies(ctx, db, map[string]any{"dataset_ids": []string{privateDataset.ID}}); !errors.Is(err, permission.ErrPermissionDenied) {
+ t.Fatalf("check private dataset dependency error = %v, want permission denied", err)
+ }
+
+ missingCanvasState := runtime.NewCanvasState("run-2", "session-2")
+ missingCanvasState.Sys["user_id"] = "caller"
+ if err := checkCanvasRetrievalDependencies(runtime.WithState(t.Context(), missingCanvasState), db, nil); !errors.Is(err, permission.ErrInvalidPermission) {
+ t.Fatalf("check missing canvas identity error = %v, want invalid permission", err)
+ }
+}
diff --git a/internal/agent/component/universe_a_wrappers.go b/internal/agent/component/universe_a_wrappers.go
index c003af882a..2af220bbe7 100644
--- a/internal/agent/component/universe_a_wrappers.go
+++ b/internal/agent/component/universe_a_wrappers.go
@@ -203,6 +203,9 @@ func (c *retrievalComponent) Outputs() map[string]string {
func (c *retrievalComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[string]any) (map[string]any, error) {
merged := c.applyDefaults(inputs)
normalizeLegacyRetrievalInputs(ctx, db, merged)
+ if err := checkCanvasRetrievalDependencies(ctx, db, merged); err != nil {
+ return nil, fmt.Errorf("agent Retrieval dependency permission: %w", err)
+ }
query, _ := merged["query"].(string)
if state, err := runtime.GetStateFromContext(ctx); err == nil && state != nil {
if resolved, err := runtime.ResolveTemplateAuto(query, state); err == nil {
@@ -242,6 +245,38 @@ func (c *retrievalComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map
}
+func checkCanvasRetrievalDependencies(ctx context.Context, db *gorm.DB, inputs map[string]any) error {
+ state, err := runtime.GetStateFromContext(ctx)
+ if err != nil || state == nil {
+ return nil
+ }
+ canvasID, _ := state.Sys["canvas_id"].(string)
+ userID, _ := state.Sys["user_id"].(string)
+ if canvasID == "" && userID == "" {
+ return nil
+ }
+ if canvasID == "" {
+ return fmt.Errorf("%w: canvas id missing from runtime state", permission.ErrInvalidPermission)
+ }
+ if userID == "" {
+ return permission.ErrUnauthenticated
+ }
+
+ checker := permission.NewDatabaseChecker(db)
+ entry := permission.ResourceRef{Kind: permission.ResourceKindCanvas, ID: canvasID}
+ for _, datasetID := range toStringSlice(inputs["dataset_ids"]) {
+ datasetID = strings.TrimSpace(datasetID)
+ if datasetID == "" {
+ continue
+ }
+ dependency := permission.ResourceRef{Kind: permission.ResourceKindDataset, ID: datasetID}
+ if err := checker.CheckDependency(ctx, permission.Subject{UserID: userID}, entry, dependency, permission.OperationRun, permission.OperationUse); err != nil {
+ return fmt.Errorf("dataset %q: %w", datasetID, err)
+ }
+ }
+ return nil
+}
+
func (c *retrievalComponent) Stream(_ context.Context, _ *gorm.DB, _ map[string]any) (<-chan map[string]any, error) {
// V1: retrieval is a non-streaming node (the Python
// Retrieval component also blocks on Dealer.search). A
diff --git a/internal/dao/user_canvas.go b/internal/dao/user_canvas.go
index 209b56b38d..6c0ec44f10 100644
--- a/internal/dao/user_canvas.go
+++ b/internal/dao/user_canvas.go
@@ -27,11 +27,6 @@ import (
"ragflow/internal/entity"
)
-// ErrUserCanvasNotFound is returned by GetByIDForUser when the canvas is
-// missing or the caller has no read access. We deliberately do not
-// distinguish "missing" from "forbidden" so the response cannot be used
-// to enumerate other users' canvas ids — see plan §4.8 (IDOR mitigation).
-
func splitUserCanvasTags(raw string) []string {
parts := strings.Split(raw, ",")
tags := make([]string, 0, len(parts))
@@ -98,96 +93,11 @@ func (dao *UserCanvasDAO) GetByID(ctx context.Context, db *gorm.DB, id string) (
return &canvas, nil
}
-// GetByIDForUser fetches a canvas and enforces ownership visibility:
-//
-// - canvases with permission="me" or owned by the requesting user are
-// always returned;
-// - canvases with permission="team" are returned when the canvas owner
-// is a tenant the requesting user belongs to (the team membership
-// predicate mirrors user_canvas.ListByTenantIDs).
-//
-// Any other case — missing row, foreign private canvas, foreign team
-// canvas — yields ErrUserCanvasNotFound. The single error type stops
-// callers from leaking "exists but not yours" vs "doesn't exist" via the
-// HTTP status code.
-func (dao *UserCanvasDAO) GetByIDForUser(ctx context.Context, db *gorm.DB, canvasID, userID string, tenantIDs []string) (*entity.UserCanvas, error) {
- if canvasID == "" {
- return nil, ErrUserCanvasNotFound
- }
- if userID == "" {
- return nil, ErrUserCanvasNotFound
- }
-
- // owner=userID is allowed regardless of permission, matching the
- // ListByTenantIDs predicate used by GET /api/v1/agents.
- ownerOrTeam := db.WithContext(ctx).Where("user_id = ?", userID)
- if len(tenantIDs) > 0 {
- ownerOrTeam = ownerOrTeam.Or(
- "user_id IN ? AND permission = ?", tenantIDs, "team",
- )
- }
-
- var canvas entity.UserCanvas
- err := db.WithContext(ctx).Where("id = ?", canvasID).Where(ownerOrTeam).First(&canvas).Error
- if err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, ErrUserCanvasNotFound
- }
- return nil, err
- }
- return &canvas, nil
-}
-
// Update update user canvas
func (dao *UserCanvasDAO) Update(ctx context.Context, db *gorm.DB, userCanvas *entity.UserCanvas) error {
return db.WithContext(ctx).Save(userCanvas).Error
}
-// Accessible reports whether canvasID is reachable by userID under
-// the same owner-or-team rule used by GetByIDForUser. Used by
-// downstream authorization gates (e.g. the sandbox-artifact
-// download endpoint introduced by PR #16169) to confirm a caller
-// may reach a given canvas before exposing its runtime artifacts.
-// Returns false on any error (not found, DB failure, or empty
-// inputs) so callers can treat a denial as a 404-equivalent and
-// avoid leaking whether the canvas exists at all.
-//
-// Tenant scoping (PR review round 5, security review #1): unlike
-// the previous form, a `permission = "team"` canvas is only
-// reachable when userID is a member of one of the owner's tenants.
-// Passing a nil/empty tenantIDs list effectively disables the
-// team-canvas branch (no team canvas can match), which is the
-// safe default — a caller that forgot to plumb the tenant list
-// cannot accidentally bypass team-membership scoping.
-//
-// Callers that don't have a tenant list handy (rare; most
-// handlers derive it from the user context) should call
-// GetTenantIDsByUserID first and pass the result.
-func (dao *UserCanvasDAO) Accessible(ctx context.Context, db *gorm.DB, canvasID, userID string, tenantIDs []string) bool {
- if canvasID == "" || userID == "" {
- return false
- }
- // Owner can always access their own canvas regardless of permission.
- // Team-permission canvases are reachable only when the caller is a
- // member of one of the owner's tenants — mirrors the predicate in
- // GetByIDForUser / ListByTenantIDs.
- ownerOrTeam := db.WithContext(ctx).Where("user_id = ?", userID)
- if len(tenantIDs) > 0 {
- ownerOrTeam = ownerOrTeam.Or(
- "user_id IN ? AND permission = ?", tenantIDs, "team",
- )
- }
- var canvas entity.UserCanvas
- err := db.WithContext(ctx).Select("id").
- Where("id = ?", canvasID).
- Where(ownerOrTeam).
- First(&canvas).Error
- if err != nil {
- return false
- }
- return canvas.ID == canvasID
-}
-
// Delete delete user canvas
func (dao *UserCanvasDAO) Delete(ctx context.Context, db *gorm.DB, id string) error {
// gorm v2 treats the first non-int inline arg as a column name, not a
@@ -285,7 +195,7 @@ func (dao *UserCanvasDAO) GetAllCanvasesByTenantIDs(ctx context.Context, db *gor
return results, err
}
-// UserCanvasListItem is the joined row returned by ListByTenantIDs.
+// UserCanvasListItem is the joined row returned by ListByIDs.
type UserCanvasListItem struct {
ID string `gorm:"column:id"`
Avatar *string `gorm:"column:avatar"`
@@ -303,15 +213,12 @@ type UserCanvasListItem struct {
UpdateTime *int64 `gorm:"column:update_time"`
}
-// ListByTenantIDs lists agent canvases accessible to the given owner IDs with optional
-// keyword filter, tag filter, pagination, and ordering.
-// Mirrors Python UserCanvasService.get_by_tenant_ids (list route only).
-func (dao *UserCanvasDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, ownerIDs []string, userID string, page, pageSize int, terms []OrderTerm, keywords string, canvasCategories []string, canvasType string, tags []string) ([]*UserCanvasListItem, int64, error) {
- if len(ownerIDs) == 0 {
+// ListByIDs lists permission-filtered canvases with optional metadata filters.
+func (dao *UserCanvasDAO) ListByIDs(ctx context.Context, db *gorm.DB, canvasIDs, ownerIDs []string, page, pageSize int, terms []OrderTerm, keywords string, canvasCategories []string, canvasType string, tags []string) ([]*UserCanvasListItem, int64, error) {
+ if len(canvasIDs) == 0 {
return nil, 0, nil
}
- // Canvases owned by any of the ownerIDs that are "team"-permission, plus all owned by userID.
base := db.WithContext(ctx).Model(&entity.UserCanvas{}).
Select(`user_canvas.id,
user_canvas.avatar,
@@ -328,10 +235,10 @@ func (dao *UserCanvasDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, owne
user_canvas.create_time,
user_canvas.update_time`).
Joins("LEFT JOIN user ON user_canvas.user_id = user.id").
- Where("user_canvas.user_id IN ?", ownerIDs).
- Where(
- db.WithContext(ctx).Where("user_canvas.permission = ?", "team").
- Or("user_canvas.user_id = ?", userID))
+ Where("user_canvas.id IN ?", canvasIDs)
+ if len(ownerIDs) > 0 {
+ base = base.Where("user_canvas.user_id IN ?", ownerIDs)
+ }
if len(canvasCategories) > 0 {
base = base.Where("user_canvas.canvas_category IN ?", canvasCategories)
@@ -386,25 +293,14 @@ type CategoryFilterItem struct {
Count int64 `gorm:"column:count"`
}
-// visibleToUserScope scopes a user_canvas query to rows the user can see:
-// team-permission canvases owned by ownerIDs plus everything the user owns.
-func visibleToUserScope(db *gorm.DB, ownerIDs []string, userID string) *gorm.DB {
- return db.Model(&entity.UserCanvas{}).
- Where("user_canvas.user_id IN ?", ownerIDs).
- Where(
- db.Where("user_canvas.permission = ?", "team").
- Or("user_canvas.user_id = ?", userID))
-}
-
-// GetOwnerFilter aggregates visible canvases by owner, joining the user
-// table for the display label. Mirrors Python
-// UserCanvasService.get_owner_filter.
-func (dao *UserCanvasDAO) GetOwnerFilter(ctx context.Context, db *gorm.DB, ownerIDs []string, userID string) ([]*OwnerFilterItem, error) {
- if len(ownerIDs) == 0 {
+// GetOwnerFilterByCanvasIDs aggregates permission-filtered canvases by owner.
+func (dao *UserCanvasDAO) GetOwnerFilterByCanvasIDs(ctx context.Context, db *gorm.DB, canvasIDs []string) ([]*OwnerFilterItem, error) {
+ if len(canvasIDs) == 0 {
return nil, nil
}
var items []*OwnerFilterItem
- err := visibleToUserScope(db.WithContext(ctx), ownerIDs, userID).
+ err := db.WithContext(ctx).Model(&entity.UserCanvas{}).
+ Where("user_canvas.id IN ?", canvasIDs).
Select("user_canvas.user_id AS id, user.nickname AS label, COUNT(user_canvas.id) AS count").
Joins("LEFT JOIN user ON user_canvas.user_id = user.id").
Group("user_canvas.user_id, user.nickname").
@@ -412,32 +308,29 @@ func (dao *UserCanvasDAO) GetOwnerFilter(ctx context.Context, db *gorm.DB, owner
return items, err
}
-// GetCategoryFilter aggregates visible canvases by canvas_category.
-// Mirrors Python UserCanvasService.get_category_filter.
-func (dao *UserCanvasDAO) GetCategoryFilter(ctx context.Context, db *gorm.DB, ownerIDs []string, userID string) ([]*CategoryFilterItem, error) {
- if len(ownerIDs) == 0 {
+// GetCategoryFilterByCanvasIDs aggregates permission-filtered canvases by category.
+func (dao *UserCanvasDAO) GetCategoryFilterByCanvasIDs(ctx context.Context, db *gorm.DB, canvasIDs []string) ([]*CategoryFilterItem, error) {
+ if len(canvasIDs) == 0 {
return nil, nil
}
var items []*CategoryFilterItem
- err := visibleToUserScope(db.WithContext(ctx), ownerIDs, userID).
+ err := db.WithContext(ctx).Model(&entity.UserCanvas{}).
+ Where("user_canvas.id IN ?", canvasIDs).
Select("user_canvas.canvas_category AS id, COUNT(user_canvas.id) AS count").
Group("user_canvas.canvas_category").
Scan(&items).Error
return items, err
}
-// ListTags returns tag usage counts across canvases visible to userID.
-func (dao *UserCanvasDAO) ListTags(ctx context.Context, db *gorm.DB, ownerIDs []string, userID string, canvasCategory string) (map[string]int, error) {
- if len(ownerIDs) == 0 {
+// ListTagsByCanvasIDs returns tag usage counts across permission-filtered canvases.
+func (dao *UserCanvasDAO) ListTagsByCanvasIDs(ctx context.Context, db *gorm.DB, canvasIDs []string, canvasCategory string) (map[string]int, error) {
+ if len(canvasIDs) == 0 {
return map[string]int{}, nil
}
query := db.WithContext(ctx).Model(&entity.UserCanvas{}).
Select("user_canvas.tags").
- Where(
- db.WithContext(ctx).Where("user_canvas.user_id IN ? AND user_canvas.permission = ?", ownerIDs, "team").
- Or("user_canvas.user_id = ?", userID),
- )
+ Where("user_canvas.id IN ?", canvasIDs)
if canvasCategory != "" {
query = query.Where("user_canvas.canvas_category = ?", canvasCategory)
diff --git a/internal/dao/user_canvas_test.go b/internal/dao/user_canvas_test.go
index 2a15d81f06..0dd1b24381 100644
--- a/internal/dao/user_canvas_test.go
+++ b/internal/dao/user_canvas_test.go
@@ -167,7 +167,8 @@ func TestUserCanvasDAOListTagsIncludesPipelineWhenCategoryIsEmpty(t *testing.T)
}
}
- counts, err := dao.ListTags(ctx, db, []string{"user-1"}, "user-1", "")
+ canvasIDs := []string{"agent-canvas", "pipeline-canvas"}
+ counts, err := dao.ListTagsByCanvasIDs(ctx, db, canvasIDs, "")
if err != nil {
t.Fatalf("ListTags failed: %v", err)
}
@@ -181,7 +182,7 @@ func TestUserCanvasDAOListTagsIncludesPipelineWhenCategoryIsEmpty(t *testing.T)
t.Fatalf("shared count = %d, want 2", counts["shared"])
}
- counts, err = dao.ListTags(ctx, db, []string{"user-1"}, "user-1", "agent_canvas")
+ counts, err = dao.ListTagsByCanvasIDs(ctx, db, canvasIDs, "agent_canvas")
if err != nil {
t.Fatalf("ListTags with category failed: %v", err)
}
@@ -224,11 +225,10 @@ func TestUserCanvasDAOOwnerAndCategoryFilters(t *testing.T) {
}
}
- ownerIDs := []string{"user-1", "user-2"}
-
- owners, err := d.GetOwnerFilter(ctx, db, ownerIDs, "user-1")
+ visibleCanvasIDs := []string{"c1", "c2", "c3"}
+ owners, err := d.GetOwnerFilterByCanvasIDs(ctx, db, visibleCanvasIDs)
if err != nil {
- t.Fatalf("GetOwnerFilter failed: %v", err)
+ t.Fatalf("GetOwnerFilterByCanvasIDs failed: %v", err)
}
if len(owners) != 2 {
t.Fatalf("owner filter rows = %d, want 2", len(owners))
@@ -237,7 +237,7 @@ func TestUserCanvasDAOOwnerAndCategoryFilters(t *testing.T) {
for _, o := range owners {
byID[o.ID] = o
}
- // user-1 sees both of their own canvases; user-2 only the team one (c4 is "me").
+ // The caller passes only policy-authorized canvas IDs; c4 is excluded.
if byID["user-1"].Count != 2 {
t.Fatalf("user-1 count = %d, want 2", byID["user-1"].Count)
}
@@ -248,9 +248,9 @@ func TestUserCanvasDAOOwnerAndCategoryFilters(t *testing.T) {
t.Fatalf("user-1 label = %v, want Alice", byID["user-1"].Label)
}
- categories, err := d.GetCategoryFilter(ctx, db, ownerIDs, "user-1")
+ categories, err := d.GetCategoryFilterByCanvasIDs(ctx, db, visibleCanvasIDs)
if err != nil {
- t.Fatalf("GetCategoryFilter failed: %v", err)
+ t.Fatalf("GetCategoryFilterByCanvasIDs failed: %v", err)
}
catByID := make(map[string]int64, len(categories))
for _, c := range categories {
@@ -290,9 +290,9 @@ func TestUserCanvasDAOKeywordSearchIncludesTags(t *testing.T) {
}
}
- results, _, err := d.ListByTenantIDs(ctx, db, []string{"u1"}, "u1", 1, 10, []OrderTerm{{Column: "create_time"}}, "finance", nil, "", nil)
+ results, _, err := d.ListByIDs(ctx, db, []string{"c1", "c2"}, nil, 1, 10, []OrderTerm{{Column: "create_time"}}, "finance", nil, "", nil)
if err != nil {
- t.Fatalf("ListByTenantIDs: %v", err)
+ t.Fatalf("ListByIDs: %v", err)
}
if len(results) != 1 {
t.Fatalf("keyword search 'finance' returned %d rows, want 1 (matched by tag not title)", len(results))
@@ -302,9 +302,9 @@ func TestUserCanvasDAOKeywordSearchIncludesTags(t *testing.T) {
}
}
-// TestUserCanvasDAOListByTenantIDsCategoryUnion verifies that a multi-category
+// TestUserCanvasDAOListByIDsCategoryUnion verifies that a multi-category
// canvas_category filter matches the union of the selected categories.
-func TestUserCanvasDAOListByTenantIDsCategoryUnion(t *testing.T) {
+func TestUserCanvasDAOListByIDsCategoryUnion(t *testing.T) {
db := setupUserCanvasTestDB(t)
if err := db.AutoMigrate(&entity.User{}); err != nil {
t.Fatalf("failed to migrate user: %v", err)
@@ -327,17 +327,18 @@ func TestUserCanvasDAOListByTenantIDsCategoryUnion(t *testing.T) {
}
}
- rows, total, err := d.ListByTenantIDs(ctx, db, []string{"u1"}, "u1", 1, 10, []OrderTerm{{Column: "create_time"}}, "", []string{"dataflow_canvas", "agent_canvas"}, "", nil)
+ canvasIDs := []string{"c-wf-1", "c-wf-2", "c-df-1"}
+ rows, total, err := d.ListByIDs(ctx, db, canvasIDs, nil, 1, 10, []OrderTerm{{Column: "create_time"}}, "", []string{"dataflow_canvas", "agent_canvas"}, "", nil)
if err != nil {
- t.Fatalf("ListByTenantIDs: %v", err)
+ t.Fatalf("ListByIDs: %v", err)
}
if total != 3 || len(rows) != 3 {
t.Fatalf("category union returned total=%d rows=%d, want 3/3", total, len(rows))
}
- rows, total, err = d.ListByTenantIDs(ctx, db, []string{"u1"}, "u1", 1, 10, []OrderTerm{{Column: "create_time"}}, "", []string{"agent_canvas"}, "", nil)
+ rows, total, err = d.ListByIDs(ctx, db, canvasIDs, nil, 1, 10, []OrderTerm{{Column: "create_time"}}, "", []string{"agent_canvas"}, "", nil)
if err != nil {
- t.Fatalf("ListByTenantIDs (single category): %v", err)
+ t.Fatalf("ListByIDs (single category): %v", err)
}
if total != 2 || len(rows) != 2 {
t.Fatalf("single category returned total=%d rows=%d, want 2/2", total, len(rows))
@@ -369,9 +370,9 @@ func TestUserCanvasDAOOrderByTags(t *testing.T) {
}
}
- results, _, err := d.ListByTenantIDs(ctx, db, []string{"u1"}, "u1", 1, 10, []OrderTerm{{Column: "tags"}}, "", nil, "", nil)
+ results, _, err := d.ListByIDs(ctx, db, []string{"c-z", "c-a", "c-m"}, nil, 1, 10, []OrderTerm{{Column: "tags"}}, "", nil, "", nil)
if err != nil {
- t.Fatalf("ListByTenantIDs: %v", err)
+ t.Fatalf("ListByIDs: %v", err)
}
if len(results) != 3 {
t.Fatalf("returned %d rows, want 3", len(results))
diff --git a/internal/handler/agent_component.go b/internal/handler/agent_component.go
index 54ec0f56ed..8c9fb2dd67 100644
--- a/internal/handler/agent_component.go
+++ b/internal/handler/agent_component.go
@@ -215,6 +215,11 @@ func (h *AgentHandler) DebugComponent(c *gin.Context) {
debugState.Sys[strings.TrimPrefix(key, "sys.")] = value
}
}
+ // Permission checks in Retrieval use the authenticated caller and the
+ // canvas whose component is being debugged. Set these after copying inputs
+ // so request parameters cannot impersonate another user or canvas.
+ debugState.Sys["canvas_id"] = cv.ID
+ debugState.Sys["user_id"] = user.ID
invokeCtx := runtime.WithState(c.Request.Context(), debugState)
outputs, err := runtime.TrackElapsed(name, func() (map[string]any, error) {
diff --git a/internal/handler/agent_component_test.go b/internal/handler/agent_component_test.go
index 6c968ac077..fb841e47a4 100644
--- a/internal/handler/agent_component_test.go
+++ b/internal/handler/agent_component_test.go
@@ -338,6 +338,8 @@ func (s *sysEchoComponent) Invoke(ctx context.Context, _ *gorm.DB, _ map[string]
return map[string]any{
"query": state.Sys["query"],
"tenant_id": state.Sys["tenant_id"],
+ "canvas_id": state.Sys["canvas_id"],
+ "user_id": state.Sys["user_id"],
}, nil
}
@@ -366,7 +368,7 @@ func TestDebugComponent_SeedsSysInputsIntoCanvasState(t *testing.T) {
}
h := &AgentHandler{loader: &fakeCanvasLoader{canvas: cv}}
- body := `{"params":{"sys.query":{"value":"hello sys"}}}`
+ body := `{"params":{"sys.query":{"value":"hello sys"},"sys.user_id":{"value":"attacker"},"sys.canvas_id":{"value":"other-canvas"}}}`
c, w := componentCtx(t, "POST", "/api/v1/agents/c1/components/probe/debug", body)
c.Params = gin.Params{
{Key: "canvas_id", Value: "c1"},
@@ -387,6 +389,12 @@ func TestDebugComponent_SeedsSysInputsIntoCanvasState(t *testing.T) {
if env.Data["query"] != "hello sys" {
t.Fatalf("data.query = %v, want 'hello sys'", env.Data["query"])
}
+ if env.Data["user_id"] != "u-1" {
+ t.Errorf("data.user_id = %v, want authenticated caller u-1", env.Data["user_id"])
+ }
+ if env.Data["canvas_id"] != "c1" {
+ t.Errorf("data.canvas_id = %v, want loaded canvas c1", env.Data["canvas_id"])
+ }
}
func TestDebugComponent_RejectsSysTenantIDOverride(t *testing.T) {
diff --git a/internal/handler/bot.go b/internal/handler/bot.go
index 43fb552b44..8c4848c946 100644
--- a/internal/handler/bot.go
+++ b/internal/handler/bot.go
@@ -41,12 +41,12 @@ type BotHandler struct {
type botService interface {
ChatbotInfo(ctx context.Context, tenantID, dialogID string) (
title, avatar, prologue, llmID string, hasWebSearch bool, ec common.ErrorCode, err error)
- AgentbotInputs(ctx context.Context, tenantID, agentID string) (
+ AgentbotInputs(ctx context.Context, userID, agentID string) (
title, avatar, prologue, mode string, inputs map[string]any,
ec common.ErrorCode, err error)
- AgentbotCompletion(ctx context.Context, tenantID, agentID string, req service.AgentbotCompletionRequest) (
+ AgentbotCompletion(ctx context.Context, userID, agentID string, req service.AgentbotCompletionRequest) (
<-chan canvas.RunEvent, common.ErrorCode, error)
- AgentbotLogs(ctx context.Context, tenantID, agentID, messageID string) (map[string]any, common.ErrorCode, error)
+ AgentbotLogs(ctx context.Context, userID, agentID, messageID string) (map[string]any, common.ErrorCode, error)
ChatbotCompletion(ctx context.Context, tenantID, dialogID string, req service.ChatbotCompletionRequest) (
<-chan service.ChatbotSSEFrame, common.ErrorCode, error)
}
diff --git a/internal/handler/bot_test.go b/internal/handler/bot_test.go
index 5465b18e6f..4300214860 100644
--- a/internal/handler/bot_test.go
+++ b/internal/handler/bot_test.go
@@ -40,9 +40,9 @@ import (
// methods return safe defaults.
type stubBotService struct {
chatbotInfoFn func(ctx context.Context, tenantID, dialogID string) (string, string, string, string, bool, common.ErrorCode, error)
- agentbotInputsFn func(ctx context.Context, tenantID, agentID string) (string, string, string, string, map[string]any, common.ErrorCode, error)
- agentbotCompleteFn func(ctx context.Context, tenantID, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error)
- agentbotLogsFn func(ctx context.Context, tenantID, agentID, messageID string) (map[string]any, common.ErrorCode, error)
+ agentbotInputsFn func(ctx context.Context, userID, agentID string) (string, string, string, string, map[string]any, common.ErrorCode, error)
+ agentbotCompleteFn func(ctx context.Context, userID, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error)
+ agentbotLogsFn func(ctx context.Context, userID, agentID, messageID string) (map[string]any, common.ErrorCode, error)
chatbotCompleteFn func(ctx context.Context, tenantID, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error)
}
@@ -53,23 +53,23 @@ func (s *stubBotService) ChatbotInfo(ctx context.Context, tenantID, dialogID str
return "", "", "", "", false, common.CodeDataError, errors.New("not stubbed")
}
-func (s *stubBotService) AgentbotInputs(ctx context.Context, tenantID, agentID string) (string, string, string, string, map[string]any, common.ErrorCode, error) {
+func (s *stubBotService) AgentbotInputs(ctx context.Context, userID, agentID string) (string, string, string, string, map[string]any, common.ErrorCode, error) {
if s.agentbotInputsFn != nil {
- return s.agentbotInputsFn(ctx, tenantID, agentID)
+ return s.agentbotInputsFn(ctx, userID, agentID)
}
return "", "", "", "", nil, common.CodeDataError, errors.New("not stubbed")
}
-func (s *stubBotService) AgentbotCompletion(ctx context.Context, tenantID, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
+func (s *stubBotService) AgentbotCompletion(ctx context.Context, userID, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
if s.agentbotCompleteFn != nil {
- return s.agentbotCompleteFn(ctx, tenantID, agentID, req)
+ return s.agentbotCompleteFn(ctx, userID, agentID, req)
}
return nil, common.CodeDataError, errors.New("not stubbed")
}
-func (s *stubBotService) AgentbotLogs(ctx context.Context, tenantID, agentID, messageID string) (map[string]any, common.ErrorCode, error) {
+func (s *stubBotService) AgentbotLogs(ctx context.Context, userID, agentID, messageID string) (map[string]any, common.ErrorCode, error) {
if s.agentbotLogsFn != nil {
- return s.agentbotLogsFn(ctx, tenantID, agentID, messageID)
+ return s.agentbotLogsFn(ctx, userID, agentID, messageID)
}
return nil, common.CodeDataError, errors.New("not stubbed")
}
diff --git a/internal/permission/database_source.go b/internal/permission/database_source.go
index 153818f4cb..1ee1d63f54 100644
--- a/internal/permission/database_source.go
+++ b/internal/permission/database_source.go
@@ -19,6 +19,7 @@ import (
"context"
"errors"
"fmt"
+ "strings"
"ragflow/internal/entity"
@@ -32,7 +33,6 @@ type databaseSource struct {
}
// NewDatabaseChecker creates a Checker backed by the application's SQL database.
-// It currently loads dataset authorization facts.
func NewDatabaseChecker(db *gorm.DB) *Checker {
return NewChecker(&databaseSource{db: db})
}
@@ -73,21 +73,62 @@ func (s *databaseSource) GetResources(ctx context.Context, refs []ResourceRef) (
}
refs = uniqueRefs(refs)
datasetIDs := make([]string, 0, len(refs))
+ canvasIDs := make([]string, 0, len(refs))
+ agentSessionIDs := make([]string, 0, len(refs))
for _, ref := range refs {
- if ref.Kind != ResourceKindDataset {
+ switch ref.Kind {
+ case ResourceKindDataset:
+ datasetIDs = append(datasetIDs, ref.ID)
+ case ResourceKindCanvas:
+ canvasIDs = append(canvasIDs, ref.ID)
+ case ResourceKindAgentSession:
+ agentSessionIDs = append(agentSessionIDs, ref.ID)
+ default:
return nil, fmt.Errorf("%w: unsupported resource kind %q", ErrInvalidPermission, ref.Kind)
}
- datasetIDs = append(datasetIDs, ref.ID)
}
- datasetsByID, ownerIDsByTenant, err := s.loadDatasets(ctx, datasetIDs)
+ agentSessionsByID, err := s.loadAgentSessions(ctx, agentSessionIDs)
+ if err != nil {
+ return nil, err
+ }
+ for _, session := range agentSessionsByID {
+ canvasIDs = append(canvasIDs, session.DialogID)
+ }
+ var datasetsByID map[string]*entity.Knowledgebase
+ var ownerIDsByTenant map[string]string
+ if len(datasetIDs) > 0 {
+ var err error
+ datasetsByID, ownerIDsByTenant, err = s.loadDatasets(ctx, datasetIDs)
+ if err != nil {
+ return nil, err
+ }
+ }
+ canvasesByID, err := s.loadCanvases(ctx, canvasIDs)
if err != nil {
return nil, err
}
resources := make([]Resource, 0, len(refs))
for _, ref := range refs {
- if dataset, ok := datasetsByID[ref.ID]; ok {
- resources = append(resources, datasetResource(dataset, ownerIDsByTenant))
+ switch ref.Kind {
+ case ResourceKindDataset:
+ if dataset, ok := datasetsByID[ref.ID]; ok {
+ resources = append(resources, datasetResource(dataset, ownerIDsByTenant))
+ }
+ case ResourceKindCanvas:
+ if canvas, ok := canvasesByID[ref.ID]; ok {
+ resources = append(resources, canvasResource(canvas))
+ }
+ case ResourceKindAgentSession:
+ session, ok := agentSessionsByID[ref.ID]
+ if !ok {
+ continue
+ }
+ canvas, ok := canvasesByID[session.DialogID]
+ if !ok {
+ continue
+ }
+ resources = append(resources, agentSessionResource(session, canvas))
}
}
return resources, nil
@@ -106,9 +147,7 @@ func (s *databaseSource) ListResourceRefs(ctx context.Context, subject Subject,
var tenantIDs []string
if err := s.db.WithContext(ctx).Model(&entity.UserTenant{}).
Distinct("tenant_id").
- Where("user_id = ? AND status = ? AND role IN ?", subject.UserID, string(entity.StatusValid), []string{
- string(RoleOwner), string(RoleAdmin), string(RoleNormal),
- }).
+ Where("user_id = ? AND status = ?", subject.UserID, string(entity.StatusValid)).
Pluck("tenant_id", &tenantIDs).Error; err != nil {
return nil, err
}
@@ -121,6 +160,34 @@ func (s *databaseSource) ListResourceRefs(ctx context.Context, subject Subject,
if err != nil {
return nil, err
}
+ case ResourceKindCanvas:
+ if parent.ID != "" || parent.Kind != "" {
+ return nil, fmt.Errorf("%w: canvases cannot have a parent scope", ErrInvalidPermission)
+ }
+ var tenantIDs []string
+ if err := s.db.WithContext(ctx).Model(&entity.UserTenant{}).
+ Distinct("tenant_id").
+ Where("user_id = ? AND status = ? AND role IN ?", subject.UserID, string(entity.StatusValid), []string{
+ string(RoleOwner), string(RoleAdmin), string(RoleNormal),
+ }).
+ Pluck("tenant_id", &tenantIDs).Error; err != nil {
+ return nil, err
+ }
+ ownerIDs := append(append(make([]string, 0, len(tenantIDs)+1), tenantIDs...), subject.UserID)
+ if err := s.db.WithContext(ctx).Model(&entity.UserCanvas{}).
+ Where("user_id IN ?", ownerIDs).
+ Pluck("id", &ids).Error; err != nil {
+ return nil, err
+ }
+ case ResourceKindAgentSession:
+ if parent.Kind != ResourceKindCanvas || strings.TrimSpace(parent.ID) == "" {
+ return nil, fmt.Errorf("%w: agent sessions require a canvas parent scope", ErrInvalidPermission)
+ }
+ if err := s.db.WithContext(ctx).Model(&entity.API4Conversation{}).
+ Where("dialog_id = ?", parent.ID).
+ Pluck("id", &ids).Error; err != nil {
+ return nil, err
+ }
default:
return nil, fmt.Errorf("%w: unsupported scope resource kind %q", ErrInvalidPermission, kind)
}
@@ -132,6 +199,44 @@ func (s *databaseSource) ListResourceRefs(ctx context.Context, subject Subject,
return refs, nil
}
+func (s *databaseSource) loadCanvases(ctx context.Context, ids []string) (map[string]*entity.UserCanvas, error) {
+ canvasesByID := make(map[string]*entity.UserCanvas)
+ if len(ids) == 0 {
+ return canvasesByID, nil
+ }
+ query := s.db.WithContext(ctx).Model(&entity.UserCanvas{}).Where("id IN ?", ids)
+ if s.lockRows {
+ query = query.Clauses(clause.Locking{Strength: "UPDATE"})
+ }
+ var canvases []*entity.UserCanvas
+ if err := query.Find(&canvases).Error; err != nil {
+ return nil, err
+ }
+ for _, canvas := range canvases {
+ canvasesByID[canvas.ID] = canvas
+ }
+ return canvasesByID, nil
+}
+
+func (s *databaseSource) loadAgentSessions(ctx context.Context, ids []string) (map[string]*entity.API4Conversation, error) {
+ sessionsByID := make(map[string]*entity.API4Conversation)
+ if len(ids) == 0 {
+ return sessionsByID, nil
+ }
+ query := s.db.WithContext(ctx).Model(&entity.API4Conversation{}).Where("id IN ?", ids)
+ if s.lockRows {
+ query = query.Clauses(clause.Locking{Strength: "UPDATE"})
+ }
+ var sessions []*entity.API4Conversation
+ if err := query.Find(&sessions).Error; err != nil {
+ return nil, err
+ }
+ for _, session := range sessions {
+ sessionsByID[session.ID] = session
+ }
+ return sessionsByID, nil
+}
+
func (s *databaseSource) loadDatasets(ctx context.Context, ids []string) (map[string]*entity.Knowledgebase, map[string]string, error) {
datasetsByID := make(map[string]*entity.Knowledgebase)
if len(ids) == 0 {
@@ -200,3 +305,32 @@ func datasetResource(dataset *entity.Knowledgebase, ownerIDsByTenant map[string]
Active: dataset.Status != nil && *dataset.Status == string(entity.StatusValid),
}
}
+
+func canvasResource(canvas *entity.UserCanvas) Resource {
+ visibility := VisibilityPrivate
+ if canvas.Permission == string(entity.TenantPermissionTeam) {
+ visibility = VisibilityTenant
+ }
+ return Resource{
+ Ref: ResourceRef{Kind: ResourceKindCanvas, ID: canvas.ID},
+ TenantID: canvas.UserID,
+ CreatedBy: canvas.UserID,
+ OwnerUserID: canvas.UserID,
+ Visibility: visibility,
+ TenantRequirement: TenantMember,
+ OwnerOperations: []Operation{OperationRead, OperationUpdate, OperationDelete, OperationShare, OperationRun, OperationUse},
+ Active: true,
+ }
+}
+
+func agentSessionResource(session *entity.API4Conversation, canvas *entity.UserCanvas) Resource {
+ return Resource{
+ Ref: ResourceRef{Kind: ResourceKindAgentSession, ID: session.ID},
+ TenantID: canvas.UserID,
+ CreatedBy: session.UserID,
+ OwnerUserID: session.UserID,
+ Visibility: VisibilityPrivate,
+ OwnerOperations: []Operation{OperationRead, OperationRun, OperationUpdate, OperationDelete},
+ Active: true,
+ }
+}
diff --git a/internal/permission/database_source_test.go b/internal/permission/database_source_test.go
index 1ef26ae8a8..59ac6e7d24 100644
--- a/internal/permission/database_source_test.go
+++ b/internal/permission/database_source_test.go
@@ -165,3 +165,103 @@ func TestDatabaseCheckerScopesDatasetsToMembershipAndVisibility(t *testing.T) {
t.Fatalf("Scope(datasets) = %+v, want only the team-visible dataset", scope)
}
}
+
+func TestDatabaseCheckerSharedCanvasGrantsOwnerOperations(t *testing.T) {
+ db, err := gorm.Open(sqlite.Open("file:"+url.QueryEscape(t.Name())+"?mode=memory&cache=shared"), &gorm.Config{})
+ if err != nil {
+ t.Fatalf("open sqlite: %v", err)
+ }
+ if err := db.AutoMigrate(&entity.UserCanvas{}, &entity.UserTenant{}); err != nil {
+ t.Fatalf("migrate permission tables: %v", err)
+ }
+ valid := string(entity.StatusValid)
+ canvases := []entity.UserCanvas{
+ {ID: "team-canvas", UserID: "owner-1", Permission: string(entity.TenantPermissionTeam)},
+ {ID: "private-canvas", UserID: "owner-1", Permission: string(entity.TenantPermissionMe)},
+ {ID: "other-team-canvas", UserID: "owner-2", Permission: string(entity.TenantPermissionTeam)},
+ }
+ for i := range canvases {
+ if err := db.Create(&canvases[i]).Error; err != nil {
+ t.Fatalf("create canvas %q: %v", canvases[i].ID, err)
+ }
+ }
+ membership := entity.UserTenant{
+ ID: "member-owner-1", UserID: "member-1", TenantID: "owner-1",
+ Role: string(RoleNormal), Status: &valid,
+ }
+ if err := db.Create(&membership).Error; err != nil {
+ t.Fatalf("create membership: %v", err)
+ }
+ adminMembership := entity.UserTenant{
+ ID: "admin-owner-1", UserID: "admin-1", TenantID: "owner-1",
+ Role: string(RoleAdmin), Status: &valid,
+ }
+ if err := db.Create(&adminMembership).Error; err != nil {
+ t.Fatalf("create admin membership: %v", err)
+ }
+ checker := NewDatabaseChecker(db)
+ teamCanvas := ResourceRef{Kind: ResourceKindCanvas, ID: "team-canvas"}
+ privateCanvas := ResourceRef{Kind: ResourceKindCanvas, ID: "private-canvas"}
+
+ for _, operation := range []Operation{OperationRead, OperationUpdate, OperationDelete, OperationShare, OperationRun, OperationUse} {
+ if err := checker.CheckResource(context.Background(), Subject{UserID: membership.UserID}, teamCanvas, operation); err != nil {
+ t.Errorf("team member CheckResource(%s) error = %v, want nil", operation, err)
+ }
+ }
+ if err := checker.CheckResource(context.Background(), Subject{UserID: adminMembership.UserID}, teamCanvas, OperationRead); err != nil {
+ t.Errorf("tenant admin CheckResource(read) error = %v, want nil", err)
+ }
+ if err := checker.CheckResource(context.Background(), Subject{UserID: "owner-1"}, privateCanvas, OperationDelete); err != nil {
+ t.Errorf("owner CheckResource(delete) error = %v, want nil", err)
+ }
+ if err := checker.CheckResource(context.Background(), Subject{UserID: "outsider"}, teamCanvas, OperationRead); !errors.Is(err, ErrPermissionDenied) {
+ t.Errorf("outsider CheckResource(read) error = %v, want permission denied", err)
+ }
+
+ scope, err := checker.Scope(context.Background(), Subject{UserID: membership.UserID}, ScopeQuery{
+ Kind: ResourceKindCanvas, Operation: OperationRead,
+ })
+ if err != nil {
+ t.Fatalf("Scope(canvases) error = %v", err)
+ }
+ if scope.Mode != ScopeIDs || len(scope.ResourceIDs) != 1 || scope.ResourceIDs[0] != teamCanvas.ID {
+ t.Fatalf("Scope(canvases) = %+v, want only team-canvas", scope)
+ }
+}
+
+func TestDatabaseCheckerRestrictsAgentSessionRunToCreator(t *testing.T) {
+ db, err := gorm.Open(sqlite.Open("file:"+url.QueryEscape(t.Name())+"?mode=memory&cache=shared"), &gorm.Config{})
+ if err != nil {
+ t.Fatalf("open sqlite: %v", err)
+ }
+ if err := db.AutoMigrate(&entity.UserCanvas{}, &entity.API4Conversation{}); err != nil {
+ t.Fatalf("migrate permission tables: %v", err)
+ }
+ if err := db.Create(&entity.UserCanvas{ID: "canvas-1", UserID: "canvas-owner"}).Error; err != nil {
+ t.Fatalf("create canvas: %v", err)
+ }
+ if err := db.Create(&entity.API4Conversation{ID: "session-1", DialogID: "canvas-1", UserID: "session-owner"}).Error; err != nil {
+ t.Fatalf("create session: %v", err)
+ }
+ checker := NewDatabaseChecker(db)
+ session := ResourceRef{Kind: ResourceKindAgentSession, ID: "session-1"}
+ if err := checker.CheckResource(context.Background(), Subject{UserID: "session-owner"}, session, OperationRun); err != nil {
+ t.Fatalf("session owner CheckResource(run) error = %v, want nil", err)
+ }
+ if err := checker.CheckResource(context.Background(), Subject{UserID: "canvas-owner"}, session, OperationRun); !errors.Is(err, ErrPermissionDenied) {
+ t.Errorf("canvas owner CheckResource(run) error = %v, want permission denied for another user's session", err)
+ }
+ if err := checker.CheckResource(context.Background(), Subject{UserID: "outsider"}, session, OperationRun); !errors.Is(err, ErrPermissionDenied) {
+ t.Errorf("outsider CheckResource(run) error = %v, want permission denied", err)
+ }
+
+ scope, err := checker.Scope(context.Background(), Subject{UserID: "session-owner"}, ScopeQuery{
+ Kind: ResourceKindAgentSession, Parent: ResourceRef{Kind: ResourceKindCanvas, ID: "canvas-1"}, Operation: OperationRun,
+ })
+ if err != nil {
+ t.Fatalf("Scope(agent sessions) error = %v", err)
+ }
+ if scope.Mode != ScopeIDs || len(scope.ResourceIDs) != 1 || scope.ResourceIDs[0] != session.ID {
+ t.Fatalf("Scope(agent sessions) = %+v, want only session-1", scope)
+ }
+}
diff --git a/internal/permission/policy_ce.go b/internal/permission/policy_ce.go
index 201565880e..b1077710cc 100644
--- a/internal/permission/policy_ce.go
+++ b/internal/permission/policy_ce.go
@@ -316,7 +316,11 @@ func (e *evaluation) resolveResource(ctx context.Context, subject Subject, resou
case VisibilityPrivate:
return Access{}, ErrPermissionDenied
case VisibilityTenant:
- if err := e.checkTenant(ctx, subject, resource.TenantID, TenantNormalMember); err != nil {
+ requirement := resource.TenantRequirement
+ if requirement == "" {
+ requirement = TenantNormalMember
+ }
+ if err := e.checkTenant(ctx, subject, resource.TenantID, requirement); err != nil {
if errors.Is(err, ErrMembershipNotFound) {
return Access{}, ErrPermissionDenied
}
@@ -489,10 +493,7 @@ func resourceAccess(resource Resource, source AccessSource) Access {
}
func accessAllows(access Access, operation Operation) bool {
- if !access.Allows(operation) {
- return false
- }
- return operation != OperationShare || access.Source == AccessSourceOwner
+ return access.Allows(operation)
}
func contains(values []string, target string) bool {
diff --git a/internal/permission/types.go b/internal/permission/types.go
index 9cd673c421..cc7992ca3d 100644
--- a/internal/permission/types.go
+++ b/internal/permission/types.go
@@ -43,7 +43,9 @@ type Subject struct {
type ResourceKind string
const (
- ResourceKindDataset ResourceKind = "dataset"
+ ResourceKindDataset ResourceKind = "dataset"
+ ResourceKindCanvas ResourceKind = "canvas"
+ ResourceKindAgentSession ResourceKind = "agent_session"
)
// ResourceRef identifies a persisted resource.
@@ -126,6 +128,7 @@ type Resource struct {
CreatedBy string
OwnerUserID string
Visibility Visibility
+ TenantRequirement TenantRequirement
OwnerOperations []Operation
SharedWithUserIDs []string
SharedWithTenantIDs []string
diff --git a/internal/service/agent.go b/internal/service/agent.go
index e98d18487c..52bf5ba7a0 100644
--- a/internal/service/agent.go
+++ b/internal/service/agent.go
@@ -42,6 +42,7 @@ import (
"ragflow/internal/common"
"ragflow/internal/dao"
"ragflow/internal/entity"
+ "ragflow/internal/permission"
"ragflow/internal/tokenizer"
dslpkg "ragflow/internal/agent/dsl"
@@ -70,7 +71,7 @@ type webhookPayloadKey struct{}
func (s *AgentService) LoadCanvasByID(
ctx context.Context, userID, canvasID string,
) (*entity.UserCanvas, error) {
- return s.loadCanvasForUser(ctx, userID, canvasID)
+ return s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationRead)
}
// RunAgentWithWebhook is a thin wrapper over RunAgent that attaches the
@@ -314,15 +315,9 @@ func splitMessageContent(content string) []string {
return chunks
}
-// ErrAgentNotOwner is returned by DeleteAgent when the canvas exists and
-// is accessible to the caller but is owned by a different user. It maps
-// to the Python "Only the owner of the agent is authorized for this
-// operation." message via handler.mapAgentError.
-//
-// The Python agent API keeps access-check and owner-check as two
-// separate decorators (api/apps/restful_apis/agent_api.py:74-100);
-// we mirror that distinction with ErrUserCanvasNotFound (access) and
-// ErrAgentNotOwner (owner).
+// ErrAgentNotOwner is returned when a caller cannot delete an agent canvas.
+// The handler maps both missing and inaccessible canvases to the same
+// response to avoid revealing resource existence.
var ErrAgentNotOwner = errors.New("agent not owned by user")
// ErrAgentStorageError identifies internal Agent service failures such as
@@ -503,27 +498,15 @@ type AgentFiltersResponse struct {
// agents page filter bar. Mirrors the ?type=filter branch of Python
// agent_api.list_agents.
func (s *AgentService) ListAgentFilters(ctx context.Context, userID string) (*AgentFiltersResponse, common.ErrorCode, error) {
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
+ canvasIDs, err := AccessibleCanvasIDs(ctx, permission.Subject{UserID: userID}, permission.OperationRead)
if err != nil {
- return nil, common.CodeServerError, fmt.Errorf("failed to get tenant IDs: %w", err)
- }
- ownerIDs := make([]string, 0, len(tenantIDs)+1)
- seen := make(map[string]struct{}, len(tenantIDs)+1)
- seen[userID] = struct{}{}
- ownerIDs = append(ownerIDs, userID)
- for _, id := range tenantIDs {
- if _, ok := seen[id]; ok {
- continue
- }
- seen[id] = struct{}{}
- ownerIDs = append(ownerIDs, id)
+ return nil, common.CodeServerError, fmt.Errorf("failed to scope accessible canvases: %w", err)
}
-
- owners, err := s.canvasDAO.GetOwnerFilter(ctx, dao.DB, ownerIDs, userID)
+ owners, err := s.canvasDAO.GetOwnerFilterByCanvasIDs(ctx, dao.DB, canvasIDs)
if err != nil {
return nil, common.CodeServerError, fmt.Errorf("failed to aggregate agent owners: %w", err)
}
- categories, err := s.canvasDAO.GetCategoryFilter(ctx, dao.DB, ownerIDs, userID)
+ categories, err := s.canvasDAO.GetCategoryFilterByCanvasIDs(ctx, dao.DB, canvasIDs)
if err != nil {
return nil, common.CodeServerError, fmt.Errorf("failed to aggregate agent categories: %w", err)
}
@@ -613,31 +596,26 @@ func toAgentItem(c *dao.UserCanvasListItem) *AgentItem {
// Mirrors Python agent_api.list_agents — validates owner_ids against joined tenants,
// then delegates to the DAO.
func (s *AgentService) ListAgents(ctx context.Context, userID string, keywords string, page, pageSize int, terms []dao.OrderTerm, ownerIDs []string, canvasCategory, canvasType string, tags []string) (*ListAgentsResponse, common.ErrorCode, error) {
- // Build the set of tenant IDs the user is authorized to query.
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
+ subject := permission.Subject{UserID: userID}
+ canvasIDs, err := AccessibleCanvasIDs(ctx, subject, permission.OperationRead)
if err != nil {
- return nil, common.CodeServerError, fmt.Errorf("failed to get tenant IDs: %w", err)
+ return nil, common.CodeServerError, fmt.Errorf("failed to scope accessible canvases: %w", err)
}
- authorised := make(map[string]struct{}, len(tenantIDs)+1)
- for _, id := range tenantIDs {
- authorised[id] = struct{}{}
- }
- authorised[userID] = struct{}{}
-
- var effectiveOwnerIDs []string
+ checker := permission.NewDatabaseChecker(dao.DB)
if len(ownerIDs) > 0 {
for _, id := range ownerIDs {
- if _, ok := authorised[id]; !ok {
- return nil, common.CodeOperatingError, fmt.Errorf("only authorized owner_ids can be queried")
+ if id == userID {
+ continue
+ }
+ if err := checker.CheckTenant(ctx, subject, id, permission.TenantMember); err != nil {
+ if errors.Is(err, permission.ErrMembershipNotFound) {
+ return nil, common.CodeOperatingError, fmt.Errorf("only authorized owner_ids can be queried")
+ }
+ return nil, common.CodeServerError, fmt.Errorf("validate agent owner_id: %w", err)
}
- }
- effectiveOwnerIDs = ownerIDs
- } else {
- effectiveOwnerIDs = make([]string, 0, len(authorised))
- for id := range authorised {
- effectiveOwnerIDs = append(effectiveOwnerIDs, id)
}
}
+ effectiveOwnerIDs := ownerIDs
// A canvas entry is either an agent (user_canvas) or a compilation template
// group. Python splits canvas_category on commas and, when the tenant is the
@@ -654,7 +632,7 @@ func (s *AgentService) ListAgents(ctx context.Context, userID string, keywords s
// the caller is an effective owner; otherwise (e.g. owner_ids names another
// user) return an empty list (review Major).
if len(categories) == 1 && wantsGroups {
- if !sliceContains(effectiveOwnerIDs, userID) {
+ if len(ownerIDs) > 0 && !sliceContains(effectiveOwnerIDs, userID) {
return &ListAgentsResponse{Canvas: []json.RawMessage{}, Total: 0}, common.CodeSuccess, nil
}
return s.listAgentsGroupsOnly(ctx, userID, keywords, terms, page, pageSize)
@@ -666,11 +644,11 @@ func (s *AgentService) ListAgents(ctx context.Context, userID string, keywords s
if mergeMode || (wantsGroups && len(agentCategories) > 0) {
listPage, listSize = 0, 0
}
- canvases, total, err := s.canvasDAO.ListByTenantIDs(
+ canvases, total, err := s.canvasDAO.ListByIDs(
ctx,
dao.DB,
+ canvasIDs,
effectiveOwnerIDs,
- userID,
listPage,
listSize,
terms,
@@ -692,7 +670,7 @@ func (s *AgentService) ListAgents(ctx context.Context, userID string, keywords s
// Groups are owner-only (no team sharing) and scoped to the caller, so they
// are merged only when the caller's own tenant is an effective owner
// (Python include_template_groups).
- includeGroups := sliceContains(effectiveOwnerIDs, userID)
+ includeGroups := len(ownerIDs) == 0 || sliceContains(effectiveOwnerIDs, userID)
if includeGroups && (mergeMode || wantsGroups) {
return s.mergeAgentsAndGroups(ctx, userID, agentItems, keywords, terms, page, pageSize)
}
@@ -1048,21 +1026,20 @@ func updatedAgentCanvasCategory(canvasInstance *entity.UserCanvas, updates map[s
// raw errors here would have left a DAO-string leak in the very first
// hop — the earlier af2ac2eda + 804854a5e commits only sanitized the
// version-read path, missing the canvas-access path.
-func (s *AgentService) loadCanvasForUser(ctx context.Context, userID, canvasID string) (*entity.UserCanvas, error) {
+func (s *AgentService) loadCanvasForUser(ctx context.Context, userID, canvasID string, operation permission.Operation) (*entity.UserCanvas, error) {
if canvasID == "" {
return nil, dao.ErrUserCanvasNotFound
}
if userID == "" {
return nil, dao.ErrUserCanvasNotFound
}
- tenants, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
- if err != nil {
- if errors.Is(err, dao.ErrUserCanvasNotFound) {
- return nil, err
+ if err := CheckCanvasPermission(ctx, permission.Subject{UserID: userID}, canvasID, operation); err != nil {
+ if errors.Is(err, permission.ErrResourceNotFound) || errors.Is(err, permission.ErrPermissionDenied) {
+ return nil, dao.ErrUserCanvasNotFound
}
- return nil, fmt.Errorf("tenants for user %s: %w: %w", userID, err, ErrAgentStorageError)
+ return nil, fmt.Errorf("check canvas %q permission for user %s: %w: %w", canvasID, userID, err, ErrAgentStorageError)
}
- row, err := s.canvasDAO.GetByIDForUser(ctx, dao.DB, canvasID, userID, tenants)
+ row, err := s.canvasDAO.GetByID(ctx, dao.DB, canvasID)
if err != nil {
if errors.Is(err, dao.ErrUserCanvasNotFound) {
return nil, err
@@ -1076,7 +1053,7 @@ func (s *AgentService) loadCanvasForUser(ctx context.Context, userID, canvasID s
// Returns dao.ErrUserCanvasNotFound (not 403) when the canvas is missing
// or belongs to another user.
func (s *AgentService) GetAgent(ctx context.Context, userID, canvasID string) (*entity.UserCanvas, error) {
- return s.loadCanvasForUser(ctx, userID, canvasID)
+ return s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationRead)
}
// GetLastPublishTime returns the update_time of the most recently updated
@@ -1096,25 +1073,28 @@ func (s *AgentService) GetLastPublishTime(ctx context.Context, canvasID string)
// UpdateAgent applies a draft patch to user_canvas. Settings updates may omit
// dsl; in that case the existing draft DSL must be preserved.
//
-// Permission is an owner-only setting: team members who have access to the
-// canvas can still update title/avatar/description, but any permission value
-// they send is ignored so they cannot make a team agent private (or vice
-// versa). The owner can change permission together with title/avatar in one
-// request.
+// Canvas sharing grants the same operations as ownership in the community
+// policy, including changing its visibility.
func (s *AgentService) UpdateAgent(ctx context.Context, userID, canvasID string, patch map[string]interface{}) error {
- canvasInstance, err := s.loadCanvasForUser(ctx, userID, canvasID)
+ canvasInstance, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationUpdate)
if err != nil {
return err
}
ownerUserID := canvasInstance.UserID
- if v, ok := patch["permission"]; ok && ownerUserID != userID {
- requested := strings.ToLower(strings.TrimSpace(fmt.Sprint(v)))
- current := strings.ToLower(strings.TrimSpace(canvasInstance.Permission))
- if requested != current {
- return fmt.Errorf("user %s has no permission to edit permission", userID)
+ if v, ok := patch["permission"]; ok {
+ shareErr := CheckCanvasPermission(ctx, permission.Subject{UserID: userID}, canvasID, permission.OperationShare)
+ if shareErr != nil {
+ if !errors.Is(shareErr, permission.ErrPermissionDenied) {
+ return fmt.Errorf("check agent sharing permission: %w", shareErr)
+ }
+ requested := strings.ToLower(strings.TrimSpace(fmt.Sprint(v)))
+ current := strings.ToLower(strings.TrimSpace(canvasInstance.Permission))
+ if requested != current {
+ return fmt.Errorf("user %s has no permission to edit permission", userID)
+ }
+ delete(patch, "permission")
}
- delete(patch, "permission")
}
updates := map[string]interface{}{}
@@ -1125,6 +1105,11 @@ func (s *AgentService) UpdateAgent(ctx context.Context, userID, canvasID string,
value = strings.TrimSpace(title)
}
}
+ if key == "permission" {
+ if permissionValue, ok := value.(string); ok {
+ value = strings.ToLower(strings.TrimSpace(permissionValue))
+ }
+ }
updates[key] = value
}
}
@@ -1243,7 +1228,7 @@ func (s *AgentService) UpdateAgent(ctx context.Context, userID, canvasID string,
// dao.ErrUserCanvasNotFound so mapAgentError emits the same 404 the
// Python handler does for "canvas not found."
func (s *AgentService) ResetAgent(ctx context.Context, userID, canvasID string) (entity.JSONMap, error) {
- row, err := s.loadCanvasForUser(ctx, userID, canvasID)
+ row, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationUpdate)
if err != nil {
return nil, err
}
@@ -1260,33 +1245,22 @@ func (s *AgentService) ResetAgent(ctx context.Context, userID, canvasID string)
return row.DSL, nil
}
-// DeleteAgent removes the canvas and cascades to its user_canvas_version
+// DeleteAgent removes a canvas and cascades to its user_canvas_version
// rows in a single transaction so a mid-flight failure cannot leave
-// orphan version rows (Phase 5 §2.9; review follow-up M2).
-//
-// Owner-only by design (mirrors _require_canvas_owner_sync in the Python
-// agent API). Both "canvas does not exist" and "canvas is owned by
-// someone else" surface as ErrAgentNotOwner so the handler emits the
-// single "Only the owner..." 103 message — same envelope as the Python
-// decorator (api/apps/restful_apis/agent_api.py:94-100), which uses
-// UserCanvasService.query(user_id=..., id=...) and conflates those two
-// cases into one OPERATING_ERROR response.
+// orphan version rows. Canvas delete access is decided by the permission
+// policy, including its sharing rules.
func (s *AgentService) DeleteAgent(ctx context.Context, userID, canvasID string) error {
- row, err := s.canvasDAO.GetByID(ctx, dao.DB, canvasID)
- if err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
+ if err := CheckCanvasPermission(ctx, permission.Subject{UserID: userID}, canvasID, permission.OperationDelete); err != nil {
+ if errors.Is(err, permission.ErrResourceNotFound) || errors.Is(err, permission.ErrPermissionDenied) {
return ErrAgentNotOwner
}
- return fmt.Errorf("load agent %s: %w", canvasID, err)
- }
- if row.UserID != userID {
- return ErrAgentNotOwner
+ return fmt.Errorf("check agent deletion permission: %w", err)
}
return dao.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- if _, err = s.versionDAO.DeleteByCanvasIDTx(ctx, tx, canvasID); err != nil {
+ if _, err := s.versionDAO.DeleteByCanvasIDTx(ctx, tx, canvasID); err != nil {
return fmt.Errorf("delete agent: cascade versions: %w", err)
}
- if err = s.canvasDAO.DeleteTx(ctx, tx, canvasID); err != nil {
+ if err := s.canvasDAO.DeleteTx(ctx, tx, canvasID); err != nil {
return fmt.Errorf("delete agent %s: %w", canvasID, err)
}
return nil
@@ -1301,7 +1275,7 @@ type PublishAgentRequest struct {
}
func (s *AgentService) PublishAgent(ctx context.Context, userID, canvasID string, req *PublishAgentRequest) (*entity.UserCanvasVersion, error) {
- canvasInstance, err := s.loadCanvasForUser(ctx, userID, canvasID)
+ canvasInstance, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationUpdate)
if err != nil {
return nil, err
}
@@ -1393,7 +1367,7 @@ func buildVersionTitle(userNickname, agentTitle string, ts time.Time) string {
// version list is loaded so unauthorized users cannot enumerate version
// ids of canvases they cannot read.
func (s *AgentService) ListVersions(ctx context.Context, userID, canvasID string) ([]*entity.UserCanvasVersion, error) {
- if _, err := s.loadCanvasForUser(ctx, userID, canvasID); err != nil {
+ if _, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationRead); err != nil {
return nil, err
}
return s.versionDAO.ListByCanvasID(ctx, dao.DB, canvasID)
@@ -1408,7 +1382,7 @@ func (s *AgentService) GetVersion(ctx context.Context, userID, canvasID, version
if versionID == "" {
return nil, dao.ErrUserCanvasVersionNotFound
}
- if _, err := s.loadCanvasForUser(ctx, userID, canvasID); err != nil {
+ if _, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationRead); err != nil {
return nil, err
}
row, err := s.versionDAO.GetByID(ctx, dao.DB, versionID)
@@ -1429,7 +1403,7 @@ func (s *AgentService) DeleteVersion(ctx context.Context, userID, canvasID, vers
if versionID == "" {
return dao.ErrUserCanvasVersionNotFound
}
- if _, err := s.loadCanvasForUser(ctx, userID, canvasID); err != nil {
+ if _, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationUpdate); err != nil {
return err
}
row, err := s.versionDAO.GetByID(ctx, dao.DB, versionID)
@@ -1463,7 +1437,7 @@ func (s *AgentService) DeleteVersion(ctx context.Context, userID, canvasID, vers
// error-layering contract).
func (s *AgentService) RunAgent(ctx context.Context, userID, canvasID, sessionID, version string, userInput any, files []map[string]interface{}) (<-chan canvas.RunEvent, error) {
receivedAt := float64(time.Now().UnixNano()) / 1e9
- canvasRow, err := s.loadCanvasForUser(ctx, userID, canvasID)
+ canvasRow, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationRun)
if err != nil {
return nil, err
}
@@ -1481,8 +1455,8 @@ func (s *AgentService) RunAgent(ctx context.Context, userID, canvasID, sessionID
if !trustedFirstTouch {
return nil, fmt.Errorf("RunAgent: session %q not found: %w", sessionID, dao.ErrUserCanvasNotFound)
}
- } else if existingSession.DialogID != canvasID || existingSession.UserID != userID {
- return nil, fmt.Errorf("RunAgent: session %q not found: %w", sessionID, dao.ErrUserCanvasNotFound)
+ } else if err := checkAgentSessionRunPermission(ctx, userID, sessionID); err != nil {
+ return nil, fmt.Errorf("RunAgent: session %q not found: %w", sessionID, err)
}
}
messageID := common.GenerateToken()
@@ -1498,8 +1472,8 @@ func (s *AgentService) RunAgent(ctx context.Context, userID, canvasID, sessionID
if session == nil {
return nil
}
- if session.UserID != userID {
- return fmt.Errorf("RunAgent: session %q not found: %w", sessionID, dao.ErrUserCanvasNotFound)
+ if err := checkAgentSessionRunPermission(ctx, userID, sessionID); err != nil {
+ return fmt.Errorf("RunAgent: session %q not found: %w", sessionID, err)
}
if err := s.persistAgentRunQuestion(ctx, canvasID, userID, sessionID, messageID, userInput, receivedAt); err != nil {
return fmt.Errorf("RunAgent: persist question: %w: %w", err, ErrAgentStorageError)
@@ -1730,8 +1704,10 @@ func (s *AgentService) RunAgent(ctx context.Context, userID, canvasID, sessionID
if err != nil {
return nil, fmt.Errorf("RunAgent: load session %q: %w: %w", sessionID, err, ErrAgentStorageError)
}
- if existingSession != nil && (existingSession.DialogID != canvasID || existingSession.UserID != userID) {
- return nil, fmt.Errorf("RunAgent: session %q not found: %w", sessionID, dao.ErrUserCanvasNotFound)
+ if existingSession != nil {
+ if err := checkAgentSessionRunPermission(ctx, userID, sessionID); err != nil {
+ return nil, fmt.Errorf("RunAgent: session %q not found: %w", sessionID, err)
+ }
}
sessionFound = existingSession != nil
if existingSession != nil && len(existingSession.DSL) > 0 {
@@ -1923,6 +1899,22 @@ func validateAgentChatModels(ctx context.Context, userID string, dsl map[string]
return nil
}
+func checkAgentSessionRunPermission(ctx context.Context, userID, sessionID string) error {
+ err := permission.NewDatabaseChecker(dao.DB).CheckResource(
+ ctx,
+ permission.Subject{UserID: userID},
+ permission.ResourceRef{Kind: permission.ResourceKindAgentSession, ID: sessionID},
+ permission.OperationRun,
+ )
+ if errors.Is(err, permission.ErrPermissionDenied) || errors.Is(err, permission.ErrResourceNotFound) {
+ return dao.ErrUserCanvasNotFound
+ }
+ if err != nil {
+ return fmt.Errorf("check agent session run permission: %w: %w", err, ErrAgentStorageError)
+ }
+ return nil
+}
+
// buildRunFunc assembles the per-run RunFunc the orchestrator (canvas.Runner)
// drives.
//
diff --git a/internal/service/agent_sessions.go b/internal/service/agent_sessions.go
index f68c364a46..d5adc10f1d 100644
--- a/internal/service/agent_sessions.go
+++ b/internal/service/agent_sessions.go
@@ -30,6 +30,7 @@ import (
"ragflow/internal/common"
"ragflow/internal/dao"
"ragflow/internal/entity"
+ "ragflow/internal/permission"
)
const (
@@ -74,26 +75,14 @@ type DeleteAgentSessionsResponse struct {
// CheckCanvasAccess returns true when the user is the canvas owner or
// holds team-level permission for the owner's tenant.
func (s *AgentService) CheckCanvasAccess(ctx context.Context, userID, canvasID string) (bool, error) {
- canvas, err := s.canvasDAO.GetByID(ctx, dao.DB, canvasID)
- if err != nil {
- return false, err
- }
- if canvas.UserID == userID {
- return true, nil
+ err := CheckCanvasPermission(ctx, permission.Subject{UserID: userID}, canvasID, permission.OperationRead)
+ if errors.Is(err, permission.ErrResourceNotFound) {
+ return false, dao.ErrUserCanvasNotFound
}
- if canvas.Permission != string(entity.TenantPermissionTeam) {
+ if errors.Is(err, permission.ErrPermissionDenied) {
return false, nil
}
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
- if err != nil {
- return false, err
- }
- for _, tid := range tenantIDs {
- if canvas.UserID == tid {
- return true, nil
- }
- }
- return false, nil
+ return err == nil, err
}
func parseAgentSessionDate(value string, isEnd bool) (*time.Time, error) {
@@ -411,21 +400,13 @@ func (s *AgentService) DeleteAgentSessionItem(ctx context.Context, userID, agent
if sessionID == "" {
return false, common.CodeArgumentError, errors.New("session_id is required")
}
- ok, err := s.CheckCanvasAccess(ctx, userID, agentID)
- if err != nil {
- if errors.Is(err, dao.ErrUserCanvasNotFound) {
+ if err := CheckCanvasPermission(ctx, permission.Subject{UserID: userID}, agentID, permission.OperationDelete); err != nil {
+ if errors.Is(err, permission.ErrResourceNotFound) || errors.Is(err, permission.ErrPermissionDenied) {
return false, common.CodeOperatingError, errors.New("agent not found or no permission")
}
- return false, common.CodeServerError, fmt.Errorf("failed to check agent permission: %w", err)
- }
- if !ok {
- return false, common.CodeOperatingError, errors.New("agent not found or no permission")
+ return false, common.CodeServerError, fmt.Errorf("failed to check agent deletion permission: %w", err)
}
- // Shared-session readonly rule (same design as the owner-only batch
- // delete below): deleting a session is a write, so it is limited to the
- // canvas owner or the session's creator. Team members who can read the
- // shared agent see the session readonly.
conv, cerr := s.api4ConversationDAO.GetBySessionID(ctx, dao.DB, sessionID, agentID)
if cerr != nil {
return false, common.CodeServerError, cerr
@@ -433,14 +414,6 @@ func (s *AgentService) DeleteAgentSessionItem(ctx context.Context, userID, agent
if conv == nil {
return false, common.CodeSuccess, nil
}
- canvasOwned, oerr := s.canvasOwnedByUser(ctx, userID, agentID)
- if oerr != nil {
- return false, common.CodeServerError, oerr
- }
- if !canvasOwned && conv.UserID != userID {
- return false, common.CodeAuthenticationError, errors.New("shared session is readonly")
- }
-
row, err := s.api4ConversationDAO.DeleteBySessionIDAndAgentID(ctx, dao.DB, sessionID, agentID)
if err != nil {
return false, common.CodeServerError, err
@@ -451,21 +424,7 @@ func (s *AgentService) DeleteAgentSessionItem(ctx context.Context, userID, agent
return true, common.CodeSuccess, nil
}
-// canvasOwnedByUser reports whether the canvas is directly owned by userID
-// (canvas.user_id), ignoring team sharing. Companion of CheckCanvasAccess,
-// which authorizes the wider team-read scope.
-func (s *AgentService) canvasOwnedByUser(ctx context.Context, userID, canvasID string) (bool, error) {
- canvas, err := s.canvasDAO.GetByID(ctx, dao.DB, canvasID)
- if err != nil {
- if errors.Is(err, dao.ErrUserCanvasNotFound) {
- return false, nil
- }
- return false, err
- }
- return canvas.UserID == userID, nil
-}
-
-// DeleteAgentSessions removes multiple conversations owned by agentID.
+// DeleteAgentSessions removes selected conversations belonging to agentID.
// When ids is empty and deleteAll is true, every session under agentID is
// removed.
func (s *AgentService) DeleteAgentSessions(ctx context.Context, userID, agentID string, ids []string, deleteAll bool) (*DeleteAgentSessionsResult, common.ErrorCode, error) {
@@ -473,13 +432,11 @@ func (s *AgentService) DeleteAgentSessions(ctx context.Context, userID, agentID
return nil, common.CodeArgumentError, errors.New("agent_id is required")
}
- // Owner-only by design: batch session deletion is destructive and must
- // not be available to team members even when the canvas has team
- // permission. CheckCanvasAccess (used elsewhere) would also allow team
- // access, which is too permissive for this operation.
- canvas, err := s.canvasDAO.GetByID(ctx, dao.DB, agentID)
- if err != nil || canvas == nil || canvas.UserID != userID {
- return nil, common.CodeDataError, fmt.Errorf("you don't own the agent %s", agentID)
+ if err := CheckCanvasPermission(ctx, permission.Subject{UserID: userID}, agentID, permission.OperationDelete); err != nil {
+ if errors.Is(err, permission.ErrResourceNotFound) || errors.Is(err, permission.ErrPermissionDenied) {
+ return nil, common.CodeDataError, fmt.Errorf("you don't have permission to delete sessions for agent %s", agentID)
+ }
+ return nil, common.CodeServerError, fmt.Errorf("check agent deletion permission: %w", err)
}
if len(ids) == 0 {
@@ -487,10 +444,11 @@ func (s *AgentService) DeleteAgentSessions(ctx context.Context, userID, agentID
return &DeleteAgentSessionsResult{}, common.CodeSuccess, nil
}
- ids, err = s.api4ConversationDAO.ListIDsByAgentID(ctx, dao.DB, agentID)
+ listedIDs, err := s.api4ConversationDAO.ListIDsByAgentID(ctx, dao.DB, agentID)
if err != nil {
return nil, common.CodeServerError, err
}
+ ids = listedIDs
if len(ids) == 0 {
return &DeleteAgentSessionsResult{}, common.CodeSuccess, nil
}
@@ -550,22 +508,11 @@ func (s *AgentService) DeleteAgentSessions(ctx context.Context, userID, agentID
// ListAgentTags list agent tags
func (s *AgentService) ListAgentTags(ctx context.Context, userID, canvasCategory string) ([]AgentTagCount, common.ErrorCode, error) {
- tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
+ canvasIDs, err := AccessibleCanvasIDs(ctx, permission.Subject{UserID: userID}, permission.OperationRead)
if err != nil {
return nil, common.CodeServerError, err
}
-
- ownerSet := make(map[string]struct{}, len(tenantIDs)+1)
- ownerSet[userID] = struct{}{}
- for _, id := range tenantIDs {
- ownerSet[id] = struct{}{}
- }
- ownerIDs := make([]string, 0, len(ownerSet))
- for id := range ownerSet {
- ownerIDs = append(ownerIDs, id)
- }
-
- counts, err := s.canvasDAO.ListTags(ctx, dao.DB, ownerIDs, userID, canvasCategory)
+ counts, err := s.canvasDAO.ListTagsByCanvasIDs(ctx, dao.DB, canvasIDs, canvasCategory)
if err != nil {
return nil, common.CodeServerError, err
}
@@ -652,17 +599,12 @@ func normalizeAgentTags(rawTags interface{}) (string, error) {
// UpdateAgentTags normalises tags and persists them on a single canvas.
func (s *AgentService) UpdateAgentTags(ctx context.Context, userID, canvasID string, tags interface{}) (bool, common.ErrorCode, error) {
- ok, err := s.CheckCanvasAccess(ctx, userID, canvasID)
- if err != nil {
- if errors.Is(err, dao.ErrUserCanvasNotFound) {
+ if err := CheckCanvasPermission(ctx, permission.Subject{UserID: userID}, canvasID, permission.OperationUpdate); err != nil {
+ if errors.Is(err, permission.ErrResourceNotFound) || errors.Is(err, permission.ErrPermissionDenied) {
return false, common.CodeOperatingError, errors.New("agent not found or no permission")
}
return false, common.CodeServerError, fmt.Errorf("failed to check agent permission: %w", err)
}
- if !ok {
- return false, common.CodeOperatingError, errors.New("agent not found or no permission")
- }
-
normalized, nErr := normalizeAgentTags(tags)
if nErr != nil {
return false, common.CodeBadRequest, nErr
@@ -725,17 +667,12 @@ func (s *AgentService) CreateAgentSession(ctx context.Context, req *CreateAgentS
return nil, common.CodeArgumentError, errors.New("create agent session: user_id is required")
}
- ok, err := s.CheckCanvasAccess(ctx, req.UserID, req.AgentID)
- if err != nil {
- if errors.Is(err, dao.ErrUserCanvasNotFound) {
+ if err := CheckCanvasPermission(ctx, permission.Subject{UserID: req.UserID}, req.AgentID, permission.OperationRun); err != nil {
+ if errors.Is(err, permission.ErrResourceNotFound) || errors.Is(err, permission.ErrPermissionDenied) {
return nil, common.CodeOperatingError, errors.New("agent not found or no permission")
}
return nil, common.CodeServerError, fmt.Errorf("check canvas access: %w", err)
}
- if !ok {
- return nil, common.CodeOperatingError, errors.New("agent not found or no permission")
- }
-
messages := req.Messages
if len(messages) == 0 {
messages = json.RawMessage(`[]`)
diff --git a/internal/service/agent_test.go b/internal/service/agent_test.go
index d6d7e3817d..fa136015ac 100644
--- a/internal/service/agent_test.go
+++ b/internal/service/agent_test.go
@@ -29,6 +29,7 @@ import (
"ragflow/internal/common"
"ragflow/internal/dao"
"ragflow/internal/entity"
+ "ragflow/internal/permission"
)
func TestBuildAgentMessageEventsThinkingProtocol(t *testing.T) {
@@ -887,7 +888,7 @@ func TestLoadCanvasForUser_StorageErrorWrap(t *testing.T) {
ctx := t.Context()
svc := NewAgentService()
- _, err := svc.loadCanvasForUser(ctx, "user-1", "canvas-1")
+ _, err := svc.loadCanvasForUser(ctx, "user-1", "canvas-1", permission.OperationRead)
if err == nil {
t.Fatal("expected storage error from closed DB")
}
@@ -1607,7 +1608,7 @@ func TestUpdateAgentAllowsExistingTitleForSameCanvas(t *testing.T) {
}
}
-func TestUpdateAgentTeamMemberPermissionAndOwnerTitleChecks(t *testing.T) {
+func TestUpdateAgentTeamMemberCanUpdateAndShareCanvas(t *testing.T) {
setupAgentSessionServiceTest(t)
ctx := t.Context()
@@ -1653,18 +1654,25 @@ func TestUpdateAgentTeamMemberPermissionAndOwnerTitleChecks(t *testing.T) {
t.Fatalf("UpdateAgent with same permission failed: %v", err)
}
- nextPermission := "me"
- if err := NewAgentService().UpdateAgent(ctx, "member-1", "canvas-team-edit", map[string]interface{}{
- "permission": nextPermission,
- }); err == nil {
- t.Fatal("UpdateAgent permission change error = nil, want error")
- }
-
if err := NewAgentService().UpdateAgent(ctx, "member-1", "canvas-team-edit", map[string]interface{}{
"title": "Owner Duplicate",
}); err == nil || err.Error() != "Owner Duplicate already exists." {
t.Fatalf("UpdateAgent duplicate title error = %v, want Owner Duplicate already exists.", err)
}
+
+ nextPermission := "me"
+ if err := NewAgentService().UpdateAgent(ctx, "member-1", "canvas-team-edit", map[string]interface{}{
+ "permission": nextPermission,
+ }); err != nil {
+ t.Fatalf("UpdateAgent permission change failed: %v", err)
+ }
+ var canvas entity.UserCanvas
+ if err := dao.DB.WithContext(ctx).Where("id = ?", "canvas-team-edit").Take(&canvas).Error; err != nil {
+ t.Fatalf("reload canvas: %v", err)
+ }
+ if canvas.Permission != nextPermission {
+ t.Fatalf("canvas permission = %q, want %q", canvas.Permission, nextPermission)
+ }
}
func TestUpdateAgentRejectsDuplicateTitleInDestinationCategory(t *testing.T) {
@@ -2554,9 +2562,6 @@ func TestOpenAICompatPriorHistoryPreservesConversation(t *testing.T) {
}
}
-// Shared-agent readonly rule: deleting a session is a write, so only the
-// canvas owner or the session's creator may do it. Team members who can
-// read the shared agent see its sessions readonly.
func createTeamSharedAgentTestFixtures(t *testing.T, canvasOwner, teammate, sessionID, sessionOwner string) {
t.Helper()
if err := dao.DB.Create(&entity.UserCanvas{
@@ -2580,27 +2585,27 @@ func createTeamSharedAgentTestFixtures(t *testing.T, canvasOwner, teammate, sess
createAgentSessionTestConversation(t, sessionID, "canvas-1", sessionOwner, 1000)
}
-func TestDeleteAgentSessionItem_SharedSessionReadonlyForTeammate(t *testing.T) {
+func TestDeleteAgentSessionItem_SharedCanvasGrantsDeleteAccess(t *testing.T) {
setupAgentSessionServiceTest(t)
createTeamSharedAgentTestFixtures(t, "owner-1", "user-1", "session-1", "owner-1")
deleted, code, err := NewAgentService().DeleteAgentSessionItem(t.Context(), "user-1", "canvas-1", "session-1")
- if err == nil || err.Error() != "shared session is readonly" {
- t.Fatalf("err=%v", err)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
}
- if code != common.CodeAuthenticationError {
+ if code != common.CodeSuccess {
t.Fatalf("code=%v", code)
}
- if deleted {
- t.Fatal("shared session must not be deleted by a team member")
+ if !deleted {
+ t.Fatal("team member with access to the shared canvas should be able to delete its session")
}
var count int64
if err = dao.DB.Model(&entity.API4Conversation{}).Where("id = ?", "session-1").Count(&count).Error; err != nil {
t.Fatalf("failed to count session: %v", err)
}
- if count != 1 {
- t.Fatalf("session should remain, count=%d", count)
+ if count != 0 {
+ t.Fatalf("session should be deleted, count=%d", count)
}
}
diff --git a/internal/service/bot.go b/internal/service/bot.go
index b396f720db..a45f7e6244 100644
--- a/internal/service/bot.go
+++ b/internal/service/bot.go
@@ -34,6 +34,7 @@ import (
"ragflow/internal/dao"
"ragflow/internal/engine/kvrocks"
"ragflow/internal/entity"
+ "ragflow/internal/permission"
)
// BotService coordinates chatbot + agentbot reads and the matching
@@ -97,11 +98,11 @@ func (s *BotService) ChatbotInfo(ctx context.Context, tenantID, dialogID string)
// Mirrors the python `bot_api.py::agentbot_inputs` handler. The
// authorisation check is the same IDOR guard the production
// AgentService uses (canvas must be visible to the requesting user).
-func (s *BotService) AgentbotInputs(ctx context.Context, tenantID, agentID string) (
+func (s *BotService) AgentbotInputs(ctx context.Context, userID, agentID string) (
title, avatar, prologue, mode string, inputs map[string]any,
ec common.ErrorCode, err error,
) {
- cv, err := s.loadCanvas(ctx, tenantID, agentID)
+ cv, err := s.loadCanvas(ctx, userID, agentID, permission.OperationRead)
if err != nil {
return "", "", "", "", nil, common.CodeDataError, err
}
@@ -136,7 +137,7 @@ func (s *BotService) AgentbotInputs(ctx context.Context, tenantID, agentID strin
// is the cheap fast-fail that costs a single DAO roundtrip
// instead of a full canvas compile.
func (s *BotService) AgentbotCompletion(
- ctx context.Context, tenantID, agentID string, req AgentbotCompletionRequest,
+ ctx context.Context, userID, agentID string, req AgentbotCompletionRequest,
) (<-chan canvas.RunEvent, common.ErrorCode, error) {
question, err := ResolveCompletionQuestion(req.Question, req.Query, req.Messages)
if err != nil {
@@ -146,7 +147,7 @@ func (s *BotService) AgentbotCompletion(
if s.agentService == nil {
return nil, common.CodeServerError, fmt.Errorf("bot: agent service not wired")
}
- if _, err := s.loadCanvas(ctx, tenantID, agentID); err != nil {
+ if _, err := s.loadCanvas(ctx, userID, agentID, permission.OperationRun); err != nil {
return nil, common.CodeDataError, err
}
// Compose the canvas user input the same way Python's
@@ -161,10 +162,10 @@ func (s *BotService) AgentbotCompletion(
userInput := agentbotUserInput(req)
var ch <-chan canvas.RunEvent
if req.Release != nil && *req.Release {
- ch, err = s.agentService.runReleasedAgent(ctx, tenantID, agentID,
+ ch, err = s.agentService.runReleasedAgent(ctx, userID, agentID,
req.SessionID, userInput, req.Files)
} else {
- ch, err = s.agentService.RunAgent(ctx, tenantID, agentID,
+ ch, err = s.agentService.RunAgent(ctx, userID, agentID,
req.SessionID, "", userInput, req.Files)
}
if err != nil {
@@ -176,8 +177,8 @@ func (s *BotService) AgentbotCompletion(
// AgentbotLogs returns the stored execution timeline for an agentbot run.
// Access is scoped to the caller's accessible tenants, matching the Python
// agent_bot_logs endpoint.
-func (s *BotService) AgentbotLogs(ctx context.Context, tenantID, agentID, messageID string) (map[string]any, common.ErrorCode, error) {
- if _, err := s.loadCanvas(ctx, tenantID, agentID); err != nil {
+func (s *BotService) AgentbotLogs(ctx context.Context, userID, agentID, messageID string) (map[string]any, common.ErrorCode, error) {
+ if _, err := s.loadCanvas(ctx, userID, agentID, permission.OperationRead); err != nil {
return nil, common.CodeDataError, err
}
payload, err := kvrocks.Get().Get(ctx, fmt.Sprintf("%s-%s-logs", agentID, messageID))
@@ -280,23 +281,22 @@ type ChatbotCompletionRequest struct {
DocIDs string `json:"doc_ids"`
}
-// loadCanvas is the IDOR guard for agentbot reads. It mirrors the
-// private loadCanvasForUser helper on AgentService without taking a
-// dependency on the agentService pointer (so BotService can be
-// tested with a nil agentService).
-func (s *BotService) loadCanvas(ctx context.Context, tenantID, agentID string) (*entity.UserCanvas, error) {
+// loadCanvas authorizes a bot operation before loading its canvas. Keeping this
+// guard here prevents public bot endpoints from depending on AgentService.
+func (s *BotService) loadCanvas(ctx context.Context, userID, agentID string, operation permission.Operation) (*entity.UserCanvas, error) {
if agentID == "" {
return nil, dao.ErrUserCanvasNotFound
}
- if tenantID == "" {
+ if userID == "" {
return nil, dao.ErrUserCanvasNotFound
}
- userTenantDAO := dao.NewUserTenantDAO()
- tenants, err := userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, tenantID)
- if err != nil {
- return nil, fmt.Errorf("bot: tenants for user %s: %w", tenantID, err)
+ if err := CheckCanvasPermission(ctx, permission.Subject{UserID: userID}, agentID, operation); err != nil {
+ if errors.Is(err, permission.ErrResourceNotFound) || errors.Is(err, permission.ErrPermissionDenied) {
+ return nil, dao.ErrUserCanvasNotFound
+ }
+ return nil, fmt.Errorf("bot: check canvas %s permission: %w", agentID, err)
}
- return s.canvasDAO.GetByIDForUser(ctx, dao.DB, agentID, tenantID, tenants)
+ return s.canvasDAO.GetByID(ctx, dao.DB, agentID)
}
// canvasDSLMap projects a UserCanvas.DSL JSONMap into a
diff --git a/internal/service/canvas_permission.go b/internal/service/canvas_permission.go
new file mode 100644
index 0000000000..568f2ca298
--- /dev/null
+++ b/internal/service/canvas_permission.go
@@ -0,0 +1,33 @@
+package service
+
+import (
+ "context"
+
+ "ragflow/internal/dao"
+ "ragflow/internal/permission"
+)
+
+// CheckCanvasPermission checks a canvas operation through the active permission policy.
+func CheckCanvasPermission(ctx context.Context, subject permission.Subject, canvasID string, operation permission.Operation) error {
+ return permission.NewDatabaseChecker(dao.DB).CheckResource(
+ ctx,
+ subject,
+ permission.ResourceRef{Kind: permission.ResourceKindCanvas, ID: canvasID},
+ operation,
+ )
+}
+
+// AccessibleCanvasIDs returns the canvas IDs visible for an operation.
+func AccessibleCanvasIDs(ctx context.Context, subject permission.Subject, operation permission.Operation) ([]string, error) {
+ scope, err := permission.NewDatabaseChecker(dao.DB).Scope(ctx, subject, permission.ScopeQuery{
+ Kind: permission.ResourceKindCanvas,
+ Operation: operation,
+ })
+ if err != nil {
+ return nil, err
+ }
+ if scope.Mode == permission.ScopeNone {
+ return []string{}, nil
+ }
+ return scope.ResourceIDs, nil
+}
diff --git a/internal/service/dataset/crud.go b/internal/service/dataset/crud.go
index d6a507cc45..44bc9e093f 100644
--- a/internal/service/dataset/crud.go
+++ b/internal/service/dataset/crud.go
@@ -111,7 +111,7 @@ func (d *DatasetService) CreateDataset(ctx context.Context, req *service.CreateD
}
if pipelineID != nil && strings.TrimSpace(*pipelineID) != "" {
- if ok, err := canvasAccessibleForUser(ctx, userID, strings.TrimSpace(*pipelineID)); err != nil {
+ if ok, err := canvasAccessibleForUser(ctx, subject, strings.TrimSpace(*pipelineID)); err != nil {
return nil, common.CodeServerError, err
} else if !ok {
return nil, common.CodeDataError, errors.New("canvas is not accessible")
diff --git a/internal/service/dataset/helpers.go b/internal/service/dataset/helpers.go
index 8c0d706105..f27078a555 100644
--- a/internal/service/dataset/helpers.go
+++ b/internal/service/dataset/helpers.go
@@ -11,6 +11,7 @@ import (
"ragflow/internal/dao"
"ragflow/internal/entity"
pipelinepkg "ragflow/internal/ingestion/pipeline"
+ "ragflow/internal/permission"
"ragflow/internal/service"
"github.com/google/uuid"
@@ -296,9 +297,12 @@ func pythonStringListRepr(items []string) string {
return "[" + strings.Join(quoted, ", ") + "]"
}
-func canvasAccessibleForUser(ctx context.Context, userID, canvasID string) (bool, error) {
- tenantIDs, _ := dao.NewUserTenantDAO().GetTenantIDsByUserID(ctx, dao.DB, userID)
- return dao.NewUserCanvasDAO().Accessible(ctx, dao.DB, canvasID, userID, tenantIDs), nil
+func canvasAccessibleForUser(ctx context.Context, subject permission.Subject, canvasID string) (bool, error) {
+ err := service.CheckCanvasPermission(ctx, subject, canvasID, permission.OperationUse)
+ if errors.Is(err, permission.ErrResourceNotFound) || errors.Is(err, permission.ErrPermissionDenied) {
+ return false, nil
+ }
+ return err == nil, err
}
func parserConfigValueOrEmptyList(parserConfig map[string]interface{}, key string) interface{} {
diff --git a/internal/service/dataset/update.go b/internal/service/dataset/update.go
index c284bcd810..a89ac98b2d 100644
--- a/internal/service/dataset/update.go
+++ b/internal/service/dataset/update.go
@@ -185,6 +185,29 @@ func (d *DatasetService) UpdateDataset(ctx context.Context, datasetID, userID st
txCode = code
return authErr
}
+ if sel != nil || pipelineID != nil || req.ParserConfig != nil || req.ParserConfigProvided {
+ current := service.CurrentSelection(lockedKB.ParserID, lockedKB.PipelineID)
+ effective, resolveErr := service.Resolve(current, sel)
+ if resolveErr != nil {
+ txCode = common.CodeDataError
+ return resolveErr
+ }
+ isPipeline, _, effectivePipelineID := effective.Effective()
+ if isPipeline && effectivePipelineID != nil && strings.TrimSpace(*effectivePipelineID) != "" {
+ accessErr := permission.NewLockingDatabaseChecker(tx).CheckDependency(
+ ctx,
+ permission.Subject{UserID: userID, TenantID: lockedKB.TenantID},
+ permission.ResourceRef{Kind: permission.ResourceKindDataset, ID: lockedKB.ID},
+ permission.ResourceRef{Kind: permission.ResourceKindCanvas, ID: strings.TrimSpace(*effectivePipelineID)},
+ permission.OperationUpdate,
+ permission.OperationUse,
+ )
+ if accessErr != nil {
+ txCode, accessErr = permissionresponse.Normalize(accessErr)
+ return accessErr
+ }
+ }
+ }
updates := make(map[string]interface{}, len(simpleUpdates)+6)
for key, value := range simpleUpdates {
diff --git a/internal/service/dataset/update_test.go b/internal/service/dataset/update_test.go
index eb108e07b1..0647b56d83 100644
--- a/internal/service/dataset/update_test.go
+++ b/internal/service/dataset/update_test.go
@@ -468,7 +468,7 @@ func TestDatasetServiceUpdateDatasetRejectsNonOwner(t *testing.T) {
}
}
-func TestDatasetServiceUpdateDatasetRejectsTeamMemberPermissionChange(t *testing.T) {
+func TestDatasetServiceUpdateDatasetAllowsTeamMemberPermissionChange(t *testing.T) {
db := setupDatasetUpdateTestDB(t)
pushServiceDB(t, db)
insertDatasetUpdateKB(t, "kb-1", "owner-1", "Original")
@@ -484,22 +484,19 @@ func TestDatasetServiceUpdateDatasetRejectsTeamMemberPermissionChange(t *testing
_, code, err := testDatasetUpdateService(t).UpdateDataset(ctx, "kb-1", "user-1", service.UpdateDatasetRequest{
Permission: &permission,
})
- if err == nil {
- t.Fatal("expected permission change error")
- }
- if code != common.CodeForbidden {
- t.Fatalf("expected forbidden code, got %d", code)
+ if err != nil {
+ t.Fatalf("expected shared tenant member to update dataset permission: %v", err)
}
- if err.Error() != "Permission denied" {
- t.Fatalf("unexpected error: %v", err)
+ if code != common.CodeSuccess {
+ t.Fatalf("expected success code, got %d", code)
}
persisted, err := dao.NewKnowledgebaseDAO().GetByID(ctx, db, "kb-1")
if err != nil {
t.Fatalf("get dataset: %v", err)
}
- if persisted.Permission != string(entity.TenantPermissionTeam) {
- t.Fatalf("expected permission unchanged, got %q", persisted.Permission)
+ if persisted.Permission != string(entity.TenantPermissionMe) {
+ t.Fatalf("expected permission to change to %q, got %q", entity.TenantPermissionMe, persisted.Permission)
}
}
diff --git a/internal/service/document/document.go b/internal/service/document/document.go
index 6be6e8b96d..342f0721b9 100644
--- a/internal/service/document/document.go
+++ b/internal/service/document/document.go
@@ -41,7 +41,6 @@ type DocumentService struct {
taskDAO *dao.TaskDAO
file2DocumentDAO *dao.File2DocumentDAO
fileDAO *dao.FileDAO
- canvasDAO *dao.UserCanvasDAO
api4ConvDAO *dao.API4ConversationDAO
purgeTaskState func(context.Context, string) error
}
@@ -66,7 +65,6 @@ func NewDocumentService() *DocumentService {
taskDAO: dao.NewTaskDAO(),
file2DocumentDAO: dao.NewFile2DocumentDAO(),
fileDAO: dao.NewFileDAO(),
- canvasDAO: dao.NewUserCanvasDAO(),
api4ConvDAO: dao.NewAPI4ConversationDAO(),
}
}
diff --git a/internal/service/document/document_artifact.go b/internal/service/document/document_artifact.go
index 9e12286690..4144a6ecb6 100644
--- a/internal/service/document/document_artifact.go
+++ b/internal/service/document/document_artifact.go
@@ -226,29 +226,14 @@ func (s *DocumentService) sandboxArtifactDialogIDsForUser(ctx context.Context, f
return out
}
-// sandboxArtifactAccessible reports whether userID may reach at
-// least one agent canvas whose session references filename.
-// Mirrors `UserCanvasService.accessible(dialog_id, user_id)` from
-// the Python fix; on the Go side this is the same predicate as
-// UserCanvasDAO.Accessible (owner or team permission, with the
-// latter scoped to the caller's tenant membership — PR review
-// round 5).
+// sandboxArtifactAccessible reports whether userID may read at least one
+// canvas whose session references filename.
func (s *DocumentService) sandboxArtifactAccessible(ctx context.Context, filename, userID string) bool {
if userID == "" {
return false
}
- // Fetch the caller's tenant list once; passing it into
- // canvasDAO.Accessible ensures the team-permission branch only
- // matches canvases the caller can actually see. An empty list
- // (callers without tenant data) is safe — it effectively disables
- // the team branch, so the only matches are canvases the caller
- // directly owns.
- tenantIDs, terr := dao.NewUserTenantDAO().GetTenantIDsByUserID(ctx, dao.DB, userID)
- if terr != nil {
- tenantIDs = nil
- }
for _, dialogID := range s.sandboxArtifactDialogIDsForUser(ctx, filename, userID) {
- if s.canvasDAO.Accessible(ctx, dao.DB, dialogID, userID, tenantIDs) {
+ if service.CheckCanvasPermission(ctx, permission.Subject{UserID: userID}, dialogID, permission.OperationRead) == nil {
return true
}
}
diff --git a/internal/service/document/document_dataset_update.go b/internal/service/document/document_dataset_update.go
index 167aedd7f1..77521913ad 100644
--- a/internal/service/document/document_dataset_update.go
+++ b/internal/service/document/document_dataset_update.go
@@ -163,6 +163,20 @@ func (s *DocumentService) UpdateDatasetDocument(ctx context.Context, userID, dat
current := service.CurrentSelection(kb.ParserID, kb.PipelineID)
eff, _ := service.Resolve(current, sel)
isPipeline, effParserID, effPipelineID := eff.Effective()
+ if (sel != nil || present["parser_config"]) && isPipeline && effPipelineID != nil && strings.TrimSpace(*effPipelineID) != "" {
+ accessErr := permission.NewDatabaseChecker(dao.DB).CheckDependency(
+ ctx,
+ permission.Subject{UserID: userID, TenantID: kb.TenantID},
+ permission.ResourceRef{Kind: permission.ResourceKindDataset, ID: kb.ID},
+ permission.ResourceRef{Kind: permission.ResourceKindCanvas, ID: strings.TrimSpace(*effPipelineID)},
+ permission.OperationUpdate,
+ permission.OperationUse,
+ )
+ if accessErr != nil {
+ code, permissionErr := permissionresponse.Normalize(accessErr)
+ return nil, code, permissionErr
+ }
+ }
if present["parser_config"] && req.ParserConfig != nil {
// Normalize "pages" ranges before persistence. Invalid ranges are
diff --git a/internal/service/document/document_test.go b/internal/service/document/document_test.go
index 726a27b1a2..0462529468 100644
--- a/internal/service/document/document_test.go
+++ b/internal/service/document/document_test.go
@@ -535,6 +535,7 @@ func setupServiceTestDBWithDSN(t *testing.T, dsn string) *gorm.DB {
&entity.User{},
&entity.Tenant{},
&entity.UserTenant{},
+ &entity.UserCanvas{},
&entity.API4Conversation{},
); err != nil {
t.Fatalf("failed to migrate: %v", err)
@@ -642,6 +643,17 @@ func ensureTestTenantOwner(t *testing.T, userID, tenantID string) {
}
}
+func insertTestCanvas(t *testing.T, canvasID, ownerID string) {
+ t.Helper()
+ if err := dao.DB.Create(&entity.UserCanvas{
+ ID: canvasID,
+ UserID: ownerID,
+ Permission: string(entity.TenantPermissionMe),
+ }).Error; err != nil {
+ t.Fatalf("insert test canvas: %v", err)
+ }
+}
+
func assertKBDocNum(t *testing.T, kbID string, want int64) {
t.Helper()
var got int64
@@ -3417,6 +3429,7 @@ func TestUpdateDatasetDocumentPipelineIDTakesPrecedenceOverParserID(t *testing.T
insertNamedTestDoc(t, "doc-1", "kb-1", "doc.txt", 10, 5)
pipelineID := "1234567890abcdef1234567890abcdef"
+ insertTestCanvas(t, pipelineID, "user-1")
parseType := 2
svc := testDocumentService(t)
ctx := t.Context()
@@ -3488,6 +3501,7 @@ func TestUpdateDatasetDocumentParseTypePipeline(t *testing.T) {
parseType := 2
pipelineID := "1234567890abcdef1234567890abcdef"
+ insertTestCanvas(t, pipelineID, "user-1")
svc := testDocumentService(t)
ctx := t.Context()
resp, code, err := svc.UpdateDatasetDocument(ctx, "user-1", "kb-1", "doc-1", &UpdateDatasetDocumentRequest{
@@ -3551,6 +3565,7 @@ func TestUpdateDatasetDocumentParentChildConfigSurvivesDSLFailure(t *testing.T)
parseType := 2
pipelineID := "1234567890abcdef1234567890abcdef"
+ insertTestCanvas(t, pipelineID, "user-1")
resp, code, err := testDocumentService(t).UpdateDatasetDocument(t.Context(), "user-1", "kb-1", "doc-1", &UpdateDatasetDocumentRequest{
ParseType: &parseType,
PipelineID: &pipelineID,