All Files ( 96.21% covered at 389.41 hits/line )
38 files in total.
3218 relevant lines,
3096 lines covered and
122 lines missed.
(
96.21%
)
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_application_management, :OauthApplicationManagement) do
- 12
depends :oauth_management_base, :oauth_token_revocation
- 12
before "create_oauth_application"
- 12
after "create_oauth_application"
- 12
error_flash "There was an error registering your oauth application", "create_oauth_application"
- 12
notice_flash "Your oauth application has been registered", "create_oauth_application"
- 12
view "oauth_applications", "Oauth Applications", "oauth_applications"
- 12
view "oauth_application", "Oauth Application", "oauth_application"
- 12
view "new_oauth_application", "New Oauth Application", "new_oauth_application"
- 12
view "oauth_application_oauth_grants", "Oauth Application Grants", "oauth_application_oauth_grants"
# Application
- 12
APPLICATION_REQUIRED_PARAMS = %w[name scopes homepage_url redirect_uri client_secret].freeze
- 12
auth_value_method :oauth_application_required_params, APPLICATION_REQUIRED_PARAMS
- 12
(APPLICATION_REQUIRED_PARAMS + %w[description client_id]).each do |param|
- 84
auth_value_method :"oauth_application_#{param}_param", param
end
- 12
translatable_method :oauth_applications_name_label, "Name"
- 12
translatable_method :oauth_applications_description_label, "Description"
- 12
translatable_method :oauth_applications_scopes_label, "Default scopes"
- 12
translatable_method :oauth_applications_contacts_label, "Contacts"
- 12
translatable_method :oauth_applications_tos_uri_label, "Terms of service"
- 12
translatable_method :oauth_applications_policy_uri_label, "Policy"
- 12
translatable_method :oauth_applications_jwks_label, "JSON Web Keys"
- 12
translatable_method :oauth_applications_jwks_uri_label, "JSON Web Keys URI"
- 12
translatable_method :oauth_applications_homepage_url_label, "Homepage URL"
- 12
translatable_method :oauth_applications_redirect_uri_label, "Redirect URI"
- 12
translatable_method :oauth_applications_client_secret_label, "Client Secret"
- 12
translatable_method :oauth_applications_client_id_label, "Client ID"
- 12
%w[type token refresh_token expires_in revoked_at].each do |param|
- 60
translatable_method :"oauth_grants_#{param}_label", param.gsub("_", " ").capitalize
end
- 12
button "Register", "oauth_application"
- 12
button "Revoke", "oauth_grant_revoke"
- 12
auth_value_method :oauth_applications_oauth_grants_path, "oauth-grants"
- 12
auth_value_method :oauth_applications_route, "oauth-applications"
- 12
auth_value_method :oauth_applications_per_page, 20
- 12
auth_value_method :oauth_applications_id_pattern, Integer
- 12
auth_value_method :oauth_grants_per_page, 20
- 12
translatable_method :invalid_url_message, "Invalid URL"
- 12
translatable_method :null_error_message, "is not filled"
- 12
translatable_method :oauth_no_applications_text, "No oauth applications yet!"
- 12
translatable_method :oauth_no_grants_text, "No oauth grants yet!"
- 12
auth_methods(
:oauth_application_path
)
- 12
def oauth_applications_path(opts = {})
- 1032
route_path(oauth_applications_route, opts)
end
- 12
def oauth_application_path(id)
- 204
"#{oauth_applications_path}/#{id}"
end
# /oauth-applications routes
- 12
def load_oauth_application_management_routes
- 252
request.on(oauth_applications_route) do
- 252
check_csrf if check_csrf?
- 252
require_account
- 252
request.get "new" do
- 36
new_oauth_application_view
end
- 216
request.on(oauth_applications_id_pattern) do |id|
- 84
oauth_application = db[oauth_applications_table]
.where(oauth_applications_id_column => id)
.where(oauth_applications_account_id_column => account_id)
.first
- 84
next unless oauth_application
- 72
scope.instance_variable_set(:@oauth_application, oauth_application)
- 72
request.is do
- 24
request.get do
- 24
oauth_application_view
end
end
- 48
request.on(oauth_applications_oauth_grants_path) do
- 48
page = Integer(param_or_nil("page") || 1)
- 48
per_page = per_page_param(oauth_grants_per_page)
- 48
oauth_grants = db[oauth_grants_table]
.where(oauth_grants_oauth_application_id_column => id)
.order(Sequel.desc(oauth_grants_id_column))
- 48
scope.instance_variable_set(:@oauth_grants, oauth_grants.paginate(page, per_page))
- 48
request.is do
- 48
request.get do
- 48
oauth_application_oauth_grants_view
end
end
end
end
- 132
request.is do
- 132
request.get do
- 84
page = Integer(param_or_nil("page") || 1)
- 84
per_page = per_page_param(oauth_applications_per_page)
- 84
scope.instance_variable_set(:@oauth_applications, db[oauth_applications_table]
.where(oauth_applications_account_id_column => account_id)
.order(Sequel.desc(oauth_applications_id_column))
.paginate(page, per_page))
- 84
oauth_applications_view
end
- 48
request.post do
- 48
catch_error do
- 48
validate_oauth_application_params
- 24
transaction do
- 24
before_create_oauth_application
- 24
id = create_oauth_application
- 24
after_create_oauth_application
- 24
set_notice_flash create_oauth_application_notice_flash
- 24
redirect "#{request.path}/#{id}"
end
end
- 24
set_error_flash create_oauth_application_error_flash
- 24
new_oauth_application_view
end
end
end
end
- 12
private
- 12
def oauth_application_params
- 192
@oauth_application_params ||= oauth_application_required_params.each_with_object({}) do |param, params|
- 240
value = request.params[__send__(:"oauth_application_#{param}_param")]
- 240
if value && !value.empty?
- 156
params[param] = value
else
- 84
set_field_error(param, null_error_message)
end
end
end
- 12
def validate_oauth_application_params
- 48
oauth_application_params.each do |key, value|
- 156
if key == oauth_application_homepage_url_param
- 36
set_field_error(key, invalid_url_message) unless check_valid_uri?(value)
- 120
elsif key == oauth_application_redirect_uri_param
- 36
if value.respond_to?(:each)
- 12
value.each do |uri|
- 24
next if uri.empty?
- 24
set_field_error(key, invalid_url_message) unless check_valid_no_fragment_uri?(uri)
end
else
- 24
set_field_error(key, invalid_url_message) unless check_valid_no_fragment_uri?(value)
end
- 84
elsif key == oauth_application_scopes_param
- 24
value.each do |scope|
- 48
set_field_error(key, oauth_invalid_scope_message) unless oauth_application_scopes.include?(scope)
end
end
end
- 48
throw :rodauth_error if @field_errors && !@field_errors.empty?
end
- 12
def create_oauth_application
- 8
create_params = {
- 16
oauth_applications_account_id_column => account_id,
oauth_applications_name_column => oauth_application_params[oauth_application_name_param],
oauth_applications_description_column => oauth_application_params[oauth_application_description_param],
oauth_applications_scopes_column => oauth_application_params[oauth_application_scopes_param],
oauth_applications_homepage_url_column => oauth_application_params[oauth_application_homepage_url_param]
}
- 24
redirect_uris = oauth_application_params[oauth_application_redirect_uri_param]
- 24
redirect_uris = redirect_uris.to_a.reject(&:empty?).join(" ") if redirect_uris.respond_to?(:each)
- 24
create_params[oauth_applications_redirect_uri_column] = redirect_uris unless redirect_uris.empty?
# set client ID/secret pairs
- 24
set_client_secret(create_params, oauth_application_params[oauth_application_client_secret_param])
- 24
if create_params[oauth_applications_scopes_column]
- 24
create_params[oauth_applications_scopes_column] = create_params[oauth_applications_scopes_column].join(oauth_scope_separator)
end
- 24
rescue_from_uniqueness_error do
- 24
create_params[oauth_applications_client_id_column] = oauth_unique_id_generator
- 24
db[oauth_applications_table].insert(create_params)
end
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_assertion_base, :OauthAssertionBase) do
- 12
depends :oauth_base
- 12
auth_methods(
:assertion_grant_type?,
:client_assertion_type?,
:assertion_grant_type,
:client_assertion_type
)
- 12
private
- 12
def validate_token_params
- 96
return super unless assertion_grant_type?
- 48
redirect_response_error("invalid_grant") unless param_or_nil("assertion")
end
- 12
def require_oauth_application
- 192
if assertion_grant_type?
- 48
@oauth_application = __send__(:"require_oauth_application_from_#{assertion_grant_type}_assertion_issuer", param("assertion"))
- 144
elsif client_assertion_type?
- 108
@oauth_application = __send__(:"require_oauth_application_from_#{client_assertion_type}_assertion_subject",
param("client_assertion"))
- 72
if (client_id = param_or_nil("client_id")) &&
client_id != @oauth_application[oauth_applications_client_id_column]
# If present, the value of the
# "client_id" parameter MUST identify the same client as is
# identified by the client assertion.
- 24
redirect_response_error("invalid_grant")
end
else
- 36
super
end
end
- 12
def account_from_bearer_assertion_subject(subject)
- 48
__insert_or_do_nothing_and_return__(
db[accounts_table],
account_id_column,
[login_column],
login_column => subject
)
end
- 12
def create_token(grant_type)
- 60
return super unless assertion_grant_type?(grant_type) && supported_grant_type?(grant_type)
- 48
account = __send__(:"account_from_#{assertion_grant_type}_assertion", param("assertion"))
- 48
redirect_response_error("invalid_grant") unless account
- 48
grant_scopes = if param_or_nil("scope")
- 24
redirect_response_error("invalid_scope") unless check_valid_scopes?
- 12
scopes
else
- 24
@oauth_application[oauth_applications_scopes_column]
end
- 12
grant_params = {
- 24
oauth_grants_type_column => grant_type,
oauth_grants_account_id_column => account[account_id_column],
oauth_grants_oauth_application_id_column => @oauth_application[oauth_applications_id_column],
oauth_grants_scopes_column => grant_scopes
}
- 36
generate_token(grant_params, false)
end
- 12
def assertion_grant_type?(grant_type = param("grant_type"))
- 348
grant_type.start_with?("urn:ietf:params:oauth:grant-type:")
end
- 12
def client_assertion_type?(client_assertion_type = param("client_assertion_type"))
- 144
client_assertion_type.start_with?("urn:ietf:params:oauth:client-assertion-type:")
end
- 12
def assertion_grant_type(grant_type = param("grant_type"))
- 96
grant_type.delete_prefix("urn:ietf:params:oauth:grant-type:").tr("-", "_")
end
- 12
def client_assertion_type(assertion_type = param("client_assertion_type"))
- 108
assertion_type.delete_prefix("urn:ietf:params:oauth:client-assertion-type:").tr("-", "_")
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_authorization_code_grant, :OauthAuthorizationCodeGrant) do
- 12
depends :oauth_authorize_base
- 12
auth_value_method :oauth_response_mode, "form_post"
- 12
def oauth_grant_types_supported
- 4224
super | %w[authorization_code]
end
- 12
def oauth_response_types_supported
- 1932
super | %w[code]
end
- 12
def oauth_response_modes_supported
- 3264
super | %w[query form_post]
end
- 12
private
- 12
def validate_authorize_params
- 2580
super
- 2388
response_mode = param_or_nil("response_mode")
- 2388
return unless response_mode
- 996
redirect_response_error("invalid_request") unless oauth_response_modes_supported.include?(response_mode)
- 996
response_type = param_or_nil("response_type")
- 996
return unless response_type.nil? || response_type == "code"
- 828
redirect_response_error("invalid_request") unless oauth_response_modes_for_code_supported.include?(response_mode)
end
- 12
def oauth_response_modes_for_code_supported
- 828
%w[query form_post]
end
- 12
def validate_token_params
- 1680
redirect_response_error("invalid_request") if param_or_nil("grant_type") == "authorization_code" && !param_or_nil("code")
- 1680
super
end
- 12
def do_authorize(response_params = {}, response_mode = param_or_nil("response_mode"))
- 924
response_mode ||= oauth_response_mode
- 924
redirect_response_error("invalid_request") unless response_mode.nil? || supported_response_mode?(response_mode)
- 924
response_type = param_or_nil("response_type")
- 924
redirect_response_error("invalid_request") unless response_type.nil? || supported_response_type?(response_type)
- 924
case response_type
when "code", nil
- 600
response_params.replace(_do_authorize_code)
end
- 912
response_params["state"] = param("state") if param_or_nil("state")
- 912
[response_params, response_mode]
end
- 12
def _do_authorize_code
- 240
create_params = {
- 480
oauth_grants_type_column => "authorization_code",
**resource_owner_params
}
- 720
{ "code" => create_oauth_grant(create_params) }
end
- 12
def authorize_response(params, mode)
- 528
redirect_url = URI.parse(redirect_uri)
- 528
case mode
when "query"
- 504
params = [URI.encode_www_form(params)]
- 504
params << redirect_url.query if redirect_url.query
- 504
redirect_url.query = params.join("&")
- 504
redirect(redirect_url.to_s)
when "form_post"
- 24
inline_html = form_post_response_html(redirect_uri) do
- 16
params.map do |name, value|
- 24
"<input type=\"hidden\" name=\"#{scope.h(name)}\" value=\"#{scope.h(value)}\" />"
- 8
end.join
end
- 24
scope.view layout: false, inline: inline_html
end
end
- 12
def _redirect_response_error(redirect_url, params)
- 384
response_mode = param_or_nil("response_mode") || oauth_response_mode
- 384
case response_mode
when "form_post"
- 12
response["Content-Type"] = "text/html"
- 12
error_body = form_post_error_response_html(redirect_url) do
- 8
params.map do |name, value|
- 24
"<input type=\"hidden\" name=\"#{name}\" value=\"#{scope.h(value)}\" />"
- 4
end.join
end
- 12
response.write(error_body)
- 12
request.halt
else
- 372
super
end
end
- 12
def form_post_response_html(url)
- 36
<<-FORM
<html>
<head><title>Authorized</title></head>
<body onload="javascript:document.forms[0].submit()">
<form method="post" action="#{url}">
#{yield}
<input type="submit" class="btn btn-outline-primary" value="#{scope.h(oauth_authorize_post_button)}"/>
</form>
</body>
</html>
FORM
end
- 12
def form_post_error_response_html(url)
- 12
<<-FORM
<html>
<head><title></title></head>
<body onload="javascript:document.forms[0].submit()">
<form method="post" action="#{url}">
#{yield}
</form>
</body>
</html>
FORM
end
- 12
def create_token(grant_type)
- 1476
return super unless supported_grant_type?(grant_type, "authorization_code")
- 388
grant_params = {
- 776
oauth_grants_code_column => param("code"),
oauth_grants_redirect_uri_column => param("redirect_uri"),
oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column]
}
- 1164
create_token_from_authorization_code(grant_params)
end
- 12
def check_valid_response_type?
- 1584
response_type = param_or_nil("response_type")
- 1584
response_type == "code" || response_type == "none" || super
end
- 12
def oauth_server_metadata_body(*)
- 312
super.tap do |data|
- 312
data[:authorization_endpoint] = authorize_url
end
end
end
end
# frozen_string_literal: true
- 12
require "ipaddr"
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_authorize_base, :OauthAuthorizeBase) do
- 12
depends :oauth_base
- 12
before "authorize"
- 12
after "authorize"
- 12
view "authorize", "Authorize", "authorize"
- 12
view "authorize_error", "Authorize Error", "authorize_error"
- 12
button "Authorize", "oauth_authorize"
- 12
button "Back to Client Application", "oauth_authorize_post"
- 12
auth_value_method :use_oauth_access_type?, false
- 12
auth_value_method :oauth_grants_access_type_column, :access_type
- 12
translatable_method :authorize_page_lead, "The application %<name>s would like to access your data"
- 12
translatable_method :oauth_grants_scopes_label, "Scopes"
- 12
translatable_method :oauth_applications_contacts_label, "Contacts"
- 12
translatable_method :oauth_applications_tos_uri_label, "Terms of service URL"
- 12
translatable_method :oauth_applications_policy_uri_label, "Policy URL"
- 12
translatable_method :oauth_unsupported_response_type_message, "Unsupported response type"
- 12
translatable_method :oauth_authorize_parameter_required, "Invalid or missing '%<parameter>s'"
- 12
auth_methods(
:resource_owner_params,
:oauth_grants_resource_owner_columns
)
# /authorize
- 12
auth_server_route(:authorize) do |r|
- 2916
require_authorizable_account
- 2796
before_authorize_route
- 2796
validate_authorize_params
- 2196
r.get do
- 1224
authorize_view
end
- 972
r.post do
- 972
params, mode = transaction do
- 972
before_authorize
- 972
do_authorize
end
- 960
authorize_response(params, mode)
end
end
- 12
def check_csrf?
- 11040
case request.path
when authorize_path
- 2916
only_json? ? false : super
else
- 8124
super
end
end
- 12
def authorize_scopes
- 1224
scopes || begin
- 180
oauth_application[oauth_applications_scopes_column].split(oauth_scope_separator)
end
end
- 12
private
- 12
def validate_authorize_params
- 2544
redirect_authorize_error("client_id") unless oauth_application
- 2496
redirect_uris = oauth_application[oauth_applications_redirect_uri_column].split(" ")
- 2496
if (redirect_uri = param_or_nil("redirect_uri"))
- 468
normalized_redirect_uri = normalize_redirect_uri_for_comparison(redirect_uri)
- 468
unless redirect_uris.include?(normalized_redirect_uri) || redirect_uris.include?(redirect_uri)
- 12
redirect_authorize_error("redirect_uri")
end
- 2028
elsif redirect_uris.size > 1
- 12
redirect_authorize_error("redirect_uri")
end
- 2472
redirect_response_error("unsupported_response_type") unless check_valid_response_type?
- 2448
redirect_response_error("invalid_request") unless check_valid_access_type? && check_valid_approval_prompt?
- 2448
try_approval_prompt if use_oauth_access_type? && request.get?
- 2448
redirect_response_error("invalid_scope") if (request.post? || param_or_nil("scope")) && !check_valid_scopes?
- 2424
response_mode = param_or_nil("response_mode")
- 2424
redirect_response_error("invalid_request") unless response_mode.nil? || oauth_response_modes_supported.include?(response_mode)
end
- 12
def check_valid_scopes?(scp = scopes)
- 2196
super(scp - %w[offline_access])
end
- 12
def check_valid_response_type?
- 24
false
end
- 12
ACCESS_TYPES = %w[offline online].freeze
- 12
def check_valid_access_type?
- 2448
return true unless use_oauth_access_type?
- 36
access_type = param_or_nil("access_type")
- 36
!access_type || ACCESS_TYPES.include?(access_type)
end
- 12
APPROVAL_PROMPTS = %w[force auto].freeze
- 12
def check_valid_approval_prompt?
- 2448
return true unless use_oauth_access_type?
- 36
approval_prompt = param_or_nil("approval_prompt")
- 36
!approval_prompt || APPROVAL_PROMPTS.include?(approval_prompt)
end
- 12
def resource_owner_params
- 1404
{ oauth_grants_account_id_column => account_id }
end
- 12
def oauth_grants_resource_owner_columns
[oauth_grants_account_id_column]
end
- 12
def try_approval_prompt
- 24
approval_prompt = param_or_nil("approval_prompt")
- 24
return unless approval_prompt && approval_prompt == "auto"
- 8
return if db[oauth_grants_table].where(resource_owner_params).where(
oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column],
oauth_grants_redirect_uri_column => redirect_uri,
oauth_grants_scopes_column => scopes.join(oauth_scope_separator),
oauth_grants_access_type_column => "online"
- 4
).count.zero?
# if there's a previous oauth grant for the params combo, it means that this user has approved before.
- 12
request.env["REQUEST_METHOD"] = "POST"
end
- 12
def redirect_authorize_error(parameter, referer = request.referer || default_redirect)
- 96
error_message = oauth_authorize_parameter_required(parameter: parameter)
- 96
if accepts_json?
status_code = oauth_invalid_response_status
throw_json_response_error(status_code, "invalid_request", error_message)
else
- 96
scope.instance_variable_set(:@error, error_message)
- 96
scope.instance_variable_set(:@back_url, referer)
- 96
return_response(authorize_error_view)
end
end
- 12
def authorization_required
- 372
if accepts_json?
- 360
throw_json_response_error(oauth_authorization_required_error_status, "invalid_client")
else
- 12
set_redirect_error_flash(require_authorization_error_flash)
- 12
redirect(authorize_path)
end
end
- 12
def do_authorize(*args); end
- 12
def authorize_response(params, mode); end
- 12
def create_token_from_authorization_code(grant_params, should_generate_refresh_token = !use_oauth_access_type?, oauth_grant: nil)
# fetch oauth grant
- 1128
oauth_grant ||= valid_locked_oauth_grant(grant_params)
- 936
should_generate_refresh_token ||= oauth_grant[oauth_grants_access_type_column] == "offline"
- 936
generate_token(oauth_grant, should_generate_refresh_token)
end
- 12
def create_oauth_grant(create_params = {})
- 768
create_params[oauth_grants_oauth_application_id_column] ||= oauth_application[oauth_applications_id_column]
- 768
create_params[oauth_grants_redirect_uri_column] ||= redirect_uri
- 768
create_params[oauth_grants_expires_in_column] ||= Sequel.date_add(Sequel::CURRENT_TIMESTAMP, seconds: oauth_grant_expires_in)
- 768
create_params[oauth_grants_scopes_column] ||= scopes.join(oauth_scope_separator)
- 768
if use_oauth_access_type? && (access_type = param_or_nil("access_type"))
- 24
create_params[oauth_grants_access_type_column] = access_type
end
- 768
ds = db[oauth_grants_table]
- 768
create_params[oauth_grants_code_column] = oauth_unique_id_generator
- 768
if oauth_reuse_access_token
- 384
unique_conds = Hash[oauth_grants_unique_columns.map { |column| [column, create_params[column]] }]
- 96
valid_grant = valid_oauth_grant_ds(unique_conds).select(oauth_grants_id_column).first
- 96
if valid_grant
- 96
create_params[oauth_grants_id_column] = valid_grant[oauth_grants_id_column]
- 96
rescue_from_uniqueness_error do
- 96
__insert_or_update_and_return__(
ds,
oauth_grants_id_column,
[oauth_grants_id_column],
create_params
)
end
- 96
return create_params[oauth_grants_code_column]
end
end
- 672
rescue_from_uniqueness_error do
- 708
if __one_oauth_token_per_account
- 354
__insert_or_update_and_return__(
ds,
oauth_grants_id_column,
oauth_grants_unique_columns,
create_params,
nil,
{
oauth_grants_expires_in_column => Sequel.date_add(Sequel::CURRENT_TIMESTAMP, seconds: oauth_grant_expires_in),
oauth_grants_revoked_at_column => nil
}
)
else
- 354
__insert_and_return__(ds, oauth_grants_id_column, create_params)
end
end
- 660
create_params[oauth_grants_code_column]
end
- 12
def normalize_redirect_uri_for_comparison(redirect_uri)
- 468
uri = URI(redirect_uri)
- 468
return redirect_uri unless uri.scheme == "http" && uri.port
- 48
hostname = uri.hostname
# https://www.rfc-editor.org/rfc/rfc8252#section-7.3
# ignore (potentially ephemeral) port number for native clients per RFC8252
- 16
begin
- 48
ip = IPAddr.new(hostname)
- 24
uri.port = nil if ip.loopback?
rescue IPAddr::InvalidAddressError
# https://www.rfc-editor.org/rfc/rfc8252#section-8.3
# Although the use of localhost is NOT RECOMMENDED, it is still allowed.
- 24
uri.port = nil if hostname == "localhost"
end
- 48
uri.to_s
end
end
end
# frozen_string_literal: true
- 12
require "time"
- 12
require "base64"
- 12
require "securerandom"
- 12
require "cgi"
- 12
require "digest/sha2"
- 12
require "rodauth/version"
- 12
require "rodauth/oauth"
- 12
require "rodauth/oauth/database_extensions"
- 12
require "rodauth/oauth/http_extensions"
- 12
module Rodauth
- 12
Feature.define(:oauth_base, :OauthBase) do
- 12
include OAuth::HTTPExtensions
- 12
EMPTY_HASH = {}.freeze
- 12
auth_value_methods(:http_request)
- 12
auth_value_methods(:http_request_cache)
- 12
before "token"
- 12
error_flash "Please authorize to continue", "require_authorization"
- 12
error_flash "You are not authorized to revoke this token", "revoke_unauthorized_account"
- 12
button "Cancel", "oauth_cancel"
- 12
auth_value_method :json_response_content_type, "application/json"
- 12
auth_value_method :oauth_grant_expires_in, 60 * 5 # 5 minutes
- 12
auth_value_method :oauth_access_token_expires_in, 60 * 60 # 60 minutes
- 12
auth_value_method :oauth_refresh_token_expires_in, 60 * 60 * 24 * 360 # 1 year
- 12
auth_value_method :oauth_unique_id_generation_retries, 3
- 12
auth_value_method :oauth_token_endpoint_auth_methods_supported, %w[client_secret_basic client_secret_post]
- 12
auth_value_method :oauth_grant_types_supported, %w[refresh_token]
- 12
auth_value_method :oauth_response_types_supported, []
- 12
auth_value_method :oauth_response_modes_supported, []
- 12
auth_value_method :oauth_valid_uri_schemes, %w[https]
- 12
auth_value_method :oauth_scope_separator, " "
# OAuth Grants
- 12
auth_value_method :oauth_grants_table, :oauth_grants
- 12
auth_value_method :oauth_grants_id_column, :id
- 8
%i[
account_id oauth_application_id type
redirect_uri code scopes
expires_in revoked_at
token refresh_token
- 4
].each do |column|
- 120
auth_value_method :"oauth_grants_#{column}_column", column
end
# Enables Token Hash
- 12
auth_value_method :oauth_grants_token_hash_column, :token
- 12
auth_value_method :oauth_grants_refresh_token_hash_column, :refresh_token
# Access Token reuse
- 12
auth_value_method :oauth_reuse_access_token, false
- 12
auth_value_method :oauth_applications_table, :oauth_applications
- 12
auth_value_method :oauth_applications_id_column, :id
- 8
%i[
account_id
name description scopes
client_id client_secret
homepage_url redirect_uri
token_endpoint_auth_method grant_types response_types response_modes
logo_uri tos_uri policy_uri jwks jwks_uri
contacts software_id software_version
- 4
].each do |column|
- 240
auth_value_method :"oauth_applications_#{column}_column", column
end
# Enables client secret Hash
- 12
auth_value_method :oauth_applications_client_secret_hash_column, :client_secret
- 12
auth_value_method :oauth_authorization_required_error_status, 401
- 12
auth_value_method :oauth_invalid_response_status, 400
- 12
auth_value_method :oauth_already_in_use_response_status, 409
# Feature options
- 12
auth_value_method :oauth_application_scopes, []
- 12
auth_value_method :oauth_token_type, "bearer"
- 12
auth_value_method :oauth_refresh_token_protection_policy, "rotation" # can be: none, sender_constrained, rotation
- 12
translatable_method :oauth_invalid_client_message, "Invalid client"
- 12
translatable_method :oauth_invalid_grant_type_message, "Invalid grant type"
- 12
translatable_method :oauth_invalid_grant_message, "Invalid grant"
- 12
translatable_method :oauth_invalid_scope_message, "Invalid scope"
- 12
translatable_method :oauth_unsupported_token_type_message, "Invalid token type hint"
- 12
translatable_method :oauth_already_in_use_message, "error generating unique token"
- 12
auth_value_method :oauth_already_in_use_error_code, "invalid_request"
- 12
auth_value_method :oauth_invalid_grant_type_error_code, "unsupported_grant_type"
- 12
auth_value_method :is_authorization_server?, true
- 12
auth_value_methods(:only_json?)
- 12
auth_value_method :json_request_regexp, %r{\bapplication/(?:vnd\.api\+)?json\b}i
# METADATA
- 12
auth_value_method :oauth_metadata_service_documentation, nil
- 12
auth_value_method :oauth_metadata_ui_locales_supported, nil
- 12
auth_value_method :oauth_metadata_op_policy_uri, nil
- 12
auth_value_method :oauth_metadata_op_tos_uri, nil
- 12
auth_value_methods(
:authorization_server_url,
:oauth_grants_unique_columns
)
- 12
auth_methods(
:fetch_access_token,
:secret_hash,
:generate_token_hash,
:secret_matches?,
:oauth_unique_id_generator,
:require_authorizable_account,
:oauth_account_ds,
:oauth_application_ds
)
# /token
- 12
auth_server_route(:token) do |r|
- 2184
require_oauth_application
- 1896
before_token_route
- 1896
r.post do
- 1896
catch_error do
- 1896
validate_token_params
- 1824
oauth_grant = nil
- 1824
transaction do
- 1824
before_token
- 1824
oauth_grant = create_token(param("grant_type"))
end
- 1176
json_response_success(json_access_token_payload(oauth_grant))
end
throw_json_response_error(oauth_invalid_response_status, "invalid_request")
end
end
- 12
def load_oauth_server_metadata_route(issuer = nil)
- 228
request.on(".well-known") do
- 228
request.get("oauth-authorization-server") do
- 228
json_response_success(oauth_server_metadata_body(issuer), true)
end
end
end
- 12
def check_csrf?
- 10452
case request.path
when token_path
- 2184
false
else
- 8268
super
end
end
- 12
def oauth_token_subject
- 132
return unless authorization_token
- 132
authorization_token[oauth_grants_account_id_column] ||
db[oauth_applications_table].where(
oauth_applications_id_column => authorization_token[oauth_grants_oauth_application_id_column]
).select_map(oauth_applications_client_id_column).first
end
- 12
def current_oauth_account
- 132
account_id = authorization_token[oauth_grants_account_id_column]
- 132
return unless account_id
- 108
oauth_account_ds(account_id).first
end
- 12
def current_oauth_application
- 156
oauth_application_ds(authorization_token[oauth_grants_oauth_application_id_column]).first
end
- 12
def accepts_json?
- 1836
return true if only_json?
- 1824
(accept = request.env["HTTP_ACCEPT"]) && accept =~ json_request_regexp
end
# copied from the jwt feature
- 12
def json_request?
- 240
return super if features.include?(:jsonn)
- 240
return @json_request if defined?(@json_request)
- 240
@json_request = request.content_type =~ json_request_regexp
end
- 12
def scopes
- 5940
scope = request.params["scope"]
- 5940
case scope
when Array
- 2340
scope
when String
- 3228
scope.split(" ")
end
end
- 12
def redirect_uri
- 4344
param_or_nil("redirect_uri") || begin
- 3504
return unless oauth_application
- 3504
redirect_uris = oauth_application[oauth_applications_redirect_uri_column].split(" ")
- 3504
redirect_uris.size == 1 ? redirect_uris.first : nil
end
end
- 12
def oauth_application
- 39810
return @oauth_application if defined?(@oauth_application)
- 1064
@oauth_application = begin
- 3192
client_id = param_or_nil("client_id")
- 3192
return unless client_id
- 3108
db[oauth_applications_table].filter(oauth_applications_client_id_column => client_id).first
end
end
- 12
def fetch_access_token
- 780
if (token = request.params["access_token"])
- 24
if request.post? && !(request.content_type.start_with?("application/x-www-form-urlencoded") &&
request.params.size == 1)
return
end
else
- 756
value = request.env["HTTP_AUTHORIZATION"]
- 756
return unless value && !value.empty?
- 672
scheme, token = value.split(" ", 2)
- 672
return unless scheme.downcase == oauth_token_type
end
- 696
return if token.nil? || token.empty?
- 612
token
end
- 12
def authorization_token
- 1092
return @authorization_token if defined?(@authorization_token)
# check if there is a token
- 348
access_token = fetch_access_token
- 348
return unless access_token
- 216
@authorization_token = oauth_grant_by_token(access_token)
end
- 12
def require_oauth_authorization(*scopes)
- 324
authorization_required unless authorization_token
- 168
token_scopes = authorization_token[oauth_grants_scopes_column].split(oauth_scope_separator)
- 360
authorization_required unless scopes.any? { |scope| token_scopes.include?(scope) }
end
- 12
def use_date_arithmetic?
- 4986
true
end
# override
- 12
def translate(key, default, args = EMPTY_HASH)
- 27552
return i18n_translate(key, default, **args) if features.include?(:i18n)
# do not attempt to translate by default
- 96
return default if args.nil?
- 96
default % args
end
- 12
def post_configure
- 5250
super
- 5250
i18n_register(File.expand_path(File.join(__dir__, "..", "..", "..", "locales"))) if features.include?(:i18n)
# all of the extensions below involve DB changes. Resource server mode doesn't use
# database functions for OAuth though.
- 5250
return unless is_authorization_server?
- 5082
self.class.__send__(:include, Rodauth::OAuth::ExtendDatabase(db))
# Check whether we can reutilize db entries for the same account / application pair
- 5082
one_oauth_token_per_account = db.indexes(oauth_grants_table).values.any? do |definition|
- 25416
definition[:unique] &&
definition[:columns] == oauth_grants_unique_columns
end
- 6786
self.class.send(:define_method, :__one_oauth_token_per_account) { one_oauth_token_per_account }
end
- 12
private
- 12
def oauth_account_ds(account_id)
- 252
account_ds(account_id)
end
- 12
def oauth_application_ds(oauth_application_id)
- 156
db[oauth_applications_table].where(oauth_applications_id_column => oauth_application_id)
end
- 12
def require_authorizable_account
- 3168
require_account
end
- 12
def rescue_from_uniqueness_error(&block)
- 2592
retries = oauth_unique_id_generation_retries
- 864
begin
- 2664
transaction(savepoint: :only, &block)
- 96
rescue Sequel::UniqueConstraintViolation
- 96
redirect_response_error("already_in_use") if retries.zero?
- 72
retries -= 1
- 72
retry
end
end
# OAuth Token Unique/Reuse
- 12
def oauth_grants_unique_columns
- 8804
[
- 17608
oauth_grants_oauth_application_id_column,
oauth_grants_account_id_column,
oauth_grants_scopes_column
]
end
- 12
def authorization_server_url
- 1686
base_url
end
- 12
def template_path(page)
- 59802
path = File.join(File.dirname(__FILE__), "../../../templates", "#{page}.str")
- 59802
return super unless File.exist?(path)
- 2172
path
end
# to be used internally. Same semantics as require account, must:
# fetch an authorization basic header
# parse client id and secret
#
- 12
def require_oauth_application
- 2100
@oauth_application = if (token = ((v = request.env["HTTP_AUTHORIZATION"]) && v[/\A *Basic (.*)\Z/, 1]))
# client_secret_basic
- 588
require_oauth_application_from_client_secret_basic(token)
- 1512
elsif (client_id = param_or_nil("client_id"))
- 1428
if (client_secret = param_or_nil("client_secret"))
# client_secret_post
- 960
require_oauth_application_from_client_secret_post(client_id, client_secret)
else
# none
- 468
require_oauth_application_from_none(client_id)
end
else
- 84
authorization_required
end
end
- 12
def require_oauth_application_from_client_secret_basic(token)
- 588
client_id, client_secret = Base64.decode64(token).split(":", 2)
- 588
authorization_required unless client_id
- 588
oauth_application = db[oauth_applications_table].where(oauth_applications_client_id_column => client_id).first
- 392
authorization_required unless supports_auth_method?(oauth_application,
- 196
"client_secret_basic") && secret_matches?(oauth_application, client_secret)
- 564
oauth_application
end
- 12
def require_oauth_application_from_client_secret_post(client_id, client_secret)
- 960
oauth_application = db[oauth_applications_table].where(oauth_applications_client_id_column => client_id).first
- 640
authorization_required unless supports_auth_method?(oauth_application,
- 320
"client_secret_post") && secret_matches?(oauth_application, client_secret)
- 936
oauth_application
end
- 12
def require_oauth_application_from_none(client_id)
- 468
oauth_application = db[oauth_applications_table].where(oauth_applications_client_id_column => client_id).first
- 468
authorization_required unless supports_auth_method?(oauth_application, "none")
- 360
oauth_application
end
- 12
def supports_auth_method?(oauth_application, auth_method)
- 2280
return false unless oauth_application
- 2244
supported_auth_methods = if oauth_application[oauth_applications_token_endpoint_auth_method_column]
- 660
oauth_application[oauth_applications_token_endpoint_auth_method_column].split(/ +/)
else
- 1584
oauth_token_endpoint_auth_methods_supported
end
- 2244
supported_auth_methods.include?(auth_method)
end
- 12
def require_oauth_application_from_account
- 12
ds = db[oauth_applications_table]
.join(oauth_grants_table, Sequel[oauth_grants_table][oauth_grants_oauth_application_id_column] =>
Sequel[oauth_applications_table][oauth_applications_id_column])
.where(oauth_grant_by_token_ds(param("token")).opts.fetch(:where, true))
.where(Sequel[oauth_applications_table][oauth_applications_account_id_column] => account_id)
- 12
@oauth_application = ds.qualify.first
- 12
return if @oauth_application
set_redirect_error_flash revoke_unauthorized_account_error_flash
redirect request.referer || "/"
end
- 12
def secret_matches?(oauth_application, secret)
- 1500
if oauth_applications_client_secret_hash_column
- 1500
BCrypt::Password.new(oauth_application[oauth_applications_client_secret_hash_column]) == secret
else
oauth_application[oauth_applications_client_secret_column] == secret
end
end
- 12
def set_client_secret(params, secret)
- 648
if oauth_applications_client_secret_hash_column
- 648
params[oauth_applications_client_secret_hash_column] = secret_hash(secret)
else
params[oauth_applications_client_secret_column] = secret
end
end
- 12
def secret_hash(secret)
- 1548
password_hash(secret)
end
- 12
def oauth_unique_id_generator
- 4188
SecureRandom.urlsafe_base64(32)
end
- 12
def generate_token_hash(token)
- 300
Base64.urlsafe_encode64(Digest::SHA256.digest(token))
end
- 12
def grant_from_application?(oauth_grant, oauth_application)
- 204
oauth_grant[oauth_grants_oauth_application_id_column] == oauth_application[oauth_applications_id_column]
end
- 12
def password_hash(password)
- 1548
return super if features.include?(:login_password_requirements_base)
BCrypt::Password.create(password, cost: BCrypt::Engine::DEFAULT_COST)
end
- 12
def generate_token(grant_params = {}, should_generate_refresh_token = true)
- 1092
if grant_params[oauth_grants_id_column] && (oauth_reuse_access_token &&
(
- 192
if oauth_grants_token_hash_column
- 96
grant_params[oauth_grants_token_hash_column]
else
- 96
grant_params[oauth_grants_token_column]
end
))
- 96
return grant_params
end
- 332
update_params = {
- 664
oauth_grants_expires_in_column => Sequel.date_add(Sequel::CURRENT_TIMESTAMP, seconds: oauth_access_token_expires_in),
oauth_grants_code_column => nil
}
- 996
rescue_from_uniqueness_error do
- 996
access_token = _generate_access_token(update_params)
- 996
refresh_token = _generate_refresh_token(update_params) if should_generate_refresh_token
- 996
oauth_grant = store_token(grant_params, update_params)
- 996
return unless oauth_grant
- 996
oauth_grant[oauth_grants_token_column] = access_token
- 996
oauth_grant[oauth_grants_refresh_token_column] = refresh_token if refresh_token
- 996
oauth_grant
end
end
- 12
def _generate_access_token(params = {})
- 636
token = oauth_unique_id_generator
- 636
if oauth_grants_token_hash_column
- 108
params[oauth_grants_token_hash_column] = generate_token_hash(token)
else
- 528
params[oauth_grants_token_column] = token
end
- 636
token
end
- 12
def _generate_refresh_token(params)
- 636
token = oauth_unique_id_generator
- 636
if oauth_grants_refresh_token_hash_column
- 108
params[oauth_grants_refresh_token_hash_column] = generate_token_hash(token)
else
- 528
params[oauth_grants_refresh_token_column] = token
end
- 636
token
end
- 12
def _grant_with_access_token?(oauth_grant)
if oauth_grants_token_hash_column
oauth_grant[oauth_grants_token_hash_column]
else
oauth_grant[oauth_grants_token_column]
end
end
- 12
def store_token(grant_params, update_params = {})
- 996
ds = db[oauth_grants_table]
- 996
if __one_oauth_token_per_account
- 166
to_update_if_null = [
- 332
oauth_grants_token_column,
oauth_grants_token_hash_column,
oauth_grants_refresh_token_column,
oauth_grants_refresh_token_hash_column
].compact.map do |attribute|
- 368
[
- 736
attribute,
(
- 1104
if ds.respond_to?(:supports_insert_conflict?) && ds.supports_insert_conflict?
- 552
Sequel.function(:coalesce, Sequel[oauth_grants_table][attribute], Sequel[:excluded][attribute])
else
- 552
Sequel.function(:coalesce, Sequel[oauth_grants_table][attribute], update_params[attribute])
end
)
]
end
- 498
token = __insert_or_update_and_return__(
ds,
oauth_grants_id_column,
oauth_grants_unique_columns,
grant_params.merge(update_params),
Sequel.expr(Sequel[oauth_grants_table][oauth_grants_expires_in_column]) > Sequel::CURRENT_TIMESTAMP,
Hash[to_update_if_null]
)
# if the previous operation didn't return a row, it means that the conditions
# invalidated the update, and the existing token is still valid.
- 498
token || ds.where(
oauth_grants_account_id_column => update_params[oauth_grants_account_id_column],
oauth_grants_oauth_application_id_column => update_params[oauth_grants_oauth_application_id_column]
).first
else
- 498
if oauth_reuse_access_token
- 192
unique_conds = Hash[oauth_grants_unique_columns.map { |column| [column, update_params[column]] }]
- 48
valid_token_ds = valid_oauth_grant_ds(unique_conds)
- 48
if oauth_grants_token_hash_column
- 24
valid_token_ds.exclude(oauth_grants_token_hash_column => nil)
else
- 24
valid_token_ds.exclude(oauth_grants_token_column => nil)
end
- 48
valid_token = valid_token_ds.first
- 48
return valid_token if valid_token
end
- 498
if grant_params[oauth_grants_id_column]
- 420
__update_and_return__(ds.where(oauth_grants_id_column => grant_params[oauth_grants_id_column]), update_params)
else
- 78
__insert_and_return__(ds, oauth_grants_id_column, grant_params.merge(update_params))
end
end
end
- 12
def valid_locked_oauth_grant(grant_params = nil)
- 1164
oauth_grant = valid_oauth_grant_ds(grant_params).for_update.first
- 1164
redirect_response_error("invalid_grant") unless oauth_grant
- 972
oauth_grant
end
- 12
def valid_oauth_grant_ds(grant_params = nil)
- 2088
ds = db[oauth_grants_table]
.where(Sequel[oauth_grants_table][oauth_grants_revoked_at_column] => nil)
.where(Sequel.expr(Sequel[oauth_grants_table][oauth_grants_expires_in_column]) >= Sequel::CURRENT_TIMESTAMP)
- 2088
ds = ds.where(grant_params) if grant_params
- 2088
ds
end
- 12
def oauth_grant_by_token_ds(token)
- 444
ds = valid_oauth_grant_ds
- 444
if oauth_grants_token_hash_column
- 48
ds.where(Sequel[oauth_grants_table][oauth_grants_token_hash_column] => generate_token_hash(token))
else
- 396
ds.where(Sequel[oauth_grants_table][oauth_grants_token_column] => token)
end
end
- 12
def oauth_grant_by_token(token)
- 372
oauth_grant_by_token_ds(token).first
end
- 12
def oauth_grant_by_refresh_token_ds(token, revoked: false)
- 396
ds = db[oauth_grants_table].where(oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column])
#
# filter expired refresh tokens out.
# an expired refresh token is a token whose access token expired for a period longer than the
# refresh token expiration period.
#
- 396
ds = ds.where(Sequel.date_add(oauth_grants_expires_in_column,
- 396
seconds: (oauth_refresh_token_expires_in - oauth_access_token_expires_in)) >= Sequel::CURRENT_TIMESTAMP)
- 396
ds = if oauth_grants_refresh_token_hash_column
- 36
ds.where(oauth_grants_refresh_token_hash_column => generate_token_hash(token))
else
- 360
ds.where(oauth_grants_refresh_token_column => token)
end
- 396
ds = ds.where(oauth_grants_revoked_at_column => nil) unless revoked
- 396
ds
end
- 12
def oauth_grant_by_refresh_token(token, **kwargs)
- 96
oauth_grant_by_refresh_token_ds(token, **kwargs).first
end
- 12
def json_access_token_payload(oauth_grant)
- 420
payload = {
- 840
"access_token" => oauth_grant[oauth_grants_token_column],
"token_type" => oauth_token_type,
"expires_in" => oauth_access_token_expires_in
}
- 1260
payload["refresh_token"] = oauth_grant[oauth_grants_refresh_token_column] if oauth_grant[oauth_grants_refresh_token_column]
- 1260
payload
end
# Access Tokens
- 12
def validate_token_params
- 1836
unless (grant_type = param_or_nil("grant_type"))
- 60
redirect_response_error("invalid_request")
end
- 1776
redirect_response_error("invalid_request") if grant_type == "refresh_token" && !param_or_nil("refresh_token")
end
- 12
def create_token(grant_type)
- 432
redirect_response_error("invalid_request") unless supported_grant_type?(grant_type, "refresh_token")
- 300
refresh_token = param("refresh_token")
# fetch potentially revoked oauth token
- 300
oauth_grant = oauth_grant_by_refresh_token_ds(refresh_token, revoked: true).for_update.first
- 300
update_params = { oauth_grants_expires_in_column => Sequel.date_add(Sequel::CURRENT_TIMESTAMP,
seconds: oauth_access_token_expires_in) }
- 300
if !oauth_grant || oauth_grant[oauth_grants_revoked_at_column]
- 144
redirect_response_error("invalid_grant")
- 156
elsif oauth_refresh_token_protection_policy == "rotation"
# https://tools.ietf.org/html/draft-ietf-oauth-v2-1-00#section-6.1
#
# If a refresh token is compromised and subsequently used by both the attacker and the legitimate
# client, one of them will present an invalidated refresh token, which will inform the authorization
# server of the breach. The authorization server cannot determine which party submitted the invalid
# refresh token, but it will revoke the active refresh token. This stops the attack at the cost of
# forcing the legitimate client to obtain a fresh authorization grant.
- 72
refresh_token = _generate_refresh_token(update_params)
end
- 156
update_params[oauth_grants_oauth_application_id_column] = oauth_grant[oauth_grants_oauth_application_id_column]
- 156
oauth_grant = create_token_from_token(oauth_grant, update_params)
- 144
oauth_grant[oauth_grants_refresh_token_column] = refresh_token
- 144
oauth_grant
end
- 12
def create_token_from_token(oauth_grant, update_params)
- 156
redirect_response_error("invalid_grant") unless grant_from_application?(oauth_grant, oauth_application)
- 156
rescue_from_uniqueness_error do
- 192
oauth_grants_ds = db[oauth_grants_table].where(oauth_grants_id_column => oauth_grant[oauth_grants_id_column])
- 192
access_token = _generate_access_token(update_params)
- 192
oauth_grant = __update_and_return__(oauth_grants_ds, update_params)
- 144
oauth_grant[oauth_grants_token_column] = access_token
- 144
oauth_grant
end
end
- 12
def supported_grant_type?(grant_type, expected_grant_type = grant_type)
- 2172
return false unless grant_type == expected_grant_type
- 1740
grant_types_supported = if oauth_application[oauth_applications_grant_types_column]
- 48
oauth_application[oauth_applications_grant_types_column].split(/ +/)
else
- 1692
oauth_grant_types_supported
end
- 1740
grant_types_supported.include?(grant_type)
end
- 12
def supported_response_type?(response_type, expected_response_type = response_type)
- 972
return false unless response_type == expected_response_type
- 972
response_types_supported = if oauth_application[oauth_applications_grant_types_column]
- 12
oauth_application[oauth_applications_response_types_column].split(/ +/)
else
- 960
oauth_response_types_supported
end
- 972
response_types = response_type.split(/ +/)
- 972
(response_types - response_types_supported).empty?
end
- 12
def supported_response_mode?(response_mode, expected_response_mode = response_mode)
- 960
return false unless response_mode == expected_response_mode
- 960
response_modes_supported = if oauth_application[oauth_applications_response_modes_column]
oauth_application[oauth_applications_response_modes_column].split(/ +/)
else
- 960
oauth_response_modes_supported
end
- 960
response_modes_supported.include?(response_mode)
end
- 12
def oauth_server_metadata_body(path = nil)
- 312
issuer = base_url
- 312
issuer += "/#{path}" if path
- 104
{
- 208
issuer: issuer,
token_endpoint: token_url,
scopes_supported: oauth_application_scopes,
response_types_supported: oauth_response_types_supported,
response_modes_supported: oauth_response_modes_supported,
grant_types_supported: oauth_grant_types_supported,
token_endpoint_auth_methods_supported: oauth_token_endpoint_auth_methods_supported,
service_documentation: oauth_metadata_service_documentation,
ui_locales_supported: oauth_metadata_ui_locales_supported,
op_policy_uri: oauth_metadata_op_policy_uri,
op_tos_uri: oauth_metadata_op_tos_uri
}
end
- 12
def redirect_response_error(error_code, message = nil)
- 1320
if accepts_json?
- 780
status_code = if respond_to?(:"oauth_#{error_code}_response_status")
- 12
send(:"oauth_#{error_code}_response_status")
else
- 768
oauth_invalid_response_status
end
- 780
throw_json_response_error(status_code, error_code, message)
else
- 540
redirect_url = redirect_uri || request.referer || default_redirect
- 540
redirect_url = URI.parse(redirect_url)
- 540
params = response_error_params(error_code, message)
- 540
state = param_or_nil("state")
- 540
params["state"] = state if state
- 540
_redirect_response_error(redirect_url, params)
end
end
- 12
def _redirect_response_error(redirect_url, params)
- 360
params = URI.encode_www_form(params)
- 360
if redirect_url.query
params << "&" unless params.empty?
params << redirect_url.query
end
- 360
redirect_url.query = params
- 360
redirect(redirect_url.to_s)
end
- 12
def response_error_params(error_code, message = nil)
- 2676
code = if respond_to?(:"oauth_#{error_code}_error_code")
- 60
send(:"oauth_#{error_code}_error_code")
else
- 2616
error_code
end
- 2676
payload = { "error" => code }
- 2676
error_description = message
- 2676
error_description ||= send(:"oauth_#{error_code}_message") if respond_to?(:"oauth_#{error_code}_message")
- 2676
payload["error_description"] = error_description if error_description
- 2676
payload
end
- 12
def json_response_success(body, cache = false)
- 1908
response.status = 200
- 1908
response["Content-Type"] ||= json_response_content_type
- 1908
if cache
# defaulting to 1-day for everyone, for now at least
- 348
max_age = 60 * 60 * 24
- 348
response["Cache-Control"] = "private, max-age=#{max_age}"
else
- 1560
response["Cache-Control"] = "no-store"
- 1560
response["Pragma"] = "no-cache"
end
- 1908
json_payload = _json_response_body(body)
- 1908
return_response(json_payload)
end
- 12
def throw_json_response_error(status, error_code, message = nil)
- 2136
set_response_error_status(status)
- 2136
payload = response_error_params(error_code, message)
- 2136
json_payload = _json_response_body(payload)
- 2136
response["Content-Type"] ||= json_response_content_type
- 2136
response["WWW-Authenticate"] = oauth_token_type.upcase if status == 401
- 2136
return_response(json_payload)
end
- 12
def _json_response_body(hash)
- 4692
return super if features.include?(:json)
- 4692
if request.respond_to?(:convert_to_json)
request.send(:convert_to_json, hash)
else
- 4692
JSON.dump(hash)
end
end
- 12
if Gem::Version.new(Rodauth.version) < Gem::Version.new("2.23")
def return_response(body = nil)
response.write(body) if body
request.halt
end
end
- 12
def authorization_required
- 192
throw_json_response_error(oauth_authorization_required_error_status, "invalid_client")
end
- 12
def check_valid_scopes?(scp = scopes)
- 2232
return false unless scp
- 2232
(scp - oauth_application[oauth_applications_scopes_column].split(oauth_scope_separator)).empty?
end
- 12
def check_valid_uri?(uri)
- 8676
URI::DEFAULT_PARSER.make_regexp(oauth_valid_uri_schemes).match?(uri)
end
- 12
def check_valid_no_fragment_uri?(uri)
- 2676
check_valid_uri?(uri) && URI.parse(uri).fragment.nil?
end
# Resource server mode
- 12
def authorization_server_metadata
- 48
auth_url = URI(authorization_server_url).dup
- 48
auth_url.path = "/.well-known/oauth-authorization-server"
- 48
http_request_with_cache(auth_url)
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_client_credentials_grant, :OauthClientCredentialsGrant) do
- 12
depends :oauth_base
- 12
def oauth_grant_types_supported
- 96
super | %w[client_credentials]
end
- 12
private
- 12
def create_token(grant_type)
- 72
return super unless supported_grant_type?(grant_type, "client_credentials")
- 60
grant_scopes = scopes
- 60
grant_scopes = if grant_scopes
- 12
redirect_response_error("invalid_scope") unless check_valid_scopes?
- 12
grant_scopes.join(oauth_scope_separator)
else
- 48
oauth_application[oauth_applications_scopes_column]
end
- 20
grant_params = {
- 40
oauth_grants_type_column => "client_credentials",
oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column],
oauth_grants_scopes_column => grant_scopes
}
- 60
generate_token(grant_params, false)
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_device_code_grant, :OauthDeviceCodeGrant) do
- 12
depends :oauth_authorize_base
- 12
before "device_authorization"
- 12
before "device_verification"
- 12
notice_flash "The device is verified", "device_verification"
- 12
error_flash "No device to authorize with the given user code", "user_code_not_found"
- 12
view "device_verification", "Device Verification", "device_verification"
- 12
view "device_search", "Device Search", "device_search"
- 12
button "Verify", "oauth_device_verification"
- 12
button "Search", "oauth_device_search"
- 12
auth_value_method :oauth_grants_user_code_column, :user_code
- 12
auth_value_method :oauth_grants_last_polled_at_column, :last_polled_at
- 12
translatable_method :oauth_device_search_page_lead, "Insert the user code from the device you'd like to authorize."
- 12
translatable_method :oauth_device_verification_page_lead, "The device with user code %<user_code>s would like to access your data."
- 12
translatable_method :oauth_expired_token_message, "the device code has expired"
- 12
translatable_method :oauth_access_denied_message, "the authorization request has been denied"
- 12
translatable_method :oauth_authorization_pending_message, "the authorization request is still pending"
- 12
translatable_method :oauth_slow_down_message, "authorization request is still pending but poll interval should be increased"
- 12
auth_value_method :oauth_device_code_grant_polling_interval, 5 # seconds
- 12
auth_value_method :oauth_device_code_grant_user_code_size, 8 # characters
- 12
%w[user_code].each do |param|
- 12
auth_value_method :"oauth_grant_#{param}_param", param
end
- 12
translatable_method :oauth_grant_user_code_label, "User code"
- 12
auth_methods(
:generate_user_code
)
# /device-authorization
- 12
auth_server_route(:device_authorization) do |r|
- 24
require_oauth_application
- 24
before_device_authorization_route
- 24
r.post do
- 24
user_code = generate_user_code
- 24
device_code = transaction do
- 24
before_device_authorization
- 24
create_oauth_grant(
oauth_grants_type_column => "device_code",
oauth_grants_user_code_column => user_code
)
end
- 24
json_response_success \
"device_code" => device_code,
"user_code" => user_code,
"verification_uri" => device_url,
"verification_uri_complete" => device_url(user_code: user_code),
"expires_in" => oauth_grant_expires_in,
"interval" => oauth_device_code_grant_polling_interval
end
end
# /device
- 12
auth_server_route(:device) do |r|
- 252
require_authorizable_account
- 240
before_device_route
- 240
r.get do
- 204
if (user_code = param_or_nil("user_code"))
- 72
oauth_grant = valid_oauth_grant_ds(oauth_grants_user_code_column => user_code).first
- 72
unless oauth_grant
- 36
set_redirect_error_flash user_code_not_found_error_flash
- 36
redirect device_path
end
- 36
scope.instance_variable_set(:@oauth_grant, oauth_grant)
- 36
device_verification_view
else
- 132
device_search_view
end
end
- 36
r.post do
- 36
catch_error do
- 36
unless (user_code = param_or_nil("user_code")) && !user_code.empty?
- 12
set_redirect_error_flash oauth_invalid_grant_message
- 12
redirect device_path
end
- 24
transaction do
- 24
before_device_verification
- 24
create_token("device_code")
end
end
- 24
set_notice_flash device_verification_notice_flash
- 24
redirect device_path
end
end
- 12
def check_csrf?
- 564
case request.path
when device_authorization_path
- 24
false
else
- 540
super
end
end
- 12
def oauth_grant_types_supported
- 132
super | %w[urn:ietf:params:oauth:grant-type:device_code]
end
- 12
private
- 12
def generate_user_code
- 24
user_code_size = oauth_device_code_grant_user_code_size
- 16
SecureRandom.random_number(36**user_code_size)
.to_s(36) # 0 to 9, a to z
.upcase
- 8
.rjust(user_code_size, "0")
end
# TODO: think about removing this and recommend PKCE
- 12
def supports_auth_method?(oauth_application, auth_method)
- 156
return super unless auth_method == "none"
- 132
request.path == device_authorization_path || request.params.key?("device_code") || super
end
- 12
def create_token(grant_type)
- 144
if supported_grant_type?(grant_type, "urn:ietf:params:oauth:grant-type:device_code")
- 120
oauth_grant = db[oauth_grants_table].where(
oauth_grants_type_column => "device_code",
oauth_grants_code_column => param("device_code"),
oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column]
).for_update.first
- 120
throw_json_response_error(oauth_invalid_response_status, "invalid_grant") unless oauth_grant
- 108
now = Time.now
- 108
if oauth_grant[oauth_grants_user_code_column].nil?
- 16
return create_token_from_authorization_code(
{ oauth_grants_id_column => oauth_grant[oauth_grants_id_column] },
oauth_grant: oauth_grant
- 8
)
end
- 84
if oauth_grant[oauth_grants_revoked_at_column]
- 24
throw_json_response_error(oauth_invalid_response_status, "access_denied")
- 60
elsif oauth_grant[oauth_grants_expires_in_column] < now
- 12
throw_json_response_error(oauth_invalid_response_status, "expired_token")
else
- 48
last_polled_at = oauth_grant[oauth_grants_last_polled_at_column]
- 48
if last_polled_at && convert_timestamp(last_polled_at) + oauth_device_code_grant_polling_interval > now
- 12
throw_json_response_error(oauth_invalid_response_status, "slow_down")
else
- 36
db[oauth_grants_table].where(oauth_grants_id_column => oauth_grant[oauth_grants_id_column])
- 12
.update(oauth_grants_last_polled_at_column => Sequel::CURRENT_TIMESTAMP)
- 36
throw_json_response_error(oauth_invalid_response_status, "authorization_pending")
end
end
- 24
elsif grant_type == "device_code"
# fetch oauth grant
- 24
rs = valid_oauth_grant_ds(
oauth_grants_user_code_column => param("user_code")
).update(oauth_grants_user_code_column => nil, oauth_grants_type_column => "device_code")
- 24
rs if rs.positive?
else
super
end
end
- 12
def validate_token_params
- 132
grant_type = param_or_nil("grant_type")
- 132
if grant_type == "urn:ietf:params:oauth:grant-type:device_code" && !param_or_nil("device_code")
- 12
redirect_response_error("invalid_request")
end
- 120
super
end
- 12
def store_token(grant_params, update_params = {})
- 24
return super unless grant_params[oauth_grants_user_code_column]
# do not clean up device code just yet
update_params.delete(oauth_grants_code_column)
update_params[oauth_grants_user_code_column] = nil
update_params.merge!(resource_params)
super(grant_params, update_params)
end
- 12
def oauth_server_metadata_body(*)
- 12
super.tap do |data|
- 12
data[:device_authorization_endpoint] = device_authorization_url
end
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_dynamic_client_registration, :OauthDynamicClientRegistration) do
- 12
depends :oauth_base
- 12
before "register"
- 12
auth_value_method :oauth_client_registration_required_params, %w[redirect_uris client_name]
- 12
auth_value_method :oauth_applications_registration_access_token_column, :registration_access_token
- 12
auth_value_method :registration_client_uri_route, "register"
- 12
PROTECTED_APPLICATION_ATTRIBUTES = %w[account_id client_id].freeze
- 12
def load_registration_client_uri_routes
- 48
request.on(registration_client_uri_route) do
# CLIENT REGISTRATION URI
- 48
request.on(String) do |client_id|
- 48
(token = ((v = request.env["HTTP_AUTHORIZATION"]) && v[/\A *Bearer (.*)\Z/, 1]))
- 48
next unless token
- 48
oauth_application = db[oauth_applications_table]
.where(oauth_applications_client_id_column => client_id)
.first
- 48
next unless oauth_application
- 48
authorization_required unless password_hash_match?(oauth_application[oauth_applications_registration_access_token_column], token)
- 48
request.is do
- 48
request.get do
- 12
json_response_oauth_application(oauth_application)
end
- 36
request.on method: :put do
- 16
%w[client_id registration_access_token registration_client_uri client_secret_expires_at
- 8
client_id_issued_at].each do |prohibited_param|
- 72
if request.params.key?(prohibited_param)
- 12
register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(prohibited_param))
end
end
- 12
validate_client_registration_params
# if the client includes the "client_secret" field in the request, the value of this field MUST match the currently
# issued client secret for that client. The client MUST NOT be allowed to overwrite its existing client secret with
# its own chosen value.
- 12
authorization_required if request.params.key?("client_secret") && secret_matches?(oauth_application,
request.params["client_secret"])
- 12
oauth_application = transaction do
- 12
applications_ds = db[oauth_applications_table]
- 12
__update_and_return__(applications_ds, @oauth_application_params)
end
- 12
json_response_oauth_application(oauth_application)
end
- 12
request.on method: :delete do
- 12
applications_ds = db[oauth_applications_table]
- 12
applications_ds.where(oauth_applications_client_id_column => client_id).delete
- 12
response.status = 204
- 12
response["Cache-Control"] = "no-store"
- 12
response["Pragma"] = "no-cache"
- 12
response.finish
end
end
end
end
end
# /register
- 12
auth_server_route(:register) do |r|
- 1308
before_register_route
- 1308
r.post do
- 1308
oauth_client_registration_required_params.each do |required_param|
- 2568
unless request.params.key?(required_param)
- 48
register_throw_json_response_error("invalid_client_metadata", register_required_param_message(required_param))
end
end
- 1260
validate_client_registration_params
- 624
response_params = transaction do
- 624
before_register
- 624
do_register
end
- 624
response.status = 201
- 624
response["Content-Type"] = json_response_content_type
- 624
response["Cache-Control"] = "no-store"
- 624
response["Pragma"] = "no-cache"
- 624
response.write(_json_response_body(response_params))
end
end
- 12
def check_csrf?
- 1356
case request.path
when register_path
- 1308
false
else
- 48
super
end
end
- 12
private
- 12
def _before_register
raise %{dynamic client registration requires authentication.
Override ´before_register` to perform it.
example:
before_register do
account = _account_from_login(request.env["HTTP_X_USER_EMAIL"])
authorization_required unless account
@oauth_application_params[:account_id] = account[:id]
end
}
end
- 12
def validate_client_registration_params(request_params = request.params)
- 1296
@oauth_application_params = request_params.each_with_object({}) do |(key, value), params|
- 15804
case key
when "redirect_uris"
- 1260
if value.is_a?(Array)
- 1248
value = value.each do |uri|
- 2376
unless check_valid_no_fragment_uri?(uri)
- 24
register_throw_json_response_error("invalid_redirect_uri",
register_invalid_uri_message(uri))
end
end.join(" ")
else
- 12
register_throw_json_response_error("invalid_redirect_uri", register_invalid_uri_message(value))
end
- 1224
key = oauth_applications_redirect_uri_column
when "token_endpoint_auth_method"
- 612
unless oauth_token_endpoint_auth_methods_supported.include?(value)
- 12
register_throw_json_response_error("invalid_client_metadata", register_invalid_client_metadata_message(key, value))
end
# verify if in range
- 600
key = oauth_applications_token_endpoint_auth_method_column
when "grant_types"
- 672
if value.is_a?(Array)
- 660
value = value.each do |grant_type|
- 1212
unless oauth_grant_types_supported.include?(grant_type)
- 24
register_throw_json_response_error("invalid_client_metadata", register_invalid_client_metadata_message(grant_type, value))
end
end.join(" ")
else
- 12
register_throw_json_response_error("invalid_client_metadata", register_invalid_client_metadata_message(key, value))
end
- 636
key = oauth_applications_grant_types_column
when "response_types"
- 696
if value.is_a?(Array)
- 684
grant_types = request_params["grant_types"] || %w[authorization_code]
- 684
value = value.each do |response_type|
- 696
unless oauth_response_types_supported.include?(response_type)
- 12
register_throw_json_response_error("invalid_client_metadata",
register_invalid_response_type_message(response_type))
end
- 684
validate_client_registration_response_type(response_type, grant_types)
end.join(" ")
else
- 12
register_throw_json_response_error("invalid_client_metadata", register_invalid_client_metadata_message(key, value))
end
- 624
key = oauth_applications_response_types_column
# verify if in range and match grant type
when "client_uri", "logo_uri", "tos_uri", "policy_uri", "jwks_uri"
- 5808
register_throw_json_response_error("invalid_client_metadata", register_invalid_uri_message(value)) unless check_valid_uri?(value)
- 5748
case key
when "client_uri"
- 1200
key = oauth_applications_homepage_url_column
when "jwks_uri"
- 1092
if request_params.key?("jwks")
- 12
register_throw_json_response_error("invalid_client_metadata",
register_invalid_jwks_param_message(key, "jwks"))
end
end
- 5736
key = __send__(:"oauth_applications_#{key}_column")
when "jwks"
- 24
register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(value)) unless value.is_a?(Hash)
- 12
if request_params.key?("jwks_uri")
register_throw_json_response_error("invalid_client_metadata",
register_invalid_jwks_param_message(key, "jwks_uri"))
end
- 12
key = oauth_applications_jwks_column
- 12
value = JSON.dump(value)
when "scope"
- 1212
register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(value)) unless value.is_a?(String)
- 1212
scopes = value.split(" ") - oauth_application_scopes
- 1212
register_throw_json_response_error("invalid_client_metadata", register_invalid_scopes_message(value)) unless scopes.empty?
- 1188
key = oauth_applications_scopes_column
# verify if in range
when "contacts"
- 1164
register_throw_json_response_error("invalid_client_metadata", register_invalid_contacts_message(value)) unless value.is_a?(Array)
- 1152
value = value.join(" ")
- 1152
key = oauth_applications_contacts_column
when "client_name"
- 1212
register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(value)) unless value.is_a?(String)
- 1212
key = oauth_applications_name_column
when "require_signed_request_object"
- 36
unless respond_to?(:oauth_applications_require_signed_request_object_column)
register_throw_json_response_error("invalid_client_metadata",
register_invalid_param_message(key))
end
- 36
request_params[key] = value = convert_to_boolean(key, value)
- 24
key = oauth_applications_require_signed_request_object_column
when "require_pushed_authorization_requests"
- 36
unless respond_to?(:oauth_applications_require_pushed_authorization_requests_column)
register_throw_json_response_error("invalid_client_metadata",
register_invalid_param_message(key))
end
- 36
request_params[key] = value = convert_to_boolean(key, value)
- 24
key = oauth_applications_require_pushed_authorization_requests_column
when "tls_client_certificate_bound_access_tokens"
- 12
property = :oauth_applications_tls_client_certificate_bound_access_tokens_column
- 12
register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(key)) unless respond_to?(property)
- 12
request_params[key] = value = convert_to_boolean(key, value)
- 12
key = oauth_applications_tls_client_certificate_bound_access_tokens_column
when /\Atls_client_auth_/
- 84
unless respond_to?(:"oauth_applications_#{key}_column")
register_throw_json_response_error("invalid_client_metadata",
register_invalid_param_message(key))
end
# client using the tls_client_auth authentication method MUST use exactly one of the below metadata
# parameters to indicate the certificate subject value that the authorization server is to expect when
# authenticating the respective client.
- 1020
if params.any? { |k, _| k.to_s.start_with?("tls_client_auth_") }
- 12
register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(key))
end
- 72
key = __send__(:"oauth_applications_#{key}_column")
else
- 2976
if respond_to?(:"oauth_applications_#{key}_column")
- 2916
if PROTECTED_APPLICATION_ATTRIBUTES.include?(key)
- 12
register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(key))
end
- 2904
property = :"oauth_applications_#{key}_column"
- 2904
key = __send__(property)
- 60
elsif !db[oauth_applications_table].columns.include?(key.to_sym)
- 36
register_throw_json_response_error("invalid_client_metadata", register_invalid_param_message(key))
end
end
- 15444
params[key] = value
end
end
- 12
def validate_client_registration_response_type(response_type, grant_types)
- 636
case response_type
when "code"
- 564
unless grant_types.include?("authorization_code")
register_throw_json_response_error("invalid_client_metadata",
register_invalid_response_type_for_grant_type_message(response_type,
"authorization_code"))
end
when "token"
- 60
unless grant_types.include?("implicit")
- 24
register_throw_json_response_error("invalid_client_metadata",
register_invalid_response_type_for_grant_type_message(response_type, "implicit"))
end
when "none"
- 12
if grant_types.include?("implicit") || grant_types.include?("authorization_code")
- 12
register_throw_json_response_error("invalid_client_metadata", register_invalid_response_type_message(response_type))
end
end
end
- 12
def do_register(return_params = request.params.dup)
- 624
applications_ds = db[oauth_applications_table]
- 624
application_columns = applications_ds.columns
# set defaults
- 624
create_params = @oauth_application_params
# If omitted, an authorization server MAY register a client with a default set of scopes
- 624
create_params[oauth_applications_scopes_column] ||= return_params["scopes"] = oauth_application_scopes.join(" ")
# https://datatracker.ietf.org/doc/html/rfc7591#section-2
- 624
if create_params[oauth_applications_grant_types_column] ||= begin
# If omitted, the default behavior is that the client will use only the "authorization_code" Grant Type.
- 324
return_params["grant_types"] = %w[authorization_code] # rubocop:disable Lint/AssignmentInCondition
- 324
"authorization_code"
end
- 624
create_params[oauth_applications_token_endpoint_auth_method_column] ||= begin
# If unspecified or omitted, the default is "client_secret_basic", denoting the HTTP Basic
# authentication scheme as specified in Section 2.3.1 of OAuth 2.0.
- 336
return_params["token_endpoint_auth_method"] = "client_secret_basic"
- 336
"client_secret_basic"
end
end
- 624
create_params[oauth_applications_response_types_column] ||= begin
# If omitted, the default is that the client will use only the "code" response type.
- 324
return_params["response_types"] = %w[code]
- 324
"code"
end
- 624
rescue_from_uniqueness_error do
- 624
initialize_register_params(create_params, return_params)
- 12204
create_params.delete_if { |k, _| !application_columns.include?(k) }
- 624
applications_ds.insert(create_params)
end
- 624
return_params
end
- 12
def initialize_register_params(create_params, return_params)
- 624
client_id = oauth_unique_id_generator
- 624
create_params[oauth_applications_client_id_column] = client_id
- 624
return_params["client_id"] = client_id
- 624
return_params["client_id_issued_at"] = Time.now.utc.iso8601
- 624
registration_access_token = oauth_unique_id_generator
- 624
create_params[oauth_applications_registration_access_token_column] = secret_hash(registration_access_token)
- 624
return_params["registration_access_token"] = registration_access_token
- 624
return_params["registration_client_uri"] = "#{base_url}/#{registration_client_uri_route}/#{return_params['client_id']}"
- 624
if create_params.key?(oauth_applications_client_secret_column)
- 12
set_client_secret(create_params, create_params[oauth_applications_client_secret_column])
- 12
return_params.delete("client_secret")
else
- 612
client_secret = oauth_unique_id_generator
- 612
set_client_secret(create_params, client_secret)
- 612
return_params["client_secret"] = client_secret
- 612
return_params["client_secret_expires_at"] = 0
end
end
- 12
def register_throw_json_response_error(code, message)
- 696
throw_json_response_error(oauth_invalid_response_status, code, message)
end
- 12
def register_required_param_message(key)
- 60
"The param '#{key}' is required by this server."
end
- 12
def register_invalid_param_message(key)
- 120
"The param '#{key}' is not supported by this server."
end
- 12
def register_invalid_client_metadata_message(key, value)
- 192
"The value '#{value}' is not supported by this server for param '#{key}'."
end
- 12
def register_invalid_contacts_message(contacts)
- 12
"The contacts '#{contacts}' are not allowed by this server."
end
- 12
def register_invalid_uri_message(uri)
- 216
"The '#{uri}' URL is not allowed by this server."
end
- 12
def register_invalid_jwks_param_message(key1, key2)
- 12
"The param '#{key1}' cannot be accepted together with param '#{key2}'."
end
- 12
def register_invalid_scopes_message(scopes)
- 24
"The given scopes (#{scopes}) are not allowed by this server."
end
- 12
def register_oauth_invalid_grant_type_message(grant_type)
"The grant type #{grant_type} is not allowed by this server."
end
- 12
def register_invalid_response_type_message(response_type)
- 24
"The response type #{response_type} is not allowed by this server."
end
- 12
def register_invalid_response_type_for_grant_type_message(response_type, grant_type)
- 36
"The grant type '#{grant_type}' must be registered for the response " \
"type '#{response_type}' to be allowed."
end
- 12
def convert_to_boolean(key, value)
- 108
case value
when true, false then value
- 60
when "true" then true
- 24
when "false" then false
else
- 24
register_throw_json_response_error(
"invalid_client_metadata",
register_invalid_param_message(key)
)
end
end
- 12
def json_response_oauth_application(oauth_application)
- 10304
params = methods.map { |k| k.to_s[/\Aoauth_applications_(\w+)_column\z/, 1] }.compact
- 24
body = params.each_with_object({}) do |k, hash|
- 552
next if %w[id account_id client_id client_secret cliennt_secret_hash].include?(k)
- 456
value = oauth_application[__send__(:"oauth_applications_#{k}_column")]
- 456
next unless value
- 168
case k
when "redirect_uri"
- 24
hash["redirect_uris"] = value.split(" ")
when "token_endpoint_auth_method", "grant_types", "response_types", "request_uris", "post_logout_redirect_uris"
hash[k] = value.split(" ")
when "scopes"
- 24
hash["scope"] = value
when "jwks"
hash[k] = value.is_a?(String) ? JSON.parse(value) : value
when "homepage_url"
- 24
hash["client_uri"] = value
when "name"
- 24
hash["client_name"] = value
else
- 72
hash[k] = value
end
end
- 24
response.status = 200
- 24
response["Content-Type"] ||= json_response_content_type
- 24
response["Cache-Control"] = "no-store"
- 24
response["Pragma"] = "no-cache"
- 24
json_payload = _json_response_body(body)
- 24
return_response(json_payload)
end
- 12
def oauth_server_metadata_body(*)
- 24
super.tap do |data|
- 24
data[:registration_endpoint] = register_url
end
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_grant_management, :OauthTokenManagement) do
- 12
depends :oauth_management_base, :oauth_token_revocation
- 12
view "oauth_grants", "My Oauth Grants", "oauth_grants"
- 12
button "Revoke", "oauth_grant_revoke"
- 12
auth_value_method :oauth_grants_path, "oauth-grants"
- 12
%w[type token refresh_token expires_in revoked_at].each do |param|
- 60
translatable_method :"oauth_grants_#{param}_label", param.gsub("_", " ").capitalize
end
- 12
translatable_method :oauth_no_grants_text, "No oauth grants yet!"
- 12
auth_value_method :oauth_grants_route, "oauth-grants"
- 12
auth_value_method :oauth_grants_id_pattern, Integer
- 12
auth_value_method :oauth_grants_per_page, 20
- 12
auth_methods(
:oauth_grant_path
)
- 12
def oauth_grants_path(opts = {})
- 660
route_path(oauth_grants_route, opts)
end
- 12
def oauth_grant_path(id)
- 252
"#{oauth_grants_path}/#{id}"
end
- 12
def load_oauth_grant_management_routes
- 96
request.on(oauth_grants_route) do
- 96
check_csrf if check_csrf?
- 96
require_account
- 96
request.post(oauth_grants_id_pattern) do |id|
- 8
db[oauth_grants_table]
.where(oauth_grants_id_column => id)
.where(oauth_grants_account_id_column => account_id)
- 4
.update(oauth_grants_revoked_at_column => Sequel::CURRENT_TIMESTAMP)
- 12
set_notice_flash revoke_oauth_grant_notice_flash
- 12
redirect oauth_grants_path || "/"
end
- 84
request.is do
- 84
request.get do
- 84
page = Integer(param_or_nil("page") || 1)
- 84
per_page = per_page_param(oauth_grants_per_page)
- 84
scope.instance_variable_set(:@oauth_grants, db[oauth_grants_table]
.select(Sequel[oauth_grants_table].*, Sequel[oauth_applications_table][oauth_applications_name_column])
.join(oauth_applications_table, Sequel[oauth_grants_table][oauth_grants_oauth_application_id_column] =>
Sequel[oauth_applications_table][oauth_applications_id_column])
.where(Sequel[oauth_grants_table][oauth_grants_account_id_column] => account_id)
.where(oauth_grants_revoked_at_column => nil)
.order(Sequel.desc(oauth_grants_id_column))
.paginate(page, per_page))
- 84
oauth_grants_view
end
end
end
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_implicit_grant, :OauthImplicitGrant) do
- 12
depends :oauth_authorize_base
- 12
def oauth_grant_types_supported
- 2760
super | %w[implicit]
end
- 12
def oauth_response_types_supported
- 1404
super | %w[token]
end
- 12
def oauth_response_modes_supported
- 1560
super | %w[fragment]
end
- 12
private
- 12
def validate_authorize_params
- 1620
super
- 1524
response_mode = param_or_nil("response_mode")
- 1524
return unless response_mode
- 396
response_type = param_or_nil("response_type")
- 396
return unless response_type == "token"
- 72
redirect_response_error("invalid_request") unless oauth_response_modes_for_token_supported.include?(response_mode)
end
- 12
def oauth_response_modes_for_token_supported
- 72
%w[fragment]
end
- 12
def do_authorize(response_params = {}, response_mode = param_or_nil("response_mode"))
- 636
response_type = param("response_type")
- 636
return super unless response_type == "token" && supported_response_type?(response_type)
- 48
response_mode ||= "fragment"
- 48
redirect_response_error("invalid_request") unless supported_response_mode?(response_mode)
- 48
oauth_grant = _do_authorize_token
- 48
response_params.replace(json_access_token_payload(oauth_grant))
- 48
response_params["state"] = param("state") if param_or_nil("state")
- 48
[response_params, response_mode]
end
- 12
def _do_authorize_token(grant_params = {})
- 20
grant_params = {
- 40
oauth_grants_type_column => "implicit",
oauth_grants_oauth_application_id_column => oauth_application[oauth_applications_id_column],
oauth_grants_scopes_column => scopes,
**resource_owner_params
}.merge(grant_params)
- 60
generate_token(grant_params, false)
end
- 12
def _redirect_response_error(redirect_url, params)
- 240
response_types = param("response_type").split(/ +/)
- 240
return super if response_types.empty? || response_types == %w[code]
- 336
params = params.map { |k, v| "#{k}=#{v}" }
- 132
redirect_url.fragment = params.join("&")
- 132
redirect(redirect_url.to_s)
end
- 12
def authorize_response(params, mode)
- 540
return super unless mode == "fragment"
- 336
redirect_url = URI.parse(redirect_uri)
- 336
params = [URI.encode_www_form(params)]
- 336
params << redirect_url.query if redirect_url.query
- 336
redirect_url.fragment = params.join("&")
- 336
redirect(redirect_url.to_s)
end
- 12
def check_valid_response_type?
- 792
return true if param_or_nil("response_type") == "token"
- 660
super
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
require "rodauth/oauth/http_extensions"
- 12
module Rodauth
- 12
Feature.define(:oauth_jwt, :OauthJwt) do
- 12
depends :oauth_jwt_base, :oauth_jwt_jwks
- 12
auth_value_method :oauth_jwt_access_tokens, true
- 12
auth_methods(:jwt_claims)
- 12
def require_oauth_authorization(*scopes)
- 228
return super unless oauth_jwt_access_tokens
- 228
authorization_required unless authorization_token
- 216
token_scopes = authorization_token["scope"].split(" ")
- 432
authorization_required unless scopes.any? { |scope| token_scopes.include?(scope) }
end
- 12
def oauth_token_subject
- 324
return super unless oauth_jwt_access_tokens
- 324
return unless authorization_token
- 324
authorization_token["sub"]
end
- 12
def current_oauth_account
- 156
subject = oauth_token_subject
- 156
return if subject == authorization_token["client_id"]
- 144
oauth_account_ds(subject).first
end
- 12
def current_oauth_application
- 128
db[oauth_applications_table].where(
oauth_applications_client_id_column => authorization_token["client_id"]
- 64
).first
end
- 12
private
- 12
def authorization_token
- 1572
return super unless oauth_jwt_access_tokens
- 1572
return @authorization_token if defined?(@authorization_token)
- 116
@authorization_token = begin
- 348
access_token = fetch_access_token
- 348
return unless access_token
- 336
jwt_claims = jwt_decode(access_token)
- 336
return unless jwt_claims
- 336
return unless jwt_claims["sub"]
- 336
return unless jwt_claims["aud"]
- 336
jwt_claims
end
end
# /token
- 12
def create_token_from_token(_grant, update_params)
- 96
oauth_grant = super
- 96
if oauth_jwt_access_tokens
- 96
access_token = _generate_jwt_access_token(oauth_grant)
- 96
oauth_grant[oauth_grants_token_column] = access_token
end
- 96
oauth_grant
end
- 12
def generate_token(_grant_params = {}, should_generate_refresh_token = true)
- 468
oauth_grant = super
- 468
if oauth_jwt_access_tokens
- 456
access_token = _generate_jwt_access_token(oauth_grant)
- 456
oauth_grant[oauth_grants_token_column] = access_token
end
- 468
oauth_grant
end
- 12
def _generate_jwt_access_token(oauth_grant)
- 576
claims = jwt_claims(oauth_grant)
# one of the points of using jwt is avoiding database lookups, so we put here all relevant
# token data.
- 576
claims[:scope] = oauth_grant[oauth_grants_scopes_column]
- 576
jwt_encode(claims)
end
- 12
def _generate_access_token(*)
- 564
super unless oauth_jwt_access_tokens
end
- 12
def jwt_claims(oauth_grant)
- 1140
issued_at = Time.now.to_i
- 380
{
- 760
iss: oauth_jwt_issuer, # issuer
iat: issued_at, # issued at
#
# sub REQUIRED - as defined in section 4.1.2 of [RFC7519]. In case of
# access tokens obtained through grants where a resource owner is
# involved, such as the authorization code grant, the value of "sub"
# SHOULD correspond to the subject identifier of the resource owner.
# In case of access tokens obtained through grants where no resource
# owner is involved, such as the client credentials grant, the value
# of "sub" SHOULD correspond to an identifier the authorization
# server uses to indicate the client application.
sub: jwt_subject(oauth_grant[oauth_grants_account_id_column]),
client_id: oauth_application[oauth_applications_client_id_column],
exp: issued_at + oauth_access_token_expires_in,
aud: oauth_jwt_audience
}
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
require "rodauth/oauth/http_extensions"
- 12
module Rodauth
- 12
Feature.define(:oauth_jwt_base, :OauthJwtBase) do
- 12
depends :oauth_base
- 12
auth_value_method :oauth_application_jwt_public_key_param, "jwt_public_key"
- 12
auth_value_method :oauth_application_jwks_param, "jwks"
- 12
auth_value_method :oauth_jwt_keys, {}
- 12
auth_value_method :oauth_jwt_public_keys, {}
- 12
auth_value_method :oauth_jwt_jwe_keys, {}
- 12
auth_value_method :oauth_jwt_jwe_public_keys, {}
- 12
auth_value_method :oauth_jwt_jwe_copyright, nil
- 12
auth_methods(
:jwt_encode,
:jwt_decode,
:jwt_decode_no_key,
:generate_jti,
:oauth_jwt_issuer,
:oauth_jwt_audience,
:resource_owner_params_from_jwt_claims
)
- 12
private
- 12
def oauth_jwt_issuer
# The JWT MUST contain an "iss" (issuer) claim that contains a
# unique identifier for the entity that issued the JWT.
- 2463
@oauth_jwt_issuer ||= authorization_server_url
end
- 12
def oauth_jwt_audience
# The JWT MUST contain an "aud" (audience) claim containing a
# value that identifies the authorization server as an intended
# audience. The token endpoint URL of the authorization server
# MAY be used as a value for an "aud" element to identify the
# authorization server as an intended audience of the JWT.
- 1140
@oauth_jwt_audience ||= if is_authorization_server?
- 852
oauth_application[oauth_applications_client_id_column]
else
metadata = authorization_server_metadata
return unless metadata
metadata[:token_endpoint]
end
end
- 12
def grant_from_application?(grant_or_claims, oauth_application)
- 108
return super if grant_or_claims[oauth_grants_id_column]
if grant_or_claims["client_id"]
grant_or_claims["client_id"] == oauth_application[oauth_applications_client_id_column]
else
Array(grant_or_claims["aud"]).include?(oauth_application[oauth_applications_client_id_column])
end
end
- 12
def jwt_subject(account_unique_id, client_application = oauth_application)
- 1176
(account_unique_id || client_application[oauth_applications_client_id_column]).to_s
end
- 12
def resource_owner_params_from_jwt_claims(claims)
- 108
{ oauth_grants_account_id_column => claims["sub"] }
end
- 12
def oauth_server_metadata_body(path = nil)
- 180
metadata = super
- 180
metadata.merge! \
token_endpoint_auth_signing_alg_values_supported: oauth_jwt_keys.keys.uniq
- 180
metadata
end
- 12
def _jwt_key
- 267
@_jwt_key ||= (oauth_application_jwks(oauth_application) if oauth_application)
end
# Resource Server only!
#
# returns the jwks set from the authorization server.
- 12
def auth_server_jwks_set
- 48
metadata = authorization_server_metadata
- 48
return unless metadata && (jwks_uri = metadata[:jwks_uri])
- 48
jwks_uri = URI(jwks_uri)
- 48
http_request_with_cache(jwks_uri)
end
- 12
def generate_jti(payload)
# Use the key and iat to create a unique key per request to prevent replay attacks
- 545
jti_raw = [
- 1090
payload[:aud] || payload["aud"],
payload[:iat] || payload["iat"]
].join(":").to_s
- 1635
Digest::SHA256.hexdigest(jti_raw)
end
- 12
def verify_jti(jti, claims)
- 279
generate_jti(claims) == jti
end
- 12
def verify_aud(expected_aud, aud)
- 618
expected_aud == aud
end
- 12
def oauth_application_jwks(oauth_application)
- 1359
jwks = oauth_application[oauth_applications_jwks_column]
- 1359
if jwks
- 627
jwks = JSON.parse(jwks, symbolize_names: true) if jwks.is_a?(String)
- 627
return jwks
end
- 732
jwks_uri = oauth_application[oauth_applications_jwks_uri_column]
- 732
return unless jwks_uri
- 24
jwks_uri = URI(jwks_uri)
- 24
http_request_with_cache(jwks_uri)
end
- 12
if defined?(JSON::JWT)
# json-jwt
- 3
auth_value_method :oauth_jwt_jws_algorithms_supported, %w[
HS256 HS384 HS512
RS256 RS384 RS512
PS256 PS384 PS512
ES256 ES384 ES512 ES256K
]
- 3
auth_value_method :oauth_jwt_jwe_algorithms_supported, %w[
RSA1_5 RSA-OAEP dir A128KW A256KW
]
- 3
auth_value_method :oauth_jwt_jwe_encryption_methods_supported, %w[
A128GCM A256GCM A128CBC-HS256 A256CBC-HS512
]
- 3
def key_to_jwk(key)
- 15
JSON::JWK.new(key)
end
- 3
def jwk_export(key)
- 12
key_to_jwk(key)
end
- 3
def jwk_import(jwk)
- 6
JSON::JWK.new(jwk)
end
- 3
def jwk_key(jwk)
jwk = jwk_import(jwk) unless jwk.is_a?(JSON::JWK)
jwk.to_key
end
- 3
def jwk_thumbprint(jwk)
- 6
jwk = jwk_import(jwk) if jwk.is_a?(Hash)
- 6
jwk.thumbprint
end
- 3
def jwt_encode(payload,
jwks: nil,
headers: {},
encryption_algorithm: oauth_jwt_jwe_keys.keys.dig(0, 0),
encryption_method: oauth_jwt_jwe_keys.keys.dig(0, 1),
jwe_key: oauth_jwt_jwe_keys[[encryption_algorithm,
encryption_method]],
signing_algorithm: oauth_jwt_keys.keys.first)
- 339
payload[:jti] = generate_jti(payload)
- 339
jwt = JSON::JWT.new(payload)
- 339
key = oauth_jwt_keys[signing_algorithm] || _jwt_key
- 339
key = key.first if key.is_a?(Array)
- 339
jwk = JSON::JWK.new(key || "")
# update headers
- 339
headers.each_key do |k|
- 18
if jwt.respond_to?(:"#{k}=")
- 18
jwt.send(:"#{k}=", headers[k])
- 18
headers.delete(k)
end
end
- 339
jwt.header.merge(headers) unless headers.empty?
- 339
jwt = jwt.sign(jwk, signing_algorithm)
- 339
return jwt.to_s unless encryption_algorithm && encryption_method
- 57
if jwks && (jwk = jwks.find { |k| k[:use] == "enc" && k[:alg] == encryption_algorithm && k[:enc] == encryption_method })
- 18
jwk = JSON::JWK.new(jwk)
- 18
jwe = jwt.encrypt(jwk, encryption_algorithm.to_sym, encryption_method.to_sym)
- 18
jwe.to_s
- 3
elsif jwe_key
- 3
jwe_key = jwe_key.first if jwe_key.is_a?(Array)
- 3
algorithm = encryption_algorithm.to_sym
- 3
meth = encryption_method.to_sym
- 3
jwt.encrypt(jwe_key, algorithm, meth)
else
jwt.to_s
end
end
- 3
def jwt_decode(
token,
jwks: nil,
jws_algorithm: oauth_jwt_public_keys.keys.first || oauth_jwt_keys.keys.first,
jws_key: oauth_jwt_keys[jws_algorithm] || _jwt_key,
jws_encryption_algorithm: oauth_jwt_jwe_keys.keys.dig(0, 0),
jws_encryption_method: oauth_jwt_jwe_keys.keys.dig(0, 1),
jwe_key: oauth_jwt_jwe_keys[[jws_encryption_algorithm, jws_encryption_method]] || oauth_jwt_jwe_keys.values.first,
verify_claims: true,
verify_jti: true,
verify_iss: true,
verify_aud: true,
**
)
- 210
jws_key = jws_key.first if jws_key.is_a?(Array)
- 210
if jwe_key
- 9
jwe_key = jwe_key.first if jwe_key.is_a?(Array)
- 9
token = JSON::JWT.decode(token, jwe_key).plain_text
end
- 210
claims = if is_authorization_server?
- 198
if jwks
- 72
jwks = jwks[:keys] if jwks.is_a?(Hash)
- 72
enc_algs = [jws_encryption_algorithm].compact
- 72
enc_meths = [jws_encryption_method].compact
- 150
sig_algs = jws_algorithm ? [jws_algorithm] : jwks.select { |k| k[:use] == "sig" }.map { |k| k[:alg] }
- 72
sig_algs = sig_algs.compact.map(&:to_sym)
# JWKs may be set up without a KID, when there's a single one
- 72
if jwks.size == 1 && !jwks[0][:kid]
- 3
key = jwks[0]
- 3
jwk_key = JSON::JWK.new(key)
- 3
jws = JSON::JWT.decode(token, jwk_key)
else
- 69
jws = JSON::JWT.decode(token, JSON::JWK::Set.new({ keys: jwks }), enc_algs + sig_algs, enc_meths)
- 63
jws = JSON::JWT.decode(jws.plain_text, JSON::JWK::Set.new({ keys: jwks }), sig_algs) if jws.is_a?(JSON::JWE)
end
- 66
jws
- 126
elsif jws_key
- 123
JSON::JWT.decode(token, jws_key)
else
- 3
JSON::JWT.decode(token, nil, jws_algorithm)
end
- 12
elsif (jwks = auth_server_jwks_set)
- 12
JSON::JWT.decode(token, JSON::JWK::Set.new(jwks))
end
- 204
now = Time.now
- 204
if verify_claims && (
(!claims[:exp] || Time.at(claims[:exp]) < now) &&
(claims[:nbf] && Time.at(claims[:nbf]) < now) &&
(claims[:iat] && Time.at(claims[:iat]) < now) &&
(verify_iss && claims[:iss] != oauth_jwt_issuer) &&
(verify_aud && !verify_aud(claims[:aud], claims[:client_id])) &&
(verify_jti && !verify_jti(claims[:jti], claims))
)
return
end
- 204
claims
rescue JSON::JWT::Exception
- 6
nil
end
- 3
def jwt_decode_no_key(token)
- 24
jws = JSON::JWT.decode(token, :skip_verification)
- 24
[jws.to_h, jws.header]
end
- 9
elsif defined?(JWT)
# ruby-jwt
- 9
require "rodauth/oauth/jwe_extensions" if defined?(JWE)
- 9
auth_value_method :oauth_jwt_jws_algorithms_supported, %w[
HS256 HS384 HS512 HS512256
RS256 RS384 RS512
ED25519
ES256 ES384 ES512
PS256 PS384 PS512
]
- 9
if defined?(JWE)
- 9
auth_value_methods(
:oauth_jwt_jwe_algorithms_supported,
:oauth_jwt_jwe_encryption_methods_supported
)
- 9
def oauth_jwt_jwe_algorithms_supported
- 270
JWE::VALID_ALG
end
- 9
def oauth_jwt_jwe_encryption_methods_supported
- 261
JWE::VALID_ENC
end
else
auth_value_method :oauth_jwt_jwe_algorithms_supported, []
auth_value_method :oauth_jwt_jwe_encryption_methods_supported, []
end
- 9
def key_to_jwk(key)
- 45
JWT::JWK.new(key)
end
- 9
def jwk_export(key)
- 36
key_to_jwk(key).export
end
- 9
def jwk_import(jwk)
- 9
JWT::JWK.import(jwk)
end
- 9
def jwk_key(jwk)
jwk = jwk_import(jwk) unless jwk.is_a?(JWT::JWK)
jwk.keypair
end
- 9
def jwk_thumbprint(jwk)
- 18
jwk = jwk_import(jwk) if jwk.is_a?(Hash)
- 18
JWT::JWK::Thumbprint.new(jwk).generate
end
- 9
def jwt_encode(payload,
signing_algorithm: oauth_jwt_keys.keys.first,
headers: {}, **)
- 1017
key = oauth_jwt_keys[signing_algorithm] || _jwt_key
- 1017
key = key.first if key.is_a?(Array)
- 1017
case key
when OpenSSL::PKey::PKey
- 801
jwk = JWT::JWK.new(key)
- 801
headers[:kid] = jwk.kid
- 801
key = jwk.keypair
end
# @see JWT reserved claims - https://tools.ietf.org/html/draft-jones-json-web-token-07#page-7
- 1017
payload[:jti] = generate_jti(payload)
- 1017
JWT.encode(payload, key, signing_algorithm, headers)
end
- 9
if defined?(JWE)
- 9
def jwt_encode_with_jwe(
payload,
jwks: nil,
encryption_algorithm: oauth_jwt_jwe_keys.keys.dig(0, 0),
encryption_method: oauth_jwt_jwe_keys.keys.dig(0, 1),
jwe_key: oauth_jwt_jwe_keys[[encryption_algorithm, encryption_method]],
**args
)
- 1017
token = jwt_encode_without_jwe(payload, **args)
- 1017
return token unless encryption_algorithm && encryption_method
- 153
if jwks && jwks.any? { |k| k[:use] == "enc" }
- 54
JWE.__rodauth_oauth_encrypt_from_jwks(token, jwks, alg: encryption_algorithm, enc: encryption_method)
- 9
elsif jwe_key
- 9
jwe_key = jwe_key.first if jwe_key.is_a?(Array)
- 3
params = {
- 6
zip: "DEF",
copyright: oauth_jwt_jwe_copyright
}
- 9
params[:enc] = encryption_method if encryption_method
- 9
params[:alg] = encryption_algorithm if encryption_algorithm
- 9
JWE.encrypt(token, jwe_key, **params)
else
token
end
end
- 9
alias_method :jwt_encode_without_jwe, :jwt_encode
- 9
alias_method :jwt_encode, :jwt_encode_with_jwe
end
- 9
def jwt_decode(
token,
jwks: nil,
jws_algorithm: oauth_jwt_public_keys.keys.first || oauth_jwt_keys.keys.first,
jws_key: oauth_jwt_keys[jws_algorithm] || _jwt_key,
verify_claims: true,
verify_jti: true,
verify_iss: true,
verify_aud: true
)
- 621
jws_key = jws_key.first if jws_key.is_a?(Array)
# verifying the JWT implies verifying:
#
# issuer: check that server generated the token
# aud: check the audience field (client is who he says he is)
# iat: check that the token didn't expire
#
# subject can't be verified automatically without having access to the account id,
# which we don't because that's the whole point.
#
- 621
verify_claims_params = if verify_claims
- 189
{
- 378
verify_iss: verify_iss,
iss: oauth_jwt_issuer,
# can't use stock aud verification, as it's dependent on the client application id
verify_aud: false,
- 567
verify_jti: (verify_jti ? method(:verify_jti) : false),
verify_iat: true
}
else
- 54
{}
end
# decode jwt
- 621
claims = if is_authorization_server?
- 585
if jwks
- 207
jwks = jwks[:keys] if jwks.is_a?(Hash)
# JWKs may be set up without a KID, when there's a single one
- 207
if jwks.size == 1 && !jwks[0][:kid]
- 9
key = jwks[0]
- 9
algo = key[:alg]
- 9
key = JWT::JWK.import(key).keypair
- 9
JWT.decode(token, key, true, algorithms: [algo], **verify_claims_params).first
else
- 432
algorithms = jws_algorithm ? [jws_algorithm] : jwks.select { |k| k[:use] == "sig" }.map { |k| k[:alg] }
- 198
JWT.decode(token, nil, true, algorithms: algorithms, jwks: { keys: jwks }, **verify_claims_params).first
end
- 378
elsif jws_key
- 369
JWT.decode(token, jws_key, true, algorithms: [jws_algorithm], **verify_claims_params).first
else
- 9
JWT.decode(token, jws_key, false, **verify_claims_params).first
end
- 36
elsif (jwks = auth_server_jwks_set)
- 108
algorithms = jwks[:keys].select { |k| k[:use] == "sig" }.map { |k| k[:alg] }
- 36
JWT.decode(token, nil, true, jwks: jwks, algorithms: algorithms, **verify_claims_params).first
end
- 612
return if verify_claims && verify_aud && !verify_aud(claims["aud"], claims["client_id"])
- 612
claims
rescue JWT::DecodeError, JWT::JWKError
- 9
nil
end
- 9
if defined?(JWE)
- 9
def jwt_decode_with_jwe(
token,
jwks: nil,
jws_encryption_algorithm: oauth_jwt_jwe_keys.keys.dig(0, 0),
jws_encryption_method: oauth_jwt_jwe_keys.keys.dig(0, 1),
jwe_key: oauth_jwt_jwe_keys[[jws_encryption_algorithm, jws_encryption_method]] || oauth_jwt_jwe_keys.values.first,
**args
)
- 891
token = if jwks && jwks.any? { |k| k[:use] == "enc" }
- 27
JWE.__rodauth_oauth_decrypt_from_jwks(token, jwks, alg: jws_encryption_algorithm, enc: jws_encryption_method)
- 603
elsif jwe_key
- 27
jwe_key = jwe_key.first if jwe_key.is_a?(Array)
- 27
JWE.decrypt(token, jwe_key)
else
- 576
token
end
- 612
jwt_decode_without_jwe(token, jwks: jwks, **args)
rescue JWE::DecodeError => e
- 18
jwt_decode_without_jwe(token, jwks: jwks, **args) if e.message.include?("Not enough or too many segments")
end
- 9
alias_method :jwt_decode_without_jwe, :jwt_decode
- 9
alias_method :jwt_decode, :jwt_decode_with_jwe
end
- 9
def jwt_decode_no_key(token)
- 72
JWT.decode(token, nil, false)
end
else
- skipped
# :nocov:
- skipped
def jwk_export(_key)
- skipped
raise "#{__method__} is undefined, redefine it or require either \"jwt\" or \"json-jwt\""
- skipped
end
- skipped
- skipped
def jwk_import(_jwk)
- skipped
raise "#{__method__} is undefined, redefine it or require either \"jwt\" or \"json-jwt\""
- skipped
end
- skipped
- skipped
def jwk_thumbprint(_jwk)
- skipped
raise "#{__method__} is undefined, redefine it or require either \"jwt\" or \"json-jwt\""
- skipped
end
- skipped
- skipped
def jwt_encode(_token)
- skipped
raise "#{__method__} is undefined, redefine it or require either \"jwt\" or \"json-jwt\""
- skipped
end
- skipped
- skipped
def jwt_decode(_token, **)
- skipped
raise "#{__method__} is undefined, redefine it or require either \"jwt\" or \"json-jwt\""
- skipped
end
- skipped
# :nocov:
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_jwt_bearer_grant, :OauthJwtBearerGrant) do
- 12
depends :oauth_assertion_base, :oauth_jwt
- 12
auth_value_method :max_param_bytesize, nil if Rodauth::VERSION >= "2.26.0"
- 12
auth_methods(
:require_oauth_application_from_jwt_bearer_assertion_issuer,
:require_oauth_application_from_jwt_bearer_assertion_subject,
:account_from_jwt_bearer_assertion
)
- 12
def oauth_token_endpoint_auth_methods_supported
- 36
if oauth_applications_client_secret_hash_column.nil?
- 12
super | %w[client_secret_jwt private_key_jwt urn:ietf:params:oauth:client-assertion-type:jwt-bearer]
else
- 24
super | %w[private_key_jwt]
end
end
- 12
def oauth_grant_types_supported
- 96
super | %w[urn:ietf:params:oauth:grant-type:jwt-bearer]
end
- 12
private
- 12
def require_oauth_application_from_jwt_bearer_assertion_issuer(assertion)
- 36
claims = jwt_assertion(assertion)
- 36
return unless claims
- 24
db[oauth_applications_table].where(
oauth_applications_client_id_column => claims["iss"]
- 12
).first
end
- 12
def require_oauth_application_from_jwt_bearer_assertion_subject(assertion)
- 96
claims, header = jwt_decode_no_key(assertion)
- 96
client_id = claims["sub"]
- 96
case header["alg"]
when "none"
# do not accept jwts with no alg set
- 12
authorization_required
when /\AHS/
- 36
require_oauth_application_from_client_secret_jwt(client_id, assertion, header["alg"])
else
- 48
require_oauth_application_from_private_key_jwt(client_id, assertion)
end
end
- 12
def require_oauth_application_from_client_secret_jwt(client_id, assertion, alg)
- 36
oauth_application = db[oauth_applications_table].where(oauth_applications_client_id_column => client_id).first
- 36
authorization_required unless oauth_application && supports_auth_method?(oauth_application, "client_secret_jwt")
- 24
client_secret = oauth_application[oauth_applications_client_secret_column]
- 24
claims = jwt_assertion(assertion, jws_key: client_secret, jws_algorithm: alg)
- 24
authorization_required unless claims && claims["iss"] == client_id
- 24
oauth_application
end
- 12
def require_oauth_application_from_private_key_jwt(client_id, assertion)
- 48
oauth_application = db[oauth_applications_table].where(oauth_applications_client_id_column => client_id).first
- 48
authorization_required unless oauth_application && supports_auth_method?(oauth_application, "private_key_jwt")
- 36
jwks = oauth_application_jwks(oauth_application)
- 36
claims = jwt_assertion(assertion, jwks: jwks)
- 36
authorization_required unless claims
- 36
oauth_application
end
- 12
def account_from_jwt_bearer_assertion(assertion)
- 36
claims = jwt_assertion(assertion)
- 36
return unless claims
- 36
account_from_bearer_assertion_subject(claims["sub"])
end
- 12
def jwt_assertion(assertion, **kwargs)
- 132
claims = jwt_decode(assertion, verify_iss: false, verify_aud: false, verify_jti: false, **kwargs)
- 132
return unless claims && verify_aud(request.url, claims["aud"])
- 132
claims
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
require "rodauth/oauth/http_extensions"
- 12
module Rodauth
- 12
Feature.define(:oauth_jwt_jwks, :OauthJwtJwks) do
- 12
depends :oauth_jwt_base
- 12
auth_methods(:jwks_set)
- 12
auth_server_route(:jwks) do |r|
- 36
before_jwks_route
- 36
r.get do
- 36
json_response_success({ keys: jwks_set }, true)
end
end
- 12
private
- 12
def oauth_server_metadata_body(path = nil)
- 180
metadata = super
- 180
metadata.merge!(jwks_uri: jwks_url)
- 180
metadata
end
- 12
def jwks_set
- 36
@jwks_set ||= [
*(
- 36
unless oauth_jwt_public_keys.empty?
- 72
oauth_jwt_public_keys.flat_map { |algo, pkeys| Array(pkeys).map { |pkey| jwk_export(pkey).merge(use: "sig", alg: algo) } }
end
),
*(
- 36
unless oauth_jwt_jwe_public_keys.empty?
- 12
oauth_jwt_jwe_public_keys.flat_map do |(algo, _enc), pkeys|
- 12
Array(pkeys).map do |pkey|
- 12
jwk_export(pkey).merge(use: "enc", alg: algo)
end
end
end
)
].compact
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_jwt_secured_authorization_request, :OauthJwtSecuredAuthorizationRequest) do
- 12
ALLOWED_REQUEST_URI_CONTENT_TYPES = %w[application/jose application/oauth-authz-req+jwt].freeze
- 12
depends :oauth_authorize_base, :oauth_jwt_base
- 12
auth_value_method :oauth_require_request_uri_registration, false
- 12
auth_value_method :oauth_require_signed_request_object, false
- 12
auth_value_method :oauth_request_object_signing_alg_allow_none, false
- 8
%i[
request_uris require_signed_request_object request_object_signing_alg
request_object_encryption_alg request_object_encryption_enc
- 4
].each do |column|
- 60
auth_value_method :"oauth_applications_#{column}_column", column
end
- 12
translatable_method :oauth_invalid_request_object_message, "request object is invalid"
- 12
auth_value_method :max_param_bytesize, nil if Rodauth::VERSION >= "2.26.0"
- 12
private
# /authorize
- 12
def validate_authorize_params
- 540
request_object = param_or_nil("request")
- 540
request_uri = param_or_nil("request_uri")
- 540
unless (request_object || request_uri) && oauth_application
- 132
if request.path == authorize_path && request.get? && require_signed_request_object?
- 12
redirect_response_error("invalid_request_object")
end
- 120
return super
end
- 408
if request_uri
- 108
request_uri = CGI.unescape(request_uri)
- 108
redirect_response_error("invalid_request_uri") unless supported_request_uri?(request_uri, oauth_application)
- 60
response = http_request(request_uri)
- 60
unless response.code.to_i == 200 && ALLOWED_REQUEST_URI_CONTENT_TYPES.include?(response["content-type"])
- 12
redirect_response_error("invalid_request_uri")
end
- 48
request_object = response.body
end
- 348
claims = decode_request_object(request_object)
- 228
redirect_response_error("invalid_request_object") unless claims
- 228
if (iss = claims["iss"]) && (iss != oauth_application[oauth_applications_client_id_column])
- 12
redirect_response_error("invalid_request_object")
end
- 216
if (aud = claims["aud"]) && !verify_aud(aud, oauth_jwt_issuer)
- 12
redirect_response_error("invalid_request_object")
end
# If signed, the Authorization Request
# Object SHOULD contain the Claims "iss" (issuer) and "aud" (audience)
# as members, with their semantics being the same as defined in the JWT
# [RFC7519] specification. The value of "aud" should be the value of
# the Authorization Server (AS) "issuer" as defined in RFC8414
# [RFC8414].
- 204
claims.delete("iss")
- 204
audience = claims.delete("aud")
- 204
redirect_response_error("invalid_request_object") if audience && audience != oauth_jwt_issuer
- 204
claims.each do |k, v|
- 1260
request.params[k.to_s] = v
end
- 204
super
end
- 12
def supported_request_uri?(request_uri, oauth_application)
- 108
return false unless check_valid_uri?(request_uri)
- 84
request_uris = oauth_application[oauth_applications_request_uris_column]
- 144
request_uris.nil? || request_uris.split(oauth_scope_separator).one? { |uri| request_uri.start_with?(uri) }
end
- 12
def require_signed_request_object?
- 60
return @require_signed_request_object if defined?(@require_signed_request_object)
- 48
@require_signed_request_object = (oauth_application[oauth_applications_require_signed_request_object_column] if oauth_application)
- 48
@require_signed_request_object = oauth_require_signed_request_object if @require_signed_request_object.nil?
- 48
@require_signed_request_object
end
- 12
def decode_request_object(request_object)
- 120
request_sig_enc_opts = {
- 240
jws_algorithm: oauth_application[oauth_applications_request_object_signing_alg_column],
jws_encryption_algorithm: oauth_application[oauth_applications_request_object_encryption_alg_column],
jws_encryption_method: oauth_application[oauth_applications_request_object_encryption_enc_column]
}.compact
- 360
request_sig_enc_opts[:jws_algorithm] ||= "none" if oauth_request_object_signing_alg_allow_none
- 360
if request_sig_enc_opts[:jws_algorithm] == "none"
- 36
redirect_response_error("invalid_request_object") if require_signed_request_object?
- 12
jwks = nil
- 324
elsif (jwks = oauth_application_jwks(oauth_application))
- 252
jwks = JSON.parse(jwks, symbolize_names: true) if jwks.is_a?(String)
else
- 72
redirect_response_error("invalid_request_object")
end
- 264
claims = jwt_decode(request_object,
jwks: jwks,
verify_jti: false,
verify_iss: false,
verify_aud: false,
**request_sig_enc_opts)
- 264
redirect_response_error("invalid_request_object") unless claims
- 240
claims
end
- 12
def oauth_server_metadata_body(*)
- 36
super.tap do |data|
- 36
data[:request_parameter_supported] = true
- 36
data[:request_uri_parameter_supported] = true
- 36
data[:require_request_uri_registration] = oauth_require_request_uri_registration
- 36
data[:require_signed_request_object] = oauth_require_signed_request_object
end
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_jwt_secured_authorization_response_mode, :OauthJwtSecuredAuthorizationResponseMode) do
- 12
depends :oauth_authorize_base, :oauth_jwt_base
- 12
auth_value_method :oauth_authorization_response_mode_expires_in, 60 * 5 # 5 minutes
- 12
auth_value_method :oauth_applications_authorization_signed_response_alg_column, :authorization_signed_response_alg
- 12
auth_value_method :oauth_applications_authorization_encrypted_response_alg_column, :authorization_encrypted_response_alg
- 12
auth_value_method :oauth_applications_authorization_encrypted_response_enc_column, :authorization_encrypted_response_enc
- 12
auth_value_methods(
:authorization_signing_alg_values_supported,
:authorization_encryption_alg_values_supported,
:authorization_encryption_enc_values_supported
)
- 12
def oauth_response_modes_supported
- 516
jwt_response_modes = %w[jwt]
- 516
jwt_response_modes.push("query.jwt", "form_post.jwt") if features.include?(:oauth_authorization_code_grant)
- 516
jwt_response_modes << "fragment.jwt" if features.include?(:oauth_implicit_grant)
- 516
super | jwt_response_modes
end
- 12
def authorization_signing_alg_values_supported
- 12
oauth_jwt_jws_algorithms_supported
end
- 12
def authorization_encryption_alg_values_supported
- 24
oauth_jwt_jwe_algorithms_supported
end
- 12
def authorization_encryption_enc_values_supported
- 24
oauth_jwt_jwe_encryption_methods_supported
end
- 12
private
- 12
def oauth_response_modes_for_code_supported
- 144
return [] unless features.include?(:oauth_authorization_code_grant)
- 144
super | %w[query.jwt form_post.jwt jwt]
end
- 12
def oauth_response_modes_for_token_supported
- 60
return [] unless features.include?(:oauth_implicit_grant)
- 60
super | %w[fragment.jwt jwt]
end
- 12
def authorize_response(params, mode)
- 120
return super unless mode.end_with?("jwt")
- 120
response_type = param_or_nil("response_type")
- 120
redirect_url = URI.parse(redirect_uri)
- 120
jwt = jwt_encode_authorization_response_mode(params)
- 120
if mode == "query.jwt" || (mode == "jwt" && response_type == "code")
- 60
return super unless features.include?(:oauth_authorization_code_grant)
- 60
params = ["response=#{CGI.escape(jwt)}"]
- 60
params << redirect_url.query if redirect_url.query
- 60
redirect_url.query = params.join("&")
- 60
redirect(redirect_url.to_s)
- 60
elsif mode == "form_post.jwt"
- 12
return super unless features.include?(:oauth_authorization_code_grant)
- 12
response["Content-Type"] = "text/html"
- 12
body = form_post_response_html(redirect_url) do
- 12
"<input type=\"hidden\" name=\"response\" value=\"#{scope.h(jwt)}\" />"
end
- 12
response.write(body)
- 12
request.halt
- 48
elsif mode == "fragment.jwt" || (mode == "jwt" && response_type == "token")
- 48
return super unless features.include?(:oauth_implicit_grant)
- 48
params = ["response=#{CGI.escape(jwt)}"]
- 48
params << redirect_url.query if redirect_url.query
- 48
redirect_url.fragment = params.join("&")
- 48
redirect(redirect_url.to_s)
else
super
end
end
- 12
def _redirect_response_error(redirect_url, params)
- 36
response_mode = param_or_nil("response_mode")
- 36
return super unless response_mode.end_with?("jwt")
- 36
authorize_response(Hash[params], response_mode)
end
- 12
def jwt_encode_authorization_response_mode(params)
- 120
now = Time.now.to_i
- 40
claims = {
- 80
iss: oauth_jwt_issuer,
aud: oauth_application[oauth_applications_client_id_column],
exp: now + oauth_authorization_response_mode_expires_in,
iat: now
}.merge(params)
- 40
encode_params = {
- 80
jwks: oauth_application_jwks(oauth_application),
signing_algorithm: oauth_application[oauth_applications_authorization_signed_response_alg_column],
encryption_algorithm: oauth_application[oauth_applications_authorization_encrypted_response_alg_column],
encryption_method: oauth_application[oauth_applications_authorization_encrypted_response_enc_column]
}.compact
- 120
jwt_encode(claims, **encode_params)
end
- 12
def oauth_server_metadata_body(*)
- 24
super.tap do |data|
- 24
data[:authorization_signing_alg_values_supported] = authorization_signing_alg_values_supported
- 24
data[:authorization_encryption_alg_values_supported] = authorization_encryption_alg_values_supported
- 24
data[:authorization_encryption_enc_values_supported] = authorization_encryption_enc_values_supported
end
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_management_base, :OauthManagementBase) do
- 12
depends :oauth_authorize_base
- 12
button "Previous", "oauth_management_pagination_previous"
- 12
button "Next", "oauth_management_pagination_next"
- 12
def oauth_management_pagination_links(paginated_ds)
- 168
html = +'<nav aria-label="Pagination"><ul class="pagination">'
- 168
html << oauth_management_pagination_link(paginated_ds.prev_page, label: oauth_management_pagination_previous_button)
- 168
html << oauth_management_pagination_link(paginated_ds.current_page - 1) unless paginated_ds.first_page?
- 168
html << oauth_management_pagination_link(paginated_ds.current_page, label: paginated_ds.current_page, current: true)
- 168
html << oauth_management_pagination_link(paginated_ds.current_page + 1) unless paginated_ds.last_page?
- 168
html << oauth_management_pagination_link(paginated_ds.next_page, label: oauth_management_pagination_next_button)
- 168
html << "</ul></nav>"
end
- 12
def oauth_management_pagination_link(page, label: page, current: false, classes: "")
- 558
classes += " disabled" if current || !page
- 558
classes += " active" if current
- 558
if page
- 276
params = URI.encode_www_form(request.GET.merge("page" => page))
- 276
href = "#{request.path}?#{params}"
- 276
<<-HTML
<li class="page-item #{classes}" #{'aria-current="page"' if current}>
<a class="page-link" href="#{href}" tabindex="-1" aria-disabled="#{current || !page}">
#{label}
</a>
</li>
HTML
else
- 282
<<-HTML
<li class="page-item #{classes}">
<span class="page-link">
#{label}
#{'<span class="sr-only">(current)</span>' if current}
</span>
</li>
HTML
end
end
- 12
def post_configure
- 78
super
# TODO: remove this in v1, when resource-server mode does not load all of the provider features.
- 78
return unless db
- 78
db.extension :pagination
end
- 12
private
- 12
def per_page_param(default_per_page)
- 216
per_page = param_or_nil("per_page")
- 216
return default_per_page unless per_page
- 54
per_page = per_page.to_i
- 54
return default_per_page if per_page <= 0
- 54
[per_page, default_per_page].min
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_pkce, :OauthPkce) do
- 12
depends :oauth_authorization_code_grant
- 12
auth_value_method :oauth_require_pkce, true
- 12
auth_value_method :oauth_pkce_challenge_method, "S256"
- 12
auth_value_method :oauth_grants_code_challenge_column, :code_challenge
- 12
auth_value_method :oauth_grants_code_challenge_method_column, :code_challenge_method
- 12
auth_value_method :oauth_code_challenge_required_error_code, "invalid_request"
- 12
translatable_method :oauth_code_challenge_required_message, "code challenge required"
- 12
auth_value_method :oauth_unsupported_transform_algorithm_error_code, "invalid_request"
- 12
translatable_method :oauth_unsupported_transform_algorithm_message, "transform algorithm not supported"
- 12
private
- 12
def supports_auth_method?(oauth_application, auth_method)
- 72
return super unless auth_method == "none"
- 48
request.params.key?("code_verifier") || super
end
- 12
def validate_authorize_params
- 48
validate_pkce_challenge_params
- 36
super
end
- 12
def create_oauth_grant(create_params = {})
# PKCE flow
- 12
if (code_challenge = param_or_nil("code_challenge"))
- 12
code_challenge_method = param_or_nil("code_challenge_method") || oauth_pkce_challenge_method
- 12
create_params[oauth_grants_code_challenge_column] = code_challenge
- 12
create_params[oauth_grants_code_challenge_method_column] = code_challenge_method
end
- 12
super
end
- 12
def create_token_from_authorization_code(grant_params, *args, oauth_grant: nil)
- 72
oauth_grant ||= valid_locked_oauth_grant(grant_params)
- 72
if oauth_grant[oauth_grants_code_challenge_column]
- 60
code_verifier = param_or_nil("code_verifier")
- 60
redirect_response_error("invalid_request") unless code_verifier && check_valid_grant_challenge?(oauth_grant, code_verifier)
- 12
elsif oauth_require_pkce
- 12
redirect_response_error("code_challenge_required")
end
- 24
super({ oauth_grants_id_column => oauth_grant[oauth_grants_id_column] }, *args, oauth_grant: oauth_grant)
end
- 12
def validate_pkce_challenge_params
- 48
if param_or_nil("code_challenge")
- 24
challenge_method = param_or_nil("code_challenge_method")
- 24
redirect_response_error("code_challenge_required") unless oauth_pkce_challenge_method == challenge_method
else
- 24
return unless oauth_require_pkce
- 12
redirect_response_error("code_challenge_required")
end
end
- 12
def check_valid_grant_challenge?(grant, verifier)
- 48
challenge = grant[oauth_grants_code_challenge_column]
- 48
case grant[oauth_grants_code_challenge_method_column]
when "plain"
- 12
challenge == verifier
when "S256"
- 24
generated_challenge = Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false)
- 24
challenge == generated_challenge
else
- 12
redirect_response_error("unsupported_transform_algorithm")
end
end
- 12
def oauth_server_metadata_body(*)
- 12
super.tap do |data|
- 12
data[:code_challenge_methods_supported] = oauth_pkce_challenge_method
end
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_pushed_authorization_request, :OauthJwtPushedAuthorizationRequest) do
- 12
depends :oauth_authorize_base
- 12
auth_value_method :oauth_require_pushed_authorization_requests, false
- 12
auth_value_method :oauth_applications_require_pushed_authorization_requests_column, :require_pushed_authorization_requests
- 12
auth_value_method :oauth_pushed_authorization_request_expires_in, 90 # 90 seconds
- 12
auth_value_method :oauth_require_pushed_authorization_request_iss_request_object, true
- 12
auth_value_method :oauth_pushed_authorization_requests_table, :oauth_pushed_requests
- 8
%i[
oauth_application_id params code expires_in
- 4
].each do |column|
- 48
auth_value_method :"oauth_pushed_authorization_requests_#{column}_column", column
end
# /par
- 12
auth_server_route(:par) do |r|
- 48
require_oauth_application
- 36
before_par_route
- 36
r.post do
- 36
validate_par_params
- 24
ds = db[oauth_pushed_authorization_requests_table]
- 24
code = oauth_unique_id_generator
- 8
push_request_params = {
- 16
oauth_pushed_authorization_requests_oauth_application_id_column => oauth_application[oauth_applications_id_column],
oauth_pushed_authorization_requests_code_column => code,
oauth_pushed_authorization_requests_params_column => URI.encode_www_form(request.params),
oauth_pushed_authorization_requests_expires_in_column => Sequel.date_add(Sequel::CURRENT_TIMESTAMP,
seconds: oauth_pushed_authorization_request_expires_in)
}
- 24
rescue_from_uniqueness_error do
- 24
ds.insert(push_request_params)
end
- 24
json_response_success(
"request_uri" => "urn:ietf:params:oauth:request_uri:#{code}",
"expires_in" => oauth_pushed_authorization_request_expires_in
)
end
end
- 12
def check_csrf?
- 384
case request.path
when par_path
- 48
false
else
- 336
super
end
end
- 12
private
- 12
def validate_par_params
# https://datatracker.ietf.org/doc/html/rfc9126#section-2.1
# The request_uri authorization request parameter is one exception, and it MUST NOT be provided.
- 36
redirect_response_error("invalid_request") if param_or_nil("request_uri")
- 24
if features.include?(:oauth_jwt_secured_authorization_request)
- 12
if (request_object = param_or_nil("request"))
- 12
claims = decode_request_object(request_object)
# https://datatracker.ietf.org/doc/html/rfc9126#section-3-5.3
# reject the request if the authenticated client_id does not match the client_id claim in the Request Object
- 12
if (client_id = claims["client_id"]) && (client_id != oauth_application[oauth_applications_client_id_column])
redirect_response_error("invalid_request_object")
end
# requiring the iss claim to match the client_id is at the discretion of the authorization server
- 12
if oauth_require_pushed_authorization_request_iss_request_object &&
- 12
(iss = claims.delete("iss")) &&
iss != oauth_application[oauth_applications_client_id_column]
redirect_response_error("invalid_request_object")
end
- 12
if (aud = claims.delete("aud")) && !verify_aud(aud, oauth_jwt_issuer)
redirect_response_error("invalid_request_object")
end
- 12
claims.delete("exp")
- 12
request.params.delete("request")
- 12
claims.each do |k, v|
- 72
request.params[k.to_s] = v
end
elsif require_signed_request_object?
redirect_response_error("invalid_request_object")
end
end
- 24
validate_authorize_params
end
- 12
def validate_authorize_params
- 132
return super unless request.get? && request.path == authorize_path
- 84
if (request_uri = param_or_nil("request_uri"))
- 36
code = request_uri.delete_prefix("urn:ietf:params:oauth:request_uri:")
- 36
table = oauth_pushed_authorization_requests_table
- 36
ds = db[table]
- 36
pushed_request = ds.where(
oauth_pushed_authorization_requests_oauth_application_id_column => oauth_application[oauth_applications_id_column],
oauth_pushed_authorization_requests_code_column => code
).where(
Sequel.expr(Sequel[table][oauth_pushed_authorization_requests_expires_in_column]) >= Sequel::CURRENT_TIMESTAMP
).first
- 36
redirect_response_error("invalid_request") unless pushed_request
- 24
URI.decode_www_form(pushed_request[oauth_pushed_authorization_requests_params_column]).each do |k, v|
- 108
request.params[k.to_s] = v
end
- 24
request.params.delete("request_uri")
# we're removing the request_uri here, so the checkup for signed reqest has to be invalidated.
- 24
@require_signed_request_object = false
- 48
elsif oauth_require_pushed_authorization_requests ||
(oauth_application && oauth_application[oauth_applications_require_pushed_authorization_requests_column])
- 24
redirect_authorize_error("request_uri")
end
- 48
super
end
- 12
def oauth_server_metadata_body(*)
- 12
super.tap do |data|
- 12
data[:require_pushed_authorization_requests] = oauth_require_pushed_authorization_requests
- 12
data[:pushed_authorization_request_endpoint] = par_url
end
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_resource_indicators, :OauthResourceIndicators) do
- 12
depends :oauth_authorize_base
- 12
auth_value_method :oauth_grants_resource_column, :resource
- 12
def resource_indicators
- 480
return @resource_indicators if defined?(@resource_indicators)
- 120
resources = param_or_nil("resource")
- 120
return unless resources
- 120
if json_request? || param_or_nil("request") # signed request
- 24
resources = Array(resources)
else
- 96
query = if request.form_data?
- 60
request.body.rewind
- 60
request.body.read
else
- 36
request.query_string
end
# resource query param does not conform to rack parsing rules
- 96
resources = URI.decode_www_form(query).each_with_object([]) do |(k, v), memo|
- 504
memo << v if k == "resource"
end
end
- 120
@resource_indicators = resources
end
- 12
def require_oauth_authorization(*)
- 84
super
# done so to support token-in-grant-db, jwt, and resource-server mode
- 72
token_indicators = authorization_token[oauth_grants_resource_column] || authorization_token["resource"]
- 72
return unless token_indicators
- 60
token_indicators = token_indicators.split(" ") if token_indicators.is_a?(String)
- 120
authorization_required unless token_indicators.any? { |resource| base_url.start_with?(resource) }
end
- 12
private
- 12
def validate_token_params
- 48
super
- 48
return unless resource_indicators
- 48
resource_indicators.each do |resource|
- 48
redirect_response_error("invalid_target") unless check_valid_no_fragment_uri?(resource)
end
end
- 12
def create_token_from_token(oauth_grant, update_params)
return super unless resource_indicators
grant_indicators = oauth_grant[oauth_grants_resource_column]
grant_indicators = grant_indicators.split(" ") if grant_indicators.is_a?(String)
redirect_response_error("invalid_target") unless (grant_indicators - resource_indicators) != grant_indicators
super(oauth_grant, update_params.merge(oauth_grants_resource_column => resource_indicators))
end
- 12
module IndicatorAuthorizationCodeGrant
- 12
private
- 12
def validate_authorize_params
- 72
super
- 72
return unless resource_indicators
- 72
resource_indicators.each do |resource|
- 72
redirect_response_error("invalid_target") unless check_valid_no_fragment_uri?(resource)
end
end
- 12
def create_token_from_authorization_code(grant_params, *args, oauth_grant: nil)
- 48
return super unless resource_indicators
- 48
oauth_grant ||= valid_locked_oauth_grant(grant_params)
- 48
redirect_response_error("invalid_target") unless oauth_grant[oauth_grants_resource_column]
- 48
grant_indicators = oauth_grant[oauth_grants_resource_column]
- 48
grant_indicators = grant_indicators.split(" ") if grant_indicators.is_a?(String)
- 48
redirect_response_error("invalid_target") unless (grant_indicators - resource_indicators) != grant_indicators
# update ownership
- 36
if grant_indicators != resource_indicators
- 12
oauth_grant = __update_and_return__(
db[oauth_grants_table].where(oauth_grants_id_column => oauth_grant[oauth_grants_id_column]),
oauth_grants_resource_column => resource_indicators
)
end
- 36
super({ oauth_grants_id_column => oauth_grant[oauth_grants_id_column] }, *args, oauth_grant: oauth_grant)
end
- 12
def create_oauth_grant(create_params = {})
- 12
create_params[oauth_grants_resource_column] = resource_indicators.join(" ") if resource_indicators
- 12
super
end
end
- 12
module IndicatorIntrospection
- 12
def json_token_introspect_payload(grant)
- 12
return super unless grant[oauth_grants_id_column]
- 12
payload = super
- 12
token_indicators = grant[oauth_grants_resource_column]
- 12
token_indicators = token_indicators.split(" ") if token_indicators.is_a?(String)
- 12
payload[:aud] = token_indicators
- 12
payload
end
- 12
def introspection_request(*)
- 36
payload = super
- 36
payload[oauth_grants_resource_column] = payload["aud"] if payload["aud"]
- 36
payload
end
end
- 12
module IndicatorJwt
- 12
def jwt_claims(*)
- 12
return super unless resource_indicators
- 12
super.merge(aud: resource_indicators)
end
- 12
def jwt_decode(token, verify_aud: true, **args)
- 36
claims = super(token, verify_aud: false, **args)
- 36
return claims unless verify_aud
- 24
return unless claims["aud"] && claims["aud"].one? { |aud| request.url.starts_with?(aud) }
- 12
claims
end
end
- 12
def self.included(rodauth)
- 180
super
- 180
rodauth.send(:include, IndicatorAuthorizationCodeGrant) if rodauth.features.include?(:oauth_authorization_code_grant)
- 180
rodauth.send(:include, IndicatorIntrospection) if rodauth.features.include?(:oauth_token_introspection)
- 180
rodauth.send(:include, IndicatorJwt) if rodauth.features.include?(:oauth_jwt)
end
end
end
# frozen_string_literal: true
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_resource_server, :OauthResourceServer) do
- 12
depends :oauth_token_introspection
- 12
auth_value_method :is_authorization_server?, false
- 12
auth_methods(
:before_introspection_request
)
- 12
def authorization_token
- 216
return @authorization_token if defined?(@authorization_token)
# check if there is a token
- 108
access_token = fetch_access_token
- 108
return unless access_token
# where in resource server, NOT the authorization server.
- 84
payload = introspection_request("access_token", access_token)
- 84
return unless payload["active"]
- 72
@authorization_token = payload
end
- 12
def require_oauth_authorization(*scopes)
- 108
authorization_required unless authorization_token
- 72
aux_scopes = authorization_token["scope"]
- 72
token_scopes = if aux_scopes
- 72
aux_scopes.split(oauth_scope_separator)
else
[]
end
- 144
authorization_required unless scopes.any? { |scope| token_scopes.include?(scope) }
end
- 12
private
- 12
def introspection_request(token_type_hint, token)
- 84
introspect_url = URI("#{authorization_server_url}#{introspect_path}")
- 84
response = http_request(introspect_url, { "token_type_hint" => token_type_hint, "token" => token }) do |request|
- 84
before_introspection_request(request)
end
- 84
JSON.parse(response.body)
end
- 12
def before_introspection_request(request); end
end
end
# frozen_string_literal: true
- 12
require "onelogin/ruby-saml"
- 12
require "rodauth/oauth"
- 12
module Rodauth
- 12
Feature.define(:oauth_saml_bearer_grant, :OauthSamlBearerGrant) do
- 12
depends :oauth_assertion_base
- 12
auth_value_method :oauth_saml_name_identifier_format, "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
- 12
auth_value_method :oauth_saml_idp_cert_check_expiration, true
- 12
auth_value_method :max_param_bytesize, nil if Rodauth::VERSION >= "2.26.0"
- 12
auth_value_method :oauth_saml_settings_table, :oauth_saml_settings
- 8
%i[
id oauth_application_id
idp_cert idp_cert_fingerprint idp_cert_fingerprint_algorithm
name_identifier_format
issuer
audience
idp_cert_check_expiration
- 4
].each do |column|
- 108
auth_value_method :"oauth_saml_settings_#{column}_column", column
end
- 12
translatable_method :oauth_saml_assertion_not_base64_message, "SAML assertion must be in base64 format"
- 12
translatable_method :oauth_saml_assertion_single_issuer_message, "SAML assertion must have a single issuer"
- 12
translatable_method :oauth_saml_settings_not_found_message, "No SAML settings found for issuer"
- 12
auth_methods(
:require_oauth_application_from_saml2_bearer_assertion_issuer,
:require_oauth_application_from_saml2_bearer_assertion_subject,
:account_from_saml2_bearer_assertion
)
- 12
def oauth_grant_types_supported
- 24
super | %w[urn:ietf:params:oauth:grant-type:saml2-bearer]
end
- 12
private
- 12
def require_oauth_application_from_saml2_bearer_assertion_issuer(assertion)
- 12
parse_saml_assertion(assertion)
- 12
return unless @saml_settings
- 8
db[oauth_applications_table].where(
oauth_applications_id_column => @saml_settings[oauth_saml_settings_oauth_application_id_column]
- 4
).first
end
- 12
def require_oauth_application_from_saml2_bearer_assertion_subject(assertion)
- 12
parse_saml_assertion(assertion)
- 12
return unless @assertion
# 3.3.8 - For client authentication, the Subject MUST be the "client_id" of the OAuth client.
- 8
db[oauth_applications_table].where(
oauth_applications_client_id_column => @assertion.nameid
- 4
).first
end
- 12
def account_from_saml2_bearer_assertion(assertion)
- 12
parse_saml_assertion(assertion)
- 12
return unless @assertion