authproto 0.3.0.beta1 → 0.3.0.beta3

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 (91) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +67 -7
  3. data/README.md +128 -5
  4. data/examples/confidential_client/Gemfile.lock +5 -1
  5. data/examples/confidential_client/README.md +12 -2
  6. data/examples/confidential_client/app.rb +23 -22
  7. data/examples/confidential_client/config/{client-metadata.example.json → oauth-client-metadata.example.json} +0 -1
  8. data/examples/confidential_client/scripts/generate_keys.rb +15 -9
  9. data/examples/minisky_console/Gemfile.lock +2 -2
  10. data/examples/minisky_console/README.md +20 -1
  11. data/examples/minisky_console/localhost.rb +13 -28
  12. data/examples/minisky_console/production.rb +10 -4
  13. data/lib/authproto/client.rb +185 -253
  14. data/lib/authproto/configuration.rb +37 -16
  15. data/lib/authproto/dpop/client.rb +96 -79
  16. data/lib/authproto/dpop/key_set.rb +157 -0
  17. data/lib/authproto/dpop/nonce_manager.rb +38 -39
  18. data/lib/authproto/dpop/proof_generator.rb +39 -50
  19. data/lib/authproto/dpop.rb +19 -0
  20. data/lib/authproto/errors.rb +1 -1
  21. data/lib/authproto/http_client.rb +17 -31
  22. data/lib/authproto/http_helpers.rb +85 -0
  23. data/lib/authproto/localhost_server.rb +15 -6
  24. data/lib/authproto/metadata/authorization_server.rb +364 -0
  25. data/lib/authproto/metadata/client_metadata.rb +587 -0
  26. data/lib/authproto/metadata/resource_server.rb +139 -0
  27. data/lib/authproto/{server_metadata.rb → metadata.rb} +7 -7
  28. data/lib/authproto/minisky.rb +41 -41
  29. data/lib/authproto/par/client.rb +60 -115
  30. data/lib/authproto/par/client_assertion.rb +95 -21
  31. data/lib/authproto/par/request.rb +60 -146
  32. data/lib/authproto/par/response.rb +9 -10
  33. data/lib/authproto/par.rb +5 -6
  34. data/lib/authproto/pkce.rb +29 -106
  35. data/lib/authproto/serialization/session.rb +36 -18
  36. data/lib/authproto/serialization/token_set.rb +6 -7
  37. data/lib/authproto/state/session.rb +93 -37
  38. data/lib/authproto/state/session_manager.rb +97 -23
  39. data/lib/authproto/state/token_set.rb +19 -19
  40. data/lib/authproto/state.rb +4 -4
  41. data/lib/authproto/storage/key_builder.rb +3 -11
  42. data/lib/authproto/storage/memory.rb +8 -2
  43. data/lib/authproto/token/refresh.rb +50 -91
  44. data/lib/authproto/validated_uri.rb +80 -0
  45. data/lib/authproto/version.rb +1 -1
  46. data/lib/authproto.rb +1 -1
  47. data/sig/authproto/client.rbs +11 -14
  48. data/sig/authproto/dependencies.rbs +2 -0
  49. data/sig/authproto/dpop/client.rbs +9 -9
  50. data/sig/authproto/dpop/{key_manager.rbs → key_set.rbs} +9 -11
  51. data/sig/authproto/dpop/nonce_manager.rbs +4 -5
  52. data/sig/authproto/dpop/proof_generator.rbs +10 -15
  53. data/sig/authproto/dpop.rbs +6 -0
  54. data/sig/authproto/http_client.rbs +2 -2
  55. data/sig/authproto/http_helpers.rbs +7 -0
  56. data/sig/authproto/localhost_server.rbs +1 -1
  57. data/sig/authproto/{server_metadata → metadata}/authorization_server.rbs +19 -12
  58. data/sig/authproto/metadata/client_metadata.rbs +119 -0
  59. data/sig/authproto/metadata/resource_server.rbs +28 -0
  60. data/sig/authproto/minisky_oauth.rbs +9 -4
  61. data/sig/authproto/par/client.rbs +8 -14
  62. data/sig/authproto/par/client_assertion.rbs +6 -1
  63. data/sig/authproto/par/request.rbs +5 -28
  64. data/sig/authproto/par/response.rbs +1 -5
  65. data/sig/authproto/pkce.rbs +6 -16
  66. data/sig/authproto/serialization/session.rbs +2 -2
  67. data/sig/authproto/state/session.rbs +13 -9
  68. data/sig/authproto/state/session_manager.rbs +9 -4
  69. data/sig/authproto/state/token_set.rbs +1 -2
  70. data/sig/authproto/storage/key_builder.rbs +1 -2
  71. data/sig/authproto/token/refresh.rbs +6 -7
  72. data/sig/authproto/validated_uri.rbs +36 -0
  73. data/sig/authproto.rbs +10 -5
  74. metadata +24 -27
  75. data/.rspec +0 -1
  76. data/.rubocop.yml +0 -31
  77. data/.tm_properties +0 -1
  78. data/.yardopts +0 -4
  79. data/Rakefile +0 -8
  80. data/examples/confidential_client/.gitignore +0 -5
  81. data/examples/minisky_console/.gitignore +0 -2
  82. data/lib/authproto/client_metadata.rb +0 -478
  83. data/lib/authproto/dpop/key_manager.rb +0 -223
  84. data/lib/authproto/serialization/dpop_key.rb +0 -38
  85. data/lib/authproto/server_metadata/authorization_server.rb +0 -267
  86. data/lib/authproto/server_metadata/origin_url.rb +0 -71
  87. data/lib/authproto/server_metadata/resource_server.rb +0 -98
  88. data/sig/authproto/client_metadata.rbs +0 -113
  89. data/sig/authproto/serialization/dpop_key.rbs +0 -14
  90. data/sig/authproto/server_metadata/origin_url.rbs +0 -21
  91. data/sig/authproto/server_metadata/resource_server.rbs +0 -27
@@ -0,0 +1,587 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'jose'
4
+ require 'json'
5
+ require 'uri'
6
+
7
+ require_relative '../configuration'
8
+ require_relative '../errors'
9
+ require_relative '../http_helpers'
10
+ require_relative '../metadata'
11
+ require_relative '../par/client_assertion'
12
+ require_relative '../validated_uri'
13
+
14
+ module AuthProto
15
+
16
+ #
17
+ # Supported OAuth application types used by {Metadata::ClientMetadata}.
18
+ #
19
+
20
+ module ApplicationType
21
+
22
+ # Application type for browser-based OAuth client applications
23
+ WEB = "web"
24
+
25
+ # Application type for native desktop or mobile OAuth client applications
26
+ NATIVE = "native"
27
+
28
+ # Supported application type values.
29
+ # @return [Array<String>]
30
+ ALL = [WEB, NATIVE].freeze
31
+ end
32
+
33
+ module Metadata
34
+
35
+ #
36
+ # Handles validation and management of AT Protocol OAuth client metadata according to
37
+ # the specification. This includes required fields like client_id and redirect URIs,
38
+ # optional metadata like client name and logo, and authentication configuration for
39
+ # confidential clients. Validates that all fields conform to the protocol's requirements,
40
+ # including:
41
+ #
42
+ # - Application type (web/native) validation and redirect URI rules
43
+ # - Required scopes and grant types
44
+ # - JWKS configuration for confidential clients
45
+ # - DPoP binding requirements
46
+ # - URI scheme and format validation
47
+ #
48
+
49
+ class ClientMetadata
50
+ extend HTTPHelpers
51
+
52
+ # Client authentication method for confidential clients
53
+ AUTH_METHOD_PRIVATE_KEY_JWT = "private_key_jwt"
54
+
55
+ # Client authentication method value for public clients
56
+ AUTH_METHOD_NONE = "none"
57
+
58
+ # RFC 6749 scope-token characters, separated by single ASCII spaces.
59
+ SCOPE_PATTERN = /\A[\x21\x23-\x5B\x5D-\x7E]+(?: [\x21\x23-\x5B\x5D-\x7E]+)*\z/
60
+
61
+
62
+ # -- required fields --
63
+
64
+ # Client metadata URL or localhost client identifier. **Required**.
65
+ # @return [String]
66
+ attr_reader :client_id
67
+
68
+ # List of allowed grant types. ATProto requires `authorization_code` and supports `refresh_token`. **Required**.
69
+ # @return [Array<String>]
70
+ attr_reader :grant_types
71
+
72
+ # List of supported response types. In ATProto, it must include `code`. **Required**.
73
+ # @return [Array<String>]
74
+ attr_reader :response_types
75
+
76
+ # List of registered OAuth callback URIs. **Required**.
77
+ # @return [Array<String>]
78
+ attr_reader :redirect_uris
79
+
80
+ # Space-separated list of supported OAuth scopes. Must include at least `atproto`. **Required**.
81
+ # @return [String]
82
+ attr_reader :scope
83
+
84
+ # Client authentication method: `none` for public clients, or `private_key_jwt` for confidential ones.
85
+ # Not technically required, but the reference PDS sets it to `client_secret_basic` if not set,
86
+ # which we don't support.
87
+ # @return [String]
88
+ attr_reader :token_endpoint_auth_method
89
+
90
+
91
+ # -- optional fields --
92
+
93
+ # Application type: `web` (default) or `native`.
94
+ # @return [String]
95
+ attr_reader :application_type
96
+
97
+ # Public name of the client application that is presented to the user, if supplied.
98
+ # @return [String, nil]
99
+ attr_reader :client_name
100
+
101
+ # URL of the client application's home page, if supplied.
102
+ # @return [String, nil]
103
+ attr_reader :client_uri
104
+
105
+ # URL to the client application's logo image, if supplied.
106
+ # @return [String, nil]
107
+ attr_reader :logo_uri
108
+
109
+ # URL to human-readable terms of service of the client, if supplied.
110
+ # @return [String, nil]
111
+ attr_reader :tos_uri
112
+
113
+ # URL to human-readable privacy policy of the client, if supplied.
114
+ # @return [String, nil]
115
+ attr_reader :policy_uri
116
+
117
+ # Inline set of JWK keys for confidential clients, if supplied.
118
+ # @return [Hash{String => Object}, nil]
119
+ attr_reader :jwks
120
+
121
+ # HTTPS URL to a set of JWK keys for confidential clients, if supplied.
122
+ # @return [String, nil]
123
+ attr_reader :jwks_uri
124
+
125
+
126
+ # Validates string-keyed client metadata and exposes its fields.
127
+ #
128
+ # Requires `client_id`, `grant_types`, `response_types`, `redirect_uris`, `scope`,
129
+ # `token_endpoint_auth_method`, and `dpop_bound_access_tokens: true`.
130
+ # `application_type` defaults to `web`.
131
+ # Confidential clients using `private_key_jwt` require `ES256` and a JWK set or URI.
132
+ #
133
+ # @param metadata [Hash{String => Object}] parsed OAuth client metadata
134
+ # @raise [InvalidClientMetadata] if a required field or supported value is invalid
135
+ # @raise [URI::InvalidURIError] if a metadata URI cannot be parsed
136
+ #
137
+ def initialize(metadata)
138
+ validate_and_set_metadata(metadata)
139
+ end
140
+
141
+ # Fetches and validates a client metadata document using the configured transport.
142
+ #
143
+ # Requires HTTP 200 and application/json, without following redirects.
144
+ # The document's `client_id` must equal the requested URL.
145
+ # Localhost HTTP client IDs generate virtual metadata without a network request.
146
+ #
147
+ # @param url [String] HTTPS metadata URL, or localhost URL for development
148
+ # @return [ClientMetadata] validated metadata
149
+ # @raise [InvalidClientMetadata] if metadata is missing, invalid/mismatched, not JSON,
150
+ # or transport isn't configured
151
+ # @raise [HTTPClient::HTTPError, HTTPClient::SSRFError] if the transport rejects/fails the request
152
+ # @raise [URI::InvalidURIError] if a URL cannot be parsed
153
+ #
154
+ def self.from_url(url)
155
+ uri = ValidatedURI.new(url)
156
+
157
+ unless uri.scheme == 'https' || (uri.scheme == 'http' && uri.host == 'localhost')
158
+ raise InvalidClientMetadata, "client_id must use HTTPS except for localhost"
159
+ end
160
+
161
+ return from_localhost_url(url) if uri.scheme == 'http'
162
+
163
+ raise InvalidClientMetadata, "HTTP client not configured" unless AuthProto.configuration.http_client
164
+
165
+ response = AuthProto.configuration.http_client.get(url)
166
+
167
+ unless response[:status] == 200
168
+ raise InvalidClientMetadata,
169
+ "expected HTTP 200 response for client metadata request, got #{response[:status]}"
170
+ end
171
+
172
+ content_type = response_header(response, 'Content-Type', strip_parameters: true)
173
+
174
+ unless content_type.to_s.downcase == 'application/json'
175
+ raise InvalidClientMetadata, "client metadata Content-Type must be application/json"
176
+ end
177
+
178
+ raise InvalidClientMetadata, "client metadata request returned response with no body" if response[:body].nil?
179
+
180
+ metadata = JSON.parse(response[:body])
181
+ raise InvalidClientMetadata, "metadata must be a hash" unless metadata.is_a?(Hash)
182
+
183
+ if metadata['client_id'] != url
184
+ raise InvalidClientMetadata, "client_id mismatch: #{metadata['client_id']} != #{url}"
185
+ end
186
+
187
+ self.new(metadata)
188
+ rescue JSON::ParserError => e
189
+ raise InvalidClientMetadata, "Invalid JSON in client metadata: #{e.message}"
190
+ end
191
+
192
+ def self.from_localhost_url(url)
193
+ uri = ValidatedURI.new(url)
194
+ params = URI.decode_www_form(uri.query.to_s)
195
+
196
+ scopes = params.select { |k, v| k == 'scope' }.map(&:last)
197
+
198
+ if scopes.length > 1
199
+ raise InvalidClientMetadata, "localhost client_id must not contain multiple scope parameters"
200
+ end
201
+
202
+ redirects = params.select { |k, v| k == 'redirect_uri' }.map(&:last)
203
+ redirects = ['http://127.0.0.1/', 'http://[::1]/'] if redirects.empty?
204
+
205
+ self.new(
206
+ 'client_id' => url,
207
+ 'client_name' => 'Development client',
208
+ 'application_type' => ApplicationType::NATIVE,
209
+ 'token_endpoint_auth_method' => AUTH_METHOD_NONE,
210
+ 'dpop_bound_access_tokens' => true,
211
+ 'grant_types' => ['authorization_code', 'refresh_token'],
212
+ 'response_types' => ['code'],
213
+ 'scope' => scopes.first || 'atproto',
214
+ 'redirect_uris' => redirects
215
+ )
216
+ rescue ArgumentError => e
217
+ raise InvalidClientMetadata, "Invalid localhost client_id query: #{e.message}"
218
+ end
219
+
220
+ private_class_method :from_localhost_url
221
+
222
+ # Determines if the client is confidential (has authentication keys).
223
+ # @return [Boolean] true if client is confidential.
224
+ #
225
+ def confidential?
226
+ token_endpoint_auth_method == AUTH_METHOD_PRIVATE_KEY_JWT
227
+ end
228
+
229
+
230
+ private
231
+
232
+ def validate_and_set_metadata(metadata)
233
+ raise InvalidClientMetadata, "metadata must be a hash" unless metadata.is_a?(Hash)
234
+
235
+ # Optional (defaults to "web"), but must be set before validating redirect URIs
236
+ @application_type = validate_application_type(metadata['application_type'])
237
+
238
+ # Required fields
239
+ @client_id = validate_client_id(metadata['client_id'])
240
+ @grant_types = validate_grant_types(metadata['grant_types'])
241
+ @response_types = validate_response_types(metadata['response_types'])
242
+ @redirect_uris = validate_redirect_uris(metadata['redirect_uris'])
243
+ @scope = validate_scope(metadata['scope'])
244
+
245
+ # Check dpop_bound_access_tokens
246
+ validate_dpop(metadata)
247
+
248
+ # Optional fields
249
+ @client_name = validate_client_name(metadata['client_name'])
250
+ @client_uri = validate_client_uri(metadata['client_uri'])
251
+ @logo_uri = validate_https_uri(metadata['logo_uri'])
252
+ @tos_uri = validate_https_uri(metadata['tos_uri'])
253
+ @policy_uri = validate_https_uri(metadata['policy_uri'])
254
+
255
+ # Check token_endpoint_auth_method and jwks
256
+ validate_auth_methods(metadata)
257
+ end
258
+
259
+
260
+ # -- Required field validations --
261
+
262
+ def validate_client_id(client_id)
263
+ raise InvalidClientMetadata, "client_id is required" unless client_id
264
+ raise InvalidClientMetadata, "client_id must be a string" unless client_id.is_a?(String)
265
+
266
+ unless valid_https_client_id?(client_id) || valid_localhost_client_id?(client_id)
267
+ raise InvalidClientMetadata, "client_id must be HTTPS or localhost HTTP URL"
268
+ end
269
+
270
+ client_id
271
+ end
272
+
273
+ def valid_https_client_id?(client_id)
274
+ uri = ValidatedURI.new(client_id)
275
+ uri.scheme == 'https' && !uri.port && !uri.userinfo && !uri.fragment
276
+ rescue URI::InvalidURIError
277
+ false
278
+ end
279
+
280
+ def valid_localhost_client_id?(client_id)
281
+ uri = ValidatedURI.new(client_id)
282
+ uri.scheme == 'http' && uri.host == 'localhost' && !uri.port && !uri.userinfo &&
283
+ !uri.fragment && uri.path.empty?
284
+ rescue URI::InvalidURIError
285
+ false
286
+ end
287
+
288
+ def validate_grant_types(grant_types)
289
+ raise InvalidClientMetadata, "grant_types is required" unless grant_types
290
+ raise InvalidClientMetadata, "grant_types must be an array" unless grant_types.is_a?(Array)
291
+
292
+ unless grant_types.include?('authorization_code')
293
+ raise InvalidClientMetadata, "grant_types must include authorization_code"
294
+ end
295
+
296
+ valid_types = %w[authorization_code refresh_token]
297
+
298
+ grant_types.each do |grant|
299
+ raise InvalidClientMetadata, "unsupported grant type" unless valid_types.include?(grant)
300
+ end
301
+
302
+ grant_types
303
+ end
304
+
305
+ def validate_response_types(response_types)
306
+ raise InvalidClientMetadata, "response_types is required" unless response_types
307
+ raise InvalidClientMetadata, "response_types must be an array" unless response_types.is_a?(Array)
308
+ raise InvalidClientMetadata, "response_types must include 'code'" unless response_types.include?('code')
309
+
310
+ unless response_types.all? { |type| type.is_a?(String) }
311
+ raise InvalidClientMetadata, "response_types must contain only strings"
312
+ end
313
+
314
+ response_types
315
+ end
316
+
317
+ def validate_redirect_uris(uris)
318
+ raise InvalidClientMetadata, "redirect_uris is required" unless uris
319
+ raise InvalidClientMetadata, "redirect_uris must be an array" unless uris.is_a?(Array)
320
+ raise InvalidClientMetadata, "redirect_uris must not be empty" if uris.empty?
321
+
322
+ uris.each { |uri| validate_redirect_uri(uri) }
323
+ uris
324
+ end
325
+
326
+ def validate_redirect_uri(url)
327
+ raise InvalidClientMetadata, "redirect_uris entries must be strings" unless url.is_a?(String)
328
+
329
+ case application_type
330
+ when ApplicationType::WEB
331
+ validate_https_redirect_uri(url)
332
+ when ApplicationType::NATIVE
333
+ validate_native_redirect_uri(url)
334
+ end
335
+ rescue URI::InvalidURIError => e
336
+ raise InvalidClientMetadata, "Invalid redirect URI: #{e.message}"
337
+ end
338
+
339
+ def validate_https_redirect_uri(url)
340
+ uri = ValidatedURI.new(url)
341
+
342
+ unless uri.scheme == 'https'
343
+ raise InvalidClientMetadata, "redirect URI must use HTTPS with a hostname"
344
+ end
345
+
346
+ raise InvalidClientMetadata, "redirect URI must not contain credentials" if uri.userinfo
347
+ raise InvalidClientMetadata, "redirect URI must not contain a fragment" if uri.fragment
348
+
349
+ if uri.specified_port && uri.effective_port == 443
350
+ raise InvalidClientMetadata, "HTTPS redirect URI must not specify the default port"
351
+ end
352
+ end
353
+
354
+ def validate_redirect_uri_origin(url)
355
+ client_uri = ValidatedURI.new(@client_id)
356
+ uri = ValidatedURI.new(url)
357
+
358
+ unless uri.origin.downcase == client_uri.origin.downcase
359
+ raise InvalidClientMetadata, "redirect URI must match client_id origin"
360
+ end
361
+ end
362
+
363
+ def validate_native_redirect_uri(url)
364
+ uri = URI(url)
365
+
366
+ case uri.scheme
367
+ when 'https'
368
+ validate_https_redirect_uri(url)
369
+ validate_redirect_uri_origin(url)
370
+ when 'http'
371
+ uri = ValidatedURI.new(url)
372
+ raise InvalidClientMetadata, "redirect URI must not contain credentials" if uri.userinfo
373
+ raise InvalidClientMetadata, "redirect URI must not contain a fragment" if uri.fragment
374
+
375
+ unless ["127.0.0.1", "[::1]"].include?(uri.host)
376
+ raise InvalidClientMetadata, "HTTP redirect URIs for native clients must use loopback IP"
377
+ end
378
+
379
+ unless uri.effective_port.between?(1, 65_535)
380
+ raise InvalidClientMetadata, "HTTP redirect URI must have a valid port"
381
+ end
382
+ else
383
+ validate_custom_scheme(uri)
384
+ end
385
+ end
386
+
387
+ def validate_custom_scheme(uri)
388
+ reversed_host = URI(@client_id).host.downcase.split('.').reverse.join('.')
389
+
390
+ unless uri.scheme == reversed_host
391
+ raise InvalidClientMetadata, "custom scheme must match reversed client_id domain"
392
+ end
393
+
394
+ unless uri.scheme.include?('.')
395
+ raise InvalidClientMetadata, "custom scheme must include a '.'"
396
+ end
397
+
398
+ unless !uri.host && uri.path && uri.path.start_with?('/')
399
+ raise InvalidClientMetadata, "custom scheme redirect URI must use a single slash after the scheme"
400
+ end
401
+
402
+ raise InvalidClientMetadata, "redirect URI must not contain a fragment" if uri.fragment
403
+ end
404
+
405
+ def validate_scope(scope)
406
+ raise InvalidClientMetadata, "scope is required" unless scope
407
+ raise InvalidClientMetadata, "scope must be a string" unless scope.is_a?(String)
408
+
409
+ unless SCOPE_PATTERN.match?(scope)
410
+ raise InvalidClientMetadata, "scope must contain valid tokens separated by single spaces"
411
+ end
412
+
413
+ scope_values = scope.split(' ')
414
+ raise InvalidClientMetadata, "atproto scope is required" unless scope_values.include?('atproto')
415
+
416
+ scope
417
+ end
418
+
419
+ def validate_dpop(metadata)
420
+ unless metadata["dpop_bound_access_tokens"] == true
421
+ raise InvalidClientMetadata, "dpop_bound_access_tokens must be true"
422
+ end
423
+ end
424
+
425
+
426
+ # -- Optional field validations --
427
+
428
+ def validate_application_type(type)
429
+ if ApplicationType::ALL.include?(type)
430
+ type
431
+ elsif type.nil?
432
+ ApplicationType::WEB
433
+ else
434
+ raise InvalidClientMetadata, "application_type must be 'web' or 'native'"
435
+ end
436
+ end
437
+
438
+ def validate_client_name(name)
439
+ return if name.nil?
440
+ raise InvalidClientMetadata, "client_name must be a string, if provided" unless name.is_a?(String)
441
+
442
+ name
443
+ end
444
+
445
+ def validate_client_uri(uri)
446
+ return if uri.nil?
447
+ raise InvalidClientMetadata, "client_uri must be a string" unless uri.is_a?(String)
448
+
449
+ parsed = ValidatedURI.new(uri)
450
+
451
+ unless parsed.origin == URI(@client_id).origin
452
+ raise InvalidClientMetadata, "client_uri must have the same hostname as client_id"
453
+ end
454
+
455
+ uri
456
+ rescue URI::InvalidURIError
457
+ raise InvalidClientMetadata, "client_uri must use HTTP or HTTPS and must have the same hostname as client_id"
458
+ end
459
+
460
+ def validate_https_uri(uri)
461
+ return if uri.nil?
462
+
463
+ raise InvalidClientMetadata, "URI must be a string" unless uri.is_a?(String)
464
+
465
+ parsed = ValidatedURI.new(uri)
466
+ raise InvalidClientMetadata, "URI must use HTTPS" unless parsed.scheme == 'https'
467
+
468
+ uri
469
+ rescue URI::InvalidURIError
470
+ raise InvalidClientMetadata, "URI must use HTTPS with a hostname"
471
+ end
472
+
473
+ def validate_jwks(jwks)
474
+ raise InvalidClientMetadata, "jwks must be a hash" unless jwks.is_a?(Hash)
475
+ raise InvalidClientMetadata, "jwks must have a 'keys' array" unless jwks['keys'].is_a?(Array)
476
+ raise InvalidClientMetadata, "jwks must contain at least one public key" if jwks['keys'].empty?
477
+
478
+ key_ids = Set.new
479
+
480
+ jwks['keys'].each_with_index do |key, index|
481
+ path = "jwks.keys.#{index}"
482
+
483
+ raise InvalidClientMetadata, "#{path} must be a hash" unless key.is_a?(Hash)
484
+
485
+ unless key['kid'].is_a?(String) && !key['kid'].empty?
486
+ raise InvalidClientMetadata, "#{path} must have a nonempty string kid"
487
+ end
488
+
489
+ if key_ids.include?(key['kid'])
490
+ raise InvalidClientMetadata, "#{path} has a duplicate kid: #{key['kid']}"
491
+ end
492
+
493
+ key_ids << key['kid']
494
+
495
+ if %w[d p q dp dq qi oth k].any? { |field| key.key?(field) }
496
+ raise InvalidClientMetadata, "#{path} must contain only public key material"
497
+ end
498
+
499
+ if key.key?('use') && !%w[sig enc].include?(key['use'])
500
+ raise InvalidClientMetadata, "#{path}.use must be sig or enc"
501
+ end
502
+
503
+ if key.key?('key_ops')
504
+ raise InvalidClientMetadata, "#{path}.key_ops must be an array" unless key['key_ops'].is_a?(Array)
505
+
506
+ operations = key['key_ops']
507
+ unless !operations.empty? && operations.uniq == operations &&
508
+ operations.all? { |operation| %w[verify encrypt wrapKey].include?(operation) }
509
+ raise InvalidClientMetadata,
510
+ "#{path}.key_ops must contain distinct public operations: verify, encrypt or wrapKey"
511
+ end
512
+
513
+ if (key['use'] == 'sig' && operations.any? { |operation| operation != 'verify' }) ||
514
+ (key['use'] == 'enc' && operations.include?('verify'))
515
+ raise InvalidClientMetadata, "#{path}.key_ops must be consistent with use"
516
+ end
517
+ end
518
+
519
+ fields = case key['kty']
520
+ when 'EC' then %w[crv x y]
521
+ when 'RSA' then %w[n e]
522
+ when 'OKP' then %w[crv x]
523
+ else
524
+ raise InvalidClientMetadata, "#{path} must be an asymmetric public JWK"
525
+ end
526
+
527
+ unless fields.all? { |field| key[field].is_a?(String) && !key[field].empty? }
528
+ raise InvalidClientMetadata, "#{path} is missing public key material"
529
+ end
530
+
531
+ begin
532
+ JOSE::JWK.from_map(key).to_public
533
+ rescue StandardError
534
+ raise InvalidClientMetadata, "#{path} contains invalid public key material"
535
+ end
536
+ end
537
+ end
538
+
539
+
540
+ # -- Auth fields validations --
541
+
542
+ def validate_auth_methods(metadata)
543
+ @token_endpoint_auth_method = metadata['token_endpoint_auth_method']
544
+ @token_endpoint_auth_signing_alg = metadata['token_endpoint_auth_signing_alg']
545
+
546
+ raise InvalidClientMetadata, "token_endpoint_auth_method is required" if @token_endpoint_auth_method.nil?
547
+
548
+ @jwks = metadata['jwks']
549
+ @jwks_uri = metadata['jwks_uri']
550
+
551
+ if !@jwks.nil? && !@jwks_uri.nil?
552
+ raise InvalidClientMetadata, "cannot use both jwks and jwks_uri"
553
+ end
554
+
555
+ validate_jwks(@jwks) unless @jwks.nil?
556
+ validate_https_uri(@jwks_uri) unless @jwks_uri.nil?
557
+
558
+ case @token_endpoint_auth_method
559
+ when AUTH_METHOD_NONE
560
+ validate_auth_public(metadata)
561
+ when AUTH_METHOD_PRIVATE_KEY_JWT
562
+ validate_auth_confidential(metadata)
563
+ else
564
+ raise InvalidClientMetadata, "unsupported token_endpoint_auth_method"
565
+ end
566
+ end
567
+
568
+ def validate_auth_public(metadata)
569
+ unless @token_endpoint_auth_signing_alg.nil?
570
+ raise InvalidClientMetadata, "token_endpoint_auth_signing_alg must be unset for public clients"
571
+ end
572
+ end
573
+
574
+ def validate_auth_confidential(metadata)
575
+ algorithm = PAR::ClientAssertion::ALGORITHM
576
+
577
+ unless @token_endpoint_auth_signing_alg == algorithm
578
+ raise InvalidClientMetadata, "token_endpoint_auth_signing_alg must be #{algorithm}"
579
+ end
580
+
581
+ if @jwks.nil? && @jwks_uri.nil?
582
+ raise InvalidClientMetadata, "confidential clients must provide jwks or jwks_uri"
583
+ end
584
+ end
585
+ end
586
+ end
587
+ end