A platform for community discussion. Free, open, simple.
FEATURE: Render topic Open Graph cards with libvips (#43455)
Alan Guo Xiang Tan5b59681a8c85
diff --git a/lib/discourse_vips.rb b/lib/discourse_vips.rbindex 79ac675a9b3..9c5e9651cae 100644--- a/lib/discourse_vips.rb+++ b/lib/discourse_vips.rb@@ -6,6 +6,9 @@ module DiscourseVipsSVG_DIMENSIONS_TIMEOUT_SECONDS = 3private_constant :SVG_DIMENSIONS_TIMEOUT_SECONDS+ SVG_TO_PNG_TIMEOUT_SECONDS = 3+ private_constant :SVG_TO_PNG_TIMEOUT_SECONDS+def self.versionClient.call(["version"], operation: :vips_version, read: [], write: [])end@@ -83,6 +86,26 @@ module DiscourseVips)end+ def self.svg_to_png(+ input_path:,+ output_path:,+ read:,+ write:,+ timeout: SVG_TO_PNG_TIMEOUT_SECONDS,+ operation: :svg_to_png,+ nice: nil+ )+ timeout = [timeout, SVG_TO_PNG_TIMEOUT_SECONDS].min+ Client.call(+ ["svg-to-png", input_path, output_path],+ operation:,+ read: ["/etc/fonts", "/var/cache/fontconfig", *read],+ write:,+ timeout:,+ nice:,+ )+ end+def self.before_forkClient.before_forkenddiff --git a/lib/topic_og_image_generator.rb b/lib/topic_og_image_generator.rbindex e446b8391b2..1aa0565a9f4 100644--- a/lib/topic_og_image_generator.rb+++ b/lib/topic_og_image_generator.rb@@ -324,14 +324,24 @@ class TopicOgImageGeneratorsvg_path = File.join(directory, "#{basename}.svg")png_path = File.join(directory, "#{basename}.png")File.binwrite(svg_path, bytes)- ImageMagick.magick(- "MSVG:#{svg_path}",- png_path,- operation: :topic_og_asset_render,- read: [svg_path],- write: [directory],- timeout: 10,- )+ if GlobalSetting.enable_vips_image_processing+ DiscourseVips.svg_to_png(+ input_path: svg_path,+ output_path: png_path,+ read: [svg_path],+ write: [directory],+ operation: :topic_og_asset_render,+ )+ else+ ImageMagick.magick(+ "MSVG:#{svg_path}",+ png_path,+ operation: :topic_og_asset_render,+ read: [svg_path],+ write: [directory],+ timeout: 10,+ )+ endreturn png_path if File.exist?(png_path)return nil@@ -346,7 +356,7 @@ class TopicOgImageGeneratorpath = File.join(directory, "#{basename}.#{extension}")File.binwrite(path, bytes)path- rescue ArgumentError, Discourse::Utils::CommandError => error+ rescue ArgumentError, Discourse::Utils::CommandError, DiscourseVips::Error => errorDiscourse.warn("Failed to materialize topic OG image asset",topic_id: @topic.id,@@ -373,29 +383,40 @@ class TopicOgImageGeneratorFile.write(svg_path, build_svg(asset_directory: dir))- ImageMagick.magick(- "-background",- "none",- "-size",- "#{OG_WIDTH}x#{OG_HEIGHT}",- "MSVG:#{svg_path}",- "-depth",- "8",- "-define",- "png:compression-level=9",- png_path,- operation: :topic_og_render,- read: [dir],- write: [dir],- nice: 10,- timeout: 20,- )+ if GlobalSetting.enable_vips_image_processing+ DiscourseVips.svg_to_png(+ input_path: svg_path,+ output_path: png_path,+ read: [dir],+ write: [dir],+ operation: :topic_og_render,+ nice: 10,+ )+ else+ ImageMagick.magick(+ "-background",+ "none",+ "-size",+ "#{OG_WIDTH}x#{OG_HEIGHT}",+ "MSVG:#{svg_path}",+ "-depth",+ "8",+ "-define",+ "png:compression-level=9",+ png_path,+ operation: :topic_og_render,+ read: [dir],+ write: [dir],+ nice: 10,+ timeout: 20,+ )+ endreturn nil unless File.exist?(png_path)FileHelper.optimize_image!(png_path)File.binread(png_path)end- rescue Discourse::Utils::CommandError => e+ rescue Discourse::Utils::CommandError, DiscourseVips::Error => eDiscourse.warn("Failed to render topic OG image", topic_id: @topic.id, error: e.message)nilenddiff --git a/script/discourse_vips_worker b/script/discourse_vips_workerindex 13800f62dae..933a4aeb7e7 100644--- a/script/discourse_vips_worker+++ b/script/discourse_vips_worker@@ -9,7 +9,7 @@ require "tempfile"require "tmpdir"require "vips"-raise LoadError, "libvips 8.13 or newer is required" if !Vips.at_least_libvips?(8, 13)+raise LoadError, "libvips 8.18 or newer is required" if !Vips.at_least_libvips?(8, 18)class DiscourseVipsWorkerclass InvalidImage < StandardError@@ -32,6 +32,16 @@ class DiscourseVipsWorkerSVG_DIMENSIONS_RLIMITS = { cpu_seconds: 1, memory_bytes: 1024 * 1024 * 1024 }.freezeprivate_constant :SVG_DIMENSIONS_RLIMITS+ SVG_TO_PNG_MAX_INPUT_BYTES = 3 * 1024 * 1024+ private_constant :SVG_TO_PNG_MAX_INPUT_BYTES++ SVG_TO_PNG_RLIMITS = {+ cpu_seconds: 1,+ memory_bytes: 1024 * 1024 * 1024,+ file_size_bytes: 1024 * 1024,+ }.freeze+ private_constant :SVG_TO_PNG_RLIMITS+def self.warmWARM_OPERATIONS.each do |name|operation = Vips.vips_operation_new(name)@@ -61,6 +71,8 @@ class DiscourseVipsWorkerpng_to_jpeg(input_path: arguments[0], output_path: arguments[1], quality: arguments[2])when "reencode-jpeg"reencode_jpeg(input_path: arguments[0], output_path: arguments[1], quality: arguments[2])+ when "svg-to-png"+ svg_to_png(input_path: arguments[0], output_path: arguments[1])elseraise ArgumentError, "unsupported libvips operation"end@@ -248,6 +260,25 @@ class DiscourseVipsWorkerendprivate_class_method :svg_dimensions+ def self.svg_to_png(input_path:, output_path:)+ new(rlimits: SVG_TO_PNG_RLIMITS) do+ if File.expand_path(input_path) == File.expand_path(output_path) ||+ (File.exist?(output_path) && File.identical?(input_path, output_path))+ raise ArgumentError, "SVG input and PNG output must be different files"+ end+ if File.size(input_path) > SVG_TO_PNG_MAX_INPUT_BYTES+ raise ArgumentError, "SVG exceeds #{SVG_TO_PNG_MAX_INPUT_BYTES} bytes"+ end++ block_loaders(allowed: %w[VipsForeignLoadSvg])+ Vips.concurrency_set(1)+ image = Vips::Image.svgload(input_path, dpi: 96, scale: 0.75)+ image.flatten(background: [255, 255, 255]).pngsave(output_path)+ nil+ end+ end+ private_class_method :svg_to_png+def self.normalize_color(image)image = image.colourspace(:srgb)image = (image * 255).round(:rint) if %i[float double].include?(image.format)diff --git a/spec/lib/discourse_vips_spec.rb b/spec/lib/discourse_vips_spec.rbindex 644f884857a..3f3d51784c1 100644--- a/spec/lib/discourse_vips_spec.rb+++ b/spec/lib/discourse_vips_spec.rb@@ -576,4 +576,211 @@ RSpec.describe DiscourseVips dosuccess: true,)end++ describe ".svg_to_png" do+ it "renders referenced assets from a caller-permitted directory" do+ Dir.mktmpdir do |directory|+ allowed_path = File.join(directory, "allowed.png")+ ChunkyPNG::Image.new(4, 4, ChunkyPNG::Color.rgb(255, 0, 0)).save(allowed_path)+ input_path = File.join(directory, "input.svg")+ output_directory = File.join(directory, "output")+ Dir.mkdir(output_directory)+ output_path = File.join(output_directory, "output.png")+ File.write(input_path, <<~SVG)+ <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40">+ <image href="allowed.png" width="40" height="40"/>+ </svg>+ SVG++ described_class.svg_to_png(+ input_path:,+ output_path:,+ read: [directory],+ write: [output_directory],+ )++ png = ChunkyPNG::Image.from_file(output_path)+ expect(png[20, 20]).to eq(ChunkyPNG::Color.rgb(255, 0, 0))+ end+ end++ it "renders permitted file assets without including unpermitted file assets" do+ skip "Landlock is not supported" if !Discourse::SafeExec.landlock_supported?++ Dir.mktmpdir do |directory|+ input_path = File.join(directory, "input.svg")+ allowed_path = File.join(directory, "allowed.png")+ private_path = File.join(directory, "private.png")+ output_path = File.join(directory, "output.png")+ ChunkyPNG::Image.new(4, 4, ChunkyPNG::Color.rgb(255, 0, 0)).save(allowed_path)+ ChunkyPNG::Image.new(4, 4, ChunkyPNG::Color.rgb(0, 255, 0)).save(private_path)+ File.write(output_path, "")+ File.write(input_path, <<~SVG)+ <svg xmlns="http://www.w3.org/2000/svg" width="80" height="40">+ <image href="allowed.png" width="40" height="40"/>+ <image href="private.png" x="40" width="40" height="40"/>+ </svg>+ SVG++ described_class.svg_to_png(+ input_path:,+ output_path:,+ read: [input_path, allowed_path],+ write: [output_path],+ )++ png = ChunkyPNG::Image.from_file(output_path)+ expect([png[20, 20], png[60, 20]]).to eq(+ [ChunkyPNG::Color.rgb(255, 0, 0), ChunkyPNG::Color.rgb(255, 255, 255)],+ )+ end+ end++ it "raises an error when reading the input is not permitted" do+ skip "Landlock is not supported" if !Discourse::SafeExec.landlock_supported?++ file = file_from_fixtures("tiny.svg")++ Dir.mktmpdir do |directory|+ output_path = File.join(directory, "output.png")++ expect {+ described_class.svg_to_png(+ input_path: file.path,+ output_path:,+ read: [],+ write: [directory],+ )+ }.to raise_error(DiscourseVips::Error)+ end+ end++ it "renders transparent areas against a white background" do+ svg = <<~SVG+ <svg xmlns="http://www.w3.org/2000/svg" width="12" height="4">+ <rect width="4" height="4" fill="#ff0000"/>+ </svg>+ SVG+ file = file_from_contents(svg, "transparency.svg")++ Dir.mktmpdir do |directory|+ output_path = File.join(directory, "output.png")++ described_class.svg_to_png(+ input_path: file.path,+ output_path:,+ read: [file.path],+ write: [directory],+ )++ png = ChunkyPNG::Image.from_file(output_path)+ expect([png[2, 2], png[10, 2]]).to eq(+ [ChunkyPNG::Color.rgb(255, 0, 0), ChunkyPNG::Color.rgb(255, 255, 255)],+ )+ end+ end++ it "raises an error for malformed SVG input" do+ file = file_from_contents('<svg width="100" height="50">', "invalid.svg")++ Dir.mktmpdir do |directory|+ output_path = File.join(directory, "output.png")++ expect {+ described_class.svg_to_png(+ input_path: file.path,+ output_path:,+ read: [file.path],+ write: [directory],+ )+ }.to raise_error(DiscourseVips::Error)+ end+ end++ it "raises an error when input and output refer to the same file" do+ svg = '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>'++ Dir.mktmpdir do |directory|+ input_path = File.join(directory, "input.svg")+ output_path = File.join(directory, "output.png")+ File.write(input_path, svg)+ File.link(input_path, output_path)++ expect {+ described_class.svg_to_png(+ input_path:,+ output_path:,+ read: [input_path],+ write: [directory],+ )+ }.to raise_error(DiscourseVips::Error, "SVG input and PNG output must be different files")+ end+ end++ it "raises an error when SVG input exceeds the size limit" do+ svg = <<~SVG+ <svg xmlns="http://www.w3.org/2000/svg" width="300" height="100">+ #{" " * 3.megabytes}+ </svg>+ SVG+ file = file_from_contents(svg, "oversized.svg")++ Dir.mktmpdir do |directory|+ output_path = File.join(directory, "output.png")++ expect {+ described_class.svg_to_png(+ input_path: file.path,+ output_path:,+ read: [file.path],+ write: [directory],+ )+ }.to raise_error(DiscourseVips::Error, /SVG exceeds/)+ end+ end++ it "writes a PNG at the original SVG dimensions" do+ file =+ file_from_contents(+ '<svg xmlns="http://www.w3.org/2000/svg" width="600" height="200"><rect width="600" height="200" fill="#ff0000"/></svg>',+ "large.svg",+ )++ Dir.mktmpdir do |directory|+ output_path = File.join(directory, "output.png")++ described_class.svg_to_png(+ input_path: file.path,+ output_path:,+ read: [file.path],+ write: [directory],+ )++ png = ChunkyPNG::Image.from_file(output_path)+ expect([png.width, png.height]).to eq([600, 200])+ expect(png[png.width / 2, png.height / 2]).to eq(ChunkyPNG::Color.rgb(255, 0, 0))+ end+ end++ it "raises an error when writing the output is not permitted" do+ skip "Landlock is not supported" if !Discourse::SafeExec.landlock_supported?++ file =+ file_from_contents(+ '<svg xmlns="http://www.w3.org/2000/svg" width="60" height="20"/>',+ "input.svg",+ )++ Dir.mktmpdir do |directory|+ expect {+ described_class.svg_to_png(+ input_path: file.path,+ output_path: File.join(directory, "output.png"),+ read: [file.path],+ write: [],+ )+ }.to raise_error(DiscourseVips::Error)+ end+ end+ endenddiff --git a/spec/lib/topic_og_image_generator_spec.rb b/spec/lib/topic_og_image_generator_spec.rbindex 47feb0330bd..ea9cabd2822 100644--- a/spec/lib/topic_og_image_generator_spec.rb+++ b/spec/lib/topic_og_image_generator_spec.rb@@ -39,74 +39,101 @@ RSpec.describe TopicOgImageGenerator doenddescribe "#generate_bytes" do- it "renders the topic OG image as a 1200x630 PNG" do- png_bytes = described_class.new(topic).generate_bytes+ shared_examples "topic Open Graph rendering" do+ it "renders the topic OG image as a 1200x630 PNG" do+ png_bytes = described_class.new(topic).generate_bytes++ expect(png_bytes).to be_present+ Tempfile.create(%w[topic-og .png], binmode: true) do |file|+ file.write(png_bytes)+ file.flush++ expect(FastImage.type(file.path)).to eq(:png)+ expect(FastImage.size(file.path)).to eq([1200, 630])+ end+ end- expect(png_bytes).to be_present- Tempfile.create(%w[topic-og .png], binmode: true) do |file|- file.write(png_bytes)- file.flush+ it "renders raster and SVG assets in their expected regions" do+ logo_upload = Struct.new(:url, :width, :height).new("/marked-logo.svg", 200, 100)+ logo_svg = <<~SVG+ <svg xmlns="http://www.w3.org/2000/svg" width="200" height="100">+ <rect width="200" height="100" fill="#00ff00"/>+ </svg>+ SVG+ avatar_png = ChunkyPNG::Image.new(16, 16, ChunkyPNG::Color.rgb(255, 0, 0)).to_blob+ logo_data_uri = "data:image/svg+xml;base64,#{Base64.strict_encode64(logo_svg)}"+ avatar_data_uri = "data:image/png;base64,#{Base64.strict_encode64(avatar_png)}"+ avatar_url = topic.user.avatar_template_url.gsub("{size}", "120")+ SiteSetting.stubs(:logo).returns(logo_upload)+ described_class+ .any_instance+ .stubs(:fetch_as_data_uri)+ .with("/marked-logo.svg")+ .returns(logo_data_uri)+ described_class+ .any_instance+ .stubs(:fetch_as_data_uri)+ .with(avatar_url)+ .returns(avatar_data_uri)++ png = ChunkyPNG::Image.from_blob(described_class.new(topic).generate_bytes)++ avatar_pixel = png[116, 339]+ logo_pixel = png[180, 520]+ expect(+ [+ [ChunkyPNG::Color.r(avatar_pixel), ChunkyPNG::Color.g(avatar_pixel)],+ [ChunkyPNG::Color.g(logo_pixel), ChunkyPNG::Color.r(logo_pixel)],+ ],+ ).to eq([[255, 0], [255, 0]])+ end- expect(FastImage.type(file.path)).to eq(:png)- expect(FastImage.size(file.path)).to eq([1200, 630])+ it "omits an unrenderable SVG asset and still renders the canvas" do+ logo_upload = Struct.new(:url, :width, :height).new("/invalid-logo.svg", 200, 100)+ invalid_svg_data_uri =+ "data:image/svg+xml;base64,#{Base64.strict_encode64("<svg><invalid")}"+ avatar_url = topic.user.avatar_template_url.gsub("{size}", "120")+ SiteSetting.stubs(:logo).returns(logo_upload)+ described_class+ .any_instance+ .stubs(:fetch_as_data_uri)+ .with("/invalid-logo.svg")+ .returns(invalid_svg_data_uri)+ described_class.any_instance.stubs(:fetch_as_data_uri).with(avatar_url).returns(nil)+ Discourse.expects(:warn).with(+ "Failed to materialize topic OG image asset",+ has_entries(topic_id: topic.id, asset: "logo"),+ )++ png = ChunkyPNG::Image.from_blob(described_class.new(topic).generate_bytes)++ expect([png.width, png.height]).to eq([1200, 630])+ expect(png[180, 520]).to eq(png[500, 520])endend- it "renders raster and SVG assets in their expected regions" do- logo_upload = Struct.new(:url, :width, :height).new("/marked-logo.svg", 200, 100)- logo_svg = <<~SVG- <svg xmlns="http://www.w3.org/2000/svg" width="200" height="100">- <rect width="200" height="100" fill="#00ff00"/>- </svg>- SVG- avatar_png = ChunkyPNG::Image.new(16, 16, ChunkyPNG::Color.rgb(255, 0, 0)).to_blob- logo_data_uri = "data:image/svg+xml;base64,#{Base64.strict_encode64(logo_svg)}"- avatar_data_uri = "data:image/png;base64,#{Base64.strict_encode64(avatar_png)}"- avatar_url = topic.user.avatar_template_url.gsub("{size}", "120")- SiteSetting.stubs(:logo).returns(logo_upload)- described_class- .any_instance- .stubs(:fetch_as_data_uri)- .with("/marked-logo.svg")- .returns(logo_data_uri)- described_class- .any_instance- .stubs(:fetch_as_data_uri)- .with(avatar_url)- .returns(avatar_data_uri)-- png = ChunkyPNG::Image.from_blob(described_class.new(topic).generate_bytes)-- avatar_pixel = png[116, 339]- logo_pixel = png[180, 520]- expect(- [- [ChunkyPNG::Color.r(avatar_pixel), ChunkyPNG::Color.g(avatar_pixel)],- [ChunkyPNG::Color.g(logo_pixel), ChunkyPNG::Color.r(logo_pixel)],- ],- ).to eq([[255, 0], [255, 0]])- end-- it "omits an unrenderable SVG asset and still renders the canvas" do- logo_upload = Struct.new(:url, :width, :height).new("/invalid-logo.svg", 200, 100)- invalid_svg_data_uri = "data:image/svg+xml;base64,#{Base64.strict_encode64("<svg><invalid")}"- avatar_url = topic.user.avatar_template_url.gsub("{size}", "120")- SiteSetting.stubs(:logo).returns(logo_upload)- described_class- .any_instance- .stubs(:fetch_as_data_uri)- .with("/invalid-logo.svg")- .returns(invalid_svg_data_uri)- described_class.any_instance.stubs(:fetch_as_data_uri).with(avatar_url).returns(nil)- Discourse.expects(:warn).with(- "Failed to materialize topic OG image asset",- has_entries(topic_id: topic.id, asset: "logo"),- )-- png = ChunkyPNG::Image.from_blob(described_class.new(topic).generate_bytes)-- expect([png.width, png.height]).to eq([1200, 630])- expect(png[180, 520]).to eq(png[500, 520])+ context "with libvips disabled" do+ before { global_setting :enable_vips_image_processing, false }++ include_examples "topic Open Graph rendering"+ end++ context "with libvips enabled" do+ before { global_setting :enable_vips_image_processing, true }++ include_examples "topic Open Graph rendering"++ it "returns nil when card conversion raises an error" do+ DiscourseVips.stubs(:svg_to_png).raises(DiscourseVips::Error)++ expect(described_class.new(topic).generate_bytes).to eq(nil)+ end++ it "returns nil when card conversion times out" do+ DiscourseVips.stubs(:svg_to_png).raises(DiscourseVips::OperationTimeout)++ expect(described_class.new(topic).generate_bytes).to eq(nil)+ endendend