A platform for community discussion. Free, open, simple.
FIX: Transfer orphaned owner ACLs when user is destroyed (#45089)
Martin Brennandbbfbe105b34
diff --git a/.skills/discourse-acl-authoring/SKILL.md b/.skills/discourse-acl-authoring/SKILL.mdindex 741a2d146c3..b40c036af6f 100644--- a/.skills/discourse-acl-authoring/SKILL.md+++ b/.skills/discourse-acl-authoring/SKILL.md@@ -23,7 +23,7 @@ Use this skill before adding or reviewing ACL-backed resource permissions in Dis- Treat `owner` as a reserved, user-only permission supplied through the replacement service's dedicated owner-user argument. Never accept owner grants from the ordinary flattened ACL argument.- Preserve owner grants during destructive ACL replacement. An owner implicitly satisfies every other permission check for the target, including target-id scopes.- Put ordinary ACL authorization at the caller boundary before `AccessControlList::Apply.call`. When `owner_user_ids` is supplied, the service separately requires the actor to be a current owner or admin.-- Always call `AccessControlList::Apply` for writes, including empty submitted ACL arrays, so mandatory ACLs are injected and old rows are replaced intentionally.+- Always call `AccessControlList::Apply` for submitted ACL writes, including empty arrays, so mandatory ACLs are injected and old rows are replaced intentionally. User-deletion ownership handoffs use `AccessControlList::ReassignDeletedUserOwnership` instead: it preserves stored ACL provenance and works without loading target classes.- Treat `AccessControlList.flattened_list` as the API shape for UI/client payloads and `AccessControlList.expand_list_for_bulk_insert` as the DB insert shape.- Use Guardian ACL helpers or `AclTarget` visibility scopes for checks and target scopes instead of hand-querying ACL tables in controllers.- Register plugin ACL targets with `DiscoursePluginRegistry.register_acl_target_class` so `Site#access_control` exposes mandatory and banned ACL metadata to the frontend.@@ -43,7 +43,7 @@ Use this skill before adding or reviewing ACL-backed resource permissions in Dis- User ACL cache: `app/models/user.rb`- Write service: `app/services/access_control_list/apply.rb`- Modification evaluation: `app/services/access_control_list/evaluate_modification.rb`, `app/controllers/access_control_lists_controller.rb`-- Deleted grantee cleanup: `app/jobs/regular/cleanup_acls_for_deleted.rb`, `app/models/group.rb`, `app/models/user.rb`+- Deleted grantee cleanup: `app/services/access_control_list/reassign_deleted_user_ownership.rb`, `app/jobs/regular/cleanup_acls_for_deleted.rb`, `app/models/group.rb`, `app/models/user.rb`- Site metadata: `app/models/site.rb`, `app/serializers/site_serializer.rb`- Frontend components: `frontend/discourse/app/ui-kit/d-access-control.gjs`, `frontend/discourse/app/ui-kit/d-access-control-field.gjs`- Core specs: `spec/models/access_control_list_spec.rb`, `spec/models/concerns/acl_target_spec.rb`, `spec/lib/acl/target_spec.rb`, `spec/jobs/regular/cleanup_acls_for_deleted_spec.rb`, `spec/services/access_control_list/apply_spec.rb`, `spec/services/access_control_list/evaluate_modification_spec.rb`, `spec/serializers/site_serializer_spec.rb`, `frontend/discourse/tests/integration/components/d-access-control-test.gjs`, `frontend/discourse/tests/integration/components/form-kit/field-test.gjs`diff --git a/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md b/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.mdindex 5bac8716b10..ee1559dc54a 100644--- a/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md+++ b/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md@@ -4,7 +4,7 @@ Use this reference when writing ACL rows, creating an ACL-backed target model, r## AccessControlList::Apply-`AccessControlList::Apply` is the standard write path for applying a target's complete ACL configuration. It resolves the registered target internally and serializes concurrent changes for the same target.+`AccessControlList::Apply` is the standard write path for applying a target's complete ACL configuration. It resolves the registered target internally and replaces ACL rows and writes audit records in a transaction.```rubyAccessControlList::Apply.call(@@ -32,7 +32,6 @@ Behavior:- validates the target identity, nested ordinary ACL entries, grantee identities, and `source`- resolves the target only from registered ACL target classes-- locks the target identity around the read, validation, and replacement sequence- reads previous target permissions directly from stored ACL rows- resolves `initial_owner_user_id` only when the target has no valid stored owner and creates the initial owner grant from that user- preserves existing owners when `owner_user_ids` is omitted; when supplied, treats it as the complete desired owner set@@ -181,7 +180,13 @@ serialize_data(targets, TargetSerializer, owners_by_target_id:)## Deleted Grantee Cleanup-`Group#clear_acls` and `User#clear_acls` enqueue `Jobs::CleanupAclsForDeleted` after a grantee is destroyed. The job removes the deleted group id from `allowed_group_ids` and/or the deleted user id from `allowed_user_ids`, updates `updated_at`, and deletes ACL rows only when both arrays are empty.+After the user row is destroyed, `User#reassign_acl_ownership` calls `AccessControlList::ReassignDeletedUserOwnership` synchronously in the destruction transaction, before `clear_acls`. The callback passes `user_id`, `username`, and `deleted_at` (`Time.current`) as a snapshot; the service does not look up the deleted user. The service is restricted to the system actor. It finds every stored owner ACL containing the departing user's ID and chooses one random active, unsuspended real admin other than that user for all targets. If none exists, ownership falls back to the system user.++The handoff replaces only the departing owner, preserves co-owners and `source`, deduplicates the new owner, and removes their redundant lower direct grants. This specialized write path operates on stored target identities without loading target classes, so disabled plugins do not prevent deletion. Ownership changes and audit records remain in the deletion transaction. Any failure rolls back deletion. Each transferred target gets an `assume_access_control_ownership` staff action with the recipient admin as actor and target user, the ACL target as subject, and snapshot values `deleted_user_id`, `deleted_username`, and ISO 8601 `deleted_at` in context. Quiet deletions still log the ownership handoff.++`Group#clear_acls` and `User#clear_acls` enqueue `Jobs::CleanupAclsForDeleted` after a grantee is destroyed. The job removes the deleted group id from `allowed_group_ids` and/or the deleted user id from `allowed_user_ids`, updates `updated_at`, and deletes ACL rows only when both arrays are empty. It skips user cleanup when that user ID currently exists, protecting restored records from stale jobs; group cleanup still runs if supplied in the same job.++Users are hard-deleted and have no normal per-account restoration flow. The staged-user CSV import creates accounts with newly assigned database IDs, so it does not reclaim transferred ownership. Anonymization retains the user ID and ownership. User merging deletes the source through `UserDestroyer`, so the same admin handoff applies. This lifecycle prevents new orphaned ownership; it does not backfill targets whose former owner rows were already removed.## Current Limitationsdiff --git a/.skills/discourse-acl-authoring/references/testing-and-review.md b/.skills/discourse-acl-authoring/references/testing-and-review.mdindex e8f70ec1478..0b7accd28fb 100644--- a/.skills/discourse-acl-authoring/references/testing-and-review.md+++ b/.skills/discourse-acl-authoring/references/testing-and-review.md@@ -55,7 +55,12 @@ For cleanup behavior:- Destroying a group enqueues `:cleanup_acls_for_deleted`.- `Jobs::CleanupAclsForDeleted` removes the group id from ACL rows.- Destroying a user enqueues `:cleanup_acls_for_deleted`.+- After the user row is deleted and before the destruction transaction completes, all their owner grants transfer to the same randomly selected eligible admin (or the system user if none exists), preserving co-owners and ACL `source` and removing redundant lower grants for the recipient. The service uses a supplied `user_id`, `username`, and `deleted_at` snapshot without looking up the deleted user.+- Each transferred target has an `assume_access_control_ownership` staff action with the recipient admin as actor, and the deleted user's ID, username, and deletion timestamp in context, including for quiet deletions.+- Failed deletion rolls back ownership transfers and their audit records. Repeated handoffs and cleanup jobs do not remove or duplicate replacement ownership.+- Handoffs support stored target types whose classes are unavailable.- `Jobs::CleanupAclsForDeleted` removes the user id from ACL rows.+- Cleanup skips user IDs that currently exist, while still processing a deleted group supplied in the same job.- ACL rows with no remaining group or user ids are deleted.- ACL rows that still have user ids are preserved.- ACL rows that still have group ids are preserved.diff --git a/app/jobs/regular/cleanup_acls_for_deleted.rb b/app/jobs/regular/cleanup_acls_for_deleted.rbindex 69effa3d627..92de0459a31 100644--- a/app/jobs/regular/cleanup_acls_for_deleted.rb+++ b/app/jobs/regular/cleanup_acls_for_deleted.rb@@ -5,6 +5,7 @@ module Jobsdef execute(args)group_id = args[:group_id]user_id = args[:user_id]+ user_id = nil if user_id.present? && User.exists?(id: user_id)return if group_id.blank? && user_id.blank?if group_id.present?diff --git a/app/models/user.rb b/app/models/user.rbindex db8dbad6e7b..4d0daa1cef4 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -196,8 +196,20 @@ class User < ActiveRecord::Baseafter_update :trigger_user_automatic_group_refresh, if: :saved_change_to_staged?after_update :change_display_name, if: :saved_change_to_name?+ after_destroy :reassign_acl_ownership, unless: :new_record?after_destroy :clear_acls+ def reassign_acl_ownership+ AccessControlList::ReassignDeletedUserOwnership.call!(+ guardian: Discourse.system_user.guardian,+ params: {+ user_id: id,+ username: username,+ deleted_at: Time.current,+ },+ )+ end+def clear_aclsJobs.enqueue(:cleanup_acls_for_deleted, user_id: id)enddiff --git a/app/models/user_history.rb b/app/models/user_history.rbindex cb2f3721a70..070932ce88d 100644--- a/app/models/user_history.rb+++ b/app/models/user_history.rb@@ -187,6 +187,7 @@ class UserHistory < ActiveRecord::Basecreate_group: 132,add_access_control_list_owner: 133,remove_access_control_list_owner: 134,+ assume_access_control_ownership: 135,)end@@ -325,6 +326,7 @@ class UserHistory < ActiveRecord::Basecreate_groupadd_access_control_list_ownerremove_access_control_list_owner+ assume_access_control_ownership]enddiff --git a/app/services/access_control_list/action/reassign_deleted_user_ownership.rb b/app/services/access_control_list/action/reassign_deleted_user_ownership.rbnew file mode 100644index 00000000000..161b51e4c13--- /dev/null+++ b/app/services/access_control_list/action/reassign_deleted_user_ownership.rb@@ -0,0 +1,43 @@+# frozen_string_literal: true++class AccessControlList::Action::ReassignDeletedUserOwnership < Service::ActionBase+ option :owner_acl+ option :deleted_user_id+ option :deleted_username+ option :deleted_at+ option :new_admin_owner++ def call+ acls =+ AccessControlList.where(target_type: owner_acl.target_type, target_id: owner_acl.target_id)+ current_owner_acl =+ acls.where(permission: Acl::Permissions::OWNER).allowing_user(deleted_user_id).first+ return if !current_owner_acl++ current_owner_acl.update!(+ allowed_user_ids:+ (current_owner_acl.allowed_user_ids - [deleted_user_id] + [new_admin_owner.id]).uniq,+ )++ ordinary_acls =+ acls.where.not(permission: Acl::Permissions::OWNER).allowing_user(new_admin_owner.id)+ ordinary_acls.update_all(+ [+ "allowed_user_ids = array_remove(allowed_user_ids, ?), updated_at = ?",+ new_admin_owner.id,+ Time.current,+ ],+ )+ acls+ .where.not(permission: Acl::Permissions::OWNER)+ .where("allowed_user_ids = '{}'::bigint[] AND allowed_group_ids = '{}'::bigint[]")+ .delete_all++ StaffActionLogger.new(new_admin_owner).log_assume_access_control_ownership(+ current_owner_acl,+ user_id: deleted_user_id,+ username: deleted_username,+ deleted_at:,+ )+ end+enddiff --git a/app/services/access_control_list/reassign_deleted_user_ownership.rb b/app/services/access_control_list/reassign_deleted_user_ownership.rbnew file mode 100644index 00000000000..218deccbc2b--- /dev/null+++ b/app/services/access_control_list/reassign_deleted_user_ownership.rb@@ -0,0 +1,62 @@+# frozen_string_literal: true++class AccessControlList::ReassignDeletedUserOwnership+ include Service::Base++ params do+ attribute :user_id, :integer+ attribute :username, :string+ attribute :deleted_at, :datetime++ validates :user_id, numericality: { only_integer: true }+ validates :username, :deleted_at, presence: true+ end++ policy :is_system_actor++ transaction do+ model :owner_acls, optional: true+ only_if(:owns_acl_targets) do+ model :random_admin+ each(:owner_acls) { step :reassign_ownership }+ end+ end++ private++ def is_system_actor(guardian:)+ return false if guardian.anonymous?+ guardian.user.is_system_user?+ end++ def fetch_owner_acls(params:)+ AccessControlList+ .where(permission: Acl::Permissions::OWNER)+ .allowing_user(params.user_id)+ .order(:target_type, :target_id)+ .to_a+ end++ def owns_acl_targets(owner_acls:)+ owner_acls.any?+ end++ def fetch_random_admin(params:)+ User+ .active_admins+ .not_suspended+ .where.not(id: params.user_id)+ .order(Arel.sql("RANDOM()"))+ .first || Discourse.system_user+ end++ def reassign_ownership(owner_acl:, params:, random_admin:)+ AccessControlList::Action::ReassignDeletedUserOwnership.call(+ owner_acl:,+ new_admin_owner: random_admin,+ deleted_user_id: params.user_id,+ deleted_username: params.username,+ deleted_at: params.deleted_at,+ )+ end+enddiff --git a/app/services/staff_action_logger.rb b/app/services/staff_action_logger.rbindex 6c34948176f..c3c7be38b30 100644--- a/app/services/staff_action_logger.rb+++ b/app/services/staff_action_logger.rb@@ -423,6 +423,18 @@ class StaffActionLoggerlog_access_control_list_owner_change(:remove_access_control_list_owner, target, user, opts)end+ def log_assume_access_control_ownership(owner_acl, user_id:, username:, deleted_at:)+ UserHistory.create!(+ params.merge(+ action: UserHistory.actions[:assume_access_control_ownership],+ subject: "#{owner_acl.target_type} (#{owner_acl.target_id})",+ target_user_id: @admin.id,+ context:+ "deleted_user_id: #{user_id}\ndeleted_username: #{username}\ndeleted_at: #{deleted_at.iso8601}",+ ),+ )+ end+def theme_json(theme)ThemeSerializer.new(theme, root: false, include_theme_field_values: true).to_jsonenddiff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex a059ec7c1a4..60fd48e34ab 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -9733,6 +9733,7 @@ en:change_access_control_list_permissions: "change access control list permissions"add_access_control_list_owner: "add access control list owner"remove_access_control_list_owner: "remove access control list owner"+ assume_access_control_ownership: "assume access control ownership"admin_onboarding_step_completed: "complete admin onboarding step"admin_onboarding_completed: "complete admin onboarding"admin_onboarding_dismissed: "dismiss admin onboarding"diff --git a/plugins/boards/spec/requests/boards/boards_controller_spec.rb b/plugins/boards/spec/requests/boards/boards_controller_spec.rbindex 79f5e9c77d9..2b879f257c2 100644--- a/plugins/boards/spec/requests/boards/boards_controller_spec.rb+++ b/plugins/boards/spec/requests/boards/boards_controller_spec.rb@@ -747,6 +747,25 @@ RSpec.describe Boards::Api::BoardsController doFabricate(:boards_board, created_by: admin, additional_manage_groups: [manage_group])end+ it "saves settings with the replacement owner after the previous owner is deleted" do+ departing_owner = Fabricate(:user)+ board = Fabricate(:boards_board, created_by: departing_owner)+ UserDestroyer.new(admin).destroy(departing_owner)+ sign_in(admin)++ put "/boards/api/boards/#{board.id}.json",+ params: {+ board: {+ name: "Reassigned board",+ owner_user_ids: [admin.id],+ },+ }++ expect(response.status).to eq(200)+ expect(board.reload.name).to eq("Reassigned board")+ expect(response.parsed_body["board"]["owners"].pluck("id")).to eq([admin.id])+ end+it "accepts all supported ACL permissions and retains mandatory admin access" dosign_in(manager)diff --git a/spec/jobs/regular/cleanup_acls_for_deleted_spec.rb b/spec/jobs/regular/cleanup_acls_for_deleted_spec.rbindex 7477248b42f..b10d96c4ed3 100644--- a/spec/jobs/regular/cleanup_acls_for_deleted_spec.rb+++ b/spec/jobs/regular/cleanup_acls_for_deleted_spec.rb@@ -1,6 +1,38 @@# frozen_string_literal: trueRSpec.describe Jobs::CleanupAclsForDeleted do+ describe "#execute" do+ fab!(:user)++ it "preserves ACL grants for an existing or restored user" do+ acl = Fabricate(:access_control_list_with_users, users: [user])++ described_class.new.execute(user_id: user.id)++ expect(acl.reload.allowed_user_ids).to eq([user.id])+ end++ it "still cleans deleted groups when the supplied user exists" do+ group = Fabricate(:group)+ acl = Fabricate(:access_control_list_with_users_and_groups, users: [user], groups: [group])+ group.destroy!++ described_class.new.execute(user_id: user.id, group_id: group.id)++ expect(acl.reload).to have_attributes(allowed_user_ids: [user.id], allowed_group_ids: [])+ end++ it "preserves transferred ownership when cleanup runs repeatedly" do+ admin = Fabricate(:admin)+ acl = Fabricate(:access_control_list_with_users, permission: "owner", users: [user])+ user.destroy!++ 2.times { described_class.new.execute(user_id: user.id) }++ expect(acl.reload.allowed_user_ids).to eq([admin.id])+ end+ end+context "when a group is deleted" dofab!(:group)fab!(:other_group, :group)diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rbindex 078fe80ad85..381e5e0b412 100644--- a/spec/models/user_spec.rb+++ b/spec/models/user_spec.rb@@ -3438,6 +3438,60 @@ RSpec.describe User doenddescribe "#destroy!" do+ it "destroys an unsaved user without attempting an ownership handoff" do+ user = Fabricate.build(:user)++ user.destroy!++ expect(user).to be_destroyed+ end++ it "transfers owned ACLs after removing the user record" do+ user = Fabricate(:user)+ admin = Fabricate(:admin)+ owner_acl = Fabricate(:access_control_list_with_users, permission: "owner", users: [user])++ queries = track_sql_queries { user.destroy! }++ expect(user).to be_destroyed+ expect(owner_acl.reload.allowed_user_ids).to eq([admin.id])+ deletion_index = queries.index { |query| query.match?(/DELETE FROM "users"/) }+ transfer_index = queries.index { |query| query.match?(/UPDATE "access_control_lists"/) }+ expect(deletion_index).to be < transfer_index+ end++ it "rolls back ownership and its audit entry when a later destruction callback fails" do+ user = Fabricate(:user)+ Fabricate(:admin)+ owner_acl = Fabricate(:access_control_list_with_users, permission: "owner", users: [user])+ user.stubs(:clear_acls).raises(ActiveRecord::RecordNotDestroyed)+ audit_count =+ UserHistory.where(action: UserHistory.actions[:assume_access_control_ownership]).count++ expect { user.destroy! }.to raise_error(ActiveRecord::RecordNotDestroyed)++ expect(User.exists?(user.id)).to eq(true)+ expect(owner_acl.reload.allowed_user_ids).to eq([user.id])+ expect(+ UserHistory.where(action: UserHistory.actions[:assume_access_control_ownership]).count,+ ).to eq(audit_count)+ end++ it "preserves the user and ownership if the assumption cannot be audited" do+ user = Fabricate(:user)+ Fabricate(:admin)+ owner_acl = Fabricate(:access_control_list_with_users, permission: "owner", users: [user])+ StaffActionLogger+ .any_instance+ .stubs(:log_assume_access_control_ownership)+ .raises(ActiveRecord::RecordInvalid)++ expect { user.destroy! }.to raise_error(ActiveRecord::RecordInvalid)++ expect(User.exists?(user.id)).to eq(true)+ expect(owner_acl.reload.allowed_user_ids).to eq([user.id])+ end+it "clears up associated data on destroy!" douser = Fabricate(:user)post = Fabricate(:post)diff --git a/spec/services/access_control_list/action/reassign_deleted_user_ownership_spec.rb b/spec/services/access_control_list/action/reassign_deleted_user_ownership_spec.rbnew file mode 100644index 00000000000..b608182716b--- /dev/null+++ b/spec/services/access_control_list/action/reassign_deleted_user_ownership_spec.rb@@ -0,0 +1,67 @@+# frozen_string_literal: true++RSpec.describe AccessControlList::Action::ReassignDeletedUserOwnership do+ describe ".call" do+ subject(:reassign_ownership) do+ described_class.call(+ owner_acl:,+ deleted_user_id: user.id,+ deleted_username: user.username,+ deleted_at:,+ new_admin_owner:,+ )+ end++ fab!(:user)+ fab!(:new_admin_owner, :admin)+ fab!(:owner_acl) do+ Fabricate(:access_control_list_with_users, permission: "owner", users: [user])+ end++ let(:deleted_at) { Time.zone.parse("2026-10-26T01:23:45Z") }++ it "removes redundant grants for the new owner while preserving other users and groups" do+ group = Fabricate(:group)+ other_user = Fabricate(:user)+ view_acl =+ Fabricate(+ :access_control_list_with_users_and_groups,+ target: owner_acl.target,+ permission: "view",+ users: [new_admin_owner, other_user],+ groups: [group],+ )+ manage_acl =+ Fabricate(+ :access_control_list_with_users,+ target: owner_acl.target,+ permission: "manage",+ users: [new_admin_owner],+ )++ reassign_ownership++ expect(view_acl.reload).to have_attributes(+ allowed_user_ids: [other_user.id],+ allowed_group_ids: [group.id],+ )+ expect(AccessControlList.exists?(manage_acl.id)).to eq(false)+ end++ it "transfers ownership for a target type whose class is unavailable" do+ owner_acl.update_columns(target_type: "UnavailableAclTarget")++ reassign_ownership++ expect(owner_acl.reload.allowed_user_ids).to eq([new_admin_owner.id])+ expect(UserHistory.last.subject).to eq("UnavailableAclTarget (#{owner_acl.target_id})")+ end++ it "leaves records unchanged when the user has already lost ownership" do+ owner_acl.update!(allowed_user_ids: [new_admin_owner.id])++ expect { reassign_ownership }.not_to change(UserHistory, :count)+ expect(owner_acl.reload.allowed_user_ids).to eq([new_admin_owner.id])+ end+ end+enddiff --git a/spec/services/access_control_list/apply_spec.rb b/spec/services/access_control_list/apply_spec.rbindex e26dcc1f6ee..508418dad4e 100644--- a/spec/services/access_control_list/apply_spec.rb+++ b/spec/services/access_control_list/apply_spec.rb@@ -192,6 +192,26 @@ RSpec.describe AccessControlList::Apply doendend+ context "when a deleted owner is submitted after their ownership was transferred" do+ fab!(:owner_acl) do+ Fabricate(+ :access_control_list_with_users,+ target:,+ permission: Acl::Permissions::OWNER,+ users: [target_owner],+ )+ end++ let(:owner_user_ids) { [target_owner.id] }++ before { target_owner.destroy! }++ it "rejects the stale owner and preserves the replacement admin" do+ expect(result).to fail_a_policy(:requested_owners_exist)+ expect(owner_acl.reload.allowed_user_ids).to eq([admin.id])+ end+ end+context "when an admin specifies owners for an ownerless target" dolet(:acl_entries) { [] }let(:owner_user_ids) { [co_owner.id] }diff --git a/spec/services/access_control_list/reassign_deleted_user_ownership_spec.rb b/spec/services/access_control_list/reassign_deleted_user_ownership_spec.rbnew file mode 100644index 00000000000..75d399eb71e--- /dev/null+++ b/spec/services/access_control_list/reassign_deleted_user_ownership_spec.rb@@ -0,0 +1,151 @@+# frozen_string_literal: true++RSpec.describe AccessControlList::ReassignDeletedUserOwnership do+ describe described_class::Contract, type: :model do+ it { is_expected.to allow_values(-2, -1, 0, 1, 42).for(:user_id) }+ it { is_expected.not_to allow_value(nil).for(:user_id) }+ it { is_expected.to validate_presence_of(:username) }+ it { is_expected.to validate_presence_of(:deleted_at) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:user)+ fab!(:acting_user) { Discourse.system_user }+ fab!(:admin)+ fab!(:owner_acl) do+ Fabricate(:access_control_list_with_users, permission: "owner", users: [user])+ end++ let(:params) { { user_id: user.id, username: user.username, deleted_at: } }+ let(:deleted_at) { Time.zone.parse("2026-10-26T01:23:45Z") }+ let(:dependencies) { { guardian: acting_user.guardian } }++ context "with an invalid user ID" do+ let(:params) { super().merge(user_id: nil) }++ it { is_expected.to fail_a_contract }+ end++ context "when the actor is anonymous" do+ let(:dependencies) { { guardian: Guardian.new } }++ it { is_expected.to fail_a_policy(:is_system_actor) }+ end++ context "when the actor is an administrator" do+ fab!(:acting_user, :admin)++ it { is_expected.to fail_a_policy(:is_system_actor) }+ end++ context "when the user record has already been deleted" do+ let(:params) { super().merge(username: "DeletedSnapshotUsername") }++ before { User.where(id: user.id).delete_all }++ it "transfers ownership and audits the supplied identity snapshot" do+ expect(result).to run_successfully+ expect(owner_acl.reload.allowed_user_ids).to eq([admin.id])+ expect(UserHistory.last.context).to eq(+ "deleted_user_id: #{user.id}\ndeleted_username: #{params[:username]}\ndeleted_at: #{deleted_at.iso8601}",+ )+ end+ end++ context "when the departing user has a reserved negative ID" do+ fab!(:user) { Fabricate(:user, id: -123) }++ before { owner_acl.update!(allowed_user_ids: [user.id]) }++ it "transfers the reserved user's ownership to an admin" do+ expect(result).to run_successfully+ expect(owner_acl.reload.allowed_user_ids).to eq([admin.id])+ end+ end++ context "without owned ACLs" do+ before { owner_acl.update!(permission: "view") }++ it "succeeds without changing permissions or creating an audit entry" do+ expect { result }.not_to change(UserHistory, :count)+ expect(result).to run_successfully+ expect(owner_acl.reload.allowed_user_ids).to eq([user.id])+ end+ end++ context "with owned ACLs" do+ it "transfers ownership and records the departing user's identity" do+ expect { result }.to change { owner_acl.reload.allowed_user_ids }.from([user.id]).to(+ [admin.id],+ )+ expect(result).to run_successfully+ expect(UserHistory.last).to have_attributes(+ action: UserHistory.actions[:assume_access_control_ownership],+ acting_user_id: admin.id,+ target_user_id: admin.id,+ subject: "#{owner_acl.target_type} (#{owner_acl.target_id})",+ context:+ "deleted_user_id: #{user.id}\ndeleted_username: #{user.username}\ndeleted_at: #{deleted_at.iso8601}",+ )+ end++ it "selects the same eligible administrator for every owned target" do+ other_admin = Fabricate(:admin)+ other_acl = Fabricate(:access_control_list_with_users, permission: "owner", users: [user])+ Fabricate(:admin, active: false)+ Fabricate(:admin, suspended_till: 1.day.from_now)++ expect { result }.to change {+ UserHistory.where(action: UserHistory.actions[:assume_access_control_ownership]).count+ }.by(2)+ expect(result).to run_successfully+ selected_admin_id = owner_acl.reload.allowed_user_ids.sole+ expect([admin.id, other_admin.id]).to include(selected_admin_id)+ expect(other_acl.reload.allowed_user_ids).to eq([selected_admin_id])+ end++ it "preserves other owners and the source without duplicating the selected admin" do+ coowner = Fabricate(:user)+ owner_acl.update!(allowed_user_ids: [user.id, coowner.id, admin.id], source: "extension")++ expect(result).to run_successfully+ expect(owner_acl.reload).to have_attributes(+ allowed_user_ids: [coowner.id, admin.id],+ source: "extension",+ )+ end++ it "does not transfer unrelated ACLs" do+ other_owner = Fabricate(:user)+ other_acl =+ Fabricate(:access_control_list_with_users, permission: "owner", users: [other_owner])++ expect(result).to run_successfully+ expect(other_acl.reload.allowed_user_ids).to eq([other_owner.id])+ end++ it "leaves ownership and audit records unchanged on a repeated call" do+ expect(result).to run_successfully++ expect { described_class.call(params:, **dependencies) }.not_to change(UserHistory, :count)+ expect(owner_acl.reload.allowed_user_ids).to eq([admin.id])+ end+ end++ context "without another eligible administrator" do+ before do+ admin.update!(active: false)+ user.update!(admin: true)+ Fabricate(:admin, suspended_till: 1.day.from_now)+ end++ it "uses the system user when the departing user is the only active admin" do+ expect(result).to run_successfully+ expect(owner_acl.reload.allowed_user_ids).to eq([Discourse.system_user.id])+ expect(UserHistory.last.acting_user_id).to eq(Discourse.system_user.id)+ end+ end+ end+enddiff --git a/spec/services/staff_action_logger_spec.rb b/spec/services/staff_action_logger_spec.rbindex 7d3f6fdc6e2..8f34b3a76ba 100644--- a/spec/services/staff_action_logger_spec.rb+++ b/spec/services/staff_action_logger_spec.rb@@ -47,6 +47,33 @@ RSpec.describe StaffActionLogger doendend+ describe "#log_assume_access_control_ownership" do+ fab!(:deleted_user, :user)+ fab!(:owner_acl) do+ Fabricate(:access_control_list_with_users, permission: "owner", users: [deleted_user])+ end++ it "records the new owner, target, and departing user's identity" do+ deleted_at = Time.zone.parse("2026-10-26T01:23:45Z")+ entry =+ logger.log_assume_access_control_ownership(+ owner_acl,+ user_id: deleted_user.id,+ username: deleted_user.username,+ deleted_at:,+ )++ expect(entry).to have_attributes(+ action: UserHistory.actions[:assume_access_control_ownership],+ acting_user_id: admin.id,+ target_user_id: admin.id,+ subject: "#{owner_acl.target_type} (#{owner_acl.target_id})",+ context:+ "deleted_user_id: #{deleted_user.id}\ndeleted_username: #{deleted_user.username}\ndeleted_at: #{deleted_at.iso8601}",+ )+ end+ end+describe "log_user_deletion" dosubject(:log_user_deletion) { described_class.new(admin).log_user_deletion(deleted_user) }diff --git a/spec/services/user_destroyer_spec.rb b/spec/services/user_destroyer_spec.rbindex 027def05f30..1123724df00 100644--- a/spec/services/user_destroyer_spec.rb+++ b/spec/services/user_destroyer_spec.rb@@ -15,6 +15,21 @@ RSpec.describe UserDestroyer doenddescribe "#destroy" do+ it "transfers ownership and records the assumption during quiet deletion" do+ freeze_time+ owner_acl = Fabricate(:access_control_list_with_users, permission: "owner", users: [user])++ expect { UserDestroyer.new(admin).destroy(user, quiet: true) }.to change {+ UserHistory.where(action: UserHistory.actions[:assume_access_control_ownership]).count+ }.by(1)++ expect(user).to be_destroyed+ expect(owner_acl.reload.allowed_user_ids).to eq([admin.id])+ expect(UserHistory.last.context).to eq(+ "deleted_user_id: #{user.id}\ndeleted_username: #{user.username}\ndeleted_at: #{Time.current.iso8601}",+ )+ end+it "raises an error when user is nil" doexpect { UserDestroyer.new(admin).destroy(nil) }.to raise_error(Discourse::InvalidParameters)end