From 423ad5f0a488411d2f65585fe5921242d9cb0285 Mon Sep 17 00:00:00 2001 From: Sam Saffron Date: Thu, 21 Nov 2019 15:51:18 +1100 Subject: [PATCH] FIX: do not log if an invalid mime type is passed to app Previously our custom exception handler was unable to handle situations where an invalid mime type was sent, resulting in a warning log This ensures we pretend a request is HTML for the purpose of rendering the error page if an invalid mime type from a scanner is shipped to the app --- lib/middleware/discourse_public_exceptions.rb | 10 +++++- .../discourse_public_exceptions_spec.rb | 35 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 spec/components/middleware/discourse_public_exceptions_spec.rb diff --git a/lib/middleware/discourse_public_exceptions.rb b/lib/middleware/discourse_public_exceptions.rb index ffc281d85a2..c40f319a3ae 100644 --- a/lib/middleware/discourse_public_exceptions.rb +++ b/lib/middleware/discourse_public_exceptions.rb @@ -29,7 +29,15 @@ module Middleware begin fake_controller = ApplicationController.new fake_controller.response = response - fake_controller.request = ActionDispatch::Request.new(env) + fake_controller.request = request = ActionDispatch::Request.new(env) + + begin + request.format + rescue Mime::Type::InvalidMimeType + # got to do something here, we can not ship invalid format + # to the exception handler cause it will explode + request.format = "html" + end if ApplicationController.rescue_with_handler(exception, object: fake_controller) body = response.body diff --git a/spec/components/middleware/discourse_public_exceptions_spec.rb b/spec/components/middleware/discourse_public_exceptions_spec.rb new file mode 100644 index 00000000000..ac1a0cc6ceb --- /dev/null +++ b/spec/components/middleware/discourse_public_exceptions_spec.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +require "rails_helper" + +describe Middleware::DiscoursePublicExceptions do + before do + @orig_logger = Rails.logger + Rails.logger = @fake_logger = FakeLogger.new + end + + after do + Rails.logger = @orig_logger + end + + def env(opts = {}) + { + "HTTP_HOST" => "http://test.com", + "REQUEST_URI" => "/path?bla=1", + "REQUEST_METHOD" => "GET", + "rack.input" => "" + }.merge(opts) + end + + it "should not log for invalid mime type requests" do + ex = Middleware::DiscoursePublicExceptions.new("/test") + + ex.call(env( + "HTTP_ACCEPT" => "../broken../", + "action_dispatch.exception" => ActionController::RoutingError.new("abc") + )) + + expect(@fake_logger.warnings.length).to eq(0) + end + +end