feat(rbac): add tenant_members schema and auth wiring (PR 1 of 3, #1303)

Lay the foundation for tenant-level RBAC without enforcing it yet.
Schema, types, middleware lookup, and login-flow shape changes ship now;
RequireRole/route annotations and member-management endpoints follow in
PR 2 and PR 3.

Highlights:
- New tenant_members table (Postgres + SQLite) with (user_id, tenant_id)
  unique key and (owner|admin|contributor|viewer) role values. Migration
  000043 backfills one row per existing user, marking the earliest-created
  active user in each tenant as Owner and the rest as Contributor.
- KnowledgeBase.creator_id and CustomAgent.runnable_by_viewer added so
  PR 2 can wire ownership-based and Viewer-runtime checks.
- Auth middleware loads the active TenantMember row, sets a new
  TenantRoleContextKey, and falls back via three escape hatches:
  cross-tenant superusers (CanAccessAllTenants) get Admin in the target
  tenant; orphan tenants (zero members) auto-promote the first authenticating
  human to Owner; and when tenant.enable_rbac is false (the v1 default)
  unmatched lookups fail open with Admin to preserve current behaviour.
- Register / OIDC provisioning now insert an Owner membership for the
  registrant via TenantMemberService.EnsureOwner.
- LoginResponse renamed tenant -> active_tenant and gained a memberships
  array. POST /auth/switch-tenant issues a fresh token pair scoped to a
  target membership; GET /auth/config exposes auth.registration_mode for
  the frontend register-tab gating.
- New config keys: auth.registration_mode (self_serve | invite_only,
  defaults to self_serve) and tenant.enable_rbac (defaults to false).
  Both have WEKNORA_* env overrides.
- Frontend store persists memberships and exposes currentTenantRole;
  Login.vue calls /auth/config and hides the Register tab in invite_only
  mode. Go SDK types updated to match the new LoginResponse shape.
This commit is contained in:
wizardchen
2026-05-13 19:47:48 +08:00
committed by lyingbug
parent 3214e3d952
commit 7f7a48880f
26 changed files with 1295 additions and 46 deletions
+4
View File
@@ -16,6 +16,10 @@ const (
UserContextKey ContextKey = "User"
// UserIDContextKey is the context key for user ID
UserIDContextKey ContextKey = "UserID"
// TenantRoleContextKey is the context key for the caller's TenantRole
// in the currently active tenant (loaded by the auth middleware from
// the tenant_members table). See TenantRoleFromContext.
TenantRoleContextKey ContextKey = "TenantRole"
// SessionTenantIDContextKey is the context key for session owner's tenant ID.
// When set (e.g. in pipeline with shared agent), session/message lookups use this instead of TenantIDContextKey.
SessionTenantIDContextKey ContextKey = "SessionTenantID"
+12
View File
@@ -54,6 +54,18 @@ func UserIDFromContext(ctx context.Context) (string, bool) {
return v, ok && v != ""
}
// 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
// populate the role for some reason.
func TenantRoleFromContext(ctx context.Context) TenantRole {
v, ok := ctx.Value(TenantRoleContextKey).(TenantRole)
if !ok || !v.IsValid() {
return TenantRoleViewer
}
return v
}
// SessionTenantIDFromContext extracts the session-owner tenant ID from ctx.
// Falls back to TenantIDFromContext when the session key is absent.
func SessionTenantIDFromContext(ctx context.Context) (uint64, bool) {
+5
View File
@@ -75,6 +75,11 @@ type CustomAgent struct {
TenantID uint64 `yaml:"tenant_id" json:"tenant_id" gorm:"primaryKey"`
// 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.
RunnableByViewer bool `yaml:"runnable_by_viewer" json:"runnable_by_viewer" gorm:"default:true"`
// Agent configuration
Config CustomAgentConfig `yaml:"config" json:"config" gorm:"type:json"`
@@ -0,0 +1,50 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// TenantMemberRepository persists (user, tenant) membership rows that
// carry the per-tenant TenantRole.
//
// All methods operate on active rows only (deleted_at IS NULL) unless the
// docstring explicitly says otherwise. Soft deletion is handled by GORM
// via the DeletedAt field on TenantMember.
type TenantMemberRepository interface {
// Create inserts a new active membership row. Caller is responsible
// for ensuring no other active row exists for the same (user, tenant)
// pair; the partial unique index will return a conflict error otherwise.
Create(ctx context.Context, member *types.TenantMember) error
// Get returns the active membership for the given (user, tenant) pair,
// or (nil, nil) if no such row exists.
Get(ctx context.Context, userID string, tenantID uint64) (*types.TenantMember, error)
// ListByUser returns every active membership owned by the given user,
// ordered by joined_at ascending.
ListByUser(ctx context.Context, userID string) ([]*types.TenantMember, error)
// ListByTenant returns every active membership inside the given tenant,
// ordered by joined_at ascending.
ListByTenant(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error)
// UpdateRole changes the role of an existing active membership. Returns
// gorm.ErrRecordNotFound if no active row matches.
UpdateRole(ctx context.Context, userID string, tenantID uint64, role types.TenantRole) error
// SoftDelete marks the active membership as deleted. The user record
// itself is untouched.
SoftDelete(ctx context.Context, userID string, tenantID uint64) error
// CountActiveOwners reports how many active rows in the tenant carry
// the owner role. Used by service-layer invariant checks ("cannot
// remove the last owner").
CountActiveOwners(ctx context.Context, tenantID uint64) (int64, error)
// HasAnyMembers reports whether the tenant has at least one active
// membership. Used by the auth middleware to decide whether to
// auto-promote the first authenticating human in an API-key-only tenant.
HasAnyMembers(ctx context.Context, tenantID uint64) (bool, error)
}
@@ -0,0 +1,50 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// TenantMemberService is the business-logic layer over TenantMemberRepository.
// It enforces tenant-RBAC invariants such as "every tenant with members must
// keep at least one active Owner". HTTP handlers and other services call this
// interface rather than the repository directly so the invariants cannot be
// silently bypassed.
type TenantMemberService interface {
// AddMember inserts a new active membership row. Returns an error if
// (user, tenant) already has an active membership.
AddMember(ctx context.Context, userID string, tenantID uint64, role types.TenantRole, invitedBy *string) (*types.TenantMember, error)
// EnsureOwner is an idempotent helper used by the registration flow:
// if the user already has an active membership in the tenant, return
// it; otherwise create one with role=owner. This is the common path
// for self-service registration where the registrant becomes the
// Owner of the tenant their account just created.
EnsureOwner(ctx context.Context, userID string, tenantID uint64) (*types.TenantMember, error)
// GetMembership returns the active (user, tenant) membership, or
// (nil, nil) if no such row exists.
GetMembership(ctx context.Context, userID string, tenantID uint64) (*types.TenantMember, error)
// ListByUser returns every active membership owned by the user.
ListByUser(ctx context.Context, userID string) ([]*types.TenantMember, error)
// ListByTenant returns every active membership inside the tenant.
ListByTenant(ctx context.Context, tenantID uint64) ([]*types.TenantMember, error)
// HasAnyMembers reports whether the tenant has at least one active
// member. The auth middleware uses this to recover orphan tenants
// (e.g. API-key-only tenants that never had a human member): the
// first human authenticating into such a tenant is auto-promoted
// to Owner.
HasAnyMembers(ctx context.Context, tenantID uint64) (bool, error)
// UpdateRole changes the role of an existing membership while
// enforcing the "cannot demote the last active Owner" invariant.
UpdateRole(ctx context.Context, userID string, tenantID uint64, newRole types.TenantRole) error
// RemoveMember soft-deletes the membership while enforcing the
// "cannot remove the last active Owner" invariant.
RemoveMember(ctx context.Context, userID string, tenantID uint64) error
}
+5
View File
@@ -34,6 +34,11 @@ type UserService interface {
ValidatePassword(ctx context.Context, userID string, password string) error
// GenerateTokens generates access and refresh tokens for user
GenerateTokens(ctx context.Context, user *types.User) (accessToken, refreshToken string, err error)
// SwitchTenant issues a new token pair scoped to targetTenantID and
// returns the corresponding LoginResponse. The caller's previous
// refresh token (passed in for revocation) is invalidated. Membership
// is verified via the TenantMember service before tokens are issued.
SwitchTenant(ctx context.Context, user *types.User, targetTenantID uint64, currentRefreshToken string) (*types.LoginResponse, error)
// ValidateToken validates an access token
ValidateToken(ctx context.Context, token string) (*types.User, error)
// RefreshToken refreshes access token using refresh token
+6
View File
@@ -51,6 +51,12 @@ type KnowledgeBase struct {
Description string `yaml:"description" json:"description"`
// Tenant ID
TenantID uint64 `yaml:"tenant_id" json:"tenant_id"`
// CreatorID records the user ID of whoever originally created the KB.
// Used by the tenant-level RBAC middleware to let Contributors edit
// their own KBs without granting them access to everyone else's.
// Nullable for backward compatibility with rows created before the
// RBAC migration backfilled the column to the tenant Owner.
CreatorID string `yaml:"creator_id" json:"creator_id" gorm:"type:varchar(36);index"`
// Chunking configuration
ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config" gorm:"type:json"`
// Image processing configuration
+121
View File
@@ -0,0 +1,121 @@
package types
import (
"time"
"gorm.io/gorm"
)
// TenantRole represents a user's role inside a single tenant.
//
// Tenant roles govern intra-tenant authority (who can create/edit/delete
// resources, manage tenant settings, etc.) and are orthogonal to the
// OrgMemberRole defined in organization.go, which governs cross-tenant
// sharing. A user may therefore carry different TenantRole values in
// different tenants (one TenantMember row per (user, tenant) pair).
type TenantRole string
const (
// TenantRoleOwner has full control over the tenant, including tenant
// deletion, ownership transfer, and rotating the tenant API key.
TenantRoleOwner TenantRole = "owner"
// TenantRoleAdmin manages users, integrations, and tenant-scoped
// configuration such as model providers, vector stores, MCP services
// and IM channels, but cannot delete the tenant or change Owners.
TenantRoleAdmin TenantRole = "admin"
// TenantRoleContributor can create knowledge bases and agents, and edit
// the ones they created. They have read access to everything else in
// the tenant.
TenantRoleContributor TenantRole = "contributor"
// TenantRoleViewer has read-only access to tenant resources and can
// run agents that are explicitly marked as runnable by viewers.
TenantRoleViewer TenantRole = "viewer"
)
// tenantRoleLevel maps each role to a numeric level used for hierarchy
// comparisons. Higher means more privileged. Levels are spaced by 10 so
// new roles can be inserted between existing ones if needed.
var tenantRoleLevel = map[TenantRole]int{
TenantRoleOwner: 40,
TenantRoleAdmin: 30,
TenantRoleContributor: 20,
TenantRoleViewer: 10,
}
// IsValid reports whether r is one of the four defined tenant roles.
func (r TenantRole) IsValid() bool {
_, ok := tenantRoleLevel[r]
return ok
}
// Level returns the numeric privilege level of the role. Unknown roles
// return 0, which is strictly less than any defined role.
func (r TenantRole) Level() int {
return tenantRoleLevel[r]
}
// HasPermission reports whether r is at least as privileged as required.
// Used by RequireRole-style middleware to gate endpoints.
func (r TenantRole) HasPermission(required TenantRole) bool {
return r.Level() >= required.Level()
}
// TenantMemberStatus enumerates the lifecycle states of a membership row.
type TenantMemberStatus string
const (
// TenantMemberStatusActive is the normal membership state; the user
// can authenticate into the tenant and is subject to their role.
TenantMemberStatusActive TenantMemberStatus = "active"
// TenantMemberStatusInvited represents a pending invitation that has
// not yet been accepted. The auth middleware treats this as "not a
// member" until the status flips to active.
TenantMemberStatusInvited TenantMemberStatus = "invited"
// TenantMemberStatusSuspended is an admin-revoked membership. The
// row is preserved for audit trail but the user cannot authenticate
// into the tenant.
TenantMemberStatusSuspended TenantMemberStatus = "suspended"
)
// TenantMember represents the (user, tenant) membership record that
// carries the user's TenantRole for that specific tenant.
//
// A user has one TenantMember row per tenant they belong to. The home
// tenant recorded on User.TenantID is always one of these rows; additional
// rows are created when an admin adds the user to another tenant.
type TenantMember struct {
// Surrogate primary key.
ID uint64 `json:"id" gorm:"primaryKey;autoIncrement"`
// UserID references users.id. Together with TenantID forms the logical
// key enforced by the partial unique index uniq_user_tenant.
UserID string `json:"user_id" gorm:"type:varchar(36);not null;index"`
// TenantID references tenants.id.
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
// Role held by the user inside this tenant.
Role TenantRole `json:"role" gorm:"type:varchar(20);not null;default:'contributor'"`
// Status controls whether this membership is honoured by the auth
// middleware; see TenantMemberStatus constants.
Status TenantMemberStatus `json:"status" gorm:"type:varchar(20);not null;default:'active'"`
// InvitedBy records the user ID of the admin who created this row via
// an invitation flow. Nil for rows created by self-service registration.
InvitedBy *string `json:"invited_by,omitempty" gorm:"type:varchar(36)"`
// JoinedAt is when the membership became active.
JoinedAt time.Time `json:"joined_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
}
// TableName binds TenantMember to the tenant_members table.
func (TenantMember) TableName() string {
return "tenant_members"
}
// Membership is the login-response-friendly projection of a TenantMember
// joined with tenant name. Returned as part of LoginResponse so the
// frontend can render a tenant switcher and gate UI by role.
type Membership struct {
TenantID uint64 `json:"tenant_id"`
TenantName string `json:"tenant_name"`
Role TenantRole `json:"role"`
}
+14 -6
View File
@@ -103,12 +103,20 @@ type RegisterRequest struct {
// LoginResponse represents a login response
type LoginResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
User *User `json:"user,omitempty"`
Tenant *Tenant `json:"tenant,omitempty"`
Token string `json:"token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
Success bool `json:"success"`
Message string `json:"message,omitempty"`
User *User `json:"user,omitempty"`
// ActiveTenant is the tenant whose ID is encoded in the issued JWT;
// future requests are scoped to it until the client calls /auth/switch-tenant.
// Defaults to the user's home tenant on a fresh login.
ActiveTenant *Tenant `json:"active_tenant,omitempty"`
// Memberships lists every tenant the user can authenticate into,
// along with their role in each. Always populated (length 1 for users
// who only belong to their home tenant) so frontends can render a
// tenant switcher without a follow-up request.
Memberships []Membership `json:"memberships,omitempty"`
Token string `json:"token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
}
// RegisterResponse represents a registration response