A platform for community discussion. Free, open, simple.
DEV: Deferred upload accesses tempfile after request completes (#38337)
Isaac Janzendd982bf67c26
diff --git a/app/controllers/admin/watched_words_controller.rb b/app/controllers/admin/watched_words_controller.rbindex 66c90464236..6a93e4fcdfa 100644--- a/app/controllers/admin/watched_words_controller.rb+++ b/app/controllers/admin/watched_words_controller.rb@@ -58,10 +58,10 @@ class Admin::WatchedWordsController < Admin::StaffControlleraction_key = params[:action_key].to_symhas_replacement = WatchedWord.has_replacement?(action_key)+ content = Encodings.to_utf8(File.read(file.tempfile, mode: "rb"))+Scheduler::Defer.later("Upload watched words") dobegin- content = Encodings.to_utf8(File.read(file.tempfile, mode: "rb"))-words_updated = 0CSV.parse(content) do |row|diff --git a/spec/requests/admin/watched_words_controller_spec.rb b/spec/requests/admin/watched_words_controller_spec.rbindex 7f82068a9c5..1cdde32addc 100644--- a/spec/requests/admin/watched_words_controller_spec.rb+++ b/spec/requests/admin/watched_words_controller_spec.rb@@ -289,6 +289,31 @@ RSpec.describe Admin::WatchedWordsController do)end+ it "reads file content before deferring work so tempfile cleanup does not cause errors" do+ allow(Scheduler::Defer).to receive(+ :later,+ ).and_wrap_original do |original, *args, **kwargs, &block|+ if args.first == "Upload watched words"+ # Simulate Rack::TempfileReaper: delete all tempfiles before the deferred block runs.+ # With the fix, File.read has already been called before Defer.later, so this is safe.+ # Without the fix, the block tries File.read on a deleted tempfile.+ ObjectSpace.each_object(Tempfile) do |tempfile|+ tempfile.close! if tempfile.path&.include?("RackMultipart")+ end+ end+ block.call+ end++ post "/admin/customize/watched_words/upload.json",+ params: {+ action_key: "flag",+ file: Rack::Test::UploadedFile.new(file_from_fixtures("words.csv", "csv")),+ }++ expect(response.status).to eq(200)+ expect(WatchedWord.count).to eq(6)+ end+it "handles files with invalid UTF-8 sequences" docontent = String.new("h\xE9llo\nworld\x99").force_encoding("Windows-1250")