app: improve InvalidAuthenticityToken logging

- Log on all controllers
- Improve description of the controller action involved
- Ignore Safari bogus requests
This commit is contained in:
Pierre de La Morinerie 2021-07-06 10:34:23 +00:00
parent 50ebd6d17a
commit 09933454ff
4 changed files with 78 additions and 12 deletions

View file

@ -2,6 +2,7 @@ class ApplicationController < ActionController::Base
include TrustedDeviceConcern
include Pundit
include Devise::StoreLocationExtension
include ApplicationController::ErrorHandling
MAINTENANCE_MESSAGE = 'Le site est actuellement en maintenance. Il sera à nouveau disponible dans un court instant.'

View file

@ -0,0 +1,29 @@
module ApplicationController::ErrorHandling
extend ActiveSupport::Concern
included do
rescue_from ActionController::InvalidAuthenticityToken do
if cookies.count == 0
# When some browsers (like Safari) re-open a previously closed tab, they attempts
# to reload the page even if it is a POST request. But in that case, they dont
# sends any of the cookies.
#
# Ignore this error.
render plain: "Les cookies doivent être activés pour utiliser #{APPLICATION_NAME}.", status: 403
else
log_invalid_authenticity_token_error
raise # propagate the exception up, to render the default exception page
end
end
end
def log_invalid_authenticity_token_error
Sentry.with_scope do |temp_scope|
tags = {
action: "#{self.class.name}#{action_name}"
}
temp_scope.set_tags(tags)
Sentry.capture_message("ActionController::InvalidAuthenticityToken")
end
end
end

View file

@ -81,18 +81,6 @@ class Users::SessionsController < Devise::SessionsController
private
def handle_unverified_request
log_invalid_authenticity_token_error
super
end
def log_invalid_authenticity_token_error
Sentry.with_scope do |temp_scope|
tags = {
request_tokens: request_authenticity_tokens.compact.map { |t| t.gsub(/.....$/, '*****') }.join(', '),
session_token: session[:_csrf_token]&.gsub(/.....$/, '*****')
}
temp_scope.set_tags(tags)
Sentry.capture_message("ActionController::InvalidAuthenticityToken in Users::SessionsController")
end
end
end