Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: enforce actor privilege checks in user service (#3426)
Kyle Mendell21ea962f86d9
diff --git a/backend/api/handlers/auth.go b/backend/api/handlers/auth.goindex 44e784357..ffae5c3b3 100644--- a/backend/api/handlers/auth.go+++ b/backend/api/handlers/auth.go@@ -484,7 +484,7 @@ func (h *AuthHandler) UpdateMyProfile(ctx context.Context, input *UpdateMyProfilmergePreferencesInternal(&userModel.Preferences, p)}- updated, err := h.userService.UpdateUser(ctx, userModel)+ updated, err := h.userService.UpdateUser(ctx, userModel, nil)if err != nil {return nil, huma.Error500InternalServerError("Failed to update user")}diff --git a/backend/api/handlers/roles.go b/backend/api/handlers/roles.goindex 245c6ef5e..73c0c8f8a 100644--- a/backend/api/handlers/roles.go+++ b/backend/api/handlers/roles.go@@ -313,6 +313,8 @@ func (h *RoleHandler) SetUserRoleAssignments(ctx context.Context, input *SetUser}if err := h.roleService.SetUserAssignments(ctx, input.UserID, desired); err != nil {switch {+ case errors.Is(err, services.ErrUserNotFound):+ return nil, huma.Error404NotFound(err.Error())case errors.Is(err, common.ErrInvalidRoleAssignment):return nil, huma.Error400BadRequest(err.Error())case errors.Is(err, common.ErrNoGlobalAdminRemains):diff --git a/backend/api/handlers/users.go b/backend/api/handlers/users.goindex cfacf5801..ea4815be3 100644--- a/backend/api/handlers/users.go+++ b/backend/api/handlers/users.go@@ -286,8 +286,29 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*userModel.UpdatedAt = new(time.Now())- updatedUser, err := h.userService.UpdateUser(ctx, userModel)+ // Privilege ordering: a non-admin caller may not modify a global admin+ // target, nor set another user's password. The service re-enforces the+ // target-admin check.+ callerPerms, _ := humamw.PermissionsFromContext(ctx)+ caller, _ := humamw.GetCurrentUserFromContext(ctx)+ if callerPerms != nil && !callerPerms.IsGlobalAdmin() {+ if input.Body.Password != nil && *input.Body.Password != "" && caller != nil && caller.ID != userModel.ID {+ return nil, huma.Error403Forbidden(services.ErrInsufficientPrivilege.Error())+ }+ targetPerms, err := h.userService.ResolveUserPermissions(ctx, userModel.ID)+ if err != nil {+ return nil, huma.Error500InternalServerError("Failed to resolve target permissions")+ }+ if targetPerms != nil && targetPerms.IsGlobalAdmin() {+ return nil, huma.Error403Forbidden(services.ErrInsufficientPrivilege.Error())+ }+ }++ updatedUser, err := h.userService.UpdateUser(ctx, userModel, callerPerms)if err != nil {+ if errors.Is(err, services.ErrInsufficientPrivilege) {+ return nil, huma.Error403Forbidden(services.ErrInsufficientPrivilege.Error())+ }if errors.Is(err, services.ErrCannotRemoveLastAdmin) {return nil, huma.Error409Conflict(services.ErrCannotRemoveLastAdmin.Error())}@@ -316,7 +337,25 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*// DeleteUser deletes a user.func (h *UserHandler) DeleteUser(ctx context.Context, input *DeleteUserInput) (*DeleteUserOutput, error) {- if err := h.userService.DeleteUser(ctx, input.UserID); err != nil {+ // Privilege ordering: a non-admin caller may not delete a global admin+ // target. The service enforces the same check; this pre-check produces a+ // clean 403 without entering the delete path.+ callerPerms, _ := humamw.PermissionsFromContext(ctx)+ caller, _ := humamw.GetCurrentUserFromContext(ctx)+ if callerPerms != nil && !callerPerms.IsGlobalAdmin() && caller != nil && caller.ID != input.UserID {+ targetPerms, err := h.userService.ResolveUserPermissions(ctx, input.UserID)+ if err != nil {+ return nil, huma.Error500InternalServerError("Failed to resolve target permissions")+ }+ if targetPerms != nil && targetPerms.IsGlobalAdmin() {+ return nil, huma.Error403Forbidden(services.ErrInsufficientPrivilege.Error())+ }+ }++ if err := h.userService.DeleteUser(ctx, input.UserID, callerPerms); err != nil {+ if errors.Is(err, services.ErrInsufficientPrivilege) {+ return nil, huma.Error403Forbidden(services.ErrInsufficientPrivilege.Error())+ }if errors.Is(err, services.ErrCannotRemoveLastAdmin) {return nil, huma.Error409Conflict(services.ErrCannotRemoveLastAdmin.Error())}diff --git a/backend/api/handlers/users_test.go b/backend/api/handlers/users_test.goindex f56d00ecd..eb93d1be1 100644--- a/backend/api/handlers/users_test.go+++ b/backend/api/handlers/users_test.go@@ -15,6 +15,7 @@ import ("gorm.io/gorm""github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/types/v2/user")func setupUserHandlerTestDB(t *testing.T) *database.DB {@@ -65,3 +66,149 @@ func TestDeleteUserReturnsConflictForLastAdmin(t *testing.T) {require.Equal(t, http.StatusConflict, statusErr.GetStatus())require.Contains(t, statusErr.Error(), services.ErrCannotRemoveLastAdmin.Error())}++// callerContext returns a context carrying the given user and their resolved+// PermissionSet, matching what the auth bridge attaches in production.+func callerContext(u *models.User, ps *authz.PermissionSet) context.Context {+ ctx := context.WithValue(context.Background(), humamw.ContextKeyUserPermissions, ps)+ return models.WithCurrentUser(ctx, u)+}++func grantRole(t *testing.T, roleSvc *services.RoleService, userID, roleID string) {+ t.Helper()+ require.NoError(t, roleSvc.SetUserAssignments(context.Background(), userID, []models.UserRoleAssignment{+ {RoleID: roleID, EnvironmentID: nil},+ }))+}++func setupPrivilegedUserHandler(t *testing.T) (*services.UserService, *services.RoleService, *UserHandler) {+ t.Helper()+ db := setupUserHandlerTestDB(t)+ require.NoError(t, db.AutoMigrate(&models.Role{}, &models.UserRoleAssignment{}, &models.Environment{}))+ roleSvc := services.NewRoleService(db)+ require.NoError(t, roleSvc.EnsureBuiltInRoles(context.Background()))+ userSvc := services.NewUserService(db).WithRoleService(roleSvc)+ return userSvc, roleSvc, &UserHandler{userService: userSvc}+}++func TestUpdateUserRejectsPasswordResetOnAdminByDelegatedManager(t *testing.T) {+ userSvc, roleSvc, handler := setupPrivilegedUserHandler(t)+ ctx := context.Background()++ admin := createHandlerTestUser(t, userSvc, "admin-1", "arcane", models.StringSlice{})+ grantRole(t, roleSvc, admin.ID, authz.BuiltInRoleAdmin)+ manager := createHandlerTestUser(t, userSvc, "mgr-1", "manager", models.StringSlice{})+ managerRole, err := roleSvc.CreateRole(ctx, "User Manager", nil, []string{authz.PermUsersUpdate})+ require.NoError(t, err)+ grantRole(t, roleSvc, manager.ID, managerRole.ID)+ managerPerms, err := roleSvc.ResolvePermissions(ctx, manager)+ require.NoError(t, err)++ password := "attacker1234"+ _, err = handler.UpdateUser(callerContext(manager, managerPerms), &UpdateUserInput{+ UserID: admin.ID,+ Body: user.UpdateUser{Password: &password},+ })+ require.Error(t, err)+ var statusErr huma.StatusError+ require.ErrorAs(t, err, &statusErr)+ require.Equal(t, http.StatusForbidden, statusErr.GetStatus())++ reloaded, getErr := userSvc.GetUserByID(ctx, admin.ID)+ require.NoError(t, getErr)+ require.NotEqual(t, password, reloaded.PasswordHash)+}++func TestUpdateUserRejectsProfileEditOnAdminByDelegatedManager(t *testing.T) {+ userSvc, roleSvc, handler := setupPrivilegedUserHandler(t)+ ctx := context.Background()++ admin := createHandlerTestUser(t, userSvc, "admin-1", "arcane", models.StringSlice{})+ grantRole(t, roleSvc, admin.ID, authz.BuiltInRoleAdmin)+ manager := createHandlerTestUser(t, userSvc, "mgr-1", "manager", models.StringSlice{})+ managerRole, err := roleSvc.CreateRole(ctx, "User Manager", nil, []string{authz.PermUsersUpdate})+ require.NoError(t, err)+ grantRole(t, roleSvc, manager.ID, managerRole.ID)+ managerPerms, err := roleSvc.ResolvePermissions(ctx, manager)+ require.NoError(t, err)++ displayName := "pwned"+ _, err = handler.UpdateUser(callerContext(manager, managerPerms), &UpdateUserInput{+ UserID: admin.ID,+ Body: user.UpdateUser{DisplayName: &displayName},+ })+ require.Error(t, err)+ var statusErr huma.StatusError+ require.ErrorAs(t, err, &statusErr)+ require.Equal(t, http.StatusForbidden, statusErr.GetStatus())+}++func TestUpdateUserRejectsPasswordChangeOnOtherUserByNonAdmin(t *testing.T) {+ userSvc, roleSvc, handler := setupPrivilegedUserHandler(t)+ ctx := context.Background()++ admin := createHandlerTestUser(t, userSvc, "admin-1", "arcane", models.StringSlice{})+ grantRole(t, roleSvc, admin.ID, authz.BuiltInRoleAdmin)+ victim := createHandlerTestUser(t, userSvc, "user-1", "victim", models.StringSlice{})+ manager := createHandlerTestUser(t, userSvc, "mgr-1", "manager", models.StringSlice{})+ managerRole, err := roleSvc.CreateRole(ctx, "User Manager", nil, []string{authz.PermUsersUpdate})+ require.NoError(t, err)+ grantRole(t, roleSvc, manager.ID, managerRole.ID)+ managerPerms, err := roleSvc.ResolvePermissions(ctx, manager)+ require.NoError(t, err)++ password := "newpass123"+ _, err = handler.UpdateUser(callerContext(manager, managerPerms), &UpdateUserInput{+ UserID: victim.ID,+ Body: user.UpdateUser{Password: &password},+ })+ require.Error(t, err)+ var statusErr huma.StatusError+ require.ErrorAs(t, err, &statusErr)+ require.Equal(t, http.StatusForbidden, statusErr.GetStatus())+}++func TestUpdateUserAllowsGlobalAdminEditingAdmin(t *testing.T) {+ userSvc, roleSvc, handler := setupPrivilegedUserHandler(t)+ ctx := context.Background()++ admin := createHandlerTestUser(t, userSvc, "admin-1", "arcane", models.StringSlice{})+ grantRole(t, roleSvc, admin.ID, authz.BuiltInRoleAdmin)+ other := createHandlerTestUser(t, userSvc, "admin-2", "backup", models.StringSlice{})+ grantRole(t, roleSvc, other.ID, authz.BuiltInRoleAdmin)+ otherPerms, err := roleSvc.ResolvePermissions(ctx, other)+ require.NoError(t, err)++ displayName := "Renamed Admin"+ out, err := handler.UpdateUser(callerContext(other, otherPerms), &UpdateUserInput{+ UserID: admin.ID,+ Body: user.UpdateUser{DisplayName: &displayName},+ })+ require.NoError(t, err)+ require.NotNil(t, out)+}++func TestDeleteUserRejectsDelegatedManagerDeletingAdmin(t *testing.T) {+ userSvc, roleSvc, handler := setupPrivilegedUserHandler(t)+ ctx := context.Background()++ admin := createHandlerTestUser(t, userSvc, "admin-1", "arcane", models.StringSlice{})+ grantRole(t, roleSvc, admin.ID, authz.BuiltInRoleAdmin)+ backup := createHandlerTestUser(t, userSvc, "admin-2", "backup", models.StringSlice{})+ grantRole(t, roleSvc, backup.ID, authz.BuiltInRoleAdmin)+ manager := createHandlerTestUser(t, userSvc, "mgr-1", "manager", models.StringSlice{})+ managerRole, err := roleSvc.CreateRole(ctx, "User Manager", nil, []string{authz.PermUsersDelete})+ require.NoError(t, err)+ grantRole(t, roleSvc, manager.ID, managerRole.ID)+ managerPerms, err := roleSvc.ResolvePermissions(ctx, manager)+ require.NoError(t, err)++ _, err = handler.DeleteUser(callerContext(manager, managerPerms), &DeleteUserInput{UserID: admin.ID})+ require.Error(t, err)+ var statusErr huma.StatusError+ require.ErrorAs(t, err, &statusErr)+ require.Equal(t, http.StatusForbidden, statusErr.GetStatus())++ _, getErr := userSvc.GetUserByID(ctx, admin.ID)+ require.NoError(t, getErr)+}diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.goindex d1d371962..6fb8bae24 100644--- a/backend/internal/services/auth_service.go+++ b/backend/internal/services/auth_service.go@@ -274,7 +274,7 @@ func (s *AuthService) Login(ctx context.Context, username, password string, meta// Use new(*user) to create a safe copy of the user struct to avoid data raceuserCopy := new(*user)s.runInBackground(ctx, "update_last_login", func(ctx context.Context) error {- if _, err := s.userService.UpdateUser(ctx, userCopy); err != nil {+ if _, err := s.userService.UpdateUser(ctx, userCopy, nil); err != nil {return errors.WrapIf(err, "failed to update user's last login time")}return nil@@ -477,7 +477,7 @@ func (s *AuthService) updateOidcUser(ctx context.Context, user *models.User, uses.persistOidcTokens(user, tokenResp)user.LastLogin = new(time.Now())- if _, err := s.userService.UpdateUser(ctx, user); err != nil {+ if _, err := s.userService.UpdateUser(ctx, user, nil); err != nil {return err}if err := s.syncOidcRoleAssignments(ctx, user, userInfo, tokenResp); err != nil {@@ -797,7 +797,7 @@ func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPassworuser.PasswordHash = hashedPassworduser.RequiresPasswordChange = false- if _, err = s.userService.UpdateUser(ctx, user); err != nil {+ if _, err = s.userService.UpdateUser(ctx, user, nil); err != nil {return err}keys := make([]string, 0)diff --git a/backend/internal/services/role_service.go b/backend/internal/services/role_service.goindex a2a92ed9e..6f988b13d 100644--- a/backend/internal/services/role_service.go+++ b/backend/internal/services/role_service.go@@ -337,6 +337,34 @@ func (s *RoleService) CreateRole(ctx context.Context, name string, description *return role, nil}+// lockAssignedUserRowsInternal locks the user rows of everyone currently+// assigned to roleID, in deterministic id order. Role-definition writes call+// this so they serialize with UserService mutation transactions, whose in-tx+// privilege checks lock the same rows: without it a role edit could change a+// holder's effective admin status between that check and the mutation commit.+// Returns the affected user ids for post-commit cache invalidation.+func lockAssignedUserRowsInternal(tx *gorm.DB, roleID string) ([]string, error) {+ var ids []string+ if err := tx.Model(&models.UserRoleAssignment{}).+ Where("role_id = ?", roleID).+ Distinct("user_id").+ Pluck("user_id", &ids).Error; err != nil {+ return nil, errors.WrapIf(err, "failed to list users assigned to role")+ }+ if len(ids) == 0 {+ return ids, nil+ }+ var locked []string+ if err := tx.Model(&models.User{}).+ Clauses(clause.Locking{Strength: "UPDATE"}).+ Where("id IN ?", ids).+ Order("id").+ Pluck("id", &locked).Error; err != nil {+ return nil, errors.WrapIf(err, "failed to lock users assigned to role")+ }+ return ids, nil+}+func (s *RoleService) UpdateRole(ctx context.Context, id, name string, description *string, permissions []string) (*models.Role, error) {if err := validatePermissionsInternal(permissions); err != nil {return nil, err@@ -362,6 +390,9 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descriptireturn common.Classify(common.ErrRoleNameTaken, errors.New("Role name already in use"))}}+ if _, err := lockAssignedUserRowsInternal(tx, id); err != nil {+ return err+ }existing.Name = nameexisting.Description = descriptionexisting.Permissions = permissions@@ -395,12 +426,11 @@ func (s *RoleService) DeleteRole(ctx context.Context, id string) error {errors.New("Built-in role cannot be modified"))}- if err := tx.Model(&models.UserRoleAssignment{}).- Where("role_id = ?", id).- Distinct("user_id").- Pluck("user_id", &affected).Error; err != nil {- return errors.WrapIf(err, "failed to list affected users")+ ids, err := lockAssignedUserRowsInternal(tx, id)+ if err != nil {+ return err}+ affected = idsif err := tx.Delete(&models.Role{}, "id = ?", id).Error; err != nil {return errors.WrapIf(err, "failed to delete role")}@@ -457,6 +487,17 @@ func (s *RoleService) replaceUserAssignmentsForSourceInternal(ctx context.Contexdesired[i].Source = source}err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {+ // Lock the target's user row so assignment swaps serialize with+ // UserService update/delete transactions, whose in-tx privilege+ // checks lock the same row.+ if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).+ Where("id = ?", userID).+ First(&models.User{}).Error; err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return ErrUserNotFound+ }+ return errors.WrapIf(err, "failed to lock user for assignment update")+ }if err := validateAssignmentsExistInternal(tx, desired); err != nil {return err}diff --git a/backend/internal/services/user_service.go b/backend/internal/services/user_service.goindex 255071491..12ca621c9 100644--- a/backend/internal/services/user_service.go+++ b/backend/internal/services/user_service.go@@ -48,7 +48,14 @@ type UserService struct {argon2Params *Argon2Params}-const ErrCannotRemoveLastAdmin = errors.Sentinel("cannot remove the last admin user")+const (+ ErrCannotRemoveLastAdmin = errors.Sentinel("cannot remove the last admin user")++ // ErrInsufficientPrivilege is returned when a caller attempts to modify a+ // target whose effective privilege is equal to or higher than the caller's+ // (e.g. a delegated users:update holder trying to edit a global admin).+ ErrInsufficientPrivilege = errors.Sentinel("insufficient privilege to modify this user")+)func NewUserService(db *database.DB) *UserService {return &UserService{@@ -172,16 +179,92 @@ func (s *UserService) GetUserByEmail(ctx context.Context, email string) (*modelsreturn dbutil.FirstWhere[models.User](ctx, s.db.DB, ErrUserNotFound, "email = ?", email)}-func (s *UserService) UpdateUser(ctx context.Context, user *models.User) (*models.User, error) {+// ResolveUserPermissions returns the effective PermissionSet for the given+// user ID, or nil when no RoleService is wired (RBAC disabled paths).+func (s *UserService) ResolveUserPermissions(ctx context.Context, userID string) (*authz.PermissionSet, error) {+ if s.roleService == nil {+ return nil, nil+ }+ return s.roleService.ResolvePermissions(ctx, &models.User{BaseModel: models.BaseModel{ID: userID}})+}++// checkTargetPrivilegeInternal enforces actor-vs-target privilege ordering: a+// caller may not modify a target whose effective permissions make them a global+// admin unless the caller is itself a global admin. This prevents holders of+// delegated users:update/users:delete from seizing or removing admin accounts.+// A nil actorPerms denotes a trusted internal caller (e.g. the auth service+// acting on behalf of the account owner) and skips the privilege check.+//+// The target and any request-time global-admin actor are locked together before+// permissions are resolved through tx (never the TTL cache). Role-assignment+// writes lock the same user rows, so a concurrent promotion or demotion is+// serialized with the mutation. The request-time actor permissions remain part+// of the decision so revalidation can only reduce, never elevate, authority.+func (s *UserService) checkTargetPrivilegeInternal(ctx context.Context, tx *gorm.DB, actorPerms *authz.PermissionSet, targetID string) error {+ revalidateActor := actorPerms != nil && !actorPerms.Sudo && actorPerms.IsGlobalAdmin() && s.roleService != nil+ actorID := ""+ if revalidateActor {+ actor, ok := models.CurrentUserFromContext(ctx)+ if !ok || actor == nil || actor.ID == "" {+ return ErrInsufficientPrivilege+ }+ actorID = actor.ID+ }++ userIDs := []string{targetID}+ if actorID != "" && actorID != targetID {+ userIDs = append(userIDs, actorID)+ }+ var lockedUsers []models.User+ if err := tx.+ Clauses(clause.Locking{Strength: "UPDATE"}).+ Where("id IN ?", userIDs).+ Order("id ASC").+ Find(&lockedUsers).Error; err != nil {+ return errors.WrapIf(err, "failed to lock users")+ }+ targetFound := false+ actorFound := actorID == ""+ for i := range lockedUsers {+ targetFound = targetFound || lockedUsers[i].ID == targetID+ actorFound = actorFound || lockedUsers[i].ID == actorID+ }+ if !targetFound {+ return ErrUserNotFound+ }+ if !actorFound {+ return ErrInsufficientPrivilege+ }++ if actorPerms == nil || actorPerms.Sudo || s.roleService == nil {+ return nil+ }+ if revalidateActor {+ currentActorPerms, err := s.roleService.resolveUserPermissionsInternal(ctx, tx, actorID)+ if err != nil {+ return errors.WrapIf(err, "failed to resolve actor permissions")+ }+ if currentActorPerms != nil && currentActorPerms.IsGlobalAdmin() {+ return nil+ }+ }+ targetPerms, err := s.roleService.resolveUserPermissionsInternal(ctx, tx, targetID)+ if err != nil {+ return errors.WrapIf(err, "failed to resolve target permissions")+ }+ if targetPerms != nil && targetPerms.IsGlobalAdmin() {+ return ErrInsufficientPrivilege+ }+ return nil+}++// UpdateUser persists the given user. actorPerms identifies the caller+// performing the change; authenticated global-admin callers must also be+// present in ctx. Pass nil for internal service-to-service calls.+func (s *UserService) UpdateUser(ctx context.Context, user *models.User, actorPerms *authz.PermissionSet) (*models.User, error) {err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- if err := tx.- Clauses(clause.Locking{Strength: "UPDATE"}).- Where("id = ?", user.ID).- First(&models.User{}).Error; err != nil {- if errors.Is(err, gorm.ErrRecordNotFound) {- return ErrUserNotFound- }- return errors.WrapIf(err, "failed to load user")+ if err := s.checkTargetPrivilegeInternal(ctx, tx, actorPerms, user.ID); err != nil {+ return err}if err := tx.Save(user).Error; err != nil {return errors.WrapIf(err, "failed to update user")@@ -334,7 +417,11 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {return nil}-func (s *UserService) DeleteUser(ctx context.Context, id string) error {+// DeleteUser removes the user with the given id. actorPerms identifies the+// caller performing the deletion; authenticated global-admin callers must also+// be present in ctx. Pass nil for internal service-to-service calls. A+// non-admin caller may not delete a global admin target.+func (s *UserService) DeleteUser(ctx context.Context, id string, actorPerms *authz.PermissionSet) error {// Last-admin guard: if this user's effective permissions make them the only// global admin, refuse the delete. Checked outside the transaction because// RoleService uses its own session and the guard spans rows.@@ -354,14 +441,8 @@ func (s *UserService) DeleteUser(ctx context.Context, id string) error {}}return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- if err := tx.- Clauses(clause.Locking{Strength: "UPDATE"}).- Where("id = ?", id).- First(&models.User{}).Error; err != nil {- if errors.Is(err, gorm.ErrRecordNotFound) {- return ErrUserNotFound- }- return errors.WrapIf(err, "failed to load user")+ if err := s.checkTargetPrivilegeInternal(ctx, tx, actorPerms, id); err != nil {+ return err}if err := tx.Delete(&models.User{}, "id = ?", id).Error; err != nil {diff --git a/backend/internal/services/user_service_test.go b/backend/internal/services/user_service_test.goindex 1324911d0..2b36392e6 100644--- a/backend/internal/services/user_service_test.go+++ b/backend/internal/services/user_service_test.go@@ -47,7 +47,7 @@ func TestDeleteUserRejectsDeletingOnlyAdmin(t *testing.T) {admin := createTestUser(t, userSvc, "admin-1", "arcane")grantGlobalAdmin(t, roleSvc, admin.ID)- err := userSvc.DeleteUser(ctx, admin.ID)+ err := userSvc.DeleteUser(ctx, admin.ID, nil)require.ErrorIs(t, err, ErrCannotRemoveLastAdmin)stillThere, err := userSvc.GetUserByID(ctx, admin.ID)@@ -63,7 +63,7 @@ func TestDeleteUserAllowsDeletingNonAdmin(t *testing.T) {grantGlobalAdmin(t, roleSvc, admin.ID)nonAdmin := createTestUser(t, userSvc, "user-1", "user")- err := userSvc.DeleteUser(ctx, nonAdmin.ID)+ err := userSvc.DeleteUser(ctx, nonAdmin.ID, nil)require.NoError(t, err)_, err = userSvc.GetUserByID(ctx, nonAdmin.ID)@@ -79,7 +79,7 @@ func TestDeleteUserAllowsDeletingAdminWhenAnotherAdminExists(t *testing.T) {backup := createTestUser(t, userSvc, "admin-2", "backup")grantGlobalAdmin(t, roleSvc, backup.ID)- err := userSvc.DeleteUser(ctx, adminToDelete.ID)+ err := userSvc.DeleteUser(ctx, adminToDelete.ID, nil)require.NoError(t, err)_, err = userSvc.GetUserByID(ctx, adminToDelete.ID)@@ -122,7 +122,7 @@ func TestDeleteUserRejectsDeletingOnlyCustomAllPermissionsAdmin(t *testing.T) {{RoleID: customRole.ID, EnvironmentID: nil},}))- err = userSvc.DeleteUser(ctx, customAdmin.ID)+ err = userSvc.DeleteUser(ctx, customAdmin.ID, nil)require.ErrorIs(t, err, ErrCannotRemoveLastAdmin)users, _, err := userSvc.ListUsersPaginated(ctx, pagination.QueryParams{@@ -144,7 +144,7 @@ func TestUpdateUserPersistsFontSizeAndMapsToDto(t *testing.T) {require.Nil(t, u.FontSize, "new users default to no explicit font size")u.FontSize = new(16)- _, err := userSvc.UpdateUser(ctx, u)+ _, err := userSvc.UpdateUser(ctx, u, nil)require.NoError(t, err)reloaded, err := userSvc.GetUserByID(ctx, u.ID)@@ -172,7 +172,7 @@ func TestUpdateUserPersistsTimeFormatAndMapsToDto(t *testing.T) {} {t.Run(string(timeFormat), func(t *testing.T) {u.TimeFormat = timeFormat- _, err := userSvc.UpdateUser(ctx, u)+ _, err := userSvc.UpdateUser(ctx, u, nil)require.NoError(t, err)reloaded, err := userSvc.GetUserByID(ctx, u.ID)@@ -185,3 +185,122 @@ func TestUpdateUserPersistsTimeFormatAndMapsToDto(t *testing.T) {})}}++func TestUpdateUserRejectsNonAdminActorEditingAdmin(t *testing.T) {+ userSvc, roleSvc := setupUserAndRoleServices(t)+ ctx := context.Background()++ admin := createTestUser(t, userSvc, "admin-1", "arcane")+ grantGlobalAdmin(t, roleSvc, admin.ID)+ manager := createTestUser(t, userSvc, "mgr-1", "manager")+ managerRole, err := roleSvc.CreateRole(ctx, "User Manager", nil, []string{authz.PermUsersUpdate})+ require.NoError(t, err)+ require.NoError(t, roleSvc.SetUserAssignments(ctx, manager.ID, []models.UserRoleAssignment{+ {RoleID: managerRole.ID, EnvironmentID: nil},+ }))+ managerPerms, err := roleSvc.ResolvePermissions(ctx, manager)+ require.NoError(t, err)++ admin.PasswordHash = "attacker-controlled-hash"+ _, err = userSvc.UpdateUser(ctx, admin, managerPerms)+ require.ErrorIs(t, err, ErrInsufficientPrivilege)++ reloaded, err := userSvc.GetUserByID(ctx, admin.ID)+ require.NoError(t, err)+ require.NotEqual(t, "attacker-controlled-hash", reloaded.PasswordHash)+}++func TestUpdateUserAllowsGlobalAdminActorEditingAdmin(t *testing.T) {+ userSvc, roleSvc := setupUserAndRoleServices(t)+ ctx := context.Background()++ admin := createTestUser(t, userSvc, "admin-1", "arcane")+ grantGlobalAdmin(t, roleSvc, admin.ID)+ other := createTestUser(t, userSvc, "admin-2", "backup")+ grantGlobalAdmin(t, roleSvc, other.ID)+ otherPerms, err := roleSvc.ResolvePermissions(ctx, other)+ require.NoError(t, err)++ admin.DisplayName = new("Renamed Admin")+ actorCtx := models.WithCurrentUser(ctx, other)+ _, err = userSvc.UpdateUser(actorCtx, admin, otherPerms)+ require.NoError(t, err)+}++func TestUpdateUserAllowsNonAdminActorEditingNonAdmin(t *testing.T) {+ userSvc, roleSvc := setupUserAndRoleServices(t)+ ctx := context.Background()++ admin := createTestUser(t, userSvc, "admin-1", "arcane")+ grantGlobalAdmin(t, roleSvc, admin.ID)+ manager := createTestUser(t, userSvc, "mgr-1", "manager")+ managerRole, err := roleSvc.CreateRole(ctx, "User Manager", nil, []string{authz.PermUsersUpdate})+ require.NoError(t, err)+ require.NoError(t, roleSvc.SetUserAssignments(ctx, manager.ID, []models.UserRoleAssignment{+ {RoleID: managerRole.ID, EnvironmentID: nil},+ }))+ managerPerms, err := roleSvc.ResolvePermissions(ctx, manager)+ require.NoError(t, err)++ target := createTestUser(t, userSvc, "user-1", "plain-user")+ target.DisplayName = new("New Name")+ _, err = userSvc.UpdateUser(ctx, target, managerPerms)+ require.NoError(t, err)+}++func TestUpdateUserAllowsSelfEditByNonAdmin(t *testing.T) {+ userSvc, roleSvc := setupUserAndRoleServices(t)+ ctx := context.Background()++ admin := createTestUser(t, userSvc, "admin-1", "arcane")+ grantGlobalAdmin(t, roleSvc, admin.ID)+ adminPerms, err := roleSvc.ResolvePermissions(ctx, admin)+ require.NoError(t, err)++ admin.DisplayName = new("Self Rename")+ actorCtx := models.WithCurrentUser(ctx, admin)+ _, err = userSvc.UpdateUser(actorCtx, admin, adminPerms)+ require.NoError(t, err)+}++func TestDeleteUserRejectsNonAdminActorDeletingAdmin(t *testing.T) {+ userSvc, roleSvc := setupUserAndRoleServices(t)+ ctx := context.Background()++ admin := createTestUser(t, userSvc, "admin-1", "arcane")+ grantGlobalAdmin(t, roleSvc, admin.ID)+ backup := createTestUser(t, userSvc, "admin-2", "backup")+ grantGlobalAdmin(t, roleSvc, backup.ID)+ manager := createTestUser(t, userSvc, "mgr-1", "manager")+ managerRole, err := roleSvc.CreateRole(ctx, "User Manager", nil, []string{authz.PermUsersDelete})+ require.NoError(t, err)+ require.NoError(t, roleSvc.SetUserAssignments(ctx, manager.ID, []models.UserRoleAssignment{+ {RoleID: managerRole.ID, EnvironmentID: nil},+ }))+ managerPerms, err := roleSvc.ResolvePermissions(ctx, manager)+ require.NoError(t, err)++ // Two admins exist, so the last-admin guard would not fire — the+ // actor-vs-target privilege check is what must block this delete.+ err = userSvc.DeleteUser(ctx, admin.ID, managerPerms)+ require.ErrorIs(t, err, ErrInsufficientPrivilege)++ stillThere, err := userSvc.GetUserByID(ctx, admin.ID)+ require.NoError(t, err)+ require.Equal(t, admin.ID, stillThere.ID)+}++func TestDeleteUserAllowsGlobalAdminActorDeletingAdmin(t *testing.T) {+ userSvc, roleSvc := setupUserAndRoleServices(t)+ ctx := context.Background()++ admin := createTestUser(t, userSvc, "admin-1", "arcane")+ grantGlobalAdmin(t, roleSvc, admin.ID)+ other := createTestUser(t, userSvc, "admin-2", "backup")+ grantGlobalAdmin(t, roleSvc, other.ID)+ otherPerms, err := roleSvc.ResolvePermissions(ctx, other)+ require.NoError(t, err)++ actorCtx := models.WithCurrentUser(ctx, other)+ require.NoError(t, userSvc.DeleteUser(actorCtx, admin.ID, otherPerms))+}