The personal finance app for everyone (by everyone)
Ruby
Keep long return_to paths from overflowing the session (#4238)
Andrei Shkarinc15ecad80c6b
diff --git a/app/controllers/concerns/store_location.rb b/app/controllers/concerns/store_location.rbindex 14f98068de..6359e5b469 100644--- a/app/controllers/concerns/store_location.rb+++ b/app/controllers/concerns/store_location.rb@@ -1,6 +1,11 @@module StoreLocationextend ActiveSupport::Concern+ # The session lives in a 4 KB cookie, so a long filtered URL (e.g. the+ # transactions list filtered by dozens of accounts) would raise+ # CookieOverflow. Past this size only the path is kept, without the query.+ MAX_STORED_RETURN_TO_BYTES = 1024+included dohelper_method :previous_pathbefore_action :store_return_to@@ -25,7 +30,15 @@ privatedef store_return_tosafe = safe_return_to(params[:return_to])- session[:return_to] = safe if safe+ return unless safe++ safe = safe.split("?", 2).first if safe.bytesize > MAX_STORED_RETURN_TO_BYTES+ if safe.bytesize <= MAX_STORED_RETURN_TO_BYTES+ session[:return_to] = safe+ else+ # Don't leave an older target behind for previous_path to return.+ session.delete(:return_to)+ endend# Only allow internal absolute paths (a single leading "/"). Blocks absolutediff --git a/test/controllers/concerns/store_location_test.rb b/test/controllers/concerns/store_location_test.rbnew file mode 100644index 0000000000..b576645f01--- /dev/null+++ b/test/controllers/concerns/store_location_test.rb@@ -0,0 +1,36 @@+require "test_helper"++class StoreLocationTest < ActionDispatch::IntegrationTest+ setup do+ sign_in users(:family_admin)+ end++ test "stores a short return_to with its query string" do+ return_to = transactions_path(q: { search: "coffee" })++ get accounts_path(return_to: return_to)++ assert_response :success+ assert_equal return_to, session[:return_to]+ end++ test "drops the query string of a return_to too long for the session cookie" do+ account_ids = Array.new(32) { SecureRandom.uuid }+ return_to = "/transactions?" + { page: 1, q: { account_ids: account_ids } }.to_query++ get accounts_path(return_to: return_to)++ assert_response :success+ assert_equal "/transactions", session[:return_to]+ end++ test "clears a stored return_to when the new path is too long even without its query" do+ get accounts_path(return_to: transactions_path)+ assert_equal transactions_path, session[:return_to]++ get accounts_path(return_to: "/" + "a" * (StoreLocation::MAX_STORED_RETURN_TO_BYTES + 1))++ assert_response :success+ assert_nil session[:return_to]+ end+end