A platform for community discussion. Free, open, simple.
FIX: Enforce per-section sidebar link cap on partial sidebar section updates (#42277)
Isaac Janzend041a4538ce0
diff --git a/app/models/sidebar_section.rb b/app/models/sidebar_section.rbindex 3132597df72..23f5f1704c2 100644--- a/app/models/sidebar_section.rb+++ b/app/models/sidebar_section.rb@@ -32,6 +32,7 @@ class SidebarSection < ActiveRecord::Base}validates :locale, presence: true, length: { maximum: 20 }+ validate :sidebar_urls_count_within_limitscope :public_sections, -> { where("public") }scope :custom_sections, -> { where(section_type: nil) }@@ -74,6 +75,14 @@ class SidebarSection < ActiveRecord::Baseprivate+ def sidebar_urls_count_within_limit+ count = sidebar_urls.reject(&:marked_for_destruction?).size+ limit = SiteSetting.max_sidebar_section_links+ return if count <= limit++ errors.add(:base, "Maximum #{limit} records are allowed. Got #{count} records instead.")+ end+def set_system_user_for_public_sectionself.user_id = Discourse.system_user.id if publicenddiff --git a/app/services/sidebar_section_updater.rb b/app/services/sidebar_section_updater.rbindex 4c55341a463..75b374c3b07 100644--- a/app/services/sidebar_section_updater.rb+++ b/app/services/sidebar_section_updater.rb@@ -13,7 +13,7 @@ class SidebarSectionUpdaterenddef update!- ActiveRecord::Base.transaction do+ @sidebar_section.with_lock do@sidebar_section.update!(@section_params.merge(sidebar_urls_attributes: @links_params))@sidebar_section.sidebar_section_links.update_all(user_id: @sidebar_section.user_id)update_link_orderdiff --git a/spec/requests/sidebar_sections_controller_spec.rb b/spec/requests/sidebar_sections_controller_spec.rbindex ef5dd44c751..45c5996f3cc 100644--- a/spec/requests/sidebar_sections_controller_spec.rb+++ b/spec/requests/sidebar_sections_controller_spec.rb@@ -629,6 +629,28 @@ RSpec.describe SidebarSectionsController doexpect(SidebarUrlLocalization.exists?(url_localization.id)).to eq(false)end+ it "enforces the total link limit when adding links" do+ SiteSetting.max_sidebar_section_links = 5+ sign_in(user)++ put "/sidebar_sections/#{sidebar_section.id}.json",+ params: {+ title: "custom section",+ links: [+ { icon: "link", name: "latest", value: "/latest" },+ { icon: "link", name: "new", value: "/new" },+ { icon: "link", name: "top", value: "/top" },+ { icon: "link", name: "hot", value: "/hot" },+ ],+ }++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to eq(+ ["Maximum 5 records are allowed. Got 6 records instead."],+ )+ expect(sidebar_section.reload.sidebar_urls.count).to eq(2)+ end+it "validates limit of links" doSiteSetting.max_sidebar_section_links = 5