Skip to content

A platform for community discussion. Free, open, simple.

DEV: clean up splash SVG on upload, not when rendering (#37681)

Kris72a51e8943c0
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 08e3dac9ea9..e4c65c1fdc4 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -503,8 +503,8 @@ module ApplicationHelper
end
def splash_screen_image_animated?
- build_splash_screen_image unless defined?(@splash_screen_image_animated)
- @splash_screen_image_animated
+ build_splash_screen_image unless defined?(@splash_screen_image_svg)
+ @splash_screen_image_svg.present? && @splash_screen_image_svg.match?(/@keyframes\s/)
end
def splash_screen_inline_svg
@@ -536,41 +536,21 @@ module ApplicationHelper
def build_splash_screen_image
@splash_screen_image_svg = nil
- @splash_screen_image_animated = false
upload = SiteSetting.splash_screen_image
return unless upload.is_a?(Upload)
- content =
+ @splash_screen_image_svg =
Discourse
.cache
- .fetch("splash_screen_image_svg_#{upload.id}_#{upload.sha1}", expires_in: 1.day) do
- upload.content
- rescue StandardError => e
- Discourse.warn_exception(e, message: "Failed to fetch splash screen logo SVG")
- nil
+ .fetch("splash_screen_svg_#{upload.id}_#{upload.sha1}", expires_in: 1.day) do
+ begin
+ upload.content.presence
+ rescue StandardError => e
+ Discourse.warn_exception(e, message: "Failed to fetch splash screen logo SVG")
+ nil
+ end
end
-
- return if content.blank?
-
- doc = Nokogiri.XML(content)
- svg = doc.at_css("svg")
- return unless svg
-
- @splash_screen_image_animated = svg.at_css("style")&.text&.include?("@keyframes")
-
- # Strip SMIL animation elements, these run on the main thread and stutter.
- # Only CSS transform/opacity animations are recommended.
- svg.xpath(
- ".//*[local-name()='animate' or local-name()='animateTransform' or local-name()='animateMotion' or local-name()='set']",
- ).each(&:remove)
-
- has_scripts = svg.xpath("//script").present?
- has_event_handlers = svg.xpath("//@*[starts-with(name(), 'on')]").present?
-
- return if has_scripts || has_event_handlers
-
- @splash_screen_image_svg = svg.to_xml
end
public
diff --git a/app/services/site_setting/splash_screen_image_changed.rb b/app/services/site_setting/splash_screen_image_changed.rb
new file mode 100644
index 00000000000..19e2f5609c2
--- /dev/null
+++ b/app/services/site_setting/splash_screen_image_changed.rb
@@ -0,0 +1,79 @@
+# frozen_string_literal: true
+
+class SiteSetting::SplashScreenImageChanged
+ include Service::Base
+
+ params { attribute :upload_id, :integer }
+
+ model :upload
+ model :svg
+ model :cleaned_svg
+ step :save_cleaned_svg_upload
+ step :clear_cache
+
+ private
+
+ def fetch_upload(params:)
+ Upload.find_by(id: params.upload_id)
+ end
+
+ def fetch_svg(upload:)
+ content =
+ begin
+ upload.content
+ rescue StandardError
+ nil
+ end
+
+ return nil if content.blank?
+
+ Nokogiri.XML(content).at_css("svg")
+ end
+
+ def fetch_cleaned_svg(svg:)
+ # Disables SMIL animations which can cause performance issues,
+ # CSS animations are preferred.
+ svg.xpath(
+ ".//*[local-name()='animate' or local-name()='animateTransform' or local-name()='animateMotion' or local-name()='set']",
+ ).each(&:remove)
+
+ # Remove explicit dimensions so the SVG scales via viewBox
+ if svg["viewBox"].present?
+ svg.remove_attribute("width")
+ svg.remove_attribute("height")
+ end
+
+ svg.to_xml
+ end
+
+ def save_cleaned_svg_upload(cleaned_svg:, upload:)
+ return if cleaned_svg == upload.content
+
+ Tempfile.open(%w[splash_screen .svg]) do |tmp|
+ tmp.write(cleaned_svg)
+ tmp.rewind
+
+ new_sha1 = Upload.generate_digest(tmp.path)
+ existing = Upload.find_by(sha1: new_sha1)
+
+ if existing && existing.id != upload.id
+ SiteSetting.splash_screen_image = existing.id
+ else
+ old_path = Discourse.store.get_path_for_upload(upload)
+ old_url = upload.url
+ upload.tap do |u|
+ u.sha1 = new_sha1
+ u.filesize = tmp.size
+ u.url = Discourse.store.store_upload(tmp, u)
+ u.save!(validate: false)
+ end
+
+ Discourse.store.remove_file(old_url, old_path) if upload.url != old_url
+ end
+ end
+ end
+
+ def clear_cache(upload:)
+ Discourse.cache.delete("splash_screen_svg_#{upload.id}_#{upload.sha1}")
+ end
+end
diff --git a/config/initializers/014-track-setting-changes.rb b/config/initializers/014-track-setting-changes.rb
index a95fe46ee5a..fb80d87f2d6 100644
--- a/config/initializers/014-track-setting-changes.rb
+++ b/config/initializers/014-track-setting-changes.rb
@@ -88,6 +88,20 @@ DiscourseEvent.on(:site_setting_changed) do |name, old_value, new_value|
Theme.expire_site_cache! if name == :default_theme_id
+ if name == :splash_screen_image && new_value.present?
+ SiteSetting::SplashScreenImageChanged.call(
+ upload_id: new_value,
+ guardian: Discourse.system_user.guardian,
+ ) do |result|
+ on_model_not_found(:upload) { Rails.logger.error("Upload not found for #{name} change") }
+ on_model_not_found(:svg) do
+ Rails.logger.error("SVG could not be parsed from upload #{new_value} when updating #{name}")
+ end
+ on_success { Rails.logger.info("Successfully updated #{name} SVG") }
+ on_failure { Rails.logger.error("Failed to update #{name} SVG") }
+ end
+ end
+
if name == :content_localization_enabled && new_value == true
%i[post_menu post_menu_hidden_items].each do |setting_name|
current_items = SiteSetting.get(setting_name).split("|")
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index 49bb69dab72..c385278a9c9 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -2767,6 +2767,8 @@ en:
invalid_username: "There's no user with that username."
valid_username: "There's a user with that username."
invalid_group: "There's no group with that name."
+ invalid_svg: "The SVG image is invalid. It must contain an SVG element and no scripts or event handlers."
+ invalid_upload: "The upload is invalid or does not exist."
invalid_topic: "There's no topic with that ID."
invalid_integer_min_max: "Value must be between %{min} and %{max}."
invalid_integer_min: "Value must be %{min} or greater."
diff --git a/config/site_settings.yml b/config/site_settings.yml
index e7c99055bca..7e898455f05 100644
--- a/config/site_settings.yml
+++ b/config/site_settings.yml
@@ -3778,6 +3778,7 @@ uncategorized:
depends_on:
- "enable_custom_splash_screen"
depends_behavior: "hidden"
+ validator: "UploadSettingValidator"
suggest_weekends_in_date_pickers:
client: true
diff --git a/lib/validators/upload_setting_validator.rb b/lib/validators/upload_setting_validator.rb
new file mode 100644
index 00000000000..7cd1353783b
--- /dev/null
+++ b/lib/validators/upload_setting_validator.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+class UploadSettingValidator
+ def initialize(opts = {})
+ @opts = opts
+ end
+
+ def valid_value?(val)
+ return true if val.blank?
+
+ upload = Upload.find_by(id: val)
+ upload.present? && additional_validation_passed(upload)
+ end
+
+ def error_message
+ return I18n.t("site_settings.errors.invalid_svg") if @opts[:name] == :splash_screen_image
+ I18n.t("site_settings.errors.invalid_upload")
+ end
+
+ def additional_validation_passed(upload)
+ if @opts[:name] == :splash_screen_image
+ validate_svg(upload)
+ else
+ true
+ end
+ end
+
+ # We also clean svgs in UploadCreator#clean_svg!,
+ # but this is a good extra fallback.
+ def validate_svg(upload)
+ content =
+ begin
+ upload.content
+ rescue StandardError
+ nil
+ end
+ return false if content.blank?
+
+ svg = Nokogiri.XML(content).at_css("svg")
+ return false if svg.blank?
+
+ has_scripts = svg.xpath("//*[local-name()='script']").present?
+ has_event_handlers = svg.xpath("//@*[starts-with(local-name(), 'on')]").present?
+
+ !has_scripts && !has_event_handlers
+ end
+end
diff --git a/spec/lib/validators/upload_validator_spec.rb b/spec/lib/validators/upload_validator_spec.rb
index ce1d1e1b893..df787c5a9d9 100644
--- a/spec/lib/validators/upload_validator_spec.rb
+++ b/spec/lib/validators/upload_validator_spec.rb
@@ -1,218 +1,119 @@
# frozen_string_literal: true
-RSpec.describe UploadValidator do
- subject(:validator) { described_class.new }
-
- describe "validate" do
- fab!(:user)
- let(:filename) { "discourse.csv" }
- let(:csv_file) { file_from_fixtures(filename, "csv") }
-
- it "should create an invalid upload when the filename is blank" do
- SiteSetting.authorized_extensions = "*"
- created_upload = UploadCreator.new(csv_file, nil).create_for(user.id)
- validator.validate(created_upload)
- expect(created_upload).to_not be_valid
- expect(created_upload.errors.full_messages.first).to include(
- I18n.t("activerecord.errors.messages.blank"),
- )
- end
-
- it "allows 'gz' as extension when uploading export file" do
- SiteSetting.authorized_extensions = ""
-
- expect(
- UploadCreator.new(csv_file, "#{filename}.zip", for_export: true).create_for(user.id),
- ).to be_valid
- end
+RSpec.describe UploadSettingValidator do
+ subject(:validator) { described_class.new(opts) }
- it "allows uses max_export_file_size_kb when uploading export file" do
- SiteSetting.max_attachment_size_kb = "0"
- SiteSetting.authorized_extensions = "zip"
+ let(:opts) { {} }
- expect(
- UploadCreator.new(csv_file, "#{filename}.zip", for_export: true).create_for(user.id),
- ).to be_valid
- end
+ describe "#valid_value?" do
+ context "when value is blank" do
+ it "accepts nil" do
+ expect(validator.valid_value?(nil)).to eq(true)
+ end
- describe "size validation" do
- it "does not allow images that are too large" do
- SiteSetting.max_image_size_kb = 1536
- upload =
- Fabricate.build(
- :upload,
- user: Fabricate(:admin),
- original_filename: "test.png",
- filesize: 2_097_152,
- )
- validator.validate(upload)
- expect(upload.errors.full_messages.first).to eq(
- "Filesize #{I18n.t("upload.images.too_large_humanized", max_size: "1.5 MB")}",
- )
+ it "accepts empty string" do
+ expect(validator.valid_value?("")).to eq(true)
end
end
- describe "when allow_staff_to_upload_any_file_in_pm is true" do
- it "should allow uploads for pm" do
- upload =
- Fabricate.build(
- :upload,
- user: Fabricate(:admin),
- original_filename: "test.ico",
- for_private_message: true,
- )
+ context "when value is a valid upload id" do
+ fab!(:upload)
- expect(validator.validate(upload)).to eq(true)
+ it "returns true when no additional validation is required" do
+ expect(validator.valid_value?(upload.id)).to eq(true)
end
- describe "for a normal user" do
- it "should not allow uploads for pm" do
- upload =
- Fabricate.build(
- :upload,
- user: Fabricate(:user),
- original_filename: "test.ico",
- for_private_message: true,
- )
-
- expect(validator.validate(upload)).to eq(nil)
+ context "when the upload no longer exists" do
+ before { upload.destroy! }
+
+ it "returns false" do
+ expect(validator.valid_value?(upload.id)).to eq(false)
end
end
end
+ end
- describe "upload for site settings" do
- fab!(:admin)
- fab!(:user)
-
- let(:upload) do
- Fabricate.build(:upload, user: admin, original_filename: "test.png", for_site_setting: true)
- end
-
- it "allows image uploads for staff" do
- expect(validator.validate(upload)).to eq(true)
- end
+ describe "#error_message" do
+ it "returns invalid_upload as a generic message" do
+ expect(validator.error_message).to eq(I18n.t("site_settings.errors.invalid_upload"))
+ end
+ end
- it "rejects non-image uploads when no authorized_extensions specified" do
- upload.original_filename = "test.txt"
- validator.validate(upload)
- expect(upload.errors[:original_filename]).to include(I18n.t("upload.images_only"))
- end
+ describe "svg upload" do
+ subject(:validator) { described_class.new(name: :splash_screen_image) }
- it "rejects uploads from non-staff users" do
- upload.user = user
- validator.validate(upload)
- expect(upload.errors[:base]).to include(I18n.t("upload.unauthorized"))
- end
+ describe "#valid_value?" do
+ fab!(:upload)
- it "validates image file size" do
- SiteSetting.max_image_size_kb = 1
- upload.filesize = 10.kilobytes
- validator.validate(upload)
- expect(upload.errors[:filesize]).to be_present
- end
+ context "when upload content is missing or raises" do
+ before { allow_any_instance_of(Upload).to receive(:content).and_raise(StandardError) }
- context "with authorized_extensions" do
- before do
- upload.site_setting_name = "test_setting"
- SiteSetting
- .type_supervisor
- .stubs(:type_hash)
- .with(:test_setting)
- .returns({ type: "upload", authorized_extensions: "txt|md" })
+ it "returns false" do
+ expect(validator.valid_value?(upload.id)).to eq(false)
end
+ end
- it "allows matching extensions" do
- upload.original_filename = "file.txt"
- expect(validator.validate(upload)).to eq(true)
+ context "when upload content is blank" do
+ before { allow_any_instance_of(Upload).to receive(:content).and_return(nil) }
- upload.original_filename = "file.md"
- expect(validator.validate(upload)).to eq(true)
+ it "returns false" do
+ expect(validator.valid_value?(upload.id)).to eq(false)
end
+ end
- it "rejects non-matching extensions" do
- upload.original_filename = "script.js"
- validator.validate(upload)
- expect(upload.errors[:original_filename]).to include(
- I18n.t("upload.unauthorized", authorized_extensions: "txt|md"),
- )
- end
+ context "when content has no svg element" do
+ before { allow_any_instance_of(Upload).to receive(:content).and_return("<html></html>") }
- it "validates attachment file size for non-images" do
- SiteSetting.max_attachment_size_kb = 1
- upload.original_filename = "file.txt"
- upload.filesize = 10.kilobytes
- validator.validate(upload)
- expect(upload.errors[:filesize]).to be_present
+ it "returns false" do
+ expect(validator.valid_value?(upload.id)).to eq(false)
end
+ end
- it "validates image file size for images" do
- SiteSetting
- .type_supervisor
- .stubs(:type_hash)
- .with(:test_setting)
- .returns({ type: "upload", authorized_extensions: "png" })
- SiteSetting.max_image_size_kb = 1
- upload.original_filename = "image.png"
- upload.filesize = 10.kilobytes
- validator.validate(upload)
- expect(upload.errors[:filesize]).to be_present
+ context "when SVG contains a script" do
+ before { allow_any_instance_of(Upload).to receive(:content).and_return(<<~CONTENT) }
+ <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" width="50" height="50">
+ <circle cx="50" cy="50" r="40" stroke="#3498db" stroke-width="8" fill="none" stroke-linecap="round" stroke-dasharray="60 150">
+ <animateTransform attributeName="transform" type="rotate" from="0 50 50" to="360 50 50" dur="1s" repeatCount="indefinite" />
+ </circle>
+ <script>
+ console.log("Spinner loaded");
+ </script>
+ </svg>
+ CONTENT
+
+ it "returns false" do
+ expect(validator.valid_value?(upload.id)).to eq(false)
end
end
- context "with site_setting_name but no authorized_extensions" do
+ context "when SVG contains an event handler attribute" do
before do
- upload.site_setting_name = "image_only_setting"
- SiteSetting
- .type_supervisor
- .stubs(:type_hash)
- .with(:image_only_setting)
- .returns({ type: "upload" })
+ allow_any_instance_of(Upload).to receive(:content).and_return(
+ '<svg><rect onclick="evil()"/></svg>',
+ )
end
- it "falls back to images only" do
- upload.original_filename = "test.txt"
- validator.validate(upload)
- expect(upload.errors[:original_filename]).to include(I18n.t("upload.images_only"))
+ it "returns false" do
+ expect(validator.valid_value?(upload.id)).to eq(false)
end
end
- context "with max_file_size_kb" do
+ context "when SVG is clean" do
before do
- upload.site_setting_name = "limited_upload"
- upload.original_filename = "file.txt"
- end
-
- it "enforces the setting-specific file size limit" do
- SiteSetting
- .type_supervisor
- .stubs(:type_hash)
- .with(:limited_upload)
- .returns({ type: "upload", authorized_extensions: "txt", max_file_size_kb: 5 })
- upload.filesize = 10.kilobytes
- validator.validate(upload)
- expect(upload.errors[:filesize]).to be_present
+ allow_any_instance_of(Upload).to receive(:content).and_return(
+ '<svg xmlns="http://www.w3.org/2000/svg"><rect width="10" height="10"/></svg>',
+ )
end
- it "allows files within the limit" do
- SiteSetting
- .type_supervisor
- .stubs(:type_hash)
- .with(:limited_upload)
- .returns({ type: "upload", authorized_extensions: "txt", max_file_size_kb: 100 })
- upload.filesize = 50.kilobytes
- expect(validator.validate(upload)).to eq(true)
+ it "returns true" do
+ expect(validator.valid_value?(upload.id)).to eq(true)
end
+ end
+ end
- it "uses setting limit instead of global attachment limit" do
- SiteSetting.max_attachment_size_kb = 1
- SiteSetting
- .type_supervisor
- .stubs(:type_hash)
- .with(:limited_upload)
- .returns({ type: "upload", authorized_extensions: "txt", max_file_size_kb: 100 })
- upload.filesize = 50.kilobytes
- expect(validator.validate(upload)).to eq(true)
- end
+ describe "#error_message" do
+ it "returns invalid_svg" do
+ expect(validator.error_message).to eq(I18n.t("site_settings.errors.invalid_svg"))
end
end
end
diff --git a/spec/services/site_setting/splash_screen_image_changed_spec.rb b/spec/services/site_setting/splash_screen_image_changed_spec.rb
new file mode 100644
index 00000000000..901a5f83023
--- /dev/null
+++ b/spec/services/site_setting/splash_screen_image_changed_spec.rb
@@ -0,0 +1,172 @@
+# frozen_string_literal: true
+
+RSpec.describe SiteSetting::SplashScreenImageChanged do
+ describe ".call" do
+ subject(:result) { described_class.call(params:) }
+
+ fab!(:user)
+
+ def create_svg_upload(svg_content, filename: "splash.svg")
+ file = file_from_contents(svg_content, filename, "images")
+ UploadCreator.new(file, filename).create_for(user.id)
+ end
+
+ def write_upload_file(upload, content)
+ path = Discourse.store.path_for(upload)
+ FileUtils.mkdir_p(File.dirname(path))
+ File.write(path, content)
+ end
+
+ let(:params) { { upload_id: upload.id } }
+ let(:upload) { create_svg_upload(svg_content) }
+
+ context "when upload does not exist" do
+ let(:upload) { Fabricate(:upload, extension: "svg") }
+
+ before { upload.destroy! }
+
+ it { is_expected.to fail_to_find_a_model(:upload) }
+ end
+
+ context "when upload has no valid SVG content" do
+ let(:upload) do
+ u = Fabricate(:upload, extension: "svg", original_filename: "empty.svg")
+ write_upload_file(u, "")
+ u
+ end
+
+ it { is_expected.to fail_to_find_a_model(:svg) }
+ end
+
+ context "when upload content raises when read" do
+ let(:upload) { Fabricate(:upload, extension: "svg") }
+
+ it { is_expected.to fail_to_find_a_model(:svg) }
+ end
+
+ context "when upload has valid SVG content" do
+ let(:svg_with_animate) { <<~SVG }
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
+ <rect x="0" y="0" width="100" height="100" fill="white"/>
+ <animate attributeName="opacity" from="1" to="0" dur="1s"/>
+ </svg>
+ SVG
+
+ context "when cleaned SVG differs from upload content" do
+ let(:upload) do
+ u = Fabricate(:upload, extension: "svg", original_filename: "splash.svg")
+ write_upload_file(u, svg_with_animate)
+ u
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "updates the upload with new sha1 and url" do
+ original_sha1 = upload.sha1
+ original_url = upload.url
+ result
+ upload.reload
+ expect(upload.sha1).not_to eq(original_sha1)
+ expect(upload.url).not_to eq(original_url)
+ end
+
+ it "cleans the SVG (removes animate and width/height when viewBox present)" do
+ result
+ upload.reload
+ doc = Nokogiri.XML(upload.content)
+ svg = doc.at_css("svg")
+ expect(upload.content).not_to include("animate")
+ expect(svg["width"]).to be_nil
+ expect(svg["height"]).to be_nil
+ end
+
+ it "clears the splash screen SVG cache" do
+ Discourse
+ .cache
+ .expects(:delete)
+ .with { |key| key.match?(/\Asplash_screen_svg_#{upload.id}_[a-f0-9]{40}\z/) }
+ result
+ end
+ end
+
+ context "when another upload with the same cleaned sha1 exists" do
+ let(:cleaned_svg_content) do
+ doc = Nokogiri.XML(svg_with_animate)
+ svg = doc.at_css("svg")
+ svg.xpath(
+ ".//*[local-name()='animate' or local-name()='animateTransform' or local-name()='animateMotion' or local-name()='set']",
+ ).each(&:remove)
+ svg.remove_attribute("width") if svg["viewBox"].present?
+ svg.remove_attribute("height") if svg["viewBox"].present?
+ svg.to_xml
+ end
+
+ let!(:existing_upload) do
+ u = Fabricate(:upload, extension: "svg", original_filename: "existing.svg")
+ write_upload_file(u, cleaned_svg_content)
+ path = Discourse.store.path_for(u)
+ u.update!(sha1: Upload.generate_digest(path))
+ u
+ end
+
+ let(:upload) do
+ u = Fabricate(:upload, extension: "svg", original_filename: "splash.svg")
+ write_upload_file(u, svg_with_animate)
+ u
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "sets splash_screen_image to the existing upload" do
+ result
+ expect(SiteSetting.splash_screen_image).to eq(existing_upload)
+ end
+
+ it "does not update the current upload" do
+ original_sha1 = upload.sha1
+ result
+ expect(upload.reload.sha1).to eq(original_sha1)
+ end
+ end
+
+ context "when cleaned SVG equals upload content" do
+ let(:idempotent_svg) do
+ doc = Nokogiri.XML(<<~SVG)
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10">
+ <rect x="0" y="0" width="10" height="10"/>
+ </svg>
+ SVG
+ svg = doc.at_css("svg")
+ svg.remove_attribute("width") if svg["viewBox"].present?
+ svg.remove_attribute("height") if svg["viewBox"].present?
+ svg.to_xml
+ end
+
+ let(:upload) do
+ u = Fabricate(:upload, extension: "svg", original_filename: "minimal.svg")
+ write_upload_file(u, idempotent_svg)
+ u
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "does not change the upload sha1 or url" do
+ original_sha1 = upload.sha1
+ original_url = upload.url
+ result
+ upload.reload
+ expect(upload.sha1).to eq(original_sha1)
+ expect(upload.url).to eq(original_url)
+ end
+
+ it "still clears the cache" do
+ allow(Discourse.cache).to receive(:delete)
+ result
+ expect(Discourse.cache).to have_received(:delete).with(
+ "splash_screen_svg_#{upload.id}_#{upload.sha1}",
+ )
+ end
+ end
+ end
+ end
+end