Skip to content

A platform for community discussion. Free, open, simple.

DEV: Only write session cookie when contents is changed (#33828)

David Taylor31306d5f715e
diff --git a/lib/action_dispatch/session/discourse_cookie_store.rb b/lib/action_dispatch/session/discourse_cookie_store.rb
index 58da5c8f5d3..24cf5816081 100644
--- a/lib/action_dispatch/session/discourse_cookie_store.rb
+++ b/lib/action_dispatch/session/discourse_cookie_store.rb
@@ -5,6 +5,13 @@ class ActionDispatch::Session::DiscourseCookieStore < ActionDispatch::Session::C
super(app, options)
end
+ # By default, Rack/Rails will include the session cookie in every response,
+ # even if its content hasn't changed. This makes race conditions very likely when
+ # multiple requests are made in parallel
+ def commit_session?(request, session, options)
+ super(request, session, options) && session_has_changed?(request, session)
+ end
+
private
def set_cookie(request, session_id, cookie)
@@ -16,4 +23,10 @@ class ActionDispatch::Session::DiscourseCookieStore < ActionDispatch::Session::C
end
cookie_jar(request)[@key] = cookie
end
+
+ def session_has_changed?(request, session)
+ _, original_session = load_session(request)
+ new_session = session.to_hash
+ original_session != new_session
+ end
end
diff --git a/spec/integration/discourse_cookie_store_spec.rb b/spec/integration/discourse_cookie_store_spec.rb
new file mode 100644
index 00000000000..c27b87a3f57
--- /dev/null
+++ b/spec/integration/discourse_cookie_store_spec.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+describe ActionDispatch::Session::DiscourseCookieStore, type: :request do
+ it "only writes session cookie when changed" do
+ get "/session/csrf.json"
+ expect(response.status).to eq(200)
+ expect(response.cookies["_forum_session"]).to be_present
+ csrf_token = session[:_csrf_token]
+ expect(csrf_token).to be_present
+
+ get "/session/csrf.json"
+ expect(response.status).to eq(200)
+ expect(response.cookies["_forum_session"]).not_to be_present
+ expect(session[:_csrf_token]).to eq(csrf_token)
+ end
+end