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
@@ -203,7 +203,14 @@ const addForm = reactive<{ email: string; role: TenantRole }>({
// Role-aware gates. The server enforces every mutation; UI gates here
// are presentational only, matching the security note in stores/auth.ts.
const currentRole = computed<TenantRole | ''>(() => (authStore.currentTenantRole || '') as TenantRole | '')
const canManage = computed(() => currentRole.value === 'owner')
// Cross-tenant superusers (org-level operators) bypass the Owner gate
// on the server (see middleware/rbac.go RequireRole). The UI must
// mirror that or the buttons would be invisible to the exact admins
// who actually need them. Local Owners of their own tenant come in via
// the role branch.
const canManage = computed(
() => currentRole.value === 'owner' || authStore.canAccessAllTenants === true,
)
// Anyone except the last Owner can leave; we additionally hide the
// button for Owner-the-only-one because clicking would just bounce off
// the server's last-Owner check. The server is still the source of
@@ -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)
+11
View File
@@ -1,6 +1,7 @@
package handler
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
@@ -36,6 +37,16 @@ type AuthHandler struct {
// Returns a pointer to the newly created AuthHandler
func NewAuthHandler(configInfo *config.Config,
userService interfaces.UserService, tenantService interfaces.TenantService) *AuthHandler {
// Boot-time guard: a nil-or-empty Auth section silently disables the
// invite_only gate (see Register below). Emit a loud one-shot log
// pointing at the misconfiguration so operators notice on startup
// instead of discovering it the day someone hits /auth/register.
if configInfo == nil || configInfo.Auth == nil {
logger.Errorf(context.Background(),
"[auth] AuthHandler constructed with nil/incomplete config (cfg=%v); "+
"registration_mode enforcement is disabled. This is almost certainly a wiring bug.",
configInfo)
}
return &AuthHandler{
configInfo: configInfo,
userService: userService,
+94 -18
View File
@@ -10,6 +10,7 @@ import (
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/config"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
@@ -21,24 +22,36 @@ import (
// enforces RBAC (Viewer for list, Owner for any mutation) — see
// router.RegisterTenantRoutes — so we don't re-check role here.
//
// Tenant scoping: we trust :id == active-tenant because the auth
// middleware has already verified the caller is a member of that tenant.
// Operations on a foreign tenant via :id would have been rejected upstream
// when the user has no membership row in it.
// Tenant scoping: the auth middleware resolves the caller's role against
// the *active* tenant (JWT / X-Tenant-ID switch / API-key). The URL :id
// is independent and MUST be cross-checked: a user who is Owner of
// tenant A could otherwise POST /tenants/B/members and have the role
// gate happily accept their tenant-A role for an operation that targets
// tenant B. resolveTenantIDFromPath performs that check below; every
// endpoint goes through it.
//
// Cross-tenant superusers (CanAccessAllTenants + EnableCrossTenantAccess)
// bypass the cross-check the same way RequireRole does — same reasoning
// as middleware/rbac.go.
type TenantMemberHandler struct {
memberService interfaces.TenantMemberService
userService interfaces.UserService
cfg *config.Config
}
// NewTenantMemberHandler wires the dependencies. PR 1 already provides
// both services through the dig container; we just consume them.
// both services through the dig container; we just consume them. cfg is
// required so we can honour the cross-tenant superuser escape hatch the
// same way middleware/rbac.go does.
func NewTenantMemberHandler(
memberService interfaces.TenantMemberService,
userService interfaces.UserService,
cfg *config.Config,
) *TenantMemberHandler {
return &TenantMemberHandler{
memberService: memberService,
userService: userService,
cfg: cfg,
}
}
@@ -75,6 +88,52 @@ func parseTenantIDFromPath(c *gin.Context) (uint64, bool) {
return v, true
}
// resolveTenantIDFromPath parses :id and verifies it matches the
// caller's active tenant context, so an Owner-in-tenant-A can't drive
// operations on tenant B just by changing the URL. Cross-tenant
// superusers are exempt — same carve-out RequireRole grants.
//
// Returns the validated tenant ID and true; returns (0, false) after
// having written the appropriate error to the gin context, in which
// case the handler must `return` immediately.
func (h *TenantMemberHandler) resolveTenantIDFromPath(c *gin.Context) (uint64, bool) {
pathTenantID, ok := parseTenantIDFromPath(c)
if !ok {
return 0, false
}
ctx := c.Request.Context()
ctxTenantID, hasCtxTenant := types.TenantIDFromContext(ctx)
if !hasCtxTenant {
// 没有租户上下文意味着 auth 中间件没有把人放进来;这是错误的链路,
// 兜底直接拒绝避免后续以零值租户跑业务逻辑。
c.Error(apperrors.NewUnauthorizedError("tenant context missing"))
return 0, false
}
if pathTenantID == ctxTenantID {
return pathTenantID, true
}
// Cross-tenant superuser carve-out (mirrors middleware/rbac.go).
// We require BOTH the feature flag and the user attribute: just
// reading user.CanAccessAllTenants without checking the cluster-wide
// EnableCrossTenantAccess would let dormant flags grant escalation.
if h.cfg != nil && h.cfg.Tenant != nil && h.cfg.Tenant.EnableCrossTenantAccess {
if u, ok := ctx.Value(types.UserContextKey).(*types.User); ok &&
u != nil && u.CanAccessAllTenants {
return pathTenantID, true
}
}
logger.Warnf(ctx,
"[rbac] tenant member endpoint rejected: caller tenant=%d, url tenant=%d, path=%s",
ctxTenantID, pathTenantID, c.Request.URL.Path)
c.Error(apperrors.NewForbiddenError(
"Access denied: URL tenant does not match the active tenant"))
return 0, false
}
// ListMembers godoc
// @Summary 列出租户成员
// @Description 返回当前租户内全部 active 成员(含每位成员的角色、邮箱、头像)
@@ -86,7 +145,7 @@ func parseTenantIDFromPath(c *gin.Context) (uint64, bool) {
// @Router /tenants/{id}/members [get]
func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
tenantID, ok := h.resolveTenantIDFromPath(c)
if !ok {
return
}
@@ -98,9 +157,23 @@ func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
return
}
// Hydrate each row with user-facing fields. We do this in the handler
// rather than in the service because it's a pure presentation concern
// — the service stays free of UserService coupling and easier to test.
// Hydrate user-facing fields in one batched query. Before this we
// did N+1 GetUserByID calls; tenants with hundreds of members
// pressed the user repo hard for no good reason. Failure is
// best-effort — a transient batch error degrades to "no email /
// username on this page" rather than dropping rows, so dangling
// memberships can still be cleaned up by the Owner.
ids := make([]string, 0, len(members))
for _, m := range members {
ids = append(ids, m.UserID)
}
usersByID := map[string]*types.User{}
if u, err := h.userService.GetUsersByIDs(ctx, ids); err == nil {
usersByID = u
} else {
logger.Warnf(ctx, "ListMembers batch user lookup failed: tenant=%d err=%v", tenantID, err)
}
resp := make([]types.TenantMemberResponse, 0, len(members))
for _, m := range members {
row := types.TenantMemberResponse{
@@ -110,10 +183,7 @@ func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
InvitedBy: m.InvitedBy,
JoinedAt: m.JoinedAt,
}
// User lookup is best-effort: a deleted user account shouldn't
// drop the row from the management UI, otherwise an Owner can
// no longer remove the dangling membership.
if u, err := h.userService.GetUserByID(ctx, m.UserID); err == nil && u != nil {
if u, ok := usersByID[m.UserID]; ok && u != nil {
row.Email = u.Email
row.Username = u.Username
row.Avatar = u.Avatar
@@ -143,7 +213,7 @@ func (h *TenantMemberHandler) ListMembers(c *gin.Context) {
// @Router /tenants/{id}/members [post]
func (h *TenantMemberHandler) AddMember(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
tenantID, ok := h.resolveTenantIDFromPath(c)
if !ok {
return
}
@@ -177,9 +247,15 @@ func (h *TenantMemberHandler) AddMember(c *gin.Context) {
return
}
// Attribute the invite to a human caller only. The X-API-Key auth
// path attaches a synthetic "system-<tenantID>" user (see
// types.IsSyntheticUserID); recording that as invited_by would
// permanently break join-with-users views and any future "who
// invited whom" UX. Leaving invited_by NULL is the correct fallback
// — matches the same treatment KB.CreatorID gets in PR 2.
caller, _ := types.UserIDFromContext(ctx)
var invitedBy *string
if caller != "" {
if caller != "" && !types.IsSyntheticUserID(caller) {
invitedBy = &caller
}
@@ -233,7 +309,7 @@ func (h *TenantMemberHandler) AddMember(c *gin.Context) {
// @Router /tenants/{id}/members/{user_id} [put]
func (h *TenantMemberHandler) UpdateMemberRole(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
tenantID, ok := h.resolveTenantIDFromPath(c)
if !ok {
return
}
@@ -284,7 +360,7 @@ func (h *TenantMemberHandler) UpdateMemberRole(c *gin.Context) {
// @Router /tenants/{id}/members/{user_id} [delete]
func (h *TenantMemberHandler) RemoveMember(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
tenantID, ok := h.resolveTenantIDFromPath(c)
if !ok {
return
}
@@ -326,7 +402,7 @@ func (h *TenantMemberHandler) RemoveMember(c *gin.Context) {
// @Router /tenants/{id}/leave [post]
func (h *TenantMemberHandler) LeaveTenant(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
tenantID, ok := h.resolveTenantIDFromPath(c)
if !ok {
return
}
+319 -23
View File
@@ -12,6 +12,7 @@ import (
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
@@ -53,6 +54,10 @@ type stubMemberUserService struct {
interfaces.UserService
getByEmail func(ctx context.Context, email string) (*types.User, error)
getByID func(ctx context.Context, id string) (*types.User, error)
// getByIDs lets tests override the batched lookup; when unset the
// stub falls back to fanning out to getByID so existing tests stay
// green without changes.
getByIDs func(ctx context.Context, ids []string) (map[string]*types.User, error)
}
func (s *stubMemberUserService) GetUserByEmail(ctx context.Context, email string) (*types.User, error) {
@@ -63,6 +68,32 @@ func (s *stubMemberUserService) GetUserByID(ctx context.Context, id string) (*ty
return s.getByID(ctx, id)
}
func (s *stubMemberUserService) GetUsersByIDs(ctx context.Context, ids []string) (map[string]*types.User, error) {
if s.getByIDs != nil {
return s.getByIDs(ctx, ids)
}
out := make(map[string]*types.User, len(ids))
for _, id := range ids {
u, err := s.getByID(ctx, id)
if err != nil || u == nil {
continue
}
out[u.ID] = u
}
return out, nil
}
// newTestMemberHandler builds a TenantMemberHandler with a minimal
// config that enables the cross-tenant superuser carve-out by default
// (so tests can flip user.CanAccessAllTenants without having to also
// wire the feature flag). Tests that want to assert the carve-out is
// gated off should build the handler with their own cfg.
func newTestMemberHandler(ms interfaces.TenantMemberService, us interfaces.UserService) *TenantMemberHandler {
return NewTenantMemberHandler(ms, us, &config.Config{
Tenant: &config.TenantConfig{EnableCrossTenantAccess: true},
})
}
// memberTestRouter wires the handler with the same errorCapture middleware
// production uses, so c.Error() shows up as a real HTTP status in the
// recorder.
@@ -78,15 +109,49 @@ func memberTestRouter(h *TenantMemberHandler) *gin.Engine {
return r
}
// withCallerUser injects the authenticated caller's user ID into the
// request context just like middleware/auth.go does. Several handler
// branches (notably AddMember's invited_by attribution) read this.
func withCallerUser(req *http.Request, callerUserID string) *http.Request {
ctx := context.WithValue(req.Context(), types.UserIDContextKey, callerUserID)
// defaultTestTenantID is what every test request is "active in" unless
// the test overrides it via doJSONWithTenant. Tenant 1 is also what the
// per-test data fixtures hard-code, so call sites stay short.
const defaultTestTenantID uint64 = 1
// memberCtxOpts lets a test override what the auth middleware would have
// stuffed into the request context. The zero value matches the common
// case ("authenticated, active in tenant 1, no superuser flag").
type memberCtxOpts struct {
callerID string
tenantID uint64
user *types.User
skipTenant bool // when true, do NOT set TenantIDContextKey at all
}
// withMemberCtx installs the auth-middleware-equivalent values on req's
// context. We intentionally set the tenant ID here so the handler's
// resolveTenantIDFromPath cross-check has something to compare against;
// every endpoint trusts that pairing to reject cross-tenant escalation.
func withMemberCtx(req *http.Request, opts memberCtxOpts) *http.Request {
ctx := req.Context()
if opts.callerID != "" {
ctx = context.WithValue(ctx, types.UserIDContextKey, opts.callerID)
}
if !opts.skipTenant {
tid := opts.tenantID
if tid == 0 {
tid = defaultTestTenantID
}
ctx = context.WithValue(ctx, types.TenantIDContextKey, tid)
}
if opts.user != nil {
ctx = context.WithValue(ctx, types.UserContextKey, opts.user)
}
return req.WithContext(ctx)
}
func doJSON(t *testing.T, r *gin.Engine, method, path string, body any, callerID string) *httptest.ResponseRecorder {
t.Helper()
return doJSONWithCtx(t, r, method, path, body, memberCtxOpts{callerID: callerID})
}
func doJSONWithCtx(t *testing.T, r *gin.Engine, method, path string, body any, opts memberCtxOpts) *httptest.ResponseRecorder {
t.Helper()
var reader *bytes.Reader
if body != nil {
@@ -97,9 +162,7 @@ func doJSON(t *testing.T, r *gin.Engine, method, path string, body any, callerID
}
req := httptest.NewRequest(method, path, reader)
req.Header.Set("Content-Type", "application/json")
if callerID != "" {
req = withCallerUser(req, callerID)
}
req = withMemberCtx(req, opts)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
@@ -125,7 +188,7 @@ func TestTenantMember_ListMembers_HappyPath(t *testing.T) {
return &types.User{ID: id, Username: id, Email: id + "@x.com"}, nil
},
}
h := NewTenantMemberHandler(ms, us)
h := newTestMemberHandler(ms, us)
w := doJSON(t, memberTestRouter(h), http.MethodGet, "/tenants/1/members", nil, "u-owner")
if w.Code != http.StatusOK {
@@ -166,7 +229,7 @@ func TestTenantMember_ListMembers_TolerantToDeletedUsers(t *testing.T) {
return nil, apprepo.ErrUserNotFound
},
}
h := NewTenantMemberHandler(ms, us)
h := newTestMemberHandler(ms, us)
w := doJSON(t, memberTestRouter(h), http.MethodGet, "/tenants/1/members", nil, "u-owner")
if w.Code != http.StatusOK {
@@ -178,7 +241,7 @@ func TestTenantMember_ListMembers_TolerantToDeletedUsers(t *testing.T) {
}
func TestTenantMember_ListMembers_RejectsBadTenantID(t *testing.T) {
h := NewTenantMemberHandler(&stubMemberService{}, &stubMemberUserService{})
h := newTestMemberHandler(&stubMemberService{}, &stubMemberUserService{})
w := doJSON(t, memberTestRouter(h), http.MethodGet, "/tenants/abc/members", nil, "u1")
if w.Code != http.StatusBadRequest {
t.Fatalf("non-numeric tenant id must 400, got %d", w.Code)
@@ -203,7 +266,7 @@ func TestTenantMember_AddMember_HappyPath(t *testing.T) {
return &types.User{ID: "u-bob", Email: email, Username: "bob"}, nil
},
}
h := NewTenantMemberHandler(ms, us)
h := newTestMemberHandler(ms, us)
body := map[string]any{"email": "bob@x.com", "role": "contributor"}
w := doJSON(t, memberTestRouter(h), http.MethodPost, "/tenants/1/members", body, caller)
@@ -221,7 +284,7 @@ func TestTenantMember_AddMember_UnknownEmailReturns404(t *testing.T) {
return nil, apprepo.ErrUserNotFound
},
}
h := NewTenantMemberHandler(&stubMemberService{}, us)
h := newTestMemberHandler(&stubMemberService{}, us)
body := map[string]any{"email": "ghost@x.com", "role": "viewer"}
w := doJSON(t, memberTestRouter(h), http.MethodPost, "/tenants/1/members", body, "u-owner")
@@ -241,7 +304,7 @@ func TestTenantMember_AddMember_DuplicateMaps409(t *testing.T) {
return &types.User{ID: "u-bob", Email: "bob@x.com"}, nil
},
}
h := NewTenantMemberHandler(ms, us)
h := newTestMemberHandler(ms, us)
body := map[string]any{"email": "bob@x.com", "role": "contributor"}
w := doJSON(t, memberTestRouter(h), http.MethodPost, "/tenants/1/members", body, "u-owner")
@@ -259,7 +322,7 @@ func TestTenantMember_AddMember_InvalidRoleRejectedUpfront(t *testing.T) {
return &types.User{ID: "u-bob"}, nil
},
}
h := NewTenantMemberHandler(&stubMemberService{}, us)
h := newTestMemberHandler(&stubMemberService{}, us)
body := map[string]any{"email": "bob@x.com", "role": "wizard"}
w := doJSON(t, memberTestRouter(h), http.MethodPost, "/tenants/1/members", body, "u-owner")
@@ -282,7 +345,7 @@ func TestTenantMember_UpdateRole_HappyPath(t *testing.T) {
return nil
},
}
h := NewTenantMemberHandler(ms, &stubMemberUserService{})
h := newTestMemberHandler(ms, &stubMemberUserService{})
body := map[string]any{"role": "admin"}
w := doJSON(t, memberTestRouter(h), http.MethodPut, "/tenants/1/members/u-bob", body, "u-owner")
@@ -300,7 +363,7 @@ func TestTenantMember_UpdateRole_LastOwnerMaps409(t *testing.T) {
return service.ErrLastOwner
},
}
h := NewTenantMemberHandler(ms, &stubMemberUserService{})
h := newTestMemberHandler(ms, &stubMemberUserService{})
body := map[string]any{"role": "viewer"}
w := doJSON(t, memberTestRouter(h), http.MethodPut, "/tenants/1/members/u-only-owner", body, "u-only-owner")
@@ -315,7 +378,7 @@ func TestTenantMember_UpdateRole_UnknownMembershipMaps404(t *testing.T) {
return service.ErrMembershipNotFound
},
}
h := NewTenantMemberHandler(ms, &stubMemberUserService{})
h := newTestMemberHandler(ms, &stubMemberUserService{})
body := map[string]any{"role": "admin"}
w := doJSON(t, memberTestRouter(h), http.MethodPut, "/tenants/1/members/u-ghost", body, "u-owner")
@@ -335,7 +398,7 @@ func TestTenantMember_RemoveMember_HappyPath(t *testing.T) {
return nil
},
}
h := NewTenantMemberHandler(ms, &stubMemberUserService{})
h := newTestMemberHandler(ms, &stubMemberUserService{})
w := doJSON(t, memberTestRouter(h), http.MethodDelete, "/tenants/1/members/u-bob", nil, "u-owner")
if w.Code != http.StatusOK {
@@ -349,7 +412,7 @@ func TestTenantMember_RemoveMember_LastOwnerMaps409(t *testing.T) {
return service.ErrLastOwner
},
}
h := NewTenantMemberHandler(ms, &stubMemberUserService{})
h := newTestMemberHandler(ms, &stubMemberUserService{})
w := doJSON(t, memberTestRouter(h), http.MethodDelete, "/tenants/1/members/u-only-owner", nil, "u-only-owner")
if w.Code != http.StatusConflict {
@@ -371,7 +434,7 @@ func TestTenantMember_LeaveTenant_HappyPath(t *testing.T) {
return nil
},
}
h := NewTenantMemberHandler(ms, &stubMemberUserService{})
h := newTestMemberHandler(ms, &stubMemberUserService{})
w := doJSON(t, memberTestRouter(h), http.MethodPost, "/tenants/1/leave", nil, "u-self")
if w.Code != http.StatusOK {
@@ -389,7 +452,7 @@ func TestTenantMember_LeaveTenant_LastOwnerMaps409(t *testing.T) {
return service.ErrLastOwner
},
}
h := NewTenantMemberHandler(ms, &stubMemberUserService{})
h := newTestMemberHandler(ms, &stubMemberUserService{})
w := doJSON(t, memberTestRouter(h), http.MethodPost, "/tenants/1/leave", nil, "u-only-owner")
if w.Code != http.StatusConflict {
@@ -408,7 +471,7 @@ func TestTenantMember_LeaveTenant_MissingCallerReturns401(t *testing.T) {
return nil
},
}
h := NewTenantMemberHandler(ms, &stubMemberUserService{})
h := newTestMemberHandler(ms, &stubMemberUserService{})
w := doJSON(t, memberTestRouter(h), http.MethodPost, "/tenants/1/leave", nil, "")
if w.Code != http.StatusUnauthorized {
@@ -418,3 +481,236 @@ func TestTenantMember_LeaveTenant_MissingCallerReturns401(t *testing.T) {
t.Fatalf("RemoveMember must not be called without a caller id")
}
}
// ---------- Cross-tenant guard ----------
// A user whose active tenant context is N must NOT be able to drive
// operations on tenant M just by changing the URL. This is the
// regression test for the H1 finding in #1320's review: the handler
// used to trust :id and pass it straight to the service, so an Owner
// of tenant 1 could POST /tenants/5/members and have the service
// happily create rows for a tenant they had no claim to.
func TestTenantMember_RejectsCrossTenantURL_List(t *testing.T) {
called := false
ms := &stubMemberService{
listTenant: func(_ context.Context, _ uint64) ([]*types.TenantMember, error) {
called = true
return nil, nil
},
}
h := newTestMemberHandler(ms, &stubMemberUserService{})
// Active tenant 1, URL targets tenant 5.
w := doJSONWithCtx(t, memberTestRouter(h), http.MethodGet, "/tenants/5/members", nil,
memberCtxOpts{callerID: "u1", tenantID: 1})
if w.Code != http.StatusForbidden {
t.Fatalf("cross-tenant URL must 403, got %d body=%s", w.Code, w.Body.String())
}
if called {
t.Fatalf("service must NOT be reached when :id != active tenant")
}
}
func TestTenantMember_RejectsCrossTenantURL_Add(t *testing.T) {
called := false
ms := &stubMemberService{
add: func(_ context.Context, _ string, _ uint64, _ types.TenantRole, _ *string) (*types.TenantMember, error) {
called = true
return nil, nil
},
}
us := &stubMemberUserService{
getByEmail: func(_ context.Context, _ string) (*types.User, error) {
t.Fatalf("user lookup must not run when :id is rejected upfront")
return nil, nil
},
}
h := newTestMemberHandler(ms, us)
body := map[string]any{"email": "bob@x.com", "role": "contributor"}
w := doJSONWithCtx(t, memberTestRouter(h), http.MethodPost, "/tenants/5/members", body,
memberCtxOpts{callerID: "u1", tenantID: 1})
if w.Code != http.StatusForbidden {
t.Fatalf("expected 403 on cross-tenant add, got %d body=%s", w.Code, w.Body.String())
}
if called {
t.Fatalf("AddMember must NOT be reached")
}
}
func TestTenantMember_RejectsCrossTenantURL_Update(t *testing.T) {
ms := &stubMemberService{updateRole: func(context.Context, string, uint64, types.TenantRole) error {
t.Fatalf("UpdateRole must not be reached")
return nil
}}
h := newTestMemberHandler(ms, &stubMemberUserService{})
body := map[string]any{"role": "admin"}
w := doJSONWithCtx(t, memberTestRouter(h), http.MethodPut, "/tenants/5/members/u2", body,
memberCtxOpts{callerID: "u1", tenantID: 1})
if w.Code != http.StatusForbidden {
t.Fatalf("expected 403, got %d", w.Code)
}
}
func TestTenantMember_RejectsCrossTenantURL_Remove(t *testing.T) {
ms := &stubMemberService{remove: func(context.Context, string, uint64) error {
t.Fatalf("RemoveMember must not be reached")
return nil
}}
h := newTestMemberHandler(ms, &stubMemberUserService{})
w := doJSONWithCtx(t, memberTestRouter(h), http.MethodDelete, "/tenants/5/members/u2", nil,
memberCtxOpts{callerID: "u1", tenantID: 1})
if w.Code != http.StatusForbidden {
t.Fatalf("expected 403, got %d", w.Code)
}
}
func TestTenantMember_RejectsCrossTenantURL_Leave(t *testing.T) {
// Even LeaveTenant — although functionally a no-op for non-members
// — must reject mismatched URLs to keep the handler contract
// uniform with the other endpoints.
ms := &stubMemberService{remove: func(context.Context, string, uint64) error {
t.Fatalf("RemoveMember must not be reached")
return nil
}}
h := newTestMemberHandler(ms, &stubMemberUserService{})
w := doJSONWithCtx(t, memberTestRouter(h), http.MethodPost, "/tenants/5/leave", nil,
memberCtxOpts{callerID: "u1", tenantID: 1})
if w.Code != http.StatusForbidden {
t.Fatalf("expected 403, got %d", w.Code)
}
}
func TestTenantMember_CrossTenantSuperuserBypassesURLCheck(t *testing.T) {
// CanAccessAllTenants + EnableCrossTenantAccess is the documented
// escape hatch (mirrors middleware/rbac.go). Once flipped on, an
// org-level operator can drive any tenant's member list from any
// session — including a session whose active tenant != URL.
called := false
ms := &stubMemberService{
listTenant: func(_ context.Context, tenantID uint64) ([]*types.TenantMember, error) {
called = true
if tenantID != 5 {
t.Fatalf("expected tenant 5 to reach service, got %d", tenantID)
}
return nil, nil
},
}
us := &stubMemberUserService{
getByID: func(_ context.Context, _ string) (*types.User, error) { return nil, apprepo.ErrUserNotFound },
}
h := newTestMemberHandler(ms, us)
w := doJSONWithCtx(t, memberTestRouter(h), http.MethodGet, "/tenants/5/members", nil,
memberCtxOpts{
callerID: "u-superuser",
tenantID: 1,
user: &types.User{ID: "u-superuser", CanAccessAllTenants: true},
})
if w.Code != http.StatusOK {
t.Fatalf("superuser bypass must reach service, got %d body=%s", w.Code, w.Body.String())
}
if !called {
t.Fatalf("service must be reached for the superuser bypass")
}
}
func TestTenantMember_SuperuserBypassRequiresFeatureFlag(t *testing.T) {
// Just having user.CanAccessAllTenants on the User struct is not
// enough — the cluster operator must also have flipped
// cfg.Tenant.EnableCrossTenantAccess. Otherwise a stale token
// claim couldn't be revoked operationally.
called := false
ms := &stubMemberService{
listTenant: func(_ context.Context, _ uint64) ([]*types.TenantMember, error) {
called = true
return nil, nil
},
}
// Explicitly build without the flag.
h := NewTenantMemberHandler(ms, &stubMemberUserService{}, &config.Config{
Tenant: &config.TenantConfig{EnableCrossTenantAccess: false},
})
w := doJSONWithCtx(t, memberTestRouter(h), http.MethodGet, "/tenants/5/members", nil,
memberCtxOpts{
callerID: "u-superuser",
tenantID: 1,
user: &types.User{ID: "u-superuser", CanAccessAllTenants: true},
})
if w.Code != http.StatusForbidden {
t.Fatalf("expected 403 when feature flag is off, got %d body=%s", w.Code, w.Body.String())
}
if called {
t.Fatalf("service must not be reached without the feature flag")
}
}
// ---------- Hydration + invited_by ----------
func TestTenantMember_ListMembers_UsesBatchedUserLookup(t *testing.T) {
// Regression for the N+1 finding: the handler should call
// GetUsersByIDs exactly once, NOT GetUserByID per row.
now := time.Now()
ms := &stubMemberService{
listTenant: func(_ context.Context, _ uint64) ([]*types.TenantMember, error) {
return []*types.TenantMember{
{UserID: "u1", TenantID: 1, Role: types.TenantRoleOwner, Status: types.TenantMemberStatusActive, JoinedAt: now},
{UserID: "u2", TenantID: 1, Role: types.TenantRoleAdmin, Status: types.TenantMemberStatusActive, JoinedAt: now},
{UserID: "u3", TenantID: 1, Role: types.TenantRoleViewer, Status: types.TenantMemberStatusActive, JoinedAt: now},
}, nil
},
}
batchCalls := 0
singleCalls := 0
us := &stubMemberUserService{
getByIDs: func(_ context.Context, ids []string) (map[string]*types.User, error) {
batchCalls++
out := map[string]*types.User{}
for _, id := range ids {
out[id] = &types.User{ID: id, Username: id, Email: id + "@x.com"}
}
return out, nil
},
getByID: func(_ context.Context, _ string) (*types.User, error) {
singleCalls++
return nil, apprepo.ErrUserNotFound
},
}
h := newTestMemberHandler(ms, us)
w := doJSON(t, memberTestRouter(h), http.MethodGet, "/tenants/1/members", nil, "u-owner")
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
}
if batchCalls != 1 {
t.Fatalf("GetUsersByIDs should be called exactly once, got %d", batchCalls)
}
if singleCalls != 0 {
t.Fatalf("the handler must not fall back to per-row GetUserByID, got %d calls", singleCalls)
}
}
func TestTenantMember_AddMember_SyntheticCallerLeavesInvitedByNull(t *testing.T) {
// X-API-Key path attaches a synthetic "system-<tenantID>" user.
// Recording that as invited_by would permanently break any future
// join-with-users UX; the handler must skip it.
captured := struct{ invited *string }{}
ms := &stubMemberService{
add: func(_ context.Context, _ string, _ uint64, _ types.TenantRole, invitedBy *string) (*types.TenantMember, error) {
captured.invited = invitedBy
return &types.TenantMember{UserID: "u-bob", TenantID: 1, Role: types.TenantRoleContributor, Status: types.TenantMemberStatusActive, JoinedAt: time.Now()}, nil
},
}
us := &stubMemberUserService{
getByEmail: func(_ context.Context, _ string) (*types.User, error) {
return &types.User{ID: "u-bob", Email: "bob@x.com"}, nil
},
}
h := newTestMemberHandler(ms, us)
body := map[string]any{"email": "bob@x.com", "role": "contributor"}
w := doJSON(t, memberTestRouter(h), http.MethodPost, "/tenants/1/members", body, "system-1")
if w.Code != http.StatusCreated {
t.Fatalf("expected 201, got %d body=%s", w.Code, w.Body.String())
}
if captured.invited != nil {
t.Fatalf("invited_by must be nil for synthetic caller; got %q", *captured.invited)
}
}
@@ -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