Module: BetterAuth::Plugins

Defined in:
lib/better_auth/plugins/sso.rb

Constant Summary collapse

SSO_ERROR_CODES =
{
  "PROVIDER_NOT_FOUND" => "No provider found",
  "INVALID_STATE" => "Invalid state",
  "SAML_RESPONSE_REPLAYED" => "SAML response has already been used",
  "SINGLE_LOGOUT_NOT_ENABLED" => "Single Logout is not enabled",
  "INVALID_LOGOUT_REQUEST" => "Invalid LogoutRequest",
  "INVALID_LOGOUT_RESPONSE" => "Invalid LogoutResponse",
  "LOGOUT_FAILED_AT_IDP" => "Logout failed at IdP",
  "IDP_SLO_NOT_SUPPORTED" => "IdP does not support Single Logout Service"
}.freeze
SSO_SAML_SIGNATURE_ALGORITHMS =
{
  "rsa-sha1" => "http://www.w3.org/2000/09/xmldsig#rsa-sha1",
  "rsa-sha256" => "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
  "rsa-sha384" => "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384",
  "rsa-sha512" => "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512",
  "ecdsa-sha256" => "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256",
  "ecdsa-sha384" => "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384",
  "ecdsa-sha512" => "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512",
  "sha1" => "http://www.w3.org/2000/09/xmldsig#rsa-sha1",
  "sha256" => "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
  "sha384" => "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384",
  "sha512" => "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"
}.freeze
SSO_SAML_DIGEST_ALGORITHMS =
{
  "sha1" => "http://www.w3.org/2000/09/xmldsig#sha1",
  "sha256" => "http://www.w3.org/2001/04/xmlenc#sha256",
  "sha384" => "http://www.w3.org/2001/04/xmldsig-more#sha384",
  "sha512" => "http://www.w3.org/2001/04/xmlenc#sha512"
}.freeze
SSO_SAML_SECURE_SIGNATURE_ALGORITHMS =
(SSO_SAML_SIGNATURE_ALGORITHMS.values - ["http://www.w3.org/2000/09/xmldsig#rsa-sha1"]).uniq.freeze
SSO_SAML_SECURE_DIGEST_ALGORITHMS =
(SSO_SAML_DIGEST_ALGORITHMS.values - ["http://www.w3.org/2000/09/xmldsig#sha1"]).uniq.freeze
SSO_SAML_SECURE_KEY_ENCRYPTION_ALGORITHMS =
%w[
  http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p
  http://www.w3.org/2009/xmlenc11#rsa-oaep
].freeze
SSO_SAML_SECURE_DATA_ENCRYPTION_ALGORITHMS =
%w[
  http://www.w3.org/2001/04/xmlenc#aes128-cbc
  http://www.w3.org/2001/04/xmlenc#aes192-cbc
  http://www.w3.org/2001/04/xmlenc#aes256-cbc
  http://www.w3.org/2009/xmlenc11#aes128-gcm
  http://www.w3.org/2009/xmlenc11#aes192-gcm
  http://www.w3.org/2009/xmlenc11#aes256-gcm
].freeze
SSO_DEFAULT_MAX_SAML_RESPONSE_SIZE =
256 * 1024
SSO_DEFAULT_MAX_SAML_METADATA_SIZE =
100 * 1024
SSO_SAML_RELAY_STATE_KEY_PREFIX =
"saml-relay-state:"
SSO_SAML_AUTHN_REQUEST_KEY_PREFIX =
"saml-authn-request:"
SSO_DEFAULT_AUTHN_REQUEST_TTL_MS =
5 * 60 * 1000
SSO_SAML_USED_ASSERTION_KEY_PREFIX =
"saml-used-assertion:"
SSO_DEFAULT_ASSERTION_TTL_MS =
15 * 60 * 1000
SSO_DEFAULT_CLOCK_SKEW_MS =
5 * 60 * 1000
SSO_SAML_SESSION_KEY_PREFIX =
"saml-session:"
SSO_SAML_SESSION_BY_ID_KEY_PREFIX =
"saml-session-by-id:"
SSO_SAML_LOGOUT_REQUEST_KEY_PREFIX =
"saml-logout-request:"
SSO_SAML_STATUS_SUCCESS =
"urn:oasis:names:tc:SAML:2.0:status:Success"
SSO_DEFAULT_LOGOUT_REQUEST_TTL_MS =
5 * 60 * 1000

Class Method Summary collapse

Class Method Details

.sso(options = {}) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/better_auth/plugins/sso.rb', line 83

def sso(options = {})
  config = normalize_hash(options)
  if defined?(BetterAuth::SSO::SAML) && defined?(BetterAuth::SSO::SAMLHooks)
    config = BetterAuth::SSO::SAMLHooks.merge_options(BetterAuth::SSO::SAML.sso_options, config)
  end
  endpoints = BetterAuth::SSO::Routes::SSO.endpoints(config)
  Plugin.new(
    id: "sso",
    init: ->(_ctx) { {options: {advanced: {disable_origin_check: ["/sso/saml2/callback", "/sso/saml2/sp/acs", "/sso/saml2/sp/slo"]}}} },
    schema: BetterAuth::SSO::Routes::Schemas.plugin_schema(config),
    endpoints: endpoints,
    error_codes: SSO_ERROR_CODES,
    options: config
  )
end

.sso_append_error(url, error, description = nil) ⇒ Object



1473
1474
1475
1476
1477
# File 'lib/better_auth/plugins/sso.rb', line 1473

def sso_append_error(url, error, description = nil)
  separator = url.to_s.include?("?") ? "&" : "?"
  query = {error: error, error_description: description}.compact
  "#{url}#{separator}#{URI.encode_www_form(query)}"
end

.sso_assign_organization_membership(ctx, provider, user, config) ⇒ Object



980
981
982
983
984
985
986
987
988
989
990
991
992
993
# File 'lib/better_auth/plugins/sso.rb', line 980

def sso_assign_organization_membership(ctx, provider, user, config)
  organization_id = provider["organizationId"]
  return if organization_id.to_s.empty?
  return if config.dig(:organization_provisioning, :disabled)
  return unless ctx.context.options.plugins.any? { |plugin| plugin.id == "organization" }
  return if ctx.context.adapter.find_one(model: "member", where: [{field: "organizationId", value: organization_id}, {field: "userId", value: user.fetch("id")}])

  role = if config.dig(:organization_provisioning, :get_role).respond_to?(:call)
    config.dig(:organization_provisioning, :get_role).call(user: user, userInfo: {}, provider: provider)
  else
    config.dig(:organization_provisioning, :default_role) || config.dig(:organization_provisioning, :role) || "member"
  end
  ctx.context.adapter.create(model: "member", data: {organizationId: organization_id, userId: user.fetch("id"), role: role, createdAt: Time.now})
end

.sso_authorize_domain_verification!(ctx, provider, user_id) ⇒ Object

Raises:

  • (APIError)


1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
# File 'lib/better_auth/plugins/sso.rb', line 1620

def sso_authorize_domain_verification!(ctx, provider, user_id)
  organization_id = provider["organizationId"]
  is_org_member = true
  if organization_id
    is_org_member = !!ctx.context.adapter.find_one(
      model: "member",
      where: [{field: "userId", value: user_id}, {field: "organizationId", value: organization_id}]
    )
  end
  return if provider["userId"] == user_id && is_org_member

  raise APIError.new("FORBIDDEN", message: "User must be owner of or belong to the SSO provider organization", code: "INSUFICCIENT_ACCESS")
end

.sso_base64_urlsafe(value) ⇒ Object



1512
1513
1514
# File 'lib/better_auth/plugins/sso.rb', line 1512

def sso_base64_urlsafe(value)
  Base64.strict_encode64(value).tr("+/", "-_").delete("=")
end

.sso_base64_xml?(value) ⇒ Boolean

Returns:

  • (Boolean)


1063
1064
1065
1066
1067
# File 'lib/better_auth/plugins/sso.rb', line 1063

def sso_base64_xml?(value)
  Base64.decode64(value.to_s).lstrip.start_with?("<")
rescue
  false
end

.sso_callback_provider(ctx, config, provider_id) ⇒ Object



1326
1327
1328
1329
1330
1331
1332
1333
# File 'lib/better_auth/plugins/sso.rb', line 1326

def sso_callback_provider(ctx, config, provider_id)
  if config[:default_sso]
    provider = sso_default_provider(config, provider_id: provider_id.to_s, domain: "")
    return provider if provider
  end

  ctx.context.adapter.find_one(model: "ssoProvider", where: [{field: "providerId", value: provider_id.to_s}])
end

.sso_context_domain_verification_enabled?(context) ⇒ Boolean

Returns:

  • (Boolean)


1691
1692
1693
1694
1695
# File 'lib/better_auth/plugins/sso.rb', line 1691

def sso_context_domain_verification_enabled?(context)
  context.options.plugins.any? do |plugin|
    plugin.id == "sso" && plugin.options.dig(:domain_verification, :enabled)
  end
end

.sso_decode_jwt_payload(token) ⇒ Object



1464
1465
1466
1467
1468
1469
1470
1471
# File 'lib/better_auth/plugins/sso.rb', line 1464

def sso_decode_jwt_payload(token)
  payload = token.to_s.split(".")[1]
  return {} unless payload

  JSON.parse(Base64.urlsafe_decode64(payload.ljust((payload.length + 3) & ~3, "=")))
rescue
  {}
end

.sso_decode_state(state, secret) ⇒ Object



1506
1507
1508
1509
1510
# File 'lib/better_auth/plugins/sso.rb', line 1506

def sso_decode_state(state, secret)
  BetterAuth::Crypto.verify_jwt(state.to_s, secret)
rescue
  nil
end

.sso_default_provider(config, provider_id:, domain:) ⇒ Object



1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
# File 'lib/better_auth/plugins/sso.rb', line 1479

def sso_default_provider(config, provider_id:, domain:)
  Array(config[:default_sso]).each do |raw_provider|
    default_provider = normalize_hash(raw_provider)
    next if !provider_id.empty? && default_provider[:provider_id].to_s != provider_id
    next if provider_id.empty? && default_provider[:domain].to_s.downcase != domain

    oidc_config = default_provider[:oidc_config] ? sso_storage_config(default_provider[:oidc_config]) : nil
    saml_config = default_provider[:saml_config] ? sso_storage_config(default_provider[:saml_config]) : nil
    return {
      "issuer" => default_provider[:issuer] || default_provider.dig(:oidc_config, :issuer) || default_provider.dig(:saml_config, :issuer) || "",
      "providerId" => default_provider.fetch(:provider_id),
      "userId" => "default",
      "domain" => default_provider[:domain],
      "domainVerified" => true,
      "oidcConfig" => oidc_config,
      "samlConfig" => saml_config
    }.compact
  end
  nil
end

.sso_delete_provider_endpointObject



280
281
282
283
284
285
286
287
288
289
# File 'lib/better_auth/plugins/sso.rb', line 280

def sso_delete_provider_endpoint
  Endpoint.new(path: "/sso/delete-provider", method: "POST") do |ctx|
    session = Routes.current_session(ctx)
    provider = sso_find_provider!(ctx, sso_fetch(ctx.body, :provider_id) || sso_fetch(ctx.params, :provider_id))
    raise APIError.new("FORBIDDEN", message: "You don't have access to this provider") unless sso_provider_access?(provider, session.fetch(:user).fetch("id"), ctx)

    ctx.context.adapter.delete(model: "ssoProvider", where: [{field: "id", value: provider.fetch("id")}])
    ctx.json({success: true})
  end
end

.sso_discover_oidc_config(issuer:, fetch: nil, existing_config: nil, discovery_endpoint: nil, trusted_origin: nil, timeout: nil) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/better_auth/plugins/sso.rb', line 103

def sso_discover_oidc_config(issuer:, fetch: nil, existing_config: nil, discovery_endpoint: nil, trusted_origin: nil, timeout: nil)
  existing = normalize_hash(existing_config || {})
  discovery_url = discovery_endpoint || existing[:discovery_endpoint] || "#{issuer.to_s.sub(%r{/+\z}, "")}/.well-known/openid-configuration"
  if trusted_origin && !trusted_origin.call(discovery_url)
    raise APIError.new("BAD_REQUEST", message: "OIDC discovery endpoint is not trusted")
  end
  document = if fetch
    fetch.call(discovery_url)
  else
    uri = URI(discovery_url)
    JSON.parse(Net::HTTP.get(uri))
  end
  document = normalize_hash(document)
  valid = document[:issuer].to_s.sub(%r{/+\z}, "") == issuer.to_s.sub(%r{/+\z}, "") &&
    !document[:authorization_endpoint].to_s.empty? &&
    !document[:token_endpoint].to_s.empty? &&
    !document[:jwks_uri].to_s.empty?
  raise APIError.new("BAD_REQUEST", message: "Invalid OIDC discovery document") unless valid

  authorization_endpoint = sso_normalize_discovery_url(document[:authorization_endpoint], issuer, trusted_origin)
  token_endpoint = sso_normalize_discovery_url(document[:token_endpoint], issuer, trusted_origin)
  jwks_endpoint = sso_normalize_discovery_url(document[:jwks_uri], issuer, trusted_origin)
   = document[:userinfo_endpoint] && sso_normalize_discovery_url(document[:userinfo_endpoint], issuer, trusted_origin)
  auth_methods = Array(document[:token_endpoint_auth_methods_supported])
  token_endpoint_authentication = if existing[:token_endpoint_authentication]
    existing[:token_endpoint_authentication]
  elsif auth_methods.include?("client_secret_post") && !auth_methods.include?("client_secret_basic")
    "client_secret_post"
  else
    "client_secret_basic"
  end

  {
    issuer: existing[:issuer] || document[:issuer],
    discovery_endpoint: existing[:discovery_endpoint] || discovery_url,
    client_id: existing[:client_id],
    authorization_endpoint: existing[:authorization_endpoint] || authorization_endpoint,
    token_endpoint: existing[:token_endpoint] || token_endpoint,
    jwks_endpoint: existing[:jwks_endpoint] || jwks_endpoint,
    user_info_endpoint: existing[:user_info_endpoint] || ,
    token_endpoint_authentication: token_endpoint_authentication,
    scopes_supported: existing[:scopes_supported] || document[:scopes_supported]
  }.compact
rescue APIError
  raise
rescue
  raise APIError.new("BAD_REQUEST", message: "Invalid OIDC discovery document")
end

.sso_domain_verification_identifier(config, provider_id) ⇒ Object



1634
1635
1636
1637
# File 'lib/better_auth/plugins/sso.rb', line 1634

def sso_domain_verification_identifier(config, provider_id)
  prefix = config.dig(:domain_verification, :token_prefix) || "better-auth-token"
  "_#{prefix}-#{provider_id}"
end

.sso_email_domain_matches?(email_domain, provider_domain) ⇒ Boolean

Returns:

  • (Boolean)


1591
1592
1593
1594
1595
1596
1597
1598
1599
# File 'lib/better_auth/plugins/sso.rb', line 1591

def sso_email_domain_matches?(email_domain, provider_domain)
  email_domain = email_domain.to_s.strip.downcase
  email_domain = email_domain.split("@", 2).last if email_domain.include?("@")
  return false if email_domain.to_s.empty?

  provider_domain.to_s.split(",").map { |value| value.strip.downcase }.reject(&:empty?).any? do |domain|
    email_domain == domain || email_domain.end_with?(".#{domain}")
  end
end

.sso_ensure_runtime_oidc_provider(ctx, provider, plugin_config, require_jwks: false) ⇒ Object



1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
# File 'lib/better_auth/plugins/sso.rb', line 1562

def sso_ensure_runtime_oidc_provider(ctx, provider, plugin_config, require_jwks: false)
  oidc_config = normalize_hash(provider["oidcConfig"] || {})
  needs_discovery = sso_oidc_needs_runtime_discovery?(oidc_config) || (require_jwks && oidc_config[:jwks_endpoint].to_s.empty?)
  return provider if !needs_discovery

  discovered = sso_discover_oidc_config(
    issuer: provider.fetch("issuer"),
    existing_config: oidc_config.merge(issuer: provider.fetch("issuer")),
    fetch: plugin_config[:oidc_discovery_fetch],
    trusted_origin: ->(url) { ctx.context.trusted_origin?(url, allow_relative_paths: false) }
  )
  provider.merge("oidcConfig" => oidc_config.merge(discovered))
end

.sso_exchange_oidc_code(token_endpoint:, code:, code_verifier:, redirect_uri:, client_id:, client_secret:, authentication:) ⇒ Object



1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
# File 'lib/better_auth/plugins/sso.rb', line 1363

def sso_exchange_oidc_code(token_endpoint:, code:, code_verifier:, redirect_uri:, client_id:, client_secret:, authentication:)
  uri = URI(token_endpoint.to_s)
  request = Net::HTTP::Post.new(uri)
  form = {
    grant_type: "authorization_code",
    code: code,
    redirect_uri: redirect_uri,
    client_id: client_id,
    code_verifier: code_verifier
  }.compact
  if authentication.to_s == "client_secret_post"
    form[:client_secret] = client_secret
  elsif client_secret.to_s != ""
    request.basic_auth(client_id.to_s, client_secret.to_s)
  end
  request.set_form_data(form)
  response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") { |http| http.request(request) }
  return nil unless response.is_a?(Net::HTTPSuccess)

  normalize_hash(JSON.parse(response.body))
end

.sso_extract_saml_in_response_to(raw_response) ⇒ Object



1292
1293
1294
1295
1296
1297
# File 'lib/better_auth/plugins/sso.rb', line 1292

def sso_extract_saml_in_response_to(raw_response)
  xml = Base64.decode64(raw_response.to_s.gsub(/\s+/, ""))
  xml[/\bInResponseTo=['"]([^'"]+)['"]/, 1]
rescue
  nil
end

.sso_extract_saml_request_id(url) ⇒ Object



1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
# File 'lib/better_auth/plugins/sso.rb', line 1238

def sso_extract_saml_request_id(url)
  query = URI.decode_www_form(URI.parse(url.to_s).query.to_s).to_h
  encoded = query["SAMLRequest"]
  return nil if encoded.to_s.empty?

  xml = Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate(Base64.decode64(encoded))
  xml[/\bID=['"]([^'"]+)['"]/, 1]
rescue
  nil
end

.sso_fetch(data, key) ⇒ Object



1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
# File 'lib/better_auth/plugins/sso.rb', line 1758

def sso_fetch(data, key)
  return nil unless data.respond_to?(:[])

  compact = key.to_s.delete("_").downcase
  direct = data[key] ||
    data[key.to_s] ||
    data[Schema.storage_key(key)] ||
    data[Schema.storage_key(key).to_sym] ||
    data[compact] ||
    data[compact.to_sym]
  return direct unless direct.nil?

  data.each do |candidate, value|
    normalized = candidate.to_s.delete("_").downcase
    return value if normalized == compact
  end
  nil
end

.sso_fetch_oidc_jwks(jwks_endpoint, fetch: nil) ⇒ Object



1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
# File 'lib/better_auth/plugins/sso.rb', line 1450

def sso_fetch_oidc_jwks(jwks_endpoint, fetch: nil)
  if fetch.respond_to?(:call)
    return normalize_hash(fetch.call(jwks_endpoint))
  end

  uri = URI(jwks_endpoint.to_s)
  response = Net::HTTP.get_response(uri)
  return {} unless response.is_a?(Net::HTTPSuccess)

  normalize_hash(JSON.parse(response.body))
rescue
  {}
end

.sso_fetch_oidc_user_info(endpoint, access_token) ⇒ Object



1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
# File 'lib/better_auth/plugins/sso.rb', line 1420

def (endpoint, access_token)
  uri = URI(endpoint.to_s)
  request = Net::HTTP::Get.new(uri)
  request["authorization"] = "Bearer #{access_token}"
  response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") { |http| http.request(request) }
  return {} unless response.is_a?(Net::HTTPSuccess)

  JSON.parse(response.body)
rescue
  {}
end

.sso_find_or_create_user(ctx, provider, user_info, config = {}) ⇒ Object



590
591
592
# File 'lib/better_auth/plugins/sso.rb', line 590

def sso_find_or_create_user(ctx, provider, , config = {})
  sso_find_or_create_user_result(ctx, provider, , config).fetch(:user)
end

.sso_find_or_create_user_result(ctx, provider, user_info, config = {}) ⇒ Object



594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
# File 'lib/better_auth/plugins/sso.rb', line 594

def sso_find_or_create_user_result(ctx, provider, , config = {})
   = normalize_hash()
  email = [:email].to_s.downcase
   = ([:id] || ["id"]).to_s
  provider_id = provider.fetch("providerId")
  storage_provider_id = provider["samlConfig"] ? provider_id : "sso:#{provider_id}"
   = .empty? ? nil : (
    ctx.context.internal_adapter.(, provider_id) ||
      ctx.context.internal_adapter.(, "sso:#{provider_id}")
  )
  if 
    user = ctx.context.internal_adapter.find_user_by_id(.fetch("userId"))
    created = false
  elsif (found = ctx.context.internal_adapter.find_user_by_email(email, include_accounts: true))
    already_linked_provider = Array(found[:accounts]).any? do ||
      [provider_id, "sso:#{provider_id}"].include?(["providerId"])
    end
    if provider["samlConfig"]
      return {error: "account_not_linked"} unless already_linked_provider || sso_saml_trusted_provider?(ctx, provider, email)
    end

    user = found[:user]
    unless .empty?
      ctx.context.internal_adapter.(
        accountId: ,
        providerId: storage_provider_id,
        userId: user.fetch("id")
      )
    end
    oidc_config = normalize_hash(provider["oidcConfig"] || {})
    if oidc_config[:override_user_info] || config[:default_override_user_info]
      update = {}
      update[:name] = [:name] if .key?(:name)
      update[:image] = [:image] if .key?(:image)
      update[:emailVerified] = !![:email_verified] if .key?(:email_verified)
      user = ctx.context.internal_adapter.update_user(user.fetch("id"), update) if update.any?
    end
    created = false
  else
    created = ctx.context.internal_adapter.create_user(
      email: email,
      name: [:name] || email,
      emailVerified: .key?(:email_verified) ? [:email_verified] : false,
      image: [:image]
    )
    ctx.context.internal_adapter.(
      accountId: .empty? ? created.fetch("id") : ,
      providerId: storage_provider_id,
      userId: created.fetch("id")
    )
    user = created
    created = true
  end
  sso_assign_organization_membership(ctx, provider, user, config)
  {user: user, created: created}
end

.sso_find_provider!(ctx, provider_id) ⇒ Object

Raises:

  • (APIError)


1601
1602
1603
1604
1605
1606
# File 'lib/better_auth/plugins/sso.rb', line 1601

def sso_find_provider!(ctx, provider_id)
  provider = ctx.context.adapter.find_one(model: "ssoProvider", where: [{field: "providerId", value: provider_id.to_s}])
  raise APIError.new("NOT_FOUND", message: "Provider not found", code: "PROVIDER_NOT_FOUND") unless provider

  provider
end

.sso_future_time?(value) ⇒ Boolean

Returns:

  • (Boolean)


1639
1640
1641
1642
1643
1644
# File 'lib/better_auth/plugins/sso.rb', line 1639

def sso_future_time?(value)
  time = value.is_a?(Time) ? value : Time.parse(value.to_s)
  time > Time.now
rescue
  false
end

.sso_generate_saml_relay_state(ctx, state_data) ⇒ Object



1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
# File 'lib/better_auth/plugins/sso.rb', line 1138

def sso_generate_saml_relay_state(ctx, state_data)
  ttl_ms = 10 * 60 * 1000
  relay_state = BetterAuth::Crypto.random_string(32)
  now_ms = (Time.now.to_f * 1000).to_i
  stored = state_data.each_with_object({}) { |(key, value), result| result[key.to_s] = value }.merge(
    "codeVerifier" => BetterAuth::Crypto.random_string(128),
    "expiresAt" => now_ms + ttl_ms
  )
  ctx.context.internal_adapter.create_verification_value(
    identifier: "#{SSO_SAML_RELAY_STATE_KEY_PREFIX}#{relay_state}",
    value: JSON.generate(stored),
    expiresAt: Time.at((now_ms + ttl_ms) / 1000.0)
  )
  ctx.set_signed_cookie("relay_state", relay_state, ctx.context.secret, path: "/", max_age: ttl_ms / 1000, http_only: true, same_site: "lax")
  relay_state
end

.sso_get_provider_endpointObject



238
239
240
241
242
243
244
245
246
# File 'lib/better_auth/plugins/sso.rb', line 238

def sso_get_provider_endpoint
  Endpoint.new(path: "/sso/get-provider", method: "GET") do |ctx|
    session = Routes.current_session(ctx)
    provider = sso_find_provider!(ctx, sso_fetch(ctx.query, :provider_id) || sso_fetch(ctx.params, :provider_id))
    raise APIError.new("FORBIDDEN", message: "You don't have access to this provider") unless sso_provider_access?(provider, session.fetch(:user).fetch("id"), ctx)

    ctx.json(sso_sanitize_provider(provider, ctx.context))
  end
end

.sso_handle_oidc_callback(ctx, config, provider_id, state: nil) ⇒ Object



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'lib/better_auth/plugins/sso.rb', line 344

def sso_handle_oidc_callback(ctx, config, provider_id, state: nil)
  state ||= sso_verify_state(ctx.query[:state] || ctx.query["state"], ctx.context.secret)
  return ctx.redirect("#{ctx.context.base_url}/error?error=invalid_state") unless state

  callback_url = state["callbackURL"] || "/"
  error_url = state["errorURL"] || callback_url
  if ctx.query[:error] || ctx.query["error"]
    error = ctx.query[:error] || ctx.query["error"]
    description = ctx.query[:error_description] || ctx.query["error_description"]
    return sso_redirect(ctx, sso_append_error(error_url, error, description))
  end

  provider = sso_callback_provider(ctx, config, provider_id)
  return sso_redirect(ctx, sso_append_error(error_url, "invalid_provider", "provider not found")) unless provider
  if config.dig(:domain_verification, :enabled) && !(provider.key?("domainVerified") && provider["domainVerified"])
    raise APIError.new("UNAUTHORIZED", message: "Provider domain has not been verified")
  end

  provider = sso_ensure_runtime_oidc_provider(ctx, provider, config)
  oidc_config = normalize_hash(provider["oidcConfig"] || {})
  oidc_config[:issuer] ||= provider["issuer"]
  return sso_redirect(ctx, sso_append_error(error_url, "invalid_provider", "provider not found")) if oidc_config.empty?

  tokens = sso_oidc_tokens(ctx, provider, oidc_config, state, config)
  unless tokens
    return sso_redirect(ctx, sso_append_error(error_url, "invalid_provider", "token_response_not_found"))
  end
  if oidc_config[:user_info_endpoint].to_s.empty? && tokens[:id_token] && oidc_config[:jwks_endpoint].to_s.empty?
    begin
      provider = sso_ensure_runtime_oidc_provider(ctx, provider, config, require_jwks: true)
      oidc_config = normalize_hash(provider["oidcConfig"] || {})
      oidc_config[:issuer] ||= provider["issuer"]
    rescue APIError
      # Fall through to the upstream callback error when JWKS is still unavailable.
    end
  end
   = (ctx, oidc_config, tokens, config)
  if [:_sso_error]
    return sso_redirect(ctx, sso_append_error(error_url, "invalid_provider", [:_sso_error]))
  end
  if [:email].to_s.empty? || [:id].to_s.empty?
    return sso_redirect(ctx, sso_append_error(error_url, "invalid_provider", "missing_user_info"))
  end
  if config[:disable_implicit_sign_up] && !state["requestSignUp"] && !ctx.context.internal_adapter.find_user_by_email([:email].to_s.downcase)
    return sso_redirect(ctx, sso_append_error(error_url, "signup disabled"))
  end

  result = sso_find_or_create_user_result(ctx, provider, , config)
  if config[:provision_user].respond_to?(:call) && (result.fetch(:created) || config[:provision_user_on_every_login])
    config[:provision_user].call(user: result.fetch(:user), userInfo: , token: tokens, provider: provider)
  end
  session = ctx.context.internal_adapter.create_session(result.fetch(:user).fetch("id"))
  Cookies.set_session_cookie(ctx, {session: session, user: result.fetch(:user)})
  redirect_to = (result.fetch(:created) && state["newUserURL"].to_s != "") ? state["newUserURL"] : callback_url
  sso_redirect(ctx, redirect_to || "/")
end

.sso_handle_saml_response(ctx, config = {}) ⇒ Object



540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
# File 'lib/better_auth/plugins/sso.rb', line 540

def sso_handle_saml_response(ctx, config = {})
  provider = sso_find_provider!(ctx, sso_fetch(ctx.params, :provider_id))
  relay_state = sso_fetch(ctx.body, :relay_state) || sso_fetch(ctx.query, :relay_state)
  state = sso_parse_saml_relay_state(ctx, relay_state) || {}
  raw_response = sso_fetch(ctx.body, :saml_response) || sso_fetch(ctx.query, :saml_response)
  if ctx.method == "GET" && raw_response.to_s.empty?
    session = Routes.current_session(ctx, allow_nil: true)
    unless session
      return sso_redirect(ctx, sso_append_error("#{ctx.context.base_url}/error", "invalid_request"))
    end

    return sso_redirect(ctx, sso_safe_saml_callback_url(ctx, relay_state || sso_saml_callback_url(provider) || "/", provider.fetch("providerId")))
  end
  max_response_size = config.dig(:saml, :max_response_size) || SSO_DEFAULT_MAX_SAML_RESPONSE_SIZE
  if raw_response.to_s.bytesize > max_response_size
    raise APIError.new("BAD_REQUEST", message: "SAML response exceeds maximum allowed size (#{max_response_size} bytes)")
  end
  in_response_to_error = sso_validate_saml_in_response_to(ctx, config, provider, raw_response, state)
  return in_response_to_error if in_response_to_error

  assertion = sso_parse_saml_response(raw_response, config, provider, ctx)
  assertion[:email_verified] = false unless config[:trust_email_verified]
  sso_validate_saml_timestamp!(sso_saml_timestamp_conditions(assertion), config)
  sso_validate_saml_response!(config, assertion, provider, ctx)
  assertion_id = assertion[:id] || assertion["id"] || assertion[:email]
  replay_key = "#{SSO_SAML_USED_ASSERTION_KEY_PREFIX}#{assertion_id}"
  if ctx.context.internal_adapter.find_verification_value(replay_key)
    raise APIError.new("BAD_REQUEST", message: SSO_ERROR_CODES.fetch("SAML_RESPONSE_REPLAYED"))
  end
  ctx.context.internal_adapter.create_verification_value(identifier: replay_key, value: "used", expiresAt: sso_saml_assertion_replay_expires_at(assertion, config))

  callback_url = sso_safe_saml_callback_url(ctx, state["callbackURL"] || sso_saml_callback_url(provider) || "/", provider.fetch("providerId"))
  email = (assertion[:email] || assertion["email"]).to_s.downcase
  if config[:disable_implicit_sign_up] && !state["requestSignUp"] && !ctx.context.internal_adapter.find_user_by_email(email)
    return sso_redirect(ctx, sso_append_error(callback_url, "signup disabled"))
  end

  result = sso_find_or_create_user_result(ctx, provider, assertion, config)
  return sso_redirect(ctx, sso_append_error(callback_url, result.fetch(:error))) if result[:error]

  user = result.fetch(:user)
  if config[:provision_user].respond_to?(:call) && (result.fetch(:created) || config[:provision_user_on_every_login])
    config[:provision_user].call(user: user, userInfo: assertion, provider: provider)
  end
  session = ctx.context.internal_adapter.create_session(user.fetch("id"))
  sso_store_saml_session(ctx, provider, assertion, session) if config.dig(:saml, :enable_single_logout)
  Cookies.set_session_cookie(ctx, {session: session, user: user})
  sso_redirect(ctx, callback_url)
end

.sso_hostname_from_domain(domain) ⇒ Object



1646
1647
1648
1649
1650
1651
1652
1653
1654
# File 'lib/better_auth/plugins/sso.rb', line 1646

def sso_hostname_from_domain(domain)
  value = domain.to_s.strip
  return nil if value.empty?

  uri = URI(value.include?("://") ? value : "https://#{value}")
  uri.host
rescue URI::InvalidURIError
  nil
end

.sso_hydrate_oidc_config(issuer, oidc_config, ctx) ⇒ Object



1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
# File 'lib/better_auth/plugins/sso.rb', line 1545

def sso_hydrate_oidc_config(issuer, oidc_config, ctx)
  existing = oidc_config.merge(issuer: issuer)
  discovered = sso_discover_oidc_config(
    issuer: issuer,
    existing_config: existing,
    fetch: ctx.context.options.plugins.find { |plugin| plugin.id == "sso" }&.options&.fetch(:oidc_discovery_fetch, nil),
    trusted_origin: ->(url) { ctx.context.trusted_origin?(url, allow_relative_paths: false) }
  )
  existing.merge(discovered)
end

.sso_initiate_slo_endpoint(config = {}) ⇒ Object



450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/better_auth/plugins/sso.rb', line 450

def sso_initiate_slo_endpoint(config = {})
  Endpoint.new(path: "/sso/saml2/logout/:providerId", method: "POST") do |ctx|
    raise APIError.new("BAD_REQUEST", message: "Single Logout is not enabled") unless config.dig(:saml, :enable_single_logout)

    session = Routes.current_session(ctx)
    provider = sso_find_provider!(ctx, sso_fetch(ctx.params, :provider_id))
    destination = sso_saml_logout_destination(provider)
    if destination.to_s.empty?
      raise APIError.new("BAD_REQUEST", message: "IdP does not support Single Logout Service")
    end

    relay_state = sso_fetch(ctx.body, :callback_url) || ctx.context.base_url
    session_token = session.fetch(:session).fetch("token")
    user_email = session.fetch(:user).fetch("email")
    saml_session_key = ctx.context.internal_adapter.find_verification_value("#{SSO_SAML_SESSION_BY_ID_KEY_PREFIX}#{session_token}")&.fetch("value")
    saml_session = saml_session_key && ctx.context.internal_adapter.find_verification_value(saml_session_key)
    saml_record = saml_session ? JSON.parse(saml_session.fetch("value")) : {}
    name_id = saml_record["nameId"] || user_email
    session_index = saml_record["sessionIndex"]

    request_id = "_#{BetterAuth::Crypto.random_string(32)}"
    session_index_xml = session_index.to_s.empty? ? "" : "<samlp:SessionIndex>#{CGI.escapeHTML(session_index.to_s)}</samlp:SessionIndex>"
    request = Base64.strict_encode64("<samlp:LogoutRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\" ID=\"#{request_id}\" Version=\"2.0\" IssueInstant=\"#{Time.now.utc.iso8601}\" Destination=\"#{CGI.escapeHTML(destination.to_s)}\"><saml:NameID>#{CGI.escapeHTML(name_id.to_s)}</saml:NameID>#{session_index_xml}</samlp:LogoutRequest>")
    sso_store_saml_logout_request(ctx, provider, request_id, config)
    ctx.context.internal_adapter.delete_verification_by_identifier(saml_session_key) if saml_session_key
    ctx.context.internal_adapter.delete_verification_by_identifier("#{SSO_SAML_SESSION_BY_ID_KEY_PREFIX}#{session_token}")
    ctx.context.internal_adapter.delete_session(session_token)
    Cookies.delete_session_cookie(ctx)
    query = {SAMLRequest: request, RelayState: relay_state}
    query = sso_signed_saml_redirect_query(provider, query) if config.dig(:saml, :want_logout_request_signed)
    sso_redirect(ctx, "#{destination}?#{URI.encode_www_form(query)}")
  end
end

.sso_list_providers_endpointObject



228
229
230
231
232
233
234
235
236
# File 'lib/better_auth/plugins/sso.rb', line 228

def sso_list_providers_endpoint
  Endpoint.new(path: "/sso/providers", method: "GET") do |ctx|
    session = Routes.current_session(ctx)
    providers = ctx.context.adapter.find_many(model: "ssoProvider")
      .select { |provider| sso_provider_access?(provider, session.fetch(:user).fetch("id"), ctx) }
      .map { |provider| sso_sanitize_provider(provider, ctx.context) }
    ctx.json({providers: providers})
  end
end

.sso_mask_client_id(client_id) ⇒ Object



1744
1745
1746
1747
1748
1749
# File 'lib/better_auth/plugins/sso.rb', line 1744

def sso_mask_client_id(client_id)
  value = client_id.to_s
  return "****" if value.length <= 4

  "****#{value[-4, 4]}"
end

.sso_normalize_discovery_url(value, issuer, trusted_origin) ⇒ Object



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/better_auth/plugins/sso.rb', line 152

def sso_normalize_discovery_url(value, issuer, trusted_origin)
  uri = URI(value.to_s)
  normalized = if uri.absolute?
    uri.to_s
  else
    issuer_uri = URI(issuer.to_s)
    issuer_base = issuer_uri.to_s.sub(%r{/+\z}, "")
    endpoint = value.to_s.sub(%r{\A/+}, "")
    "#{issuer_base}/#{endpoint}"
  end
  if trusted_origin && !trusted_origin.call(normalized)
    raise APIError.new("BAD_REQUEST", message: "OIDC discovery endpoint is not trusted")
  end

  normalized
rescue URI::InvalidURIError
  raise APIError.new("BAD_REQUEST", message: "Invalid OIDC discovery document")
end

.sso_normalize_saml_digest_algorithm(algorithm) ⇒ Object



1116
1117
1118
# File 'lib/better_auth/plugins/sso.rb', line 1116

def sso_normalize_saml_digest_algorithm(algorithm)
  SSO_SAML_DIGEST_ALGORITHMS.fetch(algorithm.to_s.downcase, algorithm.to_s)
end

.sso_normalize_saml_signature_algorithm(algorithm) ⇒ Object



1112
1113
1114
# File 'lib/better_auth/plugins/sso.rb', line 1112

def sso_normalize_saml_signature_algorithm(algorithm)
  SSO_SAML_SIGNATURE_ALGORITHMS.fetch(algorithm.to_s.downcase, algorithm.to_s)
end

.sso_oidc_authorization_url(provider, ctx, state, plugin_config = {}, body = {}) ⇒ Object

Raises:

  • (APIError)


1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
# File 'lib/better_auth/plugins/sso.rb', line 1177

def sso_oidc_authorization_url(provider, ctx, state, plugin_config = {}, body = {})
  config = normalize_hash(provider["oidcConfig"] || {})
  endpoint = config[:authorization_endpoint] || config[:authorization_url]
  raise APIError.new("BAD_REQUEST", message: "Invalid OIDC configuration. Authorization URL not found.") if endpoint.to_s.empty?

  scopes = Array(body[:scopes] || config[:scopes] || config[:scope] || ["openid", "email", "profile", "offline_access"])
  query = {
    client_id: config[:client_id],
    response_type: "code",
    redirect_uri: sso_oidc_redirect_uri(ctx.context, provider.fetch("providerId")),
    scope: scopes.join(" "),
    state: state
  }.compact
   = body[:login_hint] || body[:email]
  query[:login_hint] =  if 
  code_verifier = sso_decode_state(state, ctx.context.secret)&.fetch("codeVerifier", nil)
  if code_verifier
    query[:code_challenge] = sso_base64_urlsafe(OpenSSL::Digest::SHA256.digest(code_verifier))
    query[:code_challenge_method] = "S256"
  end
  "#{endpoint}?#{URI.encode_www_form(query)}"
end

.sso_oidc_callback_endpoint(config = {}) ⇒ Object



329
330
331
332
333
# File 'lib/better_auth/plugins/sso.rb', line 329

def sso_oidc_callback_endpoint(config = {})
  Endpoint.new(path: "/sso/callback/:providerId", method: "GET") do |ctx|
    sso_handle_oidc_callback(ctx, config, sso_fetch(ctx.params, :provider_id))
  end
end

.sso_oidc_needs_runtime_discovery?(oidc_config) ⇒ Boolean

Returns:

  • (Boolean)


1556
1557
1558
1559
1560
# File 'lib/better_auth/plugins/sso.rb', line 1556

def sso_oidc_needs_runtime_discovery?(oidc_config)
  config = normalize_hash(oidc_config || {})
  config[:authorization_endpoint].to_s.empty? ||
    config[:token_endpoint].to_s.empty?
end

.sso_oidc_pkce_state(provider) ⇒ Object



1500
1501
1502
1503
1504
# File 'lib/better_auth/plugins/sso.rb', line 1500

def sso_oidc_pkce_state(provider)
  return {} unless normalize_hash(provider["oidcConfig"] || {})[:pkce]

  {codeVerifier: BetterAuth::Crypto.random_string(128)}
end

.sso_oidc_redirect_uri(context, provider_id) ⇒ Object



1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
# File 'lib/better_auth/plugins/sso.rb', line 1576

def sso_oidc_redirect_uri(context, provider_id)
  redirect_uri = context.options.plugins.find { |plugin| plugin.id == "sso" }&.options&.fetch(:redirect_uri, nil)
  if redirect_uri && !redirect_uri.to_s.strip.empty?
    value = redirect_uri.to_s
    return value if URI(value).absolute?

    path = value.start_with?("/") ? value : "/#{value}"
    return "#{context.base_url}#{path}"
  end

  "#{context.base_url}/sso/callback/#{provider_id}"
rescue URI::InvalidURIError
  "#{context.base_url}/sso/callback/#{provider_id}"
end

.sso_oidc_shared_callback_endpoint(config = {}) ⇒ Object



335
336
337
338
339
340
341
342
# File 'lib/better_auth/plugins/sso.rb', line 335

def sso_oidc_shared_callback_endpoint(config = {})
  Endpoint.new(path: "/sso/callback", method: "GET") do |ctx|
    state = sso_verify_state(ctx.query[:state] || ctx.query["state"], ctx.context.secret)
    next ctx.redirect("#{ctx.context.base_url}/error?error=invalid_state") unless state

    sso_handle_oidc_callback(ctx, config, state["providerId"], state: state)
  end
end

.sso_oidc_tokens(ctx, provider, oidc_config, state, plugin_config) ⇒ Object



1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
# File 'lib/better_auth/plugins/sso.rb', line 1335

def sso_oidc_tokens(ctx, provider, oidc_config, state, plugin_config)
  token_callback = oidc_config[:get_token]
  if token_callback.respond_to?(:call)
    return normalize_hash(token_callback.call(
      code: ctx.query[:code] || ctx.query["code"],
      codeVerifier: state["codeVerifier"],
      redirectURI: sso_oidc_redirect_uri(ctx.context, provider.fetch("providerId")),
      provider: provider,
      context: ctx
    ))
  end

  token_endpoint = oidc_config[:token_endpoint]
  return nil if token_endpoint.to_s.empty?

  sso_exchange_oidc_code(
    token_endpoint: token_endpoint,
    code: ctx.query[:code] || ctx.query["code"],
    code_verifier: state["codeVerifier"],
    redirect_uri: sso_oidc_redirect_uri(ctx.context, provider.fetch("providerId")),
    client_id: oidc_config[:client_id],
    client_secret: oidc_config[:client_secret],
    authentication: oidc_config[:token_endpoint_authentication]
  )
rescue
  nil
end

.sso_oidc_user_info(ctx, oidc_config, tokens, plugin_config) ⇒ Object



1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
# File 'lib/better_auth/plugins/sso.rb', line 1385

def (ctx, oidc_config, tokens, plugin_config)
  user_callback = oidc_config[:get_user_info]
  raw = if user_callback.respond_to?(:call)
    user_callback.call(tokens)
  elsif oidc_config[:user_info_endpoint]
    (oidc_config[:user_info_endpoint], tokens[:access_token])
  elsif tokens[:id_token]
    return {_sso_error: "jwks_endpoint_not_found"} if oidc_config[:jwks_endpoint].to_s.empty?

    sso_validate_oidc_id_token(
      tokens[:id_token],
      jwks_endpoint: oidc_config[:jwks_endpoint],
      audience: oidc_config[:client_id],
      issuer: oidc_config[:issuer],
      fetch: plugin_config[:oidc_jwks_fetch]
    ) || {_sso_error: "token_not_verified"}
  else
    {}
  end
  raw = normalize_hash(raw || {})
  return raw if raw[:_sso_error]

  mapping = normalize_hash(oidc_config[:mapping] || {})
  extra_fields = normalize_hash(mapping[:extra_fields] || {}).each_with_object({}) do |(target, source), result|
    result[target] = raw[normalize_key(source)] || raw[source.to_s]
  end
  extra_fields.merge(
    id: raw[normalize_key(mapping[:id] || "sub")] || raw[:id],
    email: raw[normalize_key(mapping[:email] || "email")],
    email_verified: plugin_config[:trust_email_verified] ? raw[normalize_key(mapping[:email_verified] || "email_verified")] : false,
    name: raw[normalize_key(mapping[:name] || "name")],
    image: raw[normalize_key(mapping[:image] || "picture")]
  )
end

.sso_parse_certificate(cert) ⇒ Object



1751
1752
1753
1754
1755
1756
# File 'lib/better_auth/plugins/sso.rb', line 1751

def sso_parse_certificate(cert)
  OpenSSL::X509::Certificate.new(cert.to_s)
  {subject: cert.to_s.lines.first.to_s.strip}
rescue
  {error: "Failed to parse certificate"}
end

.sso_parse_saml_authn_request_record(value) ⇒ Object



1274
1275
1276
1277
1278
# File 'lib/better_auth/plugins/sso.rb', line 1274

def sso_parse_saml_authn_request_record(value)
  JSON.parse(value.to_s)
rescue
  nil
end

.sso_parse_saml_logout_request(raw_request) ⇒ Object



883
884
885
886
887
888
889
890
891
# File 'lib/better_auth/plugins/sso.rb', line 883

def sso_parse_saml_logout_request(raw_request)
  xml = Base64.decode64(raw_request.to_s.gsub(/\s+/, ""))
  {
    name_id: xml[%r{<(?:\w+:)?NameID[^>]*>([^<]+)</(?:\w+:)?NameID>}, 1],
    session_index: xml[%r{<(?:\w+:)?SessionIndex[^>]*>([^<]+)</(?:\w+:)?SessionIndex>}, 1]
  }
rescue
  {}
end

.sso_parse_saml_logout_response(raw_response) ⇒ Object



893
894
895
896
897
898
899
900
901
# File 'lib/better_auth/plugins/sso.rb', line 893

def sso_parse_saml_logout_response(raw_response)
  xml = Base64.decode64(raw_response.to_s.gsub(/\s+/, ""))
  {
    in_response_to: xml[/\bInResponseTo=['"]([^'"]+)['"]/, 1],
    status_code: xml[/<(?:\w+:)?StatusCode\b[^>]*\bValue=['"]([^'"]+)['"]/, 1]
  }
rescue
  {}
end

.sso_parse_saml_metadata_xml(xml) ⇒ Object



745
746
747
748
749
750
751
752
753
754
755
756
# File 'lib/better_auth/plugins/sso.rb', line 745

def (xml)
  doc = REXML::Document.new(xml.to_s)
  root = doc.root
  {
    entity_id: root&.attributes&.[]("entityID"),
    cert: sso_saml_normalize_certificate((doc, "X509Certificate")),
    single_sign_on_service: (doc, "SingleSignOnService"),
    single_logout_service: (doc, "SingleLogoutService")
  }.compact
rescue
  {}
end

.sso_parse_saml_relay_state(ctx, relay_state) ⇒ Object



1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
# File 'lib/better_auth/plugins/sso.rb', line 1155

def sso_parse_saml_relay_state(ctx, relay_state)
  state = sso_verify_state(relay_state, ctx.context.secret)
  return state if state

  verification = ctx.context.internal_adapter.find_verification_value("#{SSO_SAML_RELAY_STATE_KEY_PREFIX}#{relay_state}")
  return nil unless verification
  return nil unless sso_future_time?(verification.fetch("expiresAt"))

  parsed = JSON.parse(verification.fetch("value"))
  return nil if parsed["expiresAt"].to_i <= (Time.now.to_f * 1000).to_i

  parsed
rescue
  nil
end

.sso_parse_saml_response(value, config = {}, provider = nil, ctx = nil) ⇒ Object



995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
# File 'lib/better_auth/plugins/sso.rb', line 995

def sso_parse_saml_response(value, config = {}, provider = nil, ctx = nil)
  parser = config.dig(:saml, :parse_response)
  if parser.respond_to?(:call)
    sso_validate_single_saml_assertion!(value) if sso_base64_xml?(value)
    parsed = parser.call(raw_response: value.to_s, provider: provider, context: ctx)
    return normalize_hash(parsed)
  end

  JSON.parse(Base64.decode64(value.to_s), symbolize_names: true)
rescue APIError
  raise APIError.new("BAD_REQUEST", message: "Invalid SAML response")
rescue
  raise APIError.new("BAD_REQUEST", message: "Invalid SAML response")
end

.sso_parse_saml_timestamp(value, error_message) ⇒ Object



1049
1050
1051
1052
1053
# File 'lib/better_auth/plugins/sso.rb', line 1049

def sso_parse_saml_timestamp(value, error_message)
  Time.parse(value.to_s).utc
rescue
  raise APIError.new("BAD_REQUEST", message: error_message)
end

.sso_process_saml_logout_request(ctx, provider, raw_request) ⇒ Object



843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
# File 'lib/better_auth/plugins/sso.rb', line 843

def sso_process_saml_logout_request(ctx, provider, raw_request)
  data = sso_parse_saml_logout_request(raw_request)
  return if data[:name_id].to_s.empty?

  session_identifier = "#{SSO_SAML_SESSION_KEY_PREFIX}#{provider.fetch("providerId")}:#{data[:name_id]}"
  verification = ctx.context.internal_adapter.find_verification_value(session_identifier)
  return unless verification

  record = JSON.parse(verification.fetch("value"))
  session_token = record["sessionToken"]
  session_index_matches = data[:session_index].to_s.empty? || record["sessionIndex"].to_s.empty? || data[:session_index].to_s == record["sessionIndex"].to_s
  ctx.context.internal_adapter.delete_session(session_token) if session_token && session_index_matches
  ctx.context.internal_adapter.delete_verification_by_identifier(session_identifier)
  ctx.context.internal_adapter.delete_verification_by_identifier("#{SSO_SAML_SESSION_BY_ID_KEY_PREFIX}#{session_token}") if session_token
rescue
  nil
end

.sso_process_saml_logout_response(ctx, raw_response) ⇒ Object



870
871
872
873
874
875
876
877
878
879
880
881
# File 'lib/better_auth/plugins/sso.rb', line 870

def sso_process_saml_logout_response(ctx, raw_response)
  data = sso_parse_saml_logout_response(raw_response)
  status_code = data[:status_code]
  if status_code && status_code != SSO_SAML_STATUS_SUCCESS
    raise APIError.new("BAD_REQUEST", message: "Logout failed at IdP")
  end

  in_response_to = data[:in_response_to]
  return if in_response_to.to_s.empty?

  ctx.context.internal_adapter.delete_verification_by_identifier("#{SSO_SAML_LOGOUT_REQUEST_KEY_PREFIX}#{in_response_to}")
end

.sso_provider_access?(provider, user_id, ctx) ⇒ Boolean

Returns:

  • (Boolean)


1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
# File 'lib/better_auth/plugins/sso.rb', line 1608

def sso_provider_access?(provider, user_id, ctx)
  organization_id = provider["organizationId"]
  return provider["userId"] == user_id if organization_id.to_s.empty?
  return provider["userId"] == user_id unless ctx.context.options.plugins.any? { |plugin| plugin.id == "organization" }

  member = ctx.context.adapter.find_one(
    model: "member",
    where: [{field: "userId", value: user_id}, {field: "organizationId", value: organization_id}]
  )
  Array(member&.fetch("role", nil).to_s.split(",")).map(&:strip).any? { |role| %w[owner admin].include?(role) }
end

.sso_provider_config_hash(value) ⇒ Object



1681
1682
1683
1684
1685
1686
1687
1688
1689
# File 'lib/better_auth/plugins/sso.rb', line 1681

def sso_provider_config_hash(value)
  return normalize_hash(value) if value.is_a?(Hash)
  return {} if value.nil? || value.to_s.strip.empty?

  parsed = JSON.parse(value.to_s)
  normalize_hash(parsed)
rescue JSON::ParserError, TypeError
  {}
end

.sso_provider_limit(user, config) ⇒ Object



1522
1523
1524
1525
1526
# File 'lib/better_auth/plugins/sso.rb', line 1522

def sso_provider_limit(user, config)
  limit = config[:providers_limit]
  limit = 10 if limit.nil?
  limit.respond_to?(:call) ? limit.call(user) : limit
end

.sso_redirect(ctx, location) ⇒ Object



1777
1778
1779
# File 'lib/better_auth/plugins/sso.rb', line 1777

def sso_redirect(ctx, location)
  [302, ctx.response_headers.merge("location" => location), [""]]
end

.sso_register_provider_endpoint(config = {}) ⇒ Object



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/better_auth/plugins/sso.rb', line 171

def sso_register_provider_endpoint(config = {})
  Endpoint.new(path: "/sso/register", method: "POST") do |ctx|
    session = Routes.current_session(ctx)
    body = normalize_hash(ctx.body)
    provider_id = body[:provider_id].to_s
    raise APIError.new("BAD_REQUEST", message: "providerId is required") if provider_id.empty?

    limit = sso_provider_limit(session.fetch(:user), config)
    if limit.to_i.zero?
      raise APIError.new("FORBIDDEN", message: "SSO provider registration is disabled")
    end
    providers = ctx.context.adapter.find_many(model: "ssoProvider", where: [{field: "userId", value: session.fetch(:user).fetch("id")}])
    if providers.length >= limit.to_i
      raise APIError.new("FORBIDDEN", message: "You have reached the maximum number of SSO providers")
    end

    sso_validate_url!(body[:issuer], "Invalid issuer. Must be a valid URL")
    sso_validate_organization_membership!(ctx, session.fetch(:user).fetch("id"), body[:organization_id]) if body[:organization_id]
    if ctx.context.adapter.find_one(model: "ssoProvider", where: [{field: "providerId", value: provider_id}])
      raise APIError.new("UNPROCESSABLE_ENTITY", message: "SSO provider with this providerId already exists")
    end

    oidc_config = normalize_hash(body[:oidc_config] || {})
    oidc_config = sso_hydrate_oidc_config(body[:issuer], oidc_config, ctx) if oidc_config.any? && !oidc_config[:skip_discovery]
    oidc_config[:override_user_info] = !!(body[:override_user_info] || config[:default_override_user_info]) if oidc_config.any?
    saml_config = normalize_hash(body[:saml_config] || {})
    sso_validate_saml_config!(saml_config, config) unless saml_config.empty?

    provider = ctx.context.adapter.create(
      model: "ssoProvider",
      data: {
        providerId: provider_id,
        issuer: body[:issuer].to_s,
        domain: body[:domain].to_s.downcase,
        oidcConfig: oidc_config.empty? ? nil : oidc_config,
        samlConfig: saml_config.empty? ? nil : saml_config,
        userId: session.fetch(:user).fetch("id"),
        organizationId: body[:organization_id],
        domainVerified: false
      }
    )
    domain_verification_token = nil
    if config.dig(:domain_verification, :enabled)
      domain_verification_token = BetterAuth::Crypto.random_string(24)
      ctx.context.internal_adapter.create_verification_value(
        identifier: sso_domain_verification_identifier(config, provider.fetch("providerId")),
        value: domain_verification_token,
        expiresAt: Time.now + (7 * 24 * 60 * 60)
      )
    end
    response = sso_sanitize_provider(provider, ctx.context)
    response[:redirectURI] = sso_oidc_redirect_uri(ctx.context, provider.fetch("providerId"))
    response[:domainVerificationToken] = domain_verification_token if domain_verification_token
    ctx.json(response)
  end
end

.sso_request_domain_verification_endpoint(config) ⇒ Object



484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
# File 'lib/better_auth/plugins/sso.rb', line 484

def sso_request_domain_verification_endpoint(config)
  Endpoint.new(path: "/sso/request-domain-verification", method: "POST") do |ctx|
    session = Routes.current_session(ctx)
    provider = sso_find_provider!(ctx, normalize_hash(ctx.body)[:provider_id])
    sso_authorize_domain_verification!(ctx, provider, session.fetch(:user).fetch("id"))
    if provider.key?("domainVerified") && provider["domainVerified"]
      raise APIError.new("CONFLICT", message: "Domain has already been verified", code: "DOMAIN_VERIFIED")
    end

    identifier = sso_domain_verification_identifier(config, provider.fetch("providerId"))
    active = ctx.context.internal_adapter.find_verification_value(identifier)
    if active && sso_future_time?(active.fetch("expiresAt"))
      next ctx.json({domainVerificationToken: active.fetch("value")}, status: 201)
    end

    token = BetterAuth::Crypto.random_string(24)
    ctx.context.internal_adapter.create_verification_value(identifier: identifier, value: token, expiresAt: Time.now + (7 * 24 * 60 * 60))
    config.dig(:domain_verification, :request)&.call(provider: provider, token: token, context: ctx)
    ctx.json({domainVerificationToken: token}, status: 201)
  end
end

.sso_resolve_txt_records(hostname, config) ⇒ Object



1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
# File 'lib/better_auth/plugins/sso.rb', line 1656

def sso_resolve_txt_records(hostname, config)
  resolver = config.dig(:domain_verification, :dns_txt_resolver)
  return Array(resolver.call(hostname)) if resolver.respond_to?(:call)

  Resolv::DNS.open do |dns|
    dns.getresources(hostname, Resolv::DNS::Resource::IN::TXT).map { |record| record.strings }
  end
rescue
  []
end

.sso_safe_saml_callback_url(ctx, url, provider_id) ⇒ Object



925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
# File 'lib/better_auth/plugins/sso.rb', line 925

def sso_safe_saml_callback_url(ctx, url, provider_id)
  app_origin = ctx.context.base_url
  callback_path = URI.parse("#{ctx.context.base_url}/sso/saml2/callback/#{URI.encode_www_form_component(provider_id)}").path
  acs_path = URI.parse("#{ctx.context.base_url}/sso/saml2/sp/acs/#{URI.encode_www_form_component(provider_id)}").path
  value = url.to_s
  return app_origin if value.empty?

  if value.start_with?("/") && !value.start_with?("//")
    parsed = URI.parse(value)
    return app_origin if [callback_path, acs_path].include?(parsed.path)
    return value
  end

  return app_origin unless ctx.context.trusted_origin?(value, allow_relative_paths: false)

  parsed = URI.parse(value)
  return app_origin if [callback_path, acs_path].include?(parsed.path)

  value
rescue
  app_origin
end

.sso_safe_slo_redirect_url(ctx, url, provider_id) ⇒ Object



903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
# File 'lib/better_auth/plugins/sso.rb', line 903

def sso_safe_slo_redirect_url(ctx, url, provider_id)
  app_origin = ctx.context.base_url
  callback_path = URI.parse("#{ctx.context.base_url}/sso/saml2/sp/slo/#{URI.encode_www_form_component(provider_id)}").path
  value = url.to_s
  return app_origin if value.empty?

  if value.start_with?("/") && !value.start_with?("//")
    parsed = URI.parse(value)
    return app_origin if parsed.path == callback_path
    return value
  end

  return app_origin unless ctx.context.trusted_origin?(value, allow_relative_paths: false)

  parsed = URI.parse(value)
  return app_origin if parsed.path == callback_path

  value
rescue
  app_origin
end

.sso_saml_acs_endpoint(config) ⇒ Object



407
408
409
410
411
# File 'lib/better_auth/plugins/sso.rb', line 407

def sso_saml_acs_endpoint(config)
  Endpoint.new(path: "/sso/saml2/sp/acs/:providerId", method: "POST", metadata: {allowed_media_types: ["application/json", "application/x-www-form-urlencoded"]}) do |ctx|
    sso_handle_saml_response(ctx, config)
  end
end

.sso_saml_acs_url(ctx, provider) ⇒ Object



712
713
714
715
716
717
718
719
# File 'lib/better_auth/plugins/sso.rb', line 712

def sso_saml_acs_url(ctx, provider)
  provider_id = provider.fetch("providerId")
  base_url = ctx.context.base_url
  configured = normalize_hash(provider["samlConfig"] || {})[:callback_url].to_s
  return configured if sso_saml_acs_url?(configured)

  "#{base_url}/sso/saml2/sp/acs/#{URI.encode_www_form_component(provider_id)}"
end

.sso_saml_acs_url?(url) ⇒ Boolean

Returns:

  • (Boolean)


721
722
723
724
725
726
727
# File 'lib/better_auth/plugins/sso.rb', line 721

def sso_saml_acs_url?(url)
  return false if url.to_s.empty?

  URI.parse(url.to_s).path.include?("/sso/saml2/sp/acs")
rescue
  false
end

.sso_saml_assertion_replay_expires_at(assertion, config = {}) ⇒ Object



1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
# File 'lib/better_auth/plugins/sso.rb', line 1280

def sso_saml_assertion_replay_expires_at(assertion, config = {})
  timestamp = sso_saml_timestamp_conditions(assertion)[:not_on_or_after]
  parsed = Time.parse(timestamp.to_s) if timestamp
  clock_skew_seconds = ((config.dig(:saml, :clock_skew) || SSO_DEFAULT_CLOCK_SKEW_MS).to_f / 1000.0)
  return parsed + clock_skew_seconds if parsed && parsed + clock_skew_seconds > Time.now

  ttl_ms = (config.dig(:saml, :assertion_ttl) || SSO_DEFAULT_ASSERTION_TTL_MS).to_i
  Time.now + (ttl_ms / 1000.0)
rescue
  Time.now + (SSO_DEFAULT_ASSERTION_TTL_MS / 1000.0)
end

.sso_saml_authorization_url(provider, relay_state, ctx = nil, config = {}) ⇒ Object



1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
# File 'lib/better_auth/plugins/sso.rb', line 1200

def sso_saml_authorization_url(provider, relay_state, ctx = nil, config = {})
  auth_request_url = config.dig(:saml, :auth_request_url)
  if auth_request_url.respond_to?(:call)
    return auth_request_url.call(provider: provider, relay_state: relay_state, context: ctx)
  end

  config = normalize_hash(provider["samlConfig"] || {})
   = (config)
  entry_point = config[:entry_point] || normalize_hash(sso_saml_preferred_service([:single_sign_on_service]) || {})[:location]
  query = {
    SAMLRequest: Base64.strict_encode64(JSON.generate({providerId: provider.fetch("providerId")})),
    RelayState: relay_state
  }
  "#{entry_point}?#{URI.encode_www_form(query)}"
end

.sso_saml_callback_endpoint(config) ⇒ Object



401
402
403
404
405
# File 'lib/better_auth/plugins/sso.rb', line 401

def sso_saml_callback_endpoint(config)
  Endpoint.new(path: "/sso/saml2/callback/:providerId", method: ["GET", "POST"], metadata: {allowed_media_types: ["application/json", "application/x-www-form-urlencoded"]}) do |ctx|
    sso_handle_saml_response(ctx, config)
  end
end

.sso_saml_callback_url(provider) ⇒ Object



799
800
801
802
# File 'lib/better_auth/plugins/sso.rb', line 799

def sso_saml_callback_url(provider)
  saml_config = normalize_hash(provider["samlConfig"] || {})
  saml_config[:callback_url]
end

.sso_saml_idp_metadata(provider_or_config) ⇒ Object



729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
# File 'lib/better_auth/plugins/sso.rb', line 729

def (provider_or_config)
  saml_config = if provider_or_config.respond_to?(:key?) && (provider_or_config.key?("samlConfig") || provider_or_config.key?(:samlConfig))
    normalize_hash(provider_or_config["samlConfig"] || provider_or_config[:samlConfig] || {})
  else
    normalize_hash(provider_or_config || {})
  end
   = normalize_hash(saml_config[:idp_metadata] || {})
  xml = [:metadata] || saml_config[:metadata] || saml_config[:idp_metadata_xml]
  parsed = xml.to_s.strip.empty? ? {} : (xml)
  parsed[:entity_id] ||= [:entity_id] || [:entityID] || saml_config[:issuer]
  parsed[:cert] ||= [:cert] || saml_config[:cert]
  parsed[:single_sign_on_service] = ([:single_sign_on_service] || saml_config[:single_sign_on_service]) if parsed[:single_sign_on_service].to_a.empty?
  parsed[:single_logout_service] = ([:single_logout_service] || saml_config[:single_logout_service]) if parsed[:single_logout_service].to_a.empty?
  parsed
end

.sso_saml_logout_destination(provider) ⇒ Object



804
805
806
807
808
809
810
811
812
813
814
# File 'lib/better_auth/plugins/sso.rb', line 804

def sso_saml_logout_destination(provider)
  saml_config = normalize_hash(provider["samlConfig"] || {})
  direct = saml_config[:single_logout_service] ||
    saml_config[:single_logout_service_url] ||
    saml_config[:idp_slo_service_url] ||
    saml_config[:logout_url]
  return direct unless direct.to_s.empty?

  service = sso_saml_preferred_service((saml_config)[:single_logout_service])
  normalize_hash(service || {})[:location]
end

.sso_saml_metadata_first_text(doc, element_name) ⇒ Object



771
772
773
774
775
776
# File 'lib/better_auth/plugins/sso.rb', line 771

def (doc, element_name)
  REXML::XPath.each(doc, "//*") do |element|
    return element.text.to_s.strip if element.name == element_name && !element.text.to_s.strip.empty?
  end
  nil
end

.sso_saml_metadata_services(doc, element_name) ⇒ Object



758
759
760
761
762
763
764
765
766
767
768
769
# File 'lib/better_auth/plugins/sso.rb', line 758

def (doc, element_name)
  services = []
  REXML::XPath.each(doc, "//*") do |element|
    next unless element.name == element_name

    services << {
      binding: element.attributes["Binding"],
      location: element.attributes["Location"]
    }.compact
  end
  services
end

.sso_saml_metadata_services_from_config(value) ⇒ Object



778
779
780
781
782
783
784
785
# File 'lib/better_auth/plugins/sso.rb', line 778

def (value)
  Array(value).filter_map do |entry|
    data = normalize_hash(entry || {})
    next if data[:location].to_s.empty?

    {binding: data[:binding] || data[:Binding], location: data[:location] || data[:Location]}.compact
  end
end

.sso_saml_normalize_certificate(value) ⇒ Object



791
792
793
794
795
796
797
# File 'lib/better_auth/plugins/sso.rb', line 791

def sso_saml_normalize_certificate(value)
  cert = value.to_s.strip
  return nil if cert.empty?
  return cert if cert.include?("BEGIN CERTIFICATE")

  "-----BEGIN CERTIFICATE-----\n#{cert.scan(/.{1,64}/).join("\n")}\n-----END CERTIFICATE-----"
end

.sso_saml_post_form(action, saml_param, saml_value, relay_state = nil) ⇒ Object



974
975
976
977
978
# File 'lib/better_auth/plugins/sso.rb', line 974

def sso_saml_post_form(action, saml_param, saml_value, relay_state = nil)
  relay_input = relay_state.to_s.empty? ? "" : "<input type=\"hidden\" name=\"RelayState\" value=\"#{CGI.escapeHTML(relay_state.to_s)}\" />"
  html = "<!DOCTYPE html><html><body onload=\"document.forms[0].submit();\"><form method=\"POST\" action=\"#{CGI.escapeHTML(action.to_s)}\"><input type=\"hidden\" name=\"#{CGI.escapeHTML(saml_param.to_s)}\" value=\"#{CGI.escapeHTML(saml_value.to_s)}\" />#{relay_input}<noscript><input type=\"submit\" value=\"Continue\" /></noscript></form></body></html>"
  [200, {"content-type" => "text/html"}, [html]]
end

.sso_saml_preferred_service(services) ⇒ Object



787
788
789
# File 'lib/better_auth/plugins/sso.rb', line 787

def sso_saml_preferred_service(services)
  Array(services).find { |service| normalize_hash(service)[:binding].to_s.include?("HTTP-Redirect") } || Array(services).first
end

.sso_saml_signature_digest(signature_algorithm) ⇒ Object



961
962
963
964
965
966
967
968
969
970
971
972
# File 'lib/better_auth/plugins/sso.rb', line 961

def sso_saml_signature_digest(signature_algorithm)
  case signature_algorithm.to_s
  when /sha512/i
    OpenSSL::Digest.new("SHA512")
  when /sha384/i
    OpenSSL::Digest.new("SHA384")
  when /sha1/i
    OpenSSL::Digest.new("SHA1")
  else
    OpenSSL::Digest.new("SHA256")
  end
end

.sso_saml_slo_endpoint(config = {}) ⇒ Object



426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/better_auth/plugins/sso.rb', line 426

def sso_saml_slo_endpoint(config = {})
  Endpoint.new(path: "/sso/saml2/sp/slo/:providerId", method: ["GET", "POST"], metadata: {allowed_media_types: ["application/json", "application/x-www-form-urlencoded"]}) do |ctx|
    raise APIError.new("BAD_REQUEST", message: "Single Logout is not enabled") unless config.dig(:saml, :enable_single_logout)

    provider = sso_find_provider!(ctx, sso_fetch(ctx.params, :provider_id))
    relay_state = sso_fetch(ctx.body, :relay_state) || sso_fetch(ctx.query, :relay_state)
    if sso_fetch(ctx.body, :saml_response) || sso_fetch(ctx.query, :saml_response)
      sso_process_saml_logout_response(ctx, sso_fetch(ctx.body, :saml_response) || sso_fetch(ctx.query, :saml_response))
      Cookies.delete_session_cookie(ctx)
      next sso_redirect(ctx, sso_safe_slo_redirect_url(ctx, relay_state, provider.fetch("providerId")))
    end

    sso_process_saml_logout_request(ctx, provider, sso_fetch(ctx.body, :saml_request) || sso_fetch(ctx.query, :saml_request))
    response = Base64.strict_encode64("<samlp:LogoutResponse xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\"_#{BetterAuth::Crypto.random_string(32)}\" Version=\"2.0\" IssueInstant=\"#{Time.now.utc.iso8601}\" Destination=\"#{sso_saml_logout_destination(provider)}\"><samlp:Status><samlp:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/></samlp:Status></samlp:LogoutResponse>")
    if sso_fetch(ctx.body, :saml_request)
      next sso_saml_post_form(sso_saml_logout_destination(provider), "SAMLResponse", response, relay_state)
    end

    query = {SAMLResponse: response, RelayState: relay_state}
    query = sso_signed_saml_redirect_query(provider, query) if config.dig(:saml, :want_logout_response_signed)
    sso_redirect(ctx, "#{sso_saml_logout_destination(provider)}?#{URI.encode_www_form(query)}")
  end
end

.sso_saml_timestamp_conditions(assertion) ⇒ Object



1055
1056
1057
1058
1059
1060
1061
# File 'lib/better_auth/plugins/sso.rb', line 1055

def sso_saml_timestamp_conditions(assertion)
  assertion = normalize_hash(assertion || {})
  conditions = normalize_hash(assertion[:conditions] || {})
  conditions[:not_before] ||= assertion[:not_before] || assertion[:notBefore]
  conditions[:not_on_or_after] ||= assertion[:not_on_or_after] || assertion[:notOnOrAfter]
  conditions
end

.sso_saml_trusted_provider?(ctx, provider, email) ⇒ Boolean

Returns:

  • (Boolean)


651
652
653
654
655
656
657
658
# File 'lib/better_auth/plugins/sso.rb', line 651

def sso_saml_trusted_provider?(ctx, provider, email)
  provider_id = provider.fetch("providerId")
  linking = ctx.context.options.[:account_linking] || {}
  return false if linking[:enabled] == false

  trusted = Array(linking[:trusted_providers]).map(&:to_s).include?(provider_id.to_s)
  trusted || (provider["domainVerified"] && sso_email_domain_matches?(email, provider["domain"]))
end

.sso_sanitize_config(config) ⇒ Object



1697
1698
1699
1700
1701
# File 'lib/better_auth/plugins/sso.rb', line 1697

def sso_sanitize_config(config)
  data = normalize_hash(config || {})
  data.delete(:client_secret)
  data.each_with_object({}) { |(key, value), result| result[Schema.storage_key(key)] = value unless value.respond_to?(:call) }
end

.sso_sanitize_oidc_config(config) ⇒ Object



1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
# File 'lib/better_auth/plugins/sso.rb', line 1703

def sso_sanitize_oidc_config(config)
  {
    "clientIdLastFour" => sso_mask_client_id(config[:client_id]),
    "authorizationEndpoint" => config[:authorization_endpoint],
    "tokenEndpoint" => config[:token_endpoint],
    "userInfoEndpoint" => config[:user_info_endpoint],
    "jwksEndpoint" => config[:jwks_endpoint],
    "scopes" => config[:scopes],
    "tokenEndpointAuthentication" => config[:token_endpoint_authentication],
    "pkce" => config[:pkce],
    "discoveryEndpoint" => config[:discovery_endpoint],
    "mapping" => config[:mapping] && sso_sanitize_config(config[:mapping])
  }.compact
end

.sso_sanitize_provider(provider, context) ⇒ Object



1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
# File 'lib/better_auth/plugins/sso.rb', line 1667

def sso_sanitize_provider(provider, context)
  data = provider.dup
  oidc_config = sso_provider_config_hash(data["oidcConfig"])
  saml_config = sso_provider_config_hash(data["samlConfig"])
  data["type"] = saml_config.empty? ? "oidc" : "saml"
  data["organizationId"] ||= nil
  data["domainVerified"] = !!data["domainVerified"]
  data.delete("domainVerified") unless sso_context_domain_verification_enabled?(context)
  data["oidcConfig"] = oidc_config.empty? ? nil : sso_sanitize_oidc_config(oidc_config)
  data["samlConfig"] = saml_config.empty? ? nil : sso_sanitize_saml_config(saml_config)
  data["spMetadataUrl"] = "#{context.base_url}/sso/saml2/sp/metadata?providerId=#{URI.encode_www_form_component(data.fetch("providerId"))}"
  data.compact
end

.sso_sanitize_saml_config(config) ⇒ Object



1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
# File 'lib/better_auth/plugins/sso.rb', line 1718

def sso_sanitize_saml_config(config)
  {
    "entryPoint" => config[:entry_point],
    "callbackUrl" => config[:callback_url],
    "audience" => config[:audience],
    "wantAssertionsSigned" => config[:want_assertions_signed],
    "authnRequestsSigned" => config[:authn_requests_signed],
    "identifierFormat" => config[:identifier_format],
    "signatureAlgorithm" => config[:signature_algorithm],
    "digestAlgorithm" => config[:digest_algorithm],
    "certificate" => sso_parse_certificate(config[:cert]),
    "idpMetadata" => (config[:idp_metadata]),
    "spMetadata" => (config[:sp_metadata]),
    "mapping" => config[:mapping] && sso_sanitize_config(config[:mapping])
  }.compact
end

.sso_sanitize_saml_metadata_config(metadata) ⇒ Object



1735
1736
1737
1738
1739
1740
1741
1742
# File 'lib/better_auth/plugins/sso.rb', line 1735

def ()
  data = normalize_hash( || {})
  return nil if data.empty?

  data.except(:private_key, :private_key_pass, :enc_private_key, :enc_private_key_pass, :decryption_pvk).each_with_object({}) do |(key, value), result|
    result[(key == :entity_id) ? "entityID" : Schema.storage_key(key)] = value
  end
end

.sso_schema(config = {}) ⇒ Object



99
100
101
# File 'lib/better_auth/plugins/sso.rb', line 99

def sso_schema(config = {})
  BetterAuth::SSO::Routes::Schemas.plugin_schema(config)
end

.sso_select_provider(ctx, body, config = {}) ⇒ Object

Raises:

  • (APIError)


1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
# File 'lib/better_auth/plugins/sso.rb', line 1299

def sso_select_provider(ctx, body, config = {})
  provider_id = body[:provider_id].to_s
  issuer = body[:issuer].to_s
  organization_slug = body[:organization_slug].to_s
  domain = (body[:domain] || body[:email].to_s.split("@").last).to_s.downcase
  if config[:default_sso]
    provider = sso_default_provider(config, provider_id: provider_id, domain: domain)
    return provider if provider
  end

  providers = ctx.context.adapter.find_many(model: "ssoProvider")
  provider = if !provider_id.empty?
    providers.find { |entry| entry["providerId"] == provider_id }
  elsif !issuer.empty?
    providers.find { |entry| entry["issuer"] == issuer }
  elsif !organization_slug.empty?
    organization = ctx.context.adapter.find_one(model: "organization", where: [{field: "slug", value: organization_slug}])
    providers.find { |entry| entry["organizationId"] == organization&.fetch("id", nil) }
  elsif !domain.empty?
    providers.find { |entry| entry["domain"].to_s.downcase == domain } ||
      providers.find { |entry| sso_email_domain_matches?(domain, entry["domain"]) }
  end
  raise APIError.new("NOT_FOUND", message: SSO_ERROR_CODES.fetch("PROVIDER_NOT_FOUND")) unless provider

  provider
end

.sso_sign_in_endpoint(config = {}) ⇒ Object



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/better_auth/plugins/sso.rb', line 291

def (config = {})
  Endpoint.new(path: "/sign-in/sso", method: "POST") do |ctx|
    body = normalize_hash(ctx.body)
    provider = sso_select_provider(ctx, body, config)
    provider_type = body[:provider_type].to_s
    if provider_type == "oidc" && !provider["oidcConfig"]
      raise APIError.new("BAD_REQUEST", message: "OIDC provider is not configured")
    end
    if provider_type == "saml" && !provider["samlConfig"]
      raise APIError.new("BAD_REQUEST", message: "SAML provider is not configured")
    end
    if config.dig(:domain_verification, :enabled) && !(provider.key?("domainVerified") && provider["domainVerified"])
      raise APIError.new("UNAUTHORIZED", message: "Provider domain has not been verified")
    end

    state_data = {
      providerId: provider.fetch("providerId"),
      callbackURL: body[:callback_url] || "/",
      errorURL: body[:error_callback_url],
      newUserURL: body[:new_user_callback_url],
      requestSignUp: body[:request_sign_up]
    }

    if provider["oidcConfig"] && provider_type != "saml"
      provider = sso_ensure_runtime_oidc_provider(ctx, provider, config)
      state = BetterAuth::Crypto.sign_jwt(state_data.merge(sso_oidc_pkce_state(provider)), ctx.context.secret, expires_in: 600)
      url = sso_oidc_authorization_url(provider, ctx, state, config, body)
    elsif provider["samlConfig"]
      relay_state = sso_generate_saml_relay_state(ctx, state_data)
      url = sso_saml_authorization_url(provider, relay_state, ctx, config)
      sso_store_saml_authn_request(ctx, provider, url, config)
    else
      raise APIError.new("BAD_REQUEST", message: "OIDC provider is not configured")
    end
    ctx.json({url: url, redirect: true})
  end
end

.sso_signed_saml_redirect_query(provider, query) ⇒ Object

Raises:

  • (APIError)


948
949
950
951
952
953
954
955
956
957
958
959
# File 'lib/better_auth/plugins/sso.rb', line 948

def sso_signed_saml_redirect_query(provider, query)
  saml_config = normalize_hash(provider["samlConfig"] || {})
  private_key = saml_config.dig(:sp_metadata, :private_key) || saml_config[:private_key] || saml_config[:sp_private_key]
  raise APIError.new("BAD_REQUEST", message: "SAML Redirect signing requires privateKey") if private_key.to_s.empty?

  sig_alg = saml_config[:signature_algorithm] ? sso_normalize_saml_signature_algorithm(saml_config[:signature_algorithm]) : XMLSecurity::Document::RSA_SHA256
  signed = query.compact.merge(SigAlg: sig_alg)
  signed_payload = signed.keys.map(&:to_s).select { |key| %w[SAMLRequest SAMLResponse RelayState SigAlg].include?(key) }.map { |key| [key, signed[key.to_sym] || signed[key]] }.reject { |_key, value| value.nil? }
  signature_input = URI.encode_www_form(signed_payload)
  signed[:Signature] = Base64.strict_encode64(OpenSSL::PKey.read(private_key).sign(sso_saml_signature_digest(sig_alg), signature_input))
  signed
end

.sso_sp_metadata_endpoint(config = {}) ⇒ Object



413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/better_auth/plugins/sso.rb', line 413

def (config = {})
  Endpoint.new(path: "/sso/saml2/sp/metadata", method: "GET") do |ctx|
    provider = sso_find_provider!(ctx, sso_fetch(ctx.query, :provider_id))
     = (ctx, provider, config)
    if (ctx.query[:format] || ctx.query["format"]) == "json"
      ctx.json({providerId: provider.fetch("providerId"), metadata: })
    else
      ctx.set_header("content-type", "application/samlmetadata+xml")
      ctx.json()
    end
  end
end

.sso_sp_metadata_xml(ctx, provider, config = {}) ⇒ Object



693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
# File 'lib/better_auth/plugins/sso.rb', line 693

def (ctx, provider, config = {})
  provider_id = provider.fetch("providerId")
  saml_config = normalize_hash(provider["samlConfig"] || {})
   = saml_config.dig(:sp_metadata, :metadata)
  return  unless .to_s.empty?

  entity_id = saml_config.dig(:sp_metadata, :entity_id) || saml_config[:audience] || provider["issuer"] || "#{ctx.context.base_url}/sso/saml2/sp/metadata?providerId=#{URI.encode_www_form_component(provider_id)}"
  acs_url = sso_saml_acs_url(ctx, provider)
  authn_requests_signed = !!saml_config[:authn_requests_signed]
  want_assertions_signed = saml_config.key?(:want_assertions_signed) ? !!saml_config[:want_assertions_signed] : true
  name_id_format = saml_config[:identifier_format].to_s.empty? ? "" : "<NameIDFormat>#{saml_config[:identifier_format]}</NameIDFormat>"
  slo = if config.dig(:saml, :enable_single_logout)
    location = "#{ctx.context.base_url}/sso/saml2/sp/slo/#{URI.encode_www_form_component(provider_id)}"
    "<SingleLogoutService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" Location=\"#{location}\" /><SingleLogoutService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect\" Location=\"#{location}\" />"
  end

  "<EntityDescriptor entityID=\"#{entity_id}\"><SPSSODescriptor AuthnRequestsSigned=\"#{authn_requests_signed}\" WantAssertionsSigned=\"#{want_assertions_signed}\">#{slo}#{name_id_format}<AssertionConsumerService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" Location=\"#{acs_url}\" index=\"0\" /></SPSSODescriptor></EntityDescriptor>"
end

.sso_storage_config(config) ⇒ Object



1516
1517
1518
1519
1520
# File 'lib/better_auth/plugins/sso.rb', line 1516

def sso_storage_config(config)
  normalize_hash(config || {}).each_with_object({}) do |(key, value), result|
    result[Schema.storage_key(key)] = value unless value.respond_to?(:call)
  end
end

.sso_store_saml_authn_request(ctx, provider, url, config) ⇒ Object



1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
# File 'lib/better_auth/plugins/sso.rb', line 1216

def sso_store_saml_authn_request(ctx, provider, url, config)
  return if config.dig(:saml, :enable_in_response_to_validation) == false

  request_id = sso_extract_saml_request_id(url)
  return if request_id.to_s.empty?

  ttl_ms = (config.dig(:saml, :request_ttl) || SSO_DEFAULT_AUTHN_REQUEST_TTL_MS).to_i
  now_ms = (Time.now.to_f * 1000).to_i
  expires_at_ms = now_ms + ttl_ms
  record = {
    id: request_id,
    providerId: provider.fetch("providerId"),
    createdAt: now_ms,
    expiresAt: expires_at_ms
  }
  ctx.context.internal_adapter.create_verification_value(
    identifier: "#{SSO_SAML_AUTHN_REQUEST_KEY_PREFIX}#{request_id}",
    value: JSON.generate(record),
    expiresAt: Time.at(expires_at_ms / 1000.0)
  )
end

.sso_store_saml_logout_request(ctx, provider, request_id, config) ⇒ Object



861
862
863
864
865
866
867
868
# File 'lib/better_auth/plugins/sso.rb', line 861

def sso_store_saml_logout_request(ctx, provider, request_id, config)
  ttl_ms = (config.dig(:saml, :logout_request_ttl) || SSO_DEFAULT_LOGOUT_REQUEST_TTL_MS).to_i
  ctx.context.internal_adapter.create_verification_value(
    identifier: "#{SSO_SAML_LOGOUT_REQUEST_KEY_PREFIX}#{request_id}",
    value: provider.fetch("providerId"),
    expiresAt: Time.now + (ttl_ms / 1000.0)
  )
end

.sso_store_saml_session(ctx, provider, assertion, session) ⇒ Object



816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
# File 'lib/better_auth/plugins/sso.rb', line 816

def sso_store_saml_session(ctx, provider, assertion, session)
  name_id = assertion[:name_id] || assertion[:nameid] || assertion[:email]
  session_index = assertion[:session_index] || assertion[:sessionindex] || assertion[:id]
  return if name_id.to_s.empty? || session_index.to_s.empty?

  record = {
    providerId: provider.fetch("providerId"),
    sessionToken: session.fetch("token"),
    userId: session.fetch("userId"),
    nameId: name_id.to_s,
    sessionIndex: session_index.to_s
  }
  expires_at = session["expiresAt"] || Time.now + (SSO_DEFAULT_ASSERTION_TTL_MS / 1000.0)
  value = JSON.generate(record)
  session_identifier = "#{SSO_SAML_SESSION_KEY_PREFIX}#{provider.fetch("providerId")}:#{name_id}"
  ctx.context.internal_adapter.create_verification_value(
    identifier: session_identifier,
    value: value,
    expiresAt: expires_at
  )
  ctx.context.internal_adapter.create_verification_value(
    identifier: "#{SSO_SAML_SESSION_BY_ID_KEY_PREFIX}#{session.fetch("token")}",
    value: session_identifier,
    expiresAt: expires_at
  )
end

.sso_update_provider_endpointObject



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/better_auth/plugins/sso.rb', line 248

def sso_update_provider_endpoint
  Endpoint.new(path: "/sso/update-provider", method: "POST") do |ctx|
    session = Routes.current_session(ctx)
    body = normalize_hash(ctx.body)
    provider = sso_find_provider!(ctx, sso_fetch(body, :provider_id) || sso_fetch(ctx.params, :provider_id))
    raise APIError.new("FORBIDDEN", message: "You don't have access to this provider") unless sso_provider_access?(provider, session.fetch(:user).fetch("id"), ctx)

    if !body.key?(:issuer) && !body.key?(:domain) && !body.key?(:oidc_config) && !body.key?(:saml_config)
      raise APIError.new("BAD_REQUEST", message: "No fields provided for update")
    end
    sso_validate_url!(body[:issuer], "Invalid issuer. Must be a valid URL") if body.key?(:issuer)
    update = {}
    update[:issuer] = body[:issuer] if body.key?(:issuer)
    update[:domain] = body[:domain].to_s.downcase if body.key?(:domain)
    update[:domainVerified] = false if body.key?(:domain) && body[:domain].to_s.downcase != provider["domain"].to_s
    if body.key?(:oidc_config)
      current = sso_provider_config_hash(provider["oidcConfig"])
      raise APIError.new("BAD_REQUEST", message: "Cannot update OIDC config for a provider that doesn't have OIDC configured") if current.empty?

      update[:oidcConfig] = current.merge(normalize_hash(body[:oidc_config]))
    end
    if body.key?(:saml_config)
      current = sso_provider_config_hash(provider["samlConfig"])
      raise APIError.new("BAD_REQUEST", message: "Cannot update SAML config for a provider that doesn't have SAML configured") if current.empty?

      update[:samlConfig] = current.merge(normalize_hash(body[:saml_config]))
    end
    updated = ctx.context.adapter.update(model: "ssoProvider", where: [{field: "id", value: provider.fetch("id")}], update: update)
    ctx.json(sso_sanitize_provider(updated, ctx.context))
  end
end

.sso_validate_oidc_id_token(token, jwks_endpoint:, audience:, issuer:, fetch: nil) ⇒ Object



1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
# File 'lib/better_auth/plugins/sso.rb', line 1432

def sso_validate_oidc_id_token(token, jwks_endpoint:, audience:, issuer:, fetch: nil)
  jwks = sso_fetch_oidc_jwks(jwks_endpoint, fetch: fetch)
  payload, = ::JWT.decode(
    token.to_s,
    nil,
    true,
    algorithms: %w[RS256 RS384 RS512 ES256 ES384 ES512],
    jwks: jwks,
    aud: audience,
    verify_aud: true,
    iss: issuer,
    verify_iss: true
  )
  payload
rescue
  nil
end

.sso_validate_organization_membership!(ctx, user_id, organization_id) ⇒ Object

Raises:

  • (APIError)


1537
1538
1539
1540
1541
1542
1543
# File 'lib/better_auth/plugins/sso.rb', line 1537

def sso_validate_organization_membership!(ctx, user_id, organization_id)
  member = ctx.context.adapter.find_one(
    model: "member",
    where: [{field: "userId", value: user_id}, {field: "organizationId", value: organization_id}]
  )
  raise APIError.new("BAD_REQUEST", message: "You are not a member of the organization") unless member
end

.sso_validate_saml_algorithm_group!(algorithms, allowed:, secure:, deprecated:, on_deprecated:, label:) ⇒ Object



1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
# File 'lib/better_auth/plugins/sso.rb', line 1120

def sso_validate_saml_algorithm_group!(algorithms, allowed:, secure:, deprecated:, on_deprecated:, label:)
  algorithms.each do |algorithm|
    if allowed
      next if allowed.include?(algorithm)

      raise APIError.new("BAD_REQUEST", message: "SAML #{label} algorithm not in allow-list: #{algorithm}")
    end

    if deprecated.include?(algorithm)
      raise APIError.new("BAD_REQUEST", message: "SAML response uses deprecated #{label} algorithm: #{algorithm}") if on_deprecated == "reject"
      next
    end
    next if secure.include?(algorithm)

    raise APIError.new("BAD_REQUEST", message: "SAML #{label} algorithm not recognized: #{algorithm}")
  end
end

.sso_validate_saml_algorithms!(xml, options = {}) ⇒ Object



1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
# File 'lib/better_auth/plugins/sso.rb', line 1069

def sso_validate_saml_algorithms!(xml, options = {})
  on_deprecated = (options[:on_deprecated] || "warn").to_s
  signature_algorithms = xml.to_s.scan(/SignatureMethod[^>]+Algorithm=["']([^"']+)["']/).flatten.map { |algorithm| sso_normalize_saml_signature_algorithm(algorithm) }
  digest_algorithms = xml.to_s.scan(/DigestMethod[^>]+Algorithm=["']([^"']+)["']/).flatten.map { |algorithm| sso_normalize_saml_digest_algorithm(algorithm) }
  key_encryption_algorithms = xml.to_s.scan(/<[^\/>]*EncryptedKey\b[\s\S]*?EncryptionMethod[^>]+Algorithm=["']([^"']+)["']/).flatten
  data_encryption_algorithms = xml.to_s.scan(/<[^\/>]*EncryptedData\b[\s\S]*?EncryptionMethod[^>]+Algorithm=["']([^"']+)["']/).flatten

  sso_validate_saml_algorithm_group!(
    signature_algorithms,
    allowed: options[:allowed_signature_algorithms]&.map { |algorithm| sso_normalize_saml_signature_algorithm(algorithm) },
    secure: SSO_SAML_SECURE_SIGNATURE_ALGORITHMS,
    deprecated: ["http://www.w3.org/2000/09/xmldsig#rsa-sha1"],
    on_deprecated: on_deprecated,
    label: "signature"
  )
  sso_validate_saml_algorithm_group!(
    digest_algorithms,
    allowed: options[:allowed_digest_algorithms]&.map { |algorithm| sso_normalize_saml_digest_algorithm(algorithm) },
    secure: SSO_SAML_SECURE_DIGEST_ALGORITHMS,
    deprecated: ["http://www.w3.org/2000/09/xmldsig#sha1"],
    on_deprecated: on_deprecated,
    label: "digest"
  )
  sso_validate_saml_algorithm_group!(
    key_encryption_algorithms,
    allowed: options[:allowed_key_encryption_algorithms],
    secure: SSO_SAML_SECURE_KEY_ENCRYPTION_ALGORITHMS,
    deprecated: ["http://www.w3.org/2001/04/xmlenc#rsa-1_5"],
    on_deprecated: on_deprecated,
    label: "key encryption"
  )
  sso_validate_saml_algorithm_group!(
    data_encryption_algorithms,
    allowed: options[:allowed_data_encryption_algorithms],
    secure: SSO_SAML_SECURE_DATA_ENCRYPTION_ALGORITHMS,
    deprecated: ["http://www.w3.org/2001/04/xmlenc#tripledes-cbc"],
    on_deprecated: on_deprecated,
    label: "data encryption"
  )

  true
end

.sso_validate_saml_config!(saml_config, plugin_config = {}) ⇒ Object



668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
# File 'lib/better_auth/plugins/sso.rb', line 668

def sso_validate_saml_config!(saml_config, plugin_config = {})
   = saml_config[:idp_metadata] || saml_config[:metadata] || saml_config[:idp_metadata_xml]
   = plugin_config.dig(:saml, :max_metadata_size) || SSO_DEFAULT_MAX_SAML_METADATA_SIZE
  if .to_s.bytesize > 
    raise APIError.new("BAD_REQUEST", message: "IdP metadata exceeds maximum allowed size (#{} bytes)")
  end

  if saml_config[:entry_point].to_s.empty? && saml_config[:single_sign_on_service].to_s.empty? && .to_s.empty?
    raise APIError.new("BAD_REQUEST", message: "SAML config must include entryPoint, singleSignOnService, or IdP metadata")
  end
  sso_validate_url!(saml_config[:entry_point], "SAML entryPoint must be a valid URL") unless saml_config[:entry_point].to_s.empty?
  unless saml_config[:single_sign_on_service].to_s.empty?
    sso_validate_url!(saml_config[:single_sign_on_service], "SAML singleLogoutService must be a valid URL")
  end

  sso_validate_saml_algorithms!(
    .to_s,
    on_deprecated: plugin_config.dig(:saml, :algorithms, :on_deprecated) || saml_config[:on_deprecated_algorithm] || "warn",
    allowed_signature_algorithms: plugin_config.dig(:saml, :algorithms, :allowed_signature_algorithms) || saml_config[:allowed_signature_algorithms],
    allowed_digest_algorithms: plugin_config.dig(:saml, :algorithms, :allowed_digest_algorithms) || saml_config[:allowed_digest_algorithms],
    allowed_key_encryption_algorithms: plugin_config.dig(:saml, :algorithms, :allowed_key_encryption_algorithms) || saml_config[:allowed_key_encryption_algorithms],
    allowed_data_encryption_algorithms: plugin_config.dig(:saml, :algorithms, :allowed_data_encryption_algorithms) || saml_config[:allowed_data_encryption_algorithms]
  )
end

.sso_validate_saml_in_response_to(ctx, config, provider, raw_response, state) ⇒ Object



1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
# File 'lib/better_auth/plugins/sso.rb', line 1249

def sso_validate_saml_in_response_to(ctx, config, provider, raw_response, state)
  return nil if config.dig(:saml, :enable_in_response_to_validation) == false

  in_response_to = sso_extract_saml_in_response_to(raw_response)
  if in_response_to && !in_response_to.empty?
    identifier = "#{SSO_SAML_AUTHN_REQUEST_KEY_PREFIX}#{in_response_to}"
    verification = ctx.context.internal_adapter.find_verification_value(identifier)
    record = sso_parse_saml_authn_request_record(verification&.fetch("value", nil))
    if !record || record["expiresAt"].to_i < (Time.now.to_f * 1000).to_i
      return sso_redirect(ctx, sso_append_error(state["callbackURL"] || "/", "invalid_saml_response", "Unknown or expired request ID"))
    end

    if record["providerId"] != provider.fetch("providerId")
      ctx.context.internal_adapter.delete_verification_by_identifier(identifier)
      return sso_redirect(ctx, sso_append_error(state["callbackURL"] || "/", "invalid_saml_response", "Provider mismatch"))
    end

    ctx.context.internal_adapter.delete_verification_by_identifier(identifier)
  elsif config.dig(:saml, :allow_idp_initiated) == false
    return sso_redirect(ctx, sso_append_error(state["callbackURL"] || "/", "unsolicited_response", "IdP-initiated SSO not allowed"))
  end

  nil
end

.sso_validate_saml_response!(config, assertion, provider, ctx) ⇒ Object

Raises:

  • (APIError)


660
661
662
663
664
665
666
# File 'lib/better_auth/plugins/sso.rb', line 660

def sso_validate_saml_response!(config, assertion, provider, ctx)
  validator = config.dig(:saml, :validate_response)
  return unless validator.respond_to?(:call)
  return if validator.call(response: assertion, provider: provider, context: ctx)

  raise APIError.new("BAD_REQUEST", message: "Invalid SAML response")
end

.sso_validate_saml_timestamp!(conditions, config = {}, now: Time.now.utc) ⇒ Object

Raises:

  • (APIError)


1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
# File 'lib/better_auth/plugins/sso.rb', line 1029

def sso_validate_saml_timestamp!(conditions, config = {}, now: Time.now.utc)
  conditions = normalize_hash(conditions || {})
  not_before = conditions[:not_before] || conditions[:notBefore]
  not_on_or_after = conditions[:not_on_or_after] || conditions[:notOnOrAfter]
  if not_before.to_s.empty? && not_on_or_after.to_s.empty?
    raise APIError.new("BAD_REQUEST", message: "SAML assertion missing required timestamp conditions") if config.dig(:saml, :require_timestamps)

    return true
  end

  clock_skew_seconds = ((config.dig(:saml, :clock_skew) || SSO_DEFAULT_CLOCK_SKEW_MS).to_f / 1000.0)
  parsed_not_before = sso_parse_saml_timestamp(not_before, "SAML assertion has invalid NotBefore timestamp") unless not_before.to_s.empty?
  parsed_not_on_or_after = sso_parse_saml_timestamp(not_on_or_after, "SAML assertion has invalid NotOnOrAfter timestamp") unless not_on_or_after.to_s.empty?

  raise APIError.new("BAD_REQUEST", message: "SAML assertion is not yet valid") if parsed_not_before && now < (parsed_not_before - clock_skew_seconds)
  raise APIError.new("BAD_REQUEST", message: "SAML assertion has expired") if parsed_not_on_or_after && now > (parsed_not_on_or_after + clock_skew_seconds)

  true
end

.sso_validate_single_saml_assertion!(saml_response) ⇒ Object



1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
# File 'lib/better_auth/plugins/sso.rb', line 1010

def sso_validate_single_saml_assertion!(saml_response)
  xml = Base64.decode64(saml_response.to_s)
  raise APIError.new("BAD_REQUEST", message: "Invalid base64-encoded SAML response") unless xml.include?("<")

  assertions = xml.scan(/<(?:\w+:)?Assertion(?:\s|>|\/)/).length
  encrypted_assertions = xml.scan(/<(?:\w+:)?EncryptedAssertion(?:\s|>|\/)/).length
  total = assertions + encrypted_assertions
  raise APIError.new("BAD_REQUEST", message: "SAML response contains no assertions") if total.zero?
  if total > 1
    raise APIError.new("BAD_REQUEST", message: "SAML response contains #{total} assertions, expected exactly 1")
  end

  true
rescue APIError
  raise
rescue
  raise APIError.new("BAD_REQUEST", message: "Invalid base64-encoded SAML response")
end

.sso_validate_url!(value, message) ⇒ Object



1528
1529
1530
1531
1532
1533
1534
1535
# File 'lib/better_auth/plugins/sso.rb', line 1528

def sso_validate_url!(value, message)
  uri = URI(value.to_s)
  unless uri.is_a?(URI::HTTP) && !uri.host.to_s.empty?
    raise APIError.new("BAD_REQUEST", message: message)
  end
rescue URI::InvalidURIError
  raise APIError.new("BAD_REQUEST", message: message)
end

.sso_verify_domain_endpoint(config) ⇒ Object



506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# File 'lib/better_auth/plugins/sso.rb', line 506

def sso_verify_domain_endpoint(config)
  Endpoint.new(path: "/sso/verify-domain", method: "POST") do |ctx|
    session = Routes.current_session(ctx)
    provider = sso_find_provider!(ctx, normalize_hash(ctx.body)[:provider_id])
    sso_authorize_domain_verification!(ctx, provider, session.fetch(:user).fetch("id"))
    if provider.key?("domainVerified") && provider["domainVerified"]
      raise APIError.new("CONFLICT", message: "Domain has already been verified", code: "DOMAIN_VERIFIED")
    end

    identifier = sso_domain_verification_identifier(config, provider.fetch("providerId"))
    if identifier.length > 63
      raise APIError.new("BAD_REQUEST", message: "Verification identifier exceeds the DNS label limit of 63 characters", code: "IDENTIFIER_TOO_LONG")
    end
    active = ctx.context.internal_adapter.find_verification_value(identifier)
    if !active || !sso_future_time?(active.fetch("expiresAt"))
      raise APIError.new("NOT_FOUND", message: "No pending domain verification exists", code: "NO_PENDING_VERIFICATION")
    end

    hostname = sso_hostname_from_domain(provider.fetch("domain"))
    raise APIError.new("BAD_REQUEST", message: "Invalid domain", code: "INVALID_DOMAIN") if hostname.to_s.empty?

    records = sso_resolve_txt_records("#{identifier}.#{hostname}", config)
    expected = "#{identifier}=#{active.fetch("value")}"
    unless records.flatten.any? { |record| record.to_s.include?(expected) }
      raise APIError.new("BAD_GATEWAY", message: "Unable to verify domain ownership. Try again later", code: "DOMAIN_VERIFICATION_FAILED")
    end

    ctx.context.adapter.update(model: "ssoProvider", where: [{field: "id", value: provider.fetch("id")}], update: {domainVerified: true})
    ctx.context.internal_adapter.delete_verification_by_identifier(identifier)
    ctx.set_status(204)
    nil
  end
end

.sso_verify_state(value, secret) ⇒ Object



1171
1172
1173
1174
1175
# File 'lib/better_auth/plugins/sso.rb', line 1171

def sso_verify_state(value, secret)
  BetterAuth::Crypto.verify_jwt(value.to_s, secret)
rescue
  nil
end