fix(rbac): address PR 3 + leave-endpoint review feedback

Security
- Reject URL :id when it does not match the caller's active tenant on
  every /tenants/:id/members/* and /tenants/:id/leave endpoint. Without
  this an Owner of tenant A could drive operations on tenant B simply
  by changing the URL, because RequireRole resolves the caller's role
  against the active tenant from context, not the URL param. The
  cross-tenant superuser carve-out mirrors middleware/rbac.go
  (CanAccessAllTenants + EnableCrossTenantAccess required).
- AddMember no longer records the synthetic "system-<tenantID>" caller
  (X-API-Key auth path) as invited_by, matching the same filter
  KB.CreatorID got in PR 2.
- AuthHandler now logs a loud one-shot error when constructed with a
  nil/incomplete config so a wiring bug that silently disables the
  invite_only gate is visible at boot.

Race fixes
- New repo helpers DemoteOwnerAtomically / RemoveOwnerAtomically wrap
  the count-other-owners + write step in a transaction that holds
  SELECT … FOR UPDATE locks on every other active Owner row. The
  service routes Owner demotion / Owner removal through them, closing
  the TOCTOU window where two concurrent demotes of two different
  Owners could each observe count=2 and both commit, leaving the
  tenant ownerless.

Performance
- ListMembers hydration now batches user lookups via a new
  GetUsersByIDs interface method (one SELECT … WHERE id IN (…)
  instead of N round-trips). Failure degrades to "no email/username"
  rather than dropping rows.

Frontend
- canManage also fires for cross-tenant superusers
  (authStore.canAccessAllTenants), mirroring the backend carve-out so
  the UI controls match what the server actually allows.

Tests
- Cross-tenant URL guard regression cases for List / Add / Update /
  Remove / Leave.
- Superuser bypass tests (flag on -> service reached, flag off -> 403).
- Batched lookup test ensures GetUsersByIDs is called exactly once and
  GetUserByID is never used as a fallback.
- Synthetic caller invited_by filter regression test.
- Service-layer atomic last-Owner regression tests for both
  UpdateRole and RemoveMember.
This commit is contained in:
wizardchen
2026-05-13 23:07:18 +08:00
committed by lyingbug
parent ae7cd02cd6
commit 543e9709be
11 changed files with 713 additions and 53 deletions
@@ -8,8 +8,23 @@ import (
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// ErrLastOwner is returned by the atomic demote / remove repo helpers
// when the operation would leave the tenant without an active Owner.
// The service layer maps this to its own ErrLastOwner sentinel (same
// semantic; just kept separate so the repo doesn't import service).
var ErrLastOwner = errors.New("repository: last active owner")
// forUpdateClause returns the gorm SELECT ... FOR UPDATE clause. Kept
// in one place so we can swap it out for `clause.Locking{Strength: "UPDATE"}`
// on databases that don't support row-level locking (none in our matrix,
// but keeps the seam if SQLite-lite ever needs a no-op).
func forUpdateClause() clause.Expression {
return clause.Locking{Strength: "UPDATE"}
}
// tenantMemberRepository implements interfaces.TenantMemberRepository.
type tenantMemberRepository struct {
db *gorm.DB
@@ -114,6 +129,94 @@ func (r *tenantMemberRepository) CountActiveOwners(ctx context.Context, tenantID
return count, err
}
// DemoteOwnerAtomically transitions an Owner row to a non-Owner role
// while holding an UPDATE lock on the tenant's other Owner rows. This
// closes the TOCTOU window in the old "Get → CountActiveOwners → Update"
// sequence where two concurrent demotions of two different Owners could
// each read count=2, then both commit, leaving the tenant ownerless.
//
// Returns:
// - ErrLastOwner when there is no other active Owner.
// - gorm.ErrRecordNotFound when the row isn't there anymore (race
// between concurrent removes); callers map this to ErrMembershipNotFound.
// - any other error verbatim for the caller to log / surface.
//
// The caller is responsible for verifying the *current* role is Owner
// before invoking this; the method is purposely narrow (it only handles
// the dangerous demotion path) so other UpdateRole transitions can keep
// using the cheap single-statement UpdateRole above.
func (r *tenantMemberRepository) DemoteOwnerAtomically(
ctx context.Context,
userID string,
tenantID uint64,
newRole types.TenantRole,
) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// Lock every other active Owner row in the tenant. Locking ONLY
// owners (not the row being demoted) is enough: a concurrent
// demote of the locked row will block on this same SELECT.
var locked []types.TenantMember
err := tx.
Clauses(forUpdateClause()).
Where("tenant_id = ? AND user_id <> ? AND role = ? AND status = ?",
tenantID, userID, types.TenantRoleOwner, types.TenantMemberStatusActive).
Find(&locked).Error
if err != nil {
return err
}
if len(locked) == 0 {
return ErrLastOwner
}
res := tx.
Model(&types.TenantMember{}).
Where("user_id = ? AND tenant_id = ?", userID, tenantID).
Updates(map[string]any{
"role": newRole,
"updated_at": time.Now(),
})
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}
return nil
})
}
// RemoveOwnerAtomically soft-deletes an Owner row under the same lock
// as DemoteOwnerAtomically. Same return semantics.
func (r *tenantMemberRepository) RemoveOwnerAtomically(
ctx context.Context,
userID string,
tenantID uint64,
) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var locked []types.TenantMember
err := tx.
Clauses(forUpdateClause()).
Where("tenant_id = ? AND user_id <> ? AND role = ? AND status = ?",
tenantID, userID, types.TenantRoleOwner, types.TenantMemberStatusActive).
Find(&locked).Error
if err != nil {
return err
}
if len(locked) == 0 {
return ErrLastOwner
}
res := tx.
Where("user_id = ? AND tenant_id = ?", userID, tenantID).
Delete(&types.TenantMember{})
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}
return nil
})
}
// HasAnyMembers reports whether the tenant has at least one active
// membership row. Uses a LIMIT 1 SELECT (instead of COUNT(*)) so the query
// short-circuits after the first match — important because this is on the
+20
View File
@@ -42,6 +42,26 @@ func (r *userRepository) GetUserByID(ctx context.Context, id string) (*types.Use
return &user, nil
}
// GetUsersByIDs batch-fetches users by id with a single SELECT … WHERE id IN (…)
// and projects the result into a map keyed by user id. Returns an empty
// map for an empty input slice. Missing ids are silently absent from
// the result (consistent with the interface contract used by tenant
// member hydration).
func (r *userRepository) GetUsersByIDs(ctx context.Context, ids []string) (map[string]*types.User, error) {
out := make(map[string]*types.User, len(ids))
if len(ids) == 0 {
return out, nil
}
var users []*types.User
if err := r.db.WithContext(ctx).Where("id IN ?", ids).Find(&users).Error; err != nil {
return nil, err
}
for _, u := range users {
out[u.ID] = u
}
return out, nil
}
// GetUserByEmail gets a user by email
func (r *userRepository) GetUserByEmail(ctx context.Context, email string) (*types.User, error) {
var user types.User
+22 -11
View File
@@ -5,6 +5,7 @@ import (
"errors"
"time"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@@ -153,20 +154,29 @@ func (s *tenantMemberService) UpdateRole(
if current.Role == newRole {
return nil
}
// Owner demotion is the dangerous path: two concurrent demotions of
// two different Owners with the old "Get → Count → Update" sequence
// could each observe count=2 and both commit, leaving the tenant
// ownerless. Route through the repo's atomic helper instead, which
// takes a row-level UPDATE lock on every other active Owner before
// committing the role change.
if current.Role == types.TenantRoleOwner && newRole != types.TenantRoleOwner {
owners, err := s.repo.CountActiveOwners(ctx, tenantID)
if err != nil {
err := s.repo.DemoteOwnerAtomically(ctx, userID, tenantID, newRole)
switch {
case errors.Is(err, apprepo.ErrLastOwner):
return ErrLastOwner
case err != nil:
return err
}
if owners <= 1 {
return ErrLastOwner
}
return nil
}
return s.repo.UpdateRole(ctx, userID, tenantID, newRole)
}
// RemoveMember enforces the "cannot remove the last Owner" invariant
// before soft-deleting the membership.
// before soft-deleting the membership. For Owner removals it routes
// through the repo's transactional helper so the count + delete commit
// atomically (no TOCTOU between checking owner count and deleting).
func (s *tenantMemberService) RemoveMember(ctx context.Context, userID string, tenantID uint64) error {
current, err := s.repo.Get(ctx, userID, tenantID)
if err != nil {
@@ -176,13 +186,14 @@ func (s *tenantMemberService) RemoveMember(ctx context.Context, userID string, t
return ErrMembershipNotFound
}
if current.Role == types.TenantRoleOwner {
owners, err := s.repo.CountActiveOwners(ctx, tenantID)
if err != nil {
err := s.repo.RemoveOwnerAtomically(ctx, userID, tenantID)
switch {
case errors.Is(err, apprepo.ErrLastOwner):
return ErrLastOwner
case err != nil:
return err
}
if owners <= 1 {
return ErrLastOwner
}
return nil
}
return s.repo.SoftDelete(ctx, userID, tenantID)
}
@@ -4,11 +4,20 @@ import (
"context"
"errors"
"testing"
"time"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
// gormErrRecordNotFound is the sentinel the fake repo returns when an
// atomic helper is asked to touch a row that no longer exists, matching
// the real repo's behaviour. Kept as a package-level alias so the
// tests can reference it without re-importing gorm at every call site.
var gormErrRecordNotFound = gorm.ErrRecordNotFound
// fakeTenantMemberRepo is an in-memory implementation of
// interfaces.TenantMemberRepository for unit tests. It is intentionally
// not safe for concurrent use; tests should drive it sequentially.
@@ -133,6 +142,66 @@ func (r *fakeTenantMemberRepo) HasAnyMembers(ctx context.Context, tenantID uint6
return false, nil
}
// DemoteOwnerAtomically and RemoveOwnerAtomically mimic the production
// repo's transactional invariants: count other active Owners, fail
// closed when there are none, otherwise apply the role change /
// soft-delete in-memory. The fake doesn't simulate row-level locks
// because every Go test is single-goroutine here; the production
// transaction is exercised via the repo tests against a real DB.
func (r *fakeTenantMemberRepo) DemoteOwnerAtomically(
ctx context.Context, userID string, tenantID uint64, newRole types.TenantRole,
) error {
others := int64(0)
var target *types.TenantMember
for _, e := range r.rows {
if e.TenantID != tenantID || e.DeletedAt.Valid || e.Status != types.TenantMemberStatusActive {
continue
}
if e.Role == types.TenantRoleOwner && e.UserID != userID {
others++
}
if e.UserID == userID {
target = e
}
}
if others == 0 {
return apprepo.ErrLastOwner
}
if target == nil {
return gormErrRecordNotFound
}
target.Role = newRole
target.UpdatedAt = time.Now()
return nil
}
func (r *fakeTenantMemberRepo) RemoveOwnerAtomically(
ctx context.Context, userID string, tenantID uint64,
) error {
others := int64(0)
var target *types.TenantMember
for _, e := range r.rows {
if e.TenantID != tenantID || e.DeletedAt.Valid || e.Status != types.TenantMemberStatusActive {
continue
}
if e.Role == types.TenantRoleOwner && e.UserID != userID {
others++
}
if e.UserID == userID {
target = e
}
}
if others == 0 {
return apprepo.ErrLastOwner
}
if target == nil {
return gormErrRecordNotFound
}
target.DeletedAt.Time = time.Now()
target.DeletedAt.Valid = true
return nil
}
// Compile-time guard so the test stays in sync with the interface.
var _ interfaces.TenantMemberRepository = (*fakeTenantMemberRepo)(nil)
@@ -272,6 +341,48 @@ func TestTenantMemberService_RemoveMember_ReturnsNotFound(t *testing.T) {
}
}
// The TOCTOU race the atomic helpers were introduced for: two Owner
// rows, demoting both must keep at least one. Sequentially via the
// service the second call must observe the post-first-demote state
// and refuse with ErrLastOwner. (True concurrent demotes are
// exercised at the repo layer with a real DB; here we pin the
// service-level contract.)
func TestTenantMemberService_UpdateRole_AtomicDemoteRejectsSecondLastOwner(t *testing.T) {
svc, repo := newServiceWithRepo()
ctx := context.Background()
const tenantID uint64 = 7
for _, uid := range []string{"a", "b"} {
repo.rows = append(repo.rows, &types.TenantMember{
ID: uint64(len(repo.rows) + 1), UserID: uid, TenantID: tenantID,
Role: types.TenantRoleOwner, Status: types.TenantMemberStatusActive,
})
}
if err := svc.UpdateRole(ctx, "a", tenantID, types.TenantRoleViewer); err != nil {
t.Fatalf("first demote should succeed, got %v", err)
}
if err := svc.UpdateRole(ctx, "b", tenantID, types.TenantRoleViewer); !errors.Is(err, ErrLastOwner) {
t.Fatalf("second demote must hit ErrLastOwner, got %v", err)
}
}
func TestTenantMemberService_RemoveMember_AtomicRemoveRejectsSecondLastOwner(t *testing.T) {
svc, repo := newServiceWithRepo()
ctx := context.Background()
const tenantID uint64 = 7
for _, uid := range []string{"a", "b"} {
repo.rows = append(repo.rows, &types.TenantMember{
ID: uint64(len(repo.rows) + 1), UserID: uid, TenantID: tenantID,
Role: types.TenantRoleOwner, Status: types.TenantMemberStatusActive,
})
}
if err := svc.RemoveMember(ctx, "a", tenantID); err != nil {
t.Fatalf("first remove should succeed, got %v", err)
}
if err := svc.RemoveMember(ctx, "b", tenantID); !errors.Is(err, ErrLastOwner) {
t.Fatalf("second remove must hit ErrLastOwner, got %v", err)
}
}
func TestTenantRole_HasPermission(t *testing.T) {
cases := []struct {
caller types.TenantRole
+6
View File
@@ -467,6 +467,12 @@ func (s *userService) GetUserByID(ctx context.Context, id string) (*types.User,
return s.userRepo.GetUserByID(ctx, id)
}
// GetUsersByIDs proxies to the repository batch fetch. Returns an empty
// map for an empty input; missing ids are absent from the result.
func (s *userService) GetUsersByIDs(ctx context.Context, ids []string) (map[string]*types.User, error) {
return s.userRepo.GetUsersByIDs(ctx, ids)
}
// GetUserByEmail gets a user by email
func (s *userService) GetUserByEmail(ctx context.Context, email string) (*types.User, error) {
return s.userRepo.GetUserByEmail(ctx, email)