doorkeeper 6.0.0.rc2 → 6.0.0.rc3

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 (32) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +20 -0
  3. data/README.md +84 -1
  4. data/app/controllers/doorkeeper/authorizations_controller.rb +4 -1
  5. data/lib/doorkeeper/config.rb +40 -1
  6. data/lib/doorkeeper/helpers/controller.rb +3 -0
  7. data/lib/doorkeeper/http_fetcher.rb +164 -28
  8. data/lib/doorkeeper/models/access_token_mixin.rb +89 -2
  9. data/lib/doorkeeper/oauth/authorization/token.rb +5 -2
  10. data/lib/doorkeeper/oauth/authorization_code_request.rb +21 -0
  11. data/lib/doorkeeper/oauth/client.rb +4 -0
  12. data/lib/doorkeeper/oauth/client_id_metadata_document.rb +276 -0
  13. data/lib/doorkeeper/oauth/helpers/uri_checker.rb +5 -2
  14. data/lib/doorkeeper/oauth/metadata_response.rb +6 -3
  15. data/lib/doorkeeper/oauth/pre_authorization.rb +43 -4
  16. data/lib/doorkeeper/oauth/refresh_token_request.rb +29 -4
  17. data/lib/doorkeeper/oauth/token_introspection.rb +14 -2
  18. data/lib/doorkeeper/orm/active_record/redirect_uri_validator.rb +13 -4
  19. data/lib/doorkeeper/orm/active_record/stale_records_cleaner.rb +6 -3
  20. data/lib/doorkeeper/rails/routes/abstract_router.rb +1 -1
  21. data/lib/doorkeeper/rails/routes.rb +5 -1
  22. data/lib/doorkeeper/rake/db.rake +14 -1
  23. data/lib/doorkeeper/revocable_tokens/revocable_refresh_token.rb +13 -1
  24. data/lib/doorkeeper/version.rb +1 -1
  25. data/lib/doorkeeper.rb +1 -0
  26. data/lib/generators/doorkeeper/client_id_metadata_documents_generator.rb +33 -0
  27. data/lib/generators/doorkeeper/refresh_token_revoked_at_generator.rb +43 -0
  28. data/lib/generators/doorkeeper/templates/add_client_id_metadata_materialized_at_to_applications_migration.rb.erb +7 -0
  29. data/lib/generators/doorkeeper/templates/add_refresh_token_revoked_at_to_access_tokens.rb.erb +13 -0
  30. data/lib/generators/doorkeeper/templates/initializer.rb +47 -0
  31. data/lib/generators/doorkeeper/templates/migration.rb.erb +7 -0
  32. metadata +8 -3
@@ -207,6 +207,24 @@ module Doorkeeper
207
207
  access_token.refresh_token_scopes == scopes
208
208
  end
209
209
 
210
+ # Checks whether a candidate token's refresh token can still be used.
211
+ #
212
+ # A row whose refresh token was revoked on its own (see
213
+ # +previous_access_token_kept_on_refresh?+) keeps a usable access token,
214
+ # so it is still among the authorized tokens, but reusing it would hand
215
+ # the client a refresh token the token endpoint refuses. A candidate
216
+ # without a refresh token has nothing to refuse.
217
+ #
218
+ # @param access_token [Doorkeeper::AccessToken]
219
+ # the candidate token for reuse
220
+ #
221
+ # @return [Boolean] true if the candidate has no refresh token or one
222
+ # that is not revoked, false otherwise
223
+ #
224
+ def refresh_token_usable?(access_token)
225
+ access_token.refresh_token.blank? || !access_token.refresh_token_revoked?
226
+ end
227
+
210
228
  # Checks whether the token scopes match the scopes from the parameters
211
229
  #
212
230
  # @param token_scopes [#to_s]
@@ -304,6 +322,31 @@ module Doorkeeper
304
322
  column_names.include?("refresh_token_scopes")
305
323
  end
306
324
 
325
+ # A refresh token shares its row with the access token it was issued
326
+ # with, so revoking the row (+revoked_at+) revokes both. The
327
+ # `refresh_token_revoked_at` column (added by the
328
+ # `doorkeeper:refresh_token_revoked_at` generator) lets the refresh
329
+ # token be revoked on its own.
330
+ #
331
+ # @return [Boolean] true if the refresh_token_revoked_at column exists
332
+ #
333
+ def refresh_token_revoked_at_supported?
334
+ column_names.include?("refresh_token_revoked_at")
335
+ end
336
+
337
+ # Determines if the refresh grant leaves the previous access token
338
+ # usable until it expires and revokes only the refresh token it was
339
+ # issued with. Requires both the `refresh_token_revoked_at` column and
340
+ # the +revoke_previous_access_token_on_refresh+ option set to false,
341
+ # so that adding the column alone changes nothing.
342
+ #
343
+ # @return [Boolean] true if only the refresh token is revoked on refresh
344
+ #
345
+ def previous_access_token_kept_on_refresh?
346
+ !Doorkeeper.config.revoke_previous_access_token_on_refresh &&
347
+ refresh_token_revoked_at_supported?
348
+ end
349
+
307
350
  # Looking for not expired AccessToken record with a matching set of
308
351
  # scopes that belongs to specific Application and Resource Owner.
309
352
  # If it doesn't exists - then creates it.
@@ -354,6 +397,7 @@ module Doorkeeper
354
397
  application, resource_owner, scopes, custom_attributes: custom_attributes, include_expired: false,
355
398
  ) do |token|
356
399
  refresh_token_matches?(token, token_attributes) &&
400
+ refresh_token_usable?(token) &&
357
401
  refresh_token_scopes_match?(token, scopes) &&
358
402
  resource_indicators_match?(token, requested_resource) &&
359
403
  Doorkeeper::OAuth::Authorization::Token.within_public_client_expires_in?(
@@ -533,6 +577,45 @@ module Doorkeeper
533
577
  self[:refresh_token_scopes]
534
578
  end
535
579
 
580
+ # Indicates whether the refresh token of this record has been revoked:
581
+ # either together with the access token (+revoked_at+) or on its own
582
+ # (+refresh_token_revoked_at+). A row revoked before the
583
+ # `refresh_token_revoked_at` column existed therefore needs no backfill.
584
+ #
585
+ # The column is consulted whenever it exists, whatever
586
+ # +revoke_previous_access_token_on_refresh+ says at the moment: turning
587
+ # the option back on must not bring refresh tokens revoked under it back
588
+ # to life.
589
+ #
590
+ # @return [Boolean] true if the refresh token is revoked
591
+ #
592
+ def refresh_token_revoked?
593
+ return true if revoked?
594
+ return false unless self.class.refresh_token_revoked_at_supported?
595
+
596
+ refresh_revoked_at = self[:refresh_token_revoked_at]
597
+ !!(refresh_revoked_at && refresh_revoked_at <= Time.now.utc)
598
+ end
599
+
600
+ # Revokes the refresh token after it was exchanged for a new one. The
601
+ # access token issued with it is revoked as well unless
602
+ # +previous_access_token_kept_on_refresh?+, in which case it stays usable
603
+ # until it expires.
604
+ #
605
+ # Revoking a token through the revocation endpoint or +#revoke+ still
606
+ # revokes the whole record (RFC 7009 §2.1).
607
+ #
608
+ # @param clock [Time] time object
609
+ #
610
+ def revoke_refresh_token(clock = Time)
611
+ return revoke(clock) unless self.class.previous_access_token_kept_on_refresh?
612
+ return if refresh_token_revoked?
613
+
614
+ self.class.with_primary_role do
615
+ update_attribute(:refresh_token_revoked_at, clock.now.utc)
616
+ end
617
+ end
618
+
536
619
  # JSON representation of the Access Token instance.
537
620
  #
538
621
  # @return [Hash] hash with token data
@@ -621,12 +704,14 @@ module Doorkeeper
621
704
  end
622
705
 
623
706
  # Revokes token with `:refresh_token` equal to `:previous_refresh_token`
624
- # and clears `:previous_refresh_token` attribute.
707
+ # and clears `:previous_refresh_token` attribute. Only the refresh token
708
+ # of that record is revoked when
709
+ # `previous_access_token_kept_on_refresh?` (see `#revoke_refresh_token`).
625
710
  #
626
711
  def revoke_previous_refresh_token!
627
712
  return if !self.class.refresh_token_revoked_on_use? || previous_refresh_token.blank?
628
713
 
629
- old_refresh_token&.revoke
714
+ old_refresh_token&.revoke_refresh_token
630
715
 
631
716
  if self.class.respond_to?(:with_primary_role)
632
717
  self.class.with_primary_role { update_attribute(:previous_refresh_token, "") }
@@ -705,6 +790,8 @@ module Doorkeeper
705
790
  attributes[:resource_owner] = resource_owner
706
791
  end
707
792
 
793
+ attributes[:resource] = resource if self.class.resource_indicators_supported?
794
+
708
795
  Doorkeeper.config.custom_access_token_attributes.each do |attribute_name|
709
796
  attributes[attribute_name] = public_send(attribute_name)
710
797
  end
@@ -103,11 +103,14 @@ module Doorkeeper
103
103
  private
104
104
 
105
105
  # The cap +public_client_access_token_expires_in+ puts on tokens
106
- # issued to +application+, or nil when none applies.
106
+ # issued to +application+, or nil when none applies. A client known
107
+ # from its metadata document stays capped when it authenticates with
108
+ # private_key_jwt, as anyone can publish one with keys of their own.
107
109
  def public_client_expires_in_cap(configuration, application)
108
110
  cap = configuration.public_client_access_token_expires_in
109
111
  return if cap.nil?
110
- return if application.respond_to?(:confidential?) && application.confidential?
112
+ return if application.respond_to?(:confidential?) && application.confidential? &&
113
+ !OAuth::ClientIdMetadataDocument.materialized?(application)
111
114
 
112
115
  cap
113
116
  end
@@ -8,6 +8,9 @@ module Doorkeeper
8
8
  validate :grant, error: Errors::InvalidGrant
9
9
  # @see https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
10
10
  validate :redirect_uri, error: Errors::InvalidGrant
11
+ # Runs before :code_verifier, which has nothing to verify against when
12
+ # the PKCE columns are missing.
13
+ validate :pkce_storage, error: Errors::ServerError
11
14
  validate :code_verifier, error: Errors::InvalidGrant
12
15
  # Runs last, so the single-use enforcement it performs only acts once
13
16
  # the caller has proven possession of the code (redirect_uri + PKCE).
@@ -131,6 +134,24 @@ module Doorkeeper
131
134
  )
132
135
  end
133
136
 
137
+ # With force_pkce the code_verifier must be checked against the
138
+ # challenge stored on the grant. Without the columns the
139
+ # doorkeeper:pkce generator adds there is no stored challenge, and
140
+ # #validate_code_verifier would accept any verifier. Refuse the exchange
141
+ # with server_error instead (see PreAuthorization#validate_pkce_storage,
142
+ # which stops such a code from being issued in the first place).
143
+ def validate_pkce_storage
144
+ return true unless Doorkeeper.config.force_pkce?
145
+ return true if pkce_supported?
146
+
147
+ ::Rails.logger.error(
148
+ "[DOORKEEPER] force_pkce is enabled but the PKCE columns are missing from the " \
149
+ "oauth_access_grants table, so authorization codes cannot be exchanged. " \
150
+ "Run `rails generate doorkeeper:pkce` and apply the migration.",
151
+ )
152
+ false
153
+ end
154
+
134
155
  # if either side (server or client) request PKCE, check the verifier
135
156
  # against the DB - if PKCE is supported
136
157
  def validate_code_verifier
@@ -31,6 +31,8 @@ module Doorkeeper
31
31
 
32
32
  def self.find(uid, method = Doorkeeper.config.application_model.method(:by_uid))
33
33
  return unless (application = method.call(uid))
34
+ return if ClientIdMetadataDocument.orphaned?(application) ||
35
+ ClientIdMetadataDocument.other_client?(application, uid)
34
36
 
35
37
  new(application)
36
38
  end
@@ -44,6 +46,8 @@ module Doorkeeper
44
46
  return find(credentials.uid) if credentials.respond_to?(:pre_authenticated?) && credentials.pre_authenticated?
45
47
 
46
48
  return unless (application = method.call(credentials.uid, credentials.secret))
49
+ return if ClientIdMetadataDocument.orphaned?(application) ||
50
+ ClientIdMetadataDocument.other_client?(application, credentials.uid)
47
51
 
48
52
  new(application)
49
53
  end
@@ -0,0 +1,276 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Doorkeeper
4
+ module OAuth
5
+ # OAuth Client ID Metadata Documents (draft-ietf-oauth-client-id-metadata-document)
6
+ # for public clients: an https client_id is the URL of the client's own metadata,
7
+ # fetched and kept as an application row, since grants and tokens reference one.
8
+ #
9
+ # Rows written from a document carry the time of the first write in MARKER, which is what tells
10
+ # them apart from registered applications (draft-03, Supporting Both Pre-Registered and
11
+ # Unregistered Clients). ActiveRecord only.
12
+ module ClientIdMetadataDocument
13
+ MARKER = :client_id_metadata_materialized_at
14
+
15
+ # A refused client_id is looked up like a registered one, so its document is never fetched. Neither is
16
+ # the issuer's own, as its tokens' aud and its assertions' iss would then name this server
17
+ # (draft-03, Client Identifier URL Confusion Attacks); other parties' identifiers are for
18
+ # allow_client_id_metadata_document to refuse.
19
+ def self.url?(client_id)
20
+ Doorkeeper.config.use_client_id_metadata_documents? && url_form?(client_id) &&
21
+ client_id.to_s != Doorkeeper.config.issuer.to_s && allowed?(client_id)
22
+ end
23
+
24
+ # The port is held to what the fetcher could connect to, so the two agree on what is fetchable.
25
+ def self.url_form?(client_id)
26
+ return false unless storable?(client_id.to_s)
27
+
28
+ uri = URI.parse(client_id.to_s)
29
+ uri.is_a?(URI::HTTPS) && uri.host.present? && HttpFetcher::PORT_RANGE.cover?(uri.port) &&
30
+ uri.path.length > 1 && uri.userinfo.nil? && uri.fragment.nil? &&
31
+ (uri.path.split("/").map { |segment| URI.decode_uri_component(segment) } & %w[. ..]).empty?
32
+ rescue URI::InvalidURIError, ArgumentError
33
+ false
34
+ end
35
+
36
+ # At most 255 characters, as the uid column holds no more on MySQL, and no control characters,
37
+ # which URI.parse lets through in a query, and which would reach the log on a refusal.
38
+ def self.storable?(client_id)
39
+ client_id.length <= 255 && !client_id.match?(/[[:cntrl:]]/)
40
+ end
41
+
42
+ def self.materialized?(application)
43
+ application.respond_to?(MARKER) && application.public_send(MARKER).present?
44
+ end
45
+
46
+ # A row written from a document while the option was on, and is no longer, or whose
47
+ # client_id is refused by now.
48
+ def self.orphaned?(application)
49
+ materialized?(application) && !url?(application.uid)
50
+ end
51
+
52
+ def self.allowed?(client_id)
53
+ Doorkeeper.config.allow_client_id_metadata_document.call(client_id)
54
+ end
55
+
56
+ # A row written from a document stands for one client_id only, compared as a simple string
57
+ # (draft-03, Client Identifier URL). The database may compare more loosely: MySQL's default
58
+ # collations ignore case and accents, some of them trailing spaces as well.
59
+ def self.other_client?(application, client_id)
60
+ materialized?(application) && application.uid != client_id.to_s
61
+ end
62
+
63
+ # The authorization endpoint's lookup. A registered application wins (draft-03, Pre-Registering
64
+ # Client Identifier URLs); otherwise the document is fetched, and a failed fetch refuses the
65
+ # client even when a row was written from an earlier one (draft-03, Metadata Discovery Errors).
66
+ def self.application(client_id)
67
+ model = Doorkeeper.config.application_model
68
+ registered = model.by_uid(client_id)
69
+ return registered if registered && !materialized?(registered)
70
+ return if other_client?(registered, client_id)
71
+
72
+ entry = cache.fetch(client_id) { (document = fetch(client_id)) && { document: document, fetched_at: Time.current } }
73
+ return unless entry
74
+ return registered if registered && registered.updated_at >= entry[:fetched_at]
75
+
76
+ materialize(model, registered || model.new(uid: client_id), entry[:document])
77
+ end
78
+
79
+ # The authorization response has to carry +iss+ (RFC 9207) for a client known from its document,
80
+ # which Doorkeeper only adds once +issuer+ is set (draft-03, Authorization Response). Only a
81
+ # warning, as the issuer may be resolved per request.
82
+ def self.warn_without_issuer
83
+ return if Doorkeeper.config.issuer.present?
84
+
85
+ ::Rails.logger.warn("[DOORKEEPER] use_client_id_metadata_documents needs `issuer` to be set, " \
86
+ "as the authorization response must carry iss (RFC 9207)")
87
+ end
88
+
89
+ def self.cache
90
+ @cache ||= DocumentCache.new
91
+ end
92
+
93
+ # Logs why a document is refused, as the client itself only sees invalid_client.
94
+ def self.fetch(client_id)
95
+ document = JSON.parse(HttpFetcher.new.fetch(client_id))
96
+ reason = refusal(client_id, document)
97
+ return log_refusal(client_id, reason) if reason
98
+
99
+ warn_without_issuer
100
+ document
101
+ rescue HttpFetcher::FetchError => e
102
+ log_refusal(client_id, "its document could not be fetched: #{e.message}")
103
+ rescue JSON::ParserError
104
+ # Not its message, which older json versions fill with the body as served.
105
+ log_refusal(client_id, "its document is no JSON")
106
+ end
107
+
108
+ # Why a document is refused, the first reason that applies, or nil.
109
+ def self.refusal(client_id, document)
110
+ return "its document is no JSON object" unless document.is_a?(Hash)
111
+ return "its document names another client_id" unless document["client_id"] == client_id
112
+ return "its document has malformed redirect_uris, scope or client_name" unless well_typed?(document)
113
+ return "its document declares no authorization code flow" unless code_flow_declared?(document)
114
+ return "its client_name cannot be shown" unless displayable?(display_name(client_id, document["client_name"]))
115
+ return "its document declares no public client" unless public_client?(document)
116
+ return "client_authentication does not offer none" unless public_clients_accepted?
117
+ return "its document declares private_key_jwt without an https jwks_uri" if keyless_private_key_jwt?(document)
118
+
119
+ "its document carries a client secret or both jwks and jwks_uri" unless credentials_allowed?(document)
120
+ end
121
+
122
+ # No shared secret, and not both jwks and jwks_uri, which leaves open which keys count
123
+ # (RFC 7591 §2, draft-03, Credential and Key Material Restrictions).
124
+ def self.credentials_allowed?(document)
125
+ document.keys.none? { |key| key.start_with?("client_secret") } &&
126
+ !(document.key?("jwks") && document.key?("jwks_uri"))
127
+ end
128
+
129
+ def self.well_typed?(document)
130
+ uris = document["redirect_uris"]
131
+ uris.is_a?(Array) && uris.any? && uris.all? { |uri| uri.is_a?(String) } &&
132
+ document.values_at("scope", "client_name").all? { |value| value.nil? || value.is_a?(String) }
133
+ end
134
+
135
+ # A client known from its document gets the authorization code flow only, so its grant and response
136
+ # types, RFC 7591's defaults when absent, have to include it; otherwise what the client declares and
137
+ # what this server supports for it do not intersect (draft-03, Client Information Discovery).
138
+ CODE_FLOW = { "grant_types" => "authorization_code", "response_types" => "code" }.freeze
139
+
140
+ def self.code_flow_declared?(document)
141
+ CODE_FLOW.all? do |property, type|
142
+ declared = document[property].nil? ? [type] : document[property]
143
+ declared.is_a?(Array) && declared.all?(String) && declared.include?(type)
144
+ end
145
+ end
146
+
147
+ SHARED_SECRET_METHODS = %w[client_secret_basic client_secret_post client_secret_jwt].freeze
148
+
149
+ # Public clients only: the method is +none+, or the supported methods (OpenID Connect RP Metadata
150
+ # Choices) include +none+ and no shared-secret one, as ChatGPT's do with +private_key_jwt+. A method
151
+ # named next to them must be among them. Naming neither means +none+, not RFC 7591's default of
152
+ # +client_secret_basic+ (draft-03, Client Authentication).
153
+ def self.public_client?(document)
154
+ method, supported = document.values_at("token_endpoint_auth_method", "token_endpoint_auth_methods_supported")
155
+ return [nil, "none"].include?(method) if supported.nil?
156
+ return false unless supported.is_a?(Array) && supported.all?(String)
157
+
158
+ (method.nil? || supported.include?(method)) && supported.include?("none") &&
159
+ (supported & SHARED_SECRET_METHODS).empty?
160
+ end
161
+
162
+ # Without +none+ among the client authentication methods, the code could never be exchanged.
163
+ def self.public_clients_accepted?
164
+ Doorkeeper.config.client_authentication_methods.any? { |method| method.name.to_s == "none" }
165
+ end
166
+
167
+ # The host leads the name, as the consent screen's only verified hint of who is asking.
168
+ def self.display_name(client_id, client_name)
169
+ host = URI.parse(client_id).host
170
+ client_name.present? ? "#{host}: #{client_name}" : host
171
+ end
172
+
173
+ # Fits a varchar(255) column, and puts no control characters, line breaks or bidi controls on the
174
+ # consent screen. Joiners (U+200C, U+200D) stay allowed, as names in many scripts need them.
175
+ UNDISPLAYABLE = /[\p{Cc}\p{Zl}\p{Zp}\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/
176
+
177
+ def self.displayable?(name)
178
+ name.length <= 255 && !name.match?(UNDISPLAYABLE)
179
+ end
180
+
181
+ def self.materialize(model, application, document)
182
+ scopes = scopes(document["scope"])
183
+ return log_refusal(application.uid, "leaves no scopes") if scopes.nil?
184
+
185
+ redirect_uris = acceptable_redirect_uris(application, document["redirect_uris"])
186
+ return log_refusal(application.uid, "lists no acceptable redirect URI") if redirect_uris.empty?
187
+
188
+ application.assign_attributes(
189
+ name: display_name(application.uid, document["client_name"]),
190
+ redirect_uri: redirect_uris.join("\n"),
191
+ scopes: scopes,
192
+ confidential: false,
193
+ )
194
+ assign_keys(application, document) if application.respond_to?(:jwks_uri=)
195
+ application.public_send(:"#{MARKER}=", Time.current) unless materialized?(application)
196
+ # A savepoint, so that losing the uid race leaves a caller's transaction usable for the re-read.
197
+ return application if model.with_primary_role { model.transaction(requires_new: true) { application.save } }
198
+
199
+ concurrent_row(model, application) || log_refusal(application.uid, application.errors.full_messages.to_sentence)
200
+ rescue ActiveRecord::RecordNotUnique
201
+ concurrent_row(model, application)
202
+ end
203
+
204
+ def self.assign_keys(application, document)
205
+ application.jwks_uri = jwks_uri(document["jwks_uri"])
206
+ application.confidential = private_key_jwt?(document)
207
+ # Generated on create only, so a public client turning confidential may still lack one.
208
+ application.renew_secret if application.confidential? && application.secret.blank?
209
+ end
210
+
211
+ # A client declaring private_key_jwt, on a server offering it, must authenticate with it: as a
212
+ # confidential client, +none+ no longer redeems its codes or refresh tokens (draft-03, Client
213
+ # Authentication). Only among its supported methods, next to +none+, as public_client? refuses the rest.
214
+ def self.private_key_jwt?(document)
215
+ Array(document["token_endpoint_auth_methods_supported"]).include?("private_key_jwt") &&
216
+ Doorkeeper.config.client_authentication_methods.any? { |method| method.name.to_s == "private_key_jwt" }
217
+ end
218
+
219
+ # Its keys could not be fetched, as Doorkeeper verifies assertions against a jwks_uri only, so it
220
+ # could not authenticate as it must.
221
+ def self.keyless_private_key_jwt?(document)
222
+ private_key_jwt?(document) && jwks_uri(document["jwks_uri"]).nil?
223
+ end
224
+
225
+ # Kept where the application model has the column, so private_key_jwt can verify the client's
226
+ # assertions: ChatGPT picks it whenever the server offers it. Https only, as the key resolver
227
+ # fetches nothing else (and refuses a malformed one itself), and at most 255 characters, like the uid.
228
+ def self.jwks_uri(uri)
229
+ uri if uri.is_a?(String) && uri.length <= 255 && uri.start_with?("https://")
230
+ end
231
+
232
+ # A concurrent first request may have written the row in the meantime, on the primary.
233
+ def self.concurrent_row(model, application)
234
+ return if application.persisted?
235
+
236
+ row = model.with_primary_role { model.by_uid(application.uid) }
237
+ row if materialized?(row) && !other_client?(row, application.uid)
238
+ end
239
+
240
+ # A document may list redirect URIs this server refuses (e.g. http://localhost); keep the rest.
241
+ # Whitespace would split one URI into several once stored. Out-of-band shows the code to whoever
242
+ # is at the screen, which an unregistered client must not be able to ask for.
243
+ def self.acceptable_redirect_uris(application, uris)
244
+ validator = RedirectUriValidator.new(attributes: [:redirect_uri])
245
+ uris.select do |uri|
246
+ next false if uri.blank? || uri.match?(/\s/) || NonStandard::IETF_WG_OAUTH2_OOB_METHODS.include?(uri)
247
+
248
+ probe = application.class.new
249
+ validator.validate_each(probe, :redirect_uri, uri)
250
+ probe.errors.empty?
251
+ end
252
+ end
253
+
254
+ # Blank scopes would mean all server scopes, so a client left without any is refused,
255
+ # also under an empty cap.
256
+ def self.scopes(requested)
257
+ allowed = Doorkeeper.config.client_id_metadata_document_scopes
258
+ scopes = if allowed.nil?
259
+ requested.present? ? OAuth::Scopes.from_string(requested) : Doorkeeper.config.default_scopes
260
+ elsif requested.present?
261
+ OAuth::Scopes.from_string(requested) & allowed
262
+ else
263
+ OAuth::Scopes.from_array(allowed.to_a)
264
+ end
265
+ scopes.to_s.presence
266
+ end
267
+
268
+ # A fetch error may quote what the document's host sent, so the line is scrubbed like a client_name.
269
+ def self.log_refusal(client_id, reason)
270
+ line = "[DOORKEEPER] client_id #{client_id} refused: #{reason}"
271
+ ::Rails.logger.warn(line.dup.force_encoding(Encoding::UTF_8).scrub("?").gsub(UNDISPLAYABLE, "?"))
272
+ nil
273
+ end
274
+ end
275
+ end
276
+ end
@@ -16,7 +16,7 @@ module Doorkeeper
16
16
  SCRIPT_SCHEMES = %w[javascript vbscript data].freeze
17
17
 
18
18
  def self.valid?(url)
19
- return true if oob_uri?(url)
19
+ return Doorkeeper.config.allow_oob_redirect_uris if oob_uri?(url)
20
20
 
21
21
  uri = as_uri(url)
22
22
  valid_scheme?(uri) && iff_host?(uri) && uri.fragment.nil? && uri.opaque.nil?
@@ -62,8 +62,11 @@ module Doorkeeper
62
62
  url.fragment == client_url.fragment
63
63
  end
64
64
 
65
+ # RFC 8252 §8.3 discourages `localhost` for clients but says it behaves
66
+ # like the loopback IP literals, and native clients such as Claude Code
67
+ # register it, so its port may vary too.
65
68
  def self.loopback_uri?(uri)
66
- IPAddr.new(uri.host).loopback?
69
+ uri.host == "localhost" || IPAddr.new(uri.host).loopback?
67
70
  rescue IPAddr::Error, IPAddr::InvalidAddressError
68
71
  false
69
72
  end
@@ -25,18 +25,19 @@ module Doorkeeper
25
25
  token_endpoint: token_endpoint,
26
26
  revocation_endpoint: revocation_endpoint,
27
27
  introspection_endpoint: (introspection_endpoint if introspection_enabled?),
28
- scopes_supported: scopes_supported,
28
+ scopes_supported: scopes_supported.presence,
29
29
  response_types_supported: response_types_supported,
30
30
  response_modes_supported: response_modes_supported,
31
31
  grant_types_supported: grant_types_supported,
32
32
  token_endpoint_auth_methods_supported: token_endpoint_auth_methods_supported,
33
- code_challenge_methods_supported: code_challenge_methods_supported,
33
+ code_challenge_methods_supported: code_challenge_methods_supported.presence,
34
34
  # RFC 9207: true only when an issuer is configured, matching the
35
35
  # condition under which the iss parameter is emitted. false survives
36
36
  # the compaction below, so it is advertised explicitly.
37
37
  authorization_response_iss_parameter_supported: config.issuer.present?,
38
38
  # RFC 8707: advertise resource indicator support when configured.
39
39
  resource_indicators_supported: resource_indicators_supported?,
40
+ client_id_metadata_document_supported: (true if config.use_client_id_metadata_documents?),
40
41
  }
41
42
  data.compact!
42
43
 
@@ -55,7 +56,9 @@ module Doorkeeper
55
56
 
56
57
  def headers
57
58
  {
58
- "Cache-Control" => "public",
59
+ # The document is built from the request host, so a shared cache
60
+ # must not hand one request's answer to the next (RFC 9111 §5.2.2.7).
61
+ "Cache-Control" => "private",
59
62
  "Content-Type" => "application/json; charset=utf-8",
60
63
  }
61
64
  end
@@ -26,6 +26,11 @@ module Doorkeeper
26
26
  validate :scopes, error: Errors::InvalidScope
27
27
  validate :code_challenge, error: Errors::InvalidRequest
28
28
  validate :code_challenge_method, error: Errors::InvalidCodeChallengeMethod
29
+ # Runs after :code_challenge so a missing challenge is still answered as
30
+ # the client's error. The method is not: without the columns no method is
31
+ # supported (#validate_code_challenge_method skips the check), so an
32
+ # unknown one is answered with server_error like a known one.
33
+ validate :pkce_storage, error: Errors::ServerError
29
34
  validate :resource_indicators, error: Errors::InvalidTarget
30
35
  # Runs after :resource_indicators so a malformed target is still answered
31
36
  # as the client's error rather than the server's.
@@ -127,7 +132,11 @@ module Doorkeeper
127
132
  end
128
133
 
129
134
  def validate_client
130
- @client = OAuth::Client.find(client_id)
135
+ @client = if ClientIdMetadataDocument.url?(client_id)
136
+ ClientIdMetadataDocument.application(client_id)&.then { |application| OAuth::Client.new(application) }
137
+ else
138
+ OAuth::Client.find(client_id)
139
+ end
131
140
  @client.present?
132
141
  end
133
142
 
@@ -201,7 +210,10 @@ module Doorkeeper
201
210
  end
202
211
 
203
212
  def validate_code_challenge
204
- return true unless Doorkeeper.config.force_pkce?
213
+ # A client known from its metadata document is unregistered, so it always uses PKCE, with S256
214
+ # (RFC 9700 §2.1.1), also when it authenticates with private_key_jwt.
215
+ document_client = ClientIdMetadataDocument.materialized?(client.application)
216
+ return true unless Doorkeeper.config.force_pkce? || document_client
205
217
  # PKCE (RFC 7636) protects the exchange of an authorization code, so
206
218
  # a code_challenge is only required from response types that issue one
207
219
  # ("code" and code-carrying hybrid types like "code id_token"). For
@@ -210,9 +222,9 @@ module Doorkeeper
210
222
  # verifier could ever be checked, so requiring a challenge would
211
223
  # reject those requests over a parameter that cannot be validated.
212
224
  return true unless code_issuing_response_type?
213
- return true if code_challenge.present?
225
+ return true if code_challenge.present? && (!document_client || code_challenge_method == "S256")
214
226
 
215
- @invalid_request_reason = :invalid_code_challenge
227
+ @invalid_request_reason = code_challenge.blank? ? :invalid_code_challenge : :unknown
216
228
  false
217
229
  end
218
230
 
@@ -223,6 +235,33 @@ module Doorkeeper
223
235
  (code_challenge_method.present? && Doorkeeper.config.pkce_code_challenge_methods_supported.include?(code_challenge_method))
224
236
  end
225
237
 
238
+ # force_pkce promises that every authorization code is bound to a
239
+ # code_challenge, but the columns that hold the challenge come from the
240
+ # separate doorkeeper:pkce generator. Without them Authorization::Code
241
+ # drops the challenge and the token endpoint has nothing to check the
242
+ # code_verifier against, so the code would be exchangeable with any
243
+ # verifier while the server appears to enforce PKCE. Like a missing
244
+ # `resource` column below, that is a server misconfiguration: refuse to
245
+ # issue the code and answer server_error (RFC 6749 Section 4.1.2.1).
246
+ #
247
+ # Only response types that issue a code are refused, as in
248
+ # #validate_code_challenge. Without force_pkce nothing changes: PKCE is
249
+ # then opportunistic and a challenge is ignored when it cannot be stored.
250
+ # A client known from its metadata document always has to use PKCE, so it
251
+ # is refused like under force_pkce.
252
+ def validate_pkce_storage
253
+ return true unless Doorkeeper.config.force_pkce? || ClientIdMetadataDocument.materialized?(client.application)
254
+ return true unless code_issuing_response_type?
255
+ return true if Doorkeeper.config.access_grant_model.pkce_supported?
256
+
257
+ ::Rails.logger.error(
258
+ "[DOORKEEPER] PKCE is required but the PKCE columns are missing from the " \
259
+ "oauth_access_grants table, so authorization codes cannot be issued. " \
260
+ "Run `rails generate doorkeeper:pkce` and apply the migration.",
261
+ )
262
+ false
263
+ end
264
+
226
265
  def validate_resource_indicators
227
266
  validator = Doorkeeper.config.resource_indicator_validator
228
267
  # When no validator is configured, resource indicators are ignored (feature disabled)