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
@@ -47,4 +47,15 @@ type TenantMemberRepository interface {
// 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)
// DemoteOwnerAtomically demotes an Owner to a non-Owner role inside
// a transaction that holds an UPDATE lock on the tenant's other
// active Owners, fixing the TOCTOU race where two concurrent
// demotions could leave the tenant ownerless. Returns the
// repo-level ErrLastOwner sentinel when no other Owner exists.
DemoteOwnerAtomically(ctx context.Context, userID string, tenantID uint64, newRole types.TenantRole) error
// RemoveOwnerAtomically soft-deletes an Owner row under the same
// lock as DemoteOwnerAtomically.
RemoveOwnerAtomically(ctx context.Context, userID string, tenantID uint64) error
}
+8
View File
@@ -18,6 +18,11 @@ type UserService interface {
LoginWithOIDC(ctx context.Context, code, redirectURI string) (*types.OIDCCallbackResponse, error)
// GetUserByID gets a user by ID
GetUserByID(ctx context.Context, id string) (*types.User, error)
// GetUsersByIDs batch-fetches users by id, returning a map keyed by
// user id. Missing ids are simply absent from the result; the call
// is not an error when some ids resolve to no row. Used on hot list
// endpoints (tenant members, audit logs) to avoid N+1 queries.
GetUsersByIDs(ctx context.Context, ids []string) (map[string]*types.User, error)
// GetUserByEmail gets a user by email
GetUserByEmail(ctx context.Context, email string) (*types.User, error)
// GetUserByUsername gets a user by username
@@ -68,6 +73,9 @@ type UserRepository interface {
CreateUser(ctx context.Context, user *types.User) error
// GetUserByID gets a user by ID
GetUserByID(ctx context.Context, id string) (*types.User, error)
// GetUsersByIDs batch-fetches users by id, returning a map keyed by
// user id. Missing ids are simply absent from the result.
GetUsersByIDs(ctx context.Context, ids []string) (map[string]*types.User, error)
// GetUserByEmail gets a user by email
GetUserByEmail(ctx context.Context, email string) (*types.User, error)
// GetUserByUsername gets a user by username