Module: BetterAuth::Plugins
- Defined in:
- lib/better_auth/sso/plugin/oidc_core.rb,
lib/better_auth/sso/plugin/oidc_runtime.rb,
lib/better_auth/sso/plugin/oidc_discovery.rb
Constant Summary collapse
- 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
- .sso_append_error(url, error, description = nil) ⇒ Object
- .sso_base64_urlsafe(value) ⇒ Object
- .sso_callback_provider(ctx, config, provider_id) ⇒ Object
- .sso_consume_saml_in_response_to(ctx, result) ⇒ Object
- .sso_decode_jwt_payload(token) ⇒ Object
- .sso_decode_state(state, secret) ⇒ Object
- .sso_default_provider(config, provider_id:, domain:) ⇒ Object
- .sso_discover_oidc_config(issuer:, fetch: nil, existing_config: nil, discovery_endpoint: nil, trusted_origin: nil, timeout: nil) ⇒ Object
- .sso_ensure_runtime_oidc_provider(ctx, provider, plugin_config, require_jwks: false) ⇒ Object
- .sso_exchange_oidc_code(token_endpoint:, code:, code_verifier:, redirect_uri:, client_id:, client_secret:, authentication:, timeout: nil, max_body_size: nil) ⇒ Object
- .sso_extract_saml_in_response_to(raw_response) ⇒ Object
- .sso_extract_saml_request_id(url) ⇒ Object
- .sso_fetch_oidc_jwks(jwks_endpoint, fetch: nil) ⇒ Object
- .sso_fetch_oidc_user_info(endpoint, access_token, timeout: nil, max_body_size: nil) ⇒ Object
- .sso_hydrate_oidc_config(issuer, oidc_config, ctx) ⇒ Object
- .sso_normalize_discovery_url(value, issuer, trusted_origin) ⇒ Object
- .sso_oidc_authorization_url(provider, ctx, state, plugin_config = {}, body = {}) ⇒ Object
- .sso_oidc_code_verifier(ctx, state) ⇒ Object
- .sso_oidc_discovery_fetcher(fetch) ⇒ Object
- .sso_oidc_http_max_body_size(value) ⇒ Object
- .sso_oidc_http_timeout(value) ⇒ Object
- .sso_oidc_needs_runtime_discovery?(oidc_config) ⇒ Boolean
- .sso_oidc_pkce_state(provider) ⇒ Object
- .sso_oidc_tokens(ctx, provider, oidc_config, state, plugin_config, raw_state: nil) ⇒ Object
- .sso_oidc_trusted_origin_enforced?(ctx) ⇒ Boolean
- .sso_oidc_user_info(ctx, oidc_config, tokens, plugin_config, expected_nonce: nil) ⇒ Object
- .sso_parse_saml_authn_request_record(value) ⇒ Object
- .sso_provider_limit(user, config) ⇒ Object
- .sso_saml_assertion_replay_expires_at(assertion, config = {}) ⇒ Object
- .sso_saml_authorization_url(provider, relay_state, ctx = nil, config = {}) ⇒ Object
- .sso_select_provider(ctx, body, config = {}) ⇒ Object
- .sso_storage_config(config) ⇒ Object
- .sso_store_oidc_pkce_verifier(ctx, state, verifier) ⇒ Object
- .sso_store_saml_authn_request(ctx, provider, url, config) ⇒ Object
- .sso_validate_oidc_endpoint_origins!(ctx, oidc_config) ⇒ Object
- .sso_validate_oidc_id_token(token, jwks_endpoint:, audience:, issuer:, fetch: nil, expected_nonce: nil) ⇒ Object
- .sso_validate_organization_membership!(ctx, user_id, organization_id) ⇒ Object
- .sso_validate_saml_in_response_to(ctx, config, provider, raw_response, state) ⇒ Object
- .sso_validate_url!(value, message) ⇒ Object
- .sso_verify_state(value, secret) ⇒ Object
Class Method Details
.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_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_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_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_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_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_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 sso_fetch_oidc_user_info(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_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..plugins.find { |plugin| plugin.id == "sso" }&.&.fetch(:oidc_discovery_fetch, nil), trusted_origin: ->(url) { ctx.context.trusted_origin?(url, allow_relative_paths: false) }, timeout: ctx.context..plugins.find { |plugin| plugin.id == "sso" }&.&.fetch(:oidc_http_timeout, nil) ) existing.merge(discovered) 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_oidc_authorization_url(provider, ctx, state, plugin_config = {}, body = {}) ⇒ Object
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 (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? login_hint = body[:login_hint] || body[:email] query[:login_hint] = login_hint if login_hint 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_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
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_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
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_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 sso_oidc_user_info(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] sso_fetch_oidc_user_info(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_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_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_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 = {}) = (assertion)[:not_on_or_after] parsed = Time.parse(.to_s) if 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 (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_select_provider(ctx, body, config = {}) ⇒ Object
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_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_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
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_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_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, ) uri = URI(value.to_s) unless uri.is_a?(URI::HTTP) && !uri.host.to_s.empty? raise APIError.new("BAD_REQUEST", message: ) end rescue URI::InvalidURIError raise APIError.new("BAD_REQUEST", message: ) 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 |