Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

security: expire inactive sessions server-side, whitelist session tab keys (#3242)

GFR879d45be975e
diff --git a/app/constraints/super_admin_constraint.rb b/app/constraints/super_admin_constraint.rb
index 675108dfba..2fada63774 100644
--- a/app/constraints/super_admin_constraint.rb
+++ b/app/constraints/super_admin_constraint.rb
@@ -1,7 +1,8 @@
# Routing constraint for mounting engines that bypass ApplicationController
# entirely (e.g. Sidekiq::Web). Resolves the signed session cookie the same
-# way Authentication#find_session_by_cookie does and requires the session's
-# user to be a super admin.
+# way Authentication#find_session_by_cookie does (via Session.find_active_by_cookie,
+# which also enforces inactivity expiry) and requires the session's user to
+# be a super admin.
#
# The session's user is always the TRUE user: impersonation is resolved at the
# Current level, so an impersonated member can never satisfy this, and a
@@ -13,20 +14,7 @@
class SuperAdminConstraint
def matches?(request)
cookie_value = request.cookie_jar.signed[:session_token]
- return false if cookie_value.blank?
-
- session_record = Session.find_by(id: cookie_value)
- return false unless session_record
-
- unless session_record.user&.active?
- # Same cleanup as Authentication#find_session_by_cookie — a stale
- # session belonging to a deactivated user is destroyed here, not just
- # denied, so it can't be reused once found.
- session_record.destroy
- return false
- end
-
- session_record.user.super_admin?
+ Session.find_active_by_cookie(cookie_value)&.user&.super_admin? || false
rescue => e
Rails.logger.warn("SuperAdminConstraint rejected request: #{e.class}: #{e.message}")
false
diff --git a/app/controllers/concerns/authentication.rb b/app/controllers/concerns/authentication.rb
index 1ad099a395..b9ee115e90 100644
--- a/app/controllers/concerns/authentication.rb
+++ b/app/controllers/concerns/authentication.rb
@@ -29,13 +29,9 @@ module Authentication
end
def find_session_by_cookie
- cookie_value = cookies.signed[:session_token]
- return if cookie_value.blank?
+ session_record = Session.find_active_by_cookie(cookies.signed[:session_token])
+ return session_record if session_record
- session_record = Session.includes(:user).find_by(id: cookie_value)
- return session_record if session_record&.user&.active?
-
- session_record&.destroy!
cookies.delete(:session_token)
nil
end
diff --git a/app/jobs/session_cleaner_job.rb b/app/jobs/session_cleaner_job.rb
new file mode 100644
index 0000000000..94727493af
--- /dev/null
+++ b/app/jobs/session_cleaner_job.rb
@@ -0,0 +1,9 @@
+class SessionCleanerJob < ApplicationJob
+ queue_as :scheduled
+
+ def perform
+ deleted_count = Session.clean
+
+ Rails.logger.info("SessionCleanerJob: Deleted #{deleted_count} sessions inactive for over #{Session::INACTIVITY_TIMEOUT.inspect}") if deleted_count > 0
+ end
+end
diff --git a/app/models/session.rb b/app/models/session.rb
index 891a72f24b..6ca442a730 100644
--- a/app/models/session.rb
+++ b/app/models/session.rb
@@ -6,6 +6,22 @@ class Session < ApplicationRecord
encrypts :user_agent
end
+ # Sessions have no explicit expiry column; a session is considered expired
+ # once it hasn't been touched (see Authentication#find_session_by_cookie)
+ # for this long. Without this, the signed session cookie is `.permanent`
+ # (20 years) and a stolen cookie would grant indefinite access.
+ INACTIVITY_TIMEOUT = 30.days
+
+ # Only keys actually rendered by DS::Tabs (session_key:) may be persisted.
+ # Without this, PUT /current_session accepts any tab_key/tab_value pair
+ # from the client and writes it straight into this record's jsonb column.
+ ALLOWED_TAB_KEYS = %w[account_sidebar_tab].freeze
+
+ # How often an active session's `updated_at` is bumped. Touching on every
+ # request would mean a write per page load; this keeps the inactivity
+ # clock reasonably accurate without that cost.
+ SESSION_TOUCH_INTERVAL = 1.hour
+
belongs_to :user, counter_cache: :sessions_count
belongs_to :active_impersonator_session,
-> { where(status: :in_progress) },
@@ -16,6 +32,50 @@ class Session < ApplicationRecord
after_create :update_user_last_login
+ class << self
+ def clean
+ count = 0
+ where("updated_at < ?", INACTIVITY_TIMEOUT.ago).find_each do |session|
+ # Recheck under a row lock: a request may have touched this session
+ # (see Authentication#find_session_by_cookie) between the query above
+ # and this iteration, in which case it is no longer inactive.
+ session.with_lock do
+ next unless session.updated_at < INACTIVITY_TIMEOUT.ago
+ session.destroy
+ count += 1
+ end
+ rescue ActiveRecord::RecordNotFound
+ # with_lock reloads the row before yielding; if find_active_by_cookie
+ # destroyed it concurrently (expired user, invalid session) in that
+ # window, there's nothing left to clean up here.
+ next
+ end
+ count
+ end
+
+ # Shared cookie -> Session resolver used by every path that authenticates
+ # via the signed session_token cookie (Authentication concern, Doorkeeper
+ # authenticators, SuperAdminConstraint), so inactivity expiry can't be
+ # bypassed by adding a new entry point that forgets to check `expired?`.
+ #
+ # Also refreshes the activity clock here (not per-caller) so any of these
+ # paths keeps a session alive, not just cookie-based web requests.
+ def find_active_by_cookie(cookie_value)
+ return nil if cookie_value.blank?
+
+ session_record = includes(:user).find_by(id: cookie_value)
+ return nil unless session_record
+
+ if session_record.user&.active? && !session_record.expired?
+ session_record.touch if session_record.updated_at < SESSION_TOUCH_INTERVAL.ago
+ session_record
+ else
+ session_record.destroy!
+ nil
+ end
+ end
+ end
+
def prev_transaction_page_params
super || {}
end
@@ -26,11 +86,17 @@ class Session < ApplicationRecord
end
def set_preferred_tab(tab_key, tab_value)
+ return unless ALLOWED_TAB_KEYS.include?(tab_key)
+
data["tab_preferences"] ||= {}
data["tab_preferences"][tab_key] = tab_value
save!
end
+ def expired?
+ updated_at < INACTIVITY_TIMEOUT.ago
+ end
+
private
def capture_session_info
diff --git a/config/initializers/doorkeeper.rb b/config/initializers/doorkeeper.rb
index 5d2a1fdfd6..9ac2245907 100644
--- a/config/initializers/doorkeeper.rb
+++ b/config/initializers/doorkeeper.rb
@@ -8,27 +8,15 @@ Doorkeeper.configure do
# This block will be called to check whether the resource owner is authenticated or not.
resource_owner_authenticator do
# Manually replicate the app's session-based authentication logic, since
- # Doorkeeper controllers don't include our Authentication concern. This
- # must reject (and destroy) a session whose user has been deactivated,
- # the same way Authentication#find_session_by_cookie does — otherwise a
- # stale session (e.g. `active` flipped via update_column, which skips
- # callbacks) could still be used to issue a fresh OAuth authorization
- # grant for a deactivated user.
- if (session_id = cookies.signed[:session_token]).present?
- if (session_record = Session.find_by(id: session_id))
- if session_record.user&.active?
- # Set Current.session so downstream code expecting it behaves normally.
- Current.session = session_record
- # Return the authenticated user object as the resource owner.
- session_record.user
- else
- Rails.logger.warn("[AUTH] Rejected OAuth authorization for deactivated user_id=#{session_record.user_id}")
- session_record.destroy
- redirect_to new_session_url
- end
- else
- redirect_to new_session_url
- end
+ # Doorkeeper controllers don't include our Authentication concern.
+ # Session.find_active_by_cookie enforces the same inactivity expiry as
+ # Authentication#find_session_by_cookie (nil for a missing, inactive-user,
+ # or expired session).
+ if (session_record = Session.find_active_by_cookie(cookies.signed[:session_token]))
+ # Set Current.session so downstream code expecting it behaves normally.
+ Current.session = session_record
+ # Return the authenticated user object as the resource owner.
+ session_record.user
else
redirect_to new_session_url
end
@@ -41,19 +29,9 @@ Doorkeeper.configure do
#
# Same active?-check-and-destroy treatment as resource_owner_authenticator above.
admin_authenticator do
- if (session_id = cookies.signed[:session_token]).present?
- if (session_record = Session.find_by(id: session_id))
- if session_record.user&.active?
- Current.session = session_record
- head :forbidden unless session_record.user.super_admin?
- else
- Rails.logger.warn("[AUTH] Rejected Doorkeeper admin access for deactivated user_id=#{session_record.user_id}")
- session_record.destroy
- redirect_to new_session_url
- end
- else
- redirect_to new_session_url
- end
+ if (session_record = Session.find_active_by_cookie(cookies.signed[:session_token]))
+ Current.session = session_record
+ head :forbidden unless session_record.user&.super_admin?
else
redirect_to new_session_url
end
diff --git a/config/schedule.yml b/config/schedule.yml
index 07f6a0f003..7ff15d08a8 100644
--- a/config/schedule.yml
+++ b/config/schedule.yml
@@ -69,6 +69,13 @@ clean_inactive_families:
queue: "scheduled"
description: "Archives and destroys families that expired their trial without subscribing (managed mode only)"
+clean_sessions:
+ cron: "15 4 * * *" # daily at 4:15 AM
+ class: "SessionCleanerJob"
+ active_job: true
+ queue: "scheduled"
+ description: "Deletes sessions inactive for over 30 days"
+
refresh_demo_family:
cron: "0 5 * * *" # daily at 5:00 AM UTC
class: "DemoFamilyRefreshJob"
diff --git a/db/migrate/20260828100000_add_index_on_sessions_updated_at.rb b/db/migrate/20260828100000_add_index_on_sessions_updated_at.rb
new file mode 100644
index 0000000000..b71343895b
--- /dev/null
+++ b/db/migrate/20260828100000_add_index_on_sessions_updated_at.rb
@@ -0,0 +1,7 @@
+class AddIndexOnSessionsUpdatedAt < ActiveRecord::Migration[8.1]
+ disable_ddl_transaction!
+
+ def change
+ add_index :sessions, :updated_at, algorithm: :concurrently, if_not_exists: true
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 55d4b3e361..88acf644ac 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -2379,6 +2379,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_20_090001) do
t.uuid "user_id", null: false
t.index ["active_impersonator_session_id"], name: "index_sessions_on_active_impersonator_session_id"
t.index ["ip_address_digest"], name: "index_sessions_on_ip_address_digest"
+ t.index ["updated_at"], name: "index_sessions_on_updated_at"
t.index ["user_id"], name: "index_sessions_on_user_id"
end
diff --git a/test/constraints/super_admin_constraint_test.rb b/test/constraints/super_admin_constraint_test.rb
new file mode 100644
index 0000000000..717c17e17b
--- /dev/null
+++ b/test/constraints/super_admin_constraint_test.rb
@@ -0,0 +1,35 @@
+require "test_helper"
+
+class SuperAdminConstraintTest < ActionDispatch::IntegrationTest
+ test "allows a super admin with an active session" do
+ sign_in users(:sure_support_staff)
+
+ get "/sidekiq"
+
+ assert_response :success
+ end
+
+ test "rejects a super admin whose session is expired" do
+ user = users(:sure_support_staff)
+ sign_in user
+ user.sessions.order(created_at: :desc).first.update_column(:updated_at, Session::INACTIVITY_TIMEOUT.ago - 1.day)
+
+ get "/sidekiq"
+
+ assert_response :not_found
+ end
+
+ test "rejects a non-super-admin with an active session" do
+ sign_in users(:family_admin)
+
+ get "/sidekiq"
+
+ assert_response :not_found
+ end
+
+ test "rejects requests without a session cookie" do
+ get "/sidekiq"
+
+ assert_response :not_found
+ end
+end
diff --git a/test/controllers/current_sessions_controller_test.rb b/test/controllers/current_sessions_controller_test.rb
index 9d498fb33c..aac4128852 100644
--- a/test/controllers/current_sessions_controller_test.rb
+++ b/test/controllers/current_sessions_controller_test.rb
@@ -6,10 +6,17 @@ class CurrentSessionsControllerTest < ActionDispatch::IntegrationTest
sign_in @user
end
- test "can update the preferred tab for any namespace" do
- put current_session_url, params: { current_session: { tab_key: "accounts_sidebar_tab", tab_value: "asset" } }
+ test "can update an allowed preferred tab" do
+ put current_session_url, params: { current_session: { tab_key: "account_sidebar_tab", tab_value: "asset" } }
assert_response :success
- session = Session.order(updated_at: :desc).first
- assert_equal "asset", session.get_preferred_tab("accounts_sidebar_tab")
+ session = @user.sessions.order(updated_at: :desc).first
+ assert_equal "asset", session.get_preferred_tab("account_sidebar_tab")
+ end
+
+ test "ignores tab keys outside the allowlist" do
+ put current_session_url, params: { current_session: { tab_key: "some_arbitrary_key", tab_value: "asset" } }
+ assert_response :success
+ session = @user.sessions.order(updated_at: :desc).first
+ assert_nil session.get_preferred_tab("some_arbitrary_key")
end
end
diff --git a/test/controllers/sessions_controller_test.rb b/test/controllers/sessions_controller_test.rb
index aed9cf0898..3a9cb75d24 100644
--- a/test/controllers/sessions_controller_test.rb
+++ b/test/controllers/sessions_controller_test.rb
@@ -1144,6 +1144,28 @@ class SessionsControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to new_session_path
end
+ test "a session inactive past the timeout is rejected and destroyed" do
+ sign_in @user
+ session_record = Session.order(created_at: :desc).first
+ session_record.update_column(:updated_at, Session::INACTIVITY_TIMEOUT.ago - 1.day)
+
+ get root_url
+ assert_redirected_to new_session_url
+ assert_not Session.exists?(session_record.id)
+ end
+
+ test "an active session is touched at most once per touch interval" do
+ sign_in @user
+ session_record = Session.order(created_at: :desc).first
+ recent_activity = 5.minutes.ago
+ session_record.update_column(:updated_at, recent_activity)
+
+ get root_url
+ assert_response :success
+ session_record.reload
+ assert_in_delta recent_activity, session_record.updated_at, 10.seconds
+ end
+
# create_session_for refuses a deactivated user, so the OIDC callback cannot
# mint one either. Nothing covered that, and the identity record survives
# deactivation, so it is worth pinning down.
diff --git a/test/jobs/session_cleaner_job_test.rb b/test/jobs/session_cleaner_job_test.rb
new file mode 100644
index 0000000000..01ddec8a4f
--- /dev/null
+++ b/test/jobs/session_cleaner_job_test.rb
@@ -0,0 +1,17 @@
+require "test_helper"
+
+class SessionCleanerJobTest < ActiveSupport::TestCase
+ test "deletes sessions inactive past the timeout and spares active ones" do
+ user = users(:family_admin)
+
+ stale = user.sessions.create!
+ stale.update_column(:updated_at, Session::INACTIVITY_TIMEOUT.ago - 1.day)
+
+ fresh = user.sessions.create!
+
+ SessionCleanerJob.perform_now
+
+ assert_not Session.exists?(stale.id)
+ assert Session.exists?(fresh.id)
+ end
+end
diff --git a/test/models/session_test.rb b/test/models/session_test.rb
new file mode 100644
index 0000000000..f19d9276c2
--- /dev/null
+++ b/test/models/session_test.rb
@@ -0,0 +1,119 @@
+require "test_helper"
+
+class SessionTest < ActiveSupport::TestCase
+ setup do
+ @user = users(:family_admin)
+ end
+
+ test "clean destroys sessions inactive past the timeout" do
+ stale = @user.sessions.create!
+ stale.update_column(:updated_at, Session::INACTIVITY_TIMEOUT.ago - 1.day)
+
+ fresh = @user.sessions.create!
+
+ deleted_count = Session.clean
+
+ assert_equal 1, deleted_count
+ assert_not Session.exists?(stale.id)
+ assert Session.exists?(fresh.id)
+ end
+
+ test "expired? is true once past the inactivity timeout" do
+ session = @user.sessions.create!
+ assert_not session.expired?
+
+ session.update_column(:updated_at, Session::INACTIVITY_TIMEOUT.ago - 1.day)
+ assert session.expired?
+ end
+
+ test "clean spares a session touched between the stale query and the row lock" do
+ stale = @user.sessions.create!
+ stale.update_column(:updated_at, Session::INACTIVITY_TIMEOUT.ago - 1.day)
+
+ # Simulate a concurrent request refreshing the session between the initial
+ # stale-session query and the row lock inside `clean`: stub `updated_at`
+ # so the recheck sees a fresh timestamp, while leaving the real
+ # `with_lock` (and its `SELECT ... FOR UPDATE` reload) in place so the
+ # locked recheck path is actually exercised.
+ Session.any_instance.stubs(:updated_at).returns(Time.current)
+
+ deleted_count = Session.clean
+
+ assert_equal 0, deleted_count
+ assert Session.exists?(stale.id)
+ end
+
+ test "clean rescues a session destroyed between the stale query and the row lock" do
+ stale = @user.sessions.create!
+ stale.update_column(:updated_at, Session::INACTIVITY_TIMEOUT.ago - 1.day)
+
+ # Simulate find_active_by_cookie destroying this session concurrently:
+ # with_lock reloads the row before yielding, so a destroy in that window
+ # surfaces as RecordNotFound instead of running the block. `clean` must
+ # rescue this and move on rather than aborting the sweep.
+ Session.any_instance.stubs(:with_lock).raises(ActiveRecord::RecordNotFound)
+
+ deleted_count = Session.clean
+
+ assert_equal 0, deleted_count
+ end
+
+ test "find_active_by_cookie returns nil for a blank cookie" do
+ assert_nil Session.find_active_by_cookie(nil)
+ assert_nil Session.find_active_by_cookie("")
+ end
+
+ test "find_active_by_cookie returns nil and cleans up an unknown session id" do
+ assert_nil Session.find_active_by_cookie(SecureRandom.uuid)
+ end
+
+ test "find_active_by_cookie returns the session when active" do
+ session = @user.sessions.create!
+ assert_equal session, Session.find_active_by_cookie(session.id)
+ end
+
+ test "find_active_by_cookie destroys and returns nil for an expired session" do
+ session = @user.sessions.create!
+ session.update_column(:updated_at, Session::INACTIVITY_TIMEOUT.ago - 1.day)
+
+ assert_nil Session.find_active_by_cookie(session.id)
+ assert_not Session.exists?(session.id)
+ end
+
+ test "find_active_by_cookie destroys and returns nil when the user is inactive" do
+ session = @user.sessions.create!
+ User.any_instance.stubs(:active?).returns(false)
+
+ assert_nil Session.find_active_by_cookie(session.id)
+ assert_not Session.exists?(session.id)
+ end
+
+ test "find_active_by_cookie refreshes updated_at once past the touch interval" do
+ session = @user.sessions.create!
+ session.update_column(:updated_at, Session::SESSION_TOUCH_INTERVAL.ago - 1.minute)
+
+ Session.find_active_by_cookie(session.id)
+
+ assert session.reload.updated_at > Session::SESSION_TOUCH_INTERVAL.ago
+ end
+
+ test "find_active_by_cookie does not touch a recently active session" do
+ session = @user.sessions.create!
+ recent_updated_at = Session::SESSION_TOUCH_INTERVAL.ago + 1.minute
+ session.update_column(:updated_at, recent_updated_at)
+
+ Session.find_active_by_cookie(session.id)
+
+ assert_in_delta recent_updated_at, session.reload.updated_at, 1.second
+ end
+
+ test "set_preferred_tab only persists allowlisted keys" do
+ session = @user.sessions.create!
+
+ session.set_preferred_tab("account_sidebar_tab", "asset")
+ assert_equal "asset", session.get_preferred_tab("account_sidebar_tab")
+
+ session.set_preferred_tab("some_arbitrary_key", "evil")
+ assert_nil session.get_preferred_tab("some_arbitrary_key")
+ end
+end
diff --git a/test/system/loan_payoff_chart_test.rb b/test/system/loan_payoff_chart_test.rb
index 7eeb93ae44..271d06014e 100644
--- a/test/system/loan_payoff_chart_test.rb
+++ b/test/system/loan_payoff_chart_test.rb
@@ -20,8 +20,11 @@ class LoanPayoffChartTest < ApplicationSystemTestCase
TODAY = Date.new(2027, 1, 15)
SERIES = %w[actual scheduled projected].freeze
+ # Sign in on the pinned date: a session signed in at the real clock would
+ # count as idle beyond Session::INACTIVITY_TIMEOUT once the tests travel to
+ # TODAY, and every visit would land on the login page.
setup do
- sign_in @user = users(:family_admin)
+ travel_to(TODAY) { sign_in @user = users(:family_admin) }
end
test "the chart paints all three lines, in the light theme and the dark" do