From 0c43170630b5b4e90e8f91526066435a06e077eb Mon Sep 17 00:00:00 2001 From: Stan Hu Date: Sun, 13 May 2018 21:43:48 -0700 Subject: [PATCH] Fix cross-origin errors when attempting to download JavaScript attachments If you upload a file with a .js extension, Rails' cross-origin JavaScript protection will prevent a user from downloading the file with a 422 error. Setting the content-type to `text/plain` will allow the user to download the file as a plaintext file. Closes #45826 --- app/controllers/concerns/send_file_upload.rb | 4 ++++ .../sh-fix-cross-site-origin-uploads-js.yml | 5 +++++ .../controllers/concerns/send_file_upload_spec.rb | 15 +++++++++++++++ 3 files changed, 24 insertions(+) create mode 100644 changelogs/unreleased/sh-fix-cross-site-origin-uploads-js.yml diff --git a/app/controllers/concerns/send_file_upload.rb b/app/controllers/concerns/send_file_upload.rb index 55011c89886..237c93daee8 100644 --- a/app/controllers/concerns/send_file_upload.rb +++ b/app/controllers/concerns/send_file_upload.rb @@ -2,6 +2,10 @@ module SendFileUpload def send_upload(file_upload, send_params: {}, redirect_params: {}, attachment: nil, disposition: 'attachment') if attachment redirect_params[:query] = { "response-content-disposition" => "#{disposition};filename=#{attachment.inspect}" } + # By default, Rails will send uploads with an extension of .js with a + # content-type of text/javascript, which will trigger Rails' + # cross-origin JavaScript protection. + send_params[:content_type] = 'text/plain' if File.extname(attachment) == '.js' send_params.merge!(filename: attachment, disposition: disposition) end diff --git a/changelogs/unreleased/sh-fix-cross-site-origin-uploads-js.yml b/changelogs/unreleased/sh-fix-cross-site-origin-uploads-js.yml new file mode 100644 index 00000000000..3c51aaae896 --- /dev/null +++ b/changelogs/unreleased/sh-fix-cross-site-origin-uploads-js.yml @@ -0,0 +1,5 @@ +--- +title: Fix cross-origin errors when attempting to download JavaScript attachments +merge_request: +author: +type: fixed diff --git a/spec/controllers/concerns/send_file_upload_spec.rb b/spec/controllers/concerns/send_file_upload_spec.rb index f4c99ea4064..58bb91a0c80 100644 --- a/spec/controllers/concerns/send_file_upload_spec.rb +++ b/spec/controllers/concerns/send_file_upload_spec.rb @@ -51,6 +51,21 @@ describe SendFileUpload do end end + context 'with attachment' do + subject { controller.send_upload(uploader, attachment: 'test.js') } + + it 'sends a file with content-type of text/plain' do + expected_params = { + content_type: 'text/plain', + filename: 'test.js', + disposition: 'attachment' + } + expect(controller).to receive(:send_file).with(uploader.path, expected_params) + + subject + end + end + context 'when remote file is used' do before do stub_uploads_object_storage(uploader: uploader_class)