From b7d215adb69cd49bc4f36adf6ebe7e5599b012af Mon Sep 17 00:00:00 2001 From: Martin Slemr Date: Mon, 24 May 2021 13:45:29 +0200 Subject: [PATCH] Ensure UTF-8 compatibility for ErrorDocument#to_json --- lib/insights/api/common/error_document.rb | 3 ++- spec/dummy/app/controllers/api/v1x0.rb | 4 ++++ spec/dummy/config/routes.rb | 1 + spec/requests/exception_handling_spec.rb | 8 ++++++++ 4 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/insights/api/common/error_document.rb b/lib/insights/api/common/error_document.rb index 888c249e..7aa89fd2 100644 --- a/lib/insights/api/common/error_document.rb +++ b/lib/insights/api/common/error_document.rb @@ -4,7 +4,8 @@ module Common class ErrorDocument def add(status = 400, message) @status = status - errors << {"status" => status, "detail" => message} + safe_message = message.to_s.encode('UTF-8', :invalid => :replace, :undef => :replace) + errors << {"status" => status, "detail" => safe_message} self end diff --git a/spec/dummy/app/controllers/api/v1x0.rb b/spec/dummy/app/controllers/api/v1x0.rb index fbdc814b..d8d11f70 100644 --- a/spec/dummy/app/controllers/api/v1x0.rb +++ b/spec/dummy/app/controllers/api/v1x0.rb @@ -67,6 +67,10 @@ def error_nested raise SomethingHappened, "something else happened" end + def error_utf8 + raise StandardError, "something \xAE happened" + end + def http_error raise ActionCable::Connection::Authorization::UnauthorizedError end diff --git a/spec/dummy/config/routes.rb b/spec/dummy/config/routes.rb index 0464cc7b..d76e3ca5 100644 --- a/spec/dummy/config/routes.rb +++ b/spec/dummy/config/routes.rb @@ -32,6 +32,7 @@ namespace :v1x0, :path => "v1.0" do get "/error", :to => "errors#error" get "/error_nested", :to => "errors#error_nested" + get "/error_utf8", :to => "errors#error_utf8" get "/http_error", :to => "errors#http_error" get "/api_client_error", :to => "errors#api_client_error" get "/pundit_error", :to => "errors#pundit_error" diff --git a/spec/requests/exception_handling_spec.rb b/spec/requests/exception_handling_spec.rb index bb84c559..b64d49ef 100644 --- a/spec/requests/exception_handling_spec.rb +++ b/spec/requests/exception_handling_spec.rb @@ -34,6 +34,14 @@ end end + context "utf-8 conversion error" do + it "returns the error message" do + get "/api/v1.0/error_utf8", :headers => headers + expect(response.status).to eq(400) + expect(error.first["detail"]).to match(/StandardError/) + end + end + context "api_client_error" do context "with response body" do let(:response_header) { { 'Content-Type' => 'application/json' } }