diff --git a/internal/application/service/custom_agent.go b/internal/application/service/custom_agent.go index 923889a9..d3e703f1 100644 --- a/internal/application/service/custom_agent.go +++ b/internal/application/service/custom_agent.go @@ -68,8 +68,9 @@ func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.Custo // Record the creator. Mirrors KnowledgeBase.CreatorID — needed by // RBAC's RequireOwnershipOrRole so Contributors can edit their own // agents. Synthetic system-{tenantID} users (X-API-Key path) leave - // the field empty, which makes the agent tenant-owned (Admin+ only). - if uid, ok := types.UserIDFromContext(ctx); ok { + // the field empty via IsSyntheticUserID, which makes the agent + // tenant-owned (Admin+ only). + if uid, ok := types.UserIDFromContext(ctx); ok && !types.IsSyntheticUserID(uid) { agent.CreatedBy = uid } @@ -415,8 +416,9 @@ func (s *customAgentService) CopyAgent(ctx context.Context, id string) (*types.C UpdatedAt: time.Now(), } // The clone is owned by whoever ran the copy, not the original - // creator — same reasoning as CopyKnowledgeBase. - if uid, ok := types.UserIDFromContext(ctx); ok { + // creator — same reasoning as CopyKnowledgeBase. Skip synthetic + // API-key users. + if uid, ok := types.UserIDFromContext(ctx); ok && !types.IsSyntheticUserID(uid) { newAgent.CreatedBy = uid } diff --git a/internal/application/service/knowledgebase.go b/internal/application/service/knowledgebase.go index decfcb23..795ab170 100644 --- a/internal/application/service/knowledgebase.go +++ b/internal/application/service/knowledgebase.go @@ -94,11 +94,13 @@ func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context, kb.UpdatedAt = time.Now() // Record the creator so RBAC's RequireOwnershipOrRole can let // Contributors edit their own KBs without granting them tenant-wide - // edit rights. UserIDFromContext returns ("", false) for the - // synthetic system-{tenantID} user used by the X-API-Key auth path - // — leaving CreatorID empty there marks the KB as tenant-owned, which - // matches today's API-key semantics (any human Admin can manage it). - if uid, ok := types.UserIDFromContext(ctx); ok { + // edit rights. The X-API-Key auth path attaches a synthetic + // `system-` user; we deliberately skip those so the KB + // stays tenant-owned (CreatorID == ""), which matches the original + // API-key semantics (any human Admin can manage it) and prevents a + // later "list KBs by creator" feature from surfacing rows nobody can + // re-attribute. + if uid, ok := types.UserIDFromContext(ctx); ok && !types.IsSyntheticUserID(uid) { kb.CreatorID = uid } kb.EnsureDefaults() @@ -804,8 +806,9 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context, } // The clone is owned by the caller, not the original creator — // otherwise a Contributor copying someone else's KB would still - // not be able to edit the result. - if uid, ok := types.UserIDFromContext(ctx); ok { + // not be able to edit the result. Skip synthetic API-key users + // (see CreateKnowledgeBase for the same reasoning). + if uid, ok := types.UserIDFromContext(ctx); ok && !types.IsSyntheticUserID(uid) { targetKB.CreatorID = uid } targetKB.EnsureDefaults() diff --git a/internal/handler/rbac_lookups.go b/internal/handler/rbac_lookups.go index 420151e4..5fd7bcea 100644 --- a/internal/handler/rbac_lookups.go +++ b/internal/handler/rbac_lookups.go @@ -4,37 +4,59 @@ import ( "errors" apprepo "github.com/Tencent/WeKnora/internal/application/repository" + "github.com/Tencent/WeKnora/internal/application/service" "github.com/Tencent/WeKnora/internal/middleware" + "github.com/Tencent/WeKnora/internal/types" "github.com/gin-gonic/gin" ) // Per-resource creator-id resolvers used by middleware.RequireOwnershipOrRole. // The route registration wires these as closures so they capture the handler's // service dependencies; the middleware just calls them with the gin.Context -// and gets back ("", nil) for legacy tenant-owned rows or (creatorID, nil) -// for resources we know how to attribute. +// and gets back one of: // -// Lookup contract (mirrors middleware.CreatorLookup): -// - URL param missing -> error (the middleware will 403; better than -// letting an unauthenticated mutation through on a malformed route). -// - Resource not found -> error (downstream handler would 404 anyway, -// and middleware-level 403 is a fine signal to clients). -// - Resource found but creator_id == "" -> ("", nil); the middleware -// treats that as tenant-owned and falls back to pure role check. +// - (creatorID, nil) : ownership match check decides +// - ("", nil) : tenant-owned (legacy or built-in) +// - ("", ErrResourceNotFound) : :id doesn't resolve in this tenant; +// middleware passes through so the +// handler can issue a real 404 +// - ("", ) : transient/unexpected failure; +// middleware will 503 the request +// +// Tenant scoping is enforced INSIDE the lookup: even if the underlying +// `Get*ByID` repo call is unscoped, the lookup re-checks `tenant_id` +// against the caller's context. This stops a creator-match shortcut +// from leaking access to a same-ID resource in a different tenant. -// KBCreatorLookup resolves :id -> KnowledgeBase.CreatorID. Used by all -// per-KB mutating routes. +// KBCreatorLookup resolves :id -> KnowledgeBase.CreatorID, scoped to +// the caller's tenant. Used by all per-KB mutating routes. func (h *KnowledgeBaseHandler) KBCreatorLookup(c *gin.Context) (string, error) { id := c.Param("id") if id == "" { return "", errors.New("missing :id param for KB creator lookup") } - kb, err := h.service.GetKnowledgeBaseByID(c.Request.Context(), id) + ctx := c.Request.Context() + tenantID, ok := types.TenantIDFromContext(ctx) + if !ok { + // 没有租户上下文意味着 auth 中间件未完成;当作 lookup 失败让上层 503, + // 而不是 silently 走 fail-open 给一个不该有的访问。 + return "", errors.New("tenant context missing") + } + kb, err := h.service.GetKnowledgeBaseByID(ctx, id) if err != nil { + if errors.Is(err, apprepo.ErrKnowledgeBaseNotFound) { + return "", middleware.ErrResourceNotFound + } return "", err } if kb == nil { - return "", apprepo.ErrKnowledgeBaseNotFound + return "", middleware.ErrResourceNotFound + } + // 显式重校验租户:repo.GetKnowledgeBaseByID 不带 tenant 过滤, + // 万一未来 :id 被攻击者从他人租户 UUID 试探到,也不会借由 + // "ownership match" 通过中间件。 + if kb.TenantID != tenantID { + return "", middleware.ErrResourceNotFound } return kb.CreatorID, nil } @@ -44,17 +66,33 @@ func (h *KnowledgeBaseHandler) KBCreatorLookup(c *gin.Context) (string, error) { // belong to the tenant rather than to any one user, so we return // ("", nil) and let the role check decide. The same holds for legacy // rows whose CreatedBy was never populated. +// +// The underlying GetAgentByID already scopes to the caller's tenant, +// but we keep an explicit defence-in-depth check here in case future +// refactors loosen the service-layer scope. func (h *CustomAgentHandler) AgentCreatorLookup(c *gin.Context) (string, error) { id := c.Param("id") if id == "" { return "", errors.New("missing :id param for agent creator lookup") } - agent, err := h.service.GetAgentByID(c.Request.Context(), id) + ctx := c.Request.Context() + tenantID, ok := types.TenantIDFromContext(ctx) + if !ok { + return "", errors.New("tenant context missing") + } + agent, err := h.service.GetAgentByID(ctx, id) if err != nil { + if errors.Is(err, service.ErrAgentNotFound) || + errors.Is(err, apprepo.ErrCustomAgentNotFound) { + return "", middleware.ErrResourceNotFound + } return "", err } if agent == nil { - return "", errors.New("agent not found") + return "", middleware.ErrResourceNotFound + } + if agent.TenantID != tenantID { + return "", middleware.ErrResourceNotFound } if agent.IsBuiltin { return "", nil diff --git a/internal/handler/rbac_lookups_test.go b/internal/handler/rbac_lookups_test.go new file mode 100644 index 00000000..37a57ed3 --- /dev/null +++ b/internal/handler/rbac_lookups_test.go @@ -0,0 +1,150 @@ +package handler + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + apprepo "github.com/Tencent/WeKnora/internal/application/repository" + "github.com/Tencent/WeKnora/internal/application/service" + "github.com/Tencent/WeKnora/internal/middleware" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/gin-gonic/gin" +) + +// The lookup helpers translate handler/service errors into the +// middleware sentinel set; that translation is where bugs hide (404 +// becoming 403, cross-tenant leaks, etc.), so we test those edges +// directly rather than via end-to-end HTTP. + +// stubKBService implements just enough of interfaces.KnowledgeBaseService +// to drive KBCreatorLookup. Any other method panics so the test fails +// loudly if a future lookup refactor reaches outside the contract. +type stubKBService struct { + interfaces.KnowledgeBaseService + get func(ctx context.Context, id string) (*types.KnowledgeBase, error) +} + +func (s *stubKBService) GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) { + return s.get(ctx, id) +} + +func newKBLookupCtx(t *testing.T, tenantID uint64, paramID string) *gin.Context { + t.Helper() + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodGet, "/x", nil) + ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, tenantID) + c.Request = c.Request.WithContext(ctx) + c.Params = gin.Params{{Key: "id", Value: paramID}} + return c +} + +func TestKBCreatorLookup_NotFoundMapsToSentinel(t *testing.T) { + h := &KnowledgeBaseHandler{service: &stubKBService{ + get: func(_ context.Context, _ string) (*types.KnowledgeBase, error) { + return nil, apprepo.ErrKnowledgeBaseNotFound + }, + }} + _, err := h.KBCreatorLookup(newKBLookupCtx(t, 1, "kb-1")) + if !errors.Is(err, middleware.ErrResourceNotFound) { + t.Fatalf("expected ErrResourceNotFound, got %v", err) + } +} + +func TestKBCreatorLookup_CrossTenantIsHiddenAsNotFound(t *testing.T) { + // A foreign-tenant KB must NEVER leak via the ownership shortcut. + // Returning the row's CreatorID would let a user-id collision pass + // the middleware's "creator == uid" branch; hiding it as not-found + // keeps the lookup strictly tenant-scoped. + h := &KnowledgeBaseHandler{service: &stubKBService{ + get: func(_ context.Context, _ string) (*types.KnowledgeBase, error) { + return &types.KnowledgeBase{ID: "kb-1", TenantID: 999, CreatorID: "u1"}, nil + }, + }} + _, err := h.KBCreatorLookup(newKBLookupCtx(t, 1, "kb-1")) + if !errors.Is(err, middleware.ErrResourceNotFound) { + t.Fatalf("cross-tenant KB must surface as not-found, got %v", err) + } +} + +func TestKBCreatorLookup_OwnerMatchReturnsCreatorID(t *testing.T) { + h := &KnowledgeBaseHandler{service: &stubKBService{ + get: func(_ context.Context, _ string) (*types.KnowledgeBase, error) { + return &types.KnowledgeBase{ID: "kb-1", TenantID: 1, CreatorID: "u-creator"}, nil + }, + }} + creator, err := h.KBCreatorLookup(newKBLookupCtx(t, 1, "kb-1")) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if creator != "u-creator" { + t.Fatalf("expected creator=u-creator, got %q", creator) + } +} + +func TestKBCreatorLookup_MissingTenantContext(t *testing.T) { + // Without tenant context, the lookup can't decide scope. Surfacing + // a real error (which middleware turns into 503) is safer than + // silently returning ErrResourceNotFound: the request shouldn't be + // happening at all. + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodGet, "/x", nil) + c.Params = gin.Params{{Key: "id", Value: "kb-1"}} + h := &KnowledgeBaseHandler{service: &stubKBService{ + get: func(_ context.Context, _ string) (*types.KnowledgeBase, error) { + t.Fatalf("service must not be called without tenant context") + return nil, nil + }, + }} + _, err := h.KBCreatorLookup(c) + if err == nil { + t.Fatalf("expected error when tenant context missing") + } + if errors.Is(err, middleware.ErrResourceNotFound) { + t.Fatalf("missing tenant must not be reported as not-found: %v", err) + } +} + +// stubAgentService mirrors stubKBService for the agent lookup tests. +type stubAgentService struct { + interfaces.CustomAgentService + get func(ctx context.Context, id string) (*types.CustomAgent, error) +} + +func (s *stubAgentService) GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error) { + return s.get(ctx, id) +} + +func TestAgentCreatorLookup_BuiltinIsTenantOwned(t *testing.T) { + h := &CustomAgentHandler{service: &stubAgentService{ + get: func(_ context.Context, _ string) (*types.CustomAgent, error) { + return &types.CustomAgent{ + ID: "smart-reasoning", TenantID: 1, IsBuiltin: true, CreatedBy: "ignored", + }, nil + }, + }} + creator, err := h.AgentCreatorLookup(newKBLookupCtx(t, 1, "smart-reasoning")) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if creator != "" { + t.Fatalf("built-in agent must surface as tenant-owned (empty creator), got %q", creator) + } +} + +func TestAgentCreatorLookup_AgentNotFoundMapsToSentinel(t *testing.T) { + h := &CustomAgentHandler{service: &stubAgentService{ + get: func(_ context.Context, _ string) (*types.CustomAgent, error) { + return nil, service.ErrAgentNotFound + }, + }} + _, err := h.AgentCreatorLookup(newKBLookupCtx(t, 1, "missing-agent")) + if !errors.Is(err, middleware.ErrResourceNotFound) { + t.Fatalf("expected ErrResourceNotFound, got %v", err) + } +} diff --git a/internal/middleware/rbac.go b/internal/middleware/rbac.go index 015b78bf..c42f1864 100644 --- a/internal/middleware/rbac.go +++ b/internal/middleware/rbac.go @@ -1,7 +1,10 @@ package middleware import ( + "context" + "errors" "net/http" + "sync" "github.com/Tencent/WeKnora/internal/config" "github.com/Tencent/WeKnora/internal/logger" @@ -9,25 +12,49 @@ import ( "github.com/gin-gonic/gin" ) +// ErrResourceNotFound is the sentinel a CreatorLookup returns when the +// :id on the request does not match any row the lookup can see (either +// the row is genuinely missing or its tenant doesn't match). When a +// lookup returns this error, RequireOwnershipOrRole intentionally lets +// the request proceed so the downstream handler can respond with its +// own 404 — middleware-level 403 would hide real "URL is wrong" failures +// behind a permissions error, which breaks client diagnostics and +// operator dashboards. +var ErrResourceNotFound = errors.New("rbac: resource not found") + // CreatorLookup resolves the creator user ID for the resource targeted // by the current request, based on whatever is on the gin.Context (URL // params, query, body). Implementations live next to the handlers they // guard, e.g. handler.kbCreatorLookup(c) reads ":id" and returns // KnowledgeBase.CreatorID. // -// Returning ("", nil) means "no creator recorded" — the resource pre-dates -// the migration backfill. RequireOwnershipOrRole treats this as -// "tenant-owned" and requires the role check to pass. -// -// Any non-nil error short-circuits the request with 403; callers should -// distinguish "not found" (404 in the handler if needed) from genuine -// failures inside their lookup helper. +// Return value contract: +// - (creatorID, nil) where creatorID != "" -> the resource has a +// recorded owner; ownership match grants access. +// - ("", nil) -> "tenant-owned": no +// human creator was recorded (legacy row or built-in resource); +// only callers whose role meets the bar may proceed. +// - ("", ErrResourceNotFound) -> the :id does not +// resolve to any row visible to this caller's tenant. Middleware +// proceeds to the handler so the handler can return 404 instead +// of masking it as 403. +// - ("", other error) -> transient or +// unexpected failure (DB hiccup, etc.). Middleware returns 503 +// when enforcement is on so monitoring catches the real fault; +// when enforcement is off, it logs and lets the request through. type CreatorLookup func(c *gin.Context) (creatorID string, err error) // RequireRole returns a gin middleware that aborts the request with // HTTP 403 unless the caller's TenantRole (set by the auth middleware // in TenantRoleContextKey) is at least min. // +// Cross-tenant superusers (User.CanAccessAllTenants) automatically +// satisfy any role gate. Otherwise rolling out tenant-RBAC would silently +// break organisation-level operators who own no tenant_members row in +// the tenant they're administering. The escape hatch is bounded by the +// existing canAccessTenant gate in auth.go; this middleware does not +// grant extra reach, only honours what was already approved. +// // When cfg.Tenant.EnableRBAC is false, the middleware logs the would-be // rejection but lets the request through — preserving today's behaviour // during the rollout window. Once operators flip the flag to true, @@ -38,21 +65,27 @@ type CreatorLookup func(c *gin.Context) (creatorID string, err error) // is the safest fail-closed value: anything that requires more than // Viewer will reject. func RequireRole(min types.TenantRole, cfg *config.Config) gin.HandlerFunc { + warnOnNilConfig(cfg) return func(c *gin.Context) { - role := types.TenantRoleFromContext(c.Request.Context()) + ctx := c.Request.Context() + role := types.TenantRoleFromContext(ctx) if role.HasPermission(min) { c.Next() return } - uid, _ := types.UserIDFromContext(c.Request.Context()) + if isCrossTenantSuperuser(ctx) { + c.Next() + return + } + uid, _ := types.UserIDFromContext(ctx) if !rbacEnforcementEnabled(cfg) { - logger.Warnf(c.Request.Context(), + logger.Warnf(ctx, "[rbac] role insufficient (logged but not enforced): user=%s have=%s need=%s path=%s", uid, role, min, c.Request.URL.Path) c.Next() return } - logger.Warnf(c.Request.Context(), + logger.Warnf(ctx, "[rbac] role insufficient: user=%s have=%s need=%s path=%s", uid, role, min, c.Request.URL.Path) c.JSON(http.StatusForbidden, gin.H{ @@ -69,66 +102,81 @@ func RequireRole(min types.TenantRole, cfg *config.Config) gin.HandlerFunc { // Use it for KB / agent mutations where Contributors should only manage // their own resources but Admins+ have free reign. The lookup closure // is responsible for translating the URL into the resource's creator -// user ID. +// user ID (see CreatorLookup for the return-value contract). // // Decision order: -// 1. role >= min -> allow. -// 2. lookup returns the caller's user ID -> allow. -// 3. lookup returns a non-empty different user ID -> deny (or log when -// enforcement is disabled). -// 4. lookup returns an empty creator ID (legacy / unmigrated row) -> -// treat as tenant-owned; only role >= min may proceed. Effectively -// equivalent to step 1 for that row. -// 5. lookup returns an error -> deny (don't fail open on lookup errors: -// a broken creator query is more often a bug than a transient blip, -// and treating a load failure as "approve" would be a footgun). -// -// Like RequireRole, when cfg.Tenant.EnableRBAC is false the middleware -// logs but does not block. +// 1. role >= min -> allow without running lookup. +// 2. cross-tenant superuser -> allow without running lookup. +// 3. enforcement off -> log, allow without running lookup. This is the +// critical rollout-safety guarantee: when EnableRBAC is false, the +// lookup is NEVER invoked, so dormant mode incurs zero extra DB +// roundtrips on hot per-resource mutation paths. +// 4. lookup returns ErrResourceNotFound -> pass through; let the +// handler issue the proper 404. +// 5. lookup returns other error -> 503 (transient/unexpected fault). +// Preserves observability instead of disguising server errors as 403. +// 6. lookup returns the caller's user ID -> allow (ownership match). +// 7. lookup returns "" -> tenant-owned, role check already failed: 403. +// 8. lookup returns a different non-empty user ID -> 403. func RequireOwnershipOrRole(min types.TenantRole, lookup CreatorLookup, cfg *config.Config) gin.HandlerFunc { + warnOnNilConfig(cfg) return func(c *gin.Context) { ctx := c.Request.Context() role := types.TenantRoleFromContext(ctx) - // Fast path: role meets the bar, skip the lookup entirely. + // 1. Fast path: role meets the bar. if role.HasPermission(min) { c.Next() return } + // 2. Cross-tenant superuser bypass — same reasoning as RequireRole. + if isCrossTenantSuperuser(ctx) { + c.Next() + return + } + uid, _ := types.UserIDFromContext(ctx) - creator, err := lookup(c) - if err != nil { + + // 3. Fail-open shortcut: when enforcement is off, do NOT run the + // lookup. Running it would add a hidden DB roundtrip on every + // mutating request during the rollout window — see #1318 review. + if !rbacEnforcementEnabled(cfg) { logger.Warnf(ctx, + "[rbac] ownership/role would be checked (enforcement off, lookup skipped): "+ + "user=%s have=%s need=%s path=%s", + uid, role, min, c.Request.URL.Path) + c.Next() + return + } + + creator, err := lookup(c) + switch { + case errors.Is(err, ErrResourceNotFound): + // 4. Hand off to the handler so the client sees a real 404 + // rather than a fake "no permission" 403. + c.Next() + return + case err != nil: + // 5. Genuine failure — surface it as 5xx so monitoring catches it. + logger.Errorf(ctx, "[rbac] creator lookup failed: user=%s path=%s err=%v", uid, c.Request.URL.Path, err) - if !rbacEnforcementEnabled(cfg) { - c.Next() - return - } - c.JSON(http.StatusForbidden, gin.H{ - "error": "Forbidden: cannot verify resource ownership", + c.JSON(http.StatusServiceUnavailable, gin.H{ + "error": "Service Unavailable: cannot verify resource ownership", }) c.Abort() return } - // Ownership match wins even when role is below min — that's the - // whole point: Contributors can edit their own resources. + // 6. Ownership match wins even when role is below min — that's the + // whole point: Contributors can edit their own resources. if creator != "" && creator == uid { c.Next() return } - if !rbacEnforcementEnabled(cfg) { - logger.Warnf(ctx, - "[rbac] ownership/role insufficient (logged, not enforced): "+ - "user=%s have=%s need=%s creator=%q path=%s", - uid, role, min, creator, c.Request.URL.Path) - c.Next() - return - } - + // 7-8. Tenant-owned (creator=="") or non-creator with insufficient role. logger.Warnf(ctx, "[rbac] ownership/role insufficient: user=%s have=%s need=%s creator=%q path=%s", uid, role, min, creator, c.Request.URL.Path) @@ -141,9 +189,43 @@ func RequireOwnershipOrRole(min types.TenantRole, lookup CreatorLookup, cfg *con // rbacEnforcementEnabled reports whether middleware should actually // reject failed checks. When the flag is off the middleware still runs -// (so role lookups exercise the membership table and any logging fires) -// but rejection is downgraded to a warning. Mirrors the pattern in -// resolveTenantRole's fail-open branch in middleware/auth.go. +// role-only checks (logging, fast paths), but rejection is downgraded +// to a warning and ownership lookups are skipped entirely so the dormant +// rollout window incurs no per-request DB cost. func rbacEnforcementEnabled(cfg *config.Config) bool { return cfg != nil && cfg.Tenant != nil && cfg.Tenant.EnableRBAC } + +// isCrossTenantSuperuser reports whether the caller is an org-level +// superuser whose CanAccessAllTenants flag was honoured by the auth +// middleware (cfg.Tenant.EnableCrossTenantAccess must also be on for +// the flag to mean anything operationally). Such callers bypass tenant +// role gates because their access is already governed by a separate +// org-level authorisation check. +func isCrossTenantSuperuser(ctx context.Context) bool { + u, ok := ctx.Value(types.UserContextKey).(*types.User) + if !ok || u == nil { + return false + } + return u.CanAccessAllTenants +} + +// warnOnNilConfig emits a one-shot startup warning when a guard is +// constructed with a nil-or-incomplete config. nil cfg makes +// rbacEnforcementEnabled return false, which means an entire deployment +// silently runs with RBAC disabled — usually because of a configuration +// bug rather than an intentional choice. Operators should see a noisy +// log line at boot pointing at the misconfiguration. +var nilCfgWarnOnce sync.Once + +func warnOnNilConfig(cfg *config.Config) { + if cfg != nil && cfg.Tenant != nil { + return + } + nilCfgWarnOnce.Do(func() { + logger.Errorf(context.Background(), + "[rbac] middleware constructed with nil/incomplete config "+ + "(cfg=%v); enforcement is permanently disabled. This is "+ + "almost certainly a wiring bug.", cfg) + }) +} diff --git a/internal/middleware/rbac_test.go b/internal/middleware/rbac_test.go index 7f5a060f..499b9613 100644 --- a/internal/middleware/rbac_test.go +++ b/internal/middleware/rbac_test.go @@ -142,14 +142,106 @@ func TestRequireOwnershipOrRole_LegacyEmptyCreatorTreatedAsTenantOwned(t *testin } } -func TestRequireOwnershipOrRole_LookupErrorRejects(t *testing.T) { - // A failing lookup is treated as deny — failing open here would mean +func TestRequireOwnershipOrRole_LookupErrorReturns503(t *testing.T) { + // A transient lookup error surfaces as 503 (not 403) so monitoring + // and clients can tell "your permission was denied" from "the server + // briefly couldn't verify ownership". Failing open here would mean // any DB hiccup on the creator query becomes a free pass. lookup := func(c *gin.Context) (string, error) { return "", errors.New("boom") } w := rbacTestHarness(types.TenantRoleContributor, "u1", RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true))) - if w.Code != http.StatusForbidden { - t.Fatalf("lookup error must reject, got %d", w.Code) + if w.Code != http.StatusServiceUnavailable { + t.Fatalf("lookup error must surface as 503, got %d", w.Code) + } +} + +func TestRequireOwnershipOrRole_NotFoundPassesThroughTo404(t *testing.T) { + // When the lookup signals "no such resource visible to this tenant", + // the middleware MUST NOT mask it as 403. The handler downstream + // gets to decide the right status (usually 404), which keeps client + // error handling honest and avoids hiding "wrong URL" behind a + // permissions error. + called := false + lookup := func(c *gin.Context) (string, error) { + return "", ErrResourceNotFound + } + router := gin.New() + router.Use(func(c *gin.Context) { + ctx := c.Request.Context() + ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleContributor) + ctx = context.WithValue(ctx, types.UserIDContextKey, "u1") + c.Request = c.Request.WithContext(ctx) + c.Next() + }) + router.GET("/protected", + RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true)), + func(c *gin.Context) { + called = true + c.JSON(http.StatusNotFound, gin.H{"error": "kb not found"}) + }, + ) + req := httptest.NewRequest(http.MethodGet, "/protected", nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + if !called { + t.Fatalf("handler should have been invoked so it can produce 404") + } + if w.Code != http.StatusNotFound { + t.Fatalf("expected handler 404 to win, got %d", w.Code) + } +} + +func TestRequireOwnershipOrRole_SkipsLookupWhenRBACDisabled(t *testing.T) { + // H1 regression: when enforcement is off, the lookup must not run at + // all. Hooking up RBAC pre-rollout used to add a hidden DB roundtrip + // to every mutating request even though the result was thrown away. + calls := 0 + lookup := func(c *gin.Context) (string, error) { + calls++ + return "someone-else", nil + } + w := rbacTestHarness(types.TenantRoleViewer, "u1", + RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(false))) + if w.Code != http.StatusOK { + t.Fatalf("fail-open should let the request through, got %d", w.Code) + } + if calls != 0 { + t.Fatalf("lookup must not run when EnableRBAC=false (got %d calls)", calls) + } +} + +func TestRequireOwnershipOrRole_CrossTenantSuperuserBypass(t *testing.T) { + // Cross-tenant superusers resolve to Admin in foreign tenants (see + // resolveTenantRole). For Owner-only gates we additionally let them + // through to preserve the pre-RBAC ability to administer any tenant. + calls := 0 + lookup := func(c *gin.Context) (string, error) { + calls++ + return "", nil + } + router := gin.New() + router.Use(func(c *gin.Context) { + ctx := c.Request.Context() + ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleAdmin) + ctx = context.WithValue(ctx, types.UserIDContextKey, "su1") + ctx = context.WithValue(ctx, types.UserContextKey, &types.User{ + ID: "su1", CanAccessAllTenants: true, + }) + c.Request = c.Request.WithContext(ctx) + c.Next() + }) + router.GET("/protected", + RequireOwnershipOrRole(types.TenantRoleOwner, lookup, cfgRBAC(true)), + func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{}) }, + ) + req := httptest.NewRequest(http.MethodGet, "/protected", nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("superuser must bypass Owner gate, got %d", w.Code) + } + if calls != 0 { + t.Fatalf("superuser bypass must skip lookup, got %d", calls) } } diff --git a/internal/router/router.go b/internal/router/router.go index 188ec5ec..e47b5c99 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -151,28 +151,28 @@ func NewRouter(params RouterParams) *gin.Engine { RegisterAuthRoutes(v1, params.AuthHandler) RegisterTenantRoutes(v1, params.TenantHandler, rbacGuards) RegisterKnowledgeBaseRoutes(v1, params.KBHandler, rbacGuards) - RegisterKnowledgeTagRoutes(v1, params.TagHandler) + RegisterKnowledgeTagRoutes(v1, params.TagHandler, rbacGuards) RegisterKnowledgeRoutes(v1, params.KnowledgeHandler, rbacGuards) - RegisterFAQRoutes(v1, params.FAQHandler) + RegisterFAQRoutes(v1, params.FAQHandler, rbacGuards) RegisterChunkRoutes(v1, params.ChunkHandler, rbacGuards) - RegisterSessionRoutes(v1, params.SessionHandler) - RegisterChatRoutes(v1, params.SessionHandler) - RegisterMessageRoutes(v1, params.MessageHandler) + RegisterSessionRoutes(v1, params.SessionHandler, rbacGuards) + RegisterChatRoutes(v1, params.SessionHandler, rbacGuards) + RegisterMessageRoutes(v1, params.MessageHandler, rbacGuards) RegisterModelRoutes(v1, params.ModelHandler, params.ModelCredentialsHandler, rbacGuards) RegisterEvaluationRoutes(v1, params.EvaluationHandler) RegisterInitializationRoutes(v1, params.InitializationHandler) RegisterSystemRoutes(v1, params.SystemHandler) RegisterMCPServiceRoutes(v1, params.MCPServiceHandler, params.MCPCredentialsHandler, rbacGuards) - RegisterWebSearchRoutes(v1, params.WebSearchHandler) + RegisterWebSearchRoutes(v1, params.WebSearchHandler, rbacGuards) RegisterWebSearchProviderRoutes(v1, params.WebSearchProviderHandler, params.WebSearchCredentialsHandler, rbacGuards) RegisterVectorStoreRoutes(v1, params.VectorStoreHandler, rbacGuards) RegisterCustomAgentRoutes(v1, params.CustomAgentHandler, rbacGuards) - RegisterSkillRoutes(v1, params.SkillHandler) + RegisterSkillRoutes(v1, params.SkillHandler, rbacGuards) RegisterOrganizationRoutes(v1, params.OrganizationHandler) RegisterIMChannelRoutes(v1, params.IMHandler, rbacGuards) RegisterDataSourceRoutes(v1, params.DataSourceHandler, params.DataSourceCredentialsHandler, rbacGuards) - RegisterWeKnoraCloudRoutes(v1, params.WeKnoraCloudHandler) - RegisterWikiPageRoutes(v1, params.WikiPageHandler) + RegisterWeKnoraCloudRoutes(v1, params.WeKnoraCloudHandler, rbacGuards) + RegisterWikiPageRoutes(v1, params.WikiPageHandler, rbacGuards) RegisterChunkerDebugRoutes(v1) } @@ -246,31 +246,35 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandl } // RegisterFAQRoutes 注册 FAQ 相关路由 -func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler) { +// +// FAQ entries are KB content: reads are Viewer+, all mutations +// (create / update / upsert / delete / batch field+tag updates, +// import display flag) are Contributor+. Search is read-only. +func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler, g *rbacGuards) { if handler == nil { return } faq := r.Group("/knowledge-bases/:id/faq") { - faq.GET("/entries", handler.ListEntries) - faq.GET("/entries/export", handler.ExportEntries) - faq.GET("/entries/:entry_id", handler.GetEntry) - faq.POST("/entries", handler.UpsertEntries) - faq.POST("/entry", handler.CreateEntry) - faq.PUT("/entries/:entry_id", handler.UpdateEntry) - faq.POST("/entries/:entry_id/similar-questions", handler.AddSimilarQuestions) + faq.GET("/entries", g.Viewer(), handler.ListEntries) + faq.GET("/entries/export", g.Viewer(), handler.ExportEntries) + faq.GET("/entries/:entry_id", g.Viewer(), handler.GetEntry) + faq.POST("/entries", g.Contributor(), handler.UpsertEntries) + faq.POST("/entry", g.Contributor(), handler.CreateEntry) + faq.PUT("/entries/:entry_id", g.Contributor(), handler.UpdateEntry) + faq.POST("/entries/:entry_id/similar-questions", g.Contributor(), handler.AddSimilarQuestions) // Unified batch update API - supports is_enabled, is_recommended, tag_id - faq.PUT("/entries/fields", handler.UpdateEntryFieldsBatch) - faq.PUT("/entries/tags", handler.UpdateEntryTagBatch) - faq.DELETE("/entries", handler.DeleteEntries) - faq.POST("/search", handler.SearchFAQ) + faq.PUT("/entries/fields", g.Contributor(), handler.UpdateEntryFieldsBatch) + faq.PUT("/entries/tags", g.Contributor(), handler.UpdateEntryTagBatch) + faq.DELETE("/entries", g.Contributor(), handler.DeleteEntries) + faq.POST("/search", g.Viewer(), handler.SearchFAQ) // FAQ import result display status - faq.PUT("/import/last-result/display", handler.UpdateLastImportResultDisplayStatus) + faq.PUT("/import/last-result/display", g.Contributor(), handler.UpdateLastImportResultDisplayStatus) } - // FAQ import progress route (outside of knowledge-base scope) + // FAQ import progress route (outside of knowledge-base scope) — Viewer+ faqImport := r.Group("/faq/import") { - faqImport.GET("/progress/:task_id", handler.GetImportProgress) + faqImport.GET("/progress/:task_id", g.Viewer(), handler.GetImportProgress) } } @@ -302,39 +306,49 @@ func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeB } } -// RegisterKnowledgeTagRoutes 注册知识库标签相关路由 -func RegisterKnowledgeTagRoutes(r *gin.RouterGroup, tagHandler *handler.TagHandler) { +// RegisterKnowledgeTagRoutes 注册知识库标签相关路由。 +// +// Tags are KB metadata: Viewer reads, Contributor writes. Per-KB +// ownership granularity for tags is out of scope for PR 2; this is +// purely role-based. +func RegisterKnowledgeTagRoutes(r *gin.RouterGroup, tagHandler *handler.TagHandler, g *rbacGuards) { if tagHandler == nil { return } kbTags := r.Group("/knowledge-bases/:id/tags") { - kbTags.GET("", tagHandler.ListTags) - kbTags.POST("", tagHandler.CreateTag) - kbTags.PUT("/:tag_id", tagHandler.UpdateTag) - kbTags.DELETE("/:tag_id", tagHandler.DeleteTag) + kbTags.GET("", g.Viewer(), tagHandler.ListTags) + kbTags.POST("", g.Contributor(), tagHandler.CreateTag) + kbTags.PUT("/:tag_id", g.Contributor(), tagHandler.UpdateTag) + kbTags.DELETE("/:tag_id", g.Contributor(), tagHandler.DeleteTag) } } -// RegisterMessageRoutes 注册消息相关的路由 -func RegisterMessageRoutes(r *gin.RouterGroup, handler *handler.MessageHandler) { - // 消息路由组 +// RegisterMessageRoutes 注册消息相关的路由。 +// +// Per-session ownership is already enforced inside each handler (the +// user must own the session). We add Viewer+ here so non-members +// (e.g. revoked accounts retained in the tenant for audit) cannot +// reach the endpoints at all once RBAC is on. +func RegisterMessageRoutes(r *gin.RouterGroup, handler *handler.MessageHandler, g *rbacGuards) { messages := r.Group("/messages") { - // 搜索历史对话(关键词 + 向量混合搜索) - messages.POST("/search", handler.SearchMessages) - // 获取聊天历史知识库的统计信息 - messages.GET("/chat-history-stats", handler.GetChatHistoryKBStats) - // 加载更早的消息,用于向上滚动加载 - messages.GET("/:session_id/load", handler.LoadMessages) - // 删除消息 - messages.DELETE("/:session_id/:id", handler.DeleteMessage) + messages.POST("/search", g.Viewer(), handler.SearchMessages) + messages.GET("/chat-history-stats", g.Viewer(), handler.GetChatHistoryKBStats) + messages.GET("/:session_id/load", g.Viewer(), handler.LoadMessages) + messages.DELETE("/:session_id/:id", g.Viewer(), handler.DeleteMessage) } } -// RegisterSessionRoutes 注册路由 -func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler) { - sessions := r.Group("/sessions") +// RegisterSessionRoutes 注册路由。 +// +// Sessions are per-user resources; the handler enforces user ownership. +// We gate at Viewer+ to keep non-members out once RBAC is on, matching +// the message routes above. A future refactor can introduce +// per-session ownership in the middleware layer the same way KB/agent +// routes do today. +func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGuards) { + sessions := r.Group("/sessions", g.Viewer()) { sessions.POST("", handler.CreateSession) sessions.DELETE("/batch", handler.BatchDeleteSessions) @@ -356,21 +370,23 @@ func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler) { } } -// RegisterChatRoutes 注册路由 -func RegisterChatRoutes(r *gin.RouterGroup, handler *session.Handler) { - knowledgeChat := r.Group("/knowledge-chat") +// RegisterChatRoutes 注册路由。Chat endpoints are tenant-member usage +// surfaces; Viewer+ is sufficient because per-session/per-agent +// authorisation is enforced inside the handlers. +func RegisterChatRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGuards) { + knowledgeChat := r.Group("/knowledge-chat", g.Viewer()) { knowledgeChat.POST("/:session_id", handler.KnowledgeQA) } // Agent-based chat - agentChat := r.Group("/agent-chat") + agentChat := r.Group("/agent-chat", g.Viewer()) { agentChat.POST("/:session_id", handler.AgentQA) } // 新增知识检索接口,不需要session_id - knowledgeSearch := r.Group("/knowledge-search") + knowledgeSearch := r.Group("/knowledge-search", g.Viewer()) { knowledgeSearch.POST("", handler.SearchKnowledge) } @@ -555,20 +571,21 @@ func RegisterMCPServiceRoutes( } // RegisterWebSearchRoutes registers web search routes -func RegisterWebSearchRoutes(r *gin.RouterGroup, webSearchHandler *handler.WebSearchHandler) { - // Web search providers +func RegisterWebSearchRoutes(r *gin.RouterGroup, webSearchHandler *handler.WebSearchHandler, g *rbacGuards) { + // Web search providers — Viewer+ (read-only listing of provider catalog). webSearch := r.Group("/web-search") { - // Get available providers - webSearch.GET("/providers", webSearchHandler.GetProviders) + webSearch.GET("/providers", g.Viewer(), webSearchHandler.GetProviders) } } -// RegisterWebSearchProviderRoutes registers CRUD routes for web search provider configurations. +// RegisterWebSearchProviderRoutes registers CRUD routes for web search +// provider configurations. // -// Web search providers hold tenant-level external API credentials -// (Google/Bing/Tavily/...); reads are Viewer+, all writes / connection -// tests / credential subresource are Admin+. +// Provider rows hold external service credentials (Bing, Tavily, Google, +// etc.); reads are Viewer+, all mutations / connection tests (which +// probe external systems with stored credentials) and the per-field +// credential subresource are Admin+. func RegisterWebSearchProviderRoutes( r *gin.RouterGroup, h *handler.WebSearchProviderHandler, @@ -648,12 +665,16 @@ func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomA r.GET("/agents/:id/suggested-questions", g.Viewer(), agentHandler.GetSuggestedQuestions) } -// RegisterSkillRoutes registers skill routes -func RegisterSkillRoutes(r *gin.RouterGroup, skillHandler *handler.SkillHandler) { +// RegisterSkillRoutes registers skill routes. +// +// PR 2 currently only exposes a read-only `ListSkills`; gated to +// Viewer+. Future skill upload / enable endpoints must use Admin+ since +// skills run sandboxed code on tenant resources. +func RegisterSkillRoutes(r *gin.RouterGroup, skillHandler *handler.SkillHandler, g *rbacGuards) { skills := r.Group("/skills") { - // List all preloaded skills - skills.GET("", skillHandler.ListSkills) + // List all preloaded skills — Viewer+ + skills.GET("", g.Viewer(), skillHandler.ListSkills) } } @@ -1082,38 +1103,47 @@ func RegisterDataSourceRoutes( } // RegisterWeKnoraCloudRoutes 注册 WeKnoraCloud 初始化路由 -func RegisterWeKnoraCloudRoutes(r *gin.RouterGroup, handler *handler.WeKnoraCloudHandler) { - r.POST("/weknoracloud/credentials", handler.SaveCredentials) - r.GET("/models/weknoracloud/status", handler.Status) +// RegisterWeKnoraCloudRoutes registers the WeKnoraCloud credential +// management endpoints. SaveCredentials persists external SaaS keys +// for the tenant (Admin+), Status is a low-risk readiness probe (Viewer+). +func RegisterWeKnoraCloudRoutes(r *gin.RouterGroup, handler *handler.WeKnoraCloudHandler, g *rbacGuards) { + r.POST("/weknoracloud/credentials", g.Admin(), handler.SaveCredentials) + r.GET("/models/weknoracloud/status", g.Viewer(), handler.Status) } -// RegisterWikiPageRoutes registers wiki page related routes -func RegisterWikiPageRoutes(r *gin.RouterGroup, wikiHandler *handler.WikiPageHandler) { +// 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) are Contributor+. +// Per-KB ownership granularity for individual pages is a follow-up, +// same as plain knowledge entries. +func RegisterWikiPageRoutes(r *gin.RouterGroup, wikiHandler *handler.WikiPageHandler, g *rbacGuards) { wiki := r.Group("/knowledgebase/:kb_id/wiki") { // Page CRUD - wiki.GET("/pages", wikiHandler.ListPages) - wiki.POST("/pages", wikiHandler.CreatePage) - wiki.GET("/pages/*slug", wikiHandler.GetPage) - wiki.PUT("/pages/*slug", wikiHandler.UpdatePage) - wiki.DELETE("/pages/*slug", wikiHandler.DeletePage) + wiki.GET("/pages", g.Viewer(), wikiHandler.ListPages) + wiki.POST("/pages", g.Contributor(), wikiHandler.CreatePage) + wiki.GET("/pages/*slug", g.Viewer(), wikiHandler.GetPage) + wiki.PUT("/pages/*slug", g.Contributor(), wikiHandler.UpdatePage) + wiki.DELETE("/pages/*slug", g.Contributor(), wikiHandler.DeletePage) // Special pages - wiki.GET("/index", wikiHandler.GetIndex) - wiki.GET("/log", wikiHandler.GetLog) + wiki.GET("/index", g.Viewer(), wikiHandler.GetIndex) + wiki.GET("/log", g.Viewer(), wikiHandler.GetLog) // Graph and stats - wiki.GET("/graph", wikiHandler.GetGraph) - wiki.GET("/stats", wikiHandler.GetStats) + wiki.GET("/graph", g.Viewer(), wikiHandler.GetGraph) + wiki.GET("/stats", g.Viewer(), wikiHandler.GetStats) // Search and maintenance - wiki.GET("/search", wikiHandler.SearchPages) - wiki.POST("/rebuild-links", wikiHandler.RebuildLinks) - wiki.GET("/lint", wikiHandler.Lint) - wiki.POST("/auto-fix", wikiHandler.AutoFix) + wiki.GET("/search", g.Viewer(), wikiHandler.SearchPages) + wiki.POST("/rebuild-links", g.Contributor(), wikiHandler.RebuildLinks) + wiki.GET("/lint", g.Viewer(), wikiHandler.Lint) + wiki.POST("/auto-fix", g.Contributor(), wikiHandler.AutoFix) // Issues - wiki.GET("/issues", wikiHandler.ListIssues) - wiki.PUT("/issues/:issue_id/status", wikiHandler.UpdateIssueStatus) + wiki.GET("/issues", g.Viewer(), wikiHandler.ListIssues) + wiki.PUT("/issues/:issue_id/status", g.Contributor(), wikiHandler.UpdateIssueStatus) } } diff --git a/internal/types/context_helpers.go b/internal/types/context_helpers.go index fb1b8dd9..0d053df7 100644 --- a/internal/types/context_helpers.go +++ b/internal/types/context_helpers.go @@ -54,6 +54,33 @@ func UserIDFromContext(ctx context.Context) (string, bool) { return v, ok && v != "" } +// IsSyntheticUserID reports whether id refers to the synthetic system +// user that the X-API-Key auth path attaches to each tenant +// (User.ID = "system-"). These users have no real human +// behind them and no tenant_members row, so RBAC ownership matching +// against them is never meaningful — service-layer code that records +// "the creator" should skip storing this ID and treat the resource as +// tenant-owned instead. +// +// Kept minimal on purpose: the prefix and "all digits afterwards" +// invariant comes from middleware/auth.go's User construction for the +// API-key branch. If that prefix changes, update both sides. +func IsSyntheticUserID(id string) bool { + const prefix = "system-" + if len(id) <= len(prefix) { + return false + } + if id[:len(prefix)] != prefix { + return false + } + for _, r := range id[len(prefix):] { + if r < '0' || r > '9' { + return false + } + } + return true +} + // TenantRoleFromContext extracts the caller's TenantRole in the currently // active tenant. Returns TenantRoleViewer when the key is absent so that // callers fail closed (least privilege) if the auth middleware did not diff --git a/internal/types/context_helpers_test.go b/internal/types/context_helpers_test.go index 1e156726..a5457e9a 100644 --- a/internal/types/context_helpers_test.go +++ b/internal/types/context_helpers_test.go @@ -4,6 +4,35 @@ import ( "testing" ) +func TestIsSyntheticUserID(t *testing.T) { + cases := []struct { + name string + id string + want bool + }{ + {"matches system-", "system-1", true}, + {"matches large tenant id", "system-1234567890", true}, + {"empty string", "", false}, + {"prefix only", "system-", false}, + {"missing prefix", "1", false}, + {"non-digit suffix", "system-abc", false}, + {"mixed suffix", "system-1a2", false}, + {"prefix with space", "system- 1", false}, + {"uppercase prefix", "SYSTEM-1", false}, + {"normal uuid user", "550e8400-e29b-41d4-a716-446655440000", false}, + {"system uuid trap", "system-550e8400", false}, // contains '-' + } + for _, c := range cases { + c := c + t.Run(c.name, func(t *testing.T) { + got := IsSyntheticUserID(c.id) + if got != c.want { + t.Fatalf("IsSyntheticUserID(%q) = %v, want %v", c.id, got, c.want) + } + }) + } +} + func TestLanguageLocaleName(t *testing.T) { tests := []struct { name string diff --git a/internal/types/custom_agent.go b/internal/types/custom_agent.go index c66c89e1..ff866e0c 100644 --- a/internal/types/custom_agent.go +++ b/internal/types/custom_agent.go @@ -76,9 +76,15 @@ type CustomAgent struct { // Created by user ID CreatedBy string `yaml:"created_by" json:"created_by" gorm:"type:varchar(36)"` // RunnableByViewer controls whether users with TenantRoleViewer can - // start chat sessions against this agent. Defaults to true so viewers - // can still consume published agents; admins toggle it off for agents - // whose tools should be restricted to contributors and above. + // run this agent IN AGENT MODE (i.e. with tools, MCP, sandboxed code + // execution, etc.). Plain RAG / Wiki QA sessions against the same + // agent are unaffected — they don't invoke tools, so restricting + // them buys no security and would just block Viewer consumption of + // published agents. Defaults to true; admins toggle it off for + // agents whose tools should be restricted to contributors and above. + // + // Enforcement lives in handler/session/qa.go's AgentQA, gated behind + // cfg.Tenant.EnableRBAC like every other PR2 check. // // Note: no GORM `default:true` tag here. With a plain `bool` field that // tag causes GORM to treat Go's zero value (false) as "unspecified" and