Proposal for improving InvalidAuthenticityToken error when invalid same origin

Hello

When your server do not properly manage request.origin VS request.base_url you end up with a very helping log introduced here Improve logging when Origin header doesn’t match · rails/rails@a500b47 · GitHub

“HTTP Origin header (#{request.origin}) didn’t match request.base_url (#{request.base_url})”

There is a lot of discussion about InvalidAuthenticityToken on Github and Stackoverflow and I think the error should be more helpful.

One problem is, the exception is always InvalidAuthenticityToken and do not provide any further informations. So people think there is a wrong handling of authenticity_token when it is a same origin issue.

I would like to make 2 proposals:

  • Set the log message as InvalidAuthenticityToken exception message:
    • ActionController::InvalidAuthenticityToken: {:message=>"HTTP Origin header (https://x.v.com) didn't match request.base_url (https://u.v.com)"}
  • Use a custom class for wrong Origin to reflect that the error is not related to an AuthenticityToken . ActionController::InvalidSameOrigin: {:message=>"HTTP Origin header (https://x.v.com) didn't match request.base_url (https://u.v.com)"}

The second point means that the two validations will remain activated by default but will have there own error class: ActionController::InvalidAuthenticityToken and a new ActionController::InvalidSameOrigin

Related:

3 Likes

Smallest change first. https://github.com/rails/rails/pull/41822

in initializers/omniauth.rb

token_verifier = OmniAuth.config.before_request_phase # omniauth-rails_csrf_protection
OmniAuth.config.before_request_phase = proc do |env|
  begin
    token_verifier&.call(env)
  rescue ActionController::InvalidAuthenticityToken => e
    OmniAuth::FailureEndpoint.new(env).redirect_to_failure
  end
end

Yes. It will probably need to be a new error on a sub class to be properly rescuable by existing code.

At the moment I am waiting for an approval on the first PR.