Module: BetterAuth::Plugins

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

Constant Summary collapse

SSO_ERROR_CODES =
{
  "PROVIDER_NOT_FOUND" => "No provider found",
  "INVALID_STATE" => "Invalid state",
  "SAML_RESPONSE_REPLAYED" => "SAML response has already been used"
}.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

Class Method Summary collapse

Class Method Details

.sso(options = {}) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/better_auth/plugins/sso.rb', line 59

def sso(options = {})
  config = normalize_hash(options)
  Plugin.new(
    id: "sso",
    init: ->(_ctx) { {options: {advanced: {disable_origin_check: ["/sso/saml2/callback", "/sso/saml2/sp/acs"]}}} },
    schema: sso_schema(config),
    endpoints: {
      sp_metadata: ,
      register_sso_provider: sso_register_provider_endpoint,
      sign_in_sso: (config),
      callback_sso: sso_oidc_callback_endpoint,
      callback_sso_saml: sso_saml_callback_endpoint(config),
      acs_endpoint: sso_saml_acs_endpoint(config),
      list_sso_providers: sso_list_providers_endpoint,
      get_sso_provider: sso_get_provider_endpoint,
      update_sso_provider: sso_update_provider_endpoint,
      delete_sso_provider: sso_delete_provider_endpoint,
      request_domain_verification: sso_request_domain_verification_endpoint(config),
      verify_domain: sso_verify_domain_endpoint(config)
    },
    error_codes: SSO_ERROR_CODES,
    options: config
  )
end

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



390
391
392
393
394
395
396
397
398
399
400
# File 'lib/better_auth/plugins/sso.rb', line 390

def sso_assign_organization_membership(ctx, provider, user, config)
  organization_id = provider["organizationId"]
  return if organization_id.to_s.empty?
  return unless provider["domainVerified"]
  return unless sso_email_domain_matches?(user["email"].to_s.split("@").last.to_s.downcase, provider["domain"])
  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 = config.dig(:organization_provisioning, :role) || "member"
  ctx.context.adapter.create(model: "member", data: {organizationId: organization_id, userId: user.fetch("id"), role: role, createdAt: Time.now})
end

.sso_delete_provider_endpointObject



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

def sso_delete_provider_endpoint
  Endpoint.new(path: "/sso/providers/:providerId", method: "DELETE") do |ctx|
    session = Routes.current_session(ctx)
    provider = sso_find_provider!(ctx, sso_fetch(ctx.params, :provider_id))
    raise APIError.new("FORBIDDEN", message: "Access denied") unless sso_provider_access?(provider, session.fetch(:user).fetch("id"), ctx)

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

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



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

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

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

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

.sso_email_domain_matches?(email_domain, provider_domain) ⇒ Boolean

Returns:

  • (Boolean)


550
551
552
553
554
# File 'lib/better_auth/plugins/sso.rb', line 550

def sso_email_domain_matches?(email_domain, provider_domain)
  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_fetch(data, key) ⇒ Object



635
636
637
638
639
640
641
642
643
# File 'lib/better_auth/plugins/sso.rb', line 635

def sso_fetch(data, key)
  compact = key.to_s.delete("_").downcase
  data[key] ||
    data[key.to_s] ||
    data[Schema.storage_key(key)] ||
    data[Schema.storage_key(key).to_sym] ||
    data[compact] ||
    data[compact.to_sym]
end

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



358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/better_auth/plugins/sso.rb', line 358

def sso_find_or_create_user(ctx, provider, , config = {})
   = normalize_hash()
  email = [:email].to_s.downcase
  found = ctx.context.internal_adapter.find_user_by_email(email)
  user = if found
    found[:user]
  else
    created = ctx.context.internal_adapter.create_user(
      email: email,
      name: [:name] || email,
      emailVerified: .key?(:email_verified) ? [:email_verified] : true,
      image: [:image]
    )
    ctx.context.internal_adapter.(
      accountId: ([:id] || created.fetch("id")).to_s,
      providerId: "sso:#{provider.fetch("providerId")}",
      userId: created.fetch("id")
    )
    created
  end
  sso_assign_organization_membership(ctx, provider, user, config)
  user
end

.sso_find_provider!(ctx, provider_id) ⇒ Object

Raises:

  • (APIError)


556
557
558
559
560
561
# File 'lib/better_auth/plugins/sso.rb', line 556

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: SSO_ERROR_CODES.fetch("PROVIDER_NOT_FOUND")) unless provider

  provider
end

.sso_get_provider_endpointObject



206
207
208
209
210
211
212
213
214
# File 'lib/better_auth/plugins/sso.rb', line 206

def sso_get_provider_endpoint
  Endpoint.new(path: "/sso/providers/:providerId", method: "GET") do |ctx|
    session = Routes.current_session(ctx)
    provider = sso_find_provider!(ctx, sso_fetch(ctx.params, :provider_id))
    raise APIError.new("FORBIDDEN", message: "Access denied") unless sso_provider_access?(provider, session.fetch(:user).fetch("id"), ctx)

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

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



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/better_auth/plugins/sso.rb', line 337

def sso_handle_saml_response(ctx, config = {})
  provider = sso_find_provider!(ctx, sso_fetch(ctx.params, :provider_id))
  relay_state = sso_fetch(ctx.body, :relay_state) || sso_fetch(ctx.query, :relay_state)
  state = sso_verify_state(relay_state, ctx.context.secret) || {}
  assertion = sso_parse_saml_response(sso_fetch(ctx.body, :saml_response), config, provider, ctx)
  sso_validate_saml_response!(config, assertion, provider, ctx)
  assertion_id = assertion[:id] || assertion["id"] || assertion[:email]
  replay_key = "sso-saml-assertion:#{provider.fetch("providerId")}:#{assertion_id}"
  if ctx.context.internal_adapter.find_verification_value(replay_key)
    raise APIError.new("BAD_REQUEST", message: SSO_ERROR_CODES.fetch("SAML_RESPONSE_REPLAYED"))
  end
  ctx.context.internal_adapter.create_verification_value(identifier: replay_key, value: "used", expiresAt: Time.now + 300)

  user = sso_find_or_create_user(ctx, provider, assertion, config)
  session = ctx.context.internal_adapter.create_session(user.fetch("id"))
  Cookies.set_session_cookie(ctx, {session: session, user: user})
  callback_url = state["callbackURL"] || "/"
  callback_url = "/" unless ctx.context.trusted_origin?(callback_url, allow_relative_paths: true)
  sso_redirect(ctx, callback_url)
end

.sso_list_providers_endpointObject



196
197
198
199
200
201
202
203
204
# File 'lib/better_auth/plugins/sso.rb', line 196

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



621
622
623
624
625
626
# File 'lib/better_auth/plugins/sso.rb', line 621

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

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

.sso_normalize_discovery_url(value, issuer, trusted_origin) ⇒ Object



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

def sso_normalize_discovery_url(value, issuer, trusted_origin)
  uri = URI(value.to_s)
  normalized = if uri.absolute?
    uri.to_s
  else
    issuer_uri = URI(issuer.to_s)
    URI.join("#{issuer_uri.scheme}://#{issuer_uri.host}", value.to_s).to_s
  end
  if trusted_origin && !trusted_origin.call(normalized)
    raise APIError.new("BAD_REQUEST", message: "OIDC discovery endpoint is not trusted")
  end

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

.sso_normalize_saml_digest_algorithm(algorithm) ⇒ Object



480
481
482
# File 'lib/better_auth/plugins/sso.rb', line 480

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



476
477
478
# File 'lib/better_auth/plugins/sso.rb', line 476

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) ⇒ Object



508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/better_auth/plugins/sso.rb', line 508

def sso_oidc_authorization_url(provider, ctx, state)
  config = normalize_hash(provider["oidcConfig"] || {})
  endpoint = config[:authorization_endpoint] || config[:authorization_url]
  query = {
    client_id: config[:client_id],
    response_type: "code",
    redirect_uri: "#{ctx.context.base_url}/sso/callback/#{provider.fetch("providerId")}",
    scope: Array(config[:scope] || config[:scopes] || ["openid", "email", "profile"]).join(" "),
    state: state
  }
  "#{endpoint}?#{URI.encode_www_form(query)}"
end

.sso_oidc_callback_endpointObject



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/better_auth/plugins/sso.rb', line 268

def sso_oidc_callback_endpoint
  Endpoint.new(path: "/sso/callback/:providerId", 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

    provider = sso_find_provider!(ctx, sso_fetch(ctx.params, :provider_id))
    oidc_config = normalize_hash(provider["oidcConfig"] || {})
    token_callback = oidc_config[:get_token]
    user_callback = oidc_config[:get_user_info]
    tokens = token_callback ? token_callback.call(code: ctx.query[:code] || ctx.query["code"]) : {accessToken: "access-token"}
     = user_callback ? user_callback.call(tokens) : {}
    user = sso_find_or_create_user(ctx, provider, )
    session = ctx.context.internal_adapter.create_session(user.fetch("id"))
    Cookies.set_session_cookie(ctx, {session: session, user: user})
    redirect_to = (state["newUserURL"] && !state["newUserURL"].to_s.empty?) ? state["newUserURL"] : state["callbackURL"]
    sso_redirect(ctx, redirect_to || "/")
  end
end

.sso_parse_certificate(cert) ⇒ Object



628
629
630
631
632
633
# File 'lib/better_auth/plugins/sso.rb', line 628

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_response(value, config = {}, provider = nil, ctx = nil) ⇒ Object



402
403
404
405
406
407
408
409
410
411
412
# File 'lib/better_auth/plugins/sso.rb', line 402

def sso_parse_saml_response(value, config = {}, provider = nil, ctx = nil)
  parser = config.dig(:saml, :parse_response)
  if parser.respond_to?(:call)
    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
  raise APIError.new("BAD_REQUEST", message: "Invalid SAML response")
end

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

Returns:

  • (Boolean)


563
564
565
566
567
568
569
570
571
572
573
# File 'lib/better_auth/plugins/sso.rb', line 563

def sso_provider_access?(provider, user_id, ctx)
  organization_id = provider["organizationId"]
  return provider["userId"] == user_id if organization_id.to_s.empty?
  return false 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_redirect(ctx, location) ⇒ Object



645
646
647
# File 'lib/better_auth/plugins/sso.rb', line 645

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

.sso_register_provider_endpointObject



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/better_auth/plugins/sso.rb', line 169

def sso_register_provider_endpoint
  Endpoint.new(path: "/sso/register", method: "POST") do |ctx|
    session = Routes.current_session(ctx)
    body = normalize_hash(ctx.body)
    provider_id = body[:provider_id].to_s
    raise APIError.new("BAD_REQUEST", message: "providerId is required") if provider_id.empty?
    if ctx.context.adapter.find_one(model: "ssoProvider", where: [{field: "providerId", value: provider_id}])
      raise APIError.new("BAD_REQUEST", message: "Provider already exists")
    end

    provider = ctx.context.adapter.create(
      model: "ssoProvider",
      data: {
        providerId: provider_id,
        issuer: body[:issuer].to_s,
        domain: body[:domain].to_s.downcase,
        oidcConfig: body[:oidc_config],
        samlConfig: body[:saml_config],
        userId: session.fetch(:user).fetch("id"),
        organizationId: body[:organization_id],
        domainVerified: body[:domain_verified] || false
      }
    )
    ctx.json(sso_sanitize_provider(provider, ctx.context))
  end
end

.sso_request_domain_verification_endpoint(config) ⇒ Object



312
313
314
315
316
317
318
319
320
321
# File 'lib/better_auth/plugins/sso.rb', line 312

def sso_request_domain_verification_endpoint(config)
  Endpoint.new(path: "/sso/request-domain-verification", method: "POST") do |ctx|
    Routes.current_session(ctx)
    provider = sso_find_provider!(ctx, normalize_hash(ctx.body)[:provider_id])
    token = "_better-auth-sso-verification-#{provider.fetch("providerId")}-#{SecureRandom.hex(16)}"
    updated = ctx.context.adapter.update(model: "ssoProvider", where: [{field: "id", value: provider.fetch("id")}], update: {domainVerificationToken: token, domainVerified: false})
    config.dig(:domain_verification, :request)&.call(provider: updated, token: token, context: ctx)
    ctx.json({success: true, token: token}, status: 201)
  end
end

.sso_saml_acs_endpoint(config) ⇒ Object



293
294
295
296
297
# File 'lib/better_auth/plugins/sso.rb', line 293

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

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



521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'lib/better_auth/plugins/sso.rb', line 521

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

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

.sso_saml_callback_endpoint(config) ⇒ Object



287
288
289
290
291
# File 'lib/better_auth/plugins/sso.rb', line 287

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

.sso_sanitize_config(config) ⇒ Object



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

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



594
595
596
597
598
599
600
601
602
603
604
605
606
# File 'lib/better_auth/plugins/sso.rb', line 594

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]
  }.compact
end

.sso_sanitize_provider(provider, context) ⇒ Object



575
576
577
578
579
580
581
582
583
584
585
586
# File 'lib/better_auth/plugins/sso.rb', line 575

def sso_sanitize_provider(provider, context)
  data = provider.dup
  oidc_config = normalize_hash(data["oidcConfig"] || {})
  saml_config = normalize_hash(data["samlConfig"] || {})
  data["type"] = saml_config.empty? ? "oidc" : "saml"
  data["organizationId"] ||= nil
  data["domainVerified"] = !!data["domainVerified"]
  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



608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/better_auth/plugins/sso.rb', line 608

def sso_sanitize_saml_config(config)
  {
    "entryPoint" => config[:entry_point],
    "callbackUrl" => config[:callback_url],
    "audience" => config[:audience],
    "wantAssertionsSigned" => config[:want_assertions_signed],
    "identifierFormat" => config[:identifier_format],
    "signatureAlgorithm" => config[:signature_algorithm],
    "digestAlgorithm" => config[:digest_algorithm],
    "certificate" => sso_parse_certificate(config[:cert])
  }.compact
end

.sso_schema(config = {}) ⇒ Object



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

def sso_schema(config = {})
  {
    ssoProvider: {
      model_name: config[:model_name] || "ssoProviders",
      fields: {
        issuer: {type: "string", required: true},
        oidcConfig: {type: "string", required: false},
        samlConfig: {type: "string", required: false},
        userId: {type: "string", required: true},
        providerId: {type: "string", required: true, unique: true},
        domain: {type: "string", required: true},
        domainVerified: {type: "boolean", required: false, default_value: false},
        domainVerificationToken: {type: "string", required: false},
        organizationId: {type: "string", required: false}
      }
    }
  }
end

.sso_select_provider(ctx, body) ⇒ Object

Raises:

  • (APIError)


535
536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/better_auth/plugins/sso.rb', line 535

def sso_select_provider(ctx, body)
  providers = ctx.context.adapter.find_many(model: "ssoProvider")
  provider = if body[:provider_id]
    providers.find { |entry| entry["providerId"] == body[:provider_id].to_s }
  elsif body[:issuer]
    providers.find { |entry| entry["issuer"] == body[:issuer].to_s }
  else
    domain = body[:email].to_s.split("@").last.to_s.downcase
    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



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/better_auth/plugins/sso.rb', line 245

def (config = {})
  Endpoint.new(path: "/sign-in/sso", method: "POST") do |ctx|
    body = normalize_hash(ctx.body)
    provider = sso_select_provider(ctx, body)
    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["samlConfig"]
      relay_state = BetterAuth::Crypto.sign_jwt(state_data.merge(nonce: SecureRandom.hex(8)), ctx.context.secret, expires_in: 600)
      url = sso_saml_authorization_url(provider, relay_state, ctx, config)
    else
      state = BetterAuth::Crypto.sign_jwt(state_data, ctx.context.secret, expires_in: 600)
      url = sso_oidc_authorization_url(provider, ctx, state)
    end
    ctx.json({url: url, redirect: true})
  end
end

.sso_sp_metadata_endpointObject



299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/better_auth/plugins/sso.rb', line 299

def 
  Endpoint.new(path: "/sso/saml2/sp/metadata", method: "GET") do |ctx|
    provider = sso_find_provider!(ctx, sso_fetch(ctx.query, :provider_id))
     = "<EntityDescriptor entityID=\"#{ctx.context.base_url}/sso/saml2/sp/metadata\"><SPSSODescriptor /></EntityDescriptor>"
    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_update_provider_endpointObject



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/better_auth/plugins/sso.rb', line 216

def sso_update_provider_endpoint
  Endpoint.new(path: "/sso/providers/:providerId", method: "PATCH") do |ctx|
    session = Routes.current_session(ctx)
    provider = sso_find_provider!(ctx, sso_fetch(ctx.params, :provider_id))
    raise APIError.new("FORBIDDEN", message: "Access denied") unless sso_provider_access?(provider, session.fetch(:user).fetch("id"), ctx)

    body = normalize_hash(ctx.body)
    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)
    update[:oidcConfig] = body[:oidc_config] if body.key?(:oidc_config)
    update[:samlConfig] = body[:saml_config] if body.key?(:saml_config)
    updated = ctx.context.adapter.update(model: "ssoProvider", where: [{field: "id", value: provider.fetch("id")}], update: update)
    ctx.json(sso_sanitize_provider(updated, ctx.context))
  end
end

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



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

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



433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'lib/better_auth/plugins/sso.rb', line 433

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_response!(config, assertion, provider, ctx) ⇒ Object

Raises:

  • (APIError)


382
383
384
385
386
387
388
# File 'lib/better_auth/plugins/sso.rb', line 382

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_single_saml_assertion!(saml_response) ⇒ Object



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/better_auth/plugins/sso.rb', line 414

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_verify_domain_endpoint(config) ⇒ Object



323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/better_auth/plugins/sso.rb', line 323

def sso_verify_domain_endpoint(config)
  Endpoint.new(path: "/sso/verify-domain", method: "POST") do |ctx|
    Routes.current_session(ctx)
    provider = sso_find_provider!(ctx, normalize_hash(ctx.body)[:provider_id])
    token = provider["domainVerificationToken"].to_s
    verifier = config.dig(:domain_verification, :verify)
    verified = verifier ? verifier.call(domain: provider.fetch("domain"), token: token, provider: provider, context: ctx) : true
    raise APIError.new("BAD_REQUEST", message: "Unable to verify domain ownership") unless verified

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

.sso_verify_state(value, secret) ⇒ Object



502
503
504
505
506
# File 'lib/better_auth/plugins/sso.rb', line 502

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