loading
Generated 2024-11-29T16:13:26+00:00

All Files ( 96.15% covered at 408.96 hits/line )

39 files in total.
3453 relevant lines, 3320 lines covered and 133 lines missed. ( 96.15% )
File % covered Lines Relevant Lines Lines covered Lines missed Avg. Hits / Line
lib/rodauth/features/oauth_application_management.rb 100.00 % 210 117 117 0 73.28
lib/rodauth/features/oauth_assertion_base.rb 100.00 % 92 38 38 0 57.47
lib/rodauth/features/oauth_authorization_code_grant.rb 100.00 % 165 83 83 0 621.82
lib/rodauth/features/oauth_authorize_base.rb 97.67 % 260 129 126 3 770.53
lib/rodauth/features/oauth_base.rb 96.10 % 880 436 419 17 1508.96
lib/rodauth/features/oauth_client_credentials_grant.rb 100.00 % 35 17 17 0 35.94
lib/rodauth/features/oauth_device_code_grant.rb 95.33 % 208 107 102 5 52.22
lib/rodauth/features/oauth_dpop.rb 92.67 % 409 191 177 14 72.24
lib/rodauth/features/oauth_dynamic_client_registration.rb 95.22 % 444 230 219 11 664.33
lib/rodauth/features/oauth_grant_management.rb 100.00 % 70 33 33 0 72.58
lib/rodauth/features/oauth_implicit_grant.rb 100.00 % 95 49 49 0 394.84
lib/rodauth/features/oauth_jwt.rb 100.00 % 136 59 59 0 325.12
lib/rodauth/features/oauth_jwt_base.rb 95.13 % 526 226 215 11 250.97
lib/rodauth/features/oauth_jwt_bearer_grant.rb 100.00 % 91 47 47 0 39.70
lib/rodauth/features/oauth_jwt_jwks.rb 100.00 % 47 23 23 0 48.04
lib/rodauth/features/oauth_jwt_secured_authorization_request.rb 100.00 % 143 68 68 0 144.51
lib/rodauth/features/oauth_jwt_secured_authorization_response_mode.rb 98.53 % 126 68 67 1 75.68
lib/rodauth/features/oauth_management_base.rb 100.00 % 72 39 39 0 165.23
lib/rodauth/features/oauth_pkce.rb 100.00 % 93 49 49 0 32.08
lib/rodauth/features/oauth_pushed_authorization_request.rb 92.75 % 144 69 64 5 53.42
lib/rodauth/features/oauth_resource_indicators.rb 93.90 % 166 82 77 5 58.29
lib/rodauth/features/oauth_resource_server.rb 96.30 % 59 27 26 1 64.52
lib/rodauth/features/oauth_saml_bearer_grant.rb 96.77 % 140 62 60 2 18.69
lib/rodauth/features/oauth_tls_client_auth.rb 89.29 % 168 84 75 9 135.24
lib/rodauth/features/oauth_token_introspection.rb 98.33 % 139 60 59 1 110.62
lib/rodauth/features/oauth_token_revocation.rb 100.00 % 124 60 60 0 79.77
lib/rodauth/features/oidc.rb 93.61 % 880 391 366 25 249.77
lib/rodauth/features/oidc_backchannel_logout.rb 98.15 % 120 54 53 1 48.35
lib/rodauth/features/oidc_dynamic_client_registration.rb 90.51 % 298 137 124 13 116.01
lib/rodauth/features/oidc_frontchannel_logout.rb 100.00 % 134 68 68 0 46.19
lib/rodauth/features/oidc_logout_base.rb 100.00 % 76 38 38 0 94.16
lib/rodauth/features/oidc_rp_initiated_logout.rb 95.24 % 140 63 60 3 44.71
lib/rodauth/features/oidc_self_issued.rb 97.06 % 73 34 33 1 23.38
lib/rodauth/features/oidc_session_management.rb 97.92 % 91 48 47 1 16.50
lib/rodauth/oauth.rb 100.00 % 38 19 19 0 2856.42
lib/rodauth/oauth/database_extensions.rb 100.00 % 92 42 42 0 1718.86
lib/rodauth/oauth/http_extensions.rb 95.56 % 74 45 43 2 145.40
lib/rodauth/oauth/jwe_extensions.rb 100.00 % 64 33 33 0 37.88
lib/rodauth/oauth/ttl_store.rb 92.86 % 67 28 26 2 13.32

lib/rodauth/features/oauth_application_management.rb

100.0% lines covered

117 relevant lines. 117 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_application_management, :OauthApplicationManagement) do
  5. 13 depends :oauth_management_base, :oauth_token_revocation
  6. 13 before "create_oauth_application"
  7. 13 after "create_oauth_application"
  8. 13 error_flash "There was an error registering your oauth application", "create_oauth_application"
  9. 13 notice_flash "Your oauth application has been registered", "create_oauth_application"
  10. 13 view "oauth_applications", "Oauth Applications", "oauth_applications"
  11. 13 view "oauth_application", "Oauth Application", "oauth_application"
  12. 13 view "new_oauth_application", "New Oauth Application", "new_oauth_application"
  13. 13 view "oauth_application_oauth_grants", "Oauth Application Grants", "oauth_application_oauth_grants"
  14. # Application
  15. 13 APPLICATION_REQUIRED_PARAMS = %w[name scopes homepage_url redirect_uri client_secret].freeze
  16. 13 auth_value_method :oauth_application_required_params, APPLICATION_REQUIRED_PARAMS
  17. 13 (APPLICATION_REQUIRED_PARAMS + %w[description client_id]).each do |param|
  18. 91 auth_value_method :"oauth_application_#{param}_param", param
  19. end
  20. 13 translatable_method :oauth_applications_name_label, "Name"
  21. 13 translatable_method :oauth_applications_description_label, "Description"
  22. 13 translatable_method :oauth_applications_scopes_label, "Default scopes"
  23. 13 translatable_method :oauth_applications_contacts_label, "Contacts"
  24. 13 translatable_method :oauth_applications_tos_uri_label, "Terms of service"
  25. 13 translatable_method :oauth_applications_policy_uri_label, "Policy"
  26. 13 translatable_method :oauth_applications_jwks_label, "JSON Web Keys"
  27. 13 translatable_method :oauth_applications_jwks_uri_label, "JSON Web Keys URI"
  28. 13 translatable_method :oauth_applications_homepage_url_label, "Homepage URL"
  29. 13 translatable_method :oauth_applications_redirect_uri_label, "Redirect URI"
  30. 13 translatable_method :oauth_applications_client_secret_label, "Client Secret"
  31. 13 translatable_method :oauth_applications_client_id_label, "Client ID"
  32. 13 %w[type token refresh_token expires_in revoked_at].each do |param|
  33. 65 translatable_method :"oauth_grants_#{param}_label", param.gsub("_", " ").capitalize
  34. end
  35. 13 button "Register", "oauth_application"
  36. 13 button "Revoke", "oauth_grant_revoke"
  37. 13 auth_value_method :oauth_applications_oauth_grants_path, "oauth-grants"
  38. 13 auth_value_method :oauth_applications_route, "oauth-applications"
  39. 13 auth_value_method :oauth_applications_per_page, 20
  40. 13 auth_value_method :oauth_applications_id_pattern, Integer
  41. 13 auth_value_method :oauth_grants_per_page, 20
  42. 13 translatable_method :invalid_url_message, "Invalid URL"
  43. 13 translatable_method :null_error_message, "is not filled"
  44. 13 translatable_method :oauth_no_applications_text, "No oauth applications yet!"
  45. 13 translatable_method :oauth_no_grants_text, "No oauth grants yet!"
  46. 13 auth_methods(
  47. :oauth_application_path
  48. )
  49. 13 def oauth_applications_path(opts = {})
  50. 1341 route_path(oauth_applications_route, opts)
  51. end
  52. 13 def oauth_application_path(id)
  53. 153 "#{oauth_applications_path}/#{id}"
  54. end
  55. # /oauth-applications routes
  56. 13 def load_oauth_application_management_routes
  57. 325 request.on(oauth_applications_route) do
  58. 325 check_csrf if check_csrf?
  59. 325 require_account
  60. 325 request.get "new" do
  61. 52 new_oauth_application_view
  62. end
  63. 273 request.on(oauth_applications_id_pattern) do |id|
  64. 104 oauth_application = db[oauth_applications_table]
  65. .where(oauth_applications_id_column => id)
  66. .where(oauth_applications_account_id_column => account_id)
  67. .first
  68. 104 next unless oauth_application
  69. 91 scope.instance_variable_set(:@oauth_application, oauth_application)
  70. 91 request.is do
  71. 39 request.get do
  72. 39 oauth_application_view
  73. end
  74. end
  75. 52 request.on(oauth_applications_oauth_grants_path) do
  76. 52 page = Integer(param_or_nil("page") || 1)
  77. 52 per_page = per_page_param(oauth_grants_per_page)
  78. 52 oauth_grants = db[oauth_grants_table]
  79. .where(oauth_grants_oauth_application_id_column => id)
  80. .order(Sequel.desc(oauth_grants_id_column))
  81. 52 scope.instance_variable_set(:@oauth_grants, oauth_grants.paginate(page, per_page))
  82. 52 request.is do
  83. 52 request.get do
  84. 52 oauth_application_oauth_grants_view
  85. end
  86. end
  87. end
  88. end
  89. 169 request.is do
  90. 169 request.get do
  91. 104 page = Integer(param_or_nil("page") || 1)
  92. 104 per_page = per_page_param(oauth_applications_per_page)
  93. 104 scope.instance_variable_set(:@oauth_applications, db[oauth_applications_table]
  94. .where(oauth_applications_account_id_column => account_id)
  95. .order(Sequel.desc(oauth_applications_id_column))
  96. .paginate(page, per_page))
  97. 104 oauth_applications_view
  98. end
  99. 65 request.post do
  100. 65 catch_error do
  101. 65 validate_oauth_application_params
  102. 39 transaction do
  103. 39 before_create_oauth_application
  104. 39 id = create_oauth_application
  105. 39 after_create_oauth_application
  106. 39 set_notice_flash create_oauth_application_notice_flash
  107. 39 redirect "#{request.path}/#{id}"
  108. end
  109. end
  110. 26 set_error_flash create_oauth_application_error_flash
  111. 26 new_oauth_application_view
  112. end
  113. end
  114. end
  115. end
  116. 13 private
  117. 13 def oauth_application_params
  118. 299 @oauth_application_params ||= oauth_application_required_params.each_with_object({}) do |param, params|
  119. 325 value = request.params[__send__(:"oauth_application_#{param}_param")]
  120. 325 if value && !value.empty?
  121. 162 params[param] = value
  122. else
  123. 91 set_field_error(param, null_error_message)
  124. end
  125. end
  126. end
  127. 13 def validate_oauth_application_params
  128. 65 oauth_application_params.each do |key, value|
  129. 234 if key == oauth_application_homepage_url_param
  130. 52 set_field_error(key, invalid_url_message) unless check_valid_uri?(value)
  131. 182 elsif key == oauth_application_redirect_uri_param
  132. 52 if value.respond_to?(:each)
  133. 13 value.each do |uri|
  134. 26 next if uri.empty?
  135. 26 set_field_error(key, invalid_url_message) unless check_valid_no_fragment_uri?(uri)
  136. end
  137. else
  138. 39 set_field_error(key, invalid_url_message) unless check_valid_no_fragment_uri?(value)
  139. end
  140. 130 elsif key == oauth_application_scopes_param
  141. 39 value.each do |scope|
  142. 78 set_field_error(key, oauth_invalid_scope_message) unless oauth_application_scopes.include?(scope)
  143. end
  144. end
  145. end
  146. 65 throw :rodauth_error if @field_errors && !@field_errors.empty?
  147. end
  148. 13 def create_oauth_application
  149. 15 create_params = {
  150. 24 oauth_applications_account_id_column => account_id,
  151. oauth_applications_name_column => oauth_application_params[oauth_application_name_param],
  152. oauth_applications_description_column => oauth_application_params[oauth_application_description_param],
  153. oauth_applications_scopes_column => oauth_application_params[oauth_application_scopes_param],
  154. oauth_applications_homepage_url_column => oauth_application_params[oauth_application_homepage_url_param]
  155. }
  156. 39 redirect_uris = oauth_application_params[oauth_application_redirect_uri_param]
  157. 39 redirect_uris = redirect_uris.to_a.reject(&:empty?).join(" ") if redirect_uris.respond_to?(:each)
  158. 39 create_params[oauth_applications_redirect_uri_column] = redirect_uris unless redirect_uris.empty?
  159. # set client ID/secret pairs
  160. 39 set_client_secret(create_params, oauth_application_params[oauth_application_client_secret_param])
  161. 39 if create_params[oauth_applications_scopes_column]
  162. 27 create_params[oauth_applications_scopes_column] = create_params[oauth_applications_scopes_column].join(oauth_scope_separator)
  163. end
  164. 39 rescue_from_uniqueness_error do
  165. 27 create_params[oauth_applications_client_id_column] = oauth_unique_id_generator
  166. 39 db[oauth_applications_table].insert(create_params)
  167. end
  168. end
  169. end
  170. end

lib/rodauth/features/oauth_assertion_base.rb

100.0% lines covered

38 relevant lines. 38 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_assertion_base, :OauthAssertionBase) do
  5. 13 depends :oauth_base
  6. 13 auth_methods(
  7. :assertion_grant_type?,
  8. :client_assertion_type?,
  9. :assertion_grant_type,
  10. :client_assertion_type
  11. )
  12. 13 private
  13. 13 def validate_token_params
  14. 104 return super unless assertion_grant_type?
  15. 52 redirect_response_error("invalid_grant") unless param_or_nil("assertion")
  16. end
  17. 13 def require_oauth_application
  18. 208 if assertion_grant_type?
  19. 52 @oauth_application = __send__(:"require_oauth_application_from_#{assertion_grant_type}_assertion_issuer", param("assertion"))
  20. 156 elsif client_assertion_type?
  21. 117 @oauth_application = __send__(:"require_oauth_application_from_#{client_assertion_type}_assertion_subject",
  22. param("client_assertion"))
  23. 78 if (client_id = param_or_nil("client_id")) &&
  24. client_id != @oauth_application[oauth_applications_client_id_column]
  25. # If present, the value of the
  26. # "client_id" parameter MUST identify the same client as is
  27. # identified by the client assertion.
  28. 26 redirect_response_error("invalid_grant")
  29. end
  30. else
  31. 39 super
  32. end
  33. end
  34. 13 def account_from_bearer_assertion_subject(subject)
  35. 52 __insert_or_do_nothing_and_return__(
  36. db[accounts_table],
  37. account_id_column,
  38. [login_column],
  39. login_column => subject
  40. )
  41. end
  42. 13 def create_token(grant_type)
  43. 65 return super unless assertion_grant_type?(grant_type) && supported_grant_type?(grant_type)
  44. 52 account = __send__(:"account_from_#{assertion_grant_type}_assertion", param("assertion"))
  45. 52 redirect_response_error("invalid_grant") unless account
  46. 52 grant_scopes = if param_or_nil("scope")
  47. 26 redirect_response_error("invalid_scope") unless check_valid_scopes?
  48. 13 scopes
  49. else
  50. 26 @oauth_application[oauth_applications_scopes_column]
  51. end
  52. 15 grant_params = {
  53. 24 oauth_grants_type_column => grant_type,
  54. oauth_grants_account_id_column => account[account_id_column],
  55. oauth_grants_oauth_application_id_column => @oauth_application[oauth_applications_id_column],
  56. oauth_grants_scopes_column => grant_scopes
  57. }
  58. 39 generate_token(grant_params, false)
  59. end
  60. 13 def assertion_grant_type?(grant_type = param("grant_type"))
  61. 377 grant_type.start_with?("urn:ietf:params:oauth:grant-type:")
  62. end
  63. 13 def client_assertion_type?(client_assertion_type = param("client_assertion_type"))
  64. 156 client_assertion_type.start_with?("urn:ietf:params:oauth:client-assertion-type:")
  65. end
  66. 13 def assertion_grant_type(grant_type = param("grant_type"))
  67. 104 grant_type.delete_prefix("urn:ietf:params:oauth:grant-type:").tr("-", "_")
  68. end
  69. 13 def client_assertion_type(assertion_type = param("client_assertion_type"))
  70. 117 assertion_type.delete_prefix("urn:ietf:params:oauth:client-assertion-type:").tr("-", "_")
  71. end
  72. end
  73. end

lib/rodauth/features/oauth_authorization_code_grant.rb

100.0% lines covered

83 relevant lines. 83 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_authorization_code_grant, :OauthAuthorizationCodeGrant) do
  5. 13 depends :oauth_authorize_base
  6. 13 auth_value_method :oauth_response_mode, "form_post"
  7. 13 def oauth_grant_types_supported
  8. 4732 super | %w[authorization_code]
  9. end
  10. 13 def oauth_response_types_supported
  11. 2171 super | %w[code]
  12. end
  13. 13 def oauth_response_modes_supported
  14. 3614 super | %w[query form_post]
  15. end
  16. 13 private
  17. 13 def validate_authorize_params
  18. 2973 super
  19. 2765 response_mode = param_or_nil("response_mode")
  20. 2765 return unless response_mode
  21. 1079 redirect_response_error("invalid_request") unless oauth_response_modes_supported.include?(response_mode)
  22. 1079 response_type = param_or_nil("response_type")
  23. 1079 return unless response_type.nil? || response_type == "code"
  24. 897 redirect_response_error("invalid_request") unless oauth_response_modes_for_code_supported.include?(response_mode)
  25. end
  26. 13 def oauth_response_modes_for_code_supported
  27. 897 %w[query form_post]
  28. end
  29. 13 def validate_token_params
  30. 1963 redirect_response_error("invalid_request") if param_or_nil("grant_type") == "authorization_code" && !param_or_nil("code")
  31. 1963 super
  32. end
  33. 13 def do_authorize(response_params = {}, response_mode = param_or_nil("response_mode"))
  34. 1066 response_mode ||= oauth_response_mode
  35. 1066 redirect_response_error("invalid_request") unless response_mode.nil? || supported_response_mode?(response_mode)
  36. 1066 response_type = param_or_nil("response_type")
  37. 1066 redirect_response_error("invalid_request") unless response_type.nil? || supported_response_type?(response_type)
  38. 738 case response_type
  39. when "code", nil
  40. 715 response_params.replace(_do_authorize_code)
  41. end
  42. 1053 response_params["state"] = param("state") if param_or_nil("state")
  43. 1053 [response_params, response_mode]
  44. end
  45. 13 def _do_authorize_code
  46. 325 create_params = {
  47. 520 oauth_grants_type_column => "authorization_code",
  48. **resource_owner_params
  49. }
  50. 845 { "code" => create_oauth_grant(create_params) }
  51. end
  52. 13 def authorize_response(params, mode)
  53. 637 redirect_url = URI.parse(redirect_uri)
  54. 441 case mode
  55. when "query"
  56. 611 params = [URI.encode_www_form(params)]
  57. 611 params << redirect_url.query if redirect_url.query
  58. 611 redirect_url.query = params.join("&")
  59. 611 redirect(redirect_url.to_s)
  60. when "form_post"
  61. 26 inline_html = form_post_response_html(redirect_uri) do
  62. 24 params.map do |name, value|
  63. 26 "<input type=\"hidden\" name=\"#{scope.h(name)}\" value=\"#{scope.h(value)}\" />"
  64. 2 end.join
  65. end
  66. 26 scope.view layout: false, inline: inline_html
  67. end
  68. end
  69. 13 def _redirect_response_error(redirect_url, params)
  70. 416 response_mode = param_or_nil("response_mode") || oauth_response_mode
  71. 288 case response_mode
  72. when "form_post"
  73. 9 response["Content-Type"] = "text/html"
  74. 13 error_body = form_post_error_response_html(redirect_url) do
  75. 12 params.map do |name, value|
  76. 26 "<input type=\"hidden\" name=\"#{name}\" value=\"#{scope.h(value)}\" />"
  77. 1 end.join
  78. end
  79. 13 response.write(error_body)
  80. 13 request.halt
  81. else
  82. 403 super
  83. end
  84. end
  85. 13 def form_post_response_html(url)
  86. 27 <<-FORM
  87. 12 <html>
  88. <head><title>Authorized</title></head>
  89. <body onload="javascript:document.forms[0].submit()">
  90. 12 <form method="post" action="#{url}">
  91. 12 #{yield}
  92. 12 <input type="submit" class="btn btn-outline-primary" value="#{scope.h(oauth_authorize_post_button)}"/>
  93. </form>
  94. </body>
  95. </html>
  96. FORM
  97. end
  98. 13 def form_post_error_response_html(url)
  99. 9 <<-FORM
  100. 4 <html>
  101. <head><title></title></head>
  102. <body onload="javascript:document.forms[0].submit()">
  103. 4 <form method="post" action="#{url}">
  104. 4 #{yield}
  105. </form>
  106. </body>
  107. </html>
  108. FORM
  109. end
  110. 13 def create_token(grant_type)
  111. 1742 return super unless supported_grant_type?(grant_type, "authorization_code")
  112. 540 grant_params = {
  113. 864 oauth_grants_code_column => param("code"),
  114. oauth_grants_redirect_uri_column => param("redirect_uri"),
  115. oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column]
  116. }
  117. 1404 create_token_from_authorization_code(grant_params)
  118. end
  119. 13 def check_valid_response_type?
  120. 1894 response_type = param_or_nil("response_type")
  121. 1894 response_type == "code" || response_type == "none" || super
  122. end
  123. 13 def oauth_server_metadata_body(*)
  124. 351 super.tap do |data|
  125. 243 data[:authorization_endpoint] = authorize_url
  126. end
  127. end
  128. end
  129. end

lib/rodauth/features/oauth_authorize_base.rb

97.67% lines covered

129 relevant lines. 126 lines covered and 3 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "ipaddr"
  3. 13 require "rodauth/oauth"
  4. 13 module Rodauth
  5. 13 Feature.define(:oauth_authorize_base, :OauthAuthorizeBase) do
  6. 13 depends :oauth_base
  7. 13 before "authorize"
  8. 13 after "authorize"
  9. 13 view "authorize", "Authorize", "authorize"
  10. 13 view "authorize_error", "Authorize Error", "authorize_error"
  11. 13 button "Authorize", "oauth_authorize"
  12. 13 button "Back to Client Application", "oauth_authorize_post"
  13. 13 auth_value_method :use_oauth_access_type?, false
  14. 13 auth_value_method :oauth_grants_access_type_column, :access_type
  15. 13 translatable_method :authorize_page_lead, "The application %<name>s would like to access your data"
  16. 13 translatable_method :oauth_grants_scopes_label, "Scopes"
  17. 13 translatable_method :oauth_applications_contacts_label, "Contacts"
  18. 13 translatable_method :oauth_applications_tos_uri_label, "Terms of service URL"
  19. 13 translatable_method :oauth_applications_policy_uri_label, "Policy URL"
  20. 13 translatable_method :oauth_unsupported_response_type_message, "Unsupported response type"
  21. 13 translatable_method :oauth_authorize_parameter_required, "Invalid or missing '%<parameter>s'"
  22. 13 auth_methods(
  23. :resource_owner_params,
  24. :oauth_grants_resource_owner_columns
  25. )
  26. # /authorize
  27. 13 auth_server_route(:authorize) do |r|
  28. 3281 require_authorizable_account
  29. 3151 before_authorize_route
  30. 3151 validate_authorize_params
  31. 2505 r.get do
  32. 1387 authorize_view
  33. end
  34. 1118 r.post do
  35. 1118 params, mode = transaction do
  36. 1118 before_authorize
  37. 1118 do_authorize
  38. end
  39. 1105 authorize_response(params, mode)
  40. end
  41. end
  42. 13 def check_csrf?
  43. 8742 case request.path
  44. when authorize_path
  45. 3281 only_json? ? false : super
  46. else
  47. 9337 super
  48. end
  49. end
  50. 13 def authorize_scopes
  51. 1387 scopes || begin
  52. 195 oauth_application[oauth_applications_scopes_column].split(oauth_scope_separator)
  53. end
  54. end
  55. 13 private
  56. 13 def validate_authorize_params
  57. 2934 redirect_authorize_error("client_id") unless oauth_application
  58. 2882 redirect_uris = oauth_application[oauth_applications_redirect_uri_column].split(" ")
  59. 2882 if (redirect_uri = param_or_nil("redirect_uri"))
  60. 611 normalized_redirect_uri = normalize_redirect_uri_for_comparison(redirect_uri)
  61. 611 unless redirect_uris.include?(normalized_redirect_uri) || redirect_uris.include?(redirect_uri)
  62. 13 redirect_authorize_error("redirect_uri")
  63. end
  64. 2271 elsif redirect_uris.size > 1
  65. 13 redirect_authorize_error("redirect_uri")
  66. end
  67. 2856 redirect_response_error("unsupported_response_type") unless check_valid_response_type?
  68. 2830 redirect_response_error("invalid_request") unless check_valid_access_type? && check_valid_approval_prompt?
  69. 2830 try_approval_prompt if use_oauth_access_type? && request.get?
  70. 2830 redirect_response_error("invalid_scope") if (request.post? || param_or_nil("scope")) && !check_valid_scopes?
  71. 2804 response_mode = param_or_nil("response_mode")
  72. 2804 redirect_response_error("invalid_request") unless response_mode.nil? || oauth_response_modes_supported.include?(response_mode)
  73. end
  74. 13 def check_valid_scopes?(scp = scopes)
  75. 2557 super(scp - %w[offline_access])
  76. end
  77. 13 def check_valid_response_type?
  78. 26 false
  79. end
  80. 13 ACCESS_TYPES = %w[offline online].freeze
  81. 13 def check_valid_access_type?
  82. 2830 return true unless use_oauth_access_type?
  83. 39 access_type = param_or_nil("access_type")
  84. 39 !access_type || ACCESS_TYPES.include?(access_type)
  85. end
  86. 13 APPROVAL_PROMPTS = %w[force auto].freeze
  87. 13 def check_valid_approval_prompt?
  88. 2830 return true unless use_oauth_access_type?
  89. 39 approval_prompt = param_or_nil("approval_prompt")
  90. 39 !approval_prompt || APPROVAL_PROMPTS.include?(approval_prompt)
  91. end
  92. 13 def resource_owner_params
  93. 1586 { oauth_grants_account_id_column => account_id }
  94. end
  95. 13 def oauth_grants_resource_owner_columns
  96. [oauth_grants_account_id_column]
  97. end
  98. 13 def try_approval_prompt
  99. 26 approval_prompt = param_or_nil("approval_prompt")
  100. 26 return unless approval_prompt && approval_prompt == "auto"
  101. 12 return if db[oauth_grants_table].where(resource_owner_params).where(
  102. oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column],
  103. oauth_grants_redirect_uri_column => redirect_uri,
  104. oauth_grants_scopes_column => scopes.join(oauth_scope_separator),
  105. oauth_grants_access_type_column => "online"
  106. 1 ).count.zero?
  107. # if there's a previous oauth grant for the params combo, it means that this user has approved before.
  108. 9 request.env["REQUEST_METHOD"] = "POST"
  109. end
  110. 13 def redirect_authorize_error(parameter, referer = request.referer || default_redirect)
  111. 104 error_message = oauth_authorize_parameter_required(parameter: parameter)
  112. 104 if accepts_json?
  113. status_code = oauth_invalid_response_status
  114. throw_json_response_error(status_code, "invalid_request", error_message)
  115. else
  116. 104 scope.instance_variable_set(:@error, error_message)
  117. 104 scope.instance_variable_set(:@back_url, referer)
  118. 104 return_response(authorize_error_view)
  119. end
  120. end
  121. 13 def authorization_required
  122. 442 if accepts_json?
  123. 429 throw_json_response_error(oauth_authorization_required_error_status, "invalid_client")
  124. else
  125. 13 set_redirect_error_flash(require_authorization_error_flash)
  126. 13 redirect(authorize_path)
  127. end
  128. end
  129. 13 def do_authorize(*args); end
  130. 13 def authorize_response(params, mode); end
  131. 13 def create_token_from_authorization_code(grant_params, should_generate_refresh_token = !use_oauth_access_type?, oauth_grant: nil)
  132. # fetch oauth grant
  133. 1352 oauth_grant ||= valid_locked_oauth_grant(grant_params)
  134. 1131 should_generate_refresh_token ||= oauth_grant[oauth_grants_access_type_column] == "offline"
  135. 1131 generate_token(oauth_grant, should_generate_refresh_token)
  136. end
  137. 13 def create_oauth_grant(create_params = {})
  138. 897 create_params[oauth_grants_oauth_application_id_column] ||= oauth_application[oauth_applications_id_column]
  139. 897 create_params[oauth_grants_redirect_uri_column] ||= redirect_uri
  140. 897 create_params[oauth_grants_expires_in_column] ||= Sequel.date_add(Sequel::CURRENT_TIMESTAMP, seconds: oauth_grant_expires_in)
  141. 897 create_params[oauth_grants_scopes_column] ||= scopes.join(oauth_scope_separator)
  142. 897 if use_oauth_access_type? && (access_type = param_or_nil("access_type"))
  143. 18 create_params[oauth_grants_access_type_column] = access_type
  144. end
  145. 897 ds = db[oauth_grants_table]
  146. 621 create_params[oauth_grants_code_column] = oauth_unique_id_generator
  147. 897 if oauth_reuse_access_token
  148. 416 unique_conds = Hash[oauth_grants_unique_columns.map { |column| [column, create_params[column]] }]
  149. 104 valid_grant = valid_oauth_grant_ds(unique_conds).select(oauth_grants_id_column).first
  150. 104 if valid_grant
  151. 72 create_params[oauth_grants_id_column] = valid_grant[oauth_grants_id_column]
  152. 104 rescue_from_uniqueness_error do
  153. 104 __insert_or_update_and_return__(
  154. ds,
  155. oauth_grants_id_column,
  156. [oauth_grants_id_column],
  157. create_params
  158. )
  159. end
  160. 104 return create_params[oauth_grants_code_column]
  161. end
  162. end
  163. 793 rescue_from_uniqueness_error do
  164. 832 if __one_oauth_token_per_account
  165. 256 __insert_or_update_and_return__(
  166. ds,
  167. oauth_grants_id_column,
  168. oauth_grants_unique_columns,
  169. create_params,
  170. nil,
  171. {
  172. oauth_grants_expires_in_column => Sequel.date_add(Sequel::CURRENT_TIMESTAMP, seconds: oauth_grant_expires_in),
  173. oauth_grants_revoked_at_column => nil
  174. }
  175. )
  176. else
  177. 576 __insert_and_return__(ds, oauth_grants_id_column, create_params)
  178. end
  179. end
  180. 780 create_params[oauth_grants_code_column]
  181. end
  182. 13 def normalize_redirect_uri_for_comparison(redirect_uri)
  183. 611 uri = URI(redirect_uri)
  184. 611 return redirect_uri unless uri.scheme == "http" && uri.port
  185. 52 hostname = uri.hostname
  186. # https://www.rfc-editor.org/rfc/rfc8252#section-7.3
  187. # ignore (potentially ephemeral) port number for native clients per RFC8252
  188. 4 begin
  189. 52 ip = IPAddr.new(hostname)
  190. 26 uri.port = nil if ip.loopback?
  191. rescue IPAddr::InvalidAddressError
  192. # https://www.rfc-editor.org/rfc/rfc8252#section-8.3
  193. # Although the use of localhost is NOT RECOMMENDED, it is still allowed.
  194. 26 uri.port = nil if hostname == "localhost"
  195. end
  196. 52 uri.to_s
  197. end
  198. end
  199. end

lib/rodauth/features/oauth_base.rb

96.1% lines covered

436 relevant lines. 419 lines covered and 17 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "time"
  3. 13 require "base64"
  4. 13 require "securerandom"
  5. 13 require "cgi"
  6. 13 require "digest/sha2"
  7. 13 require "rodauth/version"
  8. 13 require "rodauth/oauth"
  9. 13 require "rodauth/oauth/database_extensions"
  10. 13 require "rodauth/oauth/http_extensions"
  11. 13 module Rodauth
  12. 13 Feature.define(:oauth_base, :OauthBase) do
  13. 13 include OAuth::HTTPExtensions
  14. 13 EMPTY_HASH = {}.freeze
  15. 13 auth_value_methods(:http_request)
  16. 13 auth_value_methods(:http_request_cache)
  17. 13 before "token"
  18. 13 error_flash "Please authorize to continue", "require_authorization"
  19. 13 error_flash "You are not authorized to revoke this token", "revoke_unauthorized_account"
  20. 13 button "Cancel", "oauth_cancel"
  21. 13 auth_value_method :json_response_content_type, "application/json"
  22. 13 auth_value_method :oauth_grant_expires_in, 60 * 5 # 5 minutes
  23. 13 auth_value_method :oauth_access_token_expires_in, 60 * 60 # 60 minutes
  24. 13 auth_value_method :oauth_refresh_token_expires_in, 60 * 60 * 24 * 360 # 1 year
  25. 13 auth_value_method :oauth_unique_id_generation_retries, 3
  26. 13 auth_value_method :oauth_token_endpoint_auth_methods_supported, %w[client_secret_basic client_secret_post]
  27. 13 auth_value_method :oauth_grant_types_supported, %w[refresh_token]
  28. 13 auth_value_method :oauth_response_types_supported, []
  29. 13 auth_value_method :oauth_response_modes_supported, []
  30. 13 auth_value_method :oauth_valid_uri_schemes, %w[https]
  31. 13 auth_value_method :oauth_scope_separator, " "
  32. # OAuth Grants
  33. 13 auth_value_method :oauth_grants_table, :oauth_grants
  34. 13 auth_value_method :oauth_grants_id_column, :id
  35. 12 %i[
  36. account_id oauth_application_id type
  37. redirect_uri code scopes
  38. expires_in revoked_at
  39. token refresh_token
  40. 1 ].each do |column|
  41. 130 auth_value_method :"oauth_grants_#{column}_column", column
  42. end
  43. # Enables Token Hash
  44. 13 auth_value_method :oauth_grants_token_hash_column, :token
  45. 13 auth_value_method :oauth_grants_refresh_token_hash_column, :refresh_token
  46. # Access Token reuse
  47. 13 auth_value_method :oauth_reuse_access_token, false
  48. 13 auth_value_method :oauth_applications_table, :oauth_applications
  49. 13 auth_value_method :oauth_applications_id_column, :id
  50. 12 %i[
  51. account_id
  52. name description scopes
  53. client_id client_secret
  54. homepage_url redirect_uri
  55. token_endpoint_auth_method grant_types response_types response_modes
  56. logo_uri tos_uri policy_uri jwks jwks_uri
  57. contacts software_id software_version
  58. 1 ].each do |column|
  59. 260 auth_value_method :"oauth_applications_#{column}_column", column
  60. end
  61. # Enables client secret Hash
  62. 13 auth_value_method :oauth_applications_client_secret_hash_column, :client_secret
  63. 13 auth_value_method :oauth_authorization_required_error_status, 401
  64. 13 auth_value_method :oauth_invalid_response_status, 400
  65. 13 auth_value_method :oauth_already_in_use_response_status, 409
  66. # Feature options
  67. 13 auth_value_method :oauth_application_scopes, []
  68. 13 auth_value_method :oauth_token_type, "bearer"
  69. 13 auth_value_method :oauth_refresh_token_protection_policy, "rotation" # can be: none, sender_constrained, rotation
  70. 13 translatable_method :oauth_invalid_client_message, "Invalid client"
  71. 13 translatable_method :oauth_invalid_grant_type_message, "Invalid grant type"
  72. 13 translatable_method :oauth_invalid_grant_message, "Invalid grant"
  73. 13 translatable_method :oauth_invalid_scope_message, "Invalid scope"
  74. 13 translatable_method :oauth_unsupported_token_type_message, "Invalid token type hint"
  75. 13 translatable_method :oauth_already_in_use_message, "error generating unique token"
  76. 13 auth_value_method :oauth_already_in_use_error_code, "invalid_request"
  77. 13 auth_value_method :oauth_invalid_grant_type_error_code, "unsupported_grant_type"
  78. 13 auth_value_method :is_authorization_server?, true
  79. 13 auth_value_methods(:only_json?)
  80. 13 auth_value_method :json_request_regexp, %r{\bapplication/(?:vnd\.api\+)?json\b}i
  81. # METADATA
  82. 13 auth_value_method :oauth_metadata_service_documentation, nil
  83. 13 auth_value_method :oauth_metadata_ui_locales_supported, nil
  84. 13 auth_value_method :oauth_metadata_op_policy_uri, nil
  85. 13 auth_value_method :oauth_metadata_op_tos_uri, nil
  86. 13 auth_value_methods(
  87. :authorization_server_url,
  88. :oauth_grants_unique_columns
  89. )
  90. 13 auth_methods(
  91. :fetch_access_token,
  92. :secret_hash,
  93. :generate_token_hash,
  94. :secret_matches?,
  95. :oauth_unique_id_generator,
  96. :require_authorizable_account,
  97. :oauth_account_ds,
  98. :oauth_application_ds
  99. )
  100. # /token
  101. 13 auth_server_route(:token) do |r|
  102. 2626 require_oauth_application
  103. 2314 before_token_route
  104. 2314 r.post do
  105. 2314 catch_error do
  106. 2314 validate_token_params
  107. 2119 oauth_grant = nil
  108. 2119 transaction do
  109. 2119 before_token
  110. 2119 oauth_grant = create_token(param("grant_type"))
  111. end
  112. 1391 json_response_success(json_access_token_payload(oauth_grant))
  113. end
  114. throw_json_response_error(oauth_invalid_response_status, "invalid_request")
  115. end
  116. end
  117. 13 def load_oauth_server_metadata_route(issuer = nil)
  118. 260 request.on(".well-known") do
  119. 260 request.get("oauth-authorization-server") do
  120. 260 json_response_success(oauth_server_metadata_body(issuer), true)
  121. end
  122. end
  123. end
  124. 13 def check_csrf?
  125. 8274 case request.path
  126. when token_path
  127. 2626 false
  128. else
  129. 9316 super
  130. end
  131. end
  132. 13 def oauth_token_subject
  133. 143 return unless authorization_token
  134. 143 authorization_token[oauth_grants_account_id_column] ||
  135. db[oauth_applications_table].where(
  136. oauth_applications_id_column => authorization_token[oauth_grants_oauth_application_id_column]
  137. ).select_map(oauth_applications_client_id_column).first
  138. end
  139. 13 def current_oauth_account
  140. 143 account_id = authorization_token[oauth_grants_account_id_column]
  141. 143 return unless account_id
  142. 117 oauth_account_ds(account_id).first
  143. end
  144. 13 def current_oauth_application
  145. 169 oauth_application_ds(authorization_token[oauth_grants_oauth_application_id_column]).first
  146. end
  147. 13 def accepts_json?
  148. 2184 return true if only_json?
  149. 2171 (accept = request.env["HTTP_ACCEPT"]) && accept =~ json_request_regexp
  150. end
  151. # copied from the jwt feature
  152. 13 def json_request?
  153. 260 return super if features.include?(:jsonn)
  154. 260 return @json_request if defined?(@json_request)
  155. 260 @json_request = request.content_type =~ json_request_regexp
  156. end
  157. 13 def scopes
  158. 6735 scope = request.params["scope"]
  159. 4671 case scope
  160. when Array
  161. 2665 scope
  162. when String
  163. 3667 scope.split(" ")
  164. end
  165. end
  166. 13 def redirect_uri
  167. 4923 param_or_nil("redirect_uri") || begin
  168. 3909 return unless oauth_application
  169. 3909 redirect_uris = oauth_application[oauth_applications_redirect_uri_column].split(" ")
  170. 3909 redirect_uris.size == 1 ? redirect_uris.first : nil
  171. end
  172. end
  173. 13 def oauth_application
  174. 45553 return @oauth_application if defined?(@oauth_application)
  175. 1391 @oauth_application = begin
  176. 3623 client_id = param_or_nil("client_id")
  177. 3623 return unless client_id
  178. 3493 db[oauth_applications_table].filter(oauth_applications_client_id_column => client_id).first
  179. end
  180. end
  181. 13 def fetch_access_token
  182. 871 if (token = request.params["access_token"])
  183. 26 if request.post? && !(request.content_type.start_with?("application/x-www-form-urlencoded") &&
  184. request.params.size == 1)
  185. return
  186. end
  187. else
  188. 845 token = fetch_access_token_from_authorization_header
  189. end
  190. 871 return if token.nil? || token.empty?
  191. 689 token
  192. end
  193. 13 def fetch_access_token_from_authorization_header(token_type = oauth_token_type)
  194. 897 value = request.env["HTTP_AUTHORIZATION"]
  195. 897 return unless value && !value.empty?
  196. 793 scheme, token = value.split(" ", 2)
  197. 793 return unless scheme.downcase == token_type
  198. 767 token
  199. end
  200. 13 def authorization_token
  201. 1183 return @authorization_token if defined?(@authorization_token)
  202. # check if there is a token
  203. 377 access_token = fetch_access_token
  204. 377 return unless access_token
  205. 234 @authorization_token = oauth_grant_by_token(access_token)
  206. end
  207. 13 def require_oauth_authorization(*scopes)
  208. 351 authorization_required unless authorization_token
  209. 182 token_scopes = authorization_token[oauth_grants_scopes_column].split(oauth_scope_separator)
  210. 390 authorization_required unless scopes.any? { |scope| token_scopes.include?(scope) }
  211. end
  212. 13 def use_date_arithmetic?
  213. 5699 true
  214. end
  215. # override
  216. 13 def translate(key, default, args = EMPTY_HASH)
  217. 31447 return i18n_translate(key, default, **args) if features.include?(:i18n)
  218. # do not attempt to translate by default
  219. 104 return default if args.nil?
  220. 104 default % args
  221. end
  222. 13 def post_configure
  223. 5985 super
  224. 5985 i18n_register(File.expand_path(File.join(__dir__, "..", "..", "..", "locales"))) if features.include?(:i18n)
  225. # all of the extensions below involve DB changes. Resource server mode doesn't use
  226. # database functions for OAuth though.
  227. 5985 return unless is_authorization_server?
  228. 5803 self.class.__send__(:include, Rodauth::OAuth::ExtendDatabase(db))
  229. # Check whether we can reutilize db entries for the same account / application pair
  230. 5803 one_oauth_token_per_account = db.indexes(oauth_grants_table).values.any? do |definition|
  231. 31696 definition[:unique] &&
  232. definition[:columns] == oauth_grants_unique_columns
  233. end
  234. 7831 self.class.send(:define_method, :__one_oauth_token_per_account) { one_oauth_token_per_account }
  235. end
  236. 13 private
  237. 13 def oauth_account_ds(account_id)
  238. 286 account_ds(account_id)
  239. end
  240. 13 def oauth_application_ds(oauth_application_id)
  241. 169 db[oauth_applications_table].where(oauth_applications_id_column => oauth_application_id)
  242. end
  243. 13 def require_authorizable_account
  244. 3554 require_account
  245. end
  246. 13 def rescue_from_uniqueness_error(&block)
  247. 3068 retries = oauth_unique_id_generation_retries
  248. 236 begin
  249. 3146 transaction(savepoint: :only, &block)
  250. 40 rescue Sequel::UniqueConstraintViolation
  251. 104 redirect_response_error("already_in_use") if retries.zero?
  252. 54 retries -= 1
  253. 78 retry
  254. end
  255. end
  256. # OAuth Token Unique/Reuse
  257. 13 def oauth_grants_unique_columns
  258. 13466 [
  259. 18584 oauth_grants_oauth_application_id_column,
  260. oauth_grants_account_id_column,
  261. oauth_grants_scopes_column
  262. ]
  263. end
  264. 13 def authorization_server_url
  265. 2094 base_url
  266. end
  267. 13 def template_path(page)
  268. 68134 path = File.join(File.dirname(__FILE__), "../../../templates", "#{page}.str")
  269. 68134 return super unless File.exist?(path)
  270. 2541 path
  271. end
  272. # to be used internally. Same semantics as require account, must:
  273. # fetch an authorization basic header
  274. # parse client id and secret
  275. #
  276. 13 def require_oauth_application
  277. 2600 @oauth_application = if (token = (v = request.env["HTTP_AUTHORIZATION"]) && v[/\A *Basic (.*)\Z/, 1])
  278. # client_secret_basic
  279. 715 require_oauth_application_from_client_secret_basic(token)
  280. 1885 elsif (client_id = param_or_nil("client_id"))
  281. 1794 if (client_secret = param_or_nil("client_secret"))
  282. # client_secret_post
  283. 1261 require_oauth_application_from_client_secret_post(client_id, client_secret)
  284. else
  285. # none
  286. 533 require_oauth_application_from_none(client_id)
  287. end
  288. else
  289. 91 authorization_required
  290. end
  291. end
  292. 13 def require_oauth_application_from_client_secret_basic(token)
  293. 715 client_id, client_secret = Base64.decode64(token).split(":", 2)
  294. 715 authorization_required unless client_id
  295. 715 oauth_application = db[oauth_applications_table].where(oauth_applications_client_id_column => client_id).first
  296. 660 authorization_required unless supports_auth_method?(oauth_application,
  297. 55 "client_secret_basic") && secret_matches?(oauth_application, client_secret)
  298. 689 oauth_application
  299. end
  300. 13 def require_oauth_application_from_client_secret_post(client_id, client_secret)
  301. 1261 oauth_application = db[oauth_applications_table].where(oauth_applications_client_id_column => client_id).first
  302. 1164 authorization_required unless supports_auth_method?(oauth_application,
  303. 97 "client_secret_post") && secret_matches?(oauth_application, client_secret)
  304. 1235 oauth_application
  305. end
  306. 13 def require_oauth_application_from_none(client_id)
  307. 533 oauth_application = db[oauth_applications_table].where(oauth_applications_client_id_column => client_id).first
  308. 533 authorization_required unless supports_auth_method?(oauth_application, "none")
  309. 416 oauth_application
  310. end
  311. 13 def supports_auth_method?(oauth_application, auth_method)
  312. 2769 return false unless oauth_application
  313. 2730 supported_auth_methods = if oauth_application[oauth_applications_token_endpoint_auth_method_column]
  314. 715 oauth_application[oauth_applications_token_endpoint_auth_method_column].split(/ +/)
  315. else
  316. 2015 oauth_token_endpoint_auth_methods_supported
  317. end
  318. 2730 supported_auth_methods.include?(auth_method)
  319. end
  320. 13 def require_oauth_application_from_account
  321. 13 ds = db[oauth_applications_table]
  322. .join(oauth_grants_table, Sequel[oauth_grants_table][oauth_grants_oauth_application_id_column] =>
  323. Sequel[oauth_applications_table][oauth_applications_id_column])
  324. .where(oauth_grant_by_token_ds(param("token")).opts.fetch(:where, true))
  325. .where(Sequel[oauth_applications_table][oauth_applications_account_id_column] => account_id)
  326. 13 @oauth_application = ds.qualify.first
  327. 13 return if @oauth_application
  328. set_redirect_error_flash revoke_unauthorized_account_error_flash
  329. redirect request.referer || "/"
  330. end
  331. 13 def secret_matches?(oauth_application, secret)
  332. 1924 if oauth_applications_client_secret_hash_column
  333. 1924 BCrypt::Password.new(oauth_application[oauth_applications_client_secret_hash_column]) == secret
  334. else
  335. oauth_application[oauth_applications_client_secret_column] == secret
  336. end
  337. end
  338. 13 def set_client_secret(params, secret)
  339. 741 if oauth_applications_client_secret_hash_column
  340. 513 params[oauth_applications_client_secret_hash_column] = secret_hash(secret)
  341. else
  342. params[oauth_applications_client_secret_column] = secret
  343. end
  344. end
  345. 13 def secret_hash(secret)
  346. 1742 password_hash(secret)
  347. end
  348. 13 def oauth_unique_id_generator
  349. 4849 SecureRandom.urlsafe_base64(32)
  350. end
  351. 13 def generate_token_hash(token)
  352. 325 Base64.urlsafe_encode64(Digest::SHA256.digest(token))
  353. end
  354. 13 def grant_from_application?(oauth_grant, oauth_application)
  355. 221 oauth_grant[oauth_grants_oauth_application_id_column] == oauth_application[oauth_applications_id_column]
  356. end
  357. 13 def password_hash(password)
  358. 1742 return super if features.include?(:login_password_requirements_base)
  359. BCrypt::Password.create(password, cost: BCrypt::Engine::DEFAULT_COST)
  360. end
  361. 13 def generate_token(grant_params = {}, should_generate_refresh_token = true)
  362. 1300 if grant_params[oauth_grants_id_column] && (oauth_reuse_access_token &&
  363. (
  364. 208 if oauth_grants_token_hash_column
  365. 104 grant_params[oauth_grants_token_hash_column]
  366. else
  367. 104 grant_params[oauth_grants_token_column]
  368. end
  369. ))
  370. 72 return grant_params
  371. end
  372. 460 update_params = {
  373. 736 oauth_grants_expires_in_column => Sequel.date_add(Sequel::CURRENT_TIMESTAMP, seconds: oauth_access_token_expires_in),
  374. oauth_grants_code_column => nil
  375. }
  376. 1196 rescue_from_uniqueness_error do
  377. 1196 access_token = _generate_access_token(update_params)
  378. 1196 refresh_token = _generate_refresh_token(update_params) if should_generate_refresh_token
  379. 1196 oauth_grant = store_token(grant_params, update_params)
  380. 1196 return unless oauth_grant
  381. 828 oauth_grant[oauth_grants_token_column] = access_token
  382. 1196 oauth_grant[oauth_grants_refresh_token_column] = refresh_token if refresh_token
  383. 1196 oauth_grant
  384. end
  385. end
  386. 13 def _generate_access_token(params = {})
  387. 689 token = oauth_unique_id_generator
  388. 689 if oauth_grants_token_hash_column
  389. 81 params[oauth_grants_token_hash_column] = generate_token_hash(token)
  390. else
  391. 396 params[oauth_grants_token_column] = token
  392. end
  393. 689 token
  394. end
  395. 13 def _generate_refresh_token(params)
  396. 806 token = oauth_unique_id_generator
  397. 806 if oauth_grants_refresh_token_hash_column
  398. 81 params[oauth_grants_refresh_token_hash_column] = generate_token_hash(token)
  399. else
  400. 477 params[oauth_grants_refresh_token_column] = token
  401. end
  402. 806 token
  403. end
  404. 13 def _grant_with_access_token?(oauth_grant)
  405. if oauth_grants_token_hash_column
  406. oauth_grant[oauth_grants_token_hash_column]
  407. else
  408. oauth_grant[oauth_grants_token_column]
  409. end
  410. end
  411. 13 def store_token(grant_params, update_params = {})
  412. 1196 ds = db[oauth_grants_table]
  413. 1196 if __one_oauth_token_per_account
  414. to_update_if_null = [
  415. 368 oauth_grants_token_column,
  416. oauth_grants_token_hash_column,
  417. oauth_grants_refresh_token_column,
  418. oauth_grants_refresh_token_hash_column
  419. ].compact.map do |attribute|
  420. [
  421. 808 attribute,
  422. (
  423. 808 if ds.respond_to?(:supports_insert_conflict?) && ds.supports_insert_conflict?
  424. 404 Sequel.function(:coalesce, Sequel[oauth_grants_table][attribute], Sequel[:excluded][attribute])
  425. else
  426. 404 Sequel.function(:coalesce, Sequel[oauth_grants_table][attribute], update_params[attribute])
  427. end
  428. )
  429. ]
  430. end
  431. 368 token = __insert_or_update_and_return__(
  432. ds,
  433. oauth_grants_id_column,
  434. oauth_grants_unique_columns,
  435. grant_params.merge(update_params),
  436. Sequel.expr(Sequel[oauth_grants_table][oauth_grants_expires_in_column]) > Sequel::CURRENT_TIMESTAMP,
  437. Hash[to_update_if_null]
  438. )
  439. # if the previous operation didn't return a row, it means that the conditions
  440. # invalidated the update, and the existing token is still valid.
  441. 368 token || ds.where(
  442. oauth_grants_account_id_column => update_params[oauth_grants_account_id_column],
  443. oauth_grants_oauth_application_id_column => update_params[oauth_grants_oauth_application_id_column]
  444. ).first
  445. else
  446. 828 if oauth_reuse_access_token
  447. 288 unique_conds = Hash[oauth_grants_unique_columns.map { |column| [column, update_params[column]] }]
  448. 72 valid_token_ds = valid_oauth_grant_ds(unique_conds)
  449. 72 if oauth_grants_token_hash_column
  450. 36 valid_token_ds.exclude(oauth_grants_token_hash_column => nil)
  451. else
  452. 36 valid_token_ds.exclude(oauth_grants_token_column => nil)
  453. end
  454. 72 valid_token = valid_token_ds.first
  455. 72 return valid_token if valid_token
  456. end
  457. 828 if grant_params[oauth_grants_id_column]
  458. 711 __update_and_return__(ds.where(oauth_grants_id_column => grant_params[oauth_grants_id_column]), update_params)
  459. else
  460. 117 __insert_and_return__(ds, oauth_grants_id_column, grant_params.merge(update_params))
  461. end
  462. end
  463. end
  464. 13 def valid_locked_oauth_grant(grant_params = nil)
  465. 1404 oauth_grant = valid_oauth_grant_ds(grant_params).for_update.first
  466. 1404 redirect_response_error("invalid_grant") unless oauth_grant
  467. 1170 oauth_grant
  468. end
  469. 13 def valid_oauth_grant_ds(grant_params = nil)
  470. 2425 ds = db[oauth_grants_table]
  471. .where(Sequel[oauth_grants_table][oauth_grants_revoked_at_column] => nil)
  472. .where(Sequel.expr(Sequel[oauth_grants_table][oauth_grants_expires_in_column]) >= Sequel::CURRENT_TIMESTAMP)
  473. 2425 ds = ds.where(grant_params) if grant_params
  474. 2425 ds
  475. end
  476. 13 def oauth_grant_by_token_ds(token)
  477. 481 ds = valid_oauth_grant_ds
  478. 481 if oauth_grants_token_hash_column
  479. 52 ds.where(Sequel[oauth_grants_table][oauth_grants_token_hash_column] => generate_token_hash(token))
  480. else
  481. 429 ds.where(Sequel[oauth_grants_table][oauth_grants_token_column] => token)
  482. end
  483. end
  484. 13 def oauth_grant_by_token(token)
  485. 403 oauth_grant_by_token_ds(token).first
  486. end
  487. 13 def oauth_grant_by_refresh_token_ds(token, revoked: false)
  488. 429 ds = db[oauth_grants_table].where(oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column])
  489. #
  490. # filter expired refresh tokens out.
  491. # an expired refresh token is a token whose access token expired for a period longer than the
  492. # refresh token expiration period.
  493. #
  494. 429 ds = ds.where(Sequel.date_add(oauth_grants_expires_in_column,
  495. 429 seconds: (oauth_refresh_token_expires_in - oauth_access_token_expires_in)) >= Sequel::CURRENT_TIMESTAMP)
  496. 429 ds = if oauth_grants_refresh_token_hash_column
  497. 39 ds.where(oauth_grants_refresh_token_hash_column => generate_token_hash(token))
  498. else
  499. 390 ds.where(oauth_grants_refresh_token_column => token)
  500. end
  501. 429 ds = ds.where(oauth_grants_revoked_at_column => nil) unless revoked
  502. 429 ds
  503. end
  504. 13 def oauth_grant_by_refresh_token(token, **kwargs)
  505. 104 oauth_grant_by_refresh_token_ds(token, **kwargs).first
  506. end
  507. 13 def json_access_token_payload(oauth_grant)
  508. 570 payload = {
  509. 912 "access_token" => oauth_grant[oauth_grants_token_column],
  510. "token_type" => oauth_token_type,
  511. "expires_in" => oauth_access_token_expires_in
  512. }
  513. 1482 payload["refresh_token"] = oauth_grant[oauth_grants_refresh_token_column] if oauth_grant[oauth_grants_refresh_token_column]
  514. 1482 payload
  515. end
  516. # Access Tokens
  517. 13 def validate_token_params
  518. 2132 unless (grant_type = param_or_nil("grant_type"))
  519. 65 redirect_response_error("invalid_request")
  520. end
  521. 2067 redirect_response_error("invalid_request") if grant_type == "refresh_token" && !param_or_nil("refresh_token")
  522. end
  523. 13 def create_token(grant_type)
  524. 468 redirect_response_error("invalid_request") unless supported_grant_type?(grant_type, "refresh_token")
  525. 325 refresh_token = param("refresh_token")
  526. # fetch potentially revoked oauth token
  527. 325 oauth_grant = oauth_grant_by_refresh_token_ds(refresh_token, revoked: true).for_update.first
  528. 325 update_params = { oauth_grants_expires_in_column => Sequel.date_add(Sequel::CURRENT_TIMESTAMP,
  529. seconds: oauth_access_token_expires_in) }
  530. 325 if !oauth_grant || oauth_grant[oauth_grants_revoked_at_column]
  531. 156 redirect_response_error("invalid_grant")
  532. 169 elsif oauth_refresh_token_protection_policy == "rotation"
  533. # https://tools.ietf.org/html/draft-ietf-oauth-v2-1-00#section-6.1
  534. #
  535. # If a refresh token is compromised and subsequently used by both the attacker and the legitimate
  536. # client, one of them will present an invalidated refresh token, which will inform the authorization
  537. # server of the breach. The authorization server cannot determine which party submitted the invalid
  538. # refresh token, but it will revoke the active refresh token. This stops the attack at the cost of
  539. # forcing the legitimate client to obtain a fresh authorization grant.
  540. 78 refresh_token = _generate_refresh_token(update_params)
  541. end
  542. 117 update_params[oauth_grants_oauth_application_id_column] = oauth_grant[oauth_grants_oauth_application_id_column]
  543. 169 oauth_grant = create_token_from_token(oauth_grant, update_params)
  544. 108 oauth_grant[oauth_grants_refresh_token_column] = refresh_token
  545. 156 oauth_grant
  546. end
  547. 13 def create_token_from_token(oauth_grant, update_params)
  548. 169 redirect_response_error("invalid_grant") unless grant_from_application?(oauth_grant, oauth_application)
  549. 169 rescue_from_uniqueness_error do
  550. 208 oauth_grants_ds = db[oauth_grants_table].where(oauth_grants_id_column => oauth_grant[oauth_grants_id_column])
  551. 208 access_token = _generate_access_token(update_params)
  552. 208 oauth_grant = __update_and_return__(oauth_grants_ds, update_params)
  553. 108 oauth_grant[oauth_grants_token_column] = access_token
  554. 156 oauth_grant
  555. end
  556. end
  557. 13 def supported_grant_type?(grant_type, expected_grant_type = grant_type)
  558. 2496 return false unless grant_type == expected_grant_type
  559. 2028 grant_types_supported = if oauth_application[oauth_applications_grant_types_column]
  560. 52 oauth_application[oauth_applications_grant_types_column].split(/ +/)
  561. else
  562. 1976 oauth_grant_types_supported
  563. end
  564. 2028 grant_types_supported.include?(grant_type)
  565. end
  566. 13 def supported_response_type?(response_type, expected_response_type = response_type)
  567. 1118 return false unless response_type == expected_response_type
  568. 1118 response_types_supported = if oauth_application[oauth_applications_response_types_column]
  569. 13 oauth_application[oauth_applications_response_types_column].split(/ +/)
  570. else
  571. 1105 oauth_response_types_supported
  572. end
  573. 1118 response_types = response_type.split(/ +/)
  574. 1118 (response_types - response_types_supported).empty?
  575. end
  576. 13 def supported_response_mode?(response_mode, expected_response_mode = response_mode)
  577. 1105 return false unless response_mode == expected_response_mode
  578. 1105 response_modes_supported = if oauth_application[oauth_applications_response_modes_column]
  579. oauth_application[oauth_applications_response_modes_column].split(/ +/)
  580. else
  581. 1105 oauth_response_modes_supported
  582. end
  583. 1105 response_modes_supported.include?(response_mode)
  584. end
  585. 13 def oauth_server_metadata_body(path = nil)
  586. 351 issuer = base_url
  587. 351 issuer += "/#{path}" if path
  588. 135 {
  589. 216 issuer: issuer,
  590. token_endpoint: token_url,
  591. scopes_supported: oauth_application_scopes,
  592. response_types_supported: oauth_response_types_supported,
  593. response_modes_supported: oauth_response_modes_supported,
  594. grant_types_supported: oauth_grant_types_supported,
  595. token_endpoint_auth_methods_supported: oauth_token_endpoint_auth_methods_supported,
  596. service_documentation: oauth_metadata_service_documentation,
  597. ui_locales_supported: oauth_metadata_ui_locales_supported,
  598. op_policy_uri: oauth_metadata_op_policy_uri,
  599. op_tos_uri: oauth_metadata_op_tos_uri
  600. }
  601. end
  602. 13 def redirect_response_error(error_code, message = nil)
  603. 1586 if accepts_json?
  604. 1001 status_code = if respond_to?(:"oauth_#{error_code}_response_status")
  605. 26 send(:"oauth_#{error_code}_response_status")
  606. else
  607. 975 oauth_invalid_response_status
  608. end
  609. 1001 throw_json_response_error(status_code, error_code, message)
  610. else
  611. 585 redirect_url = redirect_uri || request.referer || default_redirect
  612. 585 redirect_url = URI.parse(redirect_url)
  613. 585 params = response_error_params(error_code, message)
  614. 585 state = param_or_nil("state")
  615. 585 params["state"] = state if state
  616. 585 _redirect_response_error(redirect_url, params)
  617. end
  618. end
  619. 13 def _redirect_response_error(redirect_url, params)
  620. 390 params = URI.encode_www_form(params)
  621. 390 if redirect_url.query
  622. params << "&" unless params.empty?
  623. params << redirect_url.query
  624. end
  625. 390 redirect_url.query = params
  626. 390 redirect(redirect_url.to_s)
  627. end
  628. 13 def response_error_params(error_code, message = nil)
  629. 3107 code = if respond_to?(:"oauth_#{error_code}_error_code")
  630. 91 send(:"oauth_#{error_code}_error_code")
  631. else
  632. 3016 error_code
  633. end
  634. 3107 payload = { "error" => code }
  635. 3107 error_description = message
  636. 3107 error_description ||= send(:"oauth_#{error_code}_message") if respond_to?(:"oauth_#{error_code}_message")
  637. 3107 payload["error_description"] = error_description if error_description
  638. 3107 payload
  639. end
  640. 13 def json_response_success(body, cache = false)
  641. 2249 response.status = 200
  642. 2249 response["Content-Type"] ||= json_response_content_type
  643. 2249 if cache
  644. # defaulting to 1-day for everyone, for now at least
  645. 390 max_age = 60 * 60 * 24
  646. 270 response["Cache-Control"] = "private, max-age=#{max_age}"
  647. else
  648. 1287 response["Cache-Control"] = "no-store"
  649. 1287 response["Pragma"] = "no-cache"
  650. end
  651. 2249 json_payload = _json_response_body(body)
  652. 2249 return_response(json_payload)
  653. end
  654. 13 def throw_json_response_error(status, error_code, message = nil)
  655. 2522 set_response_error_status(status)
  656. 2522 payload = response_error_params(error_code, message)
  657. 2522 json_payload = _json_response_body(payload)
  658. 2522 response["Content-Type"] ||= json_response_content_type
  659. 2522 response["WWW-Authenticate"] = www_authenticate_header(payload) if status == 401
  660. 2522 return_response(json_payload)
  661. end
  662. 13 def www_authenticate_header(*)
  663. 624 oauth_token_type.capitalize
  664. end
  665. 13 def _json_response_body(hash)
  666. 5499 return super if features.include?(:json)
  667. 5499 if request.respond_to?(:convert_to_json)
  668. request.send(:convert_to_json, hash)
  669. else
  670. 5499 JSON.dump(hash)
  671. end
  672. end
  673. 13 if Gem::Version.new(Rodauth.version) < Gem::Version.new("2.23")
  674. def return_response(body = nil)
  675. response.write(body) if body
  676. request.halt
  677. end
  678. end
  679. 13 def authorization_required
  680. 208 throw_json_response_error(oauth_authorization_required_error_status, "invalid_client")
  681. end
  682. 13 def check_valid_scopes?(scp = scopes)
  683. 2596 return false unless scp
  684. 2596 (scp - oauth_application[oauth_applications_scopes_column].split(oauth_scope_separator)).empty?
  685. end
  686. 13 def check_valid_uri?(uri)
  687. 9698 URI::DEFAULT_PARSER.make_regexp(oauth_valid_uri_schemes).match?(uri)
  688. end
  689. 13 def check_valid_no_fragment_uri?(uri)
  690. 2990 check_valid_uri?(uri) && URI.parse(uri).fragment.nil?
  691. end
  692. # Resource server mode
  693. 13 def authorization_server_metadata
  694. 52 auth_url = URI(authorization_server_url).dup
  695. 52 auth_url.path = "/.well-known/oauth-authorization-server"
  696. 52 http_request_with_cache(auth_url)
  697. end
  698. end
  699. end

lib/rodauth/features/oauth_client_credentials_grant.rb

100.0% lines covered

17 relevant lines. 17 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_client_credentials_grant, :OauthClientCredentialsGrant) do
  5. 13 depends :oauth_base
  6. 13 def oauth_grant_types_supported
  7. 104 super | %w[client_credentials]
  8. end
  9. 13 private
  10. 13 def create_token(grant_type)
  11. 78 return super unless supported_grant_type?(grant_type, "client_credentials")
  12. 65 grant_scopes = scopes
  13. 65 grant_scopes = if grant_scopes
  14. 13 redirect_response_error("invalid_scope") unless check_valid_scopes?
  15. 13 grant_scopes.join(oauth_scope_separator)
  16. else
  17. 52 oauth_application[oauth_applications_scopes_column]
  18. end
  19. 25 grant_params = {
  20. 40 oauth_grants_type_column => "client_credentials",
  21. oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column],
  22. oauth_grants_scopes_column => grant_scopes
  23. }
  24. 65 generate_token(grant_params, false)
  25. end
  26. end
  27. end

lib/rodauth/features/oauth_device_code_grant.rb

95.33% lines covered

107 relevant lines. 102 lines covered and 5 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_device_code_grant, :OauthDeviceCodeGrant) do
  5. 13 depends :oauth_authorize_base
  6. 13 before "device_authorization"
  7. 13 before "device_verification"
  8. 13 notice_flash "The device is verified", "device_verification"
  9. 13 error_flash "No device to authorize with the given user code", "user_code_not_found"
  10. 13 view "device_verification", "Device Verification", "device_verification"
  11. 13 view "device_search", "Device Search", "device_search"
  12. 13 button "Verify", "oauth_device_verification"
  13. 13 button "Search", "oauth_device_search"
  14. 13 auth_value_method :oauth_grants_user_code_column, :user_code
  15. 13 auth_value_method :oauth_grants_last_polled_at_column, :last_polled_at
  16. 13 translatable_method :oauth_device_search_page_lead, "Insert the user code from the device you'd like to authorize."
  17. 13 translatable_method :oauth_device_verification_page_lead, "The device with user code %<user_code>s would like to access your data."
  18. 13 translatable_method :oauth_expired_token_message, "the device code has expired"
  19. 13 translatable_method :oauth_access_denied_message, "the authorization request has been denied"
  20. 13 translatable_method :oauth_authorization_pending_message, "the authorization request is still pending"
  21. 13 translatable_method :oauth_slow_down_message, "authorization request is still pending but poll interval should be increased"
  22. 13 auth_value_method :oauth_device_code_grant_polling_interval, 5 # seconds
  23. 13 auth_value_method :oauth_device_code_grant_user_code_size, 8 # characters
  24. 13 %w[user_code].each do |param|
  25. 13 auth_value_method :"oauth_grant_#{param}_param", param
  26. end
  27. 13 translatable_method :oauth_grant_user_code_label, "User code"
  28. 13 auth_methods(
  29. :generate_user_code
  30. )
  31. # /device-authorization
  32. 13 auth_server_route(:device_authorization) do |r|
  33. 26 require_oauth_application
  34. 26 before_device_authorization_route
  35. 26 r.post do
  36. 26 user_code = generate_user_code
  37. 26 device_code = transaction do
  38. 26 before_device_authorization
  39. 26 create_oauth_grant(
  40. oauth_grants_type_column => "device_code",
  41. oauth_grants_user_code_column => user_code
  42. )
  43. end
  44. 26 json_response_success \
  45. "device_code" => device_code,
  46. "user_code" => user_code,
  47. "verification_uri" => device_url,
  48. "verification_uri_complete" => device_url(user_code: user_code),
  49. "expires_in" => oauth_grant_expires_in,
  50. "interval" => oauth_device_code_grant_polling_interval
  51. end
  52. end
  53. # /device
  54. 13 auth_server_route(:device) do |r|
  55. 273 require_authorizable_account
  56. 260 before_device_route
  57. 260 r.get do
  58. 221 if (user_code = param_or_nil("user_code"))
  59. 78 oauth_grant = valid_oauth_grant_ds(oauth_grants_user_code_column => user_code).first
  60. 78 unless oauth_grant
  61. 39 set_redirect_error_flash user_code_not_found_error_flash
  62. 39 redirect device_path
  63. end
  64. 39 scope.instance_variable_set(:@oauth_grant, oauth_grant)
  65. 39 device_verification_view
  66. else
  67. 143 device_search_view
  68. end
  69. end
  70. 39 r.post do
  71. 39 catch_error do
  72. 39 unless (user_code = param_or_nil("user_code")) && !user_code.empty?
  73. 13 set_redirect_error_flash oauth_invalid_grant_message
  74. 13 redirect device_path
  75. end
  76. 26 transaction do
  77. 26 before_device_verification
  78. 26 create_token("device_code")
  79. end
  80. end
  81. 26 set_notice_flash device_verification_notice_flash
  82. 26 redirect device_path
  83. end
  84. end
  85. 13 def check_csrf?
  86. 423 case request.path
  87. when device_authorization_path
  88. 26 false
  89. else
  90. 585 super
  91. end
  92. end
  93. 13 def oauth_grant_types_supported
  94. 143 super | %w[urn:ietf:params:oauth:grant-type:device_code]
  95. end
  96. 13 private
  97. 13 def generate_user_code
  98. 26 user_code_size = oauth_device_code_grant_user_code_size
  99. 24 SecureRandom.random_number(36**user_code_size)
  100. .to_s(36) # 0 to 9, a to z
  101. .upcase
  102. 2 .rjust(user_code_size, "0")
  103. end
  104. # TODO: think about removing this and recommend PKCE
  105. 13 def supports_auth_method?(oauth_application, auth_method)
  106. 169 return super unless auth_method == "none"
  107. 143 request.path == device_authorization_path || request.params.key?("device_code") || super
  108. end
  109. 13 def create_token(grant_type)
  110. 156 if supported_grant_type?(grant_type, "urn:ietf:params:oauth:grant-type:device_code")
  111. 130 oauth_grant = db[oauth_grants_table].where(
  112. oauth_grants_type_column => "device_code",
  113. oauth_grants_code_column => param("device_code"),
  114. oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column]
  115. ).for_update.first
  116. 130 throw_json_response_error(oauth_invalid_response_status, "invalid_grant") unless oauth_grant
  117. 117 now = Time.now
  118. 117 if oauth_grant[oauth_grants_user_code_column].nil?
  119. 16 return create_token_from_authorization_code(
  120. { oauth_grants_id_column => oauth_grant[oauth_grants_id_column] },
  121. oauth_grant: oauth_grant
  122. 2 )
  123. end
  124. 91 if oauth_grant[oauth_grants_revoked_at_column]
  125. 26 throw_json_response_error(oauth_invalid_response_status, "access_denied")
  126. 65 elsif oauth_grant[oauth_grants_expires_in_column] < now
  127. 13 throw_json_response_error(oauth_invalid_response_status, "expired_token")
  128. else
  129. 52 last_polled_at = oauth_grant[oauth_grants_last_polled_at_column]
  130. 52 if last_polled_at && convert_timestamp(last_polled_at) + oauth_device_code_grant_polling_interval > now
  131. 13 throw_json_response_error(oauth_invalid_response_status, "slow_down")
  132. else
  133. 39 db[oauth_grants_table].where(oauth_grants_id_column => oauth_grant[oauth_grants_id_column])
  134. 3 .update(oauth_grants_last_polled_at_column => Sequel::CURRENT_TIMESTAMP)
  135. 39 throw_json_response_error(oauth_invalid_response_status, "authorization_pending")
  136. end
  137. end
  138. 26 elsif grant_type == "device_code"
  139. # fetch oauth grant
  140. 26 rs = valid_oauth_grant_ds(
  141. oauth_grants_user_code_column => param("user_code")
  142. ).update(oauth_grants_user_code_column => nil, oauth_grants_type_column => "device_code")
  143. 26 rs if rs.positive?
  144. else
  145. super
  146. end
  147. end
  148. 13 def validate_token_params
  149. 143 grant_type = param_or_nil("grant_type")
  150. 143 if grant_type == "urn:ietf:params:oauth:grant-type:device_code" && !param_or_nil("device_code")
  151. 13 redirect_response_error("invalid_request")
  152. end
  153. 130 super
  154. end
  155. 13 def store_token(grant_params, update_params = {})
  156. 26 return super unless grant_params[oauth_grants_user_code_column]
  157. # do not clean up device code just yet
  158. update_params.delete(oauth_grants_code_column)
  159. update_params[oauth_grants_user_code_column] = nil
  160. update_params.merge!(resource_params)
  161. super(grant_params, update_params)
  162. end
  163. 13 def oauth_server_metadata_body(*)
  164. 13 super.tap do |data|
  165. 9 data[:device_authorization_endpoint] = device_authorization_url
  166. end
  167. end
  168. end
  169. end

lib/rodauth/features/oauth_dpop.rb

92.67% lines covered

191 relevant lines. 177 lines covered and 14 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_dpop, :OauthDpop) do
  5. 13 depends :oauth_jwt, :oauth_authorize_base
  6. 13 auth_value_method :oauth_invalid_token_error_response_status, 401
  7. 13 auth_value_method :oauth_multiple_auth_methods_response_status, 401
  8. 13 auth_value_method :oauth_access_token_dpop_bound_response_status, 401
  9. 13 translatable_method :oauth_invalid_dpop_proof_message, "Invalid DPoP proof"
  10. 13 translatable_method :oauth_multiple_auth_methods_message, "Multiple methods used to include access token"
  11. 13 auth_value_method :oauth_multiple_dpop_proofs_error_code, "invalid_request"
  12. 13 translatable_method :oauth_multiple_dpop_proofs_message, "Multiple DPoP proofs used"
  13. 13 auth_value_method :oauth_invalid_dpop_jkt_error_code, "invalid_dpop_proof"
  14. 13 translatable_method :oauth_invalid_dpop_jkt_message, "Invalid DPoP JKT"
  15. 13 auth_value_method :oauth_invalid_dpop_jti_error_code, "invalid_dpop_proof"
  16. 13 translatable_method :oauth_invalid_dpop_jti_message, "Invalid DPoP jti"
  17. 13 auth_value_method :oauth_invalid_dpop_htm_error_code, "invalid_dpop_proof"
  18. 13 translatable_method :oauth_invalid_dpop_htm_message, "Invalid DPoP htm"
  19. 13 auth_value_method :oauth_invalid_dpop_htu_error_code, "invalid_dpop_proof"
  20. 13 translatable_method :oauth_invalid_dpop_htu_message, "Invalid DPoP htu"
  21. 13 translatable_method :oauth_access_token_dpop_bound_message, "DPoP bound access token requires DPoP proof"
  22. 13 translatable_method :oauth_use_dpop_nonce_message, "DPoP nonce is required"
  23. 13 auth_value_method :oauth_dpop_proof_expires_in, 60 * 5 # 5 minutes
  24. 13 auth_value_method :oauth_dpop_bound_access_tokens, false
  25. 13 auth_value_method :oauth_dpop_use_nonce, false
  26. 13 auth_value_method :oauth_dpop_nonce_expires_in, 5 # 5 seconds
  27. 13 auth_value_method :oauth_dpop_signing_alg_values_supported,
  28. %w[
  29. RS256
  30. RS384
  31. RS512
  32. PS256
  33. PS384
  34. PS512
  35. ES256
  36. ES384
  37. ES512
  38. ES256K
  39. ]
  40. 13 auth_value_method :oauth_applications_dpop_bound_access_tokens_column, :dpop_bound_access_tokens
  41. 13 auth_value_method :oauth_grants_dpop_jkt_column, :dpop_jkt
  42. 13 auth_value_method :oauth_pushed_authorization_requests_dpop_jkt_column, :dpop_jkt
  43. 13 auth_value_method :oauth_dpop_proofs_table, :oauth_dpop_proofs
  44. 13 auth_value_method :oauth_dpop_proofs_jti_column, :jti
  45. 13 auth_value_method :oauth_dpop_proofs_first_use_column, :first_use
  46. 13 auth_methods(:validate_dpop_proof_usage)
  47. 13 def require_oauth_authorization(*scopes)
  48. 52 @dpop_access_token = fetch_access_token_from_authorization_header("dpop")
  49. 52 unless @dpop_access_token
  50. 39 authorization_required if oauth_dpop_bound_access_tokens
  51. # Specifically, such a protected resource MUST reject a DPoP-bound access token received as a bearer token
  52. 26 redirect_response_error("access_token_dpop_bound") if authorization_token && authorization_token.dig("cnf", "jkt")
  53. 9 return super
  54. end
  55. 13 dpop = fetch_dpop_token
  56. 13 dpop_claims = validate_dpop_token(dpop)
  57. # 4.3.12
  58. 13 validate_ath(dpop_claims, @dpop_access_token)
  59. 13 @authorization_token = decode_access_token(@dpop_access_token)
  60. # 4.3.12 - confirm that the public key to which the access token is bound matches the public key from the DPoP proof.
  61. 13 jkt = authorization_token.dig("cnf", "jkt")
  62. 13 redirect_response_error("invalid_dpop_jkt") if oauth_dpop_bound_access_tokens && !jkt
  63. 13 redirect_response_error("invalid_dpop_jkt") unless jkt == @dpop_thumbprint
  64. 13 super
  65. end
  66. 13 private
  67. 13 def validate_token_params
  68. 260 dpop = fetch_dpop_token
  69. 260 unless dpop
  70. 13 authorization_required if dpop_bound_access_tokens_required?
  71. return super
  72. end
  73. 247 validate_dpop_token(dpop)
  74. 143 super
  75. end
  76. 13 def validate_par_params
  77. 52 super
  78. 52 return unless (dpop = fetch_dpop_token)
  79. 39 validate_dpop_token(dpop)
  80. 39 if (dpop_jkt = param_or_nil("dpop_jkt"))
  81. 26 redirect_response_error("invalid_request") if dpop_jkt != @dpop_thumbprint
  82. else
  83. 9 request.params["dpop_jkt"] = @dpop_thumbprint
  84. end
  85. end
  86. 13 def validate_dpop_token(dpop)
  87. # 4.3.2
  88. 299 @dpop_claims = dpop_decode(dpop)
  89. 260 redirect_response_error("invalid_dpop_proof") unless @dpop_claims
  90. 247 validate_dpop_jwt_claims(@dpop_claims)
  91. # 4.3.10
  92. 221 validate_nonce(@dpop_claims)
  93. # 11.1
  94. # To prevent multiple uses of the same DPoP proof, servers can store, in the
  95. # context of the target URI, the jti value of each DPoP proof for the time window
  96. # in which the respective DPoP proof JWT would be accepted.
  97. 208 validate_dpop_proof_usage(@dpop_claims)
  98. 195 @dpop_claims
  99. end
  100. 13 def validate_dpop_proof_usage(claims)
  101. 208 jti = claims["jti"]
  102. 208 dpop_proof = __insert_or_do_nothing_and_return__(
  103. db[oauth_dpop_proofs_table],
  104. oauth_dpop_proofs_jti_column,
  105. [oauth_dpop_proofs_jti_column],
  106. oauth_dpop_proofs_jti_column => Digest::SHA256.hexdigest(jti),
  107. oauth_dpop_proofs_first_use_column => Sequel::CURRENT_TIMESTAMP
  108. )
  109. 208 return unless (Time.now - dpop_proof[oauth_dpop_proofs_first_use_column]) > oauth_dpop_proof_expires_in
  110. 13 redirect_response_error("invalid_dpop_proof")
  111. end
  112. 13 def dpop_decode(dpop)
  113. # decode first without verifying!
  114. 299 _, headers = jwt_decode_no_key(dpop)
  115. 299 redirect_response_error("invalid_dpop_proof") unless verify_dpop_jwt_headers(headers)
  116. 260 dpop_jwk = headers["jwk"]
  117. 260 jwt_decode(
  118. dpop,
  119. jws_key: jwk_key(dpop_jwk),
  120. jws_algorithm: headers["alg"],
  121. verify_iss: false,
  122. verify_aud: false,
  123. verify_jti: false
  124. )
  125. end
  126. 13 def verify_dpop_jwt_headers(headers)
  127. # 4.3.4 - A field with the value dpop+jwt
  128. 299 return false unless headers["typ"] == "dpop+jwt"
  129. # 4.3.5 - It MUST NOT be none or an identifier for a symmetric algorithm
  130. 286 alg = headers["alg"]
  131. 286 return false unless alg && oauth_dpop_signing_alg_values_supported.include?(alg)
  132. 273 dpop_jwk = headers["jwk"]
  133. 273 return false unless dpop_jwk
  134. # 4.3.7 - It MUST NOT contain a private key.
  135. 273 return false if private_jwk?(dpop_jwk)
  136. # store thumbprint for future assertions
  137. 260 @dpop_thumbprint = jwk_thumbprint(dpop_jwk)
  138. 260 true
  139. end
  140. 13 def validate_dpop_jwt_claims(claims)
  141. 247 jti = claims["jti"]
  142. 247 unless jti && jti == Digest::SHA256.hexdigest("#{request.request_method}:#{request.url}:#{claims['iat']}")
  143. redirect_response_error("invalid_dpop_jti")
  144. end
  145. 247 htm = claims["htm"]
  146. # 4.3.8 - Check if htm matches the request method
  147. 247 redirect_response_error("invalid_dpop_htm") unless htm && htm == request.request_method
  148. 234 htu = claims["htu"]
  149. # 4.3.9 - Check if htu matches the request URL
  150. 234 redirect_response_error("invalid_dpop_htu") unless htu && htu == request.url
  151. end
  152. 13 def validate_ath(claims, access_token)
  153. # When the DPoP proof is used in conjunction with the presentation of an access token in protected resource access
  154. # the DPoP proof MUST also contain the following claim
  155. 13 ath = claims["ath"]
  156. 13 redirect_response_error("invalid_token") unless ath
  157. # The value MUST be the result of a base64url encoding of the SHA-256 hash of the ASCII encoding of
  158. # the associated access token's value.
  159. 13 redirect_response_error("invalid_token") unless ath == Base64.urlsafe_encode64(Digest::SHA256.digest(access_token), padding: false)
  160. end
  161. 13 def validate_nonce(claims)
  162. 221 nonce = claims["nonce"]
  163. 221 unless nonce
  164. 208 dpop_nonce_required(claims) if dpop_use_nonce?
  165. 135 return
  166. end
  167. 13 dpop_nonce_required(claims) unless valid_dpop_nonce?(nonce)
  168. end
  169. 13 def jwt_claims(oauth_grant)
  170. 117 claims = super
  171. 117 if @dpop_thumbprint
  172. # the authorization server associates the issued access token with the
  173. # public key from the DPoP proof
  174. 81 claims[:cnf] = { jkt: @dpop_thumbprint }
  175. end
  176. 117 claims
  177. end
  178. 13 def generate_token(grant_params = {}, should_generate_refresh_token = true)
  179. # When an authorization server supporting DPoP issues a refresh token to a public client
  180. # that presents a valid DPoP proof at the token endpoint, the refresh token MUST be bound to the respective public key.
  181. 117 grant_params[oauth_grants_dpop_jkt_column] = @dpop_thumbprint if @dpop_thumbprint
  182. 117 super
  183. end
  184. 13 def valid_oauth_grant_ds(grant_params = nil)
  185. 143 ds = super
  186. 143 ds = ds.where(oauth_grants_dpop_jkt_column => nil)
  187. 143 ds = ds.or(oauth_grants_dpop_jkt_column => @dpop_thumbprint) if @dpop_thumbprint
  188. 143 ds
  189. end
  190. 13 def oauth_grant_by_refresh_token_ds(_token, revoked: false)
  191. ds = super
  192. # The binding MUST be validated when the refresh token is later presented to get new access tokens.
  193. ds = ds.where(oauth_grants_dpop_jkt_column => nil)
  194. ds = ds.or(oauth_grants_dpop_jkt_column => @dpop_thumbprint) if @dpop_thumbprint
  195. ds
  196. end
  197. 13 def oauth_grant_by_token_ds(_token)
  198. ds = super
  199. # The binding MUST be validated when the refresh token is later presented to get new access tokens.
  200. ds = ds.where(oauth_grants_dpop_jkt_column => nil)
  201. ds = ds.or(oauth_grants_dpop_jkt_column => @dpop_thumbprint) if @dpop_thumbprint
  202. ds
  203. end
  204. 13 def create_oauth_grant(create_params = {})
  205. # 10. Authorization Code Binding to DPoP Key
  206. # Binding the authorization code issued to the client's proof-of-possession key can enable end-to-end
  207. # binding of the entire authorization flow.
  208. 65 if (dpop_jkt = param_or_nil("dpop_jkt"))
  209. 45 create_params[oauth_grants_dpop_jkt_column] = dpop_jkt
  210. end
  211. 65 super
  212. end
  213. 13 def json_access_token_payload(oauth_grant)
  214. 117 payload = super
  215. # 5. A token_type of DPoP MUST be included in the access token response to
  216. # signal to the client that the access token was bound to its DPoP key
  217. 117 payload["token_type"] = "DPoP" if @dpop_claims
  218. 117 payload
  219. end
  220. 13 def fetch_dpop_token
  221. 325 dpop = request.env["HTTP_DPOP"]
  222. 325 return if dpop.nil? || dpop.empty?
  223. # 4.3.1 - There is not more than one DPoP HTTP request header field.
  224. 299 redirect_response_error("multiple_dpop_proofs") if dpop.split(";").size > 1
  225. 299 dpop
  226. end
  227. 13 def dpop_bound_access_tokens_required?
  228. 65 oauth_dpop_bound_access_tokens || (oauth_application && oauth_application[oauth_applications_dpop_bound_access_tokens_column])
  229. end
  230. 13 def dpop_use_nonce?
  231. 208 oauth_dpop_use_nonce || (oauth_application && oauth_application[oauth_applications_dpop_bound_access_tokens_column])
  232. end
  233. 13 def valid_dpop_proof_required(error_code = "invalid_dpop_proof")
  234. if @dpop_access_token
  235. # protected resource access
  236. throw_json_response_error(401, error_code)
  237. else
  238. redirect_response_error(error_code)
  239. end
  240. end
  241. 13 def dpop_nonce_required(dpop_claims)
  242. 9 response["DPoP-Nonce"] = generate_dpop_nonce(dpop_claims)
  243. 13 if @dpop_access_token
  244. # protected resource access
  245. throw_json_response_error(401, "use_dpop_nonce")
  246. else
  247. 13 redirect_response_error("use_dpop_nonce")
  248. end
  249. end
  250. 13 def www_authenticate_header(payload)
  251. 52 header = if dpop_bound_access_tokens_required?
  252. 26 "DPoP"
  253. else
  254. 18 "#{super}, DPoP"
  255. end
  256. 52 error_code = payload["error"]
  257. 52 unless error_code == "invalid_client"
  258. 13 header = "#{header} error=\"#{error_code}\""
  259. 13 if (desc = payload["error_description"])
  260. 13 header = "#{header} error_description=\"#{desc}\""
  261. end
  262. end
  263. 52 algs = oauth_dpop_signing_alg_values_supported.join(" ")
  264. 36 "#{header} algs=\"#{algs}\""
  265. end
  266. # Nonce
  267. 13 def generate_dpop_nonce(dpop_claims)
  268. 13 issued_at = Time.now.to_i
  269. 13 aud = "#{dpop_claims['htm']}:#{dpop_claims['htu']}"
  270. 5 nonce_claims = {
  271. 8 iss: oauth_jwt_issuer,
  272. iat: issued_at,
  273. exp: issued_at + oauth_dpop_nonce_expires_in,
  274. aud: aud
  275. }
  276. 13 jwt_encode(nonce_claims)
  277. end
  278. 13 def valid_dpop_nonce?(nonce)
  279. 13 nonce_claims = jwt_decode(nonce, verify_aud: false, verify_jti: false)
  280. 13 return false unless nonce_claims
  281. 13 jti = nonce_claims["jti"]
  282. 13 return false unless jti
  283. 13 return false unless jti == Digest::SHA256.hexdigest("#{request.request_method}:#{request.url}:#{nonce_claims['iat']}")
  284. 13 return false unless nonce_claims.key?("aud")
  285. 13 htm, htu = nonce_claims["aud"].split(":", 2)
  286. 13 htm == request.request_method && htu == request.url
  287. end
  288. 13 def json_token_introspect_payload(grant_or_claims)
  289. 13 claims = super
  290. 13 return claims unless grant_or_claims
  291. 13 if (jkt = grant_or_claims.dig("cnf", "jkt"))
  292. 9 (claims[:cnf] ||= {})[:jkt] = jkt
  293. 9 claims[:token_type] = "DPoP"
  294. end
  295. 13 claims
  296. end
  297. 13 def oauth_server_metadata_body(*)
  298. 13 super.tap do |data|
  299. 9 data[:dpop_signing_alg_values_supported] = oauth_dpop_signing_alg_values_supported
  300. end
  301. end
  302. end
  303. end

lib/rodauth/features/oauth_dynamic_client_registration.rb

95.22% lines covered

230 relevant lines. 219 lines covered and 11 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_dynamic_client_registration, :OauthDynamicClientRegistration) do
  5. 13 depends :oauth_base
  6. 13 before "register"
  7. 13 auth_value_method :oauth_client_registration_required_params, %w[redirect_uris client_name]
  8. 13 auth_value_method :oauth_applications_registration_access_token_column, :registration_access_token
  9. 13 auth_value_method :registration_client_uri_route, "register"
  10. 13 PROTECTED_APPLICATION_ATTRIBUTES = %w[account_id client_id].freeze
  11. 13 def load_registration_client_uri_routes
  12. 52 request.on(registration_client_uri_route) do
  13. # CLIENT REGISTRATION URI
  14. 52 request.on(String) do |client_id|
  15. 52 (token = (v = request.env["HTTP_AUTHORIZATION"]) && v[/\A *Bearer (.*)\Z/, 1])
  16. 52 next unless token
  17. 52 oauth_application = db[oauth_applications_table]
  18. .where(oauth_applications_client_id_column => client_id)
  19. .first
  20. 52 next unless oauth_application
  21. 52 authorization_required unless password_hash_match?(oauth_application[oauth_applications_registration_access_token_column], token)
  22. 52 request.is do
  23. 52 request.get do
  24. 13 json_response_oauth_application(oauth_application)
  25. end
  26. 39 request.on method: :put do
  27. 24 %w[client_id registration_access_token registration_client_uri client_secret_expires_at
  28. 2 client_id_issued_at].each do |prohibited_param|
  29. 78 if request.params.key?(prohibited_param)
  30. 13 register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(prohibited_param))
  31. end
  32. end
  33. 13 validate_client_registration_params
  34. # if the client includes the "client_secret" field in the request, the value of this field MUST match the currently
  35. # issued client secret for that client. The client MUST NOT be allowed to overwrite its existing client secret with
  36. # its own chosen value.
  37. 13 authorization_required if request.params.key?("client_secret") && secret_matches?(oauth_application,
  38. request.params["client_secret"])
  39. 13 oauth_application = transaction do
  40. 13 applications_ds = db[oauth_applications_table]
  41. 13 __update_and_return__(applications_ds, @oauth_application_params)
  42. end
  43. 13 json_response_oauth_application(oauth_application)
  44. end
  45. 13 request.on method: :delete do
  46. 13 applications_ds = db[oauth_applications_table]
  47. 13 applications_ds.where(oauth_applications_client_id_column => client_id).delete
  48. 13 response.status = 204
  49. 9 response["Cache-Control"] = "no-store"
  50. 9 response["Pragma"] = "no-cache"
  51. 13 response.finish
  52. end
  53. end
  54. end
  55. end
  56. end
  57. # /register
  58. 13 auth_server_route(:register) do |r|
  59. 1456 before_register_route
  60. 1456 r.post do
  61. 1456 oauth_client_registration_required_params.each do |required_param|
  62. 2860 unless request.params.key?(required_param)
  63. 52 register_throw_json_response_error("invalid_client_metadata", register_required_param_message(required_param))
  64. end
  65. end
  66. 1404 validate_client_registration_params
  67. 702 response_params = transaction do
  68. 702 before_register
  69. 702 do_register
  70. end
  71. 702 response.status = 201
  72. 486 response["Content-Type"] = json_response_content_type
  73. 486 response["Cache-Control"] = "no-store"
  74. 486 response["Pragma"] = "no-cache"
  75. 702 response.write(_json_response_body(response_params))
  76. end
  77. end
  78. 13 def check_csrf?
  79. 1044 case request.path
  80. when register_path
  81. 1456 false
  82. else
  83. 52 super
  84. end
  85. end
  86. 13 private
  87. 13 def _before_register
  88. raise %{dynamic client registration requires authentication.
  89. Override ´before_register` to perform it.
  90. example:
  91. before_register do
  92. account = _account_from_login(request.env["HTTP_X_USER_EMAIL"])
  93. authorization_required unless account
  94. @oauth_application_params[:account_id] = account[:id]
  95. end
  96. }
  97. end
  98. 13 def validate_client_registration_params(request_params = request.params)
  99. 1443 @oauth_application_params = request_params.each_with_object({}) do |(key, value), params|
  100. 12177 case key
  101. when "redirect_uris"
  102. 1404 if value.is_a?(Array)
  103. 1391 value = value.each do |uri|
  104. 2652 unless check_valid_no_fragment_uri?(uri)
  105. 26 register_throw_json_response_error("invalid_redirect_uri",
  106. register_invalid_uri_message(uri))
  107. end
  108. end.join(" ")
  109. else
  110. 13 register_throw_json_response_error("invalid_redirect_uri", register_invalid_uri_message(value))
  111. end
  112. 1365 key = oauth_applications_redirect_uri_column
  113. when "token_endpoint_auth_method"
  114. 663 unless oauth_token_endpoint_auth_methods_supported.include?(value)
  115. 13 register_throw_json_response_error("invalid_client_metadata", register_invalid_client_metadata_message(key, value))
  116. end
  117. # verify if in range
  118. 650 key = oauth_applications_token_endpoint_auth_method_column
  119. when "grant_types"
  120. 728 if value.is_a?(Array)
  121. 715 value = value.each do |grant_type|
  122. 1313 unless oauth_grant_types_supported.include?(grant_type)
  123. 26 register_throw_json_response_error("invalid_client_metadata", register_invalid_client_metadata_message(grant_type, value))
  124. end
  125. end.join(" ")
  126. else
  127. 13 register_throw_json_response_error("invalid_client_metadata", register_invalid_client_metadata_message(key, value))
  128. end
  129. 689 key = oauth_applications_grant_types_column
  130. when "response_types"
  131. 754 if value.is_a?(Array)
  132. 741 grant_types = request_params["grant_types"] || %w[authorization_code]
  133. 741 value = value.each do |response_type|
  134. 754 unless oauth_response_types_supported.include?(response_type)
  135. 13 register_throw_json_response_error("invalid_client_metadata",
  136. register_invalid_response_type_message(response_type))
  137. end
  138. 741 validate_client_registration_response_type(response_type, grant_types)
  139. end.join(" ")
  140. else
  141. 13 register_throw_json_response_error("invalid_client_metadata", register_invalid_client_metadata_message(key, value))
  142. end
  143. 676 key = oauth_applications_response_types_column
  144. # verify if in range and match grant type
  145. when "client_uri", "logo_uri", "tos_uri", "policy_uri", "jwks_uri"
  146. 6487 register_throw_json_response_error("invalid_client_metadata", register_invalid_uri_message(value)) unless check_valid_uri?(value)
  147. 4446 case key
  148. when "client_uri"
  149. 1339 key = oauth_applications_homepage_url_column
  150. when "jwks_uri"
  151. 1222 if request_params.key?("jwks")
  152. 13 register_throw_json_response_error("invalid_client_metadata",
  153. register_invalid_jwks_param_message(key, "jwks"))
  154. end
  155. end
  156. 6409 key = __send__(:"oauth_applications_#{key}_column")
  157. when "jwks"
  158. 26 register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(value)) unless value.is_a?(Hash)
  159. 13 if request_params.key?("jwks_uri")
  160. register_throw_json_response_error("invalid_client_metadata",
  161. register_invalid_jwks_param_message(key, "jwks_uri"))
  162. end
  163. 13 key = oauth_applications_jwks_column
  164. 13 value = JSON.dump(value)
  165. when "scope"
  166. 1352 register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(value)) unless value.is_a?(String)
  167. 1352 scopes = value.split(" ") - oauth_application_scopes
  168. 1352 register_throw_json_response_error("invalid_client_metadata", register_invalid_scopes_message(value)) unless scopes.empty?
  169. 1326 key = oauth_applications_scopes_column
  170. # verify if in range
  171. when "contacts"
  172. 1300 register_throw_json_response_error("invalid_client_metadata", register_invalid_contacts_message(value)) unless value.is_a?(Array)
  173. 1287 value = value.join(" ")
  174. 1287 key = oauth_applications_contacts_column
  175. when "client_name"
  176. 1352 register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(value)) unless value.is_a?(String)
  177. 1352 key = oauth_applications_name_column
  178. when "dpop_bound_access_tokens"
  179. 39 unless respond_to?(:oauth_applications_dpop_bound_access_tokens_column)
  180. register_throw_json_response_error("invalid_client_metadata",
  181. register_invalid_param_message(key))
  182. end
  183. 27 request_params[key] = value = convert_to_boolean(key, value)
  184. 26 key = oauth_applications_dpop_bound_access_tokens_column
  185. when "require_signed_request_object"
  186. 39 unless respond_to?(:oauth_applications_require_signed_request_object_column)
  187. register_throw_json_response_error("invalid_client_metadata",
  188. register_invalid_param_message(key))
  189. end
  190. 27 request_params[key] = value = convert_to_boolean(key, value)
  191. 26 key = oauth_applications_require_signed_request_object_column
  192. when "require_pushed_authorization_requests"
  193. 39 unless respond_to?(:oauth_applications_require_pushed_authorization_requests_column)
  194. register_throw_json_response_error("invalid_client_metadata",
  195. register_invalid_param_message(key))
  196. end
  197. 27 request_params[key] = value = convert_to_boolean(key, value)
  198. 26 key = oauth_applications_require_pushed_authorization_requests_column
  199. when "tls_client_certificate_bound_access_tokens"
  200. 13 property = :oauth_applications_tls_client_certificate_bound_access_tokens_column
  201. 13 register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(key)) unless respond_to?(property)
  202. 9 request_params[key] = value = convert_to_boolean(key, value)
  203. 13 key = oauth_applications_tls_client_certificate_bound_access_tokens_column
  204. when /\Atls_client_auth_/
  205. 91 unless respond_to?(:"oauth_applications_#{key}_column")
  206. register_throw_json_response_error("invalid_client_metadata",
  207. register_invalid_param_message(key))
  208. end
  209. # client using the tls_client_auth authentication method MUST use exactly one of the below metadata
  210. # parameters to indicate the certificate subject value that the authorization server is to expect when
  211. # authenticating the respective client.
  212. 1105 if params.any? { |k, _| k.to_s.start_with?("tls_client_auth_") }
  213. 13 register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(key))
  214. end
  215. 78 key = __send__(:"oauth_applications_#{key}_column")
  216. else
  217. 3302 if respond_to?(:"oauth_applications_#{key}_column")
  218. 3237 if PROTECTED_APPLICATION_ATTRIBUTES.include?(key)
  219. 13 register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(key))
  220. end
  221. 3224 property = :"oauth_applications_#{key}_column"
  222. 3224 key = __send__(property)
  223. 65 elsif !db[oauth_applications_table].columns.include?(key.to_sym)
  224. 39 register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(key))
  225. end
  226. end
  227. 11898 params[key] = value
  228. end
  229. end
  230. 13 def validate_client_registration_response_type(response_type, grant_types)
  231. 477 case response_type
  232. when "code"
  233. 611 unless grant_types.include?("authorization_code")
  234. register_throw_json_response_error("invalid_client_metadata",
  235. register_invalid_response_type_for_grant_type_message(response_type,
  236. "authorization_code"))
  237. end
  238. when "token"
  239. 65 unless grant_types.include?("implicit")
  240. 26 register_throw_json_response_error("invalid_client_metadata",
  241. register_invalid_response_type_for_grant_type_message(response_type, "implicit"))
  242. end
  243. when "none"
  244. 13 if grant_types.include?("implicit") || grant_types.include?("authorization_code")
  245. 13 register_throw_json_response_error("invalid_client_metadata", register_invalid_response_type_message(response_type))
  246. end
  247. end
  248. end
  249. 13 def do_register(return_params = request.params.dup)
  250. 702 applications_ds = db[oauth_applications_table]
  251. 702 application_columns = applications_ds.columns
  252. # set defaults
  253. 702 create_params = @oauth_application_params
  254. # If omitted, an authorization server MAY register a client with a default set of scopes
  255. 702 create_params[oauth_applications_scopes_column] ||= return_params["scopes"] = oauth_application_scopes.join(" ")
  256. # https://datatracker.ietf.org/doc/html/rfc7591#section-2
  257. 702 if create_params[oauth_applications_grant_types_column] ||= begin
  258. # If omitted, the default behavior is that the client will use only the "authorization_code" Grant Type.
  259. 261 return_params["grant_types"] = %w[authorization_code] # rubocop:disable Lint/AssignmentInCondition
  260. 377 "authorization_code"
  261. end
  262. 702 create_params[oauth_applications_token_endpoint_auth_method_column] ||= begin
  263. # If unspecified or omitted, the default is "client_secret_basic", denoting the HTTP Basic
  264. # authentication scheme as specified in Section 2.3.1 of OAuth 2.0.
  265. 270 return_params["token_endpoint_auth_method"] =
  266. "client_secret_basic"
  267. 390 "client_secret_basic"
  268. end
  269. end
  270. 702 create_params[oauth_applications_response_types_column] ||= begin
  271. # If omitted, the default is that the client will use only the "code" response type.
  272. 261 return_params["response_types"] = %w[code]
  273. 377 "code"
  274. end
  275. 702 rescue_from_uniqueness_error do
  276. 702 initialize_register_params(create_params, return_params)
  277. 13715 create_params.delete_if { |k, _| !application_columns.include?(k) }
  278. 702 applications_ds.insert(create_params)
  279. end
  280. 702 return_params
  281. end
  282. 13 def initialize_register_params(create_params, return_params)
  283. 702 client_id = oauth_unique_id_generator
  284. 486 create_params[oauth_applications_client_id_column] = client_id
  285. 486 return_params["client_id"] = client_id
  286. 486 return_params["client_id_issued_at"] = Time.now.utc.iso8601
  287. 702 registration_access_token = oauth_unique_id_generator
  288. 486 create_params[oauth_applications_registration_access_token_column] = secret_hash(registration_access_token)
  289. 486 return_params["registration_access_token"] = registration_access_token
  290. 486 return_params["registration_client_uri"] = "#{base_url}/#{registration_client_uri_route}/#{return_params['client_id']}"
  291. 702 if create_params.key?(oauth_applications_client_secret_column)
  292. 13 set_client_secret(create_params, create_params[oauth_applications_client_secret_column])
  293. 13 return_params.delete("client_secret")
  294. else
  295. 689 client_secret = oauth_unique_id_generator
  296. 689 set_client_secret(create_params, client_secret)
  297. 477 return_params["client_secret"] = client_secret
  298. 477 return_params["client_secret_expires_at"] = 0
  299. end
  300. end
  301. 13 def register_throw_json_response_error(code, message)
  302. 767 throw_json_response_error(oauth_invalid_response_status, code, message)
  303. end
  304. 13 def register_required_param_message(key)
  305. 65 "The param '#{key}' is required by this server."
  306. end
  307. 13 def register_invalid_param_message(key)
  308. 143 "The param '#{key}' is not supported by this server."
  309. end
  310. 13 def register_invalid_client_metadata_message(key, value)
  311. 208 "The value '#{value}' is not supported by this server for param '#{key}'."
  312. end
  313. 13 def register_invalid_contacts_message(contacts)
  314. 13 "The contacts '#{contacts}' are not allowed by this server."
  315. end
  316. 13 def register_invalid_uri_message(uri)
  317. 234 "The '#{uri}' URL is not allowed by this server."
  318. end
  319. 13 def register_invalid_jwks_param_message(key1, key2)
  320. 13 "The param '#{key1}' cannot be accepted together with param '#{key2}'."
  321. end
  322. 13 def register_invalid_scopes_message(scopes)
  323. 26 "The given scopes (#{scopes}) are not allowed by this server."
  324. end
  325. 13 def register_oauth_invalid_grant_type_message(grant_type)
  326. "The grant type #{grant_type} is not allowed by this server."
  327. end
  328. 13 def register_invalid_response_type_message(response_type)
  329. 26 "The response type #{response_type} is not allowed by this server."
  330. end
  331. 13 def register_invalid_response_type_for_grant_type_message(response_type, grant_type)
  332. 39 "The grant type '#{grant_type}' must be registered for the response " \
  333. 12 "type '#{response_type}' to be allowed."
  334. end
  335. 13 def convert_to_boolean(key, value)
  336. 108 case value
  337. when true, false then value
  338. 78 when "true" then true
  339. 39 when "false" then false
  340. else
  341. 39 register_throw_json_response_error(
  342. "invalid_client_metadata",
  343. register_invalid_param_message(key)
  344. )
  345. end
  346. end
  347. 13 def json_response_oauth_application(oauth_application)
  348. 11294 params = methods.map { |k| k.to_s[/\Aoauth_applications_(\w+)_column\z/, 1] }.compact
  349. 26 body = params.each_with_object({}) do |k, hash|
  350. 598 next if %w[id account_id client_id client_secret cliennt_secret_hash].include?(k)
  351. 494 value = oauth_application[__send__(:"oauth_applications_#{k}_column")]
  352. 494 next unless value
  353. 126 case k
  354. when "redirect_uri"
  355. 18 hash["redirect_uris"] = value.split(" ")
  356. when "token_endpoint_auth_method", "grant_types", "response_types", "request_uris", "post_logout_redirect_uris"
  357. hash[k] = value.split(" ")
  358. when "scopes"
  359. 18 hash["scope"] = value
  360. when "jwks"
  361. hash[k] = value.is_a?(String) ? JSON.parse(value) : value
  362. when "homepage_url"
  363. 18 hash["client_uri"] = value
  364. when "name"
  365. 18 hash["client_name"] = value
  366. else
  367. 54 hash[k] = value
  368. end
  369. end
  370. 26 response.status = 200
  371. 26 response["Content-Type"] ||= json_response_content_type
  372. 18 response["Cache-Control"] = "no-store"
  373. 18 response["Pragma"] = "no-cache"
  374. 26 json_payload = _json_response_body(body)
  375. 26 return_response(json_payload)
  376. end
  377. 13 def oauth_server_metadata_body(*)
  378. 26 super.tap do |data|
  379. 18 data[:registration_endpoint] = register_url
  380. end
  381. end
  382. end
  383. end

lib/rodauth/features/oauth_grant_management.rb

100.0% lines covered

33 relevant lines. 33 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_grant_management, :OauthTokenManagement) do
  5. 13 depends :oauth_management_base, :oauth_token_revocation
  6. 13 view "oauth_grants", "My Oauth Grants", "oauth_grants"
  7. 13 button "Revoke", "oauth_grant_revoke"
  8. 13 auth_value_method :oauth_grants_path, "oauth-grants"
  9. 13 %w[type token refresh_token expires_in revoked_at].each do |param|
  10. 65 translatable_method :"oauth_grants_#{param}_label", param.gsub("_", " ").capitalize
  11. end
  12. 13 translatable_method :oauth_no_grants_text, "No oauth grants yet!"
  13. 13 auth_value_method :oauth_grants_route, "oauth-grants"
  14. 13 auth_value_method :oauth_grants_id_pattern, Integer
  15. 13 auth_value_method :oauth_grants_per_page, 20
  16. 13 auth_methods(
  17. :oauth_grant_path
  18. )
  19. 13 def oauth_grants_path(opts = {})
  20. 815 route_path(oauth_grants_route, opts)
  21. end
  22. 13 def oauth_grant_path(id)
  23. 206 "#{oauth_grants_path}/#{id}"
  24. end
  25. 13 def load_oauth_grant_management_routes
  26. 114 request.on(oauth_grants_route) do
  27. 114 check_csrf if check_csrf?
  28. 114 require_account
  29. 114 request.post(oauth_grants_id_pattern) do |id|
  30. 12 db[oauth_grants_table]
  31. .where(oauth_grants_id_column => id)
  32. .where(oauth_grants_account_id_column => account_id)
  33. 1 .update(oauth_grants_revoked_at_column => Sequel::CURRENT_TIMESTAMP)
  34. 13 set_notice_flash revoke_oauth_grant_notice_flash
  35. 13 redirect oauth_grants_path || "/"
  36. end
  37. 101 request.is do
  38. 101 request.get do
  39. 101 page = Integer(param_or_nil("page") || 1)
  40. 101 per_page = per_page_param(oauth_grants_per_page)
  41. 101 scope.instance_variable_set(:@oauth_grants, db[oauth_grants_table]
  42. .select(Sequel[oauth_grants_table].*, Sequel[oauth_applications_table][oauth_applications_name_column])
  43. .join(oauth_applications_table, Sequel[oauth_grants_table][oauth_grants_oauth_application_id_column] =>
  44. Sequel[oauth_applications_table][oauth_applications_id_column])
  45. .where(Sequel[oauth_grants_table][oauth_grants_account_id_column] => account_id)
  46. .where(oauth_grants_revoked_at_column => nil)
  47. .order(Sequel.desc(oauth_grants_id_column))
  48. .paginate(page, per_page))
  49. 101 oauth_grants_view
  50. end
  51. end
  52. end
  53. end
  54. end
  55. end

lib/rodauth/features/oauth_implicit_grant.rb

100.0% lines covered

49 relevant lines. 49 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_implicit_grant, :OauthImplicitGrant) do
  5. 13 depends :oauth_authorize_base
  6. 13 def oauth_grant_types_supported
  7. 2990 super | %w[implicit]
  8. end
  9. 13 def oauth_response_types_supported
  10. 1521 super | %w[token]
  11. end
  12. 13 def oauth_response_modes_supported
  13. 1690 super | %w[fragment]
  14. end
  15. 13 private
  16. 13 def validate_authorize_params
  17. 1751 super
  18. 1647 response_mode = param_or_nil("response_mode")
  19. 1647 return unless response_mode
  20. 429 response_type = param_or_nil("response_type")
  21. 429 return unless response_type == "token"
  22. 78 redirect_response_error("invalid_request") unless oauth_response_modes_for_token_supported.include?(response_mode)
  23. end
  24. 13 def oauth_response_modes_for_token_supported
  25. 78 %w[fragment]
  26. end
  27. 13 def do_authorize(response_params = {}, response_mode = param_or_nil("response_mode"))
  28. 689 response_type = param("response_type")
  29. 689 return super unless response_type == "token" && supported_response_type?(response_type)
  30. 52 response_mode ||= "fragment"
  31. 52 redirect_response_error("invalid_request") unless supported_response_mode?(response_mode)
  32. 52 oauth_grant = _do_authorize_token
  33. 52 response_params.replace(json_access_token_payload(oauth_grant))
  34. 52 response_params["state"] = param("state") if param_or_nil("state")
  35. 52 [response_params, response_mode]
  36. end
  37. 13 def _do_authorize_token(grant_params = {})
  38. 25 grant_params = {
  39. 40 oauth_grants_type_column => "implicit",
  40. oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column],
  41. oauth_grants_scopes_column => scopes,
  42. **resource_owner_params
  43. }.merge(grant_params)
  44. 65 generate_token(grant_params, false)
  45. end
  46. 13 def _redirect_response_error(redirect_url, params)
  47. 260 response_types = param("response_type").split(/ +/)
  48. 260 return super if response_types.empty? || response_types == %w[code]
  49. 296 params = params.map { |k, v| "#{k}=#{v}" }
  50. 143 redirect_url.fragment = params.join("&")
  51. 143 redirect(redirect_url.to_s)
  52. end
  53. 13 def authorize_response(params, mode)
  54. 585 return super unless mode == "fragment"
  55. 364 redirect_url = URI.parse(redirect_uri)
  56. 364 params = [URI.encode_www_form(params)]
  57. 364 params << redirect_url.query if redirect_url.query
  58. 364 redirect_url.fragment = params.join("&")
  59. 364 redirect(redirect_url.to_s)
  60. end
  61. 13 def check_valid_response_type?
  62. 854 return true if param_or_nil("response_type") == "token"
  63. 711 super
  64. end
  65. end
  66. end

lib/rodauth/features/oauth_jwt.rb

100.0% lines covered

59 relevant lines. 59 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 require "rodauth/oauth/http_extensions"
  4. 13 module Rodauth
  5. 13 Feature.define(:oauth_jwt, :OauthJwt) do
  6. 13 depends :oauth_jwt_base, :oauth_jwt_jwks
  7. 13 auth_value_method :oauth_jwt_access_tokens, true
  8. 13 auth_methods(
  9. :jwt_claims,
  10. :verify_access_token_headers
  11. )
  12. 13 def require_oauth_authorization(*scopes)
  13. 273 return super unless oauth_jwt_access_tokens
  14. 273 authorization_required unless authorization_token
  15. 247 token_scopes = authorization_token["scope"].split(" ")
  16. 494 authorization_required unless scopes.any? { |scope| token_scopes.include?(scope) }
  17. end
  18. 13 def oauth_token_subject
  19. 377 return super unless oauth_jwt_access_tokens
  20. 377 return unless authorization_token
  21. 377 authorization_token["sub"]
  22. end
  23. 13 def current_oauth_account
  24. 182 subject = oauth_token_subject
  25. 182 return if subject == authorization_token["client_id"]
  26. 169 oauth_account_ds(subject).first
  27. end
  28. 13 def current_oauth_application
  29. 204 db[oauth_applications_table].where(
  30. oauth_applications_client_id_column => authorization_token["client_id"]
  31. 17 ).first
  32. end
  33. 13 private
  34. 13 def authorization_token
  35. 1872 return super unless oauth_jwt_access_tokens
  36. 1872 return @authorization_token if defined?(@authorization_token)
  37. 403 @authorization_token = decode_access_token
  38. end
  39. 13 def verify_access_token_headers(headers)
  40. 390 headers["typ"] == "at+jwt"
  41. end
  42. 13 def decode_access_token(access_token = fetch_access_token)
  43. 416 return unless access_token
  44. 403 jwt_claims = jwt_decode(access_token, verify_headers: method(:verify_access_token_headers))
  45. 403 return unless jwt_claims
  46. 390 return unless jwt_claims["sub"]
  47. 390 return unless jwt_claims["aud"]
  48. 390 jwt_claims
  49. end
  50. # /token
  51. 13 def create_token_from_token(_grant, update_params)
  52. 104 oauth_grant = super
  53. 104 if oauth_jwt_access_tokens
  54. 104 access_token = _generate_jwt_access_token(oauth_grant)
  55. 72 oauth_grant[oauth_grants_token_column] = access_token
  56. end
  57. 104 oauth_grant
  58. end
  59. 13 def generate_token(_grant_params = {}, should_generate_refresh_token = true)
  60. 624 oauth_grant = super
  61. 624 if oauth_jwt_access_tokens
  62. 611 access_token = _generate_jwt_access_token(oauth_grant)
  63. 423 oauth_grant[oauth_grants_token_column] = access_token
  64. end
  65. 624 oauth_grant
  66. end
  67. 13 def _generate_jwt_access_token(oauth_grant)
  68. 741 claims = jwt_claims(oauth_grant)
  69. # one of the points of using jwt is avoiding database lookups, so we put here all relevant
  70. # token data.
  71. 513 claims[:scope] = oauth_grant[oauth_grants_scopes_column]
  72. # RFC8725 section 3.11: Use Explicit Typing
  73. # RFC9068 section 2.1 : The "typ" value used SHOULD be "at+jwt".
  74. 741 jwt_encode(claims, headers: { typ: "at+jwt" })
  75. end
  76. 13 def _generate_access_token(*)
  77. 728 super unless oauth_jwt_access_tokens
  78. end
  79. 13 def jwt_claims(oauth_grant)
  80. 1352 issued_at = Time.now.to_i
  81. 520 {
  82. 832 iss: oauth_jwt_issuer, # issuer
  83. iat: issued_at, # issued at
  84. #
  85. # sub REQUIRED - as defined in section 4.1.2 of [RFC7519]. In case of
  86. # access tokens obtained through grants where a resource owner is
  87. # involved, such as the authorization code grant, the value of "sub"
  88. # SHOULD correspond to the subject identifier of the resource owner.
  89. # In case of access tokens obtained through grants where no resource
  90. # owner is involved, such as the client credentials grant, the value
  91. # of "sub" SHOULD correspond to an identifier the authorization
  92. # server uses to indicate the client application.
  93. sub: jwt_subject(oauth_grant[oauth_grants_account_id_column]),
  94. client_id: oauth_application[oauth_applications_client_id_column],
  95. exp: issued_at + oauth_access_token_expires_in,
  96. aud: oauth_jwt_audience
  97. }
  98. end
  99. end
  100. end

lib/rodauth/features/oauth_jwt_base.rb

95.13% lines covered

226 relevant lines. 215 lines covered and 11 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 require "rodauth/oauth/http_extensions"
  4. 13 module Rodauth
  5. 13 Feature.define(:oauth_jwt_base, :OauthJwtBase) do
  6. 13 depends :oauth_base
  7. 13 auth_value_method :oauth_application_jwt_public_key_param, "jwt_public_key"
  8. 13 auth_value_method :oauth_application_jwks_param, "jwks"
  9. 13 auth_value_method :oauth_jwt_keys, {}
  10. 13 auth_value_method :oauth_jwt_public_keys, {}
  11. 13 auth_value_method :oauth_jwt_jwe_keys, {}
  12. 13 auth_value_method :oauth_jwt_jwe_public_keys, {}
  13. 13 auth_value_method :oauth_jwt_jwe_copyright, nil
  14. 13 auth_methods(
  15. :jwt_encode,
  16. :jwt_decode,
  17. :jwt_decode_no_key,
  18. :generate_jti,
  19. :oauth_jwt_issuer,
  20. :oauth_jwt_audience,
  21. :resource_owner_params_from_jwt_claims
  22. )
  23. 13 private
  24. 13 def oauth_jwt_issuer
  25. # The JWT MUST contain an "iss" (issuer) claim that contains a
  26. # unique identifier for the entity that issued the JWT.
  27. 3064 @oauth_jwt_issuer ||= authorization_server_url
  28. end
  29. 13 def oauth_jwt_audience
  30. # The JWT MUST contain an "aud" (audience) claim containing a
  31. # value that identifies the authorization server as an intended
  32. # audience. The token endpoint URL of the authorization server
  33. # MAY be used as a value for an "aud" element to identify the
  34. # authorization server as an intended audience of the JWT.
  35. 1352 @oauth_jwt_audience ||= if is_authorization_server?
  36. 1040 oauth_application[oauth_applications_client_id_column]
  37. else
  38. metadata = authorization_server_metadata
  39. return unless metadata
  40. metadata[:token_endpoint]
  41. end
  42. end
  43. 13 def grant_from_application?(grant_or_claims, oauth_application)
  44. 117 return super if grant_or_claims[oauth_grants_id_column]
  45. if grant_or_claims["client_id"]
  46. grant_or_claims["client_id"] == oauth_application[oauth_applications_client_id_column]
  47. else
  48. Array(grant_or_claims["aud"]).include?(oauth_application[oauth_applications_client_id_column])
  49. end
  50. end
  51. 13 def jwt_subject(account_unique_id, client_application = oauth_application)
  52. 1391 (account_unique_id || client_application[oauth_applications_client_id_column]).to_s
  53. end
  54. 13 def resource_owner_params_from_jwt_claims(claims)
  55. 117 { oauth_grants_account_id_column => claims["sub"] }
  56. end
  57. 13 def oauth_server_metadata_body(path = nil)
  58. 208 metadata = super
  59. 208 metadata.merge! \
  60. token_endpoint_auth_signing_alg_values_supported: oauth_jwt_keys.keys.uniq
  61. 208 metadata
  62. end
  63. 13 def _jwt_key
  64. 289 @_jwt_key ||= (oauth_application_jwks(oauth_application) if oauth_application)
  65. end
  66. # Resource Server only!
  67. #
  68. # returns the jwks set from the authorization server.
  69. 13 def auth_server_jwks_set
  70. 52 metadata = authorization_server_metadata
  71. 52 return unless metadata && (jwks_uri = metadata[:jwks_uri])
  72. 52 jwks_uri = URI(jwks_uri)
  73. 52 http_request_with_cache(jwks_uri)
  74. end
  75. 13 def generate_jti(payload)
  76. # Use the key and iat to create a unique key per request to prevent replay attacks
  77. 751 jti_raw = [
  78. 1188 payload[:aud] || payload["aud"],
  79. payload[:iat] || payload["iat"]
  80. ].join(":").to_s
  81. 1939 Digest::SHA256.hexdigest(jti_raw)
  82. end
  83. 13 def verify_jti(jti, claims)
  84. 340 generate_jti(claims) == jti
  85. end
  86. 13 def verify_aud(expected_aud, aud)
  87. 707 expected_aud == aud
  88. end
  89. 13 def oauth_application_jwks(oauth_application)
  90. 1472 jwks = oauth_application[oauth_applications_jwks_column]
  91. 1472 if jwks
  92. 679 jwks = JSON.parse(jwks, symbolize_names: true) if jwks.is_a?(String)
  93. 470 return jwks
  94. end
  95. 793 jwks_uri = oauth_application[oauth_applications_jwks_uri_column]
  96. 793 return unless jwks_uri
  97. 26 jwks_uri = URI(jwks_uri)
  98. 26 http_request_with_cache(jwks_uri)
  99. end
  100. 13 if defined?(JSON::JWT)
  101. # json-jwt
  102. 3 auth_value_method :oauth_jwt_jws_algorithms_supported, %w[
  103. HS256 HS384 HS512
  104. RS256 RS384 RS512
  105. PS256 PS384 PS512
  106. ES256 ES384 ES512 ES256K
  107. ]
  108. 3 auth_value_method :oauth_jwt_jwe_algorithms_supported, %w[
  109. RSA1_5 RSA-OAEP dir A128KW A256KW
  110. ]
  111. 3 auth_value_method :oauth_jwt_jwe_encryption_methods_supported, %w[
  112. A128GCM A256GCM A128CBC-HS256 A256CBC-HS512
  113. ]
  114. 3 def key_to_jwk(key)
  115. 15 JSON::JWK.new(key)
  116. end
  117. 3 def jwk_export(key)
  118. 12 key_to_jwk(key)
  119. end
  120. 3 def jwk_import(jwk)
  121. 126 JSON::JWK.new(jwk)
  122. end
  123. 3 def jwk_key(jwk)
  124. 60 jwk = jwk_import(jwk) unless jwk.is_a?(JSON::JWK)
  125. 60 jwk.to_key
  126. end
  127. 3 def jwk_thumbprint(jwk)
  128. 66 jwk = jwk_import(jwk) if jwk.is_a?(Hash)
  129. 66 jwk.thumbprint
  130. end
  131. 3 def private_jwk?(jwk)
  132. 63 %w[d p q dp dq qi].any?(&jwk.method(:key?))
  133. end
  134. 3 def jwt_encode(payload,
  135. jwks: nil,
  136. headers: {},
  137. encryption_algorithm: oauth_jwt_jwe_keys.keys.dig(0, 0),
  138. encryption_method: oauth_jwt_jwe_keys.keys.dig(0, 1),
  139. jwe_key: oauth_jwt_jwe_keys[[encryption_algorithm,
  140. encryption_method]],
  141. signing_algorithm: oauth_jwt_keys.keys.first)
  142. 246 payload[:jti] = generate_jti(payload)
  143. 369 jwt = JSON::JWT.new(payload)
  144. 369 key = oauth_jwt_keys[signing_algorithm] || _jwt_key
  145. 369 key = key.first if key.is_a?(Array)
  146. 369 jwk = JSON::JWK.new(key || "")
  147. # update headers
  148. 369 headers.each_key do |k|
  149. 330 if jwt.respond_to?(:"#{k}=")
  150. 330 jwt.send(:"#{k}=", headers[k])
  151. 330 headers.delete(k)
  152. end
  153. end
  154. 369 jwt.header.merge(headers) unless headers.empty?
  155. 369 jwt = jwt.sign(jwk, signing_algorithm)
  156. 369 return jwt.to_s unless encryption_algorithm && encryption_method
  157. 57 if jwks && (jwk = jwks.find { |k| k[:use] == "enc" && k[:alg] == encryption_algorithm && k[:enc] == encryption_method })
  158. 18 jwk = JSON::JWK.new(jwk)
  159. 18 jwe = jwt.encrypt(jwk, encryption_algorithm.to_sym, encryption_method.to_sym)
  160. 18 jwe.to_s
  161. 3 elsif jwe_key
  162. 3 jwe_key = jwe_key.first if jwe_key.is_a?(Array)
  163. 3 algorithm = encryption_algorithm.to_sym
  164. 3 meth = encryption_method.to_sym
  165. 3 jwt.encrypt(jwe_key, algorithm, meth)
  166. else
  167. jwt.to_s
  168. end
  169. end
  170. 3 def jwt_decode(
  171. token,
  172. jwks: nil,
  173. jws_algorithm: oauth_jwt_public_keys.keys.first || oauth_jwt_keys.keys.first,
  174. jws_key: oauth_jwt_keys[jws_algorithm] || _jwt_key,
  175. jws_encryption_algorithm: oauth_jwt_jwe_keys.keys.dig(0, 0),
  176. jws_encryption_method: oauth_jwt_jwe_keys.keys.dig(0, 1),
  177. jwe_key: oauth_jwt_jwe_keys[[jws_encryption_algorithm, jws_encryption_method]] || oauth_jwt_jwe_keys.values.first,
  178. verify_claims: true,
  179. verify_jti: true,
  180. verify_iss: true,
  181. verify_aud: true,
  182. verify_headers: nil,
  183. **
  184. )
  185. 285 jws_key = jws_key.first if jws_key.is_a?(Array)
  186. 285 if jwe_key
  187. 9 jwe_key = jwe_key.first if jwe_key.is_a?(Array)
  188. 9 token = JSON::JWT.decode(token, jwe_key).plain_text
  189. end
  190. 285 claims = if is_authorization_server?
  191. 273 if jwks
  192. 72 jwks = jwks[:keys] if jwks.is_a?(Hash)
  193. 72 enc_algs = [jws_encryption_algorithm].compact
  194. 72 enc_meths = [jws_encryption_method].compact
  195. 150 sig_algs = jws_algorithm ? [jws_algorithm] : jwks.select { |k| k[:use] == "sig" }.map { |k| k[:alg] }
  196. 72 sig_algs = sig_algs.compact.map(&:to_sym)
  197. # JWKs may be set up without a KID, when there's a single one
  198. 72 if jwks.size == 1 && !jwks[0][:kid]
  199. 3 key = jwks[0]
  200. 3 jwk_key = JSON::JWK.new(key)
  201. 3 jws = JSON::JWT.decode(token, jwk_key)
  202. else
  203. 69 jws = JSON::JWT.decode(token, JSON::JWK::Set.new({ keys: jwks }), enc_algs + sig_algs, enc_meths)
  204. 63 jws = JSON::JWT.decode(jws.plain_text, JSON::JWK::Set.new({ keys: jwks }), sig_algs) if jws.is_a?(JSON::JWE)
  205. end
  206. 66 jws
  207. 201 elsif jws_key
  208. 198 JSON::JWT.decode(token, jws_key)
  209. else
  210. 3 JSON::JWT.decode(token, nil, jws_algorithm)
  211. end
  212. 12 elsif (jwks = auth_server_jwks_set)
  213. 12 JSON::JWT.decode(token, JSON::JWK::Set.new(jwks))
  214. end
  215. 273 now = Time.now
  216. 273 if verify_claims && (
  217. 170 (!claims[:exp] || Time.at(claims[:exp]) < now) &&
  218. 78 (claims[:nbf] && Time.at(claims[:nbf]) < now) &&
  219. (claims[:iat] && Time.at(claims[:iat]) < now) &&
  220. (verify_iss && claims[:iss] != oauth_jwt_issuer) &&
  221. (verify_aud && !verify_aud(claims[:aud], claims[:client_id])) &&
  222. (verify_jti && !verify_jti(claims[:jti], claims))
  223. )
  224. return
  225. end
  226. 273 return if verify_headers && !verify_headers.call(claims.header)
  227. 273 claims
  228. rescue JSON::JWT::Exception
  229. 12 nil
  230. end
  231. 3 def jwt_decode_no_key(token)
  232. 93 jws = JSON::JWT.decode(token, :skip_verification)
  233. 93 [jws.to_h, jws.header]
  234. end
  235. 10 elsif defined?(JWT)
  236. # ruby-jwt
  237. 10 require "rodauth/oauth/jwe_extensions" if defined?(JWE)
  238. 10 auth_value_method :oauth_jwt_jws_algorithms_supported, %w[
  239. HS256 HS384 HS512 HS512256
  240. RS256 RS384 RS512
  241. ED25519
  242. ES256 ES384 ES512
  243. PS256 PS384 PS512
  244. ]
  245. 10 if defined?(JWE)
  246. 10 auth_value_methods(
  247. :oauth_jwt_jwe_algorithms_supported,
  248. :oauth_jwt_jwe_encryption_methods_supported
  249. )
  250. 10 def oauth_jwt_jwe_algorithms_supported
  251. 300 JWE::VALID_ALG
  252. end
  253. 10 def oauth_jwt_jwe_encryption_methods_supported
  254. 290 JWE::VALID_ENC
  255. end
  256. else
  257. auth_value_method :oauth_jwt_jwe_algorithms_supported, []
  258. auth_value_method :oauth_jwt_jwe_encryption_methods_supported, []
  259. end
  260. 10 def key_to_jwk(key)
  261. 50 JWT::JWK.new(key)
  262. end
  263. 10 def jwk_export(key)
  264. 40 key_to_jwk(key).export
  265. end
  266. 10 def jwk_import(jwk)
  267. 620 JWT::JWK.import(jwk)
  268. end
  269. 10 def jwk_key(jwk)
  270. 200 jwk = jwk_import(jwk) unless jwk.is_a?(JWT::JWK)
  271. 200 jwk.keypair
  272. end
  273. 10 def jwk_thumbprint(jwk)
  274. 220 jwk = jwk_import(jwk) if jwk.is_a?(Hash)
  275. 220 JWT::JWK::Thumbprint.new(jwk).generate
  276. end
  277. 10 def private_jwk?(jwk)
  278. 210 jwk_import(jwk).private?
  279. end
  280. 10 def jwt_encode(payload,
  281. signing_algorithm: oauth_jwt_keys.keys.first,
  282. headers: {}, **)
  283. 1230 key = oauth_jwt_keys[signing_algorithm] || _jwt_key
  284. 1230 key = key.first if key.is_a?(Array)
  285. 861 case key
  286. when OpenSSL::PKey::PKey
  287. 990 jwk = JWT::JWK.new(key)
  288. 693 headers[:kid] = jwk.kid
  289. 990 key = jwk.keypair
  290. end
  291. # @see JWT reserved claims - https://tools.ietf.org/html/draft-jones-json-web-token-07#page-7
  292. 861 payload[:jti] = generate_jti(payload)
  293. 1230 JWT.encode(payload, key, signing_algorithm, headers)
  294. end
  295. 10 if defined?(JWE)
  296. 10 def jwt_encode_with_jwe(
  297. payload,
  298. jwks: nil,
  299. encryption_algorithm: oauth_jwt_jwe_keys.keys.dig(0, 0),
  300. encryption_method: oauth_jwt_jwe_keys.keys.dig(0, 1),
  301. jwe_key: oauth_jwt_jwe_keys[[encryption_algorithm, encryption_method]],
  302. **args
  303. )
  304. 1230 token = jwt_encode_without_jwe(payload, **args)
  305. 1230 return token unless encryption_algorithm && encryption_method
  306. 170 if jwks && jwks.any? { |k| k[:use] == "enc" }
  307. 60 JWE.__rodauth_oauth_encrypt_from_jwks(token, jwks, alg: encryption_algorithm, enc: encryption_method)
  308. 10 elsif jwe_key
  309. 10 jwe_key = jwe_key.first if jwe_key.is_a?(Array)
  310. 4 params = {
  311. 6 zip: "DEF",
  312. copyright: oauth_jwt_jwe_copyright
  313. }
  314. 10 params[:enc] = encryption_method if encryption_method
  315. 10 params[:alg] = encryption_algorithm if encryption_algorithm
  316. 10 JWE.encrypt(token, jwe_key, **params)
  317. else
  318. token
  319. end
  320. end
  321. 10 alias_method :jwt_encode_without_jwe, :jwt_encode
  322. 10 alias_method :jwt_encode, :jwt_encode_with_jwe
  323. end
  324. 10 def jwt_decode(
  325. token,
  326. jwks: nil,
  327. jws_algorithm: oauth_jwt_public_keys.keys.first || oauth_jwt_keys.keys.first,
  328. jws_key: oauth_jwt_keys[jws_algorithm] || _jwt_key,
  329. verify_claims: true,
  330. verify_jti: true,
  331. verify_iss: true,
  332. verify_aud: true,
  333. verify_headers: nil
  334. )
  335. 940 jws_key = jws_key.first if jws_key.is_a?(Array)
  336. # verifying the JWT implies verifying:
  337. #
  338. # issuer: check that server generated the token
  339. # aud: check the audience field (client is who he says he is)
  340. # iat: check that the token didn't expire
  341. #
  342. # subject can't be verified automatically without having access to the account id,
  343. # which we don't because that's the whole point.
  344. #
  345. 940 verify_claims_params = if verify_claims
  346. 352 {
  347. 528 verify_iss: verify_iss,
  348. iss: oauth_jwt_issuer,
  349. # can't use stock aud verification, as it's dependent on the client application id
  350. verify_aud: false,
  351. 880 verify_jti: (verify_jti ? method(:verify_jti) : false),
  352. verify_iat: true
  353. }
  354. else
  355. 60 {}
  356. end
  357. # decode jwt
  358. 940 claims, headers = if is_authorization_server?
  359. 900 if jwks
  360. 230 jwks = jwks[:keys] if jwks.is_a?(Hash)
  361. # JWKs may be set up without a KID, when there's a single one
  362. 230 if jwks.size == 1 && !jwks[0][:kid]
  363. 10 key = jwks[0]
  364. 10 algo = key[:alg]
  365. 10 key = JWT::JWK.import(key).keypair
  366. 10 JWT.decode(token, key, true, algorithms: [algo], **verify_claims_params)
  367. else
  368. 480 algorithms = jws_algorithm ? [jws_algorithm] : jwks.select { |k| k[:use] == "sig" }.map { |k| k[:alg] }
  369. 220 JWT.decode(token, nil, true, algorithms: algorithms, jwks: { keys: jwks }, **verify_claims_params)
  370. end
  371. 670 elsif jws_key
  372. 660 JWT.decode(token, jws_key, true, algorithms: [jws_algorithm], **verify_claims_params)
  373. else
  374. 10 JWT.decode(token, jws_key, false, **verify_claims_params)
  375. end
  376. 40 elsif (jwks = auth_server_jwks_set)
  377. 120 algorithms = jwks[:keys].select { |k| k[:use] == "sig" }.map { |k| k[:alg] }
  378. 40 JWT.decode(token, nil, true, jwks: jwks, algorithms: algorithms, **verify_claims_params)
  379. end
  380. 910 return if verify_claims && verify_aud && !verify_aud(claims["aud"], claims["client_id"])
  381. 910 return if verify_headers && !verify_headers.call(headers)
  382. 910 claims
  383. rescue JWT::DecodeError, JWT::JWKError
  384. 30 nil
  385. end
  386. 10 if defined?(JWE)
  387. 10 def jwt_decode_with_jwe(
  388. token,
  389. jwks: nil,
  390. jws_encryption_algorithm: oauth_jwt_jwe_keys.keys.dig(0, 0),
  391. jws_encryption_method: oauth_jwt_jwe_keys.keys.dig(0, 1),
  392. jwe_key: oauth_jwt_jwe_keys[[jws_encryption_algorithm, jws_encryption_method]] || oauth_jwt_jwe_keys.values.first,
  393. **args
  394. )
  395. 1240 token = if jwks && jwks.any? { |k| k[:use] == "enc" }
  396. 30 JWE.__rodauth_oauth_decrypt_from_jwks(token, jwks, alg: jws_encryption_algorithm, enc: jws_encryption_method)
  397. 920 elsif jwe_key
  398. 30 jwe_key = jwe_key.first if jwe_key.is_a?(Array)
  399. 30 JWE.decrypt(token, jwe_key)
  400. else
  401. 890 token
  402. end
  403. 930 jwt_decode_without_jwe(token, jwks: jwks, **args)
  404. rescue JWE::DecodeError => e
  405. 20 jwt_decode_without_jwe(token, jwks: jwks, **args) if e.message.include?("Not enough or too many segments")
  406. end
  407. 10 alias_method :jwt_decode_without_jwe, :jwt_decode
  408. 10 alias_method :jwt_decode, :jwt_decode_with_jwe
  409. end
  410. 10 def jwt_decode_no_key(token)
  411. 310 JWT.decode(token, nil, false)
  412. end
  413. else
  414. skipped # :nocov:
  415. skipped def jwk_export(_key)
  416. skipped raise "#{__method__} is undefined, redefine it or require either \"jwt\" or \"json-jwt\""
  417. skipped end
  418. skipped
  419. skipped def jwk_import(_jwk)
  420. skipped raise "#{__method__} is undefined, redefine it or require either \"jwt\" or \"json-jwt\""
  421. skipped end
  422. skipped
  423. skipped def jwk_thumbprint(_jwk)
  424. skipped raise "#{__method__} is undefined, redefine it or require either \"jwt\" or \"json-jwt\""
  425. skipped end
  426. skipped
  427. skipped def jwt_encode(_token)
  428. skipped raise "#{__method__} is undefined, redefine it or require either \"jwt\" or \"json-jwt\""
  429. skipped end
  430. skipped
  431. skipped def jwt_decode(_token, **)
  432. skipped raise "#{__method__} is undefined, redefine it or require either \"jwt\" or \"json-jwt\""
  433. skipped end
  434. skipped
  435. skipped def private_jwk?(_jwk)
  436. skipped raise "#{__method__} is undefined, redefine it or require either \"jwt\" or \"json-jwt\""
  437. skipped end
  438. skipped # :nocov:
  439. end
  440. end
  441. end

lib/rodauth/features/oauth_jwt_bearer_grant.rb

100.0% lines covered

47 relevant lines. 47 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_jwt_bearer_grant, :OauthJwtBearerGrant) do
  5. 13 depends :oauth_assertion_base, :oauth_jwt
  6. 13 auth_value_method :max_param_bytesize, nil if Rodauth::VERSION >= "2.26.0"
  7. 13 auth_methods(
  8. :require_oauth_application_from_jwt_bearer_assertion_issuer,
  9. :require_oauth_application_from_jwt_bearer_assertion_subject,
  10. :account_from_jwt_bearer_assertion
  11. )
  12. 13 def oauth_token_endpoint_auth_methods_supported
  13. 39 if oauth_applications_client_secret_hash_column.nil?
  14. 13 super | %w[client_secret_jwt private_key_jwt urn:ietf:params:oauth:client-assertion-type:jwt-bearer]
  15. else
  16. 26 super | %w[private_key_jwt]
  17. end
  18. end
  19. 13 def oauth_grant_types_supported
  20. 104 super | %w[urn:ietf:params:oauth:grant-type:jwt-bearer]
  21. end
  22. 13 private
  23. 13 def require_oauth_application_from_jwt_bearer_assertion_issuer(assertion)
  24. 39 claims = jwt_assertion(assertion)
  25. 39 return unless claims
  26. 36 db[oauth_applications_table].where(
  27. oauth_applications_client_id_column => claims["iss"]
  28. 3 ).first
  29. end
  30. 13 def require_oauth_application_from_jwt_bearer_assertion_subject(assertion)
  31. 104 claims, header = jwt_decode_no_key(assertion)
  32. 104 client_id = claims["sub"]
  33. 72 case header["alg"]
  34. when "none"
  35. # do not accept jwts with no alg set
  36. 13 authorization_required
  37. when /\AHS/
  38. 39 require_oauth_application_from_client_secret_jwt(client_id, assertion, header["alg"])
  39. else
  40. 52 require_oauth_application_from_private_key_jwt(client_id, assertion)
  41. end
  42. end
  43. 13 def require_oauth_application_from_client_secret_jwt(client_id, assertion, alg)
  44. 39 oauth_application = db[oauth_applications_table].where(oauth_applications_client_id_column => client_id).first
  45. 39 authorization_required unless oauth_application && supports_auth_method?(oauth_application, "client_secret_jwt")
  46. 26 client_secret = oauth_application[oauth_applications_client_secret_column]
  47. 26 claims = jwt_assertion(assertion, jws_key: client_secret, jws_algorithm: alg)
  48. 26 authorization_required unless claims && claims["iss"] == client_id
  49. 26 oauth_application
  50. end
  51. 13 def require_oauth_application_from_private_key_jwt(client_id, assertion)
  52. 52 oauth_application = db[oauth_applications_table].where(oauth_applications_client_id_column => client_id).first
  53. 52 authorization_required unless oauth_application && supports_auth_method?(oauth_application, "private_key_jwt")
  54. 39 jwks = oauth_application_jwks(oauth_application)
  55. 39 claims = jwt_assertion(assertion, jwks: jwks)
  56. 39 authorization_required unless claims
  57. 39 oauth_application
  58. end
  59. 13 def account_from_jwt_bearer_assertion(assertion)
  60. 39 claims = jwt_assertion(assertion)
  61. 39 return unless claims
  62. 39 account_from_bearer_assertion_subject(claims["sub"])
  63. end
  64. 13 def jwt_assertion(assertion, **kwargs)
  65. 143 claims = jwt_decode(assertion, verify_iss: false, verify_aud: false, verify_jti: false, **kwargs)
  66. 143 return unless claims && verify_aud(request.url, claims["aud"])
  67. 143 claims
  68. end
  69. end
  70. end

lib/rodauth/features/oauth_jwt_jwks.rb

100.0% lines covered

23 relevant lines. 23 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 require "rodauth/oauth/http_extensions"
  4. 13 module Rodauth
  5. 13 Feature.define(:oauth_jwt_jwks, :OauthJwtJwks) do
  6. 13 depends :oauth_jwt_base
  7. 13 auth_methods(:jwks_set)
  8. 13 auth_server_route(:jwks) do |r|
  9. 39 before_jwks_route
  10. 39 r.get do
  11. 39 json_response_success({ keys: jwks_set }, true)
  12. end
  13. end
  14. 13 private
  15. 13 def oauth_server_metadata_body(path = nil)
  16. 208 metadata = super
  17. 208 metadata.merge!(jwks_uri: jwks_url)
  18. 208 metadata
  19. end
  20. 13 def jwks_set
  21. 39 @jwks_set ||= [
  22. *(
  23. 39 unless oauth_jwt_public_keys.empty?
  24. 78 oauth_jwt_public_keys.flat_map { |algo, pkeys| Array(pkeys).map { |pkey| jwk_export(pkey).merge(use: "sig", alg: algo) } }
  25. end
  26. ),
  27. *(
  28. 39 unless oauth_jwt_jwe_public_keys.empty?
  29. 13 oauth_jwt_jwe_public_keys.flat_map do |(algo, _enc), pkeys|
  30. 13 Array(pkeys).map do |pkey|
  31. 13 jwk_export(pkey).merge(use: "enc", alg: algo)
  32. end
  33. end
  34. end
  35. )
  36. ].compact
  37. end
  38. end
  39. end

lib/rodauth/features/oauth_jwt_secured_authorization_request.rb

100.0% lines covered

68 relevant lines. 68 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_jwt_secured_authorization_request, :OauthJwtSecuredAuthorizationRequest) do
  5. 13 ALLOWED_REQUEST_URI_CONTENT_TYPES = %w[application/jose application/oauth-authz-req+jwt].freeze
  6. 13 depends :oauth_authorize_base, :oauth_jwt_base
  7. 13 auth_value_method :oauth_require_request_uri_registration, false
  8. 13 auth_value_method :oauth_require_signed_request_object, false
  9. 13 auth_value_method :oauth_request_object_signing_alg_allow_none, false
  10. 12 %i[
  11. request_uris require_signed_request_object request_object_signing_alg
  12. request_object_encryption_alg request_object_encryption_enc
  13. 1 ].each do |column|
  14. 65 auth_value_method :"oauth_applications_#{column}_column", column
  15. end
  16. 13 translatable_method :oauth_invalid_request_object_message, "request object is invalid"
  17. 13 auth_value_method :max_param_bytesize, nil if Rodauth::VERSION >= "2.26.0"
  18. 13 private
  19. # /authorize
  20. 13 def validate_authorize_params
  21. 585 request_object = param_or_nil("request")
  22. 585 request_uri = param_or_nil("request_uri")
  23. 585 unless (request_object || request_uri) && oauth_application
  24. 143 if request.path == authorize_path && request.get? && require_signed_request_object?
  25. 13 redirect_response_error("invalid_request_object")
  26. end
  27. 90 return super
  28. end
  29. 442 if request_uri
  30. 117 request_uri = CGI.unescape(request_uri)
  31. 117 redirect_response_error("invalid_request_uri") unless supported_request_uri?(request_uri, oauth_application)
  32. 65 response = http_request(request_uri)
  33. 65 unless response.code.to_i == 200 && ALLOWED_REQUEST_URI_CONTENT_TYPES.include?(response["content-type"])
  34. 13 redirect_response_error("invalid_request_uri")
  35. end
  36. 52 request_object = response.body
  37. end
  38. 377 claims = decode_request_object(request_object)
  39. 247 redirect_response_error("invalid_request_object") unless claims
  40. 247 if (iss = claims["iss"]) && (iss != oauth_application[oauth_applications_client_id_column])
  41. 13 redirect_response_error("invalid_request_object")
  42. end
  43. 234 if (aud = claims["aud"]) && !verify_aud(aud, oauth_jwt_issuer)
  44. 13 redirect_response_error("invalid_request_object")
  45. end
  46. # If signed, the Authorization Request
  47. # Object SHOULD contain the Claims "iss" (issuer) and "aud" (audience)
  48. # as members, with their semantics being the same as defined in the JWT
  49. # [RFC7519] specification. The value of "aud" should be the value of
  50. # the Authorization Server (AS) "issuer" as defined in RFC8414
  51. # [RFC8414].
  52. 221 claims.delete("iss")
  53. 221 audience = claims.delete("aud")
  54. 221 redirect_response_error("invalid_request_object") if audience && audience != oauth_jwt_issuer
  55. 221 claims.each do |k, v|
  56. 945 request.params[k.to_s] = v
  57. end
  58. 221 super
  59. end
  60. 13 def supported_request_uri?(request_uri, oauth_application)
  61. 117 return false unless check_valid_uri?(request_uri)
  62. 91 request_uris = oauth_application[oauth_applications_request_uris_column]
  63. 156 request_uris.nil? || request_uris.split(oauth_scope_separator).one? { |uri| request_uri.start_with?(uri) }
  64. end
  65. 13 def require_signed_request_object?
  66. 65 return @require_signed_request_object if defined?(@require_signed_request_object)
  67. 52 @require_signed_request_object = (oauth_application[oauth_applications_require_signed_request_object_column] if oauth_application)
  68. 52 @require_signed_request_object = oauth_require_signed_request_object if @require_signed_request_object.nil?
  69. 52 @require_signed_request_object
  70. end
  71. 13 def decode_request_object(request_object)
  72. 150 request_sig_enc_opts = {
  73. 240 jws_algorithm: oauth_application[oauth_applications_request_object_signing_alg_column],
  74. jws_encryption_algorithm: oauth_application[oauth_applications_request_object_encryption_alg_column],
  75. jws_encryption_method: oauth_application[oauth_applications_request_object_encryption_enc_column]
  76. }.compact
  77. 390 request_sig_enc_opts[:jws_algorithm] ||= "none" if oauth_request_object_signing_alg_allow_none
  78. 390 if request_sig_enc_opts[:jws_algorithm] == "none"
  79. 39 redirect_response_error("invalid_request_object") if require_signed_request_object?
  80. 13 jwks = nil
  81. 351 elsif (jwks = oauth_application_jwks(oauth_application))
  82. 273 jwks = JSON.parse(jwks, symbolize_names: true) if jwks.is_a?(String)
  83. else
  84. 78 redirect_response_error("invalid_request_object")
  85. end
  86. 286 claims = jwt_decode(request_object,
  87. jwks: jwks,
  88. verify_jti: false,
  89. verify_iss: false,
  90. verify_aud: false,
  91. **request_sig_enc_opts)
  92. 286 redirect_response_error("invalid_request_object") unless claims
  93. 260 claims
  94. end
  95. 13 def oauth_server_metadata_body(*)
  96. 39 super.tap do |data|
  97. 27 data[:request_parameter_supported] = true
  98. 27 data[:request_uri_parameter_supported] = true
  99. 27 data[:require_request_uri_registration] = oauth_require_request_uri_registration
  100. 27 data[:require_signed_request_object] = oauth_require_signed_request_object
  101. end
  102. end
  103. end
  104. end

lib/rodauth/features/oauth_jwt_secured_authorization_response_mode.rb

98.53% lines covered

68 relevant lines. 67 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_jwt_secured_authorization_response_mode, :OauthJwtSecuredAuthorizationResponseMode) do
  5. 13 depends :oauth_authorize_base, :oauth_jwt_base
  6. 13 auth_value_method :oauth_authorization_response_mode_expires_in, 60 * 5 # 5 minutes
  7. 13 auth_value_method :oauth_applications_authorization_signed_response_alg_column, :authorization_signed_response_alg
  8. 13 auth_value_method :oauth_applications_authorization_encrypted_response_alg_column, :authorization_encrypted_response_alg
  9. 13 auth_value_method :oauth_applications_authorization_encrypted_response_enc_column, :authorization_encrypted_response_enc
  10. 13 auth_value_methods(
  11. :authorization_signing_alg_values_supported,
  12. :authorization_encryption_alg_values_supported,
  13. :authorization_encryption_enc_values_supported
  14. )
  15. 13 def oauth_response_modes_supported
  16. 559 jwt_response_modes = %w[jwt]
  17. 559 jwt_response_modes.push("query.jwt", "form_post.jwt") if features.include?(:oauth_authorization_code_grant)
  18. 559 jwt_response_modes << "fragment.jwt" if features.include?(:oauth_implicit_grant)
  19. 559 super | jwt_response_modes
  20. end
  21. 13 def authorization_signing_alg_values_supported
  22. 13 oauth_jwt_jws_algorithms_supported
  23. end
  24. 13 def authorization_encryption_alg_values_supported
  25. 26 oauth_jwt_jwe_algorithms_supported
  26. end
  27. 13 def authorization_encryption_enc_values_supported
  28. 26 oauth_jwt_jwe_encryption_methods_supported
  29. end
  30. 13 private
  31. 13 def oauth_response_modes_for_code_supported
  32. 156 return [] unless features.include?(:oauth_authorization_code_grant)
  33. 156 super | %w[query.jwt form_post.jwt jwt]
  34. end
  35. 13 def oauth_response_modes_for_token_supported
  36. 65 return [] unless features.include?(:oauth_implicit_grant)
  37. 65 super | %w[fragment.jwt jwt]
  38. end
  39. 13 def authorize_response(params, mode)
  40. 130 return super unless mode.end_with?("jwt")
  41. 130 response_type = param_or_nil("response_type")
  42. 130 redirect_url = URI.parse(redirect_uri)
  43. 130 jwt = jwt_encode_authorization_response_mode(params)
  44. 130 if mode == "query.jwt" || (mode == "jwt" && response_type == "code")
  45. 65 return super unless features.include?(:oauth_authorization_code_grant)
  46. 65 params = ["response=#{CGI.escape(jwt)}"]
  47. 65 params << redirect_url.query if redirect_url.query
  48. 65 redirect_url.query = params.join("&")
  49. 65 redirect(redirect_url.to_s)
  50. 65 elsif mode == "form_post.jwt"
  51. 13 return super unless features.include?(:oauth_authorization_code_grant)
  52. 9 response["Content-Type"] = "text/html"
  53. 13 body = form_post_response_html(redirect_url) do
  54. 13 "<input type=\"hidden\" name=\"response\" value=\"#{scope.h(jwt)}\" />"
  55. end
  56. 13 response.write(body)
  57. 13 request.halt
  58. 52 elsif mode == "fragment.jwt" || (mode == "jwt" && response_type == "token")
  59. 52 return super unless features.include?(:oauth_implicit_grant)
  60. 52 params = ["response=#{CGI.escape(jwt)}"]
  61. 52 params << redirect_url.query if redirect_url.query
  62. 52 redirect_url.fragment = params.join("&")
  63. 52 redirect(redirect_url.to_s)
  64. else
  65. super
  66. end
  67. end
  68. 13 def _redirect_response_error(redirect_url, params)
  69. 39 response_mode = param_or_nil("response_mode")
  70. 39 return super unless response_mode.end_with?("jwt")
  71. 39 authorize_response(Hash[params], response_mode)
  72. end
  73. 13 def jwt_encode_authorization_response_mode(params)
  74. 130 now = Time.now.to_i
  75. 50 claims = {
  76. 80 iss: oauth_jwt_issuer,
  77. aud: oauth_application[oauth_applications_client_id_column],
  78. exp: now + oauth_authorization_response_mode_expires_in,
  79. iat: now
  80. }.merge(params)
  81. 50 encode_params = {
  82. 80 jwks: oauth_application_jwks(oauth_application),
  83. signing_algorithm: oauth_application[oauth_applications_authorization_signed_response_alg_column],
  84. encryption_algorithm: oauth_application[oauth_applications_authorization_encrypted_response_alg_column],
  85. encryption_method: oauth_application[oauth_applications_authorization_encrypted_response_enc_column]
  86. }.compact
  87. 130 jwt_encode(claims, **encode_params)
  88. end
  89. 13 def oauth_server_metadata_body(*)
  90. 26 super.tap do |data|
  91. 18 data[:authorization_signing_alg_values_supported] = authorization_signing_alg_values_supported
  92. 18 data[:authorization_encryption_alg_values_supported] = authorization_encryption_alg_values_supported
  93. 18 data[:authorization_encryption_enc_values_supported] = authorization_encryption_enc_values_supported
  94. end
  95. end
  96. end
  97. end

lib/rodauth/features/oauth_management_base.rb

100.0% lines covered

39 relevant lines. 39 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_management_base, :OauthManagementBase) do
  5. 13 depends :oauth_authorize_base
  6. 13 button "Previous", "oauth_management_pagination_previous"
  7. 13 button "Next", "oauth_management_pagination_next"
  8. 13 def oauth_management_pagination_links(paginated_ds)
  9. 205 html = +'<nav aria-label="Pagination"><ul class="pagination">'
  10. 205 html << oauth_management_pagination_link(paginated_ds.prev_page, label: oauth_management_pagination_previous_button)
  11. 205 html << oauth_management_pagination_link(paginated_ds.current_page - 1) unless paginated_ds.first_page?
  12. 205 html << oauth_management_pagination_link(paginated_ds.current_page, label: paginated_ds.current_page, current: true)
  13. 205 html << oauth_management_pagination_link(paginated_ds.current_page + 1) unless paginated_ds.last_page?
  14. 205 html << oauth_management_pagination_link(paginated_ds.next_page, label: oauth_management_pagination_next_button)
  15. 205 html << "</ul></nav>"
  16. end
  17. 13 def oauth_management_pagination_link(page, label: page, current: false, classes: "")
  18. 681 classes += " disabled" if current || !page
  19. 681 classes += " active" if current
  20. 681 if page
  21. 337 params = URI.encode_www_form(request.GET.merge("page" => page))
  22. 337 href = "#{request.path}?#{params}"
  23. 221 <<-HTML
  24. 116 <li class="page-item #{classes}" #{'aria-current="page"' if current}>
  25. 116 <a class="page-link" href="#{href}" tabindex="-1" aria-disabled="#{current || !page}">
  26. 116 #{label}
  27. </a>
  28. </li>
  29. HTML
  30. else
  31. 232 <<-HTML
  32. 112 <li class="page-item #{classes}">
  33. <span class="page-link">
  34. 112 #{label}
  35. 112 #{'<span class="sr-only">(current)</span>' if current}
  36. </span>
  37. </li>
  38. HTML
  39. end
  40. end
  41. 13 def post_configure
  42. 100 super
  43. # TODO: remove this in v1, when resource-server mode does not load all of the provider features.
  44. 100 return unless db
  45. 100 db.extension :pagination
  46. end
  47. 13 private
  48. 13 def per_page_param(default_per_page)
  49. 257 per_page = param_or_nil("per_page")
  50. 257 return default_per_page unless per_page
  51. 66 per_page = per_page.to_i
  52. 66 return default_per_page if per_page <= 0
  53. 66 [per_page, default_per_page].min
  54. end
  55. end
  56. end

lib/rodauth/features/oauth_pkce.rb

100.0% lines covered

49 relevant lines. 49 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_pkce, :OauthPkce) do
  5. 13 depends :oauth_authorization_code_grant
  6. 13 auth_value_method :oauth_require_pkce, true
  7. 13 auth_value_method :oauth_pkce_challenge_method, "S256"
  8. 13 auth_value_method :oauth_grants_code_challenge_column, :code_challenge
  9. 13 auth_value_method :oauth_grants_code_challenge_method_column, :code_challenge_method
  10. 13 auth_value_method :oauth_code_challenge_required_error_code, "invalid_request"
  11. 13 translatable_method :oauth_code_challenge_required_message, "code challenge required"
  12. 13 auth_value_method :oauth_unsupported_transform_algorithm_error_code, "invalid_request"
  13. 13 translatable_method :oauth_unsupported_transform_algorithm_message, "transform algorithm not supported"
  14. 13 private
  15. 13 def supports_auth_method?(oauth_application, auth_method)
  16. 104 return super unless auth_method == "none"
  17. 78 request.params.key?("code_verifier") || super
  18. end
  19. 13 def validate_authorize_params
  20. 78 validate_pkce_challenge_params
  21. 65 super
  22. end
  23. 13 def create_oauth_grant(create_params = {})
  24. # PKCE flow
  25. 26 if (code_challenge = param_or_nil("code_challenge"))
  26. 26 code_challenge_method = param_or_nil("code_challenge_method") || oauth_pkce_challenge_method
  27. 18 create_params[oauth_grants_code_challenge_column] = code_challenge
  28. 18 create_params[oauth_grants_code_challenge_method_column] = code_challenge_method
  29. end
  30. 26 super
  31. end
  32. 13 def create_token_from_authorization_code(grant_params, *args, oauth_grant: nil)
  33. 104 oauth_grant ||= valid_locked_oauth_grant(grant_params)
  34. 91 if oauth_grant[oauth_grants_code_challenge_column]
  35. 78 code_verifier = param_or_nil("code_verifier")
  36. 78 redirect_response_error("invalid_request") unless code_verifier && check_valid_grant_challenge?(oauth_grant, code_verifier)
  37. 13 elsif oauth_require_pkce
  38. 13 redirect_response_error("code_challenge_required")
  39. end
  40. 39 super({ oauth_grants_id_column => oauth_grant[oauth_grants_id_column] }, *args, oauth_grant: oauth_grant)
  41. end
  42. 13 def validate_pkce_challenge_params
  43. 78 if param_or_nil("code_challenge")
  44. 52 challenge_method = param_or_nil("code_challenge_method")
  45. 52 redirect_response_error("code_challenge_required") unless oauth_pkce_challenge_method == challenge_method
  46. else
  47. 26 return unless oauth_require_pkce
  48. 13 redirect_response_error("code_challenge_required")
  49. end
  50. end
  51. 13 def check_valid_grant_challenge?(grant, verifier)
  52. 65 challenge = grant[oauth_grants_code_challenge_column]
  53. 45 case grant[oauth_grants_code_challenge_method_column]
  54. when "plain"
  55. 13 challenge == verifier
  56. when "S256"
  57. 39 generated_challenge = Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false)
  58. 39 challenge == generated_challenge
  59. else
  60. 13 redirect_response_error("unsupported_transform_algorithm")
  61. end
  62. end
  63. 13 def oauth_server_metadata_body(*)
  64. 13 super.tap do |data|
  65. 9 data[:code_challenge_methods_supported] = oauth_pkce_challenge_method
  66. end
  67. end
  68. end
  69. end

lib/rodauth/features/oauth_pushed_authorization_request.rb

92.75% lines covered

69 relevant lines. 64 lines covered and 5 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_pushed_authorization_request, :OauthJwtPushedAuthorizationRequest) do
  5. 13 depends :oauth_authorize_base
  6. 13 auth_value_method :oauth_require_pushed_authorization_requests, false
  7. 13 auth_value_method :oauth_applications_require_pushed_authorization_requests_column, :require_pushed_authorization_requests
  8. 13 auth_value_method :oauth_pushed_authorization_request_expires_in, 90 # 90 seconds
  9. 13 auth_value_method :oauth_require_pushed_authorization_request_iss_request_object, true
  10. 13 auth_value_method :oauth_pushed_authorization_requests_table, :oauth_pushed_requests
  11. 12 %i[
  12. oauth_application_id params code expires_in
  13. 1 ].each do |column|
  14. 52 auth_value_method :"oauth_pushed_authorization_requests_#{column}_column", column
  15. end
  16. # /par
  17. 13 auth_server_route(:par) do |r|
  18. 104 require_oauth_application
  19. 91 before_par_route
  20. 91 r.post do
  21. 91 validate_par_params
  22. 65 ds = db[oauth_pushed_authorization_requests_table]
  23. 65 code = oauth_unique_id_generator
  24. 25 push_request_params = {
  25. 40 oauth_pushed_authorization_requests_oauth_application_id_column => oauth_application[oauth_applications_id_column],
  26. oauth_pushed_authorization_requests_code_column => code,
  27. oauth_pushed_authorization_requests_params_column => URI.encode_www_form(request.params),
  28. oauth_pushed_authorization_requests_expires_in_column => Sequel.date_add(Sequel::CURRENT_TIMESTAMP,
  29. seconds: oauth_pushed_authorization_request_expires_in)
  30. }
  31. 65 rescue_from_uniqueness_error do
  32. 65 ds.insert(push_request_params)
  33. end
  34. 65 json_response_success(
  35. 20 "request_uri" => "urn:ietf:params:oauth:request_uri:#{code}",
  36. "expires_in" => oauth_pushed_authorization_request_expires_in
  37. )
  38. end
  39. end
  40. 13 def check_csrf?
  41. 414 case request.path
  42. when par_path
  43. 104 false
  44. else
  45. 494 super
  46. end
  47. end
  48. 13 private
  49. 13 def validate_par_params
  50. # https://datatracker.ietf.org/doc/html/rfc9126#section-2.1
  51. # The request_uri authorization request parameter is one exception, and it MUST NOT be provided.
  52. 91 redirect_response_error("invalid_request") if param_or_nil("request_uri")
  53. 78 if features.include?(:oauth_jwt_secured_authorization_request)
  54. 13 if (request_object = param_or_nil("request"))
  55. 13 claims = decode_request_object(request_object)
  56. # https://datatracker.ietf.org/doc/html/rfc9126#section-3-5.3
  57. # reject the request if the authenticated client_id does not match the client_id claim in the Request Object
  58. 13 if (client_id = claims["client_id"]) && (client_id != oauth_application[oauth_applications_client_id_column])
  59. redirect_response_error("invalid_request_object")
  60. end
  61. # requiring the iss claim to match the client_id is at the discretion of the authorization server
  62. 13 if oauth_require_pushed_authorization_request_iss_request_object &&
  63. 13 (iss = claims.delete("iss")) &&
  64. iss != oauth_application[oauth_applications_client_id_column]
  65. redirect_response_error("invalid_request_object")
  66. end
  67. 13 if (aud = claims.delete("aud")) && !verify_aud(aud, oauth_jwt_issuer)
  68. redirect_response_error("invalid_request_object")
  69. end
  70. 13 claims.delete("exp")
  71. 13 request.params.delete("request")
  72. 13 claims.each do |k, v|
  73. 54 request.params[k.to_s] = v
  74. end
  75. elsif require_signed_request_object?
  76. redirect_response_error("invalid_request_object")
  77. end
  78. end
  79. 78 validate_authorize_params
  80. end
  81. 13 def validate_authorize_params
  82. 247 return super unless request.get? && request.path == authorize_path
  83. 117 if (request_uri = param_or_nil("request_uri"))
  84. 65 code = request_uri.delete_prefix("urn:ietf:params:oauth:request_uri:")
  85. 65 table = oauth_pushed_authorization_requests_table
  86. 65 ds = db[table]
  87. 65 pushed_request = ds.where(
  88. oauth_pushed_authorization_requests_oauth_application_id_column => oauth_application[oauth_applications_id_column],
  89. oauth_pushed_authorization_requests_code_column => code
  90. ).where(
  91. Sequel.expr(Sequel[table][oauth_pushed_authorization_requests_expires_in_column]) >= Sequel::CURRENT_TIMESTAMP
  92. ).first
  93. 65 redirect_response_error("invalid_request") unless pushed_request
  94. 52 URI.decode_www_form(pushed_request[oauth_pushed_authorization_requests_params_column]).each do |k, v|
  95. 153 request.params[k.to_s] = v
  96. end
  97. 52 request.params.delete("request_uri")
  98. # we're removing the request_uri here, so the checkup for signed reqest has to be invalidated.
  99. 52 @require_signed_request_object = false
  100. 52 elsif oauth_require_pushed_authorization_requests ||
  101. 24 (oauth_application && oauth_application[oauth_applications_require_pushed_authorization_requests_column])
  102. 26 redirect_authorize_error("request_uri")
  103. end
  104. 78 super
  105. end
  106. 13 def oauth_server_metadata_body(*)
  107. 13 super.tap do |data|
  108. 9 data[:require_pushed_authorization_requests] = oauth_require_pushed_authorization_requests
  109. 9 data[:pushed_authorization_request_endpoint] = par_url
  110. end
  111. end
  112. end
  113. end

lib/rodauth/features/oauth_resource_indicators.rb

93.9% lines covered

82 relevant lines. 77 lines covered and 5 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_resource_indicators, :OauthResourceIndicators) do
  5. 13 depends :oauth_authorize_base
  6. 13 auth_value_method :oauth_grants_resource_column, :resource
  7. 13 def resource_indicators
  8. 520 return @resource_indicators if defined?(@resource_indicators)
  9. 130 resources = param_or_nil("resource")
  10. 130 return unless resources
  11. 130 if json_request? || param_or_nil("request") # signed request
  12. 26 resources = Array(resources)
  13. else
  14. 104 query = if request.form_data?
  15. 65 request.body.rewind
  16. 65 request.body.read
  17. else
  18. 39 request.query_string
  19. end
  20. # resource query param does not conform to rack parsing rules
  21. 104 resources = URI.decode_www_form(query).each_with_object([]) do |(k, v), memo|
  22. 546 memo << v if k == "resource"
  23. end
  24. end
  25. 130 @resource_indicators = resources
  26. end
  27. 13 def require_oauth_authorization(*)
  28. 91 super
  29. # done so to support token-in-grant-db, jwt, and resource-server mode
  30. 78 token_indicators = authorization_token[oauth_grants_resource_column] || authorization_token["resource"]
  31. 78 return unless token_indicators
  32. 65 token_indicators = token_indicators.split(" ") if token_indicators.is_a?(String)
  33. 130 authorization_required unless token_indicators.any? { |resource| base_url.start_with?(resource) }
  34. end
  35. 13 private
  36. 13 def validate_token_params
  37. 52 super
  38. 52 return unless resource_indicators
  39. 52 resource_indicators.each do |resource|
  40. 52 redirect_response_error("invalid_target") unless check_valid_no_fragment_uri?(resource)
  41. end
  42. end
  43. 13 def create_token_from_token(oauth_grant, update_params)
  44. return super unless resource_indicators
  45. grant_indicators = oauth_grant[oauth_grants_resource_column]
  46. grant_indicators = grant_indicators.split(" ") if grant_indicators.is_a?(String)
  47. redirect_response_error("invalid_target") unless (grant_indicators - resource_indicators) != grant_indicators
  48. super(oauth_grant, update_params.merge(oauth_grants_resource_column => resource_indicators))
  49. end
  50. 13 module IndicatorAuthorizationCodeGrant
  51. 13 private
  52. 13 def validate_authorize_params
  53. 78 super
  54. 78 return unless resource_indicators
  55. 78 resource_indicators.each do |resource|
  56. 78 redirect_response_error("invalid_target") unless check_valid_no_fragment_uri?(resource)
  57. end
  58. end
  59. 13 def create_token_from_authorization_code(grant_params, *args, oauth_grant: nil)
  60. 52 return super unless resource_indicators
  61. 52 oauth_grant ||= valid_locked_oauth_grant(grant_params)
  62. 52 redirect_response_error("invalid_target") unless oauth_grant[oauth_grants_resource_column]
  63. 52 grant_indicators = oauth_grant[oauth_grants_resource_column]
  64. 52 grant_indicators = grant_indicators.split(" ") if grant_indicators.is_a?(String)
  65. 52 redirect_response_error("invalid_target") unless (grant_indicators - resource_indicators) != grant_indicators
  66. # update ownership
  67. 39 if grant_indicators != resource_indicators
  68. 13 oauth_grant = __update_and_return__(
  69. db[oauth_grants_table].where(oauth_grants_id_column => oauth_grant[oauth_grants_id_column]),
  70. oauth_grants_resource_column => resource_indicators
  71. )
  72. end
  73. 39 super({ oauth_grants_id_column => oauth_grant[oauth_grants_id_column] }, *args, oauth_grant: oauth_grant)
  74. end
  75. 13 def create_oauth_grant(create_params = {})
  76. 13 create_params[oauth_grants_resource_column] = resource_indicators.join(" ") if resource_indicators
  77. 13 super
  78. end
  79. end
  80. 13 module IndicatorIntrospection
  81. 13 def json_token_introspect_payload(grant)
  82. 13 return super unless grant && grant[oauth_grants_id_column]
  83. 13 payload = super
  84. 13 token_indicators = grant[oauth_grants_resource_column]
  85. 13 token_indicators = token_indicators.split(" ") if token_indicators.is_a?(String)
  86. 9 payload[:aud] = token_indicators
  87. 13 payload
  88. end
  89. 13 def introspection_request(*)
  90. 39 payload = super
  91. 39 payload[oauth_grants_resource_column] = payload["aud"] if payload["aud"]
  92. 39 payload
  93. end
  94. end
  95. 13 module IndicatorJwt
  96. 13 def jwt_claims(*)
  97. 13 return super unless resource_indicators
  98. 13 super.merge(aud: resource_indicators)
  99. end
  100. 13 def jwt_decode(token, verify_aud: true, **args)
  101. 39 claims = super(token, verify_aud: false, **args)
  102. 39 return claims unless verify_aud
  103. 26 return unless claims["aud"] && claims["aud"].one? { |aud| request.url.starts_with?(aud) }
  104. 13 claims
  105. end
  106. end
  107. 13 def self.included(rodauth)
  108. 195 super
  109. 195 rodauth.send(:include, IndicatorAuthorizationCodeGrant) if rodauth.features.include?(:oauth_authorization_code_grant)
  110. 195 rodauth.send(:include, IndicatorIntrospection) if rodauth.features.include?(:oauth_token_introspection)
  111. 195 rodauth.send(:include, IndicatorJwt) if rodauth.features.include?(:oauth_jwt)
  112. end
  113. end
  114. end

lib/rodauth/features/oauth_resource_server.rb

96.3% lines covered

27 relevant lines. 26 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_resource_server, :OauthResourceServer) do
  5. 13 depends :oauth_token_introspection
  6. 13 auth_value_method :is_authorization_server?, false
  7. 13 auth_methods(
  8. :before_introspection_request
  9. )
  10. 13 def authorization_token
  11. 234 return @authorization_token if defined?(@authorization_token)
  12. # check if there is a token
  13. 117 access_token = fetch_access_token
  14. 117 return unless access_token
  15. # where in resource server, NOT the authorization server.
  16. 91 payload = introspection_request("access_token", access_token)
  17. 91 return unless payload["active"]
  18. 78 @authorization_token = payload
  19. end
  20. 13 def require_oauth_authorization(*scopes)
  21. 117 authorization_required unless authorization_token
  22. 78 aux_scopes = authorization_token["scope"]
  23. 78 token_scopes = if aux_scopes
  24. 78 aux_scopes.split(oauth_scope_separator)
  25. else
  26. []
  27. end
  28. 156 authorization_required unless scopes.any? { |scope| token_scopes.include?(scope) }
  29. end
  30. 13 private
  31. 13 def introspection_request(token_type_hint, token)
  32. 91 introspect_url = URI("#{authorization_server_url}#{introspect_path}")
  33. 91 response = http_request(introspect_url, { "token_type_hint" => token_type_hint, "token" => token }) do |request|
  34. 91 before_introspection_request(request)
  35. end
  36. 91 JSON.parse(response.body)
  37. end
  38. 13 def before_introspection_request(request); end
  39. end
  40. end

lib/rodauth/features/oauth_saml_bearer_grant.rb

96.77% lines covered

62 relevant lines. 60 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "onelogin/ruby-saml"
  3. 13 require "rodauth/oauth"
  4. 13 module Rodauth
  5. 13 Feature.define(:oauth_saml_bearer_grant, :OauthSamlBearerGrant) do
  6. 13 depends :oauth_assertion_base
  7. 13 auth_value_method :oauth_saml_name_identifier_format, "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
  8. 13 auth_value_method :oauth_saml_idp_cert_check_expiration, true
  9. 13 auth_value_method :max_param_bytesize, nil if Rodauth::VERSION >= "2.26.0"
  10. 13 auth_value_method :oauth_saml_settings_table, :oauth_saml_settings
  11. 12 %i[
  12. id oauth_application_id
  13. idp_cert idp_cert_fingerprint idp_cert_fingerprint_algorithm
  14. name_identifier_format
  15. issuer
  16. audience
  17. idp_cert_check_expiration
  18. 1 ].each do |column|
  19. 117 auth_value_method :"oauth_saml_settings_#{column}_column", column
  20. end
  21. 13 translatable_method :oauth_saml_assertion_not_base64_message, "SAML assertion must be in base64 format"
  22. 13 translatable_method :oauth_saml_assertion_single_issuer_message, "SAML assertion must have a single issuer"
  23. 13 translatable_method :oauth_saml_settings_not_found_message, "No SAML settings found for issuer"
  24. 13 auth_methods(
  25. :require_oauth_application_from_saml2_bearer_assertion_issuer,
  26. :require_oauth_application_from_saml2_bearer_assertion_subject,
  27. :account_from_saml2_bearer_assertion
  28. )
  29. 13 def oauth_grant_types_supported
  30. 26 super | %w[urn:ietf:params:oauth:grant-type:saml2-bearer]
  31. end
  32. 13 private
  33. 13 def require_oauth_application_from_saml2_bearer_assertion_issuer(assertion)
  34. 13 parse_saml_assertion(assertion)
  35. 13 return unless @saml_settings
  36. 12 db[oauth_applications_table].where(
  37. oauth_applications_id_column => @saml_settings[oauth_saml_settings_oauth_application_id_column]
  38. 1 ).first
  39. end
  40. 13 def require_oauth_application_from_saml2_bearer_assertion_subject(assertion)
  41. 13 parse_saml_assertion(assertion)
  42. 13 return unless @assertion
  43. # 3.3.8 - For client authentication, the Subject MUST be the "client_id" of the OAuth client.
  44. 12 db[oauth_applications_table].where(
  45. oauth_applications_client_id_column => @assertion.nameid
  46. 1 ).first
  47. end
  48. 13 def account_from_saml2_bearer_assertion(assertion)
  49. 13 parse_saml_assertion(assertion)
  50. 13 return unless @assertion
  51. 13 account_from_bearer_assertion_subject(@assertion.nameid)
  52. end
  53. 13 def generate_saml_settings(saml_settings)
  54. 26 settings = OneLogin::RubySaml::Settings.new
  55. # issuer
  56. 26 settings.idp_entity_id = saml_settings[oauth_saml_settings_issuer_column]
  57. # audience
  58. 26 settings.sp_entity_id = saml_settings[oauth_saml_settings_audience_column] || token_url
  59. # recipient
  60. 26 settings.assertion_consumer_service_url = token_url
  61. 26 settings.idp_cert = saml_settings[oauth_saml_settings_idp_cert_column]
  62. 26 settings.idp_cert_fingerprint = saml_settings[oauth_saml_settings_idp_cert_fingerprint_column]
  63. 26 settings.idp_cert_fingerprint_algorithm = saml_settings[oauth_saml_settings_idp_cert_fingerprint_algorithm_column]
  64. 26 if settings.idp_cert
  65. 26 check_idp_cert_expiration = saml_settings[oauth_saml_settings_idp_cert_check_expiration_column]
  66. 26 check_idp_cert_expiration = oauth_saml_idp_cert_check_expiration if check_idp_cert_expiration.nil?
  67. 18 settings.security[:check_idp_cert_expiration] = check_idp_cert_expiration
  68. end
  69. 18 settings.security[:strict_audience_validation] = true
  70. 18 settings.security[:want_name_id] = true
  71. 26 settings.name_identifier_format = saml_settings[oauth_saml_settings_name_identifier_format_column] ||
  72. oauth_saml_name_identifier_format
  73. 26 settings
  74. end
  75. # rubocop:disable Naming/MemoizedInstanceVariableName
  76. 13 def parse_saml_assertion(assertion)
  77. 39 return @assertion if defined?(@assertion)
  78. 26 response = OneLogin::RubySaml::Response.new(assertion)
  79. # The SAML Assertion XML data MUST be encoded using base64url
  80. 26 redirect_response_error("invalid_grant", oauth_saml_assertion_not_base64_message) unless response.send(:base64_encoded?, assertion)
  81. # 1. The Assertion's <Issuer> element MUST contain a unique identifier
  82. # for the entity that issued the Assertion.
  83. 26 redirect_response_error("invalid_grant", oauth_saml_assertion_single_issuer_message) unless response.issuers.size == 1
  84. 26 @saml_settings = db[oauth_saml_settings_table].where(
  85. oauth_saml_settings_issuer_column => response.issuers.first
  86. ).first
  87. 26 redirect_response_error("invalid_grant", oauth_saml_settings_not_found_message) unless @saml_settings
  88. 26 response.settings = generate_saml_settings(@saml_settings)
  89. # 2. The Assertion MUST contain a <Conditions> element ...
  90. # 3. he Assertion MUST have an expiry that limits the time window ...
  91. # 4. The Assertion MUST have an expiry that limits the time window ...
  92. # 5. The <Subject> element MUST contain at least one ...
  93. # 6. The authorization server MUST reject the entire Assertion if the ...
  94. # 7. If the Assertion issuer directly authenticated the subject, ...
  95. 26 redirect_response_error("invalid_grant", response.errors.join("; ")) unless response.is_valid?
  96. 26 @assertion = response
  97. end
  98. # rubocop:enable Naming/MemoizedInstanceVariableName
  99. 13 def oauth_server_metadata_body(*)
  100. super.tap do |data|
  101. data[:token_endpoint_auth_methods_supported] << "urn:ietf:params:oauth:client-assertion-type:saml2-bearer"
  102. end
  103. end
  104. end
  105. end

lib/rodauth/features/oauth_tls_client_auth.rb

89.29% lines covered

84 relevant lines. 75 lines covered and 9 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "openssl"
  3. 13 require "ipaddr"
  4. 13 require "uri"
  5. 13 require "rodauth/oauth"
  6. 13 module Rodauth
  7. 13 Feature.define(:oauth_tls_client_auth, :OauthTlsClientAuth) do
  8. 13 depends :oauth_base
  9. 13 auth_value_method :oauth_tls_client_certificate_bound_access_tokens, false
  10. 12 %i[
  11. tls_client_auth_subject_dn tls_client_auth_san_dns
  12. tls_client_auth_san_uri tls_client_auth_san_ip
  13. tls_client_auth_san_email tls_client_certificate_bound_access_tokens
  14. 1 ].each do |column|
  15. 78 auth_value_method :"oauth_applications_#{column}_column", column
  16. end
  17. 13 auth_value_method :oauth_grants_certificate_thumbprint_column, :certificate_thumbprint
  18. 13 def oauth_token_endpoint_auth_methods_supported
  19. 13 super | %w[tls_client_auth self_signed_tls_client_auth]
  20. end
  21. 13 private
  22. 13 def validate_token_params
  23. # For all requests to the authorization server utilizing mutual-TLS client authentication,
  24. # the client MUST include the client_id parameter
  25. 260 redirect_response_error("invalid_request") if client_certificate && !param_or_nil("client_id")
  26. 260 super
  27. end
  28. 13 def require_oauth_application
  29. 390 return super unless client_certificate
  30. 364 authorization_required unless oauth_application
  31. 364 if supports_auth_method?(oauth_application, "tls_client_auth")
  32. # It relies on a validated certificate chain [RFC5280]
  33. 351 ssl_verify = request.env["SSL_CLIENT_VERIFY"] || request.env["HTTP_SSL_CLIENT_VERIFY"] || request.env["HTTP_X_SSL_CLIENT_VERIFY"]
  34. 351 authorization_required unless ssl_verify == "SUCCESS"
  35. # and a single subject distinguished name (DN) or a single subject alternative name (SAN) to
  36. # authenticate the client. Only one subject name value of any type is used for each client.
  37. 351 name_matches = if oauth_application[:tls_client_auth_subject_dn]
  38. 299 distinguished_name_match?(client_certificate.subject, oauth_application[:tls_client_auth_subject_dn])
  39. 52 elsif (dns = oauth_application[:tls_client_auth_san_dns])
  40. 26 client_certificate_sans.any? { |san| san.tag == 2 && OpenSSL::SSL.verify_hostname(dns, san.value) }
  41. 39 elsif (uri = oauth_application[:tls_client_auth_san_uri])
  42. 13 uri = URI(uri)
  43. 52 client_certificate_sans.any? { |san| san.tag == 6 && URI(san.value) == uri }
  44. 26 elsif (ip = oauth_application[:tls_client_auth_san_ip])
  45. 13 ip = IPAddr.new(ip).hton
  46. 39 client_certificate_sans.any? { |san| san.tag == 7 && san.value == ip }
  47. 13 elsif (email = oauth_application[:tls_client_auth_san_email])
  48. 65 client_certificate_sans.any? { |san| san.tag == 1 && san.value == email }
  49. else
  50. false
  51. end
  52. 351 authorization_required unless name_matches
  53. 351 oauth_application
  54. 13 elsif supports_auth_method?(oauth_application, "self_signed_tls_client_auth")
  55. 13 jwks = oauth_application_jwks(oauth_application)
  56. 13 thumbprint = jwk_thumbprint(key_to_jwk(client_certificate.public_key))
  57. # The client is successfully authenticated if the certificate that it presented during the handshake
  58. # matches one of the certificates configured or registered for that particular client.
  59. 26 authorization_required unless jwks.any? { |jwk| Array(jwk[:x5c]).first == thumbprint }
  60. 13 oauth_application
  61. else
  62. super
  63. end
  64. rescue URI::InvalidURIError, IPAddr::InvalidAddressError
  65. authorization_required
  66. end
  67. 13 def store_token(grant_params, update_params = {})
  68. 143 return super unless client_certificate && (
  69. 88 oauth_tls_client_certificate_bound_access_tokens ||
  70. oauth_application[oauth_applications_tls_client_certificate_bound_access_tokens_column]
  71. )
  72. update_params[oauth_grants_certificate_thumbprint_column] = jwk_thumbprint(key_to_jwk(client_certificate.public_key))
  73. super
  74. end
  75. 13 def jwt_claims(oauth_grant)
  76. claims = super
  77. return claims unless oauth_grant[oauth_grants_certificate_thumbprint_column]
  78. claims[:cnf] = {
  79. "x5t#S256" => oauth_grant[oauth_grants_certificate_thumbprint_column]
  80. }
  81. claims
  82. end
  83. 13 def json_token_introspect_payload(grant_or_claims)
  84. 91 claims = super
  85. 91 return claims unless grant_or_claims && grant_or_claims[oauth_grants_certificate_thumbprint_column]
  86. 45 (claims[:cnf] ||= {})["x5t#S256"] = grant_or_claims[oauth_grants_certificate_thumbprint_column]
  87. 65 claims
  88. end
  89. 13 def oauth_server_metadata_body(*)
  90. 13 super.tap do |data|
  91. 9 data[:tls_client_certificate_bound_access_tokens] = oauth_tls_client_certificate_bound_access_tokens
  92. end
  93. end
  94. 13 def client_certificate
  95. 1209 return @client_certificate if defined?(@client_certificate)
  96. 1209 unless (pem_cert = request.env["SSL_CLIENT_CERT"] || request.env["HTTP_SSL_CLIENT_CERT"] || request.env["HTTP_X_SSL_CLIENT_CERT"])
  97. 18 return
  98. end
  99. 1183 return if pem_cert.empty?
  100. 1183 @certificate = OpenSSL::X509::Certificate.new(pem_cert)
  101. end
  102. 13 def client_certificate_sans
  103. 52 return @client_certificate_sans if defined?(@client_certificate_sans)
  104. 20 @client_certificate_sans = begin
  105. 52 return [] unless client_certificate
  106. 260 san = client_certificate.extensions.find { |ext| ext.oid == "subjectAltName" }
  107. 52 return [] unless san
  108. 52 ostr = OpenSSL::ASN1.decode(san.to_der).value.last
  109. 52 sans = OpenSSL::ASN1.decode(ostr.value)
  110. 52 return [] unless sans
  111. 52 sans.value
  112. end
  113. end
  114. 13 def distinguished_name_match?(sub1, sub2)
  115. 299 sub1 = OpenSSL::X509::Name.parse(sub1) if sub1.is_a?(String)
  116. 299 sub2 = OpenSSL::X509::Name.parse(sub2) if sub2.is_a?(String)
  117. # OpenSSL::X509::Name#cp calls X509_NAME_cmp via openssl.
  118. # https://www.openssl.org/docs/manmaster/man3/X509_NAME_cmp.html
  119. # This procedure adheres to the matching rules for Distinguished Names (DN) given in
  120. # RFC 4517 section 4.2.15 and RFC 5280 section 7.1.
  121. 299 sub1.cmp(sub2).zero?
  122. end
  123. end
  124. end

lib/rodauth/features/oauth_token_introspection.rb

98.33% lines covered

60 relevant lines. 59 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 require "rodauth/oauth/http_extensions"
  4. 13 module Rodauth
  5. 13 Feature.define(:oauth_token_introspection, :OauthTokenIntrospection) do
  6. 13 depends :oauth_base
  7. 13 before "introspect"
  8. 13 auth_methods(
  9. :resource_owner_identifier
  10. )
  11. # /introspect
  12. 13 auth_server_route(:introspect) do |r|
  13. 299 require_oauth_application_for_introspect
  14. 299 before_introspect_route
  15. 299 r.post do
  16. 299 catch_error do
  17. 299 validate_introspect_params
  18. 247 token_type_hint = param_or_nil("token_type_hint")
  19. 247 before_introspect
  20. 247 oauth_grant = case token_type_hint
  21. when "access_token", nil
  22. 221 if features.include?(:oauth_jwt) && oauth_jwt_access_tokens
  23. 52 jwt_decode(param("token"))
  24. else
  25. 169 oauth_grant_by_token(param("token"))
  26. end
  27. when "refresh_token"
  28. 26 oauth_grant_by_refresh_token(param("token"))
  29. end
  30. 247 oauth_grant ||= oauth_grant_by_refresh_token(param("token")) if token_type_hint.nil?
  31. 247 json_response_success(json_token_introspect_payload(oauth_grant))
  32. end
  33. throw_json_response_error(oauth_invalid_response_status, "invalid_request")
  34. end
  35. end
  36. # Token introspect
  37. 13 def validate_introspect_params(token_hint_types = %w[access_token refresh_token].freeze)
  38. # check if valid token hint type
  39. 299 if param_or_nil("token_type_hint") && !token_hint_types.include?(param("token_type_hint"))
  40. 26 redirect_response_error("unsupported_token_type")
  41. end
  42. 273 redirect_response_error("invalid_request") unless param_or_nil("token")
  43. end
  44. 13 def json_token_introspect_payload(grant_or_claims)
  45. 247 return { active: false } unless grant_or_claims
  46. 195 if grant_or_claims["sub"]
  47. # JWT
  48. 20 {
  49. 32 active: true,
  50. scope: grant_or_claims["scope"],
  51. client_id: grant_or_claims["client_id"],
  52. username: resource_owner_identifier(grant_or_claims),
  53. token_type: oauth_token_type.capitalize,
  54. exp: grant_or_claims["exp"],
  55. iat: grant_or_claims["iat"],
  56. nbf: grant_or_claims["nbf"],
  57. sub: grant_or_claims["sub"],
  58. aud: grant_or_claims["aud"],
  59. iss: grant_or_claims["iss"],
  60. jti: grant_or_claims["jti"]
  61. }
  62. else
  63. 55 {
  64. 88 active: true,
  65. scope: grant_or_claims[oauth_grants_scopes_column],
  66. client_id: oauth_application[oauth_applications_client_id_column],
  67. username: resource_owner_identifier(grant_or_claims),
  68. token_type: oauth_token_type,
  69. exp: grant_or_claims[oauth_grants_expires_in_column].to_i
  70. }
  71. end
  72. end
  73. 13 def check_csrf?
  74. 270 case request.path
  75. when introspect_path
  76. 299 false
  77. else
  78. 91 super
  79. end
  80. end
  81. 13 private
  82. 13 def require_oauth_application_for_introspect
  83. 299 (token = (v = request.env["HTTP_AUTHORIZATION"]) && v[/\A *Bearer (.*)\Z/, 1])
  84. 299 return require_oauth_application unless token
  85. 39 oauth_application = current_oauth_application
  86. 39 authorization_required unless oauth_application
  87. 39 @oauth_application = oauth_application
  88. end
  89. 13 def oauth_server_metadata_body(*)
  90. 26 super.tap do |data|
  91. 18 data[:introspection_endpoint] = introspect_url
  92. 18 data[:introspection_endpoint_auth_methods_supported] = %w[client_secret_basic]
  93. end
  94. end
  95. 13 def resource_owner_identifier(grant_or_claims)
  96. 195 if (account_id = grant_or_claims[oauth_grants_account_id_column])
  97. 117 account_ds(account_id).select(login_column).first[login_column]
  98. 78 elsif (app_id = grant_or_claims[oauth_grants_oauth_application_id_column])
  99. 24 db[oauth_applications_table].where(oauth_applications_id_column => app_id)
  100. .select(oauth_applications_name_column)
  101. 2 .first[oauth_applications_name_column]
  102. 52 elsif (subject = grant_or_claims["sub"])
  103. # JWT
  104. 52 if subject == grant_or_claims["client_id"]
  105. 12 db[oauth_applications_table].where(oauth_applications_client_id_column => subject)
  106. .select(oauth_applications_name_column)
  107. 1 .first[oauth_applications_name_column]
  108. else
  109. 39 account_ds(subject).select(login_column).first[login_column]
  110. end
  111. end
  112. end
  113. end
  114. end

lib/rodauth/features/oauth_token_revocation.rb

100.0% lines covered

60 relevant lines. 60 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oauth_token_revocation, :OauthTokenRevocation) do
  5. 13 depends :oauth_base
  6. 13 before "revoke"
  7. 13 after "revoke"
  8. 13 notice_flash "The oauth grant has been revoked", "revoke_oauth_grant"
  9. # /revoke
  10. 13 auth_server_route(:revoke) do |r|
  11. 130 if logged_in?
  12. 13 require_account
  13. 13 require_oauth_application_from_account
  14. else
  15. 117 require_oauth_application
  16. end
  17. 130 before_revoke_route
  18. 130 r.post do
  19. 130 catch_error do
  20. 130 validate_revoke_params
  21. 91 oauth_grant = nil
  22. 91 transaction do
  23. 91 before_revoke
  24. 91 oauth_grant = revoke_oauth_grant
  25. 52 after_revoke
  26. end
  27. 52 if accepts_json?
  28. 15 json_payload = {
  29. 24 "revoked_at" => convert_timestamp(oauth_grant[oauth_grants_revoked_at_column])
  30. }
  31. 39 if param("token_type_hint") == "refresh_token"
  32. 18 json_payload["refresh_token"] = oauth_grant[oauth_grants_refresh_token_column]
  33. else
  34. 9 json_payload["token"] = oauth_grant[oauth_grants_token_column]
  35. end
  36. 39 json_response_success json_payload
  37. else
  38. 13 set_notice_flash revoke_oauth_grant_notice_flash
  39. 13 redirect request.referer || "/"
  40. end
  41. end
  42. 26 redirect_response_error("invalid_request")
  43. end
  44. end
  45. 13 def validate_revoke_params(token_hint_types = %w[access_token refresh_token].freeze)
  46. 130 token_hint = param_or_nil("token_type_hint")
  47. 130 if features.include?(:oauth_jwt) && oauth_jwt_access_tokens && (!token_hint || token_hint == "access_token")
  48. # JWT access tokens can't be revoked
  49. 26 throw(:rodauth_error)
  50. end
  51. # check if valid token hint type
  52. 104 redirect_response_error("unsupported_token_type") if token_hint && !token_hint_types.include?(token_hint)
  53. 91 redirect_response_error("invalid_request") unless param_or_nil("token")
  54. end
  55. 13 def check_csrf?
  56. 759 case request.path
  57. when revoke_path
  58. 130 !json_request?
  59. else
  60. 977 super
  61. end
  62. end
  63. 13 private
  64. 13 def revoke_oauth_grant
  65. 91 token = param("token")
  66. 91 if param("token_type_hint") == "refresh_token"
  67. 26 oauth_grant = oauth_grant_by_refresh_token(token)
  68. 26 token_column = oauth_grants_refresh_token_column
  69. else
  70. 65 oauth_grant = oauth_grant_by_token_ds(token).where(
  71. oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column]
  72. ).first
  73. 65 token_column = oauth_grants_token_column
  74. end
  75. 91 redirect_response_error("invalid_request") unless oauth_grant
  76. 52 redirect_response_error("invalid_request") unless grant_from_application?(oauth_grant, oauth_application)
  77. 52 update_params = { oauth_grants_revoked_at_column => Sequel::CURRENT_TIMESTAMP }
  78. 52 ds = db[oauth_grants_table].where(oauth_grants_id_column => oauth_grant[oauth_grants_id_column])
  79. 52 oauth_grant = __update_and_return__(ds, update_params)
  80. 36 oauth_grant[token_column] = token
  81. 52 oauth_grant
  82. # If the particular
  83. # token is a refresh token and the authorization server supports the
  84. # revocation of access tokens, then the authorization server SHOULD
  85. # also invalidate all access tokens based on the same authorization
  86. # grant
  87. #
  88. # we don't need to do anything here, as we revalidate existing tokens
  89. end
  90. 13 def oauth_server_metadata_body(*)
  91. 26 super.tap do |data|
  92. 18 data[:revocation_endpoint] = revoke_url
  93. 18 data[:revocation_endpoint_auth_methods_supported] = nil # because it's client_secret_basic
  94. end
  95. end
  96. end
  97. end

lib/rodauth/features/oidc.rb

93.61% lines covered

391 relevant lines. 366 lines covered and 25 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oidc, :Oidc) do
  5. # https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
  6. 5 OIDC_SCOPES_MAP = {
  7. 8 "profile" => %i[name family_name given_name middle_name nickname preferred_username
  8. profile picture website gender birthdate zoneinfo locale updated_at].freeze,
  9. "email" => %i[email email_verified].freeze,
  10. "address" => %i[formatted street_address locality region postal_code country].freeze,
  11. "phone" => %i[phone_number phone_number_verified].freeze
  12. }.freeze
  13. 13 VALID_METADATA_KEYS = %i[
  14. issuer
  15. authorization_endpoint
  16. end_session_endpoint
  17. backchannel_logout_session_supported
  18. token_endpoint
  19. userinfo_endpoint
  20. jwks_uri
  21. registration_endpoint
  22. scopes_supported
  23. response_types_supported
  24. response_modes_supported
  25. grant_types_supported
  26. acr_values_supported
  27. subject_types_supported
  28. id_token_signing_alg_values_supported
  29. id_token_encryption_alg_values_supported
  30. id_token_encryption_enc_values_supported
  31. userinfo_signing_alg_values_supported
  32. userinfo_encryption_alg_values_supported
  33. userinfo_encryption_enc_values_supported
  34. request_object_signing_alg_values_supported
  35. request_object_encryption_alg_values_supported
  36. request_object_encryption_enc_values_supported
  37. token_endpoint_auth_methods_supported
  38. token_endpoint_auth_signing_alg_values_supported
  39. display_values_supported
  40. claim_types_supported
  41. claims_supported
  42. service_documentation
  43. claims_locales_supported
  44. ui_locales_supported
  45. claims_parameter_supported
  46. request_parameter_supported
  47. request_uri_parameter_supported
  48. require_request_uri_registration
  49. op_policy_uri
  50. op_tos_uri
  51. check_session_iframe
  52. frontchannel_logout_supported
  53. frontchannel_logout_session_supported
  54. backchannel_logout_supported
  55. backchannel_logout_session_supported
  56. ].freeze
  57. 13 REQUIRED_METADATA_KEYS = %i[
  58. issuer
  59. authorization_endpoint
  60. token_endpoint
  61. jwks_uri
  62. response_types_supported
  63. subject_types_supported
  64. id_token_signing_alg_values_supported
  65. ].freeze
  66. 13 depends :active_sessions, :oauth_jwt, :oauth_jwt_jwks, :oauth_authorization_code_grant, :oauth_implicit_grant
  67. 13 auth_value_method :oauth_application_scopes, %w[openid]
  68. 12 %i[
  69. subject_type application_type sector_identifier_uri initiate_login_uri
  70. id_token_signed_response_alg id_token_encrypted_response_alg id_token_encrypted_response_enc
  71. userinfo_signed_response_alg userinfo_encrypted_response_alg userinfo_encrypted_response_enc
  72. 1 ].each do |column|
  73. 130 auth_value_method :"oauth_applications_#{column}_column", column
  74. end
  75. 13 %i[nonce acr claims_locales claims].each do |column|
  76. 52 auth_value_method :"oauth_grants_#{column}_column", column
  77. end
  78. 13 auth_value_method :oauth_jwt_subject_type, "public" # fallback subject type: public, pairwise
  79. 13 auth_value_method :oauth_jwt_subject_secret, nil # salt for pairwise generation
  80. 13 translatable_method :oauth_invalid_scope_message, "The Access Token expired"
  81. 13 auth_value_method :oauth_prompt_login_cookie_key, "_rodauth_oauth_prompt_login"
  82. 13 auth_value_method :oauth_prompt_login_cookie_options, {}.freeze
  83. 13 auth_value_method :oauth_prompt_login_interval, 5 * 60 * 60 # 5 minutes
  84. 13 auth_value_methods(
  85. :userinfo_signing_alg_values_supported,
  86. :userinfo_encryption_alg_values_supported,
  87. :userinfo_encryption_enc_values_supported,
  88. :request_object_signing_alg_values_supported,
  89. :request_object_encryption_alg_values_supported,
  90. :request_object_encryption_enc_values_supported,
  91. :oauth_acr_values_supported
  92. )
  93. 13 auth_methods(
  94. :get_oidc_account_last_login_at,
  95. :oidc_authorize_on_prompt_none?,
  96. :fill_with_account_claims,
  97. :get_oidc_param,
  98. :get_additional_param,
  99. :require_acr_value_phr,
  100. :require_acr_value_phrh,
  101. :require_acr_value,
  102. :json_webfinger_payload
  103. )
  104. # /userinfo
  105. 13 auth_server_route(:userinfo) do |r|
  106. 117 r.on method: %i[get post] do
  107. 117 catch_error do
  108. 117 claims = authorization_token
  109. 117 throw_json_response_error(oauth_authorization_required_error_status, "invalid_token") unless claims
  110. 117 oauth_scopes = claims["scope"].split(" ")
  111. 117 throw_json_response_error(oauth_authorization_required_error_status, "invalid_token") unless oauth_scopes.include?("openid")
  112. 117 account = account_ds(claims["sub"]).first
  113. 117 throw_json_response_error(oauth_authorization_required_error_status, "invalid_token") unless account
  114. 117 oauth_scopes.delete("openid")
  115. 117 oidc_claims = { "sub" => claims["sub"] }
  116. 117 @oauth_application = db[oauth_applications_table].where(oauth_applications_client_id_column => claims["client_id"]).first
  117. 117 throw_json_response_error(oauth_authorization_required_error_status, "invalid_token") unless @oauth_application
  118. 117 oauth_grant = valid_oauth_grant_ds(
  119. oauth_grants_oauth_application_id_column => @oauth_application[oauth_applications_id_column],
  120. **resource_owner_params_from_jwt_claims(claims)
  121. ).first
  122. 117 claims_locales = oauth_grant[oauth_grants_claims_locales_column] if oauth_grant
  123. 117 if (claims = oauth_grant[oauth_grants_claims_column])
  124. 13 claims = JSON.parse(claims)
  125. 13 if (userinfo_essential_claims = claims["userinfo"])
  126. 9 oauth_scopes |= userinfo_essential_claims.to_a
  127. end
  128. end
  129. # 5.4 - The Claims requested by the profile, email, address, and phone scope values are returned from the UserInfo Endpoint
  130. 117 fill_with_account_claims(oidc_claims, account, oauth_scopes, claims_locales)
  131. 117 if (algo = @oauth_application[oauth_applications_userinfo_signed_response_alg_column])
  132. 10 params = {
  133. 16 jwks: oauth_application_jwks(@oauth_application),
  134. encryption_algorithm: @oauth_application[oauth_applications_userinfo_encrypted_response_alg_column],
  135. encryption_method: @oauth_application[oauth_applications_userinfo_encrypted_response_enc_column]
  136. }.compact
  137. 26 jwt = jwt_encode(
  138. oidc_claims.merge(
  139. # If signed, the UserInfo Response SHOULD contain the Claims iss (issuer) and aud (audience) as members. The iss value
  140. # SHOULD be the OP's Issuer Identifier URL. The aud value SHOULD be or include the RP's Client ID value.
  141. iss: oauth_jwt_issuer,
  142. aud: @oauth_application[oauth_applications_client_id_column]
  143. ),
  144. signing_algorithm: algo,
  145. **params
  146. )
  147. 26 jwt_response_success(jwt)
  148. else
  149. 91 json_response_success(oidc_claims)
  150. end
  151. end
  152. throw_json_response_error(oauth_authorization_required_error_status, "invalid_token")
  153. end
  154. end
  155. 13 def load_openid_configuration_route(alt_issuer = nil)
  156. 104 request.on(".well-known/openid-configuration") do
  157. 104 allow_cors(request)
  158. 91 request.is do
  159. 91 request.get do
  160. 91 json_response_success(openid_configuration_body(alt_issuer), cache: true)
  161. end
  162. end
  163. end
  164. end
  165. 13 def load_webfinger_route
  166. 26 request.on(".well-known/webfinger") do
  167. 26 request.get do
  168. 26 resource = param_or_nil("resource")
  169. 26 throw_json_response_error(400, "invalid_request") unless resource
  170. 13 response.status = 200
  171. 13 response["Content-Type"] ||= "application/jrd+json"
  172. 13 return_response(json_webfinger_payload)
  173. end
  174. end
  175. end
  176. 13 def check_csrf?
  177. 3654 case request.path
  178. when userinfo_path
  179. 117 false
  180. else
  181. 5141 super
  182. end
  183. end
  184. 13 def oauth_response_types_supported
  185. 1300 grant_types = oauth_grant_types_supported
  186. 1300 oidc_response_types = %w[id_token none]
  187. 1300 oidc_response_types |= ["code id_token"] if grant_types.include?("authorization_code")
  188. 1300 oidc_response_types |= ["code token", "id_token token", "code id_token token"] if grant_types.include?("implicit")
  189. 1300 super | oidc_response_types
  190. end
  191. 13 def current_oauth_account
  192. 13 subject_type = current_oauth_application[oauth_applications_subject_type_column] || oauth_jwt_subject_type
  193. 13 super unless subject_type == "pairwise"
  194. end
  195. 13 private
  196. 13 if defined?(::I18n)
  197. 13 def before_authorize_route
  198. 1500 if (ui_locales = param_or_nil("ui_locales"))
  199. 13 ui_locales = ui_locales.split(" ").map(&:to_sym)
  200. 9 ui_locales &= ::I18n.available_locales
  201. 13 ::I18n.locale = ui_locales.first unless ui_locales.empty?
  202. end
  203. 1500 super
  204. end
  205. end
  206. 13 def userinfo_signing_alg_values_supported
  207. oauth_jwt_jws_algorithms_supported
  208. end
  209. 13 def userinfo_encryption_alg_values_supported
  210. oauth_jwt_jwe_algorithms_supported
  211. end
  212. 13 def userinfo_encryption_enc_values_supported
  213. oauth_jwt_jwe_encryption_methods_supported
  214. end
  215. 13 def request_object_signing_alg_values_supported
  216. oauth_jwt_jws_algorithms_supported
  217. end
  218. 13 def request_object_encryption_alg_values_supported
  219. oauth_jwt_jwe_algorithms_supported
  220. end
  221. 13 def request_object_encryption_enc_values_supported
  222. oauth_jwt_jwe_encryption_methods_supported
  223. end
  224. 13 def oauth_acr_values_supported
  225. 156 acr_values = []
  226. 156 acr_values << "phrh" if features.include?(:webauthn_login)
  227. 156 acr_values << "phr" if respond_to?(:require_two_factor_authenticated)
  228. 156 acr_values
  229. end
  230. 13 def oidc_authorize_on_prompt_none?(_account)
  231. 13 false
  232. end
  233. 13 def validate_authorize_params
  234. 1500 if (max_age = param_or_nil("max_age"))
  235. 18 max_age = Integer(max_age)
  236. 18 redirect_response_error("invalid_request") unless max_age.positive?
  237. 18 if Time.now - get_oidc_account_last_login_at(session_value) > max_age
  238. # force user to re-login
  239. 9 clear_session
  240. 9 set_session_value(login_redirect_session_key, request.fullpath)
  241. 9 redirect require_login_redirect
  242. end
  243. end
  244. 1491 if (claims = param_or_nil("claims"))
  245. # The value is a JSON object listing the requested Claims.
  246. 26 claims = JSON.parse(claims)
  247. 26 claims.each_value do |individual_claims|
  248. 52 redirect_response_error("invalid_request") unless individual_claims.is_a?(Hash)
  249. 52 individual_claims.each_value do |claim|
  250. 78 redirect_response_error("invalid_request") unless claim.nil? || individual_claims.is_a?(Hash)
  251. end
  252. end
  253. end
  254. 1491 sc = scopes
  255. # MUST ensure that the prompt parameter contains consent
  256. # MUST ignore the offline_access request unless the Client
  257. # is using a response_type value that would result in an
  258. # Authorization Code
  259. 1491 if sc && sc.include?("offline_access") && !(param_or_nil("prompt") == "consent" && (
  260. 39 (response_type = param_or_nil("response_type")) && response_type.split(" ").include?("code")
  261. ))
  262. 26 sc.delete("offline_access")
  263. 18 request.params["scope"] = sc.join(" ")
  264. end
  265. 1491 super
  266. 1413 response_type = param_or_nil("response_type")
  267. 1413 is_id_token_response_type = response_type.include?("id_token")
  268. 1413 redirect_response_error("invalid_request") if is_id_token_response_type && !param_or_nil("nonce")
  269. 1400 return unless is_id_token_response_type || response_type == "code token"
  270. 793 response_mode = param_or_nil("response_mode")
  271. # id_token: The default Response Mode for this Response Type is the fragment encoding and the query encoding MUST NOT be used.
  272. 793 redirect_response_error("invalid_request") unless response_mode.nil? || response_mode == "fragment"
  273. end
  274. 13 def require_authorizable_account
  275. 1682 try_prompt
  276. 1604 super
  277. 1578 @acr = try_acr_values
  278. end
  279. 13 def get_oidc_account_last_login_at(account_id)
  280. 629 return get_activity_timestamp(account_id, account_activity_last_activity_column) if features.include?(:account_expiration)
  281. # active sessions based
  282. 629 ds = db[active_sessions_table].where(active_sessions_account_id_column => account_id)
  283. 629 ds = ds.order(Sequel.desc(active_sessions_created_at_column))
  284. 629 convert_timestamp(ds.get(active_sessions_created_at_column))
  285. end
  286. 13 def jwt_subject(account_unique_id, client_application = oauth_application)
  287. 1027 subject_type = client_application[oauth_applications_subject_type_column] || oauth_jwt_subject_type
  288. 711 case subject_type
  289. when "public"
  290. 988 super
  291. when "pairwise"
  292. 39 identifier_uri = client_application[oauth_applications_sector_identifier_uri_column]
  293. 39 unless identifier_uri
  294. 39 identifier_uri = client_application[oauth_applications_redirect_uri_column]
  295. 39 identifier_uri = identifier_uri.split(" ")
  296. # If the Client has not provided a value for sector_identifier_uri in Dynamic Client Registration
  297. # [OpenID.Registration], the Sector Identifier used for pairwise identifier calculation is the host
  298. # component of the registered redirect_uri. If there are multiple hostnames in the registered redirect_uris,
  299. # the Client MUST register a sector_identifier_uri.
  300. 39 if identifier_uri.size > 1
  301. # return error message
  302. end
  303. 39 identifier_uri = identifier_uri.first
  304. end
  305. 39 identifier_uri = URI(identifier_uri).host
  306. 39 values = [identifier_uri, account_unique_id, oauth_jwt_subject_secret]
  307. 39 Digest::SHA256.hexdigest(values.join)
  308. else
  309. raise StandardError, "unexpected subject (#{subject_type})"
  310. end
  311. end
  312. # this executes before checking for a logged in account
  313. 13 def try_prompt
  314. 1682 return unless (prompt = param_or_nil("prompt"))
  315. 153 case prompt
  316. when "none"
  317. 39 return unless request.get?
  318. 39 redirect_response_error("login_required") unless logged_in?
  319. 26 require_account
  320. 26 redirect_response_error("interaction_required") unless oidc_authorize_on_prompt_none?(account_from_session)
  321. 9 request.env["REQUEST_METHOD"] = "POST"
  322. when "login"
  323. 78 return unless request.get?
  324. 52 if logged_in? && request.cookies[oauth_prompt_login_cookie_key] == "login"
  325. 26 ::Rack::Utils.delete_cookie_header!(response.headers, oauth_prompt_login_cookie_key, oauth_prompt_login_cookie_options)
  326. 18 return
  327. end
  328. # logging out
  329. 26 clear_session
  330. 26 set_session_value(login_redirect_session_key, request.fullpath)
  331. 26 login_cookie_opts = Hash[oauth_prompt_login_cookie_options]
  332. 18 login_cookie_opts[:value] = "login"
  333. 26 if oauth_prompt_login_interval
  334. 18 login_cookie_opts[:expires] = convert_timestamp(Time.now + oauth_prompt_login_interval) # 15 minutes
  335. end
  336. 26 ::Rack::Utils.set_cookie_header!(response.headers, oauth_prompt_login_cookie_key, login_cookie_opts)
  337. 26 redirect require_login_redirect
  338. when "consent"
  339. 65 return unless request.post?
  340. 26 require_account
  341. 26 sc = scopes || []
  342. 26 redirect_response_error("consent_required") if sc.empty?
  343. when "select-account"
  344. 39 return unless request.get?
  345. # only works if select_account plugin is available
  346. 26 require_select_account if respond_to?(:require_select_account)
  347. else
  348. redirect_response_error("invalid_request")
  349. end
  350. end
  351. 13 def try_acr_values
  352. 1578 return unless (acr_values = param_or_nil("acr_values"))
  353. 65 acr_values.split(" ").each do |acr_value|
  354. 65 next unless oauth_acr_values_supported.include?(acr_value)
  355. 36 case acr_value
  356. when "phr"
  357. 26 return acr_value if require_acr_value_phr
  358. when "phrh"
  359. 26 return acr_value if require_acr_value_phrh
  360. else
  361. return acr_value if require_acr_value(acr_value)
  362. end
  363. end
  364. 4 nil
  365. end
  366. 13 def require_acr_value_phr
  367. 52 return false unless respond_to?(:require_two_factor_authenticated)
  368. 52 require_two_factor_authenticated
  369. 52 true
  370. end
  371. 13 def require_acr_value_phrh
  372. 26 return false unless features.include?(:webauthn_login)
  373. 26 require_acr_value_phr && two_factor_login_type_match?("webauthn")
  374. end
  375. 13 def require_acr_value(_acr)
  376. true
  377. end
  378. 13 def create_oauth_grant(create_params = {})
  379. 377 create_params.replace(oidc_grant_params.merge(create_params))
  380. 377 super
  381. end
  382. 13 def create_oauth_grant_with_token(create_params = {})
  383. 26 create_params.merge!(resource_owner_params)
  384. 18 create_params[oauth_grants_type_column] = "hybrid"
  385. 18 create_params[oauth_grants_expires_in_column] = Sequel.date_add(Sequel::CURRENT_TIMESTAMP, seconds: oauth_access_token_expires_in)
  386. 26 authorization_code = create_oauth_grant(create_params)
  387. 26 access_token = if oauth_jwt_access_tokens
  388. 26 _generate_jwt_access_token(create_params)
  389. else
  390. oauth_grant = valid_oauth_grant_ds.where(oauth_grants_code_column => authorization_code).first
  391. _generate_access_token(oauth_grant)
  392. end
  393. 26 json_access_token_payload(oauth_grants_token_column => access_token).merge("code" => authorization_code)
  394. end
  395. 13 def create_token(*)
  396. 325 oauth_grant = super
  397. 286 generate_id_token(oauth_grant)
  398. 286 oauth_grant
  399. end
  400. 13 def generate_id_token(oauth_grant, include_claims = false)
  401. 611 oauth_scopes = oauth_grant[oauth_grants_scopes_column].split(oauth_scope_separator)
  402. 611 return unless oauth_scopes.include?("openid")
  403. 611 signing_algorithm = oauth_application[oauth_applications_id_token_signed_response_alg_column] ||
  404. oauth_jwt_keys.keys.first
  405. 611 id_claims = id_token_claims(oauth_grant, signing_algorithm)
  406. 611 account = db[accounts_table].where(account_id_column => oauth_grant[oauth_grants_account_id_column]).first
  407. # this should never happen!
  408. # a newly minted oauth token from a grant should have been assigned to an account
  409. # who just authorized its generation.
  410. 611 return unless account
  411. 611 if (claims = oauth_grant[oauth_grants_claims_column])
  412. 26 claims = JSON.parse(claims)
  413. 26 if (id_token_essential_claims = claims["id_token"])
  414. 18 oauth_scopes |= id_token_essential_claims.to_a
  415. 26 include_claims = true
  416. end
  417. end
  418. # OpenID Connect Core 1.0's 5.4 Requesting Claims using Scope Values:
  419. # If standard claims (profile, email, etc) are requested as scope values in the Authorization Request,
  420. # include in the response.
  421. 611 include_claims ||= (OIDC_SCOPES_MAP.keys & oauth_scopes).any?
  422. # However, when no Access Token is issued (which is the case for the response_type value id_token),
  423. # the resulting Claims are returned in the ID Token.
  424. 611 fill_with_account_claims(id_claims, account, oauth_scopes, param_or_nil("claims_locales")) if include_claims
  425. 235 params = {
  426. 376 jwks: oauth_application_jwks(oauth_application),
  427. signing_algorithm: signing_algorithm,
  428. encryption_algorithm: oauth_application[oauth_applications_id_token_encrypted_response_alg_column],
  429. encryption_method: oauth_application[oauth_applications_id_token_encrypted_response_enc_column],
  430. # Not officially part of the spec, but some providers follow this convention.
  431. # This is useful for distinguishing between ID Tokens and JWT Access Tokens.
  432. headers: { typ: "id_token+jwt" }
  433. }.compact
  434. 423 oauth_grant[:id_token] = jwt_encode(id_claims, **params)
  435. end
  436. 13 def id_token_claims(oauth_grant, signing_algorithm)
  437. 611 claims = jwt_claims(oauth_grant)
  438. 611 claims[:nonce] = oauth_grant[oauth_grants_nonce_column] if oauth_grant[oauth_grants_nonce_column]
  439. 611 claims[:acr] = oauth_grant[oauth_grants_acr_column] if oauth_grant[oauth_grants_acr_column]
  440. # Time when the End-User authentication occurred.
  441. 423 claims[:auth_time] = get_oidc_account_last_login_at(oauth_grant[oauth_grants_account_id_column]).to_i
  442. # Access Token hash value.
  443. 611 if (access_token = oauth_grant[oauth_grants_token_column])
  444. 216 claims[:at_hash] = id_token_hash(access_token, signing_algorithm)
  445. end
  446. # code hash value.
  447. 611 if (code = oauth_grant[oauth_grants_code_column])
  448. 99 claims[:c_hash] = id_token_hash(code, signing_algorithm)
  449. end
  450. 611 claims
  451. end
  452. # aka fill_with_standard_claims
  453. 13 def fill_with_account_claims(claims, account, scopes, claims_locales)
  454. 351 additional_claims_info = {}
  455. 351 scopes_by_claim = scopes.each_with_object({}) do |scope, by_oidc|
  456. 442 next if scope == "openid"
  457. 208 if scope.is_a?(Array)
  458. # essential claims
  459. 65 param, additional_info = scope
  460. 65 param = param.to_sym
  461. 65 oidc, = OIDC_SCOPES_MAP.find do |_, oidc_scopes|
  462. 143 oidc_scopes.include?(param)
  463. end || param.to_s
  464. 65 param = nil if oidc == param.to_s
  465. 45 additional_claims_info[param] = additional_info
  466. else
  467. 143 oidc, param = scope.split(".", 2)
  468. 143 param = param.to_sym if param
  469. end
  470. 208 by_oidc[oidc] ||= []
  471. 208 by_oidc[oidc] << param.to_sym if param
  472. end
  473. 559 oidc_scopes, additional_scopes = scopes_by_claim.keys.partition { |key| OIDC_SCOPES_MAP.key?(key) }
  474. 351 claims_locales = claims_locales.split(" ").map(&:to_sym) if claims_locales
  475. 351 unless oidc_scopes.empty?
  476. 117 if respond_to?(:get_oidc_param)
  477. 117 get_oidc_param = proxy_get_param(:get_oidc_param, claims, claims_locales, additional_claims_info)
  478. 117 oidc_scopes.each do |scope|
  479. 117 scope_claims = claims
  480. 117 params = scopes_by_claim[scope]
  481. 117 params = params.empty? ? OIDC_SCOPES_MAP[scope] : (OIDC_SCOPES_MAP[scope] & params)
  482. 117 scope_claims = (claims["address"] = {}) if scope == "address"
  483. 117 params.each do |param|
  484. 286 get_oidc_param[account, param, scope_claims]
  485. end
  486. end
  487. else
  488. warn "`get_oidc_param(account, claim)` must be implemented to use oidc scopes."
  489. end
  490. end
  491. 351 return if additional_scopes.empty?
  492. 91 if respond_to?(:get_additional_param)
  493. 91 get_additional_param = proxy_get_param(:get_additional_param, claims, claims_locales, additional_claims_info)
  494. 91 additional_scopes.each do |scope|
  495. 91 get_additional_param[account, scope.to_sym]
  496. end
  497. else
  498. warn "`get_additional_param(account, claim)` must be implemented to use oidc scopes."
  499. end
  500. end
  501. 13 def proxy_get_param(get_param_func, claims, claims_locales, additional_claims_info)
  502. 208 meth = method(get_param_func)
  503. 208 if meth.arity == 2
  504. 182 lambda do |account, param, cl = claims|
  505. 351 additional_info = additional_claims_info[param] || EMPTY_HASH
  506. 351 value = additional_info["value"] || meth[account, param]
  507. 351 value = nil if additional_info["values"] && additional_info["values"].include?(value)
  508. 351 cl[param] = value unless value.nil?
  509. end
  510. 26 elsif claims_locales.nil?
  511. lambda do |account, param, cl = claims|
  512. additional_info = additional_claims_info[param] || EMPTY_HASH
  513. value = additional_info["value"] || meth[account, param, nil]
  514. value = nil if additional_info["values"] && additional_info["values"].include?(value)
  515. cl[param] = value unless value.nil?
  516. end
  517. else
  518. 26 lambda do |account, param, cl = claims|
  519. 26 claims_values = claims_locales.map do |locale|
  520. 52 additional_info = additional_claims_info[param] || EMPTY_HASH
  521. 52 value = additional_info["value"] || meth[account, param, locale]
  522. 52 value = nil if additional_info["values"] && additional_info["values"].include?(value)
  523. 52 value
  524. end.compact
  525. 26 if claims_values.uniq.size == 1
  526. cl[param] = claims_values.first
  527. else
  528. 26 claims_locales.zip(claims_values).each do |locale, value|
  529. 52 cl["#{param}##{locale}"] = value if value
  530. end
  531. end
  532. end
  533. end
  534. end
  535. 13 def json_access_token_payload(oauth_grant)
  536. 338 payload = super
  537. 338 payload["id_token"] = oauth_grant[:id_token] if oauth_grant[:id_token]
  538. 338 payload
  539. end
  540. # Authorize
  541. 13 def check_valid_response_type?
  542. 990 case param_or_nil("response_type")
  543. when "none", "id_token", "code id_token", # multiple
  544. "code token", "id_token token", "code id_token token"
  545. 832 true
  546. else
  547. 594 super
  548. end
  549. end
  550. 13 def supported_response_mode?(response_mode, *)
  551. 585 return super unless response_mode == "none"
  552. 13 param("response_type") == "none"
  553. end
  554. 13 def do_authorize(response_params = {}, response_mode = param_or_nil("response_mode"))
  555. 585 response_type = param("response_type")
  556. 405 case response_type
  557. when "id_token"
  558. 169 grant_params = oidc_grant_params
  559. 169 generate_id_token(grant_params, true)
  560. 169 response_params.replace("id_token" => grant_params[:id_token])
  561. when "code token"
  562. 13 response_params.replace(create_oauth_grant_with_token)
  563. when "code id_token"
  564. 130 params = _do_authorize_code
  565. 130 oauth_grant = valid_oauth_grant_ds.where(oauth_grants_code_column => params["code"]).first
  566. 130 generate_id_token(oauth_grant)
  567. 130 response_params.replace(
  568. "id_token" => oauth_grant[:id_token],
  569. "code" => params["code"]
  570. )
  571. when "id_token token"
  572. 13 grant_params = oidc_grant_params.merge(oauth_grants_type_column => "hybrid")
  573. 13 oauth_grant = _do_authorize_token(grant_params)
  574. 13 generate_id_token(oauth_grant)
  575. 13 response_params.replace(json_access_token_payload(oauth_grant))
  576. when "code id_token token"
  577. 13 params = create_oauth_grant_with_token
  578. 13 oauth_grant = valid_oauth_grant_ds.where(oauth_grants_code_column => params["code"]).first
  579. 9 oauth_grant[oauth_grants_token_column] = params["access_token"]
  580. 13 generate_id_token(oauth_grant)
  581. 13 response_params.replace(params.merge("id_token" => oauth_grant[:id_token]))
  582. when "none"
  583. 13 response_mode ||= "none"
  584. end
  585. 585 response_mode ||= "fragment" unless response_params.empty?
  586. 585 super(response_params, response_mode)
  587. end
  588. 13 def oidc_grant_params
  589. 559 grant_params = {
  590. **resource_owner_params,
  591. oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column],
  592. oauth_grants_scopes_column => scopes.join(oauth_scope_separator),
  593. oauth_grants_redirect_uri_column => param_or_nil("redirect_uri")
  594. }
  595. 559 if (nonce = param_or_nil("nonce"))
  596. 297 grant_params[oauth_grants_nonce_column] = nonce
  597. end
  598. 559 grant_params[oauth_grants_acr_column] = @acr if @acr
  599. 559 if (claims_locales = param_or_nil("claims_locales"))
  600. 18 grant_params[oauth_grants_claims_locales_column] = claims_locales
  601. end
  602. 559 if (claims = param_or_nil("claims"))
  603. 9 grant_params[oauth_grants_claims_column] = claims
  604. end
  605. 559 grant_params
  606. end
  607. 13 def generate_token(grant_params = {}, should_generate_refresh_token = true)
  608. 260 scopes = grant_params[oauth_grants_scopes_column].split(oauth_scope_separator)
  609. 260 super(grant_params, scopes.include?("offline_access") && should_generate_refresh_token)
  610. end
  611. 13 def authorize_response(params, mode)
  612. 585 redirect_url = URI.parse(redirect_uri)
  613. 585 redirect(redirect_url.to_s) if mode == "none"
  614. 572 super
  615. end
  616. # Webfinger
  617. 13 def json_webfinger_payload
  618. 13 JSON.dump({
  619. subject: param("resource"),
  620. links: [{
  621. rel: "http://openid.net/specs/connect/1.0/issuer",
  622. href: authorization_server_url
  623. }]
  624. })
  625. end
  626. # Metadata
  627. 13 def openid_configuration_body(path = nil)
  628. 91 metadata = oauth_server_metadata_body(path).select do |k, _|
  629. 1352 VALID_METADATA_KEYS.include?(k)
  630. end
  631. 91 scope_claims = oauth_application_scopes.each_with_object([]) do |scope, claims|
  632. 143 oidc, param = scope.split(".", 2)
  633. 143 if param
  634. 13 claims << param
  635. else
  636. 130 oidc_claims = OIDC_SCOPES_MAP[oidc]
  637. 130 claims.concat(oidc_claims) if oidc_claims
  638. end
  639. end
  640. 91 scope_claims.unshift("auth_time")
  641. 84 metadata.merge(
  642. userinfo_endpoint: userinfo_url,
  643. subject_types_supported: %w[public pairwise],
  644. acr_values_supported: oauth_acr_values_supported,
  645. claims_parameter_supported: true,
  646. id_token_signing_alg_values_supported: oauth_jwt_jws_algorithms_supported,
  647. id_token_encryption_alg_values_supported: oauth_jwt_jwe_algorithms_supported,
  648. id_token_encryption_enc_values_supported: oauth_jwt_jwe_encryption_methods_supported,
  649. userinfo_signing_alg_values_supported: oauth_jwt_jws_algorithms_supported,
  650. userinfo_encryption_alg_values_supported: oauth_jwt_jwe_algorithms_supported,
  651. userinfo_encryption_enc_values_supported: oauth_jwt_jwe_encryption_methods_supported,
  652. request_object_signing_alg_values_supported: oauth_jwt_jws_algorithms_supported,
  653. request_object_encryption_alg_values_supported: oauth_jwt_jwe_algorithms_supported,
  654. request_object_encryption_enc_values_supported: oauth_jwt_jwe_encryption_methods_supported,
  655. # These Claim Types are described in Section 5.6 of OpenID Connect Core 1.0 [OpenID.Core].
  656. # Values defined by this specification are normal, aggregated, and distributed.
  657. # If omitted, the implementation supports only normal Claims.
  658. claim_types_supported: %w[normal],
  659. claims_supported: %w[sub iss iat exp aud] | scope_claims
  660. 7 ).reject do |key, val|
  661. # Filter null values in optional items
  662. 2717 (!REQUIRED_METADATA_KEYS.include?(key.to_sym) && val.nil?) ||
  663. # Claims with zero elements MUST be omitted from the response
  664. 2353 (val.respond_to?(:empty?) && val.empty?)
  665. end
  666. end
  667. 13 def allow_cors(request)
  668. 117 return unless request.request_method == "OPTIONS"
  669. 9 response["Access-Control-Allow-Origin"] = "*"
  670. 9 response["Access-Control-Allow-Methods"] = "GET, OPTIONS"
  671. 9 response["Access-Control-Max-Age"] = "3600"
  672. 13 response.status = 200
  673. 13 return_response
  674. end
  675. 13 def jwt_response_success(jwt, cache = false)
  676. 26 response.status = 200
  677. 26 response["Content-Type"] ||= "application/jwt"
  678. 26 if cache
  679. # defaulting to 1-day for everyone, for now at least
  680. max_age = 60 * 60 * 24
  681. response["Cache-Control"] = "private, max-age=#{max_age}"
  682. else
  683. 18 response["Cache-Control"] = "no-store"
  684. 18 response["Pragma"] = "no-cache"
  685. end
  686. 26 return_response(jwt)
  687. end
  688. 13 def id_token_hash(hash, algo)
  689. 455 digest = case algo
  690. 455 when /256/ then Digest::SHA256
  691. when /384/ then Digest::SHA384
  692. when /512/ then Digest::SHA512
  693. end
  694. 455 return unless digest
  695. 455 hash = digest.digest(hash)
  696. 455 hash = hash[0...hash.size / 2]
  697. 455 Base64.urlsafe_encode64(hash).tr("=", "")
  698. end
  699. end
  700. end

lib/rodauth/features/oidc_backchannel_logout.rb

98.15% lines covered

54 relevant lines. 53 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oidc_backchannel_logout, :OidBackchannelLogout) do
  5. 13 depends :logout, :oidc_logout_base
  6. 13 auth_value_method :oauth_logout_token_expires_in, 60 # 1 minute
  7. 13 auth_value_method :backchannel_logout_session_supported, true
  8. 13 auth_value_method :oauth_applications_backchannel_logout_uri_column, :backchannel_logout_uri
  9. 13 auth_value_method :oauth_applications_backchannel_logout_session_required_column, :backchannel_logout_session_required
  10. 13 auth_methods(
  11. :perform_logout_requests
  12. )
  13. 13 def logout
  14. 78 visited_sites = session[visited_sites_key]
  15. 78 return super unless visited_sites
  16. 78 oauth_applications = db[oauth_applications_table].where(oauth_applications_client_id_column => visited_sites.map(&:first))
  17. .as_hash(oauth_applications_id_column)
  18. 78 logout_params = oauth_applications.flat_map do |_id, oauth_application|
  19. 78 logout_url = oauth_application[oauth_applications_backchannel_logout_uri_column]
  20. 78 next unless logout_url
  21. 78 client_id = oauth_application[oauth_applications_client_id_column]
  22. 156 sids = visited_sites.select { |cid, _| cid == client_id }.map(&:last)
  23. 78 sids.map do |sid|
  24. 78 logout_token = generate_logout_token(oauth_application, sid)
  25. 78 [logout_url, logout_token]
  26. end
  27. end.compact
  28. 78 perform_logout_requests(logout_params) unless logout_params.empty?
  29. # now we can clear the session
  30. 78 super
  31. end
  32. 13 private
  33. 13 def generate_logout_token(oauth_application, sid)
  34. 78 issued_at = Time.now.to_i
  35. 30 logout_claims = {
  36. 48 iss: oauth_jwt_issuer, # issuer
  37. iat: issued_at, # issued at
  38. exp: issued_at + oauth_logout_token_expires_in,
  39. aud: oauth_application[oauth_applications_client_id_column],
  40. events: {
  41. "http://schemas.openid.net/event/backchannel-logout": {}
  42. }
  43. }
  44. 78 logout_claims[:sid] = sid if sid
  45. 78 signing_algorithm = oauth_application[oauth_applications_id_token_signed_response_alg_column] ||
  46. oauth_jwt_keys.keys.first
  47. 30 params = {
  48. 48 jwks: oauth_application_jwks(oauth_application),
  49. headers: { typ: "logout+jwt" },
  50. signing_algorithm: signing_algorithm,
  51. encryption_algorithm: oauth_application[oauth_applications_id_token_encrypted_response_alg_column],
  52. encryption_method: oauth_application[oauth_applications_id_token_encrypted_response_enc_column]
  53. }.compact
  54. 78 jwt_encode(logout_claims, **params)
  55. end
  56. 13 def perform_logout_requests(logout_params)
  57. # performs logout requests sequentially
  58. 78 logout_params.each do |logout_url, logout_token|
  59. 78 http_request(logout_url, { "logout_token" => logout_token })
  60. rescue StandardError
  61. warn "failed to perform backchannel logout on #{logout_url}"
  62. end
  63. end
  64. 13 def id_token_claims(oauth_grant, signing_algorithm)
  65. 78 claims = super
  66. 78 return claims unless oauth_application[oauth_applications_backchannel_logout_uri_column]
  67. 78 session_id_in_claims(oauth_grant, claims)
  68. 78 claims
  69. end
  70. 13 def should_set_oauth_application_in_visited_sites?
  71. 39 true
  72. end
  73. 13 def should_set_sid_in_visited_sites?(oauth_application)
  74. 117 super || requires_backchannel_logout_session?(oauth_application)
  75. end
  76. 13 def requires_backchannel_logout_session?(oauth_application)
  77. 36 (
  78. 117 oauth_application &&
  79. oauth_application[oauth_applications_backchannel_logout_session_required_column]
  80. 9 ) || backchannel_logout_session_supported
  81. end
  82. 13 def oauth_server_metadata_body(*)
  83. 13 super.tap do |data|
  84. 9 data[:backchannel_logout_supported] = true
  85. 9 data[:backchannel_logout_session_supported] = backchannel_logout_session_supported
  86. end
  87. end
  88. end
  89. end

lib/rodauth/features/oidc_dynamic_client_registration.rb

90.51% lines covered

137 relevant lines. 124 lines covered and 13 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oidc_dynamic_client_registration, :OidcDynamicClientRegistration) do
  5. 13 depends :oauth_dynamic_client_registration, :oidc
  6. 13 auth_value_method :oauth_applications_application_type_column, :application_type
  7. 13 private
  8. 13 def validate_client_registration_params(*)
  9. 663 super
  10. 624 if (value = @oauth_application_params[oauth_applications_application_type_column])
  11. 63 case value
  12. when "native"
  13. 52 request.params["redirect_uris"].each do |uri|
  14. 52 uri = URI(uri)
  15. # Native Clients MUST only register redirect_uris using custom URI schemes or
  16. # URLs using the http: scheme with localhost as the hostname.
  17. 36 case uri.scheme
  18. when "http"
  19. 26 register_throw_json_response_error("invalid_redirect_uri", register_invalid_uri_message(uri)) unless uri.host == "localhost"
  20. when "https"
  21. 13 register_throw_json_response_error("invalid_redirect_uri", register_invalid_uri_message(uri))
  22. end
  23. end
  24. when "web"
  25. # Web Clients using the OAuth Implicit Grant Type MUST only register URLs using the https scheme as redirect_uris;
  26. # they MUST NOT use localhost as the hostname.
  27. 39 if request.params["grant_types"].include?("implicit")
  28. 26 request.params["redirect_uris"].each do |uri|
  29. 26 uri = URI(uri)
  30. 26 unless uri.scheme == "https" && uri.host != "localhost"
  31. 13 register_throw_json_response_error("invalid_redirect_uri", register_invalid_uri_message(uri))
  32. end
  33. end
  34. end
  35. else
  36. register_throw_json_response_error("invalid_client_metadata", register_invalid_application_type_message(type))
  37. end
  38. end
  39. 585 if (value = @oauth_application_params[oauth_applications_sector_identifier_uri_column]) && !check_valid_uri?(value)
  40. register_throw_json_response_error("invalid_redirect_uri", register_invalid_uri_message(value))
  41. end
  42. 585 if (value = @oauth_application_params[oauth_applications_initiate_login_uri_column])
  43. 26 uri = URI(value)
  44. 26 unless uri.scheme == "https" || uri.host == "localhost"
  45. 13 register_throw_json_response_error("invalid_redirect_uri", register_invalid_uri_message(uri))
  46. end
  47. end
  48. 572 if features.include?(:oauth_jwt_secured_authorization_request)
  49. 117 if (value = @oauth_application_params[oauth_applications_request_uris_column])
  50. 26 if value.is_a?(Array)
  51. 9 @oauth_application_params[oauth_applications_request_uris_column] = value.each do |req_uri|
  52. 13 unless check_valid_uri?(req_uri)
  53. register_throw_json_response_error("invalid_redirect_uri", register_invalid_uri_message(req_uri))
  54. end
  55. end.join(" ")
  56. else
  57. 13 register_throw_json_response_error("invalid_redirect_uri", register_invalid_uri_message(value))
  58. end
  59. 91 elsif oauth_require_request_uri_registration
  60. 13 register_throw_json_response_error("invalid_client_metadata", register_required_param_message("request_uris"))
  61. end
  62. end
  63. 546 if (value = @oauth_application_params[oauth_applications_subject_type_column])
  64. 91 unless %w[pairwise public].include?(value)
  65. 13 register_throw_json_response_error("invalid_client_metadata", register_invalid_client_metadata_message("subject_type", value))
  66. end
  67. 78 if value == "pairwise"
  68. 65 sector_identifier_uri = @oauth_application_params[oauth_applications_sector_identifier_uri_column]
  69. 65 if sector_identifier_uri
  70. 26 response = http_request(sector_identifier_uri)
  71. 26 unless response.code.to_i == 200
  72. register_throw_json_response_error("invalid_client_metadata",
  73. register_invalid_param_message("sector_identifier_uri"))
  74. end
  75. 26 uris = JSON.parse(response.body)
  76. 26 if uris != @oauth_application_params[oauth_applications_redirect_uri_column].split(" ")
  77. 13 register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message("sector_identifier_uri"))
  78. end
  79. end
  80. end
  81. end
  82. 520 if (value = @oauth_application_params[oauth_applications_id_token_signed_response_alg_column])
  83. 52 if value == "none"
  84. # The value none MUST NOT be used as the ID Token alg value unless the Client uses only Response Types
  85. # that return no ID Token from the Authorization Endpoint
  86. response_types = @oauth_application_params[oauth_applications_response_types_column]
  87. if response_types && response_types.include?("id_token")
  88. register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message("id_token_signed_response_alg"))
  89. end
  90. 52 elsif !oauth_jwt_jws_algorithms_supported.include?(value)
  91. 13 register_throw_json_response_error("invalid_client_metadata",
  92. register_invalid_client_metadata_message("id_token_signed_response_alg", value))
  93. end
  94. end
  95. 507 if features.include?(:oauth_jwt_secured_authorization_request)
  96. 91 if defined?(oauth_applications_request_object_signing_alg_column) &&
  97. 91 (value = @oauth_application_params[oauth_applications_request_object_signing_alg_column]) &&
  98. 13 !oauth_jwt_jws_algorithms_supported.include?(value) && !(value == "none" && oauth_request_object_signing_alg_allow_none)
  99. 13 register_throw_json_response_error("invalid_client_metadata",
  100. register_invalid_client_metadata_message("request_object_signing_alg", value))
  101. end
  102. 78 if defined?(oauth_applications_request_object_encryption_alg_column) &&
  103. 78 (value = @oauth_application_params[oauth_applications_request_object_encryption_alg_column]) &&
  104. !oauth_jwt_jwe_algorithms_supported.include?(value)
  105. 13 register_throw_json_response_error("invalid_client_metadata",
  106. register_invalid_client_metadata_message("request_object_encryption_alg", value))
  107. end
  108. 65 if defined?(oauth_applications_request_object_encryption_enc_column) &&
  109. 65 (value = @oauth_application_params[oauth_applications_request_object_encryption_enc_column]) &&
  110. !oauth_jwt_jwe_encryption_methods_supported.include?(value)
  111. 13 register_throw_json_response_error("invalid_client_metadata",
  112. register_invalid_client_metadata_message("request_object_encryption_enc", value))
  113. end
  114. end
  115. 468 if features.include?(:oidc_rp_initiated_logout) && (defined?(oauth_applications_post_logout_redirect_uris_column) &&
  116. 26 (value = @oauth_application_params[oauth_applications_post_logout_redirect_uris_column]))
  117. 26 if value.is_a?(Array)
  118. 9 @oauth_application_params[oauth_applications_post_logout_redirect_uris_column] = value.each do |redirect_uri|
  119. 13 unless check_valid_uri?(redirect_uri)
  120. register_throw_json_response_error("invalid_client_metadata", register_invalid_uri_message(redirect_uri))
  121. end
  122. end.join(" ")
  123. else
  124. 13 register_throw_json_response_error("invalid_client_metadata", register_invalid_uri_message(value))
  125. end
  126. end
  127. 455 if features.include?(:oidc_frontchannel_logout)
  128. 39 if (value = @oauth_application_params[oauth_applications_frontchannel_logout_uri_column]) && !check_valid_no_fragment_uri?(value)
  129. 26 register_throw_json_response_error("invalid_client_metadata",
  130. register_invalid_uri_message(value))
  131. end
  132. 13 if (value = @oauth_application_params[oauth_applications_frontchannel_logout_session_required_column])
  133. 9 @oauth_application_params[oauth_applications_frontchannel_logout_session_required_column] =
  134. convert_to_boolean("frontchannel_logout_session_required", value)
  135. end
  136. end
  137. 429 if features.include?(:oidc_backchannel_logout)
  138. 39 if (value = @oauth_application_params[oauth_applications_backchannel_logout_uri_column]) && !check_valid_no_fragment_uri?(value)
  139. 26 register_throw_json_response_error("invalid_client_metadata",
  140. register_invalid_uri_message(value))
  141. end
  142. 13 if @oauth_application_params.key?(oauth_applications_backchannel_logout_session_required_column)
  143. 13 value = @oauth_application_params[oauth_applications_backchannel_logout_session_required_column]
  144. 9 @oauth_application_params[oauth_applications_backchannel_logout_session_required_column] =
  145. convert_to_boolean("backchannel_logout_session_required", value)
  146. end
  147. end
  148. 403 if (value = @oauth_application_params[oauth_applications_id_token_encrypted_response_alg_column]) &&
  149. !oauth_jwt_jwe_algorithms_supported.include?(value)
  150. 13 register_throw_json_response_error("invalid_client_metadata",
  151. register_invalid_client_metadata_message("id_token_encrypted_response_alg", value))
  152. end
  153. 390 if (value = @oauth_application_params[oauth_applications_id_token_encrypted_response_enc_column]) &&
  154. !oauth_jwt_jwe_encryption_methods_supported.include?(value)
  155. 13 register_throw_json_response_error("invalid_client_metadata",
  156. register_invalid_client_metadata_message("id_token_encrypted_response_enc", value))
  157. end
  158. 377 if (value = @oauth_application_params[oauth_applications_userinfo_signed_response_alg_column]) &&
  159. !oauth_jwt_jws_algorithms_supported.include?(value)
  160. 13 register_throw_json_response_error("invalid_client_metadata",
  161. register_invalid_client_metadata_message("userinfo_signed_response_alg", value))
  162. end
  163. 364 if (value = @oauth_application_params[oauth_applications_userinfo_encrypted_response_alg_column]) &&
  164. !oauth_jwt_jwe_algorithms_supported.include?(value)
  165. 13 register_throw_json_response_error("invalid_client_metadata",
  166. register_invalid_client_metadata_message("userinfo_encrypted_response_alg", value))
  167. end
  168. 351 if (value = @oauth_application_params[oauth_applications_userinfo_encrypted_response_enc_column]) &&
  169. !oauth_jwt_jwe_encryption_methods_supported.include?(value)
  170. 13 register_throw_json_response_error("invalid_client_metadata",
  171. register_invalid_client_metadata_message("userinfo_encrypted_response_enc", value))
  172. end
  173. 338 if features.include?(:oauth_jwt_secured_authorization_response_mode)
  174. 26 if defined?(oauth_applications_authorization_signed_response_alg_column) &&
  175. 26 (value = @oauth_application_params[oauth_applications_authorization_signed_response_alg_column]) &&
  176. 16 (!oauth_jwt_jws_algorithms_supported.include?(value) || value == "none")
  177. register_throw_json_response_error("invalid_client_metadata",
  178. register_invalid_client_metadata_message("authorization_signed_response_alg", value))
  179. end
  180. 26 if defined?(oauth_applications_authorization_encrypted_response_alg_column) &&
  181. 26 (value = @oauth_application_params[oauth_applications_authorization_encrypted_response_alg_column]) &&
  182. !oauth_jwt_jwe_algorithms_supported.include?(value)
  183. register_throw_json_response_error("invalid_client_metadata",
  184. register_invalid_client_metadata_message("authorization_encrypted_response_alg", value))
  185. end
  186. 26 if defined?(oauth_applications_authorization_encrypted_response_enc_column)
  187. 26 if (value = @oauth_application_params[oauth_applications_authorization_encrypted_response_enc_column])
  188. 13 unless @oauth_application_params[oauth_applications_authorization_encrypted_response_alg_column]
  189. # When authorization_encrypted_response_enc is included, authorization_encrypted_response_alg MUST also be provided.
  190. 13 register_throw_json_response_error("invalid_client_metadata",
  191. register_invalid_client_metadata_message("authorization_encrypted_response_alg", value))
  192. end
  193. unless oauth_jwt_jwe_encryption_methods_supported.include?(value)
  194. register_throw_json_response_error("invalid_client_metadata",
  195. register_invalid_client_metadata_message("authorization_encrypted_response_enc", value))
  196. end
  197. 13 elsif @oauth_application_params[oauth_applications_authorization_encrypted_response_alg_column]
  198. # If authorization_encrypted_response_alg is specified, the default for this value is A128CBC-HS256.
  199. 9 @oauth_application_params[oauth_applications_authorization_encrypted_response_enc_column] = "A128CBC-HS256"
  200. end
  201. end
  202. end
  203. 325 @oauth_application_params
  204. end
  205. 13 def validate_client_registration_response_type(response_type, grant_types)
  206. 459 case response_type
  207. when "id_token"
  208. 52 unless grant_types.include?("implicit")
  209. 13 register_throw_json_response_error("invalid_client_metadata",
  210. register_invalid_response_type_for_grant_type_message(response_type, "implicit"))
  211. end
  212. else
  213. 611 super
  214. end
  215. end
  216. 13 def do_register(return_params = request.params.dup)
  217. # set defaults
  218. 299 create_params = @oauth_application_params
  219. 299 create_params[oauth_applications_application_type_column] ||= begin
  220. 171 return_params["application_type"] = "web"
  221. 247 "web"
  222. end
  223. 299 create_params[oauth_applications_id_token_signed_response_alg_column] ||= return_params["id_token_signed_response_alg"] =
  224. oauth_jwt_keys.keys.first
  225. 299 if create_params.key?(oauth_applications_id_token_encrypted_response_alg_column)
  226. 13 create_params[oauth_applications_id_token_encrypted_response_enc_column] ||= return_params["id_token_encrypted_response_enc"] =
  227. "A128CBC-HS256"
  228. end
  229. 299 if create_params.key?(oauth_applications_userinfo_encrypted_response_alg_column)
  230. 13 create_params[oauth_applications_userinfo_encrypted_response_enc_column] ||= return_params["userinfo_encrypted_response_enc"] =
  231. "A128CBC-HS256"
  232. end
  233. 299 if defined?(oauth_applications_request_object_encryption_alg_column) &&
  234. create_params.key?(oauth_applications_request_object_encryption_alg_column)
  235. 13 create_params[oauth_applications_request_object_encryption_enc_column] ||= return_params["request_object_encryption_enc"] =
  236. "A128CBC-HS256"
  237. end
  238. 299 super(return_params)
  239. end
  240. 13 def register_invalid_application_type_message(application_type)
  241. "The application type '#{application_type}' is not allowed."
  242. end
  243. 13 def initialize_register_params(create_params, return_params)
  244. 299 super
  245. 299 registration_access_token = oauth_unique_id_generator
  246. 207 create_params[oauth_applications_registration_access_token_column] = secret_hash(registration_access_token)
  247. 207 return_params["registration_access_token"] = registration_access_token
  248. 207 return_params["registration_client_uri"] = "#{base_url}/#{registration_client_uri_route}/#{return_params['client_id']}"
  249. end
  250. end
  251. end

lib/rodauth/features/oidc_frontchannel_logout.rb

100.0% lines covered

68 relevant lines. 68 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. skipped # :nocov:
  4. skipped raise LoadError, "the `:oidc_frontchannel_logout` requires rodauth 2.32.0 or higher" if Rodauth::VERSION < "2.32.0"
  5. skipped
  6. skipped # :nocov:
  7. 13 module Rodauth
  8. 13 Feature.define(:oidc_frontchannel_logout, :OidFrontchannelLogout) do
  9. 13 depends :logout, :oidc_logout_base
  10. 13 view "frontchannel_logout", "Logout", "frontchannel_logout"
  11. 13 translatable_method :oauth_frontchannel_logout_redirecting_lead, "You are being redirected..."
  12. 13 translatable_method :oauth_frontchannel_logout_redirecting_label, "please click %<link>s if your browser does not " \
  13. "redirect you in a few seconds."
  14. 13 translatable_method :oauth_frontchannel_logout_redirecting_link_label, "here"
  15. 13 auth_value_method :frontchannel_logout_session_supported, true
  16. 13 auth_value_method :frontchannel_logout_redirect_timeout, 5
  17. 13 auth_value_method :oauth_applications_frontchannel_logout_uri_column, :frontchannel_logout_uri
  18. 13 auth_value_method :oauth_applications_frontchannel_logout_session_required_column, :frontchannel_logout_session_required
  19. 13 attr_reader :frontchannel_logout_urls
  20. 13 attr_reader :frontchannel_logout_redirect
  21. 13 def logout
  22. 91 @visited_sites = session[visited_sites_key]
  23. 91 super
  24. end
  25. 13 def _logout_response
  26. 78 visited_sites = @visited_sites
  27. 78 return super unless visited_sites
  28. 78 logout_urls = db[oauth_applications_table]
  29. .where(oauth_applications_client_id_column => visited_sites.map(&:first))
  30. .as_hash(oauth_applications_client_id_column, oauth_applications_frontchannel_logout_uri_column)
  31. 78 return super if logout_urls.empty?
  32. 78 generate_frontchannel_logout_urls(visited_sites, logout_urls)
  33. 78 @frontchannel_logout_redirect = logout_redirect
  34. 78 set_notice_flash logout_notice_flash
  35. 78 return_response frontchannel_logout_view
  36. end
  37. # overrides rp-initiate logout response
  38. 13 def _oidc_logout_response
  39. 13 visited_sites = @visited_sites
  40. 13 return super unless visited_sites
  41. 13 logout_urls = db[oauth_applications_table]
  42. .where(oauth_applications_client_id_column => visited_sites.map(&:first))
  43. .as_hash(oauth_applications_client_id_column, oauth_applications_frontchannel_logout_uri_column)
  44. 13 return super if logout_urls.empty?
  45. 13 generate_frontchannel_logout_urls(visited_sites, logout_urls)
  46. 13 @frontchannel_logout_redirect = oidc_logout_redirect
  47. 13 set_notice_flash logout_notice_flash
  48. 13 return_response frontchannel_logout_view
  49. end
  50. 13 private
  51. 13 def generate_frontchannel_logout_urls(visited_sites, logout_urls)
  52. 91 @frontchannel_logout_urls = logout_urls.flat_map do |client_id, logout_url|
  53. 91 next unless logout_url
  54. 182 sids = visited_sites.select { |cid, _| cid == client_id }.map(&:last)
  55. 91 sids.map do |sid|
  56. 91 logout_url = URI(logout_url)
  57. 91 if sid
  58. 65 query = logout_url.query
  59. 65 query = if query
  60. 26 URI.decode_www_form(query)
  61. else
  62. 39 []
  63. end
  64. 65 query << ["iss", oauth_jwt_issuer]
  65. 65 query << ["sid", sid]
  66. 65 logout_url.query = URI.encode_www_form(query)
  67. end
  68. 91 logout_url
  69. end
  70. end.compact
  71. end
  72. 13 def id_token_claims(oauth_grant, signing_algorithm)
  73. 91 claims = super
  74. 91 return claims unless oauth_application[oauth_applications_frontchannel_logout_uri_column]
  75. 91 session_id_in_claims(oauth_grant, claims)
  76. 91 claims
  77. end
  78. 13 def should_set_oauth_application_in_visited_sites?
  79. 52 true
  80. end
  81. 13 def should_set_sid_in_visited_sites?(oauth_application)
  82. 143 super || requires_frontchannel_logout_session?(oauth_application)
  83. end
  84. 13 def requires_frontchannel_logout_session?(oauth_application)
  85. 44 (
  86. 143 oauth_application &&
  87. oauth_application[oauth_applications_frontchannel_logout_session_required_column]
  88. 11 ) || frontchannel_logout_session_supported
  89. end
  90. 13 def oauth_server_metadata_body(*)
  91. 13 super.tap do |data|
  92. 9 data[:frontchannel_logout_supported] = true
  93. 9 data[:frontchannel_logout_session_supported] = frontchannel_logout_session_supported
  94. end
  95. end
  96. end
  97. end

lib/rodauth/features/oidc_logout_base.rb

100.0% lines covered

38 relevant lines. 38 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oidc_logout_base, :OidcLogoutBase) do
  5. 13 depends :oidc
  6. 13 session_key :visited_sites_key, :visited_sites
  7. 13 private
  8. # set application/sid in visited sites when required
  9. 13 def create_oauth_grant(create_params = {})
  10. 143 sid_in_visited_sites
  11. 143 super
  12. end
  13. 13 def active_sessions?(session_id)
  14. 13 !active_sessions_ds.where(active_sessions_session_id_column => session_id).empty?
  15. end
  16. 13 def session_id_in_claims(oauth_grant, claims)
  17. 169 oauth_application_in_visited_sites do
  18. 169 if should_set_sid_in_visited_sites?(oauth_application)
  19. # id_token or token response types
  20. 117 session_id = if (sess = session[session_id_session_key])
  21. 65 compute_hmac(sess)
  22. else
  23. # code response type
  24. 52 ds = db[active_sessions_table]
  25. 52 ds = ds.where(active_sessions_account_id_column => oauth_grant[oauth_grants_account_id_column])
  26. 52 ds = ds.order(Sequel.desc(active_sessions_last_use_column))
  27. 52 ds.get(active_sessions_session_id_column)
  28. end
  29. 81 claims[:sid] = session_id
  30. end
  31. end
  32. end
  33. 13 def oauth_application_in_visited_sites
  34. 260 visited_sites = session[visited_sites_key] || []
  35. 260 session_id = yield
  36. 260 visited_site = [oauth_application[oauth_applications_client_id_column], session_id]
  37. 260 return if visited_sites.include?(visited_site)
  38. 247 visited_sites << visited_site
  39. 247 set_session_value(visited_sites_key, visited_sites)
  40. end
  41. 13 def sid_in_visited_sites
  42. 143 return unless should_set_oauth_application_in_visited_sites?
  43. 91 oauth_application_in_visited_sites do
  44. 91 if should_set_sid_in_visited_sites?(oauth_application)
  45. 65 ds = active_sessions_ds.order(Sequel.desc(active_sessions_last_use_column))
  46. 65 ds.get(active_sessions_session_id_column)
  47. end
  48. end
  49. end
  50. 13 def should_set_oauth_application_in_visited_sites?
  51. 52 false
  52. end
  53. 13 def should_set_sid_in_visited_sites?(*)
  54. 260 false
  55. end
  56. end
  57. end

lib/rodauth/features/oidc_rp_initiated_logout.rb

95.24% lines covered

63 relevant lines. 60 lines covered and 3 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oidc_rp_initiated_logout, :OidcRpInitiatedLogout) do
  5. 13 depends :oidc_logout_base
  6. 13 response "oidc_logout"
  7. 13 auth_value_method :oauth_applications_post_logout_redirect_uris_column, :post_logout_redirect_uris
  8. 13 translatable_method :oauth_invalid_id_token_hint_message, "Invalid ID token hint"
  9. 13 translatable_method :oauth_invalid_post_logout_redirect_uri_message, "Invalid post logout redirect URI"
  10. 13 attr_reader :oidc_logout_redirect
  11. # /oidc-logout
  12. 13 auth_server_route(:oidc_logout) do |r|
  13. 78 require_authorizable_account
  14. 78 before_oidc_logout_route
  15. # OpenID Providers MUST support the use of the HTTP GET and POST methods
  16. 78 r.on method: %i[get post] do
  17. 78 catch_error do
  18. 78 validate_oidc_logout_params
  19. 78 claims = nil
  20. 78 if (id_token_hint = param_or_nil("id_token_hint"))
  21. #
  22. # why this is done:
  23. #
  24. # we need to decode the id token in order to get the application, because, if the
  25. # signing key is application-specific, we don't know how to verify the signature
  26. # beforehand. Hence, we have to do it twice: decode-and-do-not-verify, initialize
  27. # the @oauth_application, and then decode-and-verify.
  28. #
  29. 78 claims = jwt_decode(id_token_hint, verify_claims: false)
  30. 78 redirect_logout_with_error(oauth_invalid_id_token_hint_message) unless claims
  31. # If the ID Token's sid claim does not correspond to the RP's current session or a
  32. # recent session at the OP, the OP SHOULD treat the logout request as suspect, and
  33. # MAY decline to act upon it.
  34. 78 redirect_logout_with_error(oauth_invalid_client_message) if claims["sid"] && !active_sessions?(claims["sid"])
  35. 78 oauth_application = db[oauth_applications_table].where(oauth_applications_client_id_column => claims["aud"]).first
  36. 78 oauth_grant = db[oauth_grants_table]
  37. .where(resource_owner_params)
  38. .where(oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column])
  39. .first
  40. 78 unique_account_id = if oauth_grant
  41. 65 oauth_grant[oauth_grants_account_id_column]
  42. else
  43. 13 account_id
  44. end
  45. # check whether ID token belongs to currently logged-in user
  46. 78 redirect_logout_with_error(oauth_invalid_client_message) unless claims["sub"] == jwt_subject(unique_account_id,
  47. oauth_application)
  48. # When an id_token_hint parameter is present, the OP MUST validate that it was the issuer of the ID Token.
  49. 78 redirect_logout_with_error(oauth_invalid_client_message) unless claims && claims["iss"] == oauth_jwt_issuer
  50. end
  51. # now let's logout from IdP
  52. 78 transaction do
  53. 78 before_logout
  54. 78 logout
  55. 78 after_logout
  56. end
  57. 78 error_message = logout_notice_flash
  58. 78 if (post_logout_redirect_uri = param_or_nil("post_logout_redirect_uri"))
  59. 65 error_message = catch(:default_logout_redirect) do
  60. 65 throw(:default_logout_redirect, oauth_invalid_id_token_hint_message) unless claims
  61. 65 oauth_application = db[oauth_applications_table].where(oauth_applications_client_id_column => claims["client_id"]).first
  62. 65 throw(:default_logout_redirect, oauth_invalid_client_message) unless oauth_application
  63. 65 post_logout_redirect_uris = oauth_application[oauth_applications_post_logout_redirect_uris_column].split(" ")
  64. 65 unless post_logout_redirect_uris.include?(post_logout_redirect_uri)
  65. throw(:default_logout_redirect,
  66. oauth_invalid_post_logout_redirect_uri_message)
  67. end
  68. 65 if (state = param_or_nil("state"))
  69. 13 post_logout_redirect_uri = URI(post_logout_redirect_uri)
  70. 13 params = ["state=#{CGI.escape(state)}"]
  71. 13 params << post_logout_redirect_uri.query if post_logout_redirect_uri.query
  72. 13 post_logout_redirect_uri.query = params.join("&")
  73. 13 post_logout_redirect_uri = post_logout_redirect_uri.to_s
  74. end
  75. 65 @oidc_logout_redirect = post_logout_redirect_uri
  76. 65 require_response(:_oidc_logout_response)
  77. end
  78. end
  79. 13 redirect_logout_with_error(error_message)
  80. end
  81. redirect_response_error("invalid_request")
  82. end
  83. end
  84. 13 def _oidc_logout_response
  85. 52 redirect(oidc_logout_redirect)
  86. end
  87. 13 private
  88. # Logout
  89. 13 def validate_oidc_logout_params
  90. # check if valid token hint type
  91. 78 return unless (redirect_uri = param_or_nil("post_logout_redirect_uri"))
  92. 65 return if check_valid_no_fragment_uri?(redirect_uri)
  93. redirect_logout_with_error(oauth_invalid_client_message)
  94. end
  95. 13 def redirect_logout_with_error(error_message = oauth_invalid_client_message)
  96. 13 set_notice_flash(error_message)
  97. 13 redirect(logout_redirect)
  98. end
  99. 13 def oauth_server_metadata_body(*)
  100. 13 super.tap do |data|
  101. 9 data[:end_session_endpoint] = oidc_logout_url
  102. end
  103. end
  104. end
  105. end

lib/rodauth/features/oidc_self_issued.rb

97.06% lines covered

34 relevant lines. 33 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oidc_self_issued, :OidcSelfIssued) do
  5. 13 depends :oidc, :oidc_dynamic_client_registration
  6. 13 auth_value_method :oauth_application_scopes, %w[openid profile email address phone]
  7. 13 auth_value_method :oauth_jwt_jws_algorithms_supported, %w[RS256]
  8. 5 SELF_ISSUED_DEFAULT_APPLICATION_PARAMS = {
  9. 8 "scope" => "openid profile email address phone",
  10. "response_types" => ["id_token"],
  11. "subject_type" => "pairwise",
  12. "id_token_signed_response_alg" => "RS256",
  13. "request_object_signing_alg" => "RS256",
  14. "grant_types" => %w[implicit]
  15. }.freeze
  16. 13 def oauth_application
  17. 299 return @oauth_application if defined?(@oauth_application)
  18. 26 return super unless (registration = param_or_nil("registration"))
  19. # self-issued!
  20. 26 redirect_uri = param_or_nil("client_id")
  21. 26 registration_params = JSON.parse(registration)
  22. 26 registration_params = SELF_ISSUED_DEFAULT_APPLICATION_PARAMS.merge(registration_params)
  23. 26 client_params = validate_client_registration_params(registration_params)
  24. 18 request.params["redirect_uri"] = client_params[oauth_applications_client_id_column] = redirect_uri
  25. 26 client_params[oauth_applications_redirect_uri_column] ||= redirect_uri
  26. 26 @oauth_application = client_params
  27. end
  28. 13 private
  29. 13 def oauth_response_types_supported
  30. 26 %w[id_token]
  31. end
  32. 13 def request_object_signing_alg_values_supported
  33. %w[none RS256]
  34. end
  35. 13 def id_token_claims(oauth_grant, signing_algorithm)
  36. 13 claims = super
  37. 13 return claims unless claims[:client_id] == oauth_grant[oauth_grants_redirect_uri_column]
  38. # https://openid.net/specs/openid-connect-core-1_0.html#SelfIssued - 7.4
  39. 13 pub_key = oauth_jwt_public_keys[signing_algorithm]
  40. 13 pub_key = pub_key.first if pub_key.is_a?(Array)
  41. 9 claims[:sub_jwk] = sub_jwk = jwk_export(pub_key)
  42. 9 claims[:iss] = "https://self-issued.me"
  43. 9 claims[:aud] = oauth_grant[oauth_grants_redirect_uri_column]
  44. 13 jwk_thumbprint = jwk_thumbprint(sub_jwk)
  45. 9 claims[:sub] = Base64.urlsafe_encode64(jwk_thumbprint, padding: false)
  46. 13 claims
  47. end
  48. end
  49. end

lib/rodauth/features/oidc_session_management.rb

97.92% lines covered

48 relevant lines. 47 lines covered and 1 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth/oauth"
  3. 13 module Rodauth
  4. 13 Feature.define(:oidc_session_management, :OidcSessionManagement) do
  5. 13 depends :oidc
  6. 13 view "check_session", "Check Session", "check_session"
  7. 13 auth_value_method :oauth_oidc_user_agent_state_cookie_key, "_rodauth_oauth_user_agent_state"
  8. 13 auth_value_method :oauth_oidc_user_agent_state_cookie_options, {}.freeze
  9. 13 auth_value_method :oauth_oidc_user_agent_state_cookie_expires_in, 365 * 24 * 60 * 60 # 1 year
  10. 13 auth_value_method :oauth_oidc_user_agent_state_js, nil
  11. 13 auth_value_methods(
  12. :oauth_oidc_session_management_salt
  13. )
  14. # /authorize
  15. 13 auth_server_route(:check_session) do |r|
  16. 13 allow_cors(r)
  17. 13 r.get do
  18. 13 set_title(:check_session_page_title)
  19. 13 scope.view(_view_opts("check_session").merge(layout: false))
  20. end
  21. end
  22. 13 def clear_session
  23. 39 super
  24. # update user agent state in the process
  25. # TODO: dangerous if this gets overidden by the user
  26. 39 user_agent_state_cookie_opts = Hash[oauth_oidc_user_agent_state_cookie_options]
  27. 27 user_agent_state_cookie_opts[:value] = oauth_unique_id_generator
  28. 27 user_agent_state_cookie_opts[:secure] = true
  29. 39 if oauth_oidc_user_agent_state_cookie_expires_in
  30. 27 user_agent_state_cookie_opts[:expires] = convert_timestamp(Time.now + oauth_oidc_user_agent_state_cookie_expires_in)
  31. end
  32. 39 ::Rack::Utils.set_cookie_header!(response.headers, oauth_oidc_user_agent_state_cookie_key, user_agent_state_cookie_opts)
  33. end
  34. 13 private
  35. 13 def do_authorize(*)
  36. 13 params, mode = super
  37. 9 params["session_state"] = generate_session_state
  38. 13 [params, mode]
  39. end
  40. 13 def response_error_params(*)
  41. 13 payload = super
  42. 13 return payload unless request.path == authorize_path
  43. 9 payload["session_state"] = generate_session_state
  44. 13 payload
  45. end
  46. 13 def generate_session_state
  47. 26 salt = oauth_oidc_session_management_salt
  48. 26 uri = URI(redirect_uri)
  49. 26 origin = if uri.respond_to?(:origin)
  50. 16 uri.origin
  51. else
  52. # TODO: remove when not supporting uri < 0.11
  53. 10 "#{uri.scheme}://#{uri.host}#{":#{uri.port}" if uri.port != uri.default_port}"
  54. end
  55. 26 session_id = "#{oauth_application[oauth_applications_client_id_column]} " \
  56. 8 "#{origin} " \
  57. 8 "#{request.cookies[oauth_oidc_user_agent_state_cookie_key]} #{salt}"
  58. 18 "#{Digest::SHA256.hexdigest(session_id)}.#{salt}"
  59. end
  60. 13 def oauth_server_metadata_body(*)
  61. 13 super.tap do |data|
  62. 9 data[:check_session_iframe] = check_session_url
  63. end
  64. end
  65. 13 def oauth_oidc_session_management_salt
  66. oauth_unique_id_generator
  67. end
  68. end
  69. end

lib/rodauth/oauth.rb

100.0% lines covered

19 relevant lines. 19 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "rodauth"
  3. 13 require "rodauth/oauth/version"
  4. 13 module Rodauth
  5. 13 module OAuth
  6. 13 module FeatureExtensions
  7. 13 def auth_server_route(name, *args, &blk)
  8. 156 routes = route(name, *args, &blk)
  9. 156 handle_meth = routes.last
  10. 156 define_method(:"#{handle_meth}_for_auth_server") do
  11. 8442 next unless is_authorization_server?
  12. 8442 send(:"#{handle_meth}_not_for_auth_server")
  13. end
  14. 156 alias_method :"#{handle_meth}_not_for_auth_server", handle_meth
  15. 156 alias_method handle_meth, :"#{handle_meth}_for_auth_server"
  16. # make all requests usable via internal_request feature
  17. 156 internal_request_method name
  18. end
  19. # override
  20. 13 def translatable_method(meth, value)
  21. 33891 define_method(meth) { |*args| translate(meth, value, *args) }
  22. 2444 auth_value_methods(meth)
  23. end
  24. end
  25. end
  26. 13 Feature.prepend OAuth::FeatureExtensions
  27. end
  28. 13 require "rodauth/oauth/railtie" if defined?(Rails)

lib/rodauth/oauth/database_extensions.rb

100.0% lines covered

42 relevant lines. 42 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 module Rodauth
  3. 13 module OAuth
  4. # rubocop:disable Naming/MethodName
  5. 13 def self.ExtendDatabase(db)
  6. 5803 Module.new do
  7. 5803 dataset = db.dataset
  8. 5803 if dataset.supports_returning?(:insert)
  9. 4018 def __insert_and_return__(dataset, _pkey, params)
  10. 1023 dataset.returning.insert(params).first
  11. end
  12. else
  13. 1785 def __insert_and_return__(dataset, pkey, params)
  14. 354 id = dataset.insert(params)
  15. 338 if params.key?(pkey)
  16. # mysql returns 0 when the primary key is a varchar.
  17. 48 id = params[pkey]
  18. end
  19. 338 dataset.where(pkey => id).first
  20. end
  21. end
  22. 5803 if dataset.supports_returning?(:update)
  23. 4018 def __update_and_return__(dataset, params)
  24. 791 dataset.returning.update(params).first
  25. end
  26. else
  27. 1785 def __update_and_return__(dataset, params)
  28. 438 dataset.update(params)
  29. 422 dataset.first
  30. end
  31. end
  32. 5803 if dataset.respond_to?(:supports_insert_conflict?) && dataset.supports_insert_conflict?
  33. 1784 def __insert_or_update_and_return__(dataset, pkey, unique_columns, params, conds = nil, to_update_extra = nil)
  34. 4888 to_update = Hash[(params.keys - unique_columns).map { |attribute| [attribute, Sequel[:excluded][attribute]] }]
  35. 344 to_update.merge!(to_update_extra) if to_update_extra
  36. 344 dataset = dataset.insert_conflict(
  37. target: unique_columns,
  38. update: to_update,
  39. update_where: conds
  40. )
  41. 344 __insert_and_return__(dataset, pkey, params)
  42. end
  43. 1784 def __insert_or_do_nothing_and_return__(dataset, pkey, unique_columns, params)
  44. 80 __insert_and_return__(
  45. dataset.insert_conflict(target: unique_columns),
  46. pkey,
  47. params
  48. ) || dataset.where(params).first
  49. end
  50. else
  51. 4019 def __insert_or_update_and_return__(dataset, pkey, unique_columns, params, conds = nil, to_update_extra = nil)
  52. 6970 find_params, update_params = params.partition { |key, _| unique_columns.include?(key) }.map { |h| Hash[h] }
  53. 384 dataset_where = dataset.where(find_params)
  54. 384 record = if conds
  55. 184 dataset_where_conds = dataset_where.where(conds)
  56. # this means that there's still a valid entry there, so return early
  57. 184 return if dataset_where.count != dataset_where_conds.count
  58. 184 dataset_where_conds.first
  59. else
  60. 200 dataset_where.first
  61. end
  62. 384 if record
  63. 232 update_params.merge!(to_update_extra) if to_update_extra
  64. 232 __update_and_return__(dataset_where, update_params)
  65. else
  66. 152 __insert_and_return__(dataset, pkey, params)
  67. end
  68. end
  69. 4019 def __insert_or_do_nothing_and_return__(dataset, pkey, unique_columns, params)
  70. 504 find_params = params.select { |key, _| unique_columns.include?(key) }
  71. 180 dataset.where(find_params).first || __insert_and_return__(dataset, pkey, params)
  72. end
  73. end
  74. end
  75. end
  76. # rubocop:enable Naming/MethodName
  77. end
  78. end

lib/rodauth/oauth/http_extensions.rb

95.56% lines covered

45 relevant lines. 43 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. 13 require "uri"
  3. 13 require "net/http"
  4. 13 require "rodauth/oauth/ttl_store"
  5. 13 module Rodauth
  6. 13 module OAuth
  7. 13 module HTTPExtensions
  8. 13 REQUEST_CACHE = OAuth::TtlStore.new
  9. 13 private
  10. 13 def http_request(uri, form_data = nil)
  11. 377 uri = URI(uri)
  12. 377 http = Net::HTTP.new(uri.host, uri.port)
  13. 377 http.use_ssl = uri.scheme == "https"
  14. 377 http.open_timeout = 15
  15. 377 http.read_timeout = 15
  16. 377 http.write_timeout = 15 if http.respond_to?(:write_timeout)
  17. 377 if form_data
  18. 169 request = Net::HTTP::Post.new(uri.request_uri)
  19. 117 request["content-type"] = "application/x-www-form-urlencoded"
  20. 169 request.set_form_data(form_data)
  21. else
  22. 208 request = Net::HTTP::Get.new(uri.request_uri)
  23. end
  24. 261 request["accept"] = json_response_content_type
  25. 377 yield request if block_given?
  26. 377 response = http.request(request)
  27. 377 authorization_required unless (200..299).include?(response.code.to_i)
  28. 377 response
  29. end
  30. 13 def http_request_with_cache(uri, *args)
  31. 130 uri = URI(uri)
  32. 130 response = http_request_cache[uri]
  33. 130 return response if response
  34. 117 http_request_cache.set(uri) do
  35. 117 response = http_request(uri, *args)
  36. 117 ttl = if response.key?("cache-control")
  37. 78 cache_control = response["cache-control"]
  38. 78 if cache_control.include?("no-cache")
  39. nil
  40. else
  41. 78 max_age = cache_control[/max-age=(\d+)/, 1].to_i
  42. 78 max_age.zero? ? nil : max_age
  43. end
  44. 39 elsif response.key?("expires")
  45. 39 expires = response["expires"]
  46. 3 begin
  47. 39 Time.parse(expires).to_i - Time.now.to_i
  48. rescue ArgumentError
  49. nil
  50. end
  51. end
  52. 117 [JSON.parse(response.body, symbolize_names: true), ttl]
  53. end
  54. end
  55. 13 def http_request_cache
  56. 39 REQUEST_CACHE
  57. end
  58. end
  59. end
  60. end

lib/rodauth/oauth/jwe_extensions.rb

100.0% lines covered

33 relevant lines. 33 lines covered and 0 lines missed.
    
  1. # frozen_string_literal: true
  2. 10 module JWE
  3. #
  4. # this is a monkey-patch!
  5. # it's necessary, as the original jwe does not support jwks.
  6. # if this works long term, it may be merged upstreamm.
  7. #
  8. 10 def self.__rodauth_oauth_decrypt_from_jwks(payload, jwks, alg: "RSA-OAEP", enc: "A128GCM")
  9. 30 header, enc_key, iv, ciphertext, tag = Serialization::Compact.decode(payload)
  10. 20 header = JSON.parse(header)
  11. 20 key = find_key_by_kid(jwks, header["kid"], alg, enc)
  12. 10 check_params(header, key)
  13. 10 cek = Alg.decrypt_cek(header["alg"], key, enc_key)
  14. 10 cipher = Enc.for(header["enc"], cek, iv, tag)
  15. 10 plaintext = cipher.decrypt(ciphertext, payload.split(".").first)
  16. 10 apply_zip(header, plaintext, :decompress)
  17. end
  18. 10 def self.__rodauth_oauth_encrypt_from_jwks(payload, jwks, alg: "RSA-OAEP", enc: "A128GCM", **more_headers)
  19. 60 header = generate_header(alg, enc, more_headers)
  20. 60 key = find_key_by_alg_enc(jwks, alg, enc)
  21. 60 check_params(header, key)
  22. 60 payload = apply_zip(header, payload, :compress)
  23. 60 cipher = Enc.for(enc)
  24. 60 cipher.cek = key if alg == "dir"
  25. 60 json_hdr = header.to_json
  26. 60 ciphertext = cipher.encrypt(payload, Base64.jwe_encode(json_hdr))
  27. 60 generate_serialization(json_hdr, Alg.encrypt_cek(alg, key, cipher.cek), ciphertext, cipher)
  28. end
  29. 10 def self.find_key_by_kid(jwks, kid, alg, enc)
  30. 20 raise DecodeError, "No key id (kid) found from token headers" unless kid
  31. 70 jwk = jwks.find { |key, _| (key[:kid] || key["kid"]) == kid }
  32. 20 raise DecodeError, "Could not find public key for kid #{kid}" unless jwk
  33. 20 raise DecodeError, "Expected a different encryption algorithm" unless alg == (jwk[:alg] || jwk["alg"])
  34. 20 raise DecodeError, "Expected a different encryption method" unless enc == (jwk[:enc] || jwk["enc"])
  35. 10 ::JWT::JWK.import(jwk).keypair
  36. end
  37. 10 def self.find_key_by_alg_enc(jwks, alg, enc)
  38. 60 jwk = jwks.find do |key, _|
  39. 120 (key[:alg] || key["alg"]) == alg &&
  40. 80 (key[:enc] || key["enc"]) == enc
  41. end
  42. 60 raise DecodeError, "No key found" unless jwk
  43. 60 ::JWT::JWK.import(jwk).keypair
  44. end
  45. end

lib/rodauth/oauth/ttl_store.rb

92.86% lines covered

28 relevant lines. 26 lines covered and 2 lines missed.
    
  1. # frozen_string_literal: true
  2. #
  3. # The TTL store is a data structure which keeps data by a key, and with a time-to-live.
  4. # It is specifically designed for data which is static, i.e. for a certain key in a
  5. # sufficiently large span, the value will be the same.
  6. #
  7. # Because of that, synchronizations around reads do not exist, while write synchronizations
  8. # will be short-circuited by a read.
  9. #
  10. 13 class Rodauth::OAuth::TtlStore
  11. 13 DEFAULT_TTL = 60 * 60 * 24 # default TTL is one day
  12. 13 def initialize
  13. 13 @store_mutex = Mutex.new
  14. 13 @store = {}
  15. end
  16. 13 def [](key)
  17. 26 lookup(key, now)
  18. end
  19. 13 def set(key, &block)
  20. 13 @store_mutex.synchronize do
  21. # short circuit
  22. 13 return @store[key][:payload] if @store[key] && @store[key][:ttl] < now
  23. end
  24. 13 payload, ttl = block.call
  25. 13 return payload unless ttl
  26. 13 @store_mutex.synchronize do
  27. # given that the block call triggers network, and two requests for the same key be processed
  28. # at the same time, this ensures the first one wins.
  29. 13 return @store[key][:payload] if @store[key] && @store[key][:ttl] < now
  30. 9 @store[key] = { payload: payload, ttl: ttl || (now + DEFAULT_TTL) }
  31. end
  32. 13 @store[key][:payload]
  33. end
  34. 13 def uncache(key)
  35. @store_mutex.synchronize do
  36. @store.delete(key)
  37. end
  38. end
  39. 13 private
  40. 13 def now
  41. 26 Process.clock_gettime(Process::CLOCK_MONOTONIC)
  42. end
  43. # do not use directly!
  44. 13 def lookup(key, ttl)
  45. 26 return unless @store.key?(key)
  46. 13 value = @store[key]
  47. 13 return if value.empty?
  48. 13 return unless value[:ttl] > ttl
  49. 13 value[:payload]
  50. end
  51. end