Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Support OIDC configuration changes without restart, tighten identity validation (#2504)

Orange🍊e0d9c9c1635f
diff --git a/app/controllers/api/v1/auth_controller.rb b/app/controllers/api/v1/auth_controller.rb
index 88f3605426..929b8c383f 100644
--- a/app/controllers/api/v1/auth_controller.rb
+++ b/app/controllers/api/v1/auth_controller.rb
@@ -11,6 +11,8 @@ module Api
before_action :check_api_key_rate_limit, only: :enable_ai
before_action :log_api_access, only: :enable_ai
rescue_from SsoIdentityBlock::BlockedIdentity, with: :render_removed_identity
+ rescue_from OidcIdentity::ProviderNotConfigured, OidcIdentity::IssuerMismatch,
+ with: :render_invalid_sso_linking_code
def signup
# RegistrationsController refuses to register a user while the instance
@@ -156,7 +158,7 @@ module Api
# provider config also carries client secrets. Labels fall back the same
# way as the web sign-in page.
def sso_providers
- providers = Rails.configuration.x.auth.sso_providers.map do |provider|
+ providers = AuthConfig.sso_providers.map do |provider|
name = provider[:name].to_s
strategy = provider[:strategy].to_s
id = provider[:id].to_s
@@ -174,6 +176,7 @@ module Api
render json: { providers: providers }
end
+ # Redeem a single-use mobile SSO code for its cached credentials and user payload.
def sso_exchange
code = sso_exchange_params
@@ -214,6 +217,7 @@ module Api
}
end
+ # Link trusted pending SSO authentication to a password-verified local account.
def sso_link
linking_code = params[:linking_code]
cached = validate_linking_code(linking_code)
@@ -279,6 +283,7 @@ module Api
render json: token_response.merge(user: mobile_user_payload(user))
end
+ # Create an SSO account only after revalidating the deferred provider and issuer.
def sso_create_account
linking_code = params[:linking_code]
cached = validate_linking_code(linking_code)
@@ -314,7 +319,7 @@ module Api
# New family creators must be able to administer their own family.
# Lower provider defaults are promoted to admin by role_for_new_family_creator,
# while intentional super_admin defaults remain supported.
- provider_config = Rails.configuration.x.auth.sso_providers&.find { |p| p[:name] == cached[:provider] }
+ provider_config = AuthConfig.sso_providers&.find { |p| p[:name] == cached[:provider] }
provider_default_role = provider_config&.dig(:settings, :default_role)
end
@@ -494,10 +499,12 @@ module Api
params.require(:device).permit(:device_id, :device_name, :device_type, :os_version, :app_version)
end
+ # Require the mobile authorization code submitted for credential exchange.
def sso_exchange_params
params.require(:code)
end
+ # Serialize the user fields returned with mobile authentication credentials.
def mobile_user_payload(user)
{
id: user.id,
@@ -519,6 +526,7 @@ module Api
false
end
+ # Reconstruct the cached provider identity without losing its authenticated issuer.
def build_omniauth_hash(cached)
OpenStruct.new(
provider: cached[:provider],
@@ -528,6 +536,16 @@ module Api
)
end
+ # Return the API error for deferred SSO authentication that is no longer valid.
+ def render_invalid_sso_linking_code
+ if params[:linking_code].present?
+ Rails.cache.delete("mobile_sso_link:#{params[:linking_code]}")
+ end
+
+ render json: { error: "SSO authentication is no longer valid" }, status: :forbidden
+ end
+
+ # Load single-use deferred authentication and reject stale provider trust.
def validate_linking_code(linking_code)
if linking_code.blank?
render json: { error: "Linking code is required" }, status: :bad_request
@@ -548,9 +566,14 @@ module Api
return nil
end
+ provider_config = OidcIdentity.provider_config_for(cached[:provider])
+ raise OidcIdentity::ProviderNotConfigured if provider_config.blank?
+ OidcIdentity.verified_issuer_for!(build_omniauth_hash(cached), provider_config)
+
cached
end
+ # Reject mobile authentication for an identity removed by an administrator.
def render_removed_identity
render json: { error: "SSO identity was removed by an administrator" }, status: :forbidden
end
diff --git a/app/controllers/oidc_accounts_controller.rb b/app/controllers/oidc_accounts_controller.rb
index e1d97e9a78..5dae3d3075 100644
--- a/app/controllers/oidc_accounts_controller.rb
+++ b/app/controllers/oidc_accounts_controller.rb
@@ -3,8 +3,11 @@ class OidcAccountsController < ApplicationController
before_action :set_pending_auth, only: [ :link, :create_link, :new_user, :create_user ]
before_action :reject_removed_identity, only: [ :link, :create_link, :new_user, :create_user ]
rescue_from SsoIdentityBlock::BlockedIdentity, with: :reject_removed_identity_after_lock
+ rescue_from OidcIdentity::ProviderNotConfigured, OidcIdentity::IssuerMismatch, OidcIdentity::LegacyIdentityRebindRejected,
+ with: :reject_invalid_pending_auth
layout "auth"
+ # Offer linking only while the pending identity remains trusted.
def link
# Check if there's pending OIDC auth in session
if @pending_auth.nil?
@@ -13,7 +16,8 @@ class OidcAccountsController < ApplicationController
end
@email = @pending_auth["email"]
- @user_exists = User.find_by_email_with_legacy_fallback(@email).present? if @email.present?
+ @legacy_oidc_relink = session[:pending_oidc_legacy_relink].present?
+ @user_exists = @legacy_oidc_relink || (@email.present? && User.find_by_email_with_legacy_fallback(@email).present?)
# Check for a pending invitation for this email
@pending_invitation = Invitation.pending.find_by(email: @email) if @email.present?
@@ -23,6 +27,7 @@ class OidcAccountsController < ApplicationController
@allow_account_creation = @pending_invitation.present? || (!AuthConfig.jit_link_only? && AuthConfig.allowed_oidc_domain?(@email))
end
+ # Link to a password-verified account while enforcing current issuer continuity.
def create_link
if @pending_auth.nil?
redirect_to new_session_path, alert: t(".no_pending_oidc")
@@ -34,10 +39,12 @@ class OidcAccountsController < ApplicationController
if user&.active?
linked = user.transaction do
- OidcIdentity.create_from_omniauth(
- build_auth_hash(@pending_auth),
- user
- )
+ auth = build_auth_hash(@pending_auth)
+ if session[:pending_oidc_legacy_relink]
+ OidcIdentity.rebind_legacy_issuer_from_omniauth!(auth, user)
+ else
+ OidcIdentity.create_from_omniauth(auth, user)
+ end
SsoAuditLog.log_link!(
user: user,
@@ -60,6 +67,7 @@ class OidcAccountsController < ApplicationController
# Clear pending auth from session
session.delete(:pending_oidc_auth)
+ session.delete(:pending_oidc_legacy_relink)
if user.otp_required?
begin_mfa_handoff(user, password_fingerprint: user.password_fingerprint)
@@ -69,12 +77,14 @@ class OidcAccountsController < ApplicationController
end
else
@email = params[:email]
- @user_exists = User.find_by_email_with_legacy_fallback(@email).present? if @email.present?
+ @legacy_oidc_relink = session[:pending_oidc_legacy_relink].present?
+ @user_exists = @legacy_oidc_relink || (@email.present? && User.find_by_email_with_legacy_fallback(@email).present?)
flash.now[:alert] = "Invalid email or password"
render :link, status: :unprocessable_entity
end
end
+ # Offer account creation only for a currently trusted pending identity.
def new_user
# Check if there's pending OIDC auth in session
if @pending_auth.nil?
@@ -82,6 +92,11 @@ class OidcAccountsController < ApplicationController
return
end
+ if session[:pending_oidc_legacy_relink]
+ redirect_to link_oidc_account_path
+ return
+ end
+
# Pre-fill user details from OIDC provider
@user = User.new(
email: @pending_auth["email"],
@@ -90,12 +105,18 @@ class OidcAccountsController < ApplicationController
)
end
+ # Create the account and OIDC identity using revalidated provider settings.
def create_user
if @pending_auth.nil?
redirect_to new_session_path, alert: t(".no_pending_oidc")
return
end
+ if session[:pending_oidc_legacy_relink]
+ redirect_to link_oidc_account_path
+ return
+ end
+
email = @pending_auth["email"]
# Check for a pending invitation for this email
@@ -133,7 +154,7 @@ class OidcAccountsController < ApplicationController
# New family creators must be able to administer their own family.
# Lower provider defaults are promoted to admin by role_for_new_family_creator,
# while intentional super_admin defaults remain supported.
- provider_config = Rails.configuration.x.auth.sso_providers&.find { |p| p[:name] == @pending_auth["provider"] }
+ provider_config = AuthConfig.sso_providers&.find { |p| p[:name] == @pending_auth["provider"] }
provider_default_role = provider_config&.dig(:settings, :default_role)
end
@@ -202,8 +223,10 @@ class OidcAccountsController < ApplicationController
private
+ # Reject an identity removed while the linking flow waited for its lock.
def reject_removed_identity_after_lock
session.delete(:pending_oidc_auth)
+ session.delete(:pending_oidc_legacy_relink)
redirect_to new_session_path, alert: t("sessions.openid_connect.failed")
end
@@ -215,9 +238,26 @@ class OidcAccountsController < ApplicationController
def reject_removed_identity
pending_auth = @pending_auth
return unless pending_auth.present?
- return unless SsoIdentityBlock.blocked?(provider: pending_auth["provider"], uid: pending_auth["uid"])
+ if SsoIdentityBlock.blocked?(provider: pending_auth["provider"], uid: pending_auth["uid"])
+ session.delete(:pending_oidc_auth)
+ session.delete(:pending_oidc_legacy_relink)
+ redirect_to new_session_path, alert: t("sessions.openid_connect.failed")
+ return
+ end
+
+ config = OidcIdentity.provider_config_for(pending_auth["provider"])
+ unless config
+ session.delete(:pending_oidc_auth)
+ session.delete(:pending_oidc_legacy_relink)
+ redirect_to new_session_path, alert: t("sessions.openid_connect.failed")
+ end
+ end
+
+ # Reject deferred authentication if its provider or issuer is no longer trusted.
+ def reject_invalid_pending_auth
session.delete(:pending_oidc_auth)
+ session.delete(:pending_oidc_legacy_relink)
redirect_to new_session_path, alert: t("sessions.openid_connect.failed")
end
@@ -226,7 +266,8 @@ class OidcAccountsController < ApplicationController
OpenStruct.new(
provider: pending_auth["provider"],
uid: pending_auth["uid"],
- info: OpenStruct.new(pending_auth.slice("email", "name", "first_name", "last_name"))
+ info: OpenStruct.new(pending_auth.slice("email", "name", "first_name", "last_name")),
+ extra: OpenStruct.new(raw_info: OpenStruct.new(iss: pending_auth["issuer"]))
)
end
end
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb
index d87757433f..7a39aef9ab 100644
--- a/app/controllers/sessions_controller.rb
+++ b/app/controllers/sessions_controller.rb
@@ -132,9 +132,10 @@ class SessionsController < ApplicationController
redirect_to new_session_path, notice: t(".logout_successful")
end
+ # Start the mobile OIDC flow using the currently enabled provider route.
def mobile_sso_start
provider = params[:provider].to_s
- configured_providers = Rails.configuration.x.auth.sso_providers.map { |p| p[:name].to_s }
+ configured_providers = AuthConfig.sso_providers.map { |p| p[:name].to_s }
unless configured_providers.include?(provider)
mobile_sso_redirect(error: "invalid_provider", message: "SSO provider not configured")
@@ -165,7 +166,7 @@ class SessionsController < ApplicationController
# like the mobile flow (reusing its auto-submitting form).
def desktop_sso_start
provider = params[:provider].to_s
- configured_providers = Rails.configuration.x.auth.sso_providers.map { |p| p[:name].to_s }
+ configured_providers = AuthConfig.sso_providers.map { |p| p[:name].to_s }
unless configured_providers.include?(provider)
redirect_to new_session_path, alert: t("sessions.openid_connect.failed")
@@ -237,6 +238,7 @@ class SessionsController < ApplicationController
end
end
+ # Validate live provider and issuer settings before completing web or mobile login.
def openid_connect
auth = request.env["omniauth.auth"]
@@ -247,7 +249,20 @@ class SessionsController < ApplicationController
end
if SsoIdentityBlock.blocked?(provider: auth.provider, uid: auth.uid)
- reject_removed_sso_identity(auth.provider)
+ reject_sso_login(auth.provider, reason: "removed_identity")
+ return
+ end
+
+ provider_config = OidcIdentity.provider_config_for(auth.provider)
+ unless provider_config
+ reject_sso_login(auth.provider, reason: "provider_not_configured")
+ return
+ end
+
+ begin
+ verified_issuer = OidcIdentity.verified_issuer_for!(auth, provider_config)
+ rescue OidcIdentity::IssuerMismatch
+ reject_sso_login(auth.provider, reason: "issuer_mismatch")
return
end
@@ -255,6 +270,16 @@ class SessionsController < ApplicationController
oidc_identity = OidcIdentity.find_by(provider: auth.provider, uid: auth.uid)
if oidc_identity
+ if OidcIdentity.oidc_provider_config?(provider_config, auth.provider) && oidc_identity.issuer.blank?
+ require_legacy_oidc_relink(auth, verified_issuer)
+ return
+ end
+
+ unless oidc_identity.issuer_matches_config?(provider_config)
+ reject_sso_login(auth.provider, reason: "issuer_mismatch")
+ return
+ end
+
# Existing OIDC identity found - authenticate the user
user = oidc_identity.user
@@ -326,7 +351,7 @@ class SessionsController < ApplicationController
# Mobile SSO with no linked identity - cache pending auth and redirect
# back to the app with a linking code so the user can link or create an account
if session[:mobile_sso].present?
- handle_mobile_sso_onboarding(auth)
+ handle_mobile_sso_onboarding(auth, issuer: verified_issuer)
return
end
@@ -339,20 +364,15 @@ class SessionsController < ApplicationController
return
end
- # No existing OIDC identity - need to link to account
- # Store auth data in session and redirect to linking page
- session[:pending_oidc_auth] = {
- provider: auth.provider,
- uid: auth.uid,
- email: auth.info&.email,
- name: auth.info&.name,
- first_name: auth.info&.first_name,
- last_name: auth.info&.last_name
- }
+ # No existing OIDC identity - need to link to account.
+ # Preserve the verified issuer across the local-password step.
+ session[:pending_oidc_auth] = pending_oidc_auth(auth, verified_issuer)
+ session.delete(:pending_oidc_legacy_relink)
redirect_to link_oidc_account_path
end
end
+ # Normalize provider failures and return to the matching web or mobile login flow.
def failure
# Sanitize reason to known values only
known_reasons = %w[sso_provider_unavailable sso_invalid_response sso_failed]
@@ -393,11 +413,47 @@ class SessionsController < ApplicationController
end
private
- def reject_removed_sso_identity(provider)
+ # Store the provider identity and trusted issuer for deferred account linking.
+ def pending_oidc_auth(auth, issuer)
+ {
+ "provider" => auth.provider,
+ "uid" => auth.uid,
+ "email" => auth.info&.email,
+ "name" => auth.info&.name,
+ "first_name" => auth.info&.first_name,
+ "last_name" => auth.info&.last_name,
+ "issuer" => issuer
+ }
+ end
+
+ # Require explicit relinking when a legacy identity has no trusted issuer.
+ def require_legacy_oidc_relink(auth, issuer)
+ SsoAuditLog.log_login_failed!(
+ provider: auth.provider,
+ request: request,
+ reason: "issuer_unverified"
+ )
+
+ if session.delete(:mobile_sso).present?
+ mobile_sso_redirect(
+ error: "issuer_relink_required",
+ message: t("sessions.openid_connect.legacy_issuer_relink_required")
+ )
+ elsif session.delete(:desktop_sso).present?
+ redirect_to "sure://sso/callback?error=issuer_relink_required", allow_other_host: true
+ else
+ session[:pending_oidc_auth] = pending_oidc_auth(auth, issuer)
+ session[:pending_oidc_legacy_relink] = true
+ redirect_to link_oidc_account_path, alert: t("sessions.openid_connect.legacy_issuer_relink_required")
+ end
+ end
+
+ # Reject the login and record its provider-specific diagnostic reason.
+ def reject_sso_login(provider, reason:)
SsoAuditLog.log_login_failed!(
provider: provider,
request: request,
- reason: "removed_identity"
+ reason: reason
)
if session.delete(:mobile_sso).present?
@@ -409,6 +465,7 @@ class SessionsController < ApplicationController
end
end
+ # Issue mobile credentials behind a short-lived, single-use exchange code.
def handle_mobile_sso_callback(user)
# openid_connect already checked user.active? before dispatching here,
# but record_authentication!/sync_user_attributes!/audit logging run in
@@ -464,6 +521,7 @@ class SessionsController < ApplicationController
mobile_sso_redirect(code: authorization_code)
end
+ # Hand the desktop app a short-lived authorization code bound to its PKCE challenge.
def handle_desktop_sso_callback(user)
context = (session.delete(:desktop_sso) || {}).with_indifferent_access
code_challenge = context[:code_challenge]
@@ -485,7 +543,8 @@ class SessionsController < ApplicationController
redirect_to "sure://sso/callback?code=#{code}", allow_other_host: true
end
- def handle_mobile_sso_onboarding(auth)
+ # Start mobile account onboarding with the authenticated provider and issuer.
+ def handle_mobile_sso_onboarding(auth, issuer:)
device_info = session.delete(:mobile_sso)
email = auth.info&.email
@@ -502,7 +561,7 @@ class SessionsController < ApplicationController
first_name: auth.info&.first_name,
last_name: auth.info&.last_name,
name: auth.info&.name,
- issuer: auth.extra&.raw_info&.iss || auth.extra&.raw_info&.[]("iss"),
+ issuer: issuer,
device_info: device_info,
allow_account_creation: allow_creation
},
@@ -520,6 +579,7 @@ class SessionsController < ApplicationController
)
end
+ # Return a mobile SSO result through the application callback URI.
def mobile_sso_redirect(params = {})
redirect_to "sureapp://oauth/callback?#{params.to_query}", allow_other_host: true
end
@@ -534,10 +594,12 @@ class SessionsController < ApplicationController
false
end
+ # Scope session management to the currently authenticated user.
def set_session
@session = Current.user.sessions.find(params[:id])
end
+ # Record use of the emergency local-login override for a super administrator.
def log_super_admin_override_login(user)
# Only log when local login is globally disabled but an emergency
# super-admin override is enabled.
@@ -554,6 +616,7 @@ class SessionsController < ApplicationController
demo["hosts"].include?(request.host)
end
+ # Resolve the linked provider logout endpoint and build its logout redirect.
def build_idp_logout_url(oidc_identity, id_token)
# Find the provider configuration using unified loader (supports both YAML and DB providers)
provider_config = ProviderLoader.load_providers.find do |p|
@@ -610,6 +673,7 @@ class SessionsController < ApplicationController
end
end
+ # Build the standard discovery URL while preserving an issuer trailing slash.
def discovery_url_for(issuer)
if issuer.end_with?("/")
"#{issuer}.well-known/openid-configuration"
diff --git a/app/models/auth_config.rb b/app/models/auth_config.rb
index 44fb74b594..ead1746676 100644
--- a/app/models/auth_config.rb
+++ b/app/models/auth_config.rb
@@ -80,15 +80,29 @@ class AuthConfig
domains.map(&:downcase).include?(domain)
end
+ # Load normalized enabled providers live so cache refreshes take effect without rebooting.
def sso_providers
if FeatureFlags.db_sso_providers?
- # After boot, OmniAuth registers successfully configured providers into
- # Rails.configuration.x.auth.sso_providers. Prefer that filtered list
- # so we never render login buttons for providers that couldn't be
- # registered (e.g., missing required fields in YAML fallback).
- # Fall back to ProviderLoader for pre-boot contexts.
- registered = Rails.configuration.x.auth.sso_providers
- registered&.any? ? registered : ProviderLoader.load_providers
+ # Load live DB-backed providers so login paths see provider changes
+ # without an app restart; avoid memoizing stale OmniAuth config here.
+ # Validate live settings using the same builders as middleware registration,
+ # including YAML fallback entries that may have no client credentials.
+ registered_providers = Rails.configuration.x.auth.sso_providers || []
+ ProviderLoader.load_providers.filter_map do |config|
+ registration = OmniauthProviderRegistry.registration_for(config)
+ next unless registration
+
+ # Only OIDC routes are dynamic; other strategies still need boot-time registration.
+ unless registration.strategy == :openid_connect
+ next unless registered_providers.any? do |registered|
+ registered = registered.deep_symbolize_keys
+ registered[:name].to_s == registration.config[:name].to_s &&
+ registered[:strategy].to_s == registration.strategy.to_s
+ end
+ end
+
+ registration.config
+ end
else
Rails.configuration.x.auth.sso_providers || []
end
diff --git a/app/models/oidc_identity.rb b/app/models/oidc_identity.rb
index deae3f943e..510674f456 100644
--- a/app/models/oidc_identity.rb
+++ b/app/models/oidc_identity.rb
@@ -1,10 +1,58 @@
class OidcIdentity < ApplicationRecord
+ class ProviderNotConfigured < StandardError; end
+ class IssuerMismatch < StandardError; end
+ class LegacyIdentityRebindRejected < StandardError; end
+
belongs_to :user
validates :provider, presence: true
validates :uid, presence: true, uniqueness: { scope: :provider }
validates :user_id, presence: true
+ # Look up an authentication provider in the current enabled configuration.
+ def self.provider_config_for(provider_name)
+ config = AuthConfig.sso_providers&.find do |raw_config|
+ normalized = raw_config.deep_symbolize_keys
+ normalized[:name].to_s == provider_name.to_s || normalized[:id].to_s == provider_name.to_s
+ end&.deep_symbolize_keys
+ return unless config
+
+ if oidc_provider_config?(config, provider_name) && config[:issuer].blank?
+ options = Oidc::ProviderOptionsBuilder.call(config)
+ config = config.merge(issuer: options[:issuer]) if options&.dig(:issuer).present?
+ end
+
+ config
+ end
+
+ # Identify a supported OIDC provider configuration with the requested name.
+ def self.oidc_provider_config?(config, provider_name = nil)
+ return false if config.blank?
+
+ strategy = config.deep_symbolize_keys[:strategy].to_s
+ strategy == "openid_connect" || (strategy.blank? && provider_name.to_s == "openid_connect")
+ end
+
+ # The OIDC strategy merges verified ID-token claims into raw_info. Keep the
+ # issuer from that response and require it to match the active provider.
+ def self.verified_issuer_for!(auth, config)
+ issuer = raw_issuer(auth)
+ return issuer unless oidc_provider_config?(config, auth.provider)
+
+ expected_issuer = config.deep_symbolize_keys[:issuer].to_s.strip
+ raise IssuerMismatch if issuer.blank? || expected_issuer.blank? || issuer != expected_issuer
+
+ issuer
+ end
+
+ # Read the issuer from the verified OmniAuth authentication result.
+ def self.raw_issuer(auth)
+ raw_info = auth.extra&.raw_info
+ return unless raw_info
+
+ raw_info[:iss] || raw_info["iss"] || (raw_info.iss if raw_info.respond_to?(:iss))
+ end
+
# Update the last authenticated timestamp
def record_authentication!
update!(last_authenticated_at: Time.current)
@@ -83,8 +131,10 @@ class OidcIdentity < ApplicationRecord
raise SsoIdentityBlock::BlockedIdentity
end
- # Extract issuer from OIDC auth response if available
- issuer = auth.extra&.raw_info&.iss || auth.extra&.raw_info&.[]("iss")
+ config = provider_config_for(auth.provider)
+ raise ProviderNotConfigured if config.blank?
+
+ issuer = verified_issuer_for!(auth, config)
create!(
user: user,
@@ -102,23 +152,48 @@ class OidcIdentity < ApplicationRecord
end
end
- # Find the configured provider for this identity
- def provider_config
- AuthConfig.sso_providers&.find do |p|
- p_name = p[:name] || p["name"]
- p_id = p[:id] || p["id"]
- p_name == provider || p_id == provider
+ # Rebind a legacy OIDC identity only after the user proves ownership of the
+ # Sure account that already owns the provider/uid pair.
+ def self.rebind_legacy_issuer_from_omniauth!(auth, user)
+ SsoIdentityBlock.with_identity_lock(provider: auth.provider, uid: auth.uid) do
+ if SsoIdentityBlock.blocked?(provider: auth.provider, uid: auth.uid)
+ raise SsoIdentityBlock::BlockedIdentity
+ end
+
+ config = provider_config_for(auth.provider)
+ raise ProviderNotConfigured if config.blank?
+ raise LegacyIdentityRebindRejected unless oidc_provider_config?(config, auth.provider)
+
+ issuer = verified_issuer_for!(auth, config)
+ identity = find_by(provider: auth.provider, uid: auth.uid)
+ unless identity&.user_id == user.id && identity.issuer.blank?
+ raise LegacyIdentityRebindRejected
+ end
+
+ identity.update!(issuer: issuer, last_authenticated_at: Time.current)
+ identity.sync_user_attributes!(auth)
+ identity
end
end
- # Validate that the stored issuer matches the configured provider's issuer
- # Returns true if valid, false if mismatch (security concern)
- def issuer_matches_config?
- return true if issuer.blank? # Backward compatibility for old records
+ # Find the configured provider for this identity
+ def provider_config
+ self.class.provider_config_for(provider)
+ end
- config = provider_config
- config_issuer = config&.dig(:issuer) || config&.dig("issuer")
- return true if config_issuer.blank? # No config to validate against
+ # Validate that this identity still belongs to its active provider. OIDC
+ # identities require a stored issuer because provider + uid alone cannot
+ # establish issuer continuity after an in-place provider change.
+ def issuer_matches_config?(config = provider_config)
+ return false if config.blank?
+
+ config = config.deep_symbolize_keys
+ config_issuer = config[:issuer].to_s.strip
+ if self.class.oidc_provider_config?(config, provider)
+ return false if issuer.blank? || config_issuer.blank?
+ else
+ return true if issuer.blank? || config_issuer.blank?
+ end
issuer == config_issuer
end
diff --git a/app/models/omniauth_provider_registry.rb b/app/models/omniauth_provider_registry.rb
new file mode 100644
index 0000000000..2883ba599c
--- /dev/null
+++ b/app/models/omniauth_provider_registry.rb
@@ -0,0 +1,291 @@
+# frozen_string_literal: true
+
+class OmniauthProviderRegistry
+ Registration = Struct.new(:strategy, :args, :options, :config, keyword_init: true)
+
+ # Provider settings are validated on every login page render and auth request,
+ # so an incomplete provider is reported once rather than on each request.
+ SKIP_WARNING_LOCK = Mutex.new
+ SKIPPED_PROVIDERS = Set.new
+
+ class << self
+ # Register static strategies while leaving live database OIDC routing to the dynamic strategy.
+ def register(builder, raw_cfg)
+ registration = registration_for(raw_cfg)
+ return unless registration
+
+ # Live database OIDC names are handled exclusively by the dynamic strategy.
+ # A boot-time copy would keep intercepting routes after disablement.
+ if FeatureFlags.db_sso_providers? && registration.strategy == :openid_connect
+ return registration.config
+ end
+
+ builder.provider registration.strategy, *registration.args, registration.options
+ registration.config
+ end
+
+ # Normalize provider keys and build options for a supported authentication strategy.
+ def registration_for(raw_cfg)
+ cfg = raw_cfg.deep_symbolize_keys
+ strategy = cfg[:strategy].to_s
+
+ case strategy
+ when "openid_connect"
+ openid_connect_registration(cfg)
+ when "google_oauth2"
+ google_oauth2_registration(cfg)
+ when "github"
+ github_registration(cfg)
+ when "saml"
+ saml_registration(cfg)
+ end
+ end
+
+ # Register one OIDC strategy that resolves enabled database providers at request time.
+ def register_dynamic_database_oidc_provider(builder)
+ builder.provider :openid_connect, dynamic_database_oidc_options
+ end
+
+ private
+ # Build validated OIDC options and preserve the provider name and issuer.
+ def openid_connect_registration(cfg)
+ name = provider_name(cfg)
+ oidc_options = Oidc::ProviderOptionsBuilder.call(cfg)
+
+ unless oidc_options.present?
+ warn_skipped_provider(:openid_connect, name, "missing required configuration")
+ return nil
+ end
+
+ provider_configured(:openid_connect, name)
+ Registration.new(
+ strategy: :openid_connect,
+ args: [],
+ options: oidc_options,
+ config: cfg.merge(name: name, issuer: oidc_options[:issuer])
+ )
+ end
+
+ # Build a named Google OAuth strategy when client credentials are available.
+ def google_oauth2_registration(cfg)
+ name = provider_name(cfg)
+ client_id = cfg[:client_id].presence || ENV["GOOGLE_OAUTH_CLIENT_ID"].presence
+ client_secret = cfg[:client_secret].presence || ENV["GOOGLE_OAUTH_CLIENT_SECRET"].presence
+
+ if Rails.env.test?
+ client_id ||= "test_client_id"
+ client_secret ||= "test_client_secret"
+ end
+
+ return unless client_id.present? && client_secret.present?
+
+ Registration.new(
+ strategy: :google_oauth2,
+ args: [ client_id, client_secret ],
+ options: {
+ name: name.to_sym,
+ scope: "userinfo.email,userinfo.profile"
+ },
+ config: cfg.merge(name: name)
+ )
+ end
+
+ # Build a named GitHub OAuth strategy when client credentials are available.
+ def github_registration(cfg)
+ name = provider_name(cfg)
+ client_id = cfg[:client_id].presence || ENV["GITHUB_CLIENT_ID"].presence
+ client_secret = cfg[:client_secret].presence || ENV["GITHUB_CLIENT_SECRET"].presence
+
+ if Rails.env.test?
+ client_id ||= "test_client_id"
+ client_secret ||= "test_client_secret"
+ end
+
+ return unless client_id.present? && client_secret.present?
+
+ Registration.new(
+ strategy: :github,
+ args: [ client_id, client_secret ],
+ options: {
+ name: name.to_sym,
+ scope: "user:email"
+ },
+ config: cfg.merge(name: name)
+ )
+ end
+
+ # Build a named SAML strategy with its configured identity-provider endpoints.
+ def saml_registration(cfg)
+ name = provider_name(cfg)
+ settings = cfg[:settings] || {}
+
+ idp_metadata_url = settings[:idp_metadata_url].presence || settings["idp_metadata_url"].presence
+ idp_sso_url = settings[:idp_sso_url].presence || settings["idp_sso_url"].presence
+
+ unless idp_metadata_url.present? || idp_sso_url.present?
+ warn_skipped_provider(:saml, name, "missing IdP configuration")
+ return
+ end
+
+ provider_configured(:saml, name)
+
+ options = {
+ name: name.to_sym,
+ assertion_consumer_service_url: cfg[:redirect_uri].presence || "#{ENV['APP_URL']}/auth/#{name}/callback",
+ issuer: cfg[:issuer].presence || ENV["APP_URL"],
+ name_identifier_format: settings[:name_id_format].presence || settings["name_id_format"].presence ||
+ "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress",
+ attribute_statements: {
+ email: [ "email", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" ],
+ first_name: [ "first_name", "givenName", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" ],
+ last_name: [ "last_name", "surname", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" ],
+ groups: [ "groups", "http://schemas.microsoft.com/ws/2008/06/identity/claims/groups" ]
+ }
+ }
+
+ if idp_metadata_url.present?
+ options[:idp_metadata_url] = idp_metadata_url
+ else
+ options[:idp_sso_service_url] = idp_sso_url
+ options[:idp_cert] = settings[:idp_certificate].presence || settings["idp_certificate"].presence
+ options[:idp_cert_fingerprint] = settings[:idp_cert_fingerprint].presence || settings["idp_cert_fingerprint"].presence
+ end
+
+ idp_slo_url = settings[:idp_slo_url].presence || settings["idp_slo_url"].presence
+ options[:idp_slo_service_url] = idp_slo_url if idp_slo_url.present?
+
+ Registration.new(
+ strategy: :saml,
+ args: [],
+ options: options,
+ config: cfg.merge(name: name, strategy: "saml")
+ )
+ end
+
+ # Use live route predicates and per-request setup for database-backed OIDC.
+ def dynamic_database_oidc_options
+ {
+ name: :db_openid_connect,
+ request_path: method(:database_oidc_request_path?),
+ callback_path: method(:database_oidc_callback_path?),
+ setup: method(:setup_database_oidc_provider)
+ }.merge(openid_connect_options({}, "db_openid_connect", nil, nil, nil, nil))
+ end
+
+ # Accept an enabled database OIDC login route, excluding callbacks.
+ def database_oidc_request_path?(env)
+ database_oidc_config_for(env).present? && !callback_request?(env)
+ end
+
+ # Accept a callback only for a currently enabled database OIDC provider.
+ def database_oidc_callback_path?(env)
+ database_oidc_config_for(env).present? && callback_request?(env)
+ end
+
+ # Apply the selected live provider options to the request strategy.
+ def setup_database_oidc_provider(env)
+ registration = database_oidc_registration_for(env)
+ return unless registration
+
+ strategy = env["omniauth.strategy"]
+ strategy.options.deep_merge!(registration.options)
+ end
+
+ # Return the selected request-scoped database provider configuration.
+ def database_oidc_config_for(env)
+ database_oidc_registration_for(env)&.config
+ end
+
+ # Resolve an enabled provider once per request without retaining stale boot-time routes.
+ def database_oidc_registration_for(env)
+ return unless FeatureFlags.db_sso_providers?
+ return env["sure.omniauth.database_oidc_registration"] if env.key?("sure.omniauth.database_oidc_registration")
+
+ name = auth_path_provider_name(env)
+ return env["sure.omniauth.database_oidc_registration"] = nil if name.blank? || name == "failure" || name == "logout"
+
+ ProviderLoader.load_providers.each do |raw_provider|
+ provider = raw_provider.deep_symbolize_keys
+ next unless provider[:strategy].to_s == "openid_connect" && provider_name(provider) == name
+
+ return env["sure.omniauth.database_oidc_registration"] = openid_connect_registration(provider)
+ end
+
+ env["sure.omniauth.database_oidc_registration"] = nil
+ end
+
+ # Extract a provider name only from a supported OmniAuth login or callback path.
+ def auth_path_provider_name(env)
+ match = auth_path(env).match(%r{\A/auth/([^/]+)(?:/callback)?\z})
+ match&.[](1)
+ end
+
+ # Distinguish callback requests from authentication-start requests.
+ def callback_request?(env)
+ auth_path(env).end_with?("/callback")
+ end
+
+ # Drop one trailing slash, as OmniAuth does before matching its own routes.
+ def auth_path(env)
+ env["PATH_INFO"].to_s.delete_suffix("/")
+ end
+
+ # Build common OIDC discovery, PKCE, scope and client options.
+ def openid_connect_options(cfg, name, issuer, client_id, client_secret, redirect_uri)
+ options = {
+ name: name.to_sym,
+ scope: openid_connect_scopes(cfg),
+ response_type: :code,
+ issuer: issuer.to_s.strip,
+ discovery: true,
+ pkce: true,
+ client_options: {
+ identifier: client_id,
+ secret: client_secret,
+ redirect_uri: redirect_uri,
+ ssl: ssl_options
+ }
+ }
+
+ prompt = cfg.dig(:settings, :prompt).presence || cfg.dig(:settings, "prompt").presence
+ options[:prompt] = prompt if prompt.present?
+ options
+ end
+
+ # Use configured scopes or the standard OIDC identity scopes.
+ def openid_connect_scopes(cfg)
+ custom_scopes = cfg.dig(:settings, :scopes).presence || cfg.dig(:settings, "scopes").presence
+ return %i[openid email profile] if custom_scopes.blank?
+
+ custom_scopes.to_s.split(/\s+/).map(&:to_sym)
+ end
+
+ # Honor the application certificate and TLS verification settings.
+ def ssl_options
+ ssl_config = Rails.configuration.x.ssl
+ options = {}
+ options[:ca_file] = ssl_config.ca_file if ssl_config&.ca_file.present?
+ options[:verify] = false if ssl_config&.verify == false
+ options
+ end
+
+ # Resolve the custom provider name with its identifier as fallback.
+ def provider_name(cfg)
+ (cfg[:name] || cfg[:id]).to_s
+ end
+
+ # Warn once per incomplete provider until it is configured again.
+ def warn_skipped_provider(strategy, name, reason)
+ newly_skipped = SKIP_WARNING_LOCK.synchronize { SKIPPED_PROVIDERS.add?([ strategy, name ]) }
+ return unless newly_skipped
+
+ label = strategy == :saml ? "SAML" : "OIDC"
+ Rails.logger.warn("[OmniAuth] Skipping #{label} provider '#{name}' - #{reason}")
+ end
+
+ # A provider that becomes incomplete again after a fix is reported again.
+ def provider_configured(strategy, name)
+ SKIP_WARNING_LOCK.synchronize { SKIPPED_PROVIDERS.delete([ strategy, name ]) }
+ end
+ end
+end
diff --git a/config/initializers/omniauth.rb b/config/initializers/omniauth.rb
index 8261b8c7eb..87c97e2f71 100644
--- a/config/initializers/omniauth.rb
+++ b/config/initializers/omniauth.rb
@@ -28,116 +28,17 @@ OmniAuth.config.on_failure = proc do |env|
end
Rails.application.config.middleware.use OmniAuth::Builder do
+ OmniauthProviderRegistry.register_dynamic_database_oidc_provider(self)
+
# Load providers from either YAML or DB via ProviderLoader
providers = ProviderLoader.load_providers
providers.each do |raw_cfg|
- cfg = raw_cfg.deep_symbolize_keys
- strategy = cfg[:strategy].to_s
- name = (cfg[:name] || cfg[:id]).to_s
-
- case strategy
- when "openid_connect"
- oidc_options = Oidc::ProviderOptionsBuilder.call(cfg)
-
- unless oidc_options.present?
- Rails.logger.warn("[OmniAuth] Skipping OIDC provider '#{name}' - missing required configuration")
- next
- end
-
- provider :openid_connect, oidc_options
-
- Rails.configuration.x.auth.oidc_enabled = true
- Rails.configuration.x.auth.sso_providers << cfg.merge(name: name, issuer: oidc_options[:issuer])
-
- when "google_oauth2"
- client_id = cfg[:client_id].presence || ENV["GOOGLE_OAUTH_CLIENT_ID"].presence
- client_secret = cfg[:client_secret].presence || ENV["GOOGLE_OAUTH_CLIENT_SECRET"].presence
-
- # Test environment fallback
- if Rails.env.test?
- client_id ||= "test_client_id"
- client_secret ||= "test_client_secret"
- end
-
- next unless client_id.present? && client_secret.present?
-
- provider :google_oauth2,
- client_id,
- client_secret,
- {
- name: name.to_sym,
- scope: "userinfo.email,userinfo.profile"
- }
-
- Rails.configuration.x.auth.sso_providers << cfg.merge(name: name)
-
- when "github"
- client_id = cfg[:client_id].presence || ENV["GITHUB_CLIENT_ID"].presence
- client_secret = cfg[:client_secret].presence || ENV["GITHUB_CLIENT_SECRET"].presence
-
- # Test environment fallback
- if Rails.env.test?
- client_id ||= "test_client_id"
- client_secret ||= "test_client_secret"
- end
-
- next unless client_id.present? && client_secret.present?
-
- provider :github,
- client_id,
- client_secret,
- {
- name: name.to_sym,
- scope: "user:email"
- }
-
- Rails.configuration.x.auth.sso_providers << cfg.merge(name: name)
-
- when "saml"
- settings = cfg[:settings] || {}
-
- # Require either metadata URL or manual SSO URL
- idp_metadata_url = settings[:idp_metadata_url].presence || settings["idp_metadata_url"].presence
- idp_sso_url = settings[:idp_sso_url].presence || settings["idp_sso_url"].presence
-
- unless idp_metadata_url.present? || idp_sso_url.present?
- Rails.logger.warn("[OmniAuth] Skipping SAML provider '#{name}' - missing IdP configuration")
- next
- end
-
- # Build SAML options
- saml_options = {
- name: name.to_sym,
- assertion_consumer_service_url: cfg[:redirect_uri].presence || "#{ENV['APP_URL']}/auth/#{name}/callback",
- issuer: cfg[:issuer].presence || ENV["APP_URL"],
- name_identifier_format: settings[:name_id_format].presence || settings["name_id_format"].presence ||
- "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress",
- attribute_statements: {
- email: [ "email", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" ],
- first_name: [ "first_name", "givenName", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" ],
- last_name: [ "last_name", "surname", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" ],
- groups: [ "groups", "http://schemas.microsoft.com/ws/2008/06/identity/claims/groups" ]
- }
- }
-
- # Use metadata URL or manual configuration
- if idp_metadata_url.present?
- saml_options[:idp_metadata_url] = idp_metadata_url
- else
- saml_options[:idp_sso_service_url] = idp_sso_url
- saml_options[:idp_cert] = settings[:idp_certificate].presence || settings["idp_certificate"].presence
- saml_options[:idp_cert_fingerprint] = settings[:idp_cert_fingerprint].presence || settings["idp_cert_fingerprint"].presence
- end
-
- # Optional: IdP SLO (Single Logout) URL
- idp_slo_url = settings[:idp_slo_url].presence || settings["idp_slo_url"].presence
- saml_options[:idp_slo_service_url] = idp_slo_url if idp_slo_url.present?
-
- provider :saml, saml_options
+ config = OmniauthProviderRegistry.register(self, raw_cfg)
+ next unless config
- Rails.configuration.x.auth.sso_providers << cfg.merge(name: name, strategy: "saml")
- end
+ Rails.configuration.x.auth.oidc_enabled = true if config[:strategy].to_s == "openid_connect"
+ Rails.configuration.x.auth.sso_providers << config
end
if Rails.configuration.x.auth.sso_providers.empty?
diff --git a/config/locales/views/sessions/en.yml b/config/locales/views/sessions/en.yml
index 327d08ebba..cb74dbdde7 100644
--- a/config/locales/views/sessions/en.yml
+++ b/config/locales/views/sessions/en.yml
@@ -12,6 +12,7 @@ en:
openid_connect:
account_linked: "Account successfully linked to %{provider}"
failed: Could not authenticate via OpenID Connect.
+ legacy_issuer_relink_required: This older OIDC connection needs to be verified again. Enter your Sure password to reconnect it; if you do not have a local password, contact an administrator.
failure:
failed: Could not authenticate.
sso_provider_unavailable: "The SSO provider is currently unavailable. Please try again later or contact an administrator."
diff --git a/config/locales/views/sessions/zh-CN.yml b/config/locales/views/sessions/zh-CN.yml
index 0c37658cf7..05754306b4 100644
--- a/config/locales/views/sessions/zh-CN.yml
+++ b/config/locales/views/sessions/zh-CN.yml
@@ -12,6 +12,7 @@ zh-CN:
openid_connect:
account_linked: 已成功将账户链接到 %{provider}
failed: 无法通过 OpenID Connect 进行认证。
+ legacy_issuer_relink_required: 此旧版 OIDC 关联需要重新验证。请输入 Sure 密码重新绑定;如果没有本地密码,请联系管理员。
failure:
failed: 认证失败。
sso_provider_unavailable: 当前 SSO 提供商不可用。请稍后再试或联系管理员。
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 2c65cc07ba..1b524882a0 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -5713,7 +5713,8 @@ paths:
- Auth
description: Authenticates with email/password and links the SSO identity from
a previously issued linking code. Creates an OidcIdentity, logs the link via
- SsoAuditLog, and issues mobile OAuth tokens.
+ SsoAuditLog, and issues mobile OAuth tokens. The provider must remain enabled
+ and its trusted issuer must still match the linking code.
parameters: []
responses:
'200':
@@ -5767,7 +5768,7 @@ paths:
- "$ref": "#/components/schemas/ErrorResponse"
- "$ref": "#/components/schemas/MfaRequiredResponse"
'403':
- description: SSO identity removed by an administrator
+ description: SSO identity removed, provider disabled, or issuer changed
content:
application/json:
schema:
@@ -5800,9 +5801,10 @@ paths:
- Auth
description: Creates a new user and family from a previously issued linking
code. Links the SSO identity via OidcIdentity, logs the JIT account creation
- via SsoAuditLog, and issues mobile OAuth tokens. The linking code must have
- allow_account_creation enabled. The first user on a fresh instance is assigned
- the super_admin role; later family creators are assigned an admin-capable
+ via SsoAuditLog, and issues mobile OAuth tokens. The provider must remain
+ enabled and its trusted issuer must match the linking code. The linking code
+ must have allow_account_creation enabled. The first user on a fresh instance
+ is assigned the super_admin role; later family creators are assigned an admin-capable
role.
parameters: []
responses:
@@ -5855,7 +5857,8 @@ paths:
schema:
"$ref": "#/components/schemas/ErrorResponse"
'403':
- description: SSO identity removed or account creation disabled
+ description: SSO identity removed, provider disabled, issuer changed, or
+ account creation disabled
content:
application/json:
schema:
diff --git a/docs/hosting/oidc.md b/docs/hosting/oidc.md
index 601a6787a2..5cd98f84ad 100644
--- a/docs/hosting/oidc.md
+++ b/docs/hosting/oidc.md
@@ -342,7 +342,9 @@ AUTH_PROVIDERS_SOURCE=db
When enabled:
- Providers are loaded from the `sso_providers` database table
-- Changes take effect immediately (no server restart required)
+- Valid database-backed OIDC changes take effect after the provider cache is refreshed, without a server restart.
+- Google, GitHub, and SAML strategies are registered at startup. Restart the application after adding, renaming, or changing their client settings. New names are not offered for login until their strategy has been registered.
+- Provider lists omit entries with missing required credentials, including entries returned by YAML fallback.
- Providers can be managed through the admin UI at `/admin/sso_providers`
When disabled (default):
@@ -568,6 +570,36 @@ Each provider requires a callback URL configured in your identity provider:
- On subsequent logins, Sure verifies the issuer matches the configured provider
- This prevents issuer impersonation attacks
+### Recover older identities without an issuer
+
+Check existing OIDC identities before deploying issuer-continuity enforcement.
+An identity with a blank `issuer` cannot establish which identity provider
+originally authenticated its account. Sure rejects automatic login for that
+identity instead of trusting the current provider name and subject alone.
+
+People with a local Sure password can complete the web relinking flow using
+that password. SSO-only accounts have no local password, and Sure intentionally
+blocks password reset for them. These accounts need an instance operator's
+help; there is no self-service recovery for this case. Mobile and desktop
+clients return `issuer_relink_required`.
+
+For an SSO-only account, the instance operator must:
+
+1. Independently verify ownership of the existing Sure account and its original
+ IdP identity using trusted historical or organizational identity records.
+ A matching email address, provider name, or subject from a replacement IdP
+ is insufficient.
+2. Use the Rails console to select the existing `OidcIdentity` by its row ID.
+ Confirm its `user_id`, `provider`, and `uid` against those verified records,
+ then set only its blank `issuer` to the confirmed original issuer URL.
+ Preserve the account and identity association, and record the recovery.
+3. Confirm that the enabled provider still uses that same trusted issuer, then
+ ask the person to restart SSO login. Existing MFA requirements still apply.
+
+Do not bulk-fill blank issuers from current provider configuration. If ownership
+or the original issuer cannot be established, leave the identity blocked while
+the instance operator resolves account recovery.
+
### Admin access
- SSO provider management requires `super_admin` role
diff --git a/spec/requests/api/v1/auth_spec.rb b/spec/requests/api/v1/auth_spec.rb
index 14a2d00ecb..2af15aac3e 100644
--- a/spec/requests/api/v1/auth_spec.rb
+++ b/spec/requests/api/v1/auth_spec.rb
@@ -374,7 +374,7 @@ RSpec.describe 'API V1 Auth', type: :request do
tags 'Auth'
consumes 'application/json'
produces 'application/json'
- description 'Authenticates with email/password and links the SSO identity from a previously issued linking code. Creates an OidcIdentity, logs the link via SsoAuditLog, and issues mobile OAuth tokens.'
+ description 'Authenticates with email/password and links the SSO identity from a previously issued linking code. Creates an OidcIdentity, logs the link via SsoAuditLog, and issues mobile OAuth tokens. The provider must remain enabled and its trusted issuer must still match the linking code.'
parameter name: :body, in: :body, required: true, schema: {
type: :object,
properties: {
@@ -429,7 +429,7 @@ RSpec.describe 'API V1 Auth', type: :request do
run_test!
end
- response '403', 'SSO identity removed by an administrator' do
+ response '403', 'SSO identity removed, provider disabled, or issuer changed' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:linking_code) { 'rswag-removed-identity' }
@@ -466,6 +466,7 @@ RSpec.describe 'API V1 Auth', type: :request do
produces 'application/json'
description 'Creates a new user and family from a previously issued linking code. Links the SSO identity ' \
'via OidcIdentity, logs the JIT account creation via SsoAuditLog, and issues mobile OAuth tokens. ' \
+ 'The provider must remain enabled and its trusted issuer must match the linking code. ' \
'The linking code must have allow_account_creation enabled. The first user on a fresh instance is ' \
'assigned the super_admin role; later family creators are assigned an admin-capable role.'
parameter name: :body, in: :body, required: true, schema: {
@@ -519,7 +520,7 @@ RSpec.describe 'API V1 Auth', type: :request do
run_test!
end
- response '403', 'SSO identity removed or account creation disabled' do
+ response '403', 'SSO identity removed, provider disabled, issuer changed, or account creation disabled' do
schema '$ref' => '#/components/schemas/ErrorResponse'
let(:body) { { linking_code: linking_code } }
diff --git a/test/controllers/api/v1/auth_controller_test.rb b/test/controllers/api/v1/auth_controller_test.rb
index e26b46a8cb..9dc227e34b 100644
--- a/test/controllers/api/v1/auth_controller_test.rb
+++ b/test/controllers/api/v1/auth_controller_test.rb
@@ -4,6 +4,10 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest
setup do
# Clean up any existing invite codes
InviteCode.destroy_all
+ AuthConfig.stubs(:sso_providers).returns([
+ { name: "openid_connect", strategy: "openid_connect", issuer: "https://test.example.com" },
+ { name: "google_oauth2", strategy: "google_oauth2" }
+ ])
@device_info = {
device_id: "test-device-123",
device_name: "Test iPhone",
@@ -1134,8 +1138,8 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest
end
test "sso_create_account makes new family creator admin even when provider default role is member" do
- Rails.configuration.x.auth.stubs(:sso_providers).returns([
- { name: "google_oauth2", settings: { default_role: "member" } }
+ AuthConfig.stubs(:sso_providers).returns([
+ { name: "google_oauth2", strategy: "google_oauth2", settings: { default_role: "member" } }
])
linking_code = SecureRandom.urlsafe_base64(32)
Rails.cache.write("mobile_sso_link:#{linking_code}", {
@@ -1164,8 +1168,8 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest
end
test "sso_create_account preserves super admin provider default for new family creator" do
- Rails.configuration.x.auth.stubs(:sso_providers).returns([
- { name: "google_oauth2", settings: { default_role: "super_admin" } }
+ AuthConfig.stubs(:sso_providers).returns([
+ { name: "google_oauth2", strategy: "google_oauth2", settings: { default_role: "super_admin" } }
])
linking_code = SecureRandom.urlsafe_base64(32)
Rails.cache.write("mobile_sso_link:#{linking_code}", {
@@ -1374,6 +1378,7 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest
Rails.cache.write("mobile_sso_link:#{linking_code}", {
provider: "openid_connect",
uid: "mobile-invite-uid-1",
+ issuer: "https://test.example.com",
email: invitation.email,
first_name: "Mobile",
last_name: "Invitee",
@@ -1394,6 +1399,7 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest
invitee = User.find_by(email: invitation.email)
assert_not_nil invitee
assert_equal family.id, invitee.family_id
+ assert_equal "https://test.example.com", invitee.oidc_identities.sole.issuer
assert_equal family.accounts.pluck(:id).sort,
AccountShare.where(user: invitee).pluck(:account_id).sort
end
@@ -1422,6 +1428,56 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest
assert_nil Rails.cache.read("mobile_sso_link:#{linking_code}")
end
+ test "mobile SSO cannot link an account after its provider is disabled" do
+ user = users(:family_admin)
+ user.sessions.destroy_all
+ linking_code = SecureRandom.urlsafe_base64(32)
+ Rails.cache.write("mobile_sso_link:#{linking_code}", {
+ provider: "openid_connect",
+ uid: "disabled-provider-link-uid",
+ email: user.email,
+ issuer: "https://test.example.com",
+ device_info: @device_info.stringify_keys
+ }, expires_in: 10.minutes)
+ AuthConfig.stubs(:sso_providers).returns([])
+
+ assert_no_difference [
+ "OidcIdentity.count",
+ "MobileDevice.count",
+ "Doorkeeper::AccessToken.count",
+ 'SsoAuditLog.by_event("login").count'
+ ] do
+ post "/api/v1/auth/sso_link", params: {
+ linking_code: linking_code,
+ email: user.email,
+ password: user_password_test
+ }
+ end
+
+ assert_response :forbidden
+ assert_nil Rails.cache.read("mobile_sso_link:#{linking_code}")
+ end
+
+ test "mobile SSO cannot create an account after its provider is disabled" do
+ linking_code = SecureRandom.urlsafe_base64(32)
+ Rails.cache.write("mobile_sso_link:#{linking_code}", {
+ provider: "openid_connect",
+ uid: "disabled-provider-create-uid",
+ email: "[email protected]",
+ issuer: "https://test.example.com",
+ device_info: @device_info.stringify_keys,
+ allow_account_creation: true
+ }, expires_in: 10.minutes)
+ AuthConfig.stubs(:sso_providers).returns([])
+
+ assert_no_difference [ "User.count", "Family.count", "OidcIdentity.count", "MobileDevice.count", "Doorkeeper::AccessToken.count" ] do
+ post "/api/v1/auth/sso_create_account", params: { linking_code: linking_code }
+ end
+
+ assert_response :forbidden
+ assert_nil Rails.cache.read("mobile_sso_link:#{linking_code}")
+ end
+
test "mobile SSO onboarding via invitation shares nothing when family sharing is private" do
family = families(:dylan_family)
family.update!(default_account_sharing: "private")
@@ -1433,6 +1489,7 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest
Rails.cache.write("mobile_sso_link:#{linking_code}", {
provider: "openid_connect",
uid: "mobile-private-uid-1",
+ issuer: "https://test.example.com",
email: invitation.email,
first_name: "Mobile",
last_name: "Private",
@@ -1455,6 +1512,8 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest
end
test "sso_providers lists configured providers without secrets" do
+ AuthConfig.unstub(:sso_providers)
+ FeatureFlags.stubs(:db_sso_providers?).returns(false)
Rails.configuration.x.auth.stubs(:sso_providers).returns([
{ id: "authentik", name: "authentik", strategy: "openid_connect", label: "Authentik", client_secret: "shh", issuer: "https://idp.example.com" },
{ id: "oidc", name: "openid_connect", strategy: "openid_connect", label: "", client_secret: "shh" },
@@ -1474,7 +1533,38 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest
assert_not_includes response.body, "shh"
end
+ test "sso_providers reflects database provider additions and disablement without restarting" do
+ AuthConfig.unstub(:sso_providers)
+ FeatureFlags.stubs(:db_sso_providers?).returns(true)
+ Rails.configuration.x.auth.stubs(:sso_providers).returns([])
+ provider = {
+ "name" => "live_oidc", "strategy" => "openid_connect", "label" => "Live SSO",
+ "issuer" => "https://idp.example.com", "client_id" => "client-id", "client_secret" => "private-secret"
+ }
+ ProviderLoader.stubs(:load_providers).returns([ provider ])
+
+ get "/api/v1/auth/sso_providers"
+
+ assert_response :success
+ assert_equal [ { "name" => "live_oidc", "strategy" => "openid_connect", "label" => "Live SSO" } ], JSON.parse(response.body)["providers"]
+ assert_not_includes response.body, "private-secret"
+ assert_not_includes response.body, "https://idp.example.com"
+ get "/auth/mobile/live_oidc", params: { device_id: "live-device", device_name: "Test", device_type: "ios" }
+ assert_response :success
+
+ ProviderLoader.stubs(:load_providers).returns([])
+ get "/api/v1/auth/sso_providers"
+
+ assert_response :success
+ assert_empty JSON.parse(response.body)["providers"]
+ get "/auth/mobile/live_oidc", params: { device_id: "live-device", device_name: "Test", device_type: "ios" }
+ assert_response :redirect
+ assert_equal "invalid_provider", Rack::Utils.parse_query(URI.parse(response.location).query)["error"]
+ end
+
test "sso_providers returns an empty list when no providers are configured" do
+ AuthConfig.unstub(:sso_providers)
+ FeatureFlags.stubs(:db_sso_providers?).returns(false)
Rails.configuration.x.auth.stubs(:sso_providers).returns([])
get "/api/v1/auth/sso_providers"
diff --git a/test/controllers/mfa_controller_test.rb b/test/controllers/mfa_controller_test.rb
index f782a8e839..c50f4e9091 100644
--- a/test/controllers/mfa_controller_test.rb
+++ b/test/controllers/mfa_controller_test.rb
@@ -589,6 +589,7 @@ class MfaControllerTest < ActionDispatch::IntegrationTest
provider: identity.provider,
uid: identity.uid,
info: { email: identity.user.email, name: identity.user.display_name },
+ extra: { raw_info: { iss: identity.issuer } },
credentials: {}
)
get "/auth/openid_connect/callback"
diff --git a/test/controllers/oidc_accounts_controller_test.rb b/test/controllers/oidc_accounts_controller_test.rb
index 03fe1a5c41..2624986ded 100644
--- a/test/controllers/oidc_accounts_controller_test.rb
+++ b/test/controllers/oidc_accounts_controller_test.rb
@@ -3,8 +3,12 @@ require "test_helper"
class OidcAccountsControllerTest < ActionController::TestCase
setup do
@user = users(:family_admin)
+ AuthConfig.stubs(:sso_providers).returns([
+ { name: "openid_connect", strategy: "openid_connect", issuer: "https://test.example.com" }
+ ])
end
+ # Build deferred authentication with an explicit trusted issuer for linking regressions.
def pending_auth
{
"provider" => "openid_connect",
@@ -12,7 +16,8 @@ class OidcAccountsControllerTest < ActionController::TestCase
"email" => @user.email,
"name" => "Bob Dylan",
"first_name" => "Bob",
- "last_name" => "Dylan"
+ "last_name" => "Dylan",
+ "issuer" => "https://test.example.com"
}
end
@@ -119,10 +124,52 @@ class OidcAccountsControllerTest < ActionController::TestCase
end
assert_redirected_to root_path
- assert_not_nil @user.oidc_identities.find_by(
+ identity = @user.oidc_identities.find_by(
provider: pending_auth["provider"],
uid: pending_auth["uid"]
)
+ assert_not_nil identity
+ assert_equal pending_auth["issuer"], identity.issuer
+ end
+
+ test "rejects create_link when provider is disabled after authentication" do
+ session[:pending_oidc_auth] = pending_auth
+ AuthConfig.stubs(:sso_providers).returns([])
+ @user.sessions.destroy_all
+
+ assert_no_difference [ "OidcIdentity.count", "Session.count", "SsoAuditLog.count" ] do
+ post :create_link,
+ params: {
+ email: @user.email,
+ password: user_password_test
+ }
+ end
+
+ assert_redirected_to new_session_path
+ assert_nil session[:pending_oidc_auth]
+ end
+
+ test "rebinds a legacy issuerless identity after verifying its local account" do
+ identity = oidc_identities(:bob_google)
+ identity.update!(issuer: nil)
+ session[:pending_oidc_auth] = pending_auth.merge("uid" => identity.uid)
+ session[:pending_oidc_legacy_relink] = true
+ AuthConfig.stubs(:sso_providers).returns([
+ { name: identity.provider, strategy: "openid_connect", issuer: pending_auth["issuer"] }
+ ])
+ @user.sessions.destroy_all
+
+ assert_no_difference "OidcIdentity.count" do
+ post :create_link,
+ params: {
+ email: @user.email,
+ password: user_password_test
+ }
+ end
+
+ assert_redirected_to root_path
+ assert_equal pending_auth["issuer"], identity.reload.issuer
+ assert Session.exists?(user_id: @user.id)
end
test "rolls back identity linking when session creation fails" do
@@ -248,7 +295,8 @@ class OidcAccountsControllerTest < ActionController::TestCase
"email" => "[email protected]",
"name" => "New User",
"first_name" => "New",
- "last_name" => "User"
+ "last_name" => "User",
+ "issuer" => "https://test.example.com"
}
end
@@ -343,6 +391,18 @@ class OidcAccountsControllerTest < ActionController::TestCase
assert_equal "SSO account creation is disabled. Please contact an administrator.", flash[:alert]
end
+ test "rejects create_user when provider is disabled after authentication" do
+ session[:pending_oidc_auth] = new_user_auth
+ AuthConfig.stubs(:sso_providers).returns([])
+
+ assert_no_difference [ "User.count", "OidcIdentity.count", "Family.count", "Session.count" ] do
+ post :create_user
+ end
+
+ assert_redirected_to new_session_path
+ assert_nil session[:pending_oidc_auth]
+ end
+
test "should create new user account via OIDC" do
session[:pending_oidc_auth] = new_user_auth
@@ -365,12 +425,13 @@ class OidcAccountsControllerTest < ActionController::TestCase
assert_not_nil oidc_identity
assert_equal new_user_auth["provider"], oidc_identity.provider
assert_equal new_user_auth["uid"], oidc_identity.uid
+ assert_equal new_user_auth["issuer"], oidc_identity.issuer
end
test "create_user makes new family creator admin even when provider default role is member" do
session[:pending_oidc_auth] = new_user_auth
- Rails.configuration.x.auth.stubs(:sso_providers).returns([
- { name: new_user_auth["provider"], settings: { default_role: "member" } }
+ AuthConfig.stubs(:sso_providers).returns([
+ { name: new_user_auth["provider"], strategy: "openid_connect", issuer: new_user_auth["issuer"], settings: { default_role: "member" } }
])
assert_difference [ "User.count", "OidcIdentity.count", "Family.count" ], 1 do
@@ -384,8 +445,8 @@ class OidcAccountsControllerTest < ActionController::TestCase
test "create_user preserves super admin provider default for new family creator" do
session[:pending_oidc_auth] = new_user_auth
- Rails.configuration.x.auth.stubs(:sso_providers).returns([
- { name: new_user_auth["provider"], settings: { default_role: "super_admin" } }
+ AuthConfig.stubs(:sso_providers).returns([
+ { name: new_user_auth["provider"], strategy: "openid_connect", issuer: new_user_auth["issuer"], settings: { default_role: "super_admin" } }
])
assert_difference [ "User.count", "OidcIdentity.count", "Family.count" ], 1 do
@@ -523,7 +584,8 @@ class OidcAccountsControllerTest < ActionController::TestCase
session[:pending_oidc_auth] = {
"provider" => "openid_connect", "uid" => "invite-uid-1",
- "email" => "[email protected]", "first_name" => "In", "last_name" => "Vitee"
+ "email" => "[email protected]", "first_name" => "In", "last_name" => "Vitee",
+ "issuer" => "https://test.example.com"
}
post :create_user
@@ -543,7 +605,8 @@ class OidcAccountsControllerTest < ActionController::TestCase
session[:pending_oidc_auth] = {
"provider" => "openid_connect", "uid" => "invite-uid-2",
- "email" => "[email protected]", "first_name" => "In", "last_name" => "Vitee"
+ "email" => "[email protected]", "first_name" => "In", "last_name" => "Vitee",
+ "issuer" => "https://test.example.com"
}
post :create_user
diff --git a/test/controllers/sessions_controller_test.rb b/test/controllers/sessions_controller_test.rb
index be8b44620e..4b102a1a56 100644
--- a/test/controllers/sessions_controller_test.rb
+++ b/test/controllers/sessions_controller_test.rb
@@ -56,7 +56,8 @@ class SessionsControllerTest < ActionDispatch::IntegrationTest
Faraday.stubs(:new).returns(connection)
end
- def setup_omniauth_mock(provider:, uid:, email:, name:, first_name: nil, last_name: nil, id_token: nil)
+ # Build authenticated claims that exercise provider and issuer checks in callbacks.
+ def setup_omniauth_mock(provider:, uid:, email:, name:, first_name: nil, last_name: nil, issuer: "https://test.example.com", id_token: nil)
OmniAuth.config.mock_auth[:openid_connect] = OmniAuth::AuthHash.new({
provider: provider,
uid: uid,
@@ -66,6 +67,7 @@ class SessionsControllerTest < ActionDispatch::IntegrationTest
first_name: first_name,
last_name: last_name
}.compact,
+ extra: { raw_info: { iss: issuer } },
credentials: id_token ? { id_token: id_token } : {}
})
end
@@ -334,7 +336,7 @@ class SessionsControllerTest < ActionDispatch::IntegrationTest
AuthConfig.stubs(:local_login_form_visible?).returns(true)
AuthConfig.stubs(:password_features_enabled?).returns(true)
AuthConfig.stubs(:sso_providers).returns([
- { id: "oidc", strategy: "openid_connect", name: "openid_connect", label: "Sign in with Keycloak", icon: "key" },
+ { id: "oidc", strategy: "openid_connect", name: "openid_connect", label: "Sign in with Keycloak", icon: "key", issuer: "https://test.example.com" },
{ id: "google", strategy: "google_oauth2", name: "google_oauth2", label: "Sign in with Google", icon: "google" }
])
@@ -410,6 +412,160 @@ class SessionsControllerTest < ActionDispatch::IntegrationTest
assert Session.exists?(user_id: @user.id)
end
+ test "rejects existing OIDC identity when provider issuer has changed" do
+ oidc_identity = oidc_identities(:bob_google)
+ oidc_identity.update!(issuer: "https://old-idp.example")
+ AuthConfig.stubs(:sso_providers).returns([
+ { name: oidc_identity.provider, issuer: "https://new-idp.example" }
+ ])
+ @user.sessions.destroy_all
+
+ setup_omniauth_mock(
+ provider: oidc_identity.provider,
+ uid: oidc_identity.uid,
+ email: @user.email,
+ name: "Changed by the new issuer",
+ issuer: "https://new-idp.example"
+ )
+ last_authenticated_at = oidc_identity.last_authenticated_at
+ identity_info = oidc_identity.info
+
+ assert_difference -> { SsoAuditLog.by_event("login_failed").count }, 1 do
+ assert_no_difference -> { SsoAuditLog.by_event("login").count } do
+ get "/auth/openid_connect/callback"
+ end
+ end
+
+ assert_redirected_to new_session_path
+ assert_not Session.exists?(user_id: @user.id)
+ assert_equal last_authenticated_at, oidc_identity.reload.last_authenticated_at
+ assert_equal identity_info, oidc_identity.info
+ assert_equal "issuer_mismatch", SsoAuditLog.by_event("login_failed").order(:created_at).last.metadata.fetch("reason")
+ end
+
+ test "rejects existing OIDC identity when provider is no longer configured" do
+ oidc_identity = oidc_identities(:bob_google)
+ oidc_identity.update!(issuer: nil)
+ # The callback strategy was registered at boot, but the live provider list
+ # no longer includes it after an administrator disables the DB provider.
+ AuthConfig.stubs(:sso_providers).returns([])
+ @user.sessions.destroy_all
+
+ setup_omniauth_mock(
+ provider: oidc_identity.provider,
+ uid: oidc_identity.uid,
+ email: @user.email,
+ name: "Disabled provider login"
+ )
+
+ assert_difference -> { SsoAuditLog.by_event("login_failed").count }, 1 do
+ assert_no_difference -> { SsoAuditLog.by_event("login").count } do
+ get "/auth/openid_connect/callback"
+ end
+ end
+
+ assert_redirected_to new_session_path
+ assert_not Session.exists?(user_id: @user.id)
+ assert_equal "provider_not_configured", SsoAuditLog.by_event("login_failed").order(:created_at).last.metadata.fetch("reason")
+ end
+
+ test "rejects new OIDC authentication when provider is no longer configured" do
+ AuthConfig.stubs(:sso_providers).returns([])
+ @user.sessions.destroy_all
+
+ setup_omniauth_mock(
+ provider: "openid_connect",
+ uid: "unconfigured-uid",
+ email: @user.email,
+ name: "Unconfigured provider"
+ )
+
+ assert_difference -> { SsoAuditLog.by_event("login_failed").count }, 1 do
+ assert_no_difference [ "OidcIdentity.count", "Session.count" ] do
+ get "/auth/openid_connect/callback"
+ end
+ end
+
+ assert_redirected_to new_session_path
+ assert_nil session[:pending_oidc_auth]
+ assert_equal "provider_not_configured", SsoAuditLog.by_event("login_failed").order(:created_at).last.metadata.fetch("reason")
+ end
+
+ test "routes a legacy OIDC identity without issuer through password verification" do
+ oidc_identity = oidc_identities(:bob_google)
+ oidc_identity.update!(issuer: nil)
+ AuthConfig.stubs(:sso_providers).returns([
+ { name: oidc_identity.provider, strategy: "openid_connect", issuer: "https://test.example.com" }
+ ])
+ @user.sessions.destroy_all
+
+ setup_omniauth_mock(
+ provider: oidc_identity.provider,
+ uid: oidc_identity.uid,
+ email: @user.email,
+ name: "Bob Dylan"
+ )
+
+ assert_no_difference "Session.count" do
+ assert_no_difference -> { SsoAuditLog.by_event("login").count } do
+ get "/auth/openid_connect/callback"
+ end
+ end
+
+ assert_redirected_to link_oidc_account_path
+ assert session[:pending_oidc_legacy_relink]
+ assert_equal "https://test.example.com", session[:pending_oidc_auth].fetch("issuer")
+ end
+
+ test "an issuerless SSO-only identity requires administrator recovery" do
+ identity = oidc_identities(:sso_only_identity)
+ identity.update!(issuer: nil)
+ identity.user.sessions.destroy_all
+ setup_omniauth_mock(
+ provider: identity.provider, uid: identity.uid,
+ email: identity.user.email, name: identity.user.display_name
+ )
+
+ assert_no_difference [ "Session.count", -> { SsoAuditLog.by_event("login").count } ] do
+ get "/auth/openid_connect/callback"
+ end
+
+ assert_redirected_to link_oidc_account_path
+ assert session[:pending_oidc_legacy_relink]
+ assert_equal I18n.t("sessions.openid_connect.legacy_issuer_relink_required"), flash[:alert]
+ assert_nil identity.reload.issuer
+ assert_not identity.user.has_local_password?
+ end
+
+ test "a fresh OIDC sign-in clears an abandoned legacy relink" do
+ legacy_identity = oidc_identities(:bob_google)
+ legacy_identity.update!(issuer: nil)
+ @user.sessions.destroy_all
+ setup_omniauth_mock(
+ provider: legacy_identity.provider, uid: legacy_identity.uid,
+ email: @user.email, name: "Bob Dylan"
+ )
+ get "/auth/openid_connect/callback"
+ assert session[:pending_oidc_legacy_relink]
+
+ user = users(:new_email)
+ setup_omniauth_mock(
+ provider: legacy_identity.provider, uid: "fresh-identity-after-legacy",
+ email: user.email, name: "New User"
+ )
+ get "/auth/openid_connect/callback"
+
+ assert_redirected_to link_oidc_account_path
+ assert_nil session[:pending_oidc_legacy_relink]
+ assert_equal "fresh-identity-after-legacy", session[:pending_oidc_auth].fetch("uid")
+
+ post create_link_oidc_account_path, params: { email: user.email, password: user_password_test }
+
+ assert_redirected_to root_path
+ assert_equal user.id, OidcIdentity.find_by!(uid: "fresh-identity-after-legacy").user_id
+ assert_nil legacy_identity.reload.issuer
+ end
+
test "rejects an SSO identity that an administrator permanently removed" do
oidc_identity = oidc_identities(:bob_google)
SsoIdentityBlock.block_all!(OidcIdentity.where(id: oidc_identity.id), identity_label: @user.email)
@@ -485,6 +641,7 @@ class SessionsControllerTest < ActionDispatch::IntegrationTest
get "/auth/openid_connect/callback"
assert_redirected_to link_oidc_account_path
+ assert_equal "https://test.example.com", session[:pending_oidc_auth].fetch("issuer")
# Follow redirect to verify session data is accessible
follow_redirect!
@@ -967,6 +1124,7 @@ class SessionsControllerTest < ActionDispatch::IntegrationTest
assert_equal "unlinked-uid-99999", cached[:uid]
assert_equal user_without_oidc.email, cached[:email]
assert_equal "New User", cached[:name]
+ assert_equal "https://test.example.com", cached[:issuer]
assert cached.key?(:device_info), "Expected device_info in cached payload"
assert cached.key?(:allow_account_creation), "Expected allow_account_creation in cached payload"
ensure
@@ -1208,6 +1366,29 @@ class SessionsControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to new_session_path
end
+ test "desktop_sso_start accepts a database provider added after boot" do
+ original_sso_providers = Rails.configuration.x.auth.sso_providers
+ Rails.configuration.x.auth.sso_providers = [
+ { name: "boot_provider", strategy: "openid_connect", label: "Boot provider" }
+ ]
+ FeatureFlags.stubs(:db_sso_providers?).returns(true)
+ ProviderLoader.stubs(:load_providers).returns([
+ {
+ "name" => "authentik",
+ "strategy" => "openid_connect",
+ "label" => "Sign in with Authentik",
+ "settings" => { "default_role" => "super_admin" }
+ }
+ ])
+
+ get "/auth/desktop/authentik", params: { code_challenge: "a" * 43 }
+
+ assert_response :success
+ assert_match %r{action="/auth/authentik"}, @response.body
+ ensure
+ Rails.configuration.x.auth.sso_providers = original_sso_providers
+ end
+
test "a session inactive past the timeout is rejected and destroyed" do
sign_in @user
session_record = Session.order(created_at: :desc).first
@@ -1313,7 +1494,12 @@ class SessionsControllerTest < ActionDispatch::IntegrationTest
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")
+ second = @user.oidc_identities.create!(provider: "other_idp", uid: "other-idp-uid-1", issuer: "https://test.example.com")
+ AuthConfig.stubs(:sso_providers).returns(
+ [ first.provider, second.provider ].map do |name|
+ { name: name, strategy: "openid_connect", issuer: "https://test.example.com", label: name }
+ end
+ )
setup_omniauth_mock(
provider: first.provider,
diff --git a/test/controllers/settings/securities_controller_test.rb b/test/controllers/settings/securities_controller_test.rb
index 8770f2e3ee..1f14433e38 100644
--- a/test/controllers/settings/securities_controller_test.rb
+++ b/test/controllers/settings/securities_controller_test.rb
@@ -134,6 +134,7 @@ class Settings::SecuritiesControllerTest < ActionDispatch::IntegrationTest
provider: identity.provider,
uid: identity.uid,
info: { email: identity.user.email, name: identity.user.display_name },
+ extra: { raw_info: { iss: identity.issuer } },
credentials: {}
)
get "/auth/openid_connect/callback"
diff --git a/test/fixtures/oidc_identities.yml b/test/fixtures/oidc_identities.yml
index 030cab9342..4b7449e2dc 100644
--- a/test/fixtures/oidc_identities.yml
+++ b/test/fixtures/oidc_identities.yml
@@ -1,6 +1,7 @@
bob_google:
user: family_admin
provider: openid_connect
+ issuer: https://test.example.com
uid: google-uid-12345
info:
@@ -12,6 +13,7 @@ bob_google:
jakob_google:
user: family_member
provider: openid_connect
+ issuer: https://test.example.com
uid: google-uid-67890
info:
@@ -23,6 +25,7 @@ jakob_google:
sso_only_identity:
user: sso_only
provider: openid_connect
+ issuer: https://test.example.com
uid: sso-only-uid-12345
info:
diff --git a/test/models/oidc_identity_test.rb b/test/models/oidc_identity_test.rb
index e6d6a9a100..4178f5ac17 100644
--- a/test/models/oidc_identity_test.rb
+++ b/test/models/oidc_identity_test.rb
@@ -180,6 +180,7 @@ class OidcIdentityTest < ActiveSupport::TestCase
end
test "creates from omniauth hash" do
+ AuthConfig.stubs(:sso_providers).returns([ { name: "google_oauth2", strategy: "google_oauth2" } ])
auth = OmniAuth::AuthHash.new({
provider: "google_oauth2",
uid: "google-123456",
@@ -202,7 +203,80 @@ class OidcIdentityTest < ActiveSupport::TestCase
assert_not_nil identity.last_authenticated_at
end
+ test "issuer validation trims configured whitespace and preserves trailing slashes" do
+ issuer = "https://idp.example.com/"
+ config = { name: @oidc_identity.provider, strategy: "openid_connect", issuer: " #{issuer}\n" }
+ auth = OmniAuth::AuthHash.new(provider: @oidc_identity.provider, extra: { raw_info: { iss: issuer } })
+
+ assert_equal issuer, OidcIdentity.verified_issuer_for!(auth, config)
+ @oidc_identity.update!(issuer: issuer)
+ assert @oidc_identity.issuer_matches_config?(config)
+
+ auth.extra.raw_info.iss = issuer.delete_suffix("/")
+ assert_raises(OidcIdentity::IssuerMismatch) { OidcIdentity.verified_issuer_for!(auth, config) }
+ assert_not @oidc_identity.issuer_matches_config?(config.merge(issuer: issuer.delete_suffix("/")))
+ end
+
+ test "does not accept an issuerless OIDC identity as matching the active provider" do
+ @oidc_identity.update!(issuer: nil)
+
+ assert_not @oidc_identity.issuer_matches_config?(
+ name: @oidc_identity.provider,
+ strategy: "openid_connect",
+ issuer: "https://idp.example.com"
+ )
+ end
+
+ test "does not create an OIDC identity without a verified issuer" do
+ AuthConfig.stubs(:sso_providers).returns([
+ { name: "test_oidc", strategy: "openid_connect", issuer: "https://idp.example.com" }
+ ])
+ auth = OmniAuth::AuthHash.new(
+ provider: "test_oidc",
+ uid: "missing-issuer-uid",
+ info: { email: "[email protected]" },
+ extra: { raw_info: {} }
+ )
+
+ assert_no_difference "OidcIdentity.count" do
+ assert_raises(OidcIdentity::IssuerMismatch) { OidcIdentity.create_from_omniauth(auth, @user) }
+ end
+ end
+
+ test "does not create an identity after its provider is removed" do
+ AuthConfig.stubs(:sso_providers).returns([])
+ auth = OmniAuth::AuthHash.new(
+ provider: "removed_provider",
+ uid: "removed-provider-uid",
+ info: { email: "[email protected]" }
+ )
+
+ assert_no_difference "OidcIdentity.count" do
+ assert_raises(OidcIdentity::ProviderNotConfigured) { OidcIdentity.create_from_omniauth(auth, @user) }
+ end
+ end
+
+ test "does not rebind a legacy OIDC identity to a different local user" do
+ @oidc_identity.update!(issuer: nil)
+ AuthConfig.stubs(:sso_providers).returns([
+ { name: @oidc_identity.provider, strategy: "openid_connect", issuer: "https://test.example.com" }
+ ])
+ auth = OmniAuth::AuthHash.new(
+ provider: @oidc_identity.provider,
+ uid: @oidc_identity.uid,
+ info: { email: "[email protected]" },
+ extra: { raw_info: { iss: "https://test.example.com" } }
+ )
+
+ assert_raises(OidcIdentity::LegacyIdentityRebindRejected) do
+ OidcIdentity.rebind_legacy_issuer_from_omniauth!(auth, users(:family_member))
+ end
+ assert_nil @oidc_identity.reload.issuer
+ assert_equal @user, @oidc_identity.user
+ end
+
test "refuses to create an identity after it is blocked" do
+ AuthConfig.stubs(:sso_providers).returns([ { name: "google_oauth2", strategy: "google_oauth2" } ])
auth = OmniAuth::AuthHash.new({
provider: "google_oauth2",
uid: "blocked-google-subject",
diff --git a/test/models/omniauth_provider_registry_test.rb b/test/models/omniauth_provider_registry_test.rb
new file mode 100644
index 0000000000..e8509b0011
--- /dev/null
+++ b/test/models/omniauth_provider_registry_test.rb
@@ -0,0 +1,249 @@
+require "test_helper"
+
+class OmniauthProviderRegistryTest < ActiveSupport::TestCase
+ setup do
+ @previous_test_mode = OmniAuth.config.test_mode
+ @previous_mock_auth = OmniAuth.config.mock_auth.dup
+ @previous_sso_providers = Rails.configuration.x.auth.sso_providers
+ OmniAuth.config.test_mode = true
+ end
+
+ teardown do
+ OmniAuth.config.test_mode = @previous_test_mode
+ OmniAuth.config.mock_auth = @previous_mock_auth
+ Rails.configuration.x.auth.sso_providers = @previous_sso_providers
+ end
+
+ test "registers custom database OIDC provider callbacks dynamically" do
+ FeatureFlags.stubs(:db_sso_providers?).returns(true)
+ ProviderLoader.stubs(:load_providers).returns([ custom_oidc_provider ])
+
+ OmniAuth.config.mock_auth[:authentik] = OmniAuth::AuthHash.new(
+ provider: "authentik",
+ uid: "uid-123",
+ info: { email: "[email protected]" }
+ )
+
+ response = Rack::MockRequest.new(dynamic_omniauth_app).get("/auth/authentik/callback")
+
+ assert_equal 200, response.status
+ assert_equal "authentik", response.body
+ end
+
+ test "dynamic OIDC setup uses the custom provider name and redirect URI" do
+ registration = OmniauthProviderRegistry.registration_for(custom_oidc_provider)
+
+ assert_equal :openid_connect, registration.strategy
+ assert_equal :authentik, registration.options[:name]
+ assert_equal "https://app.example.com/auth/authentik/callback", registration.options.dig(:client_options, :redirect_uri)
+ assert_equal "login", registration.options[:prompt]
+ assert registration.options.dig(:extra_authorize_params, :claims).present?
+ assert_equal "authentik", registration.config[:name]
+ end
+
+ test "database OIDC configuration is not also registered statically" do
+ FeatureFlags.stubs(:db_sso_providers?).returns(true)
+ builder = mock("omniauth builder")
+ builder.expects(:provider).never
+
+ config = OmniauthProviderRegistry.register(builder, custom_oidc_provider)
+ assert_equal "authentik", config[:name]
+ end
+
+ test "a disabled provider is no longer intercepted by a builder created while it was enabled" do
+ FeatureFlags.stubs(:db_sso_providers?).returns(true)
+ providers = [ custom_oidc_provider ]
+ ProviderLoader.stubs(:load_providers).returns(providers)
+ app = Rack::Builder.new do
+ use Rack::Session::Cookie, secret: "a" * 64
+ use OmniAuth::Builder do
+ OmniauthProviderRegistry.register_dynamic_database_oidc_provider(self)
+ OmniauthProviderRegistry.register(self, providers.first)
+ end
+ run ->(env) { [ 200, { "content-type" => "text/plain" }, [ env["omniauth.auth"] ? "authenticated" : "no auth" ] ] }
+ end.to_app
+ OmniAuth.config.mock_auth[:authentik] = OmniAuth::AuthHash.new(provider: "authentik", uid: "uid-123")
+ assert_equal "authenticated", Rack::MockRequest.new(app).get("/auth/authentik/callback").body
+
+ ProviderLoader.stubs(:load_providers).returns([])
+ assert_equal "no auth", Rack::MockRequest.new(app).get("/auth/authentik/callback").body
+ end
+
+ test "does not intercept incomplete database OIDC providers" do
+ Rails.env.stubs(:test?).returns(false)
+ FeatureFlags.stubs(:db_sso_providers?).returns(true)
+ ProviderLoader.stubs(:load_providers).returns([
+ custom_oidc_provider.except(:client_secret)
+ ])
+
+ response = Rack::MockRequest.new(dynamic_omniauth_app).get("/auth/authentik/callback")
+
+ assert_equal 200, response.status
+ assert_equal "no auth", response.body
+ end
+
+ test "an incomplete provider is reported once until its configuration changes" do
+ Rails.env.stubs(:test?).returns(false)
+ OmniauthProviderRegistry::SKIPPED_PROVIDERS.clear
+ incomplete = custom_oidc_provider.except(:client_secret)
+ warning = "[OmniAuth] Skipping OIDC provider 'authentik' - missing required configuration"
+
+ Rails.logger.expects(:warn).with(warning).twice
+ 2.times { assert_nil OmniauthProviderRegistry.registration_for(incomplete) }
+
+ assert OmniauthProviderRegistry.registration_for(custom_oidc_provider)
+ assert_nil OmniauthProviderRegistry.registration_for(incomplete)
+ ensure
+ OmniauthProviderRegistry::SKIPPED_PROVIDERS.clear
+ end
+
+ test "auth config returns current database providers instead of stale boot providers" do
+ FeatureFlags.stubs(:db_sso_providers?).returns(true)
+ Rails.configuration.x.auth.sso_providers = [
+ { id: "oidc", strategy: "openid_connect", name: "openid_connect" }
+ ]
+ provider = custom_oidc_provider.deep_stringify_keys
+ provider["settings"]["default_role"] = "super_admin"
+ ProviderLoader.stubs(:load_providers).returns([ provider ])
+
+ providers = AuthConfig.sso_providers
+
+ assert_equal [ "authentik" ], providers.map { |provider| provider[:name] }
+ assert_equal "super_admin", providers.first.dig(:settings, :default_role)
+ end
+
+ test "non-OIDC providers are listed only after their named strategy is registered" do
+ FeatureFlags.stubs(:db_sso_providers?).returns(true)
+ providers = [
+ { name: "new_google", strategy: "google_oauth2", client_id: "client-id", client_secret: "client-secret" },
+ { name: "new_github", strategy: "github", client_id: "client-id", client_secret: "client-secret" },
+ { name: "new_saml", strategy: "saml", settings: { idp_sso_url: "https://idp.example.com/saml" } }
+ ]
+
+ providers.each do |provider|
+ ProviderLoader.stubs(:load_providers).returns([ provider ])
+ Rails.configuration.x.auth.sso_providers = [ custom_oidc_provider ]
+ assert_empty AuthConfig.sso_providers, "#{provider[:strategy]} needs a registered route"
+
+ Rails.configuration.x.auth.sso_providers = [ provider ]
+ assert_equal [ provider[:name] ], AuthConfig.sso_providers.map { |config| config[:name] }
+ end
+ end
+
+ test "auth config excludes unconfigured strategies from database YAML fallback" do
+ Rails.env.stubs(:test?).returns(false)
+ FeatureFlags.stubs(:db_sso_providers?).returns(true)
+ SsoProvider.stubs(:enabled).returns(SsoProvider.none)
+ Rails.application.stubs(:config_for).with(:auth).returns(
+ "providers" => [
+ custom_oidc_provider.deep_stringify_keys,
+ { "name" => "google_oauth2", "strategy" => "google_oauth2" },
+ { "name" => "github", "strategy" => "github" }
+ ]
+ )
+ ProviderLoader.clear_cache
+
+ with_env_overrides(
+ GOOGLE_OAUTH_CLIENT_ID: nil, GOOGLE_OAUTH_CLIENT_SECRET: nil,
+ GITHUB_CLIENT_ID: nil, GITHUB_CLIENT_SECRET: nil
+ ) do
+ assert_equal [ "authentik" ], AuthConfig.sso_providers.map { |provider| provider[:name] }
+ end
+ ensure
+ ProviderLoader.clear_cache
+ end
+
+ test "dynamic OIDC route matches a provider configured with only an id" do
+ FeatureFlags.stubs(:db_sso_providers?).returns(true)
+ ProviderLoader.stubs(:load_providers).returns([ custom_oidc_provider.except(:name) ])
+ OmniAuth.config.mock_auth[:authentik] = OmniAuth::AuthHash.new(provider: "authentik", uid: "uid-123")
+
+ response = Rack::MockRequest.new(dynamic_omniauth_app).get("/auth/authentik/callback")
+
+ assert_equal "authentik", response.body
+ end
+
+ test "dynamic OIDC route accepts a callback with a trailing slash" do
+ FeatureFlags.stubs(:db_sso_providers?).returns(true)
+ ProviderLoader.stubs(:load_providers).returns([ custom_oidc_provider ])
+ OmniAuth.config.mock_auth[:authentik] = OmniAuth::AuthHash.new(provider: "authentik", uid: "uid-123")
+
+ response = Rack::MockRequest.new(dynamic_omniauth_app).get("/auth/authentik/callback/")
+
+ assert_equal "authentik", response.body
+ end
+
+ test "dynamic OIDC route supports YAML providers returned by the active provider loader" do
+ FeatureFlags.stubs(:db_sso_providers?).returns(true)
+ ProviderLoader.stubs(:load_providers).returns([ custom_oidc_provider.deep_stringify_keys ])
+
+ OmniAuth.config.mock_auth[:authentik] = OmniAuth::AuthHash.new(
+ provider: "authentik",
+ uid: "uid-123",
+ info: { email: "[email protected]" }
+ )
+
+ response = Rack::MockRequest.new(dynamic_omniauth_app).get("/auth/authentik/callback")
+
+ assert_equal 200, response.status
+ assert_equal "authentik", response.body
+ end
+
+ test "dynamic OIDC route uses YAML providers when no database providers are enabled" do
+ Rails.env.stubs(:test?).returns(false)
+ FeatureFlags.stubs(:db_sso_providers?).returns(true)
+ SsoProvider.stubs(:enabled).returns(SsoProvider.none)
+ Rails.application.stubs(:config_for).with(:auth).returns(
+ "providers" => [ custom_oidc_provider.deep_stringify_keys ]
+ )
+ ProviderLoader.clear_cache
+
+ OmniAuth.config.mock_auth[:authentik] = OmniAuth::AuthHash.new(
+ provider: "authentik",
+ uid: "uid-123",
+ info: { email: "[email protected]" }
+ )
+
+ response = Rack::MockRequest.new(dynamic_omniauth_app).get("/auth/authentik/callback")
+
+ assert_equal 200, response.status
+ assert_equal "authentik", response.body
+ ensure
+ ProviderLoader.clear_cache
+ end
+
+ private
+ # Build one Rack app to verify provider changes take effect without rebuilding middleware.
+ def dynamic_omniauth_app
+ Rack::Builder.new do
+ use Rack::Session::Cookie, secret: "a" * 64
+
+ use OmniAuth::Builder do
+ OmniauthProviderRegistry.register_dynamic_database_oidc_provider(self)
+ end
+
+ run lambda { |env|
+ auth = env["omniauth.auth"]
+ [ 200, { "content-type" => "text/plain" }, [ auth&.provider || "no auth" ] ]
+ }
+ end.to_app
+ end
+
+ # Create an enabled custom-named database OIDC provider for dynamic route tests.
+ def custom_oidc_provider
+ {
+ id: "authentik",
+ strategy: "openid_connect",
+ name: "authentik",
+ label: "Sign in with Authentik",
+ issuer: "https://idp.example.com",
+ client_id: "client-id",
+ client_secret: "client-secret",
+ redirect_uri: "https://app.example.com/auth/authentik/callback",
+ settings: {
+ scopes: "openid email profile groups",
+ prompt: "login"
+ }
+ }
+ end
+end