A platform for community discussion. Free, open, simple.
DEV: Add guardian checks for theme edits and palette creation (#45125)
Keegan George0f52471898e6
diff --git a/app/controllers/admin/color_schemes_controller.rb b/app/controllers/admin/color_schemes_controller.rbindex e0ebe99d3fc..8aaaba1ac96 100644--- a/app/controllers/admin/color_schemes_controller.rb+++ b/app/controllers/admin/color_schemes_controller.rb@@ -10,6 +10,8 @@ class Admin::ColorSchemesController < Admin::AdminControllerenddef create+ guardian.ensure_can_create_color_scheme!+color_scheme = ColorScheme.create(color_scheme_params)if color_scheme.valid?render json: color_scheme, root: false@@ -21,6 +23,16 @@ class Admin::ColorSchemesController < Admin::AdminControllerdef updateupdate_params = color_scheme_params+ # a theme's own palettes are part of the theme, and the default-on-theme+ # options change the default theme's palettes+ if @color_scheme.theme.present? && !guardian.can_edit_theme?(@color_scheme.theme)+ raise Discourse::InvalidAccess+ end+ if (Array(update_params&.keys) & %w[default_light_on_theme default_dark_on_theme]).present? &&+ !guardian.can_edit_theme?(Theme.find_default)+ raise Discourse::InvalidAccess+ end+if @color_scheme.theme_id.present?if (update_params.key?(:name) && update_params[:name] != @color_scheme.name) ||(diff --git a/app/controllers/admin/config/design_wizard_controller.rb b/app/controllers/admin/config/design_wizard_controller.rbindex f13974a08ae..495881f4872 100644--- a/app/controllers/admin/config/design_wizard_controller.rb+++ b/app/controllers/admin/config/design_wizard_controller.rb@@ -20,6 +20,8 @@ class Admin::Config::DesignWizardController < Admin::AdminControlleron_model_not_found(:theme) { raise Discourse::NotFound }# unreachable via AdminController, but don't let it 422 if that changeson_failed_policy(:current_user_is_admin) { raise Discourse::InvalidAccess }+ on_failed_policy(:can_edit_theme) { raise Discourse::InvalidAccess }+ on_failed_policy(:can_create_needed_palettes) { raise Discourse::InvalidAccess }on_failed_policy(:palettes_available_to_theme) dorender json:failed_json.merge(errors: [I18n.t("design_wizard.errors.palette_unavailable")]),diff --git a/app/controllers/admin/site_texts_controller.rb b/app/controllers/admin/site_texts_controller.rbindex af6149edd29..31c17638e0e 100644--- a/app/controllers/admin/site_texts_controller.rb+++ b/app/controllers/admin/site_texts_controller.rb@@ -221,6 +221,7 @@ class Admin::SiteTextsController < Admin::AdminControllerdef update_theme_text(locale, revert: false)text = ThemeTranslationManager.find_site_text(params[:id], locale:)raise Discourse::NotFound unless text+ guardian.ensure_can_edit_theme!(text.theme)old_value = text.valueif revertdiff --git a/app/controllers/admin/themes_controller.rb b/app/controllers/admin/themes_controller.rbindex 4837bd0d705..728b4d78379 100644--- a/app/controllers/admin/themes_controller.rb+++ b/app/controllers/admin/themes_controller.rb@@ -81,9 +81,12 @@ class Admin::ThemesController < Admin::AdminControllerif params[:placeholder]create_remote_theme_placeholder(remote, branch:, private_key:)else- RemoteTheme.import_theme(remote, theme_user, private_key:, branch:)+ RemoteTheme.import_theme(remote, theme_user, private_key:, branch:, guardian:)endrender json: serialize_data(@theme, ThemeSerializer), status: :created+ rescue Discourse::InvalidAccess+ # hijacked requests don't go through the usual error handling+ render_json_error I18n.t("invalid_access"), status: :forbiddenrescue RemoteTheme::ImportError => eif params[:force]@theme = create_remote_theme_placeholder(remote, branch:, private_key:)@@ -103,6 +106,10 @@ class Admin::ThemesController < Admin::AdminControllerupdate_components = params[:components]run_migrations = !params[:skip_migrations]+ if theme_id.present? && (existing_theme = Theme.find_by(id: theme_id))+ guardian.ensure_can_edit_theme!(existing_theme)+ end+begin@theme =RemoteTheme.update_zipped_theme(@@ -112,6 +119,7 @@ class Admin::ThemesController < Admin::AdminControllertheme_id:,update_components:,run_migrations:,+ guardian:,)log_theme_change(nil, @theme)@@ -178,6 +186,20 @@ class Admin::ThemesController < Admin::AdminController@theme = Theme.include_relations.find_by(id: params[:id])raise Discourse::InvalidParameters.new(:id) unless @theme+ guardian.ensure_can_edit_theme!(@theme)+ child_theme_ids = theme_params[:child_theme_ids]+ parent_theme_ids = theme_params[:parent_theme_ids]+ # switching between theme and component drops the relations on one side+ case theme_params[:component].to_s+ when "true"+ child_theme_ids = [] if [email protected]?+ when "false"+ parent_theme_ids = [] if @theme.component?+ end+ if !guardian.can_edit_theme_relations?(@theme, child_theme_ids:, parent_theme_ids:)+ raise Discourse::InvalidAccess+ end+original_json = ThemeSerializer.new(@theme, root: false).to_jsondisables_component = [false, "false"].include?(theme_params[:enabled])enables_component = [true, "true"].include?(theme_params[:enabled])@@ -214,7 +236,11 @@ class Admin::ThemesController < Admin::AdminControllerskipped_components =@theme.remote_theme- .update_from_remote(raise_if_theme_save_fails: false, raise_on_import_error: true)+ .update_from_remote(+ raise_if_theme_save_fails: false,+ raise_on_import_error: true,+ guardian:,+ ).skipped_child_componentselse@theme.save@@ -254,6 +280,7 @@ class Admin::ThemesController < Admin::AdminControllerrender json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_requestendon_model_not_found(:theme) { raise Discourse::NotFound }+ on_failed_policy(:can_edit_theme) { raise Discourse::InvalidAccess }endend@@ -264,6 +291,7 @@ class Admin::ThemesController < Admin::AdminControllerrender json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_requestendon_model_not_found(:themes) { raise Discourse::NotFound }+ on_failed_policy(:can_edit_themes) { raise Discourse::InvalidAccess }endend@@ -304,6 +332,7 @@ class Admin::ThemesController < Admin::AdminControllerparams.require("name")@theme = Theme.find_by(id: params[:id])raise Discourse::InvalidParameters.new(:id) unless @theme+ guardian.ensure_can_edit_theme!(@theme)setting_name = params[:name].to_symnew_value = params[:value] || nil@@ -341,6 +370,7 @@ class Admin::ThemesController < Admin::AdminControllerendendon_failed_policy(:current_user_is_admin) { raise Discourse::InvalidAccess }+ on_failed_policy(:can_edit_theme) { raise Discourse::InvalidAccess }on_failed_policy(:ensure_setting_is_themeable) dorender_json_error(I18n.t("themes.setting_not_themeable", name: params[:name]), status: 400)end@@ -364,6 +394,7 @@ class Admin::ThemesController < Admin::AdminControllerdef update_source@theme = Theme.include_relations.find_by(id: params[:id])raise Discourse::InvalidParameters.new(:id) unless @theme+ guardian.ensure_can_edit_theme!(@theme)raise Discourse::InvalidParameters.new(:remote_theme) unless @theme.remote_theme&.is_git?remote_url = params[:remote_url]&.strip@@ -400,7 +431,11 @@ class Admin::ThemesController < Admin::AdminControllerremote_theme.branch = params[:branch].presenceremote_theme.private_key = private_key if private_key.present?- remote_theme.update_from_remote(already_in_transaction: true, refresh_name_and_type: true)+ remote_theme.update_from_remote(+ already_in_transaction: true,+ refresh_name_and_type: true,+ guardian:,+ )if remote_theme.last_error_text.present?raise RemoteTheme::ImportError.new(remote_theme.last_error_text)@@ -410,6 +445,10 @@ class Admin::ThemesController < Admin::AdminControllerlog_theme_change(nil, theme.reload)render json: theme_json(theme, skipped_components: remote_theme.skipped_child_components),status: :ok+ rescue Discourse::InvalidAccess+ # hijacked requests don't go through the usual error handling+ remote_theme.reload+ render_json_error I18n.t("invalid_access"), status: :forbiddenrescue RemoteTheme::ImportError, ActiveRecord::RecordInvalid, Theme::SettingsMigrationError => eremote_theme.reloadrender_json_error e.messagediff --git a/app/models/remote_theme.rb b/app/models/remote_theme.rbindex 321ed3ebe8c..54f73297c85 100644--- a/app/models/remote_theme.rb+++ b/app/models/remote_theme.rb@@ -73,7 +73,8 @@ class RemoteTheme < ActiveRecord::Baseuser: Discourse.system_user,theme_id: nil,update_components: nil,- run_migrations: true+ run_migrations: true,+ guardian: nil)update_theme(ThemeStore::ZipImporter.new(filename, original_filename),@@ -81,9 +82,62 @@ class RemoteTheme < ActiveRecord::Basetheme_id:,update_components:,run_migrations:,+ guardian:,)end+ # Importing a theme can include its listed components, or drop the ones it+ # no longer lists, which changes where their code runs. When an import+ # runs for someone, every existing component it would include or drop has+ # to be editable by them.+ # The archive may have just changed whether the theme is a component, so+ # removals go by the links the theme has now: syncing drops them either way.+ def self.ensure_can_change_components!(guardian, theme, component_urls, update_components:)+ return if guardian.nil?++ urls = component_urls.map { |url| ThemeStore::GitImporter.new(url.strip).url }+ # components are only included in themes+ adds_components = !theme.component?+ if theme.new_record?+ return if update_components == "none" || !adds_components+ added_ids = component_ids_for(urls)+ removed_ids = []+ else+ return if update_components.blank? || update_components == "none"+ added_ids = adds_components ? component_ids_for(urls) - theme.child_theme_ids : []+ removed_ids =+ if update_components == "sync"+ theme+ .child_themes+ .joins(:remote_theme)+ .where.not(remote_themes: { remote_url: urls })+ .pluck(:id)+ else+ []+ end+ end++ changed = Theme.where(id: added_ids + removed_ids)+ raise Discourse::InvalidAccess if !changed.all? { |related| guardian.can_edit_theme?(related) }+ end++ def self.ensure_can_change_type!(guardian, theme)+ return if guardian.nil? || !theme.will_save_change_to_component?++ if !guardian.can_edit_theme_relations?(+ theme,+ child_theme_ids: theme.component? ? [] : nil,+ parent_theme_ids: theme.component? ? nil : [],+ )+ raise Discourse::InvalidAccess+ end+ end++ def self.component_ids_for(urls)+ Theme.joins(:remote_theme).where(remote_themes: { remote_url: urls }).pluck(:id)+ end+ private_class_method :component_ids_for+def self.import_theme_from_directory(directory,theme_id: nil,@@ -106,7 +160,8 @@ class RemoteTheme < ActiveRecord::Baseupdate_components: nil,run_migrations: true,allow_out_of_sequence_migration: false,- before_save: nil+ before_save: nil,+ guardian: nil)importer.import!@@ -126,9 +181,11 @@ class RemoteTheme < ActiveRecord::Baseendtheme.component = theme_info["component"].to_s == "true"+ ensure_can_change_type!(guardian, theme)theme.child_components = theme_info["components"].presence || []theme.skip_child_components_update = true if update_components == "none"update_children = existing && update_components.present? && update_components != "none"+ ensure_can_change_components!(guardian, theme, theme.child_components, update_components:)remote_theme = newremote_theme.theme = theme@@ -165,7 +222,13 @@ class RemoteTheme < ActiveRecord::Baseendprivate_class_method :update_theme- def self.import_theme(url, user = Discourse.system_user, private_key: nil, branch: nil)+ def self.import_theme(+ url,+ user = Discourse.system_user,+ private_key: nil,+ branch: nil,+ guardian: nil+ )importer = ThemeStore::GitImporter.new(url.strip, private_key: private_key, branch: branch)importer.import!@@ -181,7 +244,7 @@ class RemoteTheme < ActiveRecord::Baseremote_theme.branch = branchremote_theme.remote_url = importer.url- remote_theme.update_from_remote(importer)+ remote_theme.update_from_remote(importer, guardian:)themeensure@@ -246,7 +309,8 @@ class RemoteTheme < ActiveRecord::Baseallow_out_of_sequence_migration: false,before_save: nil,raise_on_import_error: false,- refresh_name_and_type: false+ refresh_name_and_type: false,+ guardian: nil)cleanup = false@@ -307,8 +371,19 @@ class RemoteTheme < ActiveRecord::Baseif was_placeholder || refresh_name_and_typetheme.name = theme_info["name"]theme.component = [true, "true"].include?(theme_info["component"])+ self.class.ensure_can_change_type!(guardian, theme)+ end+ if was_placeholder+ theme.child_components = theme_info["components"].presence || []+ # a new theme links its components when it's created, and finishing a+ # placeholder links them afterwards+ self.class.ensure_can_change_components!(+ guardian,+ theme,+ theme.child_components,+ update_components: new_theme ? nil : "merge",+ )end- theme.child_components = theme_info["components"].presence || [] if was_placeholderMETADATA_PROPERTIES.each { |property| public_send(:"#{property}=", theme_info[property.to_s]) }diff --git a/app/services/design_wizard/action/resolve_palette.rb b/app/services/design_wizard/action/resolve_palette.rbindex 08feb1630ad..71601c58cc8 100644--- a/app/services/design_wizard/action/resolve_palette.rb+++ b/app/services/design_wizard/action/resolve_palette.rb@@ -3,6 +3,13 @@class DesignWizard::Action::ResolvePalette < Service::ActionBaseoption :palette_id+ # Whether resolving the palette creates one: a built-in palette the wizard+ # hasn't saved yet.+ def self.creates_palette?(palette_id)+ palette_id.present? && palette_id.negative? &&+ !ColorScheme.exists?(base_scheme_id: palette_id, via_wizard: true)+ end+def callreturn if palette_id.blank?return ColorScheme.find_by(id: palette_id) if palette_id.positive?diff --git a/app/services/design_wizard/apply.rb b/app/services/design_wizard/apply.rbindex 57a4abb103c..6c715d96acd 100644--- a/app/services/design_wizard/apply.rb+++ b/app/services/design_wizard/apply.rb@@ -116,7 +116,9 @@ class DesignWizard::Applypolicy :current_user_is_adminmodel :theme+ policy :can_edit_themepolicy :palettes_available_to_theme+ policy :can_create_needed_palettestransaction domodel :light_palette, :resolve_light_palette, optional: true@@ -142,6 +144,26 @@ class DesignWizard::ApplyTheme.find_by(id: params.theme_id)end+ def can_edit_theme(guardian:, theme:)+ guardian.can_edit_theme?(theme)+ end++ # Built-in palettes are saved the first time they're chosen or offered.+ def can_create_needed_palettes(params:, theme:, guardian:)+ return true if guardian.can_create_color_scheme?++ palette_ids = [params.light_palette_id, params.dark_palette_id]+ if enabling_built_in_palettes(params:, theme:)+ palette_ids +=+ DesignWizard::PalettePairs::BUILT_IN_PAIRS.flat_map do |pair|+ pair.values_at(:light, :dark).compact.map { |name| ColorScheme::NAMES_TO_ID_MAP[name] }+ end+ end+ palette_ids.none? do |palette_id|+ DesignWizard::Action::ResolvePalette.creates_palette?(palette_id)+ end+ end+def palettes_available_to_theme(params:, theme:)[params.light_palette_id, params.dark_palette_id].all? do |palette_id|palette_id.nil? || palette_id.negative? ||diff --git a/app/services/themes/bulk_destroy.rb b/app/services/themes/bulk_destroy.rbindex 49a42943df8..e6e46d5549f 100644--- a/app/services/themes/bulk_destroy.rb+++ b/app/services/themes/bulk_destroy.rb@@ -34,6 +34,7 @@ class Themes::BulkDestroyendmodel :themes+ policy :can_edit_themestransaction dostep :log_themes_destroy@@ -46,6 +47,13 @@ class Themes::BulkDestroyTheme.where(id: params.theme_ids)end+ # deleting a theme also removes it from the themes it's related to+ def can_edit_themes(guardian:, themes:)+ themes.all? do |theme|+ guardian.can_edit_theme_relations?(theme, child_theme_ids: [], parent_theme_ids: [])+ end+ end+def log_themes_destroy(themes:, guardian:)staff_action_logger = StaffActionLogger.new(guardian.user)themes.each { |theme| staff_action_logger.log_theme_destroy(theme) }diff --git a/app/services/themes/destroy.rb b/app/services/themes/destroy.rbindex 59d8eae9843..28504e68998 100644--- a/app/services/themes/destroy.rb+++ b/app/services/themes/destroy.rb@@ -28,6 +28,7 @@ class Themes::Destroyendmodel :theme+ policy :can_edit_themepolicy :not_defaulttransaction do@@ -41,6 +42,11 @@ class Themes::DestroyTheme.find_by(id: params.id)end+ # deleting a theme also removes it from the themes it's related to+ def can_edit_theme(guardian:, theme:)+ guardian.can_edit_theme_relations?(theme, child_theme_ids: [], parent_theme_ids: [])+ end+def not_default(theme:)!theme.default?enddiff --git a/app/services/themes/theme_site_setting_manager.rb b/app/services/themes/theme_site_setting_manager.rbindex 82385849f91..7c53f64191c 100644--- a/app/services/themes/theme_site_setting_manager.rb+++ b/app/services/themes/theme_site_setting_manager.rb@@ -26,6 +26,7 @@ class Themes::ThemeSiteSettingManagerpolicy :current_user_is_adminpolicy :ensure_setting_is_themeablemodel :theme+ policy :can_edit_thememodel :existing_theme_site_setting, optional: truetransaction do@@ -50,6 +51,10 @@ class Themes::ThemeSiteSettingManagerTheme.find_by(id: params.theme_id)end+ def can_edit_theme(guardian:, theme:)+ guardian.can_edit_theme?(theme)+ end+def fetch_existing_theme_site_setting(params:, theme:)theme.theme_site_settings.find_by(name: params.name)enddiff --git a/lib/discourse_mcp/tools/themes.rb b/lib/discourse_mcp/tools/themes.rbindex 98004f355b9..e654fb67ae4 100644--- a/lib/discourse_mcp/tools/themes.rb+++ b/lib/discourse_mcp/tools/themes.rb@@ -154,6 +154,15 @@ module DiscourseMcptheme = ::Theme.include_relations.find_by(id: arguments.fetch("theme_id"))raise ToolError, I18n.t("mcp.errors.theme_not_found") if theme.blank?+ guardian.ensure_can_edit_theme!(theme)+ if !guardian.can_edit_theme_relations?(+ theme,+ child_theme_ids: arguments["child_theme_ids"],+ parent_theme_ids: arguments["parent_theme_ids"],+ )+ raise Discourse::InvalidAccess+ end+ensure_system_theme_editable!(theme, arguments)if arguments.keys == ["theme_id"]raise ToolError, I18n.t("mcp.errors.theme_update_required")diff --git a/lib/guardian/user_guardian.rb b/lib/guardian/user_guardian.rbindex d9cc68db3c1..f8aa82f9baf 100644--- a/lib/guardian/user_guardian.rb+++ b/lib/guardian/user_guardian.rb@@ -306,4 +306,44 @@ module UserGuardian# to non-admins)DiscoursePluginRegistry.apply_modifier(:user_guardian_can_create_theme, true, self)end++ def can_edit_theme?(theme)+ return false if !is_admin? || theme.blank?+ # theme imports and maintenance tasks run as the system user and have to+ # apply a theme in full, so plugin restrictions don't apply to them+ return true if @user.is_system_user?+ # like the creation modifier, this one can only further restrict which+ # themes can be changed or deleted+ DiscoursePluginRegistry.apply_modifier(:user_guardian_can_edit_theme, true, self, theme)+ end++ # Including a component in a theme, or removing it, changes where the+ # component's code runs, so both sides of the change have to be editable.+ def can_edit_theme_relations?(theme, child_theme_ids: nil, parent_theme_ids: nil)+ return false if !can_edit_theme?(theme)++ changed_ids = []+ if !child_theme_ids.nil?+ changed_ids.concat(changed_theme_ids(theme.child_theme_ids, child_theme_ids))+ end+ if !parent_theme_ids.nil?+ changed_ids.concat(changed_theme_ids(theme.parent_theme_ids, parent_theme_ids))+ end+ return true if changed_ids.empty?++ Theme.where(id: changed_ids.uniq).all? { |related| can_edit_theme?(related) }+ end++ def can_create_color_scheme?+ return false if !is_admin?+ # like the theme modifiers, this one can only further restrict palette creation+ DiscoursePluginRegistry.apply_modifier(:user_guardian_can_create_color_scheme, true, self)+ end++ private++ def changed_theme_ids(current_ids, new_ids)+ new_ids = Array(new_ids).map(&:to_i)+ (current_ids - new_ids) | (new_ids - current_ids)+ endenddiff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_theme_translations_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_theme_translations_controller.rbindex e84cd56193a..fa58d58acce 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_theme_translations_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_theme_translations_controller.rb@@ -8,6 +8,7 @@ module DiscourseAidef createtheme = Theme.find_by(id: params[:theme_id])raise Discourse::NotFound if theme.blank?+ guardian.ensure_can_edit_theme!(theme)locale = params[:locale].to_ssource_locale = (locale.present? && LocaleSiteSetting.valid_value?(locale)) ? locale : "en"diff --git a/plugins/discourse-ai/spec/requests/admin/ai_theme_translations_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_theme_translations_controller_spec.rbindex 7454ec74348..b7656ec269b 100644--- a/plugins/discourse-ai/spec/requests/admin/ai_theme_translations_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/admin/ai_theme_translations_controller_spec.rb@@ -33,6 +33,29 @@ describe DiscourseAi::Admin::AiThemeTranslationsController doexpect(response.status).to eq(204)end+ it "respects plugin restrictions on theme edits" do+ plugin = Plugin::Instance.new+ modifier = proc { false }+ plugin.register_modifier(:user_guardian_can_edit_theme, &modifier)++ expect_not_enqueued_with(job: :localize_theme_translations) do+ post "/admin/plugins/discourse-ai/ai-theme-translations.json",+ params: {+ theme_id: theme.id,+ }+ end++ expect(response.status).to eq(403)+ ensure+ if plugin+ DiscoursePluginRegistry.unregister_modifier(+ plugin,+ :user_guardian_can_edit_theme,+ &modifier+ )+ end+ end+it "passes a valid locale through as source_locale" doexpect_enqueued_with(job: :localize_theme_translations,diff --git a/spec/lib/discourse_mcp/staff_tools_spec.rb b/spec/lib/discourse_mcp/staff_tools_spec.rbindex 911ceb96d18..63150f38076 100644--- a/spec/lib/discourse_mcp/staff_tools_spec.rb+++ b/spec/lib/discourse_mcp/staff_tools_spec.rb@@ -679,6 +679,44 @@ describe DiscourseMcp::Tools doend.to raise_error(Discourse::InvalidAccess)end+ it "respects plugin restrictions on theme edits" do+ component = Fabricate(:theme, component: true, name: "Restricted")+ plugin = Plugin::Instance.new+ modifier = proc { |allowed, _guardian, target| allowed && target.id != component.id }+ plugin.register_modifier(:user_guardian_can_edit_theme, &modifier)++ expect do+ described_class.call(+ arguments: {+ "theme_id" => component.id,+ "name" => "Renamed",+ },+ request_context: request_context(admin),+ )+ end.to raise_error(Discourse::InvalidAccess)++ expect do+ described_class.call(+ arguments: {+ "theme_id" => theme.id,+ "child_theme_ids" => [component.id],+ },+ request_context: request_context(admin),+ )+ end.to raise_error(Discourse::InvalidAccess)++ expect(component.reload.name).to eq("Restricted")+ expect(theme.reload.child_theme_ids).to be_empty+ ensure+ if plugin+ DiscoursePluginRegistry.unregister_modifier(+ plugin,+ :user_guardian_can_edit_theme,+ &modifier+ )+ end+ end+it "updates attributes and fields" doresult =described_class.call(diff --git a/spec/lib/guardian/user_guardian_spec.rb b/spec/lib/guardian/user_guardian_spec.rbindex a37aad8a007..93a629a9f05 100644--- a/spec/lib/guardian/user_guardian_spec.rb+++ b/spec/lib/guardian/user_guardian_spec.rb@@ -896,4 +896,145 @@ RSpec.describe UserGuardian doexpect(Guardian.new(moderator).can_check_sso_payload?(user)).to eq(false)endend++ describe "theme permissions" do+ fab!(:theme)+ fab!(:locked_theme, :theme)+ fab!(:component) { Fabricate(:theme, component: true) }+ fab!(:locked_component) { Fabricate(:theme, component: true) }++ let(:plugin) { Plugin::Instance.new }++ describe "#can_edit_theme?" do+ it "allows admins only" do+ expect(Guardian.new(admin).can_edit_theme?(theme)).to eq(true)+ expect(Guardian.new(moderator).can_edit_theme?(theme)).to eq(false)+ expect(Guardian.new(user).can_edit_theme?(theme)).to eq(false)+ expect(Guardian.new.can_edit_theme?(theme)).to eq(false)+ expect(Guardian.new(admin).can_edit_theme?(nil)).to eq(false)+ end++ it "lets a plugin restrict which themes admins can edit" do+ received = []+ modifier =+ proc do |_allowed, guardian, target|+ received << [guardian.user, target]+ false+ end+ plugin.register_modifier(:user_guardian_can_edit_theme, &modifier)++ expect(Guardian.new(admin).can_edit_theme?(theme)).to eq(false)+ expect(received).to eq([[admin, theme]])+ ensure+ DiscoursePluginRegistry.unregister_modifier(+ plugin,+ :user_guardian_can_edit_theme,+ &modifier+ )+ end++ it "doesn't let a plugin open theme editing to non-admins" do+ modifier = proc { true }+ plugin.register_modifier(:user_guardian_can_edit_theme, &modifier)++ expect(Guardian.new(moderator).can_edit_theme?(theme)).to eq(false)+ ensure+ DiscoursePluginRegistry.unregister_modifier(+ plugin,+ :user_guardian_can_edit_theme,+ &modifier+ )+ end++ it "doesn't apply plugin restrictions to the system user" do+ modifier = proc { false }+ plugin.register_modifier(:user_guardian_can_edit_theme, &modifier)++ expect(Discourse.system_user.guardian.can_edit_theme?(theme)).to eq(true)+ expect(Guardian.new(admin).can_edit_theme?(theme)).to eq(false)+ ensure+ DiscoursePluginRegistry.unregister_modifier(+ plugin,+ :user_guardian_can_edit_theme,+ &modifier+ )+ end+ end++ describe "#can_edit_theme_relations?" do+ let(:locked_ids) { [locked_theme.id, locked_component.id] }+ let(:edit_modifier) do+ proc { |allowed, _guardian, target| allowed && locked_ids.exclude?(target.id) }+ end++ before { plugin.register_modifier(:user_guardian_can_edit_theme, &edit_modifier) }++ after do+ DiscoursePluginRegistry.unregister_modifier(+ plugin,+ :user_guardian_can_edit_theme,+ &edit_modifier+ )+ end++ it "allows linking and unlinking editable themes" do+ guardian = Guardian.new(admin)++ expect(guardian.can_edit_theme_relations?(theme, child_theme_ids: [component.id])).to eq(+ true,+ )+ expect(+ guardian.can_edit_theme_relations?(component, parent_theme_ids: [theme.id.to_s]),+ ).to eq(true)+ end++ it "requires every theme whose links change to be editable" do+ guardian = Guardian.new(admin)++ expect(+ guardian.can_edit_theme_relations?(theme, child_theme_ids: [locked_component.id]),+ ).to eq(false)+ expect(+ guardian.can_edit_theme_relations?(component, parent_theme_ids: [locked_theme.id]),+ ).to(eq(false))+ expect(guardian.can_edit_theme_relations?(locked_theme, child_theme_ids: [])).to eq(false)+ end++ it "ignores links that stay the same" do+ theme.add_relative_theme!(:child, locked_component)+ guardian = Guardian.new(admin)++ expect(+ guardian.can_edit_theme_relations?(+ theme,+ child_theme_ids: [locked_component.id, component.id],+ ),+ ).to eq(true)+ expect(guardian.can_edit_theme_relations?(theme, child_theme_ids: [component.id])).to eq(+ false,+ )+ end+ end++ describe "#can_create_color_scheme?" do+ it "allows admins only" do+ expect(Guardian.new(admin).can_create_color_scheme?).to eq(true)+ expect(Guardian.new(moderator).can_create_color_scheme?).to eq(false)+ end++ it "lets a plugin restrict palette creation" do+ modifier = proc { |allowed, guardian| allowed && guardian.user != admin }+ plugin.register_modifier(:user_guardian_can_create_color_scheme, &modifier)++ expect(Guardian.new(admin).can_create_color_scheme?).to eq(false)+ expect(Guardian.new(Fabricate(:admin)).can_create_color_scheme?).to eq(true)+ ensure+ DiscoursePluginRegistry.unregister_modifier(+ plugin,+ :user_guardian_can_create_color_scheme,+ &modifier+ )+ end+ end+ endenddiff --git a/spec/models/remote_theme_spec.rb b/spec/models/remote_theme_spec.rbindex 847deb37e3e..2deb019f9ab 100644--- a/spec/models/remote_theme_spec.rb+++ b/spec/models/remote_theme_spec.rb@@ -535,6 +535,30 @@ RSpec.describe RemoteTheme doexpect(theme.theme_site_settings.first.data_type).to eq(SiteSetting.types[:bool])end+ it "creates them while a plugin restricts theme edits" do+ plugin = Plugin::Instance.new+ modifier = proc { false }+ plugin.register_modifier(:user_guardian_can_edit_theme, &modifier)+ add_to_git_repo(+ initial_repo,+ "about.json" =>+ JSON+ .parse(about_json)+ .merge("theme_site_settings" => { "enable_welcome_banner" => false })+ .to_json,+ )++ theme = RemoteTheme.import_theme(initial_repo_url)++ expect(theme.theme_site_settings.pluck(:name, :value)).to eq([%w[enable_welcome_banner f]])+ ensure+ DiscoursePluginRegistry.unregister_modifier(+ plugin,+ :user_guardian_can_edit_theme,+ &modifier+ )+ end+it "does not remove theme site settings that are no longer in about.json" doadd_to_git_repo(initial_repo,diff --git a/spec/requests/admin/color_schemes_controller_spec.rb b/spec/requests/admin/color_schemes_controller_spec.rbindex cf35e4fe3b6..b25de2a24c3 100644--- a/spec/requests/admin/color_schemes_controller_spec.rb+++ b/spec/requests/admin/color_schemes_controller_spec.rb@@ -90,6 +90,25 @@ RSpec.describe Admin::ColorSchemesController doexpect(response.status).to eq(422)expect(response.parsed_body["errors"]).to be_presentend++ it "respects plugin restrictions on palette creation" do+ plugin = Plugin::Instance.new+ modifier = proc { false }+ plugin.register_modifier(:user_guardian_can_create_color_scheme, &modifier)++ expect do post "/admin/color_schemes.json", params: valid_params end.not_to change {+ ColorScheme.count+ }+ expect(response.status).to eq(403)+ ensure+ if plugin+ DiscoursePluginRegistry.unregister_modifier(+ plugin,+ :user_guardian_can_create_color_scheme,+ &modifier+ )+ end+ endendshared_examples "color scheme creation not allowed" do@@ -125,6 +144,43 @@ RSpec.describe Admin::ColorSchemesController docontext "when logged in as an admin" dobefore { sign_in(admin) }+ it "respects plugin restrictions on theme edits" do+ plugin = Plugin::Instance.new+ locked_theme = Fabricate(:theme)+ locked_theme.set_default!+ theme_palette = Fabricate(:color_scheme, theme: locked_theme)+ modifier = proc { |allowed, _guardian, theme| allowed && theme.id != locked_theme.id }+ plugin.register_modifier(:user_guardian_can_edit_theme, &modifier)++ put "/admin/color_schemes/#{existing.id}.json",+ params: {+ color_scheme: {+ default_light_on_theme: true,+ },+ }+ expect(response.status).to eq(403)+ expect(locked_theme.reload.color_scheme_id).not_to eq(existing.id)++ put "/admin/color_schemes/#{theme_palette.id}.json",+ params: {+ color_scheme: {+ colors: valid_params[:color_scheme][:colors],+ },+ }+ expect(response.status).to eq(403)++ put "/admin/color_schemes/#{existing.id}.json", params: valid_params+ expect(response.status).to eq(200)+ ensure+ if plugin+ DiscoursePluginRegistry.unregister_modifier(+ plugin,+ :user_guardian_can_edit_theme,+ &modifier+ )+ end+ end+it "returns success" doput "/admin/color_schemes/#{existing.id}.json", params: valid_paramsexpect(response.status).to eq(200)diff --git a/spec/requests/admin/theme_site_texts_controller_spec.rb b/spec/requests/admin/theme_site_texts_controller_spec.rbindex f58fee4bdd4..d357bd4d22a 100644--- a/spec/requests/admin/theme_site_texts_controller_spec.rb+++ b/spec/requests/admin/theme_site_texts_controller_spec.rb@@ -180,6 +180,28 @@ RSpec.describe Admin::SiteTextsController doexpect(ThemeTranslationOverride.where(theme: theme)).to be_emptyend+ it "respects plugin restrictions on theme edits" do+ plugin = Plugin::Instance.new+ modifier = proc { |allowed, _guardian, target| allowed && target.id != theme.id }+ plugin.register_modifier(:user_guardian_can_edit_theme, &modifier)++ put path, params: { site_text: { locale: "en", value: "Blocked" } }+ expect(response.status).to eq(403)++ delete path, params: { locale: "en" }+ expect(response.status).to eq(403)++ expect(ThemeTranslationOverride.where(theme: theme)).to be_empty+ ensure+ if plugin+ DiscoursePluginRegistry.unregister_modifier(+ plugin,+ :user_guardian_can_edit_theme,+ &modifier+ )+ end+ end+it "rejects unknown keys and malformed values" doput "/admin/customize/site_texts/js.theme_translations.#{theme.id}.missing.json",params: {diff --git a/spec/requests/admin/themes_controller_spec.rb b/spec/requests/admin/themes_controller_spec.rbindex 872c0af5933..fef05375ba2 100644--- a/spec/requests/admin/themes_controller_spec.rb+++ b/spec/requests/admin/themes_controller_spec.rb@@ -2119,4 +2119,327 @@ RSpec.describe Admin::ThemesController do)endend++ describe "with a plugin restricting theme edits" do+ fab!(:theme)+ fab!(:locked_theme) { Fabricate(:theme, name: "Locked theme") }+ fab!(:locked_component) { Fabricate(:theme, name: "Locked component", component: true) }++ let(:plugin) { Plugin::Instance.new }+ let(:modifier) do+ proc do |allowed, _guardian, target|+ allowed && [locked_theme.id, locked_component.id].exclude?(target.id)+ end+ end+ let(:theme_archive) do+ Rack::Test::UploadedFile.new(+ file_from_fixtures("discourse-test-theme.zip", "themes"),+ "application/zip",+ )+ end++ before do+ sign_in(admin)+ plugin.register_modifier(:user_guardian_can_edit_theme, &modifier)+ end++ after do+ DiscoursePluginRegistry.unregister_modifier(plugin, :user_guardian_can_edit_theme, &modifier)+ end++ it "still allows editing other themes" do+ put "/admin/themes/#{theme.id}.json", params: { theme: { name: "Renamed" } }++ expect(response.status).to eq(200)+ expect(theme.reload.name).to eq("Renamed")+ end++ it "blocks changes to a restricted theme" do+ put "/admin/themes/#{locked_theme.id}.json", params: { theme: { name: "Renamed" } }+ expect(response.status).to eq(403)++ put "/admin/themes/#{locked_theme.id}/setting.json", params: { name: "bg", value: "green" }+ expect(response.status).to eq(403)++ put "/admin/themes/#{locked_theme.id}/site-setting.json",+ params: {+ name: "enable_welcome_banner",+ value: false,+ }+ expect(response.status).to eq(403)++ put "/admin/themes/#{locked_theme.id}/source.json", params: { remote_url: repo_url }+ expect(response.status).to eq(403)++ expect(locked_theme.reload.name).to eq("Locked theme")+ expect(locked_theme.theme_site_settings).to be_empty+ end++ it "blocks replacing a restricted theme with an uploaded archive" do+ post "/admin/themes/import.json", params: { bundle: theme_archive, theme_id: locked_theme.id }++ expect(response.status).to eq(403)+ expect(locked_theme.reload.theme_fields).to be_empty+ end++ it "blocks deleting a restricted theme" do+ delete "/admin/themes/#{locked_theme.id}.json"+ expect(response.status).to eq(403)++ delete "/admin/themes/bulk_destroy.json", params: { theme_ids: [theme.id, locked_theme.id] }+ expect(response.status).to eq(403)++ expect(Theme.where(id: [theme.id, locked_theme.id]).count).to eq(2)+ end++ it "blocks including or removing a restricted component" do+ put "/admin/themes/#{theme.id}.json",+ params: {+ theme: {+ child_theme_ids: [locked_component.id],+ },+ }+ expect(response.status).to eq(403)+ expect(theme.reload.child_theme_ids).to be_empty++ put "/admin/themes/#{locked_component.id}.json",+ params: {+ theme: {+ parent_theme_ids: [theme.id],+ },+ }+ expect(response.status).to eq(403)++ component = Fabricate(:theme, component: true)+ theme.add_relative_theme!(:child, locked_component)+ put "/admin/themes/#{theme.id}.json", params: { theme: { child_theme_ids: [component.id] } }+ expect(response.status).to eq(403)+ expect(theme.reload.child_theme_ids).to eq([locked_component.id])++ put "/admin/themes/#{theme.id}.json",+ params: {+ theme: {+ child_theme_ids: [locked_component.id, component.id],+ },+ }+ expect(response.status).to eq(200)+ expect(theme.reload.child_theme_ids).to contain_exactly(locked_component.id, component.id)+ end++ describe "importing a theme that lists components" do+ let(:locked_url) do+ ThemeStore::GitImporter.new("https://github.com/org/locked-component").url+ end+ let(:other_url) { ThemeStore::GitImporter.new("https://github.com/org/other-component").url }+ let!(:other_component) do+ Fabricate(:theme, component: true, remote_theme: RemoteTheme.create!(remote_url: other_url))+ end++ before { locked_component.update!(remote_theme: RemoteTheme.create!(remote_url: locked_url)) }++ def archive(components, component: false)+ dir = Dir.mktmpdir+ FileUtils.mkdir_p(File.join(dir, "listing-theme"))+ File.write(+ File.join(dir, "listing-theme", "about.json"),+ { name: "Listing theme", component:, components: }.to_json,+ )+ Rack::Test::UploadedFile.new(+ Compression::Zip.new.compress(dir, "listing-theme"),+ "application/zip",+ )+ end++ it "blocks including a restricted component in a new theme" do+ expect do+ post "/admin/themes/import.json", params: { bundle: archive([locked_url]) }+ end.not_to change { Theme.count }++ expect(response.status).to eq(403)+ expect(locked_component.reload.parent_theme_ids).to be_empty+ end++ it "blocks including or dropping a restricted component when updating a theme" do+ theme.add_relative_theme!(:child, locked_component)++ post "/admin/themes/import.json",+ params: {+ bundle: archive([]),+ theme_id: theme.id,+ components: "sync",+ }+ expect(response.status).to eq(403)+ expect(theme.reload.child_theme_ids).to eq([locked_component.id])++ other_theme = Fabricate(:theme)+ post "/admin/themes/import.json",+ params: {+ bundle: archive([locked_url]),+ theme_id: other_theme.id,+ components: "merge",+ }+ expect(response.status).to eq(403)+ expect(other_theme.reload.child_theme_ids).to be_empty+ end++ it "blocks dropping a restricted component from a theme the archive turns into a component" do+ theme.add_relative_theme!(:child, locked_component)++ post "/admin/themes/import.json",+ params: {+ bundle: archive([], component: true),+ theme_id: theme.id,+ components: "sync",+ }++ expect(response.status).to eq(403)+ expect(theme.reload.child_theme_ids).to eq([locked_component.id])+ end++ %w[none merge sync].each do |components|+ it "blocks type changes removing restricted children when replacing an archive with #{components}" do+ theme.add_relative_theme!(:child, locked_component)++ post "/admin/themes/import.json",+ params: {+ bundle: archive([], component: true),+ theme_id: theme.id,+ components:,+ }++ expect(response.status).to eq(403)+ expect(theme.reload).not_to be_component+ expect(theme.child_theme_ids).to eq([locked_component.id])+ end++ it "blocks type changes removing restricted parents when replacing an archive with #{components}" do+ component = Fabricate(:theme, component: true)+ locked_theme.add_relative_theme!(:child, component)++ post "/admin/themes/import.json",+ params: {+ bundle: archive([]),+ theme_id: component.id,+ components:,+ }++ expect(response.status).to eq(403)+ expect(component.reload).to be_component+ expect(locked_theme.reload.child_theme_ids).to eq([component.id])+ end+ end++ it "blocks including a restricted component in a theme imported from a repository" do+ repo =+ setup_git_repo(+ "about.json" => { name: "Listing theme", components: [locked_url] }.to_json,+ )+ remote = MockGitImporter.register("https://github.com/org/listing-theme.git", repo)++ expect { post "/admin/themes/import.json", params: { remote: } }.not_to change {+ Theme.count+ }++ expect(response.status).to eq(403)+ expect(locked_component.reload.parent_theme_ids).to be_empty+ end++ it "blocks including a restricted component when finishing a placeholder" do+ listing_repo =+ setup_git_repo(+ "about.json" => { name: "Listing theme", components: [locked_url] }.to_json,+ )+ listing_url =+ MockGitImporter.register("https://github.com/org/listing-placeholder.git", listing_repo)+ theme.update!(remote_theme: RemoteTheme.create!(remote_url: listing_url))++ put "/admin/themes/#{theme.id}.json", params: { theme: { remote_update: true } }++ expect(response.status).to eq(403)+ expect(theme.reload.child_theme_ids).to be_empty+ expect(theme.remote_theme).to be_placeholder+ ensure+ FileUtils.rm_rf(listing_repo) if listing_repo+ end++ it "only drops components from the imported theme when syncing" do+ other_theme = Fabricate(:theme)+ theme.add_relative_theme!(:child, other_component)+ other_theme.add_relative_theme!(:child, other_component)++ post "/admin/themes/import.json",+ params: {+ bundle: archive([]),+ theme_id: theme.id,+ components: "sync",+ }++ expect(response.status).to eq(201)+ expect(theme.reload.child_theme_ids).to be_empty+ expect(other_theme.reload.child_theme_ids).to eq([other_component.id])+ end+ end++ it "blocks type changes removing restricted children when changing source" do+ theme.update!(remote_theme: RemoteTheme.create!(remote_url: repo_url, local_version: "abc"))+ theme.add_relative_theme!(:child, locked_component)+ replacement_repo =+ setup_git_repo("about.json" => { name: "Component", component: true }.to_json)+ replacement_url =+ MockGitImporter.register("https://github.com/org/replacement.git", replacement_repo)++ put "/admin/themes/#{theme.id}/source.json", params: { remote_url: replacement_url }++ expect(response.status).to eq(403)+ expect(theme.reload).not_to be_component+ expect(theme.child_theme_ids).to eq([locked_component.id])+ expect(theme.remote_theme.remote_url).to eq(repo_url)+ ensure+ FileUtils.rm_rf(replacement_repo) if replacement_repo+ end++ it "blocks type changes removing restricted parents when changing source" do+ component =+ Fabricate(+ :theme,+ component: true,+ remote_theme: RemoteTheme.create!(remote_url: repo_url, local_version: "abc"),+ )+ locked_theme.add_relative_theme!(:child, component)+ replacement_repo = setup_git_repo("about.json" => { name: "Theme" }.to_json)+ replacement_url =+ MockGitImporter.register("https://github.com/org/replacement.git", replacement_repo)++ put "/admin/themes/#{component.id}/source.json", params: { remote_url: replacement_url }++ expect(response.status).to eq(403)+ expect(component.reload).to be_component+ expect(locked_theme.reload.child_theme_ids).to eq([component.id])+ expect(component.remote_theme.remote_url).to eq(repo_url)+ ensure+ FileUtils.rm_rf(replacement_repo) if replacement_repo+ end++ it "blocks dropping a restricted theme's relations by switching or deleting the other side" do+ component = Fabricate(:theme, component: true)+ locked_theme.add_relative_theme!(:child, component)++ put "/admin/themes/#{component.id}.json", params: { theme: { component: false } }+ expect(response.status).to eq(403)++ delete "/admin/themes/#{component.id}.json"+ expect(response.status).to eq(403)++ delete "/admin/themes/bulk_destroy.json", params: { theme_ids: [component.id] }+ expect(response.status).to eq(403)++ theme.add_relative_theme!(:child, locked_component)+ put "/admin/themes/#{theme.id}.json", params: { theme: { component: true } }+ expect(response.status).to eq(403)++ expect(component.reload).to be_component+ expect(locked_theme.reload.child_theme_ids).to eq([component.id])+ expect(theme.reload.child_theme_ids).to eq([locked_component.id])+ end+ endenddiff --git a/spec/services/design_wizard/apply_spec.rb b/spec/services/design_wizard/apply_spec.rbindex ad7893cddba..eec422232df 100644--- a/spec/services/design_wizard/apply_spec.rb+++ b/spec/services/design_wizard/apply_spec.rb@@ -244,6 +244,77 @@ RSpec.describe DesignWizard::Apply doit { is_expected.to fail_to_find_a_model(:theme) }end+ context "when a plugin restricts editing the theme" do+ let(:params) { { theme_id:, light_palette_id: ColorScheme::NAMES_TO_ID_MAP["WCAG"] } }+ let(:plugin) { Plugin::Instance.new }+ let(:modifier) { proc { false } }++ before { plugin.register_modifier(:user_guardian_can_edit_theme, &modifier) }++ after do+ DiscoursePluginRegistry.unregister_modifier(+ plugin,+ :user_guardian_can_edit_theme,+ &modifier+ )+ end++ it { is_expected.to fail_a_policy(:can_edit_theme) }++ it "changes nothing" do+ expect { result }.not_to change {+ [foundation_theme.reload.color_scheme_id, ColorScheme.count]+ }+ end+ end++ context "when a plugin restricts palette creation" do+ let(:plugin) { Plugin::Instance.new }+ let(:modifier) { proc { false } }++ before { plugin.register_modifier(:user_guardian_can_create_color_scheme, &modifier) }++ after do+ DiscoursePluginRegistry.unregister_modifier(+ plugin,+ :user_guardian_can_create_color_scheme,+ &modifier+ )+ end++ context "when a built-in palette has to be saved first" do+ let(:params) { { theme_id:, light_palette_id: ColorScheme::NAMES_TO_ID_MAP["WCAG"] } }++ # new sites start with the built-in palettes saved, but they can be deleted+ before do+ ColorScheme.where(+ base_scheme_id: ColorScheme::NAMES_TO_ID_MAP["WCAG"],+ via_wizard: true,+ ).destroy_all+ end++ it { is_expected.to fail_a_policy(:can_create_needed_palettes) }+ end++ context "when offering the built-in palettes would save them" do+ let(:params) { { theme_id:, palettes_user_selectable: true } }++ it { is_expected.to fail_a_policy(:can_create_needed_palettes) }+ end++ context "when the built-in palette was saved before" do+ let(:params) { { theme_id:, light_palette_id: ColorScheme::NAMES_TO_ID_MAP["WCAG"] } }++ before do+ DesignWizard::Action::ResolvePalette.call(+ palette_id: ColorScheme::NAMES_TO_ID_MAP["WCAG"],+ )+ end++ it { is_expected.to run_successfully }+ end+ end+context "when a provided palette belongs to another theme" dofab!(:horizon_palette) { Fabricate(:color_scheme, theme_id: Theme::CORE_THEMES["horizon"]) }diff --git a/spec/services/themes/bulk_destroy_spec.rb b/spec/services/themes/bulk_destroy_spec.rbindex 35d4027eae3..dbd19047d8a 100644--- a/spec/services/themes/bulk_destroy_spec.rb+++ b/spec/services/themes/bulk_destroy_spec.rb@@ -38,6 +38,22 @@ RSpec.describe Themes::BulkDestroy doit { is_expected.to fail_to_find_a_model(:themes) }end+ context "when one of the themes can't be edited" do+ let(:guardian) { admin.guardian }+ let(:dependencies) { { guardian: } }++ before do+ allow(guardian).to receive(:can_edit_theme?).and_call_original+ allow(guardian).to receive(:can_edit_theme?).with(theme_2).and_return(false)+ end++ it { is_expected.to fail_a_policy(:can_edit_themes) }++ it "destroys nothing" do+ expect { result }.not_to change { Theme.count }+ end+ end+context "when everything is ok" doit { is_expected.to run_successfully }diff --git a/spec/services/themes/destroy_spec.rb b/spec/services/themes/destroy_spec.rbindex 6e03cc91cd0..d67c83076f9 100644--- a/spec/services/themes/destroy_spec.rb+++ b/spec/services/themes/destroy_spec.rb@@ -28,6 +28,15 @@ RSpec.describe Themes::Destroy doit { is_expected.to fail_to_find_a_model(:theme) }end+ context "when the theme can't be edited" do+ let(:guardian) { admin.guardian }+ let(:dependencies) { { guardian: } }++ before { allow(guardian).to receive(:can_edit_theme?).with(theme).and_return(false) }++ it { is_expected.to fail_a_policy(:can_edit_theme) }+ end+context "for a default theme" dobefore { theme.set_default! }diff --git a/spec/services/themes/theme_site_setting_manager_spec.rb b/spec/services/themes/theme_site_setting_manager_spec.rbindex f2ab21da9fd..09fd2d91018 100644--- a/spec/services/themes/theme_site_setting_manager_spec.rb+++ b/spec/services/themes/theme_site_setting_manager_spec.rb@@ -43,6 +43,12 @@ RSpec.describe Themes::ThemeSiteSettingManager doendend+ context "when the theme can't be edited" do+ before { allow(guardian).to receive(:can_edit_theme?).with(theme).and_return(false) }++ it { is_expected.to fail_a_policy(:can_edit_theme) }+ end+context "when creating a new theme site setting" doit { is_expected.to run_successfully }