Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

chore(rbac): update default behavior for tenant RBAC configuration

wizardchen7444c2190d45
diff --git a/.env.example b/.env.example
index ef45639a9..42ef3c203 100644
--- a/.env.example
+++ b/.env.example
@@ -433,11 +433,11 @@ WEKNORA_SANDBOX_TIMEOUT=60
# ========== Tenant / RBAC 配置 ==========
# 启用租户级 RBAC(基于 tenant_members 表的角色强制鉴权)。
-# - false(默认):观察模式,记录但不拦截,便于上线初期审计角色分配
-# - true:开启后,无 active membership 或角色不足的请求会被 403 拒绝
+# - true(默认):开启后,无 active membership 或角色不足的请求会被 403 拒绝
+# - false:观察模式,记录但不拦截,仅用于上线初期审计角色分配的灰度窗口
# 详细灰度方案见 docs/rbac.md。
# 注意:开发环境用 Air 热重载时,修改本变量需重启 dev 脚本(仅源代码变更才重读 .env)。
-# WEKNORA_TENANT_ENABLE_RBAC=false
+# WEKNORA_TENANT_ENABLE_RBAC=true
# 单个非超管用户可自助创建(成为 Owner)的租户数上限。
# 仅统计 Owner 角色——被邀请为 Admin/Editor/Viewer 的不计入。
diff --git a/docker-compose.yml b/docker-compose.yml
index 3eb0ce67e..2049b1483 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -171,7 +171,7 @@ services:
- WEKNORA_AGENT_LLM_TIMEOUT=${WEKNORA_AGENT_LLM_TIMEOUT:-}
- WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT=${WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT:-}
# Tenant / RBAC(详见 docs/rbac.md 与 .env.example 注释)
- # - WEKNORA_TENANT_ENABLE_RBAC: 是否启用租户角色强制鉴权(true / false),默认 false
+ # - WEKNORA_TENANT_ENABLE_RBAC: 是否启用租户角色强制鉴权(true / false),默认 true
# - WEKNORA_TENANT_MAX_OWNED_PER_USER: 单个非超管自助创建租户的上限
# >0 强制限额;=0 走 handler 默认;<0 关闭限额(不建议共享部署使用)
- WEKNORA_TENANT_ENABLE_RBAC=${WEKNORA_TENANT_ENABLE_RBAC:-}
diff --git a/docs/rbac.md b/docs/rbac.md
index 7e8b2b175..836fe9836 100644
--- a/docs/rbac.md
+++ b/docs/rbac.md
@@ -5,8 +5,9 @@ feature out without breaking existing deployments, and how to audit
the system once it is on.
> Status: shipped behind a feature flag (`tenant.enable_rbac`,
-> default `false`). Schema and `tenant_members` rows are populated
-> on every install; enforcement is opt-in.
+> default `true`). Schema and `tenant_members` rows are populated
+> on every install; operators may opt into a logging-only rollout
+> window by setting the flag to `false`.
## Why this exists
@@ -69,7 +70,7 @@ JWT / API-key ──► auth ──► │ tenant_members │
│ │
▼ ▼
┌──────────────────────┐ ┌──────────────────────┐
- │ false (default) │ │ true │
+ │ false │ │ true (default) │
│ role logged but │ │ role enforced; │
│ not enforced; │ │ denials emit a 403 │
│ ownership lookups │ │ AND a durable row │
@@ -77,7 +78,7 @@ JWT / API-key ──► auth ──► │ tenant_members │
└──────────────────────┘ └──────────────────────┘
```
-When `tenant.enable_rbac=false` (the shipped default):
+When `tenant.enable_rbac=false` (the opt-in rollout window):
- `RequireRole` middleware logs the would-be reject and lets the
request through (`[rbac] role insufficient (logged but not
@@ -105,8 +106,9 @@ YAML (`config/config.yaml`):
```yaml
tenant:
- # Default false. Flip to true once role assignments have been audited.
- enable_rbac: false
+ # Default true. Set to false for a logging-only rollout window while
+ # role assignments are being audited; flip back once verified.
+ enable_rbac: true
# Optional: leaves the existing cross-tenant superuser flag in place.
enable_cross_tenant_access: false
@@ -256,10 +258,13 @@ The same playbook a self-host operator (or the Tencent/WeKnora repo
itself) should follow when promoting a deployment from "logged" to
"enforced":
-1. **Upgrade.** `tenant.enable_rbac=false` (default) → schema lands,
- `tenant_members` is backfilled (one Owner per tenant, the rest
- Contributor), `creator_id` populated on every KB. No behaviour
- change yet.
+1. **Upgrade.** Set `tenant.enable_rbac=false` (or
+ `WEKNORA_TENANT_ENABLE_RBAC=false`) before restarting on the new
+ release if you want a logging-only window — the default is now
+ `true`, so skipping this step jumps straight to enforcement.
+ Either way: schema lands, `tenant_members` is backfilled (one
+ Owner per tenant, the rest Contributor), `creator_id` populated
+ on every KB.
2. **Audit the membership.** Call
`GET /api/v1/tenants/:id/members` (Admin+) and confirm:
- Exactly one Owner per tenant.
@@ -272,9 +277,9 @@ itself) should follow when promoting a deployment from "logged" to
insufficient (logged but not enforced)` lines. These tell you
exactly which production calls *would* 403 if you flipped the
flag now. Fix any user role that produces unexpected denials.
-4. **Flip the flag.** Set `tenant.enable_rbac=true` (or
- `WEKNORA_TENANT_ENABLE_RBAC=true`). Restart the app. From this
- point on:
+4. **Flip the flag back on.** Remove the `tenant.enable_rbac=false`
+ override (or set it back to `true`) and restart the app. From
+ this point on:
- Insufficient role → 403.
- `audit_logs` records every reject (subject to dedup).
5. **Optional — enable invite-only.** If you've moved off self-serve
diff --git a/internal/config/config.go b/internal/config/config.go
index 498d0cc4d..4a568897a 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -178,10 +178,15 @@ type TenantConfig struct {
// EnableCrossTenantAccess enables cross-tenant access for users with permission
EnableCrossTenantAccess bool `yaml:"enable_cross_tenant_access" json:"enable_cross_tenant_access"`
// EnableRBAC turns on tenant-level role enforcement (issue #1303).
- // Default false — the schema and tenant_members rows ship in a release
- // where role lookups are observed but not enforced; flip to true once
- // role assignments have been audited.
- EnableRBAC bool `yaml:"enable_rbac" json:"enable_rbac"`
+ // Pointer so we can distinguish "unset" from "explicit false":
+ // nil — fall back to the built-in default (true) applied
+ // by applyAuthAndTenantDefaults.
+ // pointer false — operators opted into the logging-only rollout
+ // window (set via config.yaml `enable_rbac: false`
+ // or env `WEKNORA_TENANT_ENABLE_RBAC=false`).
+ // pointer true — enforcement on (the new default).
+ // Read through IsRBACEnforced so callers stay nil-safe.
+ EnableRBAC *bool `yaml:"enable_rbac" json:"enable_rbac"`
// MaxOwnedPerUser caps how many tenants a single non-superuser can
// create (and Own) via self-service POST /tenants. Counts only Owner
// memberships so being invited as Admin/Editor/Viewer in another
@@ -198,6 +203,19 @@ type TenantConfig struct {
MaxOwnedPerUser int `yaml:"max_owned_per_user" json:"max_owned_per_user" mapstructure:"max_owned_per_user"`
}
+// IsRBACEnforced reports whether tenant-level role enforcement is
+// active. Nil receiver or nil EnableRBAC pointer means "operator did
+// not opt out", which after applyAuthAndTenantDefaults is the new
+// default (true). Callers that need to treat a nil *Config as
+// fail-open (legacy behaviour) should keep their own `cfg != nil`
+// short-circuit before invoking this helper.
+func (t *TenantConfig) IsRBACEnforced() bool {
+ if t == nil || t.EnableRBAC == nil {
+ return true
+ }
+ return *t.EnableRBAC
+}
+
// AuditConfig governs durable audit log behaviour. Writes happen on
// every member-management mutation and on RBAC denials (when
// EnableRBAC is true); the table grows monotonically unless this
@@ -516,7 +534,7 @@ func LoadConfig() (*Config, error) {
// "I edited .env but the gates still aren't firing" trap obvious
// from the first console line. Printf rather than logger because
// LoadConfig runs before the logger sink is wired in the dig graph.
- rbacOn := cfg.Tenant != nil && cfg.Tenant.EnableRBAC
+ rbacOn := cfg.Tenant.IsRBACEnforced()
xtAccess := cfg.Tenant != nil && cfg.Tenant.EnableCrossTenantAccess
fmt.Printf(
"[config] tenant RBAC enforcement: enable_rbac=%v cross_tenant_access=%v "+
@@ -704,7 +722,9 @@ func applyAgentEnvOverrides(cfg *Config) {
//
// Defaults:
// - auth.registration_mode -> "self_serve" (preserves pre-RBAC behaviour)
-// - tenant.enable_rbac -> false (rolled out in two steps; flip later)
+// - tenant.enable_rbac -> true (enforce role checks unless an
+// operator explicitly opts into the logging-only rollout window via
+// config.yaml `enable_rbac: false` or `WEKNORA_TENANT_ENABLE_RBAC=false`).
//
// Env overrides (when set and non-empty):
// - WEKNORA_TENANT_ENABLE_RBAC ("true"/"false", case-insensitive)
@@ -743,7 +763,14 @@ func applyAuthAndTenantDefaults(cfg *Config) {
}
if value := strings.TrimSpace(os.Getenv("WEKNORA_TENANT_ENABLE_RBAC")); value != "" {
- cfg.Tenant.EnableRBAC = strings.EqualFold(value, "true")
+ v := strings.EqualFold(value, "true")
+ cfg.Tenant.EnableRBAC = &v
+ }
+ if cfg.Tenant.EnableRBAC == nil {
+ // Default: enforce. Operators opt out of enforcement explicitly
+ // via config.yaml `enable_rbac: false` or the env override.
+ on := true
+ cfg.Tenant.EnableRBAC = &on
}
if value := strings.TrimSpace(os.Getenv("WEKNORA_TENANT_MAX_OWNED_PER_USER")); value != "" {
diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go
index 0cac5c234..6e84c1326 100644
--- a/internal/handler/session/qa.go
+++ b/internal/handler/session/qa.go
@@ -553,7 +553,7 @@ func (h *Handler) AgentQA(c *gin.Context) {
if agentModeEnabled && reqCtx.customAgent != nil && !reqCtx.customAgent.RunnableByViewer {
role := types.TenantRoleFromContext(reqCtx.ctx)
if !role.HasPermission(types.TenantRoleContributor) {
- if h.config != nil && h.config.Tenant != nil && h.config.Tenant.EnableRBAC {
+ if h.config != nil && h.config.Tenant.IsRBACEnforced() {
logger.Warnf(reqCtx.ctx,
"[rbac] agent run blocked: viewer cannot run runnable_by_viewer=false agent: agent=%s role=%s",
reqCtx.customAgent.ID, role)
diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go
index 02834b1b3..6c38db6f9 100644
--- a/internal/middleware/auth.go
+++ b/internal/middleware/auth.go
@@ -345,7 +345,7 @@ func resolveTenantRole(
}
// 4. 兜底:根据 EnableRBAC 决定 fail-closed 还是 fail-open
- if cfg != nil && cfg.Tenant != nil && cfg.Tenant.EnableRBAC {
+ if cfg != nil && cfg.Tenant.IsRBACEnforced() {
logger.Warnf(ctx,
"[auth] resolveTenantRole step4 fail-closed (EnableRBAC=true): user=%s tenant=%d",
user.ID, targetTenantID)
diff --git a/internal/middleware/auth_role_test.go b/internal/middleware/auth_role_test.go
index 53a04df07..43eefeed5 100644
--- a/internal/middleware/auth_role_test.go
+++ b/internal/middleware/auth_role_test.go
@@ -135,7 +135,7 @@ func (f *fakeMemberService) RemoveMember(ctx context.Context, userID string, ten
var _ interfaces.TenantMemberService = (*fakeMemberService)(nil)
func cfgWithRBAC(enabled bool) *config.Config {
- return &config.Config{Tenant: &config.TenantConfig{EnableRBAC: enabled}}
+ return &config.Config{Tenant: &config.TenantConfig{EnableRBAC: &enabled}}
}
func TestResolveTenantRole_ActiveMembershipWins(t *testing.T) {
diff --git a/internal/middleware/rbac.go b/internal/middleware/rbac.go
index a9f459c94..b2495fea7 100644
--- a/internal/middleware/rbac.go
+++ b/internal/middleware/rbac.go
@@ -207,7 +207,7 @@ func RequireOwnershipOrRole(min types.TenantRole, lookup CreatorLookup, cfg *con
// 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
+ return cfg != nil && cfg.Tenant.IsRBACEnforced()
}
// isCrossTenantSuperuser was moved to access.go (renamed to
diff --git a/internal/middleware/rbac_test.go b/internal/middleware/rbac_test.go
index 8d4f4b6be..24268735d 100644
--- a/internal/middleware/rbac_test.go
+++ b/internal/middleware/rbac_test.go
@@ -40,7 +40,7 @@ func rbacTestHarness(role types.TenantRole, userID string, mw gin.HandlerFunc) *
}
func cfgRBAC(enabled bool) *config.Config {
- return &config.Config{Tenant: &config.TenantConfig{EnableRBAC: enabled}}
+ return &config.Config{Tenant: &config.TenantConfig{EnableRBAC: &enabled}}
}
// cfgRBACWithCrossTenant returns a config with both per-tenant RBAC
@@ -49,7 +49,7 @@ func cfgRBAC(enabled bool) *config.Config {
// so cross-tenant superuser tests need this rather than plain cfgRBAC.
func cfgRBACWithCrossTenant(enabled bool) *config.Config {
return &config.Config{Tenant: &config.TenantConfig{
- EnableRBAC: enabled,
+ EnableRBAC: &enabled,
EnableCrossTenantAccess: true,
}}
}