Skip to content

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

DEV: Replace image_optim with sandboxed optimizer commands (#43938)

Alan Guo Xiang Tan5999b62c5167
diff --git a/Brewfile b/Brewfile
index efda19d0402..ffb7e2f1db0 100644
--- a/Brewfile
+++ b/Brewfile
@@ -13,6 +13,5 @@ brew 'redis'
brew "pngquant"
brew "oxipng"
-brew "jhead"
brew "jpegoptim"
brew "coreutils"
diff --git a/Gemfile b/Gemfile
index e706d9ef881..42049123228 100644
--- a/Gemfile
+++ b/Gemfile
@@ -73,7 +73,6 @@ gem "unf", require: false
gem "email_reply_trimmer"
-gem "image_optim"
gem "multi_json"
gem "mustache"
gem "liquid", "5.12.0"
diff --git a/Gemfile.lock b/Gemfile.lock
index 01687a44517..389f591dde7 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -227,7 +227,6 @@ GEM
erubi (1.13.1)
excon (1.7.1)
logger
- exifr (1.5.1)
extralite-bundle (3.0.1)
fabrication (3.0.0)
faker (3.5.3)
@@ -254,7 +253,6 @@ GEM
fiber-local (1.1.0)
fiber-storage
fiber-storage (1.0.1)
- fspath (3.1.2)
globalid (1.4.0)
activesupport (>= 6.1)
goldiloader (6.0.0)
@@ -290,14 +288,6 @@ GEM
http_accept_language (2.1.1)
i18n (1.14.8)
concurrent-ruby (~> 1.0)
- image_optim (0.32.0)
- exifr (~> 1.2, >= 1.2.2)
- fspath (~> 3.0)
- image_size (>= 1.5, < 4)
- in_threads (~> 1.3)
- progress (~> 3.0, >= 3.0.1)
- image_size (3.6.0)
- in_threads (1.6.0)
inflection (1.0.0)
io-console (0.9.2)
irb (1.18.0)
@@ -501,7 +491,6 @@ GEM
prettier_print (1.2.1)
prettyprint (0.2.0)
prism (1.9.0)
- progress (3.6.0)
propshaft (1.3.2)
actionpack (>= 7.0.0)
activesupport (>= 7.0.0)
@@ -882,7 +871,6 @@ DEPENDENCIES
highline
htmlentities
http_accept_language
- image_optim
inflection
iso8601
json
@@ -1069,7 +1057,6 @@ CHECKSUMS
erb (6.0.7) sha256=c5ca6dc25b0ef974a44dc8f59fe847577122483b1968a38dec305c60bf91ee92
erubi (1.13.1) sha256=a082103b0885dbc5ecf1172fede897f9ebdb745a4b97a5e8dc63953db1ee4ad9
excon (1.7.1) sha256=dd2d870eece1b5ce4e4f9efd938e67a69ccd8c003c3825b638b937e1082eaac2
- exifr (1.5.1) sha256=ad87a5dbc92946fbf1d8ccd178d557d95d9168e8b3c5c5f381ea2bffcc312521
extralite-bundle (3.0.1) sha256=49b9b6d459b194b44519d80936d6a98a9e54522e34a8a725fd4e81fdb3944aac
fabrication (3.0.0) sha256=a6a0bfad9071348ad3cb1701df788524b888c0cdd044b988893e7509f7463be3
faker (3.5.3) sha256=b961482dc0bb15ccb9a98ea7878b925669e9ae8f5e59b607da540b768137d765
@@ -1088,7 +1075,6 @@ CHECKSUMS
fiber-annotation (0.2.0) sha256=7abfadf1d119f508867d4103bf231c0354d019cc39a5738945dec2edadaf6c03
fiber-local (1.1.0) sha256=c885f94f210fb9b05737de65d511136ea602e00c5105953748aa0f8793489f06
fiber-storage (1.0.1) sha256=f48e5b6d8b0be96dac486332b55cee82240057065dc761c1ea692b2e719240e1
- fspath (3.1.2) sha256=b5ac9bafb97e2c8f8f9e303cd98ebd484be76fe9aa588bc4d01c6d99e78c9d75
globalid (1.4.0) sha256=037f12fbf1d9d7a014d501c2d5c77356fd4ddd96d7a7991d6700bba96706f427
goldiloader (6.0.0) sha256=613db1b28e9964291255a67a521f04d481b6afd6b9ca56ea1a612fd86e9a89c7
google-protobuf (4.36.1-aarch64-linux-gnu) sha256=3883fa1b0e99221f68f4a8511bc4fb1888897dcb6cc8bf2805c92c16fc99b499
@@ -1106,9 +1092,6 @@ CHECKSUMS
htmlentities (4.4.2) sha256=bbafbdf69f2eca9262be4efef7e43e6a1de54c95eb600f26984f71d2fe96c5c3
http_accept_language (2.1.1) sha256=0043f0d55a148cf45b604dbdd197cb36437133e990016c68c892d49dbea31634
i18n (1.14.8) sha256=285778639134865c5e0f6269e0b818256017e8cde89993fdfcbfb64d088824a5
- image_optim (0.32.0) sha256=457d5ea28ee93244c2aabc7134e06455587fb670f210e88e1be40aea882c2ba3
- image_size (3.6.0) sha256=1b9c4196cb658bf503a887920543a3991e927a4b767a5c770fb9665bce0dcb28
- in_threads (1.6.0) sha256=91a7e6138d279dc632f59b8a9a409e47148948e297c0f69c92f9a2479a182149
inflection (1.0.0) sha256=ceba9b26fc28b9af82e33e822d28f78a4312af75687efec81d5ef1062498d355
io-console (0.9.2) sha256=efa74f891dd03c0939a931dfc6e74c2813d904763d456ea9762b0525e748db08
irb (1.18.0) sha256=de9454a0703a54704b9811a5ef31a60c86949fbf4013fcf244fabc7c775248e3
@@ -1209,7 +1192,6 @@ CHECKSUMS
prettier_print (1.2.1) sha256=a72838b5f23facff21f90a5423cdcdda19e4271092b41f4ea7f50b83929e6ff9
prettyprint (0.2.0) sha256=2bc9e15581a94742064a3cc8b0fb9d45aae3d03a1baa6ef80922627a0766f193
prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85
- progress (3.6.0) sha256=360ed306dfa43d6174e847d563c70736dca249e2333cfec4b0387306c86cd573
propshaft (1.3.2) sha256=1d56a3e56a92c21bfc29caf07406b5386b00d4c47ddf357cf989a5a234b1389e
pry (0.16.0) sha256=d76c69065698ed1f85e717bd33d7942c38a50868f6b0673c636192b3d1b6054e
pry-rails (0.3.11) sha256=a69e28e24a34d75d1f60bcf241192a54253f8f7ef8a62cba1e75750a9653593d
diff --git a/docs/developer-guides/docs/02-development-environments/10-fedora-setup.md b/docs/developer-guides/docs/02-development-environments/10-fedora-setup.md
index 307cabea78a..33e5a7e8855 100644
--- a/docs/developer-guides/docs/02-development-environments/10-fedora-setup.md
+++ b/docs/developer-guides/docs/02-development-environments/10-fedora-setup.md
@@ -12,7 +12,7 @@ If you're looking to install Discourse for a **production environment**, prefer
```sh
sudo dnf update
-sudo dnf install -y "@development-tools" git rpm-build zlib-devel ruby-devel readline-devel libpq-devel ImageMagick vips sqlite sqlite-devel nodejs npm curl gcc g++ bzip2 openssl-devel libyaml-devel libffi-devel zlib-devel gdbm-devel ncurses-devel optipng pngquant jhead jpegoptim gifsicle oxipng
+sudo dnf install -y "@development-tools" git rpm-build zlib-devel ruby-devel readline-devel libpq-devel ImageMagick vips sqlite sqlite-devel nodejs npm curl gcc g++ bzip2 openssl-devel libyaml-devel libffi-devel zlib-devel gdbm-devel ncurses-devel optipng pngquant jpegoptim gifsicle oxipng
```
**Install required npm packages**
diff --git a/lib/file_helper.rb b/lib/file_helper.rb
index 2384d8f1e37..8ff5e9625cd 100644
--- a/lib/file_helper.rb
+++ b/lib/file_helper.rb
@@ -4,6 +4,7 @@ require "final_destination"
require "image_processing/instrumentation"
require "mini_mime"
require "open-uri"
+require "tempfile"
class FileHelper
def self.log(log_level, message)
@@ -134,49 +135,75 @@ class FileHelper
def self.optimize_image!(filename, allow_pngquant: false)
ImageProcessing::Instrumentation.instrument(operation: :image_optim) do
- image_optim(
- allow_pngquant: allow_pngquant,
- strip_image_metadata: SiteSetting.strip_image_metadata,
- ).optimize_image!(filename)
- end
- end
+ commands =
+ case FastImage.type(filename)
+ when :png
+ oxipng = %w[oxipng --opt 3 --interlace 0 --quiet --stdout]
+ oxipng.concat(%w[--strip all]) if SiteSetting.strip_image_metadata
+ [oxipng].tap do |pipeline|
+ if allow_pngquant
+ pipeline << %w[
+ pngquant
+ --quality=0-100
+ --speed=3
+ --output=-
+ --skip-if-larger
+ --force
+ 256
+ ]
+ end
+ end
+ when :jpeg
+ jpegoptim = %w[jpegoptim --quiet --stdout --force]
+ jpegoptim << (SiteSetting.strip_image_metadata ? "--strip-all" : "--strip-none")
+ [jpegoptim]
+ else
+ next
+ end
- def self.image_optim(allow_pngquant: false, strip_image_metadata: true)
- # memoization is critical, initializing an ImageOptim object is very expensive
- # sometimes up to 200ms searching for binaries and looking at versions
- memoize("image_optim", allow_pngquant, strip_image_metadata) do
- pngquant_options = false
- pngquant_options = { allow_lossy: true } if allow_pngquant
-
- ImageOptim.new(
- # GLOBAL
- timeout: 15,
- skip_missing_workers: true,
- # PNG
- oxipng: {
- level: 3,
- strip: strip_image_metadata,
- },
- optipng: false,
- advpng: false,
- pngcrush: false,
- pngout: false,
- pngquant: pngquant_options,
- # JPG
- jpegoptim: {
- strip: strip_image_metadata ? "all" : "none",
- },
- jpegtran: false,
- jpegrecompress: false,
- # Skip looking for gifsicle, svgo binaries
- gifsicle: false,
- svgo: false,
- )
- end
- end
+ result = nil
+ input = File.expand_path(filename)
+ commands.each do |command|
+ Tempfile.create(
+ ["image-optimization-", File.extname(filename)],
+ File.dirname(input),
+ ) do |temporary|
+ begin
+ Discourse::SafeExec.capture(
+ "sh",
+ "-c",
+ 'exec "$@" > "$0"',
+ temporary.path,
+ "nice",
+ "-n",
+ "10",
+ *command,
+ "--",
+ input,
+ env: {
+ **ENV.slice("PATH"),
+ "MALLOC_ARENA_MAX" => "2",
+ },
+ unsetenv_others: true,
+ read: [*Discourse::SafeExec.default_read_paths, input],
+ write: [temporary.path],
+ execute: Discourse::SafeExec.default_execute_paths,
+ timeout: 15,
+ rlimits: ImageMagick::RLIMITS,
+ seccomp_deny_network: true,
+ )
+ rescue Discourse::Utils::CommandError, Errno::ENOENT
+ next
+ end
+ next if temporary.size.zero? || temporary.size >= File.size(input)
- def self.memoize(*args)
- (@memoized ||= {})[args] ||= yield
+ temporary.chmod(File.stat(input).mode)
+ File.rename(temporary.path, input)
+ result = filename
+ end
+ end
+ result
+ end
end
def self.supported_gravatar_extensions
diff --git a/lib/freedom_patches/image_optim_sandbox.rb b/lib/freedom_patches/image_optim_sandbox.rb
deleted file mode 100644
index d694df1ddea..00000000000
--- a/lib/freedom_patches/image_optim_sandbox.rb
+++ /dev/null
@@ -1,54 +0,0 @@
-# frozen_string_literal: true
-
-require "image_optim/cmd"
-require "image_optim/path"
-require "tmpdir"
-
-# Route image_optim's optimizer binaries through the Landlock sandbox, confining
-# them to the file being optimized with no network. Cmd.capture (version/CPU
-# probes, no untrusted input) is intentionally not patched.
-class ImageOptim
- # Per-thread tmp directory, so that we don't have to grant access to the global tmpdir
- def self.discourse_tmp_root
- Thread.current[:discourse_image_optim_tmp_root] ||= Dir.mktmpdir("discourse-image-optim-")
- end
-
- module DiscourseScratchDestination
- def temp_path(*args, &block)
- return super if args.any?
-
- super(ImageOptim.discourse_tmp_root, &block)
- end
- end
- ImageOptim::Path.prepend(DiscourseScratchDestination)
-
- module Cmd
- class << self
- def run(*args)
- options = args.last.is_a?(Hash) ? args.pop : {}
- env = args.first.is_a?(Hash) ? args.shift : {}
-
- files = args.select { |arg| arg.is_a?(String) && File.file?(arg) }
-
- Discourse::SafeExec.capture(
- *args,
- env: {
- **env,
- "MALLOC_ARENA_MAX" => "2",
- },
- unsetenv_others: true,
- read: [*Discourse::SafeExec.default_read_paths, *files],
- write: [ImageOptim.discourse_tmp_root],
- execute: Discourse::SafeExec.default_execute_paths,
- timeout: options[:timeout]&.to_f || ImageMagick::DEFAULT_TIMEOUT,
- rlimits: ImageMagick::RLIMITS,
- seccomp_deny_network: true,
- )
- true
- rescue Discourse::Utils::CommandError
- # non-zero exit means "kept the original", like system(*args) => false
- false
- end
- end
- end
-end
diff --git a/migrations/importer/lib/migrations/importer/uploads/uploads.rb b/migrations/importer/lib/migrations/importer/uploads/uploads.rb
index f1b59ce2226..fc7edce711e 100644
--- a/migrations/importer/lib/migrations/importer/uploads/uploads.rb
+++ b/migrations/importer/lib/migrations/importer/uploads/uploads.rb
@@ -59,24 +59,15 @@ module Migrations
end
def configure_services
- configure_logging
configure_site_settings
end
- def configure_logging
- @original_exifr_logger = EXIFR.logger
-
- # disable logging for EXIFR which is used by ImageOptim
- EXIFR.logger = Logger.new(nil)
- end
-
def configure_site_settings
SiteSettings.configure!(settings[:site_settings])
end
def cleanup_resources
databases.values.each(&:close)
- EXIFR.logger = @original_exifr_logger
end
end
end
diff --git a/script/bulk_import/uploads_importer.rb b/script/bulk_import/uploads_importer.rb
index 12052c53b06..9450eb13251 100644
--- a/script/bulk_import/uploads_importer.rb
+++ b/script/bulk_import/uploads_importer.rb
@@ -46,9 +46,6 @@ module BulkImport
end
def run
- # disable logging for EXIFR which is used by ImageOptim
- EXIFR.logger = Logger.new(nil)
-
if @settings[:fix_missing]
@source_db = create_connection(@settings[:output_db_path])
diff --git a/spec/fixtures/images/unoptimized_with_metadata.jpg b/spec/fixtures/images/unoptimized_with_metadata.jpg
new file mode 100644
index 00000000000..01b636f4614
Binary files /dev/null and b/spec/fixtures/images/unoptimized_with_metadata.jpg differ
diff --git a/spec/lib/file_helper_spec.rb b/spec/lib/file_helper_spec.rb
index 70b096a3b9d..2716cc3d199 100644
--- a/spec/lib/file_helper_spec.rb
+++ b/spec/lib/file_helper_spec.rb
@@ -163,20 +163,96 @@ RSpec.describe FileHelper do
end
describe ".optimize_image!" do
+ def with_optimizer_input(fixture)
+ Tempfile.create(["optimizer-spec-", File.extname(fixture)]) do |file|
+ FileUtils.cp(file_from_fixtures(fixture).path, file.path)
+ yield file.path
+ end
+ end
+
+ it "reduces PNG size" do
+ with_optimizer_input("large_and_unoptimized.png") do |path|
+ original_size = File.size(path)
+
+ expect(described_class.optimize_image!(path)).to eq(path)
+
+ expect(File.size(path)).to be < original_size
+ expect(FastImage.type(path)).to eq(:png)
+ end
+ end
+
+ it "keeps the input intact if replacing the optimized image fails" do
+ with_optimizer_input("large_and_unoptimized.png") do |path|
+ original = File.binread(path)
+ File.stubs(:rename).raises(Errno::EACCES)
+
+ expect { described_class.optimize_image!(path) }.to raise_error(Errno::EACCES)
+
+ expect(File.binread(path)).to eq(original)
+ end
+ end
+
+ it "reduces PNG size further when quantization is enabled" do
+ with_optimizer_input("large_and_unoptimized.png") do |path|
+ original = File.binread(path)
+ described_class.optimize_image!(path)
+ lossless_size = File.size(path)
+ File.binwrite(path, original)
+
+ described_class.optimize_image!(path, allow_pngquant: true)
+
+ expect(File.size(path)).to be < lossless_size
+ expect(FastImage.type(path)).to eq(:png)
+ end
+ end
+
+ it "optimizes JPEGs with the configured metadata policy" do
+ with_optimizer_input("unoptimized_with_metadata.jpg") do |path|
+ original = File.binread(path)
+ SiteSetting.composer_media_optimization_image_enabled = false
+ SiteSetting.strip_image_metadata = false
+ described_class.optimize_image!(path)
+ expect(File.binread(path)).to include("Exif")
+ expect(File.size(path)).to be < original.bytesize
+
+ File.binwrite(path, original)
+ SiteSetting.strip_image_metadata = true
+ described_class.optimize_image!(path)
+ expect(File.binread(path)).not_to include("Exif")
+ expect(FastImage.type(path)).to eq(:jpeg)
+ expect(File.size(path)).to be < original.bytesize
+ end
+ end
+
+ it "keeps the input when optimization fails or cannot reduce its size" do
+ with_optimizer_input("logo.png") do |path|
+ described_class.optimize_image!(path)
+ optimized = File.binread(path)
+
+ expect(described_class.optimize_image!(path)).to be_nil
+ expect(File.binread(path)).to eq(optimized)
+
+ invalid_png = "\x89PNG\r\n\x1a\n".b
+ File.binwrite(path, invalid_png)
+
+ expect(described_class.optimize_image!(path)).to be_nil
+ expect(File.binread(path)).to eq(invalid_png)
+ end
+ end
+
it "emits one image-processing measurement" do
SiteSetting.instrument_image_processing = true
- optimized_image = stub
- described_class.stubs(:image_optim).returns(stub(optimize_image!: optimized_image))
-
- events =
- DiscourseEvent.track_events(:image_processing_finished) do
- expect(described_class.optimize_image!("image.png")).to eq(optimized_image)
- end
-
- expect(events.size).to eq(1)
- payload = events.first[:params].first
- expect(payload.except(:duration_seconds)).to eq(operation: "image_optim", success: true)
- expect(payload[:duration_seconds]).to be >= 0
+ with_optimizer_input("large_and_unoptimized.png") do |path|
+ events =
+ DiscourseEvent.track_events(:image_processing_finished) do
+ expect(described_class.optimize_image!(path)).to eq(path)
+ end
+
+ expect(events.size).to eq(1)
+ payload = events.first[:params].first
+ expect(payload.except(:duration_seconds)).to eq(operation: "image_optim", success: true)
+ expect(payload[:duration_seconds]).to be >= 0
+ end
end
end
diff --git a/spec/lib/freedom_patches/image_optim_sandbox_spec.rb b/spec/lib/freedom_patches/image_optim_sandbox_spec.rb
deleted file mode 100644
index 7f8549814cb..00000000000
--- a/spec/lib/freedom_patches/image_optim_sandbox_spec.rb
+++ /dev/null
@@ -1,63 +0,0 @@
-# frozen_string_literal: true
-
-RSpec.describe "image_optim Landlock sandbox freedom patch" do
- def landlock?
- Discourse::SafeExec.landlock_supported?
- end
-
- it "routes worker commands through Discourse::SafeExec with the network denied" do
- Discourse::SafeExec
- .expects(:capture)
- .with { |*_command, **opts| opts[:seccomp_deny_network] == true }
- .returns("")
-
- expect(ImageOptim::Cmd.run({ "PATH" => ENV["PATH"] }, "true")).to eq(true)
- end
-
- it "returns false (keep original) when the sandboxed command fails" do
- Discourse::SafeExec.expects(:capture).raises(
- Discourse::Utils::CommandError.new("boom", stdout: "", stderr: "", status: nil),
- )
-
- expect(ImageOptim::Cmd.run({}, "false")).to eq(false)
- end
-
- it "allows reading a file passed in argv" do
- skip("Landlock unsupported on this host") unless landlock?
-
- Dir.mktmpdir do |dir|
- file = File.join(dir, "data")
- File.write(file, "hello")
- expect(ImageOptim::Cmd.run({ "PATH" => ENV["PATH"] }, "cat", file)).to eq(true)
- end
- end
-
- it "denies reading a file outside the allowlist" do
- skip("Landlock unsupported on this host") unless landlock?
-
- Dir.mktmpdir do |dir|
- secret = File.join(dir, "secret")
- File.write(secret, "top secret")
- # secret is referenced only inside a shell string, so its directory is
- # never granted and the sandbox must block the read.
- expect(ImageOptim::Cmd.run({ "PATH" => ENV["PATH"] }, "sh", "-c", "cat #{secret}")).to eq(
- false,
- )
- end
- end
-
- it "still optimizes a real image through the sandbox" do
- skip("Landlock unsupported on this host") unless landlock?
-
- Dir.mktmpdir do |dir|
- png = File.join(dir, "logo.png")
- FileUtils.cp(Rails.root.join("spec/fixtures/images/logo.png"), png)
- before = File.size(png)
-
- FileHelper.optimize_image!(png)
-
- expect(File.size(png)).to be <= before
- expect(FastImage.type(png)).to eq(:png)
- end
- end
-end