Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

security: session fixation, password-change session revocation, impersonation guard (#1941)

David Gild515f34e032d
diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb
index 241346815f..4d52f5fd14 100644
--- a/app/controllers/admin/users_controller.rb
+++ b/app/controllers/admin/users_controller.rb
@@ -204,6 +204,10 @@ module Admin
if @user.saved_change_to_password_digest?
SecurityAuditLog.log_password_changed!(user: @user, request: request, actor: Current.true_user)
+ # A password set by an admin is usually account recovery, so every
+ # session the user had goes (CWE-613). The acting admin keeps
+ # theirs when changing their own password here.
+ @user.sessions.where.not(id: Current.session.id).destroy_all
end
true
diff --git a/app/controllers/concerns/authentication.rb b/app/controllers/concerns/authentication.rb
index b9ee115e90..2e7431d7f6 100644
--- a/app/controllers/concerns/authentication.rb
+++ b/app/controllers/concerns/authentication.rb
@@ -14,6 +14,12 @@ module Authentication
end
end
+ # Stored by the OIDC callback for RP-initiated logout. The only Rails session
+ # keys that survive the sign-in rotation, and only when the session being
+ # minted comes from that same OIDC sign-in.
+ SESSION_KEYS_OIDC_HANDOFF = %i[id_token_hint sso_login_provider].freeze
+ private_constant :SESSION_KEYS_OIDC_HANDOFF
+
private
def authenticate_user!
if session_record = find_session_by_cookie
@@ -36,10 +42,17 @@ module Authentication
nil
end
- def create_session_for(user)
+ # Every sign-in path (password, OIDC, passkey, desktop exchange, MFA) mints
+ # its session here, so this is where the pre-auth Rails session is rotated
+ # to prevent fixation (CWE-384). Only an OIDC sign-in should ask to keep
+ # the federated-logout keys it just stored.
+ def create_session_for(user, preserve_oidc_handoff: false)
return false unless user&.persisted?
+ # with_active_lock! has already refused an inactive user by the time the
+ # block runs, so a rejected sign-in never rotates the session.
user.with_active_lock! do
+ rotate_rails_session(preserve_oidc_handoff: preserve_oidc_handoff)
session = user.sessions.create!
cookies.signed.permanent[:session_token] = { value: session.id, httponly: true }
session
@@ -48,6 +61,22 @@ module Authentication
false
end
+ # Parks the user between the first factor and MFA. Only an OIDC sign-in
+ # carries federated-logout keys into the handoff; every other path drops
+ # whatever a previous OIDC session left behind, so a stale id_token_hint
+ # can never be replayed into a locally authenticated session.
+ def begin_mfa_handoff(user, from_oidc: false)
+ SESSION_KEYS_OIDC_HANDOFF.each { |key| session.delete(key) } unless from_oidc
+ session[:mfa_user_id] = user.id
+ end
+
+ def rotate_rails_session(preserve_oidc_handoff:)
+ kept = preserve_oidc_handoff ? SESSION_KEYS_OIDC_HANDOFF.index_with { |key| session[key] }.compact_blank : {}
+
+ reset_session
+ kept.each { |key, value| session[key] = value }
+ end
+
# If a super admin is currently impersonating a user who gets deactivated
# mid-session, end the impersonation (same mechanism as
# ImpersonationSessionsController#leave) rather than logging the admin out
diff --git a/app/controllers/impersonation_sessions_controller.rb b/app/controllers/impersonation_sessions_controller.rb
index 42811cf08f..23ce162395 100644
--- a/app/controllers/impersonation_sessions_controller.rb
+++ b/app/controllers/impersonation_sessions_controller.rb
@@ -53,6 +53,10 @@ class ImpersonationSessionsController < ApplicationController
@impersonation_session =
Current.true_user.impersonated_support_sessions.find_by(id: params[:id]) ||
Current.true_user.impersonator_support_sessions.find_by(id: params[:id])
+
+ # Anyone who is neither party gets the same 404 as a missing record
+ # instead of a NoMethodError on nil.
+ raise_unauthorized! if @impersonation_session.nil?
end
def require_super_admin!
diff --git a/app/controllers/mfa_controller.rb b/app/controllers/mfa_controller.rb
index d5cb1abb36..270af8377f 100644
--- a/app/controllers/mfa_controller.rb
+++ b/app/controllers/mfa_controller.rb
@@ -192,8 +192,15 @@ class MfaController < ApplicationController
end
def complete_mfa_sign_in(user)
+ # The OIDC callback stores sso_login_provider before parking the user
+ # here; a local first factor clears it (see begin_mfa_handoff), so its
+ # presence is what tells the two flows apart.
+ came_from_oidc = session[:sso_login_provider].present?
+ # Cleared up front, as PasskeySessionsController does: a rejected user
+ # mints no session, so the rotation never runs to clear it for us.
session.delete(:mfa_user_id)
- @session = create_session_for(user)
+
+ @session = create_session_for(user, preserve_oidc_handoff: came_from_oidc)
return false unless @session
true
diff --git a/app/controllers/oidc_accounts_controller.rb b/app/controllers/oidc_accounts_controller.rb
index ca5c784308..26be6f75ce 100644
--- a/app/controllers/oidc_accounts_controller.rb
+++ b/app/controllers/oidc_accounts_controller.rb
@@ -65,7 +65,7 @@ class OidcAccountsController < ApplicationController
session.delete(:pending_oidc_auth)
if user.otp_required?
- session[:mfa_user_id] = user.id
+ begin_mfa_handoff(user)
redirect_to verify_mfa_path
else
redirect_to root_path, notice: t("sessions.openid_connect.account_linked", provider: @pending_auth["provider"])
diff --git a/app/controllers/password_resets_controller.rb b/app/controllers/password_resets_controller.rb
index 618a795966..e7266df0a3 100644
--- a/app/controllers/password_resets_controller.rb
+++ b/app/controllers/password_resets_controller.rb
@@ -59,6 +59,10 @@ class PasswordResetsController < ApplicationController
next false unless @user.update(password_params)
SecurityAuditLog.log_password_changed!(user: @user, request: request)
+ # The user is signed out on this path, so every session and every
+ # OAuth token (mobile app included) goes (CWE-613).
+ @user.sessions.destroy_all
+ @user.revoke_oauth_tokens!
true
end
diff --git a/app/controllers/passwords_controller.rb b/app/controllers/passwords_controller.rb
index 5cf689f673..e58377b45a 100644
--- a/app/controllers/passwords_controller.rb
+++ b/app/controllers/passwords_controller.rb
@@ -27,6 +27,9 @@ class PasswordsController < ApplicationController
next false unless Current.user.update(password_params)
SecurityAuditLog.log_password_changed!(user: Current.user, request: request, actor: Current.true_user)
+ # A stolen or shared cookie must not outlive a password change
+ # (CWE-613). The current session stays so the user remains signed in.
+ Current.user.sessions.where.not(id: Current.session.id).destroy_all
true
end
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb
index 8440cc8f92..e494ba8dd4 100644
--- a/app/controllers/sessions_controller.rb
+++ b/app/controllers/sessions_controller.rb
@@ -76,7 +76,7 @@ class SessionsController < ApplicationController
if user.otp_required?
log_super_admin_override_login(user)
- session[:mfa_user_id] = user.id
+ begin_mfa_handoff(user)
redirect_to verify_mfa_path
else
log_super_admin_override_login(user)
@@ -225,7 +225,7 @@ class SessionsController < ApplicationController
end
if user.otp_required?
- session[:mfa_user_id] = user.id
+ begin_mfa_handoff(user)
redirect_to verify_mfa_path
else
@session = create_session_for(user)
@@ -301,16 +301,21 @@ class SessionsController < ApplicationController
return
end
- # Store id_token and provider for RP-initiated logout
- session[:id_token_hint] = auth.credentials&.id_token if auth.credentials&.id_token
+ # Store id_token and provider for RP-initiated logout. The two move
+ # together: a callback that returns no id_token has to clear the
+ # previous one. Updating the provider while keeping a stale hint makes
+ # #destroy send the token minted by an earlier provider to this
+ # provider's end-session endpoint (CWE-200).
+ id_token = auth.credentials&.id_token
+ session[:id_token_hint] = id_token.presence
session[:sso_login_provider] = auth.provider
# MFA check: If user has MFA enabled, require verification
if user.otp_required?
- session[:mfa_user_id] = user.id
+ begin_mfa_handoff(user, from_oidc: true)
redirect_to verify_mfa_path
else
- @session = create_session_for(user)
+ @session = create_session_for(user, preserve_oidc_handoff: true)
unless @session
redirect_to new_session_path, alert: t("sessions.openid_connect.failed")
return
@@ -573,6 +578,21 @@ class SessionsController < ApplicationController
return nil unless end_session_endpoint.present?
+ # The endpoint comes out of the provider's discovery document, so the
+ # app does not choose it. Forwarding the ID token to a cleartext
+ # endpoint would put the user's claims in a plain URL (CWE-319), so
+ # fall back to a local logout instead.
+ endpoint_uri = begin
+ URI.parse(end_session_endpoint)
+ rescue URI::InvalidURIError
+ nil
+ end
+
+ unless endpoint_uri&.scheme == "https" && endpoint_uri.host.present?
+ Rails.logger.warn("[SSO] Ignoring non-HTTPS end_session_endpoint for #{oidc_identity.provider}")
+ return nil
+ end
+
# Build the logout URL with post_logout_redirect_uri
post_logout_redirect = "#{request.base_url}/auth/logout/callback"
params = {
diff --git a/app/jobs/demo_family_refresh_job.rb b/app/jobs/demo_family_refresh_job.rb
index e5fef2f220..946c635fe5 100644
--- a/app/jobs/demo_family_refresh_job.rb
+++ b/app/jobs/demo_family_refresh_job.rb
@@ -69,8 +69,7 @@ class DemoFamilyRefreshJob < ApplicationJob
SsoIdentityBlock.block_all!(user.oidc_identities, identity_label: user.email)
user.sessions.delete_all
user.api_keys.active.visible.update_all(revoked_at: Time.current)
- Doorkeeper::AccessToken.where(resource_owner_id: user.id, revoked_at: nil).update_all(revoked_at: Time.current)
- Doorkeeper::AccessGrant.where(resource_owner_id: user.id, revoked_at: nil).update_all(revoked_at: Time.current)
+ user.revoke_oauth_tokens!
user.update_columns(active: false)
end
end
diff --git a/app/models/user.rb b/app/models/user.rb
index 85181fdba8..fbd0098da6 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -382,9 +382,7 @@ class User < ApplicationRecord
# provider+uid) are not gated on #active?, so they must be torn down here for
# revocation to be immediate; the async purge would otherwise leave a window.
def revoke_all_credentials!
- Doorkeeper::AccessToken
- .where(resource_owner_id: id, revoked_at: nil)
- .update_all(revoked_at: Time.current)
+ revoke_oauth_tokens!
sessions.destroy_all
api_keys.destroy_all
mobile_devices.destroy_all
@@ -513,6 +511,18 @@ class User < ApplicationRecord
Array(provider.public_send(item_association.name)) if item_association
end
+ # Revokes every Doorkeeper access token issued to this user (mobile app and
+ # third-party OAuth clients; a revoked token's refresh token is refused too)
+ # and every authorization grant not yet exchanged for one. Returns the
+ # number of tokens and grants revoked.
+ def revoke_oauth_tokens!
+ now = Time.current
+ [
+ Doorkeeper::AccessToken.where(resource_owner_id: id, revoked_at: nil).update_all(revoked_at: now),
+ Doorkeeper::AccessGrant.where(resource_owner_id: id, revoked_at: nil).update_all(revoked_at: now)
+ ]
+ end
+
# Revokes mobile/third-party API access alongside the web-session
# invalidation above. Without this, a deactivated user's existing
# Doorkeeper tokens and API keys stay valid on the wire — currently
@@ -524,8 +534,7 @@ class User < ApplicationRecord
# before deactivation could otherwise be exchanged for a fresh token
# afterward.
def revoke_all_access_tokens
- tokens_revoked = Doorkeeper::AccessToken.where(resource_owner_id: id, revoked_at: nil).update_all(revoked_at: Time.current)
- grants_revoked = Doorkeeper::AccessGrant.where(resource_owner_id: id, revoked_at: nil).update_all(revoked_at: Time.current)
+ tokens_revoked, grants_revoked = revoke_oauth_tokens!
keys_revoked = api_keys.active.visible.update_all(revoked_at: Time.current)
if tokens_revoked > 0 || grants_revoked > 0 || keys_revoked > 0
diff --git a/test/controllers/admin/users_controller_test.rb b/test/controllers/admin/users_controller_test.rb
index d016ac9196..240901e578 100644
--- a/test/controllers/admin/users_controller_test.rb
+++ b/test/controllers/admin/users_controller_test.rb
@@ -326,6 +326,38 @@ class Admin::UsersControllerTest < ActionDispatch::IntegrationTest
assert target.authenticate(new_password), "User should authenticate with the new password"
end
+ test "setting a user's password revokes every session that user has" do
+ target = users(:family_member)
+ sessions = 2.times.map { target.sessions.create! }
+
+ patch admin_user_url(target), params: { user: { role: target.role, password: "Secure1!pass" } }
+
+ assert_redirected_to admin_users_url
+ sessions.each { |s| assert_not Session.exists?(s.id), "a session must not outlive an admin password reset" }
+ end
+
+ test "a super admin setting their own password keeps their current session" do
+ admin = users(:sure_support_staff)
+ current = admin.sessions.order(:created_at).last
+ other = admin.sessions.create!
+
+ patch admin_user_url(admin), params: { user: { role: admin.role, password: "Secure1!pass" } }
+
+ assert_redirected_to admin_users_url
+ assert Session.exists?(current.id)
+ assert_not Session.exists?(other.id)
+ end
+
+ test "a role-only change leaves the user's sessions alone" do
+ target = users(:family_member)
+ session_record = target.sessions.create!
+
+ patch admin_user_url(target), params: { user: { role: "admin", password: "" } }
+
+ assert_redirected_to admin_users_url
+ assert Session.exists?(session_record.id)
+ end
+
test "update logs an audit entry with the admin as actor when setting a new password" do
target = users(:family_member)
@@ -348,6 +380,7 @@ class Admin::UsersControllerTest < ActionDispatch::IntegrationTest
test "update rolls back the password change when the audit log write fails" do
target = users(:family_member)
original_digest = target.password_digest
+ session_record = target.sessions.create!
SecurityAuditLog.stubs(:log_password_changed!).raises(ActiveRecord::RecordInvalid.new(SecurityAuditLog.new))
@@ -360,6 +393,7 @@ class Admin::UsersControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to admin_users_url
assert_equal original_digest, target.reload.password_digest
+ assert Session.exists?(session_record.id), "a rolled-back change must not revoke sessions"
end
test "update does not log an audit entry when the password is unchanged" do
diff --git a/test/controllers/impersonation_sessions_controller_test.rb b/test/controllers/impersonation_sessions_controller_test.rb
index 2f73ce58e0..d20f9094f1 100644
--- a/test/controllers/impersonation_sessions_controller_test.rb
+++ b/test/controllers/impersonation_sessions_controller_test.rb
@@ -143,4 +143,14 @@ class ImpersonationSessionsControllerTest < ActionDispatch::IntegrationTest
assert_equal "rejected", impersonator_session.reload.status
assert_redirected_to root_path
end
+
+ test "a user who is neither party gets a 404 on complete and the session stays open" do
+ sign_in users(:family_admin)
+ impersonator_session = impersonation_sessions(:in_progress)
+
+ put complete_impersonation_session_path(impersonator_session)
+
+ assert_response :not_found
+ assert_equal "in_progress", impersonator_session.reload.status
+ end
end
diff --git a/test/controllers/password_resets_controller_test.rb b/test/controllers/password_resets_controller_test.rb
index 43d51ae68b..1dfbed0b3c 100644
--- a/test/controllers/password_resets_controller_test.rb
+++ b/test/controllers/password_resets_controller_test.rb
@@ -140,4 +140,45 @@ class PasswordResetsControllerTest < ActionDispatch::IntegrationTest
sso_user.reload
assert_nil sso_user.password_digest, "SSO-only user should still have nil password_digest"
end
+
+ test "update signs the user out everywhere" do
+ sign_in @user
+ @user.sessions.create!
+ assert_operator @user.sessions.count, :>=, 2
+
+ patch password_reset_path(token: @user.generate_token_for(:password_reset)),
+ params: { user: { password: "NewPassword123!", password_confirmation: "NewPassword123!" } }
+
+ assert_redirected_to new_session_path
+ assert_equal 0, @user.sessions.reload.count
+ end
+
+ test "update revokes the user's OAuth tokens and grants, so a refresh token stops working" do
+ oauth_app = Doorkeeper::Application.create!(name: "Sure Mobile", redirect_uri: "https://client.example.com/callback", scopes: "read_write")
+ access_token = Doorkeeper::AccessToken.create!(application: oauth_app, resource_owner_id: @user.id, expires_in: 2.hours, scopes: "read_write", use_refresh_token: true)
+ refresh_token = access_token.plaintext_refresh_token
+ grant = Doorkeeper::AccessGrant.create!(application: oauth_app, resource_owner_id: @user.id, expires_in: 10.minutes, redirect_uri: oauth_app.redirect_uri, scopes: "read_write")
+
+ patch password_reset_path(token: @user.generate_token_for(:password_reset)),
+ params: { user: { password: "NewPassword123!", password_confirmation: "NewPassword123!" } }
+ assert_redirected_to new_session_path
+
+ assert access_token.reload.revoked?, "the access token must not outlive a password reset"
+ assert grant.reload.revoked?, "an unexchanged grant must not be redeemable after a password reset"
+
+ post "/oauth/token", params: { grant_type: "refresh_token", refresh_token: refresh_token, client_id: oauth_app.uid, client_secret: oauth_app.secret }
+ assert_response :bad_request
+ assert_equal "invalid_grant", JSON.parse(response.body)["error"]
+ end
+
+ test "a rejected reset leaves the user's OAuth tokens alone" do
+ oauth_app = Doorkeeper::Application.create!(name: "Sure Mobile", redirect_uri: "https://client.example.com/callback", scopes: "read_write")
+ access_token = Doorkeeper::AccessToken.create!(application: oauth_app, resource_owner_id: @user.id, expires_in: 2.hours, scopes: "read_write")
+
+ patch password_reset_path(token: @user.generate_token_for(:password_reset)),
+ params: { user: { password: "NewPassword123!", password_confirmation: "Mismatch123!" } }
+
+ assert_response :unprocessable_entity
+ assert_not access_token.reload.revoked?
+ end
end
diff --git a/test/controllers/passwords_controller_test.rb b/test/controllers/passwords_controller_test.rb
index 7284b5f283..b14236ed12 100644
--- a/test/controllers/passwords_controller_test.rb
+++ b/test/controllers/passwords_controller_test.rb
@@ -3,7 +3,9 @@ require "test_helper"
class PasswordsControllerTest < ActionDispatch::IntegrationTest
setup do
@user = users(:family_admin)
+ @other_session = @user.sessions.create!
sign_in @user
+ @current_session = Current.session
end
test "edit" do
@@ -21,6 +23,14 @@ class PasswordsControllerTest < ActionDispatch::IntegrationTest
assert SecurityAuditLog.exists?(user: @user, event_type: "password_changed")
end
+ test "changing the password revokes every other session and keeps the current one" do
+ patch password_path, params: { user: { password_challenge: user_password_test, password: "newtestpassword817983172", password_confirmation: "newtestpassword817983172" } }
+
+ assert_redirected_to root_path
+ assert_not Session.exists?(@other_session.id)
+ assert Session.exists?(@current_session.id)
+ end
+
test "update rejects a wrong current password" do
assert_password_unchanged do
patch password_path, params: { user: { password_challenge: "wrongpassword123", password: "newtestpassword817983172", password_confirmation: "newtestpassword817983172" } }
@@ -79,6 +89,7 @@ class PasswordsControllerTest < ActionDispatch::IntegrationTest
assert_response :unprocessable_entity
assert_equal original_digest, @user.reload.password_digest
+ assert Session.exists?(@other_session.id), "a rolled-back change must not revoke sessions"
end
private
@@ -92,5 +103,6 @@ class PasswordsControllerTest < ActionDispatch::IntegrationTest
assert_response :unprocessable_entity
assert_equal original_digest, @user.reload.password_digest
+ assert Session.exists?(@other_session.id), "a rejected change must not revoke sessions"
end
end
diff --git a/test/controllers/registrations_controller_test.rb b/test/controllers/registrations_controller_test.rb
index 440ad7553a..9ab4c87f32 100644
--- a/test/controllers/registrations_controller_test.rb
+++ b/test/controllers/registrations_controller_test.rb
@@ -14,6 +14,20 @@ class RegistrationsControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to root_url
end
+ # Signing up is a privilege change like signing in, and goes through the
+ # same create_session_for, so the pre-auth session must not survive it.
+ test "create discards pre-auth session state" do
+ get new_registration_url(return_to: "/transactions")
+ assert_equal "/transactions", session[:return_to], "the sentinel must really be in the pre-auth session"
+
+ post registration_url, params: { user: {
+ email: "[email protected]",
+ password: "Password1!" } }
+
+ assert_redirected_to root_url
+ assert_nil session[:return_to]
+ end
+
test "create rolls back registration when session creation fails" do
RegistrationsController.any_instance.stubs(:create_session_for).returns(false)
diff --git a/test/controllers/sessions_controller_test.rb b/test/controllers/sessions_controller_test.rb
index 97d94e73c6..be8b44620e 100644
--- a/test/controllers/sessions_controller_test.rb
+++ b/test/controllers/sessions_controller_test.rb
@@ -42,7 +42,21 @@ class SessionsControllerTest < ActionDispatch::IntegrationTest
end
end
- def setup_omniauth_mock(provider:, uid:, email:, name:, first_name: nil, last_name: nil)
+ def stub_provider(name)
+ ProviderLoader.stubs(:load_providers).returns([
+ { name: name, strategy: "openid_connect", issuer: "https://idp.example", label: "IdP" }
+ ])
+ end
+
+ def stub_discovery(end_session_endpoint)
+ body = { "end_session_endpoint" => end_session_endpoint }.to_json
+ response = OpenStruct.new(success?: true, body: body)
+ connection = mock
+ connection.stubs(:get).returns(response)
+ Faraday.stubs(:new).returns(connection)
+ end
+
+ def setup_omniauth_mock(provider:, uid:, email:, name:, first_name: nil, last_name: nil, id_token: nil)
OmniAuth.config.mock_auth[:openid_connect] = OmniAuth::AuthHash.new({
provider: provider,
uid: uid,
@@ -51,7 +65,8 @@ class SessionsControllerTest < ActionDispatch::IntegrationTest
name: name,
first_name: first_name,
last_name: last_name
- }.compact
+ }.compact,
+ credentials: id_token ? { id_token: id_token } : {}
})
end
@@ -1234,4 +1249,163 @@ class SessionsControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to new_session_path
assert_not Session.exists?(user_id: @user.id)
end
+
+ # `?return_to=` is written into the session by StoreLocation on any request,
+ # including unauthenticated ones, so it is a pre-auth value a real browser
+ # can actually carry into the sign-in POST. Writing to `session` directly
+ # from an integration test does NOT reach the next request, so a sentinel
+ # seeded that way would make these assertions vacuous.
+ test "signing in discards pre-auth session state so a fixated session cannot survive" do
+ get new_session_url(return_to: "/transactions")
+ assert_equal "/transactions", session[:return_to], "the sentinel must really be in the pre-auth session"
+
+ sign_in @user
+
+ assert_nil session[:return_to], "pre-auth session state must not survive sign-in"
+ end
+
+ # Both flags come from the framework: httponly is set where the cookie is
+ # written, and samesite from action_dispatch.cookies_same_site_protection,
+ # which also gets a `; secure` from ActionDispatch::SSL wherever force_ssl
+ # is on. Nothing in this app sets them per-cookie, so this guards against a
+ # config change quietly dropping them rather than against a regression here.
+ test "the session cookie is HttpOnly and SameSite=Lax" do
+ sign_in @user
+
+ # Set-Cookie is an array and Rails' own _sure_session cookie carries the
+ # same flags, so a regex over the joined header matches across cookie
+ # boundaries and passes even when session_token has neither. Isolate the
+ # one cookie under test.
+ session_cookie = Array(response.headers["Set-Cookie"])
+ .flat_map { |header| header.to_s.split("\n") }
+ .find { |cookie| cookie.start_with?("session_token=") }
+
+ assert session_cookie, "the sign-in response must set a session_token cookie"
+ assert_match(/;\s*httponly/i, session_cookie)
+ assert_match(/;\s*samesite=lax/i, session_cookie)
+ end
+
+ test "OIDC logout hints survive the session rotation, also after MFA" do
+ @user.setup_mfa!
+ @user.enable_mfa!
+ @user.sessions.destroy_all
+ oidc_identity = oidc_identities(:bob_google)
+ setup_omniauth_mock(
+ provider: oidc_identity.provider,
+ uid: oidc_identity.uid,
+ email: @user.email,
+ name: "Bob Dylan",
+ id_token: "id-token-for-rp-logout"
+ )
+
+ get "/auth/openid_connect/callback"
+ assert_redirected_to verify_mfa_path
+
+ totp = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances")
+ post verify_mfa_path, params: { code: totp.now }
+ assert_redirected_to root_path
+
+ assert_equal "id-token-for-rp-logout", session[:id_token_hint]
+ assert_equal oidc_identity.provider, session[:sso_login_provider]
+ assert_nil session[:mfa_user_id]
+ end
+
+ test "signing in with a second provider does not keep the first provider's logout token" do
+ @user.sessions.destroy_all
+ first = oidc_identities(:bob_google)
+ second = @user.oidc_identities.create!(provider: "other_idp", uid: "other-idp-uid-1")
+
+ setup_omniauth_mock(
+ provider: first.provider,
+ uid: first.uid,
+ email: @user.email,
+ name: "Bob Dylan",
+ id_token: "id-token-minted-by-the-first-provider"
+ )
+ get "/auth/openid_connect/callback"
+ assert_equal "id-token-minted-by-the-first-provider", session[:id_token_hint]
+
+ # The second provider issues no id_token. Carrying the first one over would
+ # hand its token to the second provider's end-session endpoint at logout.
+ setup_omniauth_mock(
+ provider: second.provider,
+ uid: second.uid,
+ email: @user.email,
+ name: "Bob Dylan"
+ )
+ get "/auth/openid_connect/callback"
+
+ assert_equal second.provider, session[:sso_login_provider]
+ assert_nil session[:id_token_hint], "a stale hint must not be paired with a new provider"
+ end
+
+ # Seeding id_token_hint by assigning to `session` from the test would never
+ # reach the app. The OIDC callback is the only thing that really sets it, so
+ # this drives the real abandoned-OIDC flow: the user starts an SSO sign-in,
+ # is parked at the MFA prompt, gives up and signs in with their password.
+ test "a local sign-in does not inherit OIDC logout hints left by an abandoned SSO attempt" do
+ @user.setup_mfa!
+ @user.enable_mfa!
+ @user.sessions.destroy_all
+ oidc_identity = oidc_identities(:bob_google)
+ setup_omniauth_mock(
+ provider: oidc_identity.provider,
+ uid: oidc_identity.uid,
+ email: @user.email,
+ name: "Bob Dylan",
+ id_token: "id-token-from-the-abandoned-attempt"
+ )
+
+ get "/auth/openid_connect/callback"
+ assert_redirected_to verify_mfa_path
+ assert_equal "id-token-from-the-abandoned-attempt", session[:id_token_hint],
+ "the OIDC attempt must really leave its hints behind for this to test anything"
+
+ post sessions_path, params: { email: @user.email, password: user_password_test }
+ assert_redirected_to verify_mfa_path
+
+ totp = ROTP::TOTP.new(@user.otp_secret, issuer: "Sure Finances")
+ post verify_mfa_path, params: { code: totp.now }
+ assert_redirected_to root_path
+
+ assert_nil session[:id_token_hint], "a local sign-in must not inherit SSO logout hints"
+ assert_nil session[:sso_login_provider]
+ end
+
+ # The end_session_endpoint comes out of the provider's discovery document, so
+ # the app does not choose it. Forwarding the ID token to an http:// endpoint
+ # would put the user's claims in a cleartext URL.
+ test "federated logout is skipped when the provider advertises a cleartext endpoint" do
+ oidc_identity = oidc_identities(:bob_google)
+ stub_provider(oidc_identity.provider)
+ stub_discovery("http://idp.example/logout")
+
+ setup_omniauth_mock(
+ provider: oidc_identity.provider, uid: oidc_identity.uid,
+ email: @user.email, name: "Bob Dylan", id_token: "an-id-token"
+ )
+ get "/auth/openid_connect/callback"
+
+ delete session_path(Session.order(:created_at).last)
+
+ assert_no_match(/an-id-token/, response.location.to_s, "the token must not travel over http")
+ assert_no_match(%r{^http://idp\.example}, response.location.to_s)
+ end
+
+ test "federated logout still runs for an https endpoint" do
+ oidc_identity = oidc_identities(:bob_google)
+ stub_provider(oidc_identity.provider)
+ stub_discovery("https://idp.example/logout")
+
+ setup_omniauth_mock(
+ provider: oidc_identity.provider, uid: oidc_identity.uid,
+ email: @user.email, name: "Bob Dylan", id_token: "an-id-token"
+ )
+ get "/auth/openid_connect/callback"
+
+ delete session_path(Session.order(:created_at).last)
+
+ assert_match(%r{^https://idp\.example/logout}, response.location.to_s)
+ assert_match(/an-id-token/, response.location.to_s)
+ end
end