1

We've just upgraded our Errbit app (https://github.com/errbit/errbit) from 0.6.0 to the latest version and we're finding that every POST request is throwing an exception that the CSRF token is invalid... if you change the protect_from_forgery in the ApplicationController to: protect_from_forgery with: :exception it will throw the InvalidAuthenticityException on every POST request.

Example from the logs:

Processing by Devise::SessionsController#new as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"iyoHKsD5c68Vk0rsiOG/oaNt+jauqy/IUIYK3GVFCnRikVDd9fFntyFBS2noPlKke27qw18yHw7MPpuglIMrdg==", "user"=>{"email"=>"test@test.com", "password"=>"[FILTERED]", "remember_me"=>"0"}}
Can't verify CSRF token authenticity.

It's not clear why this is happening as the SECRET_KEY_BASE is present, and we've confirmed that the form and csrf meta tags are all present in the code... it also works fine locally and worked before the upgrade...

The session_store also doesn't specify anything about domains (and didn't before):

Rails.application.config.session_store :cookie_store, key: '_errbit_session'

What could cause this to happen as we're a bit stuck as to what to check next.

Cameron
  • 27,963
  • 100
  • 281
  • 483
  • Hard to say.. maybe you could try a smaller upgrade? At least we could isolate the minor version increment where the problem appears.. – Stephen Crosby Jun 01 '23 at 22:27
  • The code itself seems fine as it works when running the same code locally... so not sure how it breaks on the server itself... rolling back the code to the previous version works... so doesn't seem like an issue with the server itself... it's very strange. – Cameron Jun 02 '23 at 11:31
  • Random questions: Are you using more than one server? I believe this jump includes a rails upgrade which may write sessions differently. Did you try using a private browsing session or clearing all cookies? – Stephen Crosby Jun 02 '23 at 22:54

1 Answers1

1

This commit to upgrade to Rails 5.0 https://github.com/errbit/errbit/commit/df2c0a6f8adc9190547d9c1b9ffb0a3fc20f0941?diff=split introduced Rails.application.config.action_controller.forgery_protection_origin_check = true in file config/initializers/new_framework_defaults.rb which led to this issue when using nginx as a reverse proxy and not providing sufficient headers.

To fix this, i had to pass on more nginx headers as explained here https://github.com/rails/rails/issues/22965#issuecomment-172929004

upstream myapp {
  server              unix:///path/to/puma.sock;
}
...
location / {
  proxy_pass        http://myapp;
  proxy_set_header  Host $host;
  proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header  X-Forwarded-Proto $scheme;
  proxy_set_header  X-Forwarded-Ssl on; # Optional
  proxy_set_header  X-Forwarded-Port $server_port;
  proxy_set_header  X-Forwarded-Host $host;
}
dmric
  • 91
  • 1