From 12d989568ed142175770e2cab85eaf6477bf7a56 Mon Sep 17 00:00:00 2001 From: Maikel Linke Date: Tue, 15 Feb 2022 16:09:01 +1100 Subject: [PATCH] Safer API error reporting We don't know what unknown errors would report. They could expose sensitive data. So let's not pass that data on to the public while we have the full details in Bugsnag. Also, let's not catch Exception because that could catch interrupts to gracefully shut down the application. --- app/controllers/api/v1/base_controller.rb | 17 +++++++++-------- config/locales/en.yml | 1 + 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rb index 60307ba6c7..aca1c09e55 100644 --- a/app/controllers/api/v1/base_controller.rb +++ b/app/controllers/api/v1/base_controller.rb @@ -14,7 +14,7 @@ module Api before_action :authenticate_user - rescue_from Exception, with: :error_during_processing + rescue_from StandardError, with: :error_during_processing rescue_from CanCan::AccessDenied, with: :unauthorized rescue_from ActiveRecord::RecordNotFound, with: :not_found rescue_from Pagy::VariableError, with: :invalid_pagination @@ -46,8 +46,13 @@ module Api def error_during_processing(exception) Bugsnag.notify(exception) - render status: :unprocessable_entity, - json: json_api_error(exception.message, backtrace: exception.backtrace) + if Rails.env.development? || Rails.env.test? + render status: :unprocessable_entity, + json: json_api_error(exception.message, meta: exception.backtrace) + else + render status: :unprocessable_entity, + json: json_api_error(I18n.t(:unknown_error, scope: "api")) + end end def invalid_pagination(exception) @@ -79,11 +84,7 @@ module Api end def json_api_error(message, **options) - error_response = { errors: [{ detail: message }] } - if options[:backtrace] && (Rails.env.development? || Rails.env.test?) - error_response.merge!(meta: [options[:backtrace]]) - end - error_response + { errors: [{ detail: message }] }.merge(options) end def json_api_invalid(message, errors) diff --git a/config/locales/en.yml b/config/locales/en.yml index 95fcaecaec..a20297cbf8 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -1409,6 +1409,7 @@ en: # API # api: + unknown_error: "Something went wrong. Our team has been notified." invalid_api_key: "Invalid API key (%{key}) specified." unauthorized: "You are not authorized to perform that action." invalid_resource: "Invalid resource. Please fix errors and try again."