Rails 6 CSRF Token Expiry issue - ruby-on-rails

We are encountering an issue with form submission in production environment.
The criteria seems to be exceptionally rare, I have been unable to replicate the issue.
CSRF token is created and validated just fine.
Timing
Issue seems to occur only when users wait more than 2 hours on a form before submitting, but doing this we have been unable to reproduce as well.
Logs
W, [2022-07-14T15:19:37.535241 #2433] WARN -- : Can't verify CSRF token authenticity.
I, [2022-07-14T15:19:37.535556 #2433] INFO -- : Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms | Allocations: 291)
F, [2022-07-14T15:19:37.536425 #2433] FATAL -- :
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
System configuration
Rails version 6.1.6
Ruby version 2.7.4

check in your initializers for a session_store.rb
Inside if it you may find an expire_after is already set:
Rails.application.config.session_store :cookie_store,
key: '_myapp_session_',
expire_after: 30.minutes

Related

ClassLink Devise OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected

I've looked through various similar issues and responses but to no avail. Sorry if this is obvious but OAuth is not my area of expertise.
I'm running Rails 5.2 with Ruby 2.74 and Devise. I have SSO set up with Facebook and it works fine. I'm trying to get it working with ClassLink, but I'm stuck. When clicking on our ClassLink dashboard icon (ClassLink website), it opens a new browser window to our site, as it should, but fails to log in as that user. A user with the same email is set up on both ends. The server error is
15:14:51 web.1 | D, [2022-09-01T15:14:51.715485 #1139413] DEBUG -- omniauth: (classlink) Callback phase initiated.
15:14:51 web.1 | E, [2022-09-01T15:14:51.720435 #1139413] ERROR -- omniauth: (classlink) Authentication failure! csrf_detected: OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected | CSRF detected
The Omniauth-Classlink Gem calls for a devise.rb entry of
config.omniauth :class_link,
'your-classlink-access-key',
'your-classlink-secret',
strategy_class: 'OmniAuth::Strategies::ClassLink'
but with that last parameter (strategy_class), the server won't start and exits with an error:
NoMethodError: undefined method `new' for "OmniAuth::Strategies::ClassLink":String
so I'm leaving that off since it wasn't required for my working Facebook SSO.
On the failed login I'm getting the following log entry:
Processing by Users::OmniauthCallbacksController#failure as HTML
Parameters: {"code"=>"c166206446884317a72fa1c03772a2b622c9135c526e7a", "response_type"=>"code"}
Redirected to https://dtest.pagekite.me/?locale=en
Filter chain halted as :authorize rendered or redirected
Completed 302 Found in 8ms (ActiveRecord: 0.0ms)
The domain registered on ClassLink matches our server and the callback url is correct. The permissions, routes, callback function, etc. all look OK to me (again, pretty much identical to Facebook). Any suggestions on where I might look next?
Thanks.
It sounds like you have a few different problems going on here.
15:14:51 web.1 | D, [2022-09-01T15:14:51.715485 #1139413] DEBUG -- omniauth: (classlink) Callback phase initiated. 15:14:51 web.1 | E, [2022-09-01T15:14:51.720435 #1139413] ERROR -- omniauth: (classlink) Authentication failure! csrf_detected: OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected | CSRF detected
In the request phase, you receive a state parameter with a random value. The omniauth-oauth2 strategy (from which the omniauth-classlink strategy is subclassed) stores this value in the session. In the callback phase, you again receive a state parameter and it must match the one received in the request phase. This error almost always means there is something wrong with your session
NoMethodError: undefined method `new' for "OmniAuth::Strategies::ClassLink":String
The value of the strategy_class option should be the class name constant. Removing the quotes should fix it.
Processing by Users::OmniauthCallbacksController#failure as HTML Parameters: {"code"=>"c166206446884317a72fa1c03772a2b622c9135c526e7a", "response_type"=>"code"} Redirected to https://dtest.pagekite.me/?locale=en Filter chain halted as :authorize rendered or redirected Completed 302 Found in 8ms (ActiveRecord: 0.0ms)
This is Devise trying to authorize the callback request when it should not be. Is your Users::OmniauthCallbacksController calling authenticate_user! in a before action or inheriting that behavior from a parent class?

axios/rack-cors/react-rails/heroku: Internal Server Error 500 on sign out, no persistence on refresh

ERROR MSG:
Error: Request failed with status code 500
Stack trace:
[42]/</t.exports#http://crdwk.herokuapp.com/packs/bundle-ecc8ea14dbe153e50352.js:1:89311
[42]/</t.exports#http://crdwk.herokuapp.com/packs/bundle-ecc8ea14dbe153e50352.js:1:251725
[42]/</t.exports/</d[h]#http://crdwk.herokuapp.com/packs/bundle-ecc8ea14dbe153e50352.js:1:88311
Ruby version: 2.3
Rails version: 5.1
I have a server-side rendered, client-side hydrated React/Rails app (using gem 'react-rails').
I added the gem 'rack-cors' plus setup in application.rb in order for my requests to work (I'm using axios). However, signing out (a DELETE request) fails and hitting refresh erases the current user. Neither issue occurs locally/in development.
Here's the app: http://crdwk.herokuapp.com
And the repo: https://github.com/English3000/crdwk
I took a look at my Heroku logs:
Completed 500 Internal Server Error in 8ms (ActiveRecord: 0.0ms)
NoMethodError (undefined method `reset_token' for nil:NilClass):
app/controllers/application_controller.rb:29:in `sign_out'
app/controllers/api/sessions_controller.rb:3:in `destroy'
Given that hitting refresh, the current user does not persist, the issue is the current user somehow isn't getting set.
However, this is not an issue in development. Why would that be?
Looking through my project, the only difference I can find on the backend as compared with a client-side rendered one (which I literally copy & pasted the code for this project from) is this line in application_controller.rb:
skip_before_action :verify_authenticity_token
However, if I comment out this line, when I try to sign up, I get the server error
Started POST "/api/users" for 127.0.0.1 at 2018-03-05 12:16:57 -0800
Processing by Api::UsersController#create as JSON
Parameters: {"user"=>{"email"=>"", "password"=>"[FILTERED]"}}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)
ActionController::InvalidAuthenticityToken - ActionController::InvalidAuthenticityToken:
This is a result of using gem 'react-rails'. (I don't get this error for my other client-side rendered project.)
There isn't an "authenticity_token" parameter.
I find these two resources: Rails security and Learnetto's how-to.
So I add these two lines of code from the second artilce to my api.js:
const csrfToken = document.querySelector("meta[name=csrf-token]").content;
axios.defaults.headers.common["X-CSRF-Token"] = csrfToken;
Now my web app works with the extra application_controller.rb line commented out. EXCEPT, I can't use the DOM to grab the csrf token for my React Native version, so I now have the same issue for mobile...

Rails application getting 500 error page on production

I'm migrating a working Rails 3 application from server to another type of service. Firstly I had issues with static files (e.g. application.css, application.js) not being rendered (404 status). I resolved that issue turning the config.assets.enabled to true.
Now I'm having the problem of error 500 no matter where I go in the application. I assume it's an asset problem. I don't get an error in log/production. Only something as follow:
Started GET "/" for 187.39.38.147 at 2016-06-14 12:33:05 +0000
Processing by BooksController#index as HTML
Rendered myapp/layouts/500.html (0.7ms)
Completed 404 Not Found in 16ms (Views: 10.0ms | ActiveRecord: 1.9ms)
I have no idea of how to find out what's wrong to fix that.
What can I do to find out what's wrong ?

Could not authenticate you from Foursquare because "Csrf detected"

I'm using Devise + Omniauth (actually omniauth-foursquare, the foursquare OAuth2 strategy) in my Rails app.
Upon signing in, I keep being redirected to my app (/users/sign_in#=) with the following error:
Could not authenticate you from Foursquare because "Csrf detected"
Any insights?
This is what I see last in the console:
I, [2014-10-19T19:43:38.947771 #2] INFO -- omniauth: (foursquare) Request phase initiated.
Started GET "/users/auth/foursquare" for 142.255.113... at 2014-10-19 19:43:38 +0000
Parameters: {"code"=>"2MZGM413...", "state"=>"1ba1cec3beb4..."}
Processing by Devise::SessionsController#new as HTML
Started GET "/users/auth/foursquare/callback?code=2MZGM413...&state=1ba1cec3beb4..." for 142.255.113... at 2014-10
I, [2014-10-19T19:43:39.378477 #2] INFO -- omniauth: (foursquare) Callback phase initiated.
E, [2014-10-19T19:43:39.378660 #2] ERROR -- omniauth: (foursquare) Authentication failure! csrf_detected: OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected | CSRF detected
As far as I can tell, my troubles started when I received a "cookie overflow" erorr and switched to session_storing: (session_store.rb)
Rails.application.config.session_store :active_record_store, key: '_APPNAME_session', domain: 'DOMAIN.com'
Thanks!
If you inspect the source for your app, you'll see that the generated HTML includes the CSRF meta tags in the HEAD element (i.e. csrf-token and csrf-param). Most likely, one of your layouts/views is calling the csrf_meta_tags method. Try removing it to see if it works, and then consider creating a separate layout without it for forms that won't need it. Other people with more experience on frontend rails could chime in here with best practices.

Params variable not getting filled with JSON post data....Why?

I had this service working before, with some other fields, but right now i seem not to get it working, and am not quite getting why.
I'm posting the following json to my Rails app (with RestClient 2.4, for the test) :
{
"camp":{
"total": 100,
"number": "epw1f6e"
},
"machine":{
"serial_number": "1234567",
"token": "fONxDN"
}
}
Camp controller :
def create
if is_it_json?
logger.debug params.inspect
machine = Machine.find_by_serial_number(params[:machine][:serial_number])
...
From the logger, I get that params are : {"action"=>"create", "controller"=>"camp"}
Where is the json information??
My log error :
Started POST "/camps" for 127.0.0.1 at 2012-07-15 00:08:21 +0100
Processing by CampsController#create as JSON
WARNING: Can't verify CSRF token authenticity
{"action"=>"create", "controller"=>"camps"}
Completed 500 Internal Server Error in 2ms
NoMethodError (undefined method `[]' for nil:NilClass):
app/controllers/camps_controller.rb:24:in `create'
What might i be doing wrong?
Thank you
After a lot of reading and questioning, i just found out the solution :
The params weren't getting filled because i was missing Headers (I had the Accept, but was missing the Content-type) :
Accept: application/json
Content-type: application/json
Adding the headers solved this issue.
Can't verify CSRF token authenticity {"action"=>"create", "controller"=>"camps"}
Completed 500 Internal Server Error in 2ms
That error is thrown when an invalid (or nonexistent) CSRF token is posted with your json. The CSRF needs to be attached to the header of any posted data. For testing you can disable CSRF tokens by adding the following to your controller (for Rails 3):
protect_from_forgery :except => :create
Do not leave that in your controller when the site goes into production. CSRF tokens prevent CSRF attacks. Refer to the Ruby on Rails Security Guide for more details.
Let me know if that does the trick!

Resources