doorkeeper 5.8.2 → 5.9.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +71 -3
  3. data/README.md +2 -3
  4. data/app/controllers/doorkeeper/authorizations_controller.rb +38 -4
  5. data/app/controllers/doorkeeper/authorized_applications_controller.rb +23 -0
  6. data/app/controllers/doorkeeper/tokens_controller.rb +7 -9
  7. data/app/views/doorkeeper/applications/show.html.erb +5 -5
  8. data/app/views/doorkeeper/authorizations/new.html.erb +1 -1
  9. data/app/views/doorkeeper/authorizations/show.html.erb +1 -1
  10. data/config/locales/en.yml +12 -11
  11. data/lib/doorkeeper/config/validations.rb +2 -2
  12. data/lib/doorkeeper/config.rb +31 -8
  13. data/lib/doorkeeper/engine.rb +2 -4
  14. data/lib/doorkeeper/errors.rb +15 -2
  15. data/lib/doorkeeper/helpers/controller.rb +7 -4
  16. data/lib/doorkeeper/models/access_grant_mixin.rb +10 -6
  17. data/lib/doorkeeper/models/access_token_mixin.rb +30 -13
  18. data/lib/doorkeeper/models/concerns/expiration_time_sql_math.rb +8 -0
  19. data/lib/doorkeeper/models/concerns/polymorphic_resource_owner.rb +0 -1
  20. data/lib/doorkeeper/models/concerns/revocable.rb +8 -1
  21. data/lib/doorkeeper/models/concerns/write_to_primary.rb +57 -0
  22. data/lib/doorkeeper/oauth/authorization/code.rb +3 -1
  23. data/lib/doorkeeper/oauth/authorization_code_request.rb +1 -0
  24. data/lib/doorkeeper/oauth/client/credentials.rb +58 -6
  25. data/lib/doorkeeper/oauth/client_credentials/creator.rb +7 -3
  26. data/lib/doorkeeper/oauth/client_credentials/issuer.rb +1 -1
  27. data/lib/doorkeeper/oauth/client_credentials_request.rb +1 -0
  28. data/lib/doorkeeper/oauth/error_response.rb +21 -1
  29. data/lib/doorkeeper/oauth/forbidden_token_response.rb +1 -7
  30. data/lib/doorkeeper/oauth/helpers/uri_checker.rb +14 -0
  31. data/lib/doorkeeper/oauth/pre_authorization.rb +27 -0
  32. data/lib/doorkeeper/oauth/refresh_token_request.rb +19 -7
  33. data/lib/doorkeeper/oauth/scopes.rb +3 -2
  34. data/lib/doorkeeper/oauth/token.rb +95 -2
  35. data/lib/doorkeeper/oauth/token_introspection.rb +7 -3
  36. data/lib/doorkeeper/orm/active_record/mixins/access_grant.rb +1 -0
  37. data/lib/doorkeeper/orm/active_record/mixins/access_token.rb +25 -7
  38. data/lib/doorkeeper/orm/active_record/mixins/application.rb +6 -0
  39. data/lib/doorkeeper/orm/active_record/redirect_uri_validator.rb +5 -1
  40. data/lib/doorkeeper/orm/active_record/stale_records_cleaner.rb +10 -2
  41. data/lib/doorkeeper/orm/active_record.rb +8 -12
  42. data/lib/doorkeeper/rails/routes.rb +1 -1
  43. data/lib/doorkeeper/request.rb +19 -7
  44. data/lib/doorkeeper/version.rb +2 -2
  45. data/lib/doorkeeper.rb +14 -0
  46. data/lib/generators/doorkeeper/remove_applications_secret_not_null_constraint_generator.rb +2 -2
  47. data/lib/generators/doorkeeper/templates/initializer.rb +28 -2
  48. metadata +5 -11
@@ -14,6 +14,7 @@ module Doorkeeper
14
14
  include Models::Scopes
15
15
  include Models::ResourceOwnerable
16
16
  include Models::ExpirationTimeSqlMath
17
+ include Models::Concerns::WriteToPrimary
17
18
 
18
19
  module ClassMethods
19
20
  # Returns an instance of the Doorkeeper::AccessToken with
@@ -66,12 +67,14 @@ module Doorkeeper
66
67
  # instance of the Resource Owner model or it's ID
67
68
  #
68
69
  def revoke_all_for(application_id, resource_owner, clock = Time)
69
- by_resource_owner(resource_owner)
70
- .where(
71
- application_id: application_id,
72
- revoked_at: nil,
73
- )
74
- .update_all(revoked_at: clock.now.utc)
70
+ with_primary_role do
71
+ by_resource_owner(resource_owner)
72
+ .where(
73
+ application_id: application_id,
74
+ revoked_at: nil,
75
+ )
76
+ .update_all(revoked_at: clock.now.utc)
77
+ end
75
78
  end
76
79
 
77
80
  # Looking for not revoked Access Token with a matching set of scopes
@@ -86,7 +89,8 @@ module Doorkeeper
86
89
  # @param custom_attributes [Nilable Hash]
87
90
  # A nil value, or hash with keys corresponding to the custom attributes
88
91
  # configured with the `custom_access_token_attributes` config option.
89
- # A nil value will ignore custom attributes.
92
+ # A nil value will ignore custom attributes, while an empty hash will
93
+ # only match tokens that have no custom attributes set.
90
94
  #
91
95
  # @return [Doorkeeper::AccessToken, nil] Access Token instance or
92
96
  # nil if matching record was not found
@@ -121,7 +125,8 @@ module Doorkeeper
121
125
  # @param custom_attributes [Nilable Hash]
122
126
  # A nil value, or hash with keys corresponding to the custom attributes
123
127
  # configured with the `custom_access_token_attributes` config option.
124
- # A nil value will ignore custom attributes.
128
+ # A nil value will ignore custom attributes, while an empty hash will
129
+ # only match tokens that have no custom attributes set.
125
130
  #
126
131
  # @return [Doorkeeper::AccessToken, nil] Access Token instance or
127
132
  # nil if matching record was not found
@@ -217,9 +222,13 @@ module Doorkeeper
217
222
  scopes = Doorkeeper::OAuth::Scopes.from_string(scopes) if scopes.is_a?(String)
218
223
 
219
224
  if Doorkeeper.config.reuse_access_token
220
- custom_attributes = extract_custom_attributes(token_attributes).presence
225
+ # An empty hash must stay distinct from nil here: nil ignores custom
226
+ # attributes when matching, while an empty hash only matches tokens
227
+ # that have no custom attributes set.
228
+ custom_attributes = extract_custom_attributes(token_attributes)
221
229
  access_token = matching_token_for(
222
- application, resource_owner, scopes, custom_attributes: custom_attributes, include_expired: false)
230
+ application, resource_owner, scopes, custom_attributes: custom_attributes, include_expired: false,
231
+ )
223
232
 
224
233
  return access_token if access_token&.reusable?
225
234
  end
@@ -260,7 +269,9 @@ module Doorkeeper
260
269
  token_attributes[:resource_owner_id] = resource_owner_id_for(resource_owner)
261
270
  end
262
271
 
263
- create!(token_attributes)
272
+ with_primary_role do
273
+ create!(token_attributes)
274
+ end
264
275
  end
265
276
 
266
277
  # Looking for not revoked Access Token records that belongs to specific
@@ -324,7 +335,8 @@ module Doorkeeper
324
335
  # A hash containing only the custom access token attributes.
325
336
  def extract_custom_attributes(attributes)
326
337
  attributes.with_indifferent_access.slice(
327
- *Doorkeeper.configuration.custom_access_token_attributes)
338
+ *Doorkeeper.configuration.custom_access_token_attributes,
339
+ )
328
340
  end
329
341
  end
330
342
 
@@ -435,7 +447,12 @@ module Doorkeeper
435
447
  return if !self.class.refresh_token_revoked_on_use? || previous_refresh_token.blank?
436
448
 
437
449
  old_refresh_token&.revoke
438
- update_attribute(:previous_refresh_token, "")
450
+
451
+ if self.class.respond_to?(:with_primary_role)
452
+ self.class.with_primary_role { update_attribute(:previous_refresh_token, "") }
453
+ else
454
+ update_attribute(:previous_refresh_token, "")
455
+ end
439
456
  end
440
457
 
441
458
  private
@@ -5,6 +5,14 @@ module Doorkeeper
5
5
  module ExpirationTimeSqlMath
6
6
  extend ::ActiveSupport::Concern
7
7
 
8
+ WARNING_MESSAGE = <<~WARNING.squish
9
+ [DOORKEEPER] Doorkeeper doesn't support expiration time math for your database adapter.
10
+ Records with an individual expires_in value longer than the global TTL may be incorrectly processed.
11
+ Please add a class method `custom_expiration_time_sql` to your AccessToken/AccessGrant models/mixins to provide a custom
12
+ SQL expression to calculate access token expiration time. See lib/doorkeeper/orm/active_record/mixins/access_token.rb
13
+ for more details.
14
+ WARNING
15
+
8
16
  class ExpirationTimeSqlGenerator
9
17
  attr_reader :model
10
18
 
@@ -27,4 +27,3 @@ module Doorkeeper
27
27
  end
28
28
  end
29
29
  end
30
-
@@ -9,7 +9,14 @@ module Doorkeeper
9
9
  # @param clock [Time] time object
10
10
  #
11
11
  def revoke(clock = Time)
12
- update_attribute(:revoked_at, clock.now.utc)
12
+ return if revoked?
13
+
14
+ # Wrap in with_primary_role if the model class supports it
15
+ if self.class.respond_to?(:with_primary_role)
16
+ self.class.with_primary_role { update_attribute(:revoked_at, clock.now.utc) }
17
+ else
18
+ update_attribute(:revoked_at, clock.now.utc)
19
+ end
13
20
  end
14
21
 
15
22
  # Indicates whether the object has been revoked.
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Doorkeeper
4
+ module Models
5
+ module Concerns
6
+ # Provides support for Rails read replicas by ensuring write operations
7
+ # use the primary database when automatic role switching is enabled.
8
+ #
9
+ # When Rails uses automatic role switching with read replicas, GET requests
10
+ # are routed to read-only databases. However, Doorkeeper may need to write
11
+ # to the database during GET requests (e.g., creating access tokens during
12
+ # implicit grant flow). This concern wraps write operations with
13
+ # `connected_to(role: :writing)` to ensure they use the primary database.
14
+ #
15
+ # This concern is only active when:
16
+ # 1. ActiveRecord supports `connected_to` (Rails 6.1+)
17
+ # 2. The configuration option is enabled
18
+ #
19
+ module WriteToPrimary
20
+ extend ActiveSupport::Concern
21
+
22
+ class_methods do
23
+ # Executes the given block with a connection to the primary database
24
+ # for writing, if read replica support is enabled and available.
25
+ #
26
+ # @yield Block to execute with write connection
27
+ # @return The result of the block
28
+ #
29
+ def with_primary_role(&block)
30
+ if should_use_primary_role?
31
+ ::ActiveRecord::Base.connected_to(role: :writing, &block)
32
+ else
33
+ yield
34
+ end
35
+ end
36
+
37
+ private
38
+
39
+ # Determines if we should explicitly use the primary role for writes
40
+ #
41
+ # @return [Boolean]
42
+ #
43
+ def should_use_primary_role?
44
+ # Guard clause: return false if ActiveRecord is not available
45
+ return false unless defined?(::ActiveRecord::Base)
46
+
47
+ # Only use primary role if:
48
+ # 1. The enable_multiple_database_roles option is enabled in config
49
+ # 2. ActiveRecord supports connected_to (Rails 6.1+)
50
+ Doorkeeper.config.enable_multiple_database_roles &&
51
+ ::ActiveRecord::Base.respond_to?(:connected_to)
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
57
+ end
@@ -14,7 +14,9 @@ module Doorkeeper
14
14
  def issue_token!
15
15
  return @token if defined?(@token)
16
16
 
17
- @token = Doorkeeper.config.access_grant_model.create!(access_grant_attributes)
17
+ @token = Doorkeeper.config.access_grant_model.with_primary_role do
18
+ Doorkeeper.config.access_grant_model.create!(access_grant_attributes)
19
+ end
18
20
  end
19
21
 
20
22
  def oob_redirect
@@ -14,6 +14,7 @@ module Doorkeeper
14
14
  :invalid_request_reason, :missing_param
15
15
 
16
16
  def initialize(server, grant, client, parameters = {})
17
+ super()
17
18
  @server = server
18
19
  @client = client
19
20
  @grant = grant
@@ -5,12 +5,48 @@ module Doorkeeper
5
5
  class Client
6
6
  Credentials = Struct.new(:uid, :secret) do
7
7
  class << self
8
+ # Extracts the client credentials from the request using the
9
+ # configured extraction methods. The first method that yields
10
+ # credentials wins, as it always has.
11
+ #
12
+ # Raises Errors::MultipleClientAuthMethods when the request
13
+ # authenticates the client with more than one method, or presents
14
+ # more than one client identity, which RFC 6749 §2.3 forbids ("The
15
+ # client MUST NOT use more than one authentication method in each
16
+ # request").
8
17
  def from_request(request, *credentials_methods)
9
- credentials_methods.inject(nil) do |_, method|
10
- method = self.method(method) if method.is_a?(Symbol)
11
- credentials = Credentials.new(*method.call(request))
12
- break credentials if credentials.present?
13
- end
18
+ # Callable extractors are opaque: they may legitimately overlap the
19
+ # built-in methods they are configured with, and evaluating all of
20
+ # them would also break the existing contract that the extractors
21
+ # after the matching one are not called. Such configurations keep
22
+ # the historical behaviour untouched, including the fact that a
23
+ # request authenticating with more than one method, or presenting
24
+ # more than one client identity, resolves to the first extracted
25
+ # credentials instead of being rejected: the extractor that would
26
+ # have surfaced the second identity is never evaluated. The
27
+ # +client_credentials+ configuration option documents this.
28
+ return first_from_request(request, credentials_methods) unless credentials_methods.all?(Symbol)
29
+
30
+ credentials = credentials_methods.filter_map { |method| extract(request, method) }
31
+
32
+ # Only credentials carrying a secret authenticate the client. A bare
33
+ # uid is a public client identifying itself (RFC 6749 §2.3 "none"),
34
+ # not an authentication method of its own, so it doesn't count
35
+ # towards the single-method rule — RFC 7521 §4.2, for example,
36
+ # explicitly allows a client_id next to another authentication
37
+ # method.
38
+ raise Errors::MultipleClientAuthMethods if credentials.count { |c| c.secret.present? } > 1
39
+
40
+ # §4.2 allows that bare client_id because it identifies the *same*
41
+ # client as the authentication method it accompanies. Credentials
42
+ # naming two different clients are two client identities in one
43
+ # request and authenticate neither: without this check the first
44
+ # extracted uid would win and the other identity would be silently
45
+ # discarded, so the caller could authenticate as one client while
46
+ # the request asks to act as another.
47
+ raise Errors::MultipleClientAuthMethods if credentials.uniq(&:uid).size > 1
48
+
49
+ credentials.first
14
50
  end
15
51
 
16
52
  def from_params(request)
@@ -19,10 +55,26 @@ module Doorkeeper
19
55
 
20
56
  def from_basic(request)
21
57
  authorization = request.authorization
22
- if authorization.present? && authorization =~ /^Basic (.*)/m
58
+ if authorization.present? && authorization =~ /^Basic (.*)/im
23
59
  Base64.decode64(Regexp.last_match(1)).split(/:/, 2)
24
60
  end
25
61
  end
62
+
63
+ private
64
+
65
+ def first_from_request(request, credentials_methods)
66
+ credentials_methods.inject(nil) do |_, method|
67
+ credentials = extract(request, method)
68
+ break credentials if credentials
69
+ end
70
+ end
71
+
72
+ # Returns the credentials the given method extracts from the request,
73
+ # or nil when it extracts none.
74
+ def extract(request, method)
75
+ method = self.method(method) if method.is_a?(Symbol)
76
+ Credentials.new(*method.call(request)).presence
77
+ end
26
78
  end
27
79
 
28
80
  # Public clients may have their secret blank, but "credentials" are
@@ -45,10 +45,14 @@ module Doorkeeper
45
45
  end
46
46
 
47
47
  def find_active_existing_token_for(client, scopes, attributes)
48
- custom_attributes = Doorkeeper.config.access_token_model.
49
- extract_custom_attributes(attributes).presence
48
+ # An empty hash must stay distinct from nil here: nil ignores custom
49
+ # attributes when matching, while an empty hash only matches tokens
50
+ # that have no custom attributes set.
51
+ custom_attributes = Doorkeeper.config.access_token_model
52
+ .extract_custom_attributes(attributes)
50
53
  Doorkeeper.config.access_token_model.matching_token_for(
51
- client, nil, scopes, custom_attributes: custom_attributes, include_expired: false)
54
+ client, nil, scopes, custom_attributes: custom_attributes, include_expired: false,
55
+ )
52
56
  end
53
57
  end
54
58
  end
@@ -39,7 +39,7 @@ module Doorkeeper
39
39
  scopes,
40
40
  use_refresh_token: false,
41
41
  expires_in: ttl,
42
- **attributes
42
+ **attributes,
43
43
  )
44
44
  end
45
45
  end
@@ -13,6 +13,7 @@ module Doorkeeper
13
13
  @client = client
14
14
  @server = server
15
15
  @response = nil
16
+ @grant_type = Doorkeeper::OAuth::CLIENT_CREDENTIALS
16
17
  @original_scopes = parameters[:scope]
17
18
  @parameters = parameters.except(:scope)
18
19
  end
@@ -88,13 +88,33 @@ module Doorkeeper
88
88
 
89
89
  def exception_class
90
90
  return @exception_class if @exception_class
91
+
91
92
  raise NotImplementedError, "error response must define #exception_class"
92
93
  end
93
94
 
94
95
  private
95
96
 
96
97
  def authenticate_info
97
- %(Bearer realm="#{realm}", error="#{name}", error_description="#{description}")
98
+ %(Bearer realm="#{realm}", error="#{sanitize_error_values(name)}", error_description="#{sanitize_error_values(description)}")
99
+ end
100
+
101
+ # This method removes any characters that are invalid in error
102
+ # details per RFC6750.
103
+ #
104
+ # > Values for the "error" and "error_description" attributes
105
+ # > (specified in Appendixes A.7 and A.8 of [RFC6749]) MUST NOT
106
+ # > include characters outside the set %x20-21 (" " or "!") / %x23-5B /
107
+ # > %x5D-7E (ascii "#" to "~" without "\").
108
+ def sanitize_error_values(string)
109
+ string.to_s.each_char.map do |char|
110
+ if char.in?("\x20".encode("utf-8").."\x21".encode("utf-8")) ||
111
+ char.in?("\x23".encode("utf-8").."\x5B".encode("utf-8")) ||
112
+ char.in?("\x5D".encode("utf-8").."\x7E".encode("utf-8"))
113
+ char
114
+ else
115
+ "_"
116
+ end
117
+ end.join("")
98
118
  end
99
119
  end
100
120
  end
@@ -8,7 +8,7 @@ module Doorkeeper
8
8
  end
9
9
 
10
10
  def initialize(attributes = {})
11
- super(attributes.merge(name: :invalid_scope, state: :forbidden))
11
+ super(attributes.merge(name: :insufficient_scope, state: :forbidden))
12
12
  @scopes = attributes[:scopes]
13
13
  end
14
14
 
@@ -16,12 +16,6 @@ module Doorkeeper
16
16
  :forbidden
17
17
  end
18
18
 
19
- def headers
20
- headers = super
21
- headers.delete "WWW-Authenticate"
22
- headers
23
- end
24
-
25
19
  def description
26
20
  @description ||= I18n.t("doorkeeper.errors.messages.forbidden_token.missing_scope",
27
21
  oauth_scopes: @scopes.map(&:to_s).join(" "),)
@@ -6,6 +6,15 @@ module Doorkeeper
6
6
  module OAuth
7
7
  module Helpers
8
8
  module URIChecker
9
+ # Schemes a user agent evaluates in the document that navigates to
10
+ # them instead of fetching a resource from somewhere else. With
11
+ # `response_mode=form_post` that document is the authorization
12
+ # server's own page, so a redirect URI with one of these schemes would
13
+ # run the client's script on the server's origin. None of them can be
14
+ # a legitimate redirection endpoint (RFC 6749 Section 3.1.2), so they
15
+ # are refused regardless of the `forbid_redirect_uri` configuration.
16
+ SCRIPT_SCHEMES = %w[javascript vbscript data].freeze
17
+
9
18
  def self.valid?(url)
10
19
  return true if oob_uri?(url)
11
20
 
@@ -62,10 +71,15 @@ module Doorkeeper
62
71
 
63
72
  def self.valid_scheme?(uri)
64
73
  return false if uri.scheme.blank?
74
+ return false if script_scheme?(uri)
65
75
 
66
76
  %w[localhost].exclude?(uri.scheme)
67
77
  end
68
78
 
79
+ def self.script_scheme?(uri)
80
+ SCRIPT_SCHEMES.include?(uri.scheme.to_s.downcase)
81
+ end
82
+
69
83
  def self.hypertext_scheme?(uri)
70
84
  %w[http https].include?(uri.scheme)
71
85
  end
@@ -5,6 +5,14 @@ module Doorkeeper
5
5
  class PreAuthorization
6
6
  include Validations
7
7
 
8
+ # The validations that identify the client and its redirect URI. None of
9
+ # them depend on the resource owner, and none of their failures leaves a
10
+ # redirect target worth trusting: RFC 6749 Section 4.1.2.1 (Section
11
+ # 4.2.2.1 for the implicit flow) asks for the resource owner to be
12
+ # informed when the client_id is missing or invalid, and Section 3.1.2.4
13
+ # asks the same for the redirect URI.
14
+ CLIENT_VALIDATIONS = %i[client_id client redirect_uri].freeze
15
+
8
16
  validate :client_id, error: Errors::InvalidRequest
9
17
  validate :client, error: Errors::InvalidClient
10
18
  validate :client_supports_grant_flow, error: Errors::UnauthorizedClient
@@ -40,6 +48,25 @@ module Doorkeeper
40
48
  valid?
41
49
  end
42
50
 
51
+ # Runs only CLIENT_VALIDATIONS, in declared order, so a request naming an
52
+ # unknown client or an invalid redirect URI can be refused on its own -
53
+ # the validations in between (client_supports_grant_flow,
54
+ # resource_owner_authorize_for_client) answer a different question and
55
+ # are left to a full #validate run.
56
+ def client_valid?
57
+ @error = nil
58
+ @missing_param = nil
59
+
60
+ self.class.validations.each do |validation|
61
+ next unless CLIENT_VALIDATIONS.include?(validation[:attribute])
62
+
63
+ @error = validation[:options][:error] unless send("validate_#{validation[:attribute]}")
64
+ break if @error
65
+ end
66
+
67
+ @error.nil?
68
+ end
69
+
43
70
  def scopes
44
71
  Scopes.from_string(scope)
45
72
  end
@@ -18,6 +18,7 @@ module Doorkeeper
18
18
  @server = server
19
19
  @refresh_token = refresh_token
20
20
  @credentials = credentials
21
+ @grant_type = Doorkeeper::OAuth::REFRESH_TOKEN
21
22
  @original_scopes = parameters[:scope] || parameters[:scopes]
22
23
  @refresh_token_parameter = parameters[:refresh_token]
23
24
  @client = load_client(credentials) if credentials
@@ -30,12 +31,23 @@ module Doorkeeper
30
31
  end
31
32
 
32
33
  def before_successful_response
33
- refresh_token.transaction do
34
- refresh_token.lock!
34
+ if refresh_token_revoked_on_use?
35
+ # No locking needed when refresh tokens are revoked on use
36
+ # because the old token is revoked later when the new token is used.
37
+ # This allows multiple concurrent refresh requests to succeed during the
38
+ # transition period, after which the old refresh token will be revoked.
35
39
  raise Errors::InvalidGrantReuse if refresh_token.revoked?
36
40
 
37
- refresh_token.revoke unless refresh_token_revoked_on_use?
38
41
  create_access_token
42
+ else
43
+ # Use locking when refresh tokens are revoked immediately
44
+ # to prevent race conditions where multiple tokens could be created
45
+ refresh_token.with_lock do
46
+ raise Errors::InvalidGrantReuse if refresh_token.revoked?
47
+
48
+ refresh_token.revoke
49
+ create_access_token
50
+ end
39
51
  end
40
52
  super
41
53
  end
@@ -122,10 +134,10 @@ module Doorkeeper
122
134
 
123
135
  def custom_token_attributes_with_data
124
136
  refresh_token
125
- .attributes
126
- .with_indifferent_access
127
- .slice(*Doorkeeper.config.custom_access_token_attributes)
128
- .symbolize_keys
137
+ .attributes
138
+ .with_indifferent_access
139
+ .slice(*Doorkeeper.config.custom_access_token_attributes)
140
+ .symbolize_keys
129
141
  end
130
142
  end
131
143
  end
@@ -88,7 +88,7 @@ module Doorkeeper
88
88
  #
89
89
  # @param other The set of scopes to filter
90
90
  def allowed(other)
91
- filtered_scopes = other.select { |scope| self.exists?(scope) }
91
+ filtered_scopes = other.select { |scope| exists?(scope) }
92
92
  self.class.from_array(filtered_scopes)
93
93
  end
94
94
 
@@ -115,7 +115,8 @@ module Doorkeeper
115
115
  return false if allowed_pattern[0] != request_pattern[0]
116
116
  return false if allowed_pattern[1].blank?
117
117
  return false if request_pattern[1].blank?
118
- return true if allowed_pattern[1] == DYNAMIC_SCOPE_WILDCARD && allowed_pattern[1].present?
118
+
119
+ return true if allowed_pattern[1] == DYNAMIC_SCOPE_WILDCARD
119
120
 
120
121
  allowed_pattern[1] == request_pattern[1]
121
122
  end
@@ -3,8 +3,54 @@
3
3
  module Doorkeeper
4
4
  module OAuth
5
5
  class Token
6
+ # Built-in extractors that read a request parameter, and the parameter
7
+ # each of them reads. RFC 6750 treats the form-encoded body (§2.2) and
8
+ # the URI query string (§2.3) as two distinct transmission methods, but
9
+ # Rack and ActionDispatch both collapse them into a single parameter
10
+ # hash — ActionDispatch lets the query win, Rack lets the body win — so
11
+ # a request carrying the parameter in both would present a single value
12
+ # to the extractor and never be refused. The multi-method check reads
13
+ # the two sources separately for these extractors; selection keeps
14
+ # using the extractor, so which one wins is unchanged.
15
+ PARAMETER_EXTRACTORS = {
16
+ from_access_token_param: "access_token",
17
+ from_bearer_param: "bearer_token",
18
+ }.freeze
19
+
6
20
  class << self
21
+ # RFC 6750 §2: "Clients MUST NOT use more than one method to transmit
22
+ # the token in each request", and §3.1 lists using more than one method
23
+ # among the conditions an invalid_request answers. Returning the first
24
+ # method that yields a value would discard every other token presented
25
+ # in the same request with no error, warning or log entry, leaving
26
+ # which token authorizes the request to be decided by the configured
27
+ # order of +access_token_methods+ rather than by what the caller sent —
28
+ # so a layer in front of Doorkeeper that reads a different one of them
29
+ # can reach a different verdict about the very same request.
30
+ #
31
+ # What §2 forbids is using more than one method, so the check counts
32
+ # transmission methods rather than comparing the tokens they carry:
33
+ # the same value presented twice is still two methods. Refusal answers
34
+ # nil: the caller is told the request carries no usable token and
35
+ # fails closed with the invalid_token (401) response, keeping every
36
+ # calling contract on this stable branch intact — the invalid_request
37
+ # (400) that §3.1 strictly prescribes needs a new error and render
38
+ # path, so it ships with 6.0 only.
39
+ #
40
+ # Only the built-in extractors — symbols naming methods on this class,
41
+ # all of them side-effect-free reads of the request — take part in
42
+ # that check. A custom callable extractor is a configuration adapter
43
+ # rather than a transmission method: it keeps the historical
44
+ # first-wins selection and is never invoked more than once, the same
45
+ # exemption client authentication gives its legacy callable
46
+ # extractors (Request#validate_client_authentication!).
7
47
  def from_request(request, *methods)
48
+ used = methods.sum do |method|
49
+ method.is_a?(Symbol) ? transmission_methods_used(request, method) : 0
50
+ end
51
+
52
+ return if used > 1
53
+
8
54
  methods.inject(nil) do |_, method|
9
55
  method = self.method(method) if method.is_a?(Symbol)
10
56
  credentials = method.call(request)
@@ -23,11 +69,11 @@ module Doorkeeper
23
69
  end
24
70
 
25
71
  def from_access_token_param(request)
26
- request.parameters[:access_token]
72
+ parameters(request)[:access_token]
27
73
  end
28
74
 
29
75
  def from_bearer_param(request)
30
- request.parameters[:bearer_token]
76
+ parameters(request)[:bearer_token]
31
77
  end
32
78
 
33
79
  def from_bearer_authorization(request)
@@ -44,6 +90,53 @@ module Doorkeeper
44
90
 
45
91
  private
46
92
 
93
+ # How many transmission methods the given built-in extractor finds a
94
+ # token in. Usually one, or none — but for the parameter extractors
95
+ # above it is the body and the query counted separately, since the
96
+ # parameter hash collapsed them into the single value the extractor
97
+ # reads. That value is counted on its own only when neither raw source
98
+ # explains it, so a token reaching the extractor by some other route —
99
+ # an :access_token path segment, or a host that overrode the extractor
100
+ # — is still counted exactly once rather than twice.
101
+ def transmission_methods_used(request, method)
102
+ value = self.method(method).call(request).presence
103
+
104
+ parameter = PARAMETER_EXTRACTORS[method]
105
+ return value ? 1 : 0 unless parameter
106
+
107
+ sources = parameter_sources(request, parameter)
108
+ sources.size + (value && !sources.include?(value) ? 1 : 0)
109
+ end
110
+
111
+ # The form-encoded body (§2.2) and the URI query (§2.3) as Rack
112
+ # exposes them, for a request object that keeps the two apart.
113
+ def parameter_sources(request, parameter)
114
+ return [] unless request.respond_to?(:GET) && request.respond_to?(:POST)
115
+
116
+ query = request.GET
117
+ body = body_parameters(request)
118
+ return [] unless query.is_a?(Hash) && body.is_a?(Hash)
119
+
120
+ [query[parameter], body[parameter]].filter_map(&:presence)
121
+ end
122
+
123
+ # A body ActionDispatch cannot parse — malformed JSON under a JSON
124
+ # content type, say — carries no token. Reading it must not raise out
125
+ # of the extractors, which host apps call from places that run after
126
+ # their own ParseError handling (instrumentation, exception apps), the
127
+ # same way ActionDispatch's own #filtered_parameters treats that error.
128
+ def parameters(request)
129
+ request.parameters
130
+ rescue ActionDispatch::Http::Parameters::ParseError
131
+ {}
132
+ end
133
+
134
+ def body_parameters(request)
135
+ request.POST
136
+ rescue ActionDispatch::Http::Parameters::ParseError
137
+ {}
138
+ end
139
+
47
140
  def token_from_basic_header(header, pattern)
48
141
  encoded_header = token_from_header(header, pattern)
49
142
  decode_basic_credentials_token(encoded_header)