Rail session reset intermittently

I know that this topic has been discussed a lot, but I believe that I have found a new variation of it: I have a Rails 4 application that has been updated with Rails 3 and has rails_ujsand csrf_meta_tags.

As soon as it root_urlloads in the browser, there is javascript that launches GET and PUT, each of which corresponds to its controller API in the application. By the time these two API calls are launched, the session SHOULD have _csrf_token. And this is true in most cases. Continue reading.

The problem is that, SOME, not always, we see some InvalidAuthenticityToken exceptions that occur for a PUT request. (yes, I use protect_from_forgery :with => :exceptionAPIs on our base controllers).

Analyzing the dump from exception_notification, I see that it is CSRF_TOKENcorrectly configured in the request header, but the most intriguing thing is that there is only one on it session_id. Everything else has disappeared, including _csrf_token.

Remember: this happens intermittently! Therefore, I believe that this should be some kind of race condition.

This app is hosted on Heroku and runs on Unicorn. I cannot reproduce the problem in my local environment. I also read a lot of Rails code on github, trying to understand the threads in which it resets the session, but I could not find the answer, since all CSRF protection is configured correctly, and the problem occurs intermittently.

It is also worth mentioning that we have not yet installed config.secret_key_base. But since this problem occurs intermittently, I do not think that this may be the main reason for this.

, , , :

(1) "" , ApplicationController

(2) API , Api:: BaseController, ActionController::Base

, ...

API GET json. API PUT head :ok.

, , - Ruby on Rails .

+4
2

cookie? cookie, , , , AJAX, cookie, .

2011 cookie, . CSRF , .

2014 cookie ActiveRecord . ( , URL- 404, google).

, cookie , . , , cookie, . , , get_current_results , get_quiz, cookie , update_response ! , -. .

, cookie , ajax, . , , . , ?

...

, memcache. cookie . , , ajax!

, , cookie ActiveRecord , .

, activerecord, , , , , , , cookie .

ActiveRecord, , cookie - ( ), - , , , . , , , cookie, , , , , cookie, , - .

+2

, , .

, current_user protect_from_forgery, current_user Devise:

      def current_#{mapping}
        @current_#{mapping} ||= warden.authenticate(scope: :#{mapping})
      end

config.clean_up_csrf_token_on_authentication = true.

, , csrf reset current_user get. warden.authenticate. protect_from_forgery. csrf . reset .

, .

+1

Source: https://habr.com/ru/post/1546199/


All Articles