Module: BetterAuth::Plugins

Defined in:
lib/better_auth/sso/plugin/core.rb,
lib/better_auth/sso/plugin/endpoints.rb,
lib/better_auth/sso/plugin/providers.rb,
lib/better_auth/sso/plugin/oidc_runtime.rb,
lib/better_auth/sso/plugin/saml_response.rb,
lib/better_auth/sso/plugin/oidc_discovery.rb,
lib/better_auth/sso/plugin/provider_utils.rb,
lib/better_auth/sso/plugin/saml_metadata_and_logout.rb,
lib/better_auth/sso/plugin/saml_validation_and_state.rb,
lib/better_auth/sso/plugin/sign_in_and_oidc_callbacks.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
SSO_DEFAULT_OIDC_HTTP_TIMEOUT =
10
SSO_DEFAULT_OIDC_HTTP_MAX_BODY_SIZE =
1024 * 1024
SSO_OIDC_PKCE_VERIFIER_KEY_PREFIX =
"oidc-pkce-verifier:"

Class Method Summary collapse

Class Method Details

.sso(options = {}) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/better_auth/sso/plugin/core.rb', line 73

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,
    hooks: sso_hooks(config),
    error_codes: SSO_ERROR_CODES,
    options: config
  )
end

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



124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/better_auth/sso/plugin/core.rb', line 124

def sso_after_generic_callback(ctx, config = {})
  new_session = ctx.context.new_session if ctx.context.respond_to?(:new_session)
  return unless new_session && new_session[:user]
  return unless defined?(BetterAuth::SSO::Linking::OrgAssignment)

  BetterAuth::SSO::Linking::OrgAssignment.assign_organization_by_domain(
    ctx,
    user: new_session.fetch(:user),
    provisioning_options: config[:organization_provisioning],
    domain_verification: config[:domain_verification]
  )
  nil
end

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



347
348
349
350
351
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 347

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



144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/better_auth/sso/plugin/saml_response.rb', line 144

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)


63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 63

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: "INSUFFICIENT_ACCESS")
end

.sso_base64_urlsafe(value) ⇒ Object



417
418
419
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 417

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

.sso_base64_xml?(value) ⇒ Boolean

Returns:

  • (Boolean)


75
76
77
78
79
# File 'lib/better_auth/sso/plugin/saml_validation_and_state.rb', line 75

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

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



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/better_auth/sso/plugin/core.rb', line 107

def sso_before_sign_out(ctx, config = {})
  return unless config.dig(:saml, :enable_single_logout)

  token_cookie = ctx.context.auth_cookies[:session_token]
  session_token = ctx.get_signed_cookie(token_cookie.name, ctx.context.secret)
  return if session_token.to_s.empty?

  lookup_key = "#{SSO_SAML_SESSION_BY_ID_KEY_PREFIX}#{session_token}"
  session_lookup = ctx.context.internal_adapter.find_verification_value(lookup_key)
  saml_session_key = session_lookup&.fetch("value", nil)
  ctx.context.internal_adapter.delete_verification_by_identifier(saml_session_key) if saml_session_key
  ctx.context.internal_adapter.delete_verification_by_identifier(lookup_key)
  nil
rescue
  nil
end

.sso_callback_provider(ctx, config, provider_id) ⇒ Object



170
171
172
173
174
175
176
177
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 170

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_consume_saml_in_response_to(ctx, result) ⇒ Object



113
114
115
116
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 113

def sso_consume_saml_in_response_to(ctx, result)
  identifier = result.is_a?(Hash) ? result[:identifier] : nil
  ctx.context.internal_adapter.delete_verification_by_identifier(identifier) unless identifier.to_s.empty?
end

.sso_context_domain_verification_enabled?(context) ⇒ Boolean

Returns:

  • (Boolean)


138
139
140
141
142
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 138

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



338
339
340
341
342
343
344
345
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 338

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



411
412
413
414
415
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 411

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



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 353

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



122
123
124
125
126
127
128
129
130
131
# File 'lib/better_auth/sso/plugin/providers.rb', line 122

def sso_delete_provider_endpoint
  Endpoint.new(path: "/sso/delete-provider", method: "POST", metadata: sso_openapi_for(:delete_provider)) 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_delete_provider_openapiObject



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/better_auth/sso/plugin/core.rb', line 258

def sso_delete_provider_openapi
  {
    openapi: {
      description: "Delete an SSO provider",
      requestBody: OpenAPI.json_request_body(
        OpenAPI.object_schema(
          {
            provider_id: {type: "string", description: "SSO provider ID"}
          }
        )
      ),
      responses: {
        "200" => OpenAPI.json_response("SSO provider deleted", OpenAPI.success_response_schema)
      }
    }
  }
end

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



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/better_auth/sso/plugin/oidc_discovery.rb', line 7

def sso_discover_oidc_config(issuer:, fetch: nil, existing_config: nil, discovery_endpoint: nil, trusted_origin: nil, timeout: nil)
  wrapped_fetch = sso_oidc_discovery_fetcher(fetch)
  BetterAuth::SSO::OIDC::Discovery.discover_oidc_config(
    issuer: issuer,
    fetch: wrapped_fetch,
    existing_config: existing_config,
    discovery_endpoint: discovery_endpoint,
    trusted_origin: trusted_origin,
    timeout: timeout || SSO_DEFAULT_OIDC_HTTP_TIMEOUT
  )
rescue BetterAuth::SSO::OIDC::DiscoveryError => error
  raise BetterAuth::SSO::OIDC::Errors.api_error(error)
end

.sso_domain_verification_identifier(config, provider_id) ⇒ Object



81
82
83
84
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 81

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)


22
23
24
25
26
27
28
29
30
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 22

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



468
469
470
471
472
473
474
475
476
477
478
479
480
481
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 468

def sso_ensure_runtime_oidc_provider(ctx, provider, plugin_config, require_jwks: false)
  oidc_config = sso_provider_config_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) },
    timeout: plugin_config[:oidc_http_timeout]
  )
  provider.merge("oidcConfig" => oidc_config.merge(discovered))
end

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



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 210

def sso_exchange_oidc_code(token_endpoint:, code:, code_verifier:, redirect_uri:, client_id:, client_secret:, authentication:, timeout: nil, max_body_size: nil)
  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",
    open_timeout: sso_oidc_http_timeout(timeout),
    read_timeout: sso_oidc_http_timeout(timeout)
  ) { |http| http.request(request) }
  return nil unless response.is_a?(Net::HTTPSuccess)
  return nil if response.body.to_s.bytesize > sso_oidc_http_max_body_size(max_body_size)

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

.sso_extract_saml_in_response_to(raw_response) ⇒ Object



136
137
138
139
140
141
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 136

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



77
78
79
80
81
82
83
84
85
86
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 77

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



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 205

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



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 317

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.start(
    uri.hostname,
    uri.port,
    use_ssl: uri.scheme == "https",
    open_timeout: SSO_DEFAULT_OIDC_HTTP_TIMEOUT,
    read_timeout: SSO_DEFAULT_OIDC_HTTP_TIMEOUT
  ) { |http| http.get(uri.request_uri) }
  return {} unless response.is_a?(Net::HTTPSuccess)
  return {} if response.body.to_s.bytesize > SSO_DEFAULT_OIDC_HTTP_MAX_BODY_SIZE

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

.sso_fetch_oidc_user_info(endpoint, access_token, timeout: nil, max_body_size: nil) ⇒ Object



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 275

def (endpoint, access_token, timeout: nil, max_body_size: nil)
  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",
    open_timeout: sso_oidc_http_timeout(timeout),
    read_timeout: sso_oidc_http_timeout(timeout)
  ) { |http| http.request(request) }
  return {} unless response.is_a?(Net::HTTPSuccess)
  return {} if response.body.to_s.bytesize > sso_oidc_http_max_body_size(max_body_size)

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

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



61
62
63
# File 'lib/better_auth/sso/plugin/saml_response.rb', line 61

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



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/better_auth/sso/plugin/saml_response.rb', line 65

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)
    elsif !already_linked_provider && !sso_oidc_trusted_provider?(ctx, provider, email)
      return {error: "account_not_linked"}
    end

    user = found[:user]
    unless .empty?
      ctx.context.internal_adapter.(
        accountId: ,
        providerId: storage_provider_id,
        userId: user.fetch("id")
      )
    end
    oidc_config = sso_provider_config_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)


32
33
34
35
36
37
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 32

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_find_saml_provider!(ctx, provider_id, config = {}) ⇒ Object

Raises:

  • (APIError)


39
40
41
42
43
44
45
46
47
48
49
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 39

def sso_find_saml_provider!(ctx, provider_id, config = {})
  if config[:default_sso]
    provider = sso_default_provider(config, provider_id: provider_id.to_s, domain: "")
    return provider if provider && provider["samlConfig"]
  end

  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["samlConfig"]

  provider
end

.sso_future_time?(value) ⇒ Boolean

Returns:

  • (Boolean)


86
87
88
89
90
91
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 86

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



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/better_auth/sso/plugin/saml_validation_and_state.rb', line 150

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



75
76
77
78
79
80
81
82
83
# File 'lib/better_auth/sso/plugin/providers.rb', line 75

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



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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
# File 'lib/better_auth/sso/plugin/sign_in_and_oidc_callbacks.rb', line 66

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 = sso_safe_oidc_redirect_url(ctx, state["callbackURL"] || "/")
  error_url = sso_safe_oidc_redirect_url(ctx, 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
  state_provider_id = state["providerId"] || state[:providerId]
  if state_provider_id.to_s != provider_id.to_s
    return sso_redirect(ctx, sso_append_error(error_url, "invalid_state", "provider mismatch"))
  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 = sso_provider_config_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?

  raw_state = ctx.query[:state] || ctx.query["state"]
  tokens = sso_oidc_tokens(ctx, provider, oidc_config, state, config, raw_state: raw_state)
  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 = sso_provider_config_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, expected_nonce: state["nonce"] || state[:nonce])
  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)
  return sso_redirect(ctx, sso_append_error(callback_url, result.fetch(:error))) if result[:error]

  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 != "") ? sso_safe_oidc_redirect_url(ctx, state["newUserURL"]) : callback_url
  sso_redirect(ctx, redirect_to || "/")
end

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



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/better_auth/sso/plugin/saml_response.rb', line 7

def sso_handle_saml_response(ctx, config = {})
  provider = sso_find_saml_provider!(ctx, sso_fetch(ctx.params, :provider_id), config)
  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_result = sso_validate_saml_in_response_to(ctx, config, provider, raw_response, state)
  return in_response_to_result if in_response_to_result.is_a?(Array)

  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)
  sso_consume_saml_in_response_to(ctx, in_response_to_result)
  assertion_id = assertion[:id] || assertion["id"]
  unless assertion_id.to_s.empty?
    replay_key = "#{SSO_SAML_USED_ASSERTION_KEY_PREFIX}#{assertion_id}"
    if ctx.context.internal_adapter.find_verification_value(replay_key)
      callback_url = sso_safe_saml_callback_url(ctx, state["callbackURL"] || sso_saml_callback_url(provider) || "/", provider.fetch("providerId"))
      return sso_redirect(ctx, sso_append_error(callback_url, "replay_detected", "SAML assertion has already been used"))
    end
    ctx.context.internal_adapter.create_verification_value(identifier: replay_key, value: "used", expiresAt: sso_saml_assertion_replay_expires_at(assertion, config))
  end

  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_hooks(config = {}) ⇒ Object



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/better_auth/sso/plugin/core.rb', line 90

def sso_hooks(config = {})
  {
    before: [
      {
        matcher: ->(ctx) { ctx.path == "/sign-out" },
        handler: ->(ctx) { sso_before_sign_out(ctx, config) }
      }
    ],
    after: [
      {
        matcher: ->(ctx) { ctx.path.to_s.match?(%r{\A/callback/[^/]+\z}) },
        handler: ->(ctx) { sso_after_generic_callback(ctx, config) }
      }
    ]
  }
end

.sso_hostname_from_domain(domain) ⇒ Object



93
94
95
96
97
98
99
100
101
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 93

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



450
451
452
453
454
455
456
457
458
459
460
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 450

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) },
    timeout: ctx.context.options.plugins.find { |plugin| plugin.id == "sso" }&.options&.fetch(:oidc_http_timeout, nil)
  )
  existing.merge(discovered)
end

.sso_initiate_slo_endpoint(config = {}) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/better_auth/sso/plugin/endpoints.rb', line 63

def sso_initiate_slo_endpoint(config = {})
  Endpoint.new(path: "/sso/saml2/logout/:providerId", method: "POST", metadata: sso_openapi_for(:initiate_slo)) 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_initiate_slo_openapiObject



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/better_auth/sso/plugin/core.rb', line 227

def sso_initiate_slo_openapi
  {
    openapi: {
      description: "Initiate SAML single logout",
      requestBody: OpenAPI.json_request_body(
        OpenAPI.object_schema(
          {
            callback_url: {type: "string", description: "URL to return to after logout"}
          }
        ),
        required: false
      ),
      responses: {
        "200" => OpenAPI.json_response("SAML logout initiated", {type: "object", additionalProperties: true})
      }
    }
  }
end

.sso_list_providers_endpointObject



65
66
67
68
69
70
71
72
73
# File 'lib/better_auth/sso/plugin/providers.rb', line 65

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



191
192
193
194
195
196
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 191

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



30
31
32
33
34
# File 'lib/better_auth/sso/plugin/oidc_discovery.rb', line 30

def sso_normalize_discovery_url(value, issuer, trusted_origin)
  BetterAuth::SSO::OIDC::Discovery.normalize_url("url", value, issuer, trusted_origin)
rescue BetterAuth::SSO::OIDC::DiscoveryError => error
  raise BetterAuth::SSO::OIDC::Errors.api_error(error)
end

.sso_normalize_saml_digest_algorithm(algorithm) ⇒ Object



128
129
130
# File 'lib/better_auth/sso/plugin/saml_validation_and_state.rb', line 128

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



124
125
126
# File 'lib/better_auth/sso/plugin/saml_validation_and_state.rb', line 124

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)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 13

def sso_oidc_authorization_url(provider, ctx, state, plugin_config = {}, body = {})
  config = sso_provider_config_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
  decoded_state = sso_decode_state(state, ctx.context.secret)
  nonce = decoded_state&.fetch("nonce", nil)
  query[:nonce] = nonce if nonce && !nonce.to_s.empty?
   = body[:login_hint] || body[:email]
  query[:login_hint] =  if 
  code_challenge = decoded_state&.fetch("codeChallenge", nil)
  if code_challenge
    query[:code_challenge] = code_challenge
    query[:code_challenge_method] = "S256"
  end
  "#{endpoint}?#{URI.encode_www_form(query)}"
end

.sso_oidc_callback_endpoint(config = {}) ⇒ Object



51
52
53
54
55
# File 'lib/better_auth/sso/plugin/sign_in_and_oidc_callbacks.rb', line 51

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_code_verifier(ctx, state) ⇒ Object



392
393
394
395
396
397
398
399
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 392

def sso_oidc_code_verifier(ctx, state)
  return nil if state.to_s.empty?

  identifier = "#{SSO_OIDC_PKCE_VERIFIER_KEY_PREFIX}#{state}"
  verification = ctx.context.internal_adapter.find_verification_value(identifier)
  ctx.context.internal_adapter.delete_verification_by_identifier(identifier) if verification
  verification&.fetch("value", nil)
end

.sso_oidc_discovery_fetcher(fetch) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/better_auth/sso/plugin/oidc_discovery.rb', line 21

def sso_oidc_discovery_fetcher(fetch)
  return nil unless fetch

  ->(url, timeout: nil) do
    accepts_keywords = fetch.parameters.any? { |kind, name| kind == :keyrest || (kind == :key && name == :timeout) }
    accepts_keywords ? fetch.call(url, timeout: timeout) : fetch.call(url)
  end
end

.sso_oidc_http_max_body_size(value) ⇒ Object



406
407
408
409
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 406

def sso_oidc_http_max_body_size(value)
  size = value || SSO_DEFAULT_OIDC_HTTP_MAX_BODY_SIZE
  size.to_i.positive? ? size.to_i : SSO_DEFAULT_OIDC_HTTP_MAX_BODY_SIZE
end

.sso_oidc_http_timeout(value) ⇒ Object



401
402
403
404
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 401

def sso_oidc_http_timeout(value)
  timeout = value || SSO_DEFAULT_OIDC_HTTP_TIMEOUT
  timeout.to_f.positive? ? timeout.to_f : SSO_DEFAULT_OIDC_HTTP_TIMEOUT
end

.sso_oidc_needs_runtime_discovery?(oidc_config) ⇒ Boolean

Returns:

  • (Boolean)


462
463
464
465
466
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 462

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



374
375
376
377
378
379
380
381
382
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 374

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

  verifier = BetterAuth::Crypto.random_string(128)
  {
    codeVerifier: verifier,
    codeChallenge: sso_base64_urlsafe(OpenSSL::Digest::SHA256.digest(verifier))
  }
end

.sso_oidc_redirect_uri(context, provider_id) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 7

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/#{URI.encode_www_form_component(provider_id.to_s)}"
rescue URI::InvalidURIError
  "#{context.base_url}/sso/callback/#{URI.encode_www_form_component(provider_id.to_s)}"
end

.sso_oidc_shared_callback_endpoint(config = {}) ⇒ Object



57
58
59
60
61
62
63
64
# File 'lib/better_auth/sso/plugin/sign_in_and_oidc_callbacks.rb', line 57

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, raw_state: nil) ⇒ Object



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
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 179

def sso_oidc_tokens(ctx, provider, oidc_config, state, plugin_config, raw_state: nil)
  code_verifier = sso_oidc_code_verifier(ctx, raw_state || state["state"] || state[:state])
  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: code_verifier,
      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: code_verifier,
    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],
    timeout: plugin_config[:oidc_http_timeout],
    max_body_size: plugin_config[:oidc_http_max_body_size]
  )
rescue
  nil
end

.sso_oidc_trusted_origin_enforced?(ctx) ⇒ Boolean

Returns:

  • (Boolean)


498
499
500
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 498

def sso_oidc_trusted_origin_enforced?(ctx)
  Array(ctx.context.trusted_origins).map(&:to_s).uniq.length > 1
end

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

Returns:

  • (Boolean)


133
134
135
136
137
138
139
140
141
142
# File 'lib/better_auth/sso/plugin/saml_response.rb', line 133

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

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

.sso_oidc_user_info(ctx, oidc_config, tokens, plugin_config, expected_nonce: nil) ⇒ Object



239
240
241
242
243
244
245
246
247
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
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 239

def (ctx, oidc_config, tokens, plugin_config, expected_nonce: nil)
  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], timeout: plugin_config[:oidc_http_timeout], max_body_size: plugin_config[:oidc_http_max_body_size])
  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],
      expected_nonce: expected_nonce
    ) || {_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_openapi_for(route) ⇒ Object



142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/better_auth/sso/plugin/core.rb', line 142

def sso_openapi_for(route)
  {
    register_provider: sso_register_provider_openapi,
    sign_in: ,
    saml_callback: sso_saml_callback_openapi,
    saml_acs: sso_saml_acs_openapi,
    saml_slo: sso_saml_slo_openapi,
    initiate_slo: sso_initiate_slo_openapi,
    update_provider: sso_update_provider_openapi,
    delete_provider: sso_delete_provider_openapi
  }.fetch(route)
end

.sso_parse_certificate(cert) ⇒ Object



198
199
200
201
202
203
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 198

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



118
119
120
121
122
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 118

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

.sso_parse_saml_logout_request(raw_request) ⇒ Object



246
247
248
249
250
251
252
253
254
255
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 246

def sso_parse_saml_logout_request(raw_request)
  xml = Base64.decode64(raw_request.to_s.gsub(/\s+/, ""))
  {
    id: xml[/\bID=['"]([^'"]+)['"]/, 1],
    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



291
292
293
294
295
296
297
298
299
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 291

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



107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 107

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



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/better_auth/sso/plugin/saml_validation_and_state.rb', line 167

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



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/better_auth/sso/plugin/saml_validation_and_state.rb', line 7

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



61
62
63
64
65
# File 'lib/better_auth/sso/plugin/saml_validation_and_state.rb', line 61

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



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 205

def sso_process_saml_logout_request(ctx, provider, raw_request)
  data = sso_parse_saml_logout_request(raw_request)
  return data 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 data 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
  data
rescue
  {}
end

.sso_process_saml_logout_response(ctx, raw_response) ⇒ Object



233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 233

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)


51
52
53
54
55
56
57
58
59
60
61
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 51

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_body_schema(required_fields:) ⇒ Object



276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/better_auth/sso/plugin/core.rb', line 276

def sso_provider_body_schema(required_fields:)
  OpenAPI.object_schema(
    {
      provider_id: {type: "string", description: "SSO provider ID"},
      issuer: {type: "string", description: "SSO provider issuer URL"},
      domain: {type: "string", description: "Email domain for the provider"},
      oidc_config: {type: "object", additionalProperties: true, description: "OIDC provider configuration"},
      saml_config: {type: "object", additionalProperties: true, description: "SAML provider configuration"},
      organization_id: {type: "string", description: "Organization ID for this provider"},
      override_user_info: {type: "boolean", description: "Whether to override OIDC user info with ID token claims"}
    },
    required: required_fields
  )
end

.sso_provider_config_hash(value) ⇒ Object



128
129
130
131
132
133
134
135
136
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 128

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



427
428
429
430
431
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 427

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_provider_response_schemaObject



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/better_auth/sso/plugin/core.rb', line 291

def sso_provider_response_schema
  OpenAPI.object_schema(
    {
      id: {type: "string"},
      providerId: {type: "string"},
      issuer: {type: "string"},
      domain: {type: "string"},
      oidcConfig: {type: ["object", "null"], additionalProperties: true},
      samlConfig: {type: ["object", "null"], additionalProperties: true},
      userId: {type: "string"},
      organizationId: {type: ["string", "null"]},
      domainVerified: {type: "boolean"},
      redirectURI: {type: "string"},
      domainVerificationToken: {type: "string"}
    }
  )
end

.sso_redirect(ctx, location) ⇒ Object



224
225
226
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 224

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

.sso_register_provider_endpoint(config = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/better_auth/sso/plugin/providers.rb', line 7

def sso_register_provider_endpoint(config = {})
  Endpoint.new(path: "/sso/register", method: "POST", metadata: sso_openapi_for(:register_provider)) 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]
    sso_validate_oidc_endpoint_origins!(ctx, oidc_config) if oidc_config.any?
    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_register_provider_openapiObject



155
156
157
158
159
160
161
162
163
164
165
# File 'lib/better_auth/sso/plugin/core.rb', line 155

def sso_register_provider_openapi
  {
    openapi: {
      description: "Register an SSO provider",
      requestBody: OpenAPI.json_request_body(sso_provider_body_schema(required_fields: ["provider_id", "issuer", "domain"])),
      responses: {
        "200" => OpenAPI.json_response("SSO provider registered", sso_provider_response_schema)
      }
    }
  }
end

.sso_request_domain_verification_endpoint(config) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/better_auth/sso/plugin/endpoints.rb', line 97

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



103
104
105
106
107
108
109
110
111
112
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 103

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_oidc_redirect_url(ctx, url) ⇒ Object



228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 228

def sso_safe_oidc_redirect_url(ctx, url)
  app_origin = ctx.context.base_url
  value = url.to_s
  return app_origin if value.empty?

  return value if value.start_with?("/") && !value.start_with?("//")
  return app_origin unless ctx.context.trusted_origin?(value, allow_relative_paths: false)

  value
rescue
  app_origin
end

.sso_safe_saml_callback_url(ctx, url, provider_id) ⇒ Object



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 323

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



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 301

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



13
14
15
16
17
# File 'lib/better_auth/sso/plugin/endpoints.rb', line 13

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

.sso_saml_acs_openapiObject



203
204
205
206
207
208
209
210
211
212
213
# File 'lib/better_auth/sso/plugin/core.rb', line 203

def sso_saml_acs_openapi
  {
    openapi: {
      description: "Handle a SAML assertion consumer service response",
      requestBody: OpenAPI.json_request_body(sso_saml_message_schema, required: false),
      responses: {
        "200" => OpenAPI.json_response("SAML response handled", {type: "object", additionalProperties: true})
      }
    }
  }
end

.sso_saml_acs_url(ctx, provider) ⇒ Object



74
75
76
77
78
79
80
81
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 74

def sso_saml_acs_url(ctx, provider)
  provider_id = provider.fetch("providerId")
  base_url = ctx.context.base_url
  configured = sso_provider_config_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)


83
84
85
86
87
88
89
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 83

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



124
125
126
127
128
129
130
131
132
133
134
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 124

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



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 39

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 = sso_provider_config_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



7
8
9
10
11
# File 'lib/better_auth/sso/plugin/endpoints.rb', line 7

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

.sso_saml_callback_openapiObject



191
192
193
194
195
196
197
198
199
200
201
# File 'lib/better_auth/sso/plugin/core.rb', line 191

def sso_saml_callback_openapi
  {
    openapi: {
      description: "Handle a SAML identity provider callback",
      requestBody: OpenAPI.json_request_body(sso_saml_message_schema, required: false),
      responses: {
        "200" => OpenAPI.json_response("SAML callback handled", {type: "object", additionalProperties: true})
      }
    }
  }
end

.sso_saml_callback_url(provider) ⇒ Object



161
162
163
164
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 161

def sso_saml_callback_url(provider)
  saml_config = sso_provider_config_hash(provider["samlConfig"])
  saml_config[:callback_url]
end

.sso_saml_idp_metadata(provider_or_config) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 91

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



166
167
168
169
170
171
172
173
174
175
176
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 166

def sso_saml_logout_destination(provider)
  saml_config = sso_provider_config_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_message_schemaObject



309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/better_auth/sso/plugin/core.rb', line 309

def sso_saml_message_schema
  OpenAPI.object_schema(
    {
      SAMLResponse: {type: "string", description: "SAML response"},
      SAMLRequest: {type: "string", description: "SAML logout request"},
      RelayState: {type: "string", description: "SAML relay state"},
      saml_response: {type: "string", description: "SAML response"},
      saml_request: {type: "string", description: "SAML logout request"},
      relay_state: {type: "string", description: "SAML relay state"}
    }
  )
end

.sso_saml_metadata_first_text(doc, element_name) ⇒ Object



133
134
135
136
137
138
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 133

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



120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 120

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



140
141
142
143
144
145
146
147
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 140

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



153
154
155
156
157
158
159
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 153

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



372
373
374
375
376
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 372

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



149
150
151
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 149

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



359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 359

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



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/better_auth/sso/plugin/endpoints.rb', line 32

def sso_saml_slo_endpoint(config = {})
  Endpoint.new(path: "/sso/saml2/sp/slo/:providerId", method: ["GET", "POST"], metadata: sso_openapi_for(:saml_slo).merge(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)
      raw_response = sso_fetch(ctx.body, :saml_response) || sso_fetch(ctx.query, :saml_response)
      sso_validate_saml_slo_signature!(ctx, raw_response, "Invalid LogoutResponse") if config.dig(:saml, :want_logout_response_signed)
      sso_process_saml_logout_response(ctx, raw_response)
      Cookies.delete_session_cookie(ctx)
      next sso_redirect(ctx, sso_safe_slo_redirect_url(ctx, relay_state, provider.fetch("providerId")))
    end

    raw_request = sso_fetch(ctx.body, :saml_request) || sso_fetch(ctx.query, :saml_request)
    raise APIError.new("BAD_REQUEST", message: "Invalid LogoutRequest") if raw_request.to_s.empty?

    sso_validate_saml_slo_signature!(ctx, raw_request, "Invalid LogoutRequest") if config.dig(:saml, :want_logout_request_signed)
    logout_request_data = sso_process_saml_logout_request(ctx, provider, raw_request)
    in_response_to = logout_request_data[:id].to_s.empty? ? "" : " InResponseTo=\"#{CGI.escapeHTML(logout_request_data[:id].to_s)}\""
    response = Base64.strict_encode64("<samlp:LogoutResponse xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\"_#{BetterAuth::Crypto.random_string(32)}\"#{in_response_to} 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_slo_openapiObject



215
216
217
218
219
220
221
222
223
224
225
# File 'lib/better_auth/sso/plugin/core.rb', line 215

def sso_saml_slo_openapi
  {
    openapi: {
      description: "Handle SAML single logout",
      requestBody: OpenAPI.json_request_body(sso_saml_message_schema, required: false),
      responses: {
        "200" => OpenAPI.json_response("SAML single logout handled", {type: "object", additionalProperties: true})
      }
    }
  }
end

.sso_saml_timestamp_conditions(assertion) ⇒ Object



67
68
69
70
71
72
73
# File 'lib/better_auth/sso/plugin/saml_validation_and_state.rb', line 67

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)


124
125
126
127
128
129
130
131
# File 'lib/better_auth/sso/plugin/saml_response.rb', line 124

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



144
145
146
147
148
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 144

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



150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 150

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



114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 114

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



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 165

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



182
183
184
185
186
187
188
189
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 182

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



138
139
140
# File 'lib/better_auth/sso/plugin/core.rb', line 138

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

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

Raises:

  • (APIError)


143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 143

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



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/better_auth/sso/plugin/sign_in_and_oidc_callbacks.rb', line 7

def (config = {})
  Endpoint.new(path: "/sign-in/sso", method: "POST", metadata: sso_openapi_for(:sign_in)) 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)
      pkce = sso_oidc_pkce_state(provider)
      state = BetterAuth::Crypto.sign_jwt(
        state_data.merge({nonce: BetterAuth::Crypto.random_string(32)}).merge(pkce.except(:codeVerifier)),
        ctx.context.secret,
        expires_in: 600
      )
      sso_store_oidc_pkce_verifier(ctx, state, pkce[:codeVerifier]) if pkce[:codeVerifier]
      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_sign_in_openapiObject



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/better_auth/sso/plugin/core.rb', line 167

def 
  {
    openapi: {
      description: "Start an SSO sign-in flow",
      requestBody: OpenAPI.json_request_body(
        OpenAPI.object_schema(
          {
            provider_id: {type: "string", description: "SSO provider ID"},
            domain: {type: "string", description: "Email domain used to select a provider"},
            provider_type: {type: "string", enum: ["oidc", "saml"], description: "Preferred provider protocol"},
            callback_url: {type: "string", description: "URL to redirect to after successful sign-in"},
            error_callback_url: {type: "string", description: "URL to redirect to on sign-in error"},
            new_user_callback_url: {type: "string", description: "URL to redirect to for new users"},
            request_sign_up: {type: "boolean", description: "Whether the flow is requesting sign-up"}
          }
        )
      ),
      responses: {
        "200" => OpenAPI.json_response("SSO sign-in URL", OpenAPI.object_schema({url: {type: "string"}, redirect: {type: "boolean"}}, required: ["url", "redirect"]))
      }
    }
  }
end

.sso_signed_saml_redirect_query(provider, query) ⇒ Object

Raises:

  • (APIError)


346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 346

def sso_signed_saml_redirect_query(provider, query)
  saml_config = sso_provider_config_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



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/better_auth/sso/plugin/endpoints.rb', line 19

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



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 53

def (ctx, provider, config = {})
  provider_id = provider.fetch("providerId")
  saml_config = sso_provider_config_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
  escaped_entity_id = CGI.escapeHTML(entity_id.to_s)
  escaped_acs_url = CGI.escapeHTML(acs_url.to_s)
  name_id_format = saml_config[:identifier_format].to_s.empty? ? "" : "<NameIDFormat>#{CGI.escapeHTML(saml_config[:identifier_format].to_s)}</NameIDFormat>"
  slo = if config.dig(:saml, :enable_single_logout)
    location = CGI.escapeHTML("#{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=\"#{escaped_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=\"#{escaped_acs_url}\" index=\"0\" /></SPSSODescriptor></EntityDescriptor>"
end

.sso_storage_config(config) ⇒ Object



421
422
423
424
425
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 421

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_oidc_pkce_verifier(ctx, state, verifier) ⇒ Object



384
385
386
387
388
389
390
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 384

def sso_store_oidc_pkce_verifier(ctx, state, verifier)
  ctx.context.internal_adapter.create_verification_value(
    identifier: "#{SSO_OIDC_PKCE_VERIFIER_KEY_PREFIX}#{state}",
    value: verifier,
    expiresAt: Time.now + 600
  )
end

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



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 55

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



224
225
226
227
228
229
230
231
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 224

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



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
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 178

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_txt_record_exact_match?(records, expected) ⇒ Boolean

Returns:

  • (Boolean)


77
78
79
# File 'lib/better_auth/sso/plugin/provider_utils.rb', line 77

def sso_txt_record_exact_match?(records, expected)
  Array(records).flatten.any? { |record| record.to_s.strip == expected.to_s }
end

.sso_update_provider_endpoint(config = {}) ⇒ Object



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/better_auth/sso/plugin/providers.rb', line 85

def sso_update_provider_endpoint(config = {})
  Endpoint.new(path: "/sso/update-provider", method: "POST", metadata: sso_openapi_for(:update_provider)) 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?

      resolved_issuer = update[:issuer] || current[:issuer] || provider["issuer"]
      update[:oidcConfig] = current.merge(normalize_hash(body[:oidc_config])).merge(issuer: resolved_issuer).compact
      sso_validate_oidc_endpoint_origins!(ctx, update[:oidcConfig])
    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?

      resolved_issuer = update[:issuer] || current[:issuer] || provider["issuer"]
      merged_saml_config = current.merge(normalize_hash(body[:saml_config])).merge(issuer: resolved_issuer).compact
      sso_validate_saml_config!(merged_saml_config, config)
      update[:samlConfig] = merged_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_update_provider_openapiObject



246
247
248
249
250
251
252
253
254
255
256
# File 'lib/better_auth/sso/plugin/core.rb', line 246

def sso_update_provider_openapi
  {
    openapi: {
      description: "Update an SSO provider",
      requestBody: OpenAPI.json_request_body(sso_provider_body_schema(required_fields: [])),
      responses: {
        "200" => OpenAPI.json_response("SSO provider updated", sso_provider_response_schema)
      }
    }
  }
end

.sso_validate_oidc_endpoint_origins!(ctx, oidc_config) ⇒ Object



483
484
485
486
487
488
489
490
491
492
493
494
495
496
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 483

def sso_validate_oidc_endpoint_origins!(ctx, oidc_config)
  return unless sso_oidc_trusted_origin_enforced?(ctx)

  config = normalize_hash(oidc_config || {})
  %i[authorization_endpoint token_endpoint jwks_endpoint user_info_endpoint discovery_endpoint].each do |field|
    url = config[field]
    next if url.to_s.empty?

    sso_validate_url!(url, "OIDC #{Schema.storage_key(field)} must be a valid URL")
    next if ctx.context.trusted_origin?(url.to_s, allow_relative_paths: false)

    raise APIError.new("BAD_REQUEST", message: "OIDC #{Schema.storage_key(field)} is not trusted")
  end
end

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



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 294

def sso_validate_oidc_id_token(token, jwks_endpoint:, audience:, issuer:, fetch: nil, expected_nonce: 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
  )
  if expected_nonce && !expected_nonce.to_s.empty?
    token_nonce = payload["nonce"] || payload[:nonce]
    return nil if token_nonce.to_s.empty?
    return nil unless BetterAuth::Crypto.constant_time_compare(token_nonce.to_s, expected_nonce.to_s)
  end
  payload
rescue
  nil
end

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

Raises:

  • (APIError)


442
443
444
445
446
447
448
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 442

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



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/better_auth/sso/plugin/saml_validation_and_state.rb', line 132

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



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/better_auth/sso/plugin/saml_validation_and_state.rb', line 81

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



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 7

def sso_validate_saml_config!(saml_config, plugin_config = {})
   = saml_config[:idp_metadata] || saml_config[:metadata] || saml_config[:idp_metadata_xml]
   = normalize_hash(saml_config[:idp_metadata] || {})
   = ![:metadata].to_s.empty? || !saml_config[:metadata].to_s.empty? || !saml_config[:idp_metadata_xml].to_s.empty?
  has_idp_sso_service = !Array([:single_sign_on_service] || saml_config[:single_sign_on_service]).empty?
   = 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? && !has_idp_sso_service && !
    raise APIError.new("BAD_REQUEST", message: "SAML configuration requires either idpMetadata.metadata, idpMetadata.singleSignOnService, or a valid entryPoint URL")
  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 singleSignOnService must be a valid URL")
  end
  unless saml_config[:single_logout_service].to_s.empty?
    sso_validate_url!(saml_config[:single_logout_service], "SAML singleLogoutService must be a valid URL")
  end

  config_algorithm_xml = +""
  unless saml_config[:signature_algorithm].to_s.empty?
    config_algorithm_xml << "<ds:SignatureMethod Algorithm=\"#{saml_config[:signature_algorithm]}\"/>"
  end
  unless saml_config[:digest_algorithm].to_s.empty?
    config_algorithm_xml << "<ds:DigestMethod Algorithm=\"#{saml_config[:digest_algorithm]}\"/>"
  end
  sso_validate_saml_algorithms!(
    config_algorithm_xml,
    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]
  )
  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



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 88

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

    return {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_redirect_signature(ctx, raw_message, signature, sig_alg) ⇒ Object



276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 276

def sso_validate_saml_redirect_signature(ctx, raw_message, signature, sig_alg)
  provider = sso_find_provider!(ctx, sso_fetch(ctx.params, :provider_id))
  cert = (provider)[:cert]
  certificate = OpenSSL::X509::Certificate.new(cert.to_s)
  has_saml_request = sso_fetch(ctx.body, :saml_request) || sso_fetch(ctx.query, :saml_request)
  saml_param = has_saml_request ? "SAMLRequest" : "SAMLResponse"
  relay_state = sso_fetch(ctx.body, :relay_state) || sso_fetch(ctx.query, :relay_state)
  payload = [[saml_param, raw_message]]
  payload << ["RelayState", relay_state] unless relay_state.to_s.empty?
  payload << ["SigAlg", sig_alg]
  certificate.public_key.verify(sso_saml_signature_digest(sig_alg), Base64.decode64(signature.to_s), URI.encode_www_form(payload))
rescue
  false
end

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

Raises:

  • (APIError)


159
160
161
162
163
164
165
# File 'lib/better_auth/sso/plugin/saml_response.rb', line 159

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_slo_signature!(ctx, raw_message, error_message) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/better_auth/sso/plugin/saml_metadata_and_logout.rb', line 257

def sso_validate_saml_slo_signature!(ctx, raw_message, error_message)
  signature = sso_fetch(ctx.body, :signature) || sso_fetch(ctx.query, :signature)
  sig_alg = sso_fetch(ctx.body, :sig_alg) || sso_fetch(ctx.query, :sig_alg)
  if !signature.to_s.empty? && !sig_alg.to_s.empty?
    return true if sso_validate_saml_redirect_signature(ctx, raw_message, signature, sig_alg)

    raise APIError.new("BAD_REQUEST", message: error_message)
  end

  xml = Base64.decode64(raw_message.to_s.gsub(/\s+/, ""))
  return true if xml.include?("<Signature") || xml.include?(":Signature")

  raise APIError.new("BAD_REQUEST", message: error_message)
rescue APIError
  raise
rescue
  raise APIError.new("BAD_REQUEST", message: error_message)
end

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

Raises:

  • (APIError)


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/better_auth/sso/plugin/saml_validation_and_state.rb', line 41

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



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/better_auth/sso/plugin/saml_validation_and_state.rb', line 22

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



433
434
435
436
437
438
439
440
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 433

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



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
151
# File 'lib/better_auth/sso/plugin/endpoints.rb', line 119

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 sso_txt_record_exact_match?(records, 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



7
8
9
10
11
# File 'lib/better_auth/sso/plugin/oidc_runtime.rb', line 7

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