authproto 0.3.0.beta2 → 0.3.0.beta4

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 (82) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +36 -0
  3. data/README.md +108 -5
  4. data/examples/confidential_client/Gemfile.lock +1 -1
  5. data/examples/confidential_client/README.md +11 -1
  6. data/examples/confidential_client/app.rb +35 -17
  7. data/examples/confidential_client/scripts/generate_keys.rb +1 -1
  8. data/examples/minisky_console/Gemfile.lock +2 -2
  9. data/examples/minisky_console/README.md +20 -1
  10. data/examples/minisky_console/localhost.rb +5 -3
  11. data/examples/minisky_console/production.rb +9 -3
  12. data/lib/authproto/client.rb +173 -123
  13. data/lib/authproto/configuration.rb +37 -16
  14. data/lib/authproto/dpop/client.rb +105 -40
  15. data/lib/authproto/dpop/{key_manager.rb → key_set.rb} +54 -120
  16. data/lib/authproto/dpop/nonce_manager.rb +38 -29
  17. data/lib/authproto/dpop/proof_generator.rb +21 -35
  18. data/lib/authproto/dpop.rb +19 -0
  19. data/lib/authproto/encryption.rb +29 -12
  20. data/lib/authproto/http_client.rb +8 -7
  21. data/lib/authproto/http_helpers.rb +85 -0
  22. data/lib/authproto/metadata/authorization_server.rb +23 -6
  23. data/lib/authproto/metadata/client_metadata.rb +46 -6
  24. data/lib/authproto/metadata/resource_server.rb +7 -5
  25. data/lib/authproto/minisky.rb +36 -34
  26. data/lib/authproto/par/client.rb +22 -73
  27. data/lib/authproto/par/client_assertion.rb +47 -16
  28. data/lib/authproto/par/request.rb +4 -8
  29. data/lib/authproto/par.rb +2 -1
  30. data/lib/authproto/serialization/session.rb +33 -13
  31. data/lib/authproto/serialization/token_set.rb +6 -4
  32. data/lib/authproto/state/session.rb +102 -6
  33. data/lib/authproto/state/session_manager.rb +120 -22
  34. data/lib/authproto/state/token_set.rb +22 -19
  35. data/lib/authproto/state.rb +2 -2
  36. data/lib/authproto/storage/key_builder.rb +3 -11
  37. data/lib/authproto/storage/memory.rb +8 -2
  38. data/lib/authproto/token/identity.rb +54 -0
  39. data/lib/authproto/token/refresh.rb +66 -109
  40. data/lib/authproto/token/response.rb +73 -0
  41. data/lib/authproto/token/revocation.rb +92 -0
  42. data/lib/authproto/validated_uri.rb +23 -0
  43. data/lib/authproto/version.rb +1 -1
  44. data/lib/authproto.rb +0 -1
  45. data/sig/authproto/client.rbs +10 -10
  46. data/sig/authproto/dependencies.rbs +2 -0
  47. data/sig/authproto/dpop/client.rbs +11 -4
  48. data/sig/authproto/dpop/{key_manager.rbs → key_set.rbs} +9 -11
  49. data/sig/authproto/dpop/nonce_manager.rbs +4 -4
  50. data/sig/authproto/dpop/proof_generator.rbs +5 -10
  51. data/sig/authproto/dpop.rbs +6 -0
  52. data/sig/authproto/encryption.rbs +4 -2
  53. data/sig/authproto/http_client.rbs +0 -1
  54. data/sig/authproto/http_helpers.rbs +7 -0
  55. data/sig/authproto/localhost_server.rbs +1 -1
  56. data/sig/authproto/metadata/authorization_server.rbs +1 -0
  57. data/sig/authproto/metadata/client_metadata.rbs +3 -1
  58. data/sig/authproto/metadata/resource_server.rbs +1 -0
  59. data/sig/authproto/minisky_oauth.rbs +5 -2
  60. data/sig/authproto/par/client.rbs +4 -8
  61. data/sig/authproto/par/client_assertion.rbs +4 -0
  62. data/sig/authproto/par/request.rbs +0 -9
  63. data/sig/authproto/state/session.rbs +13 -3
  64. data/sig/authproto/state/session_manager.rbs +10 -3
  65. data/sig/authproto/state/token_set.rbs +1 -2
  66. data/sig/authproto/storage/key_builder.rbs +1 -2
  67. data/sig/authproto/token/refresh.rbs +5 -5
  68. data/sig/authproto/token/response.rbs +12 -0
  69. data/sig/authproto/token/revocation.rbs +14 -0
  70. data/sig/authproto.rbs +6 -3
  71. metadata +30 -23
  72. data/.rspec +0 -1
  73. data/.rubocop.yml +0 -31
  74. data/.tm_properties +0 -1
  75. data/.yardopts +0 -5
  76. data/AGENTS.md +0 -80
  77. data/Rakefile +0 -8
  78. data/examples/confidential_client/.gitignore +0 -6
  79. data/examples/minisky_console/.gitignore +0 -2
  80. data/lib/authproto/serialization/dpop_key.rb +0 -38
  81. data/misc/yard_attributes.rb +0 -34
  82. data/sig/authproto/serialization/dpop_key.rbs +0 -14
@@ -2,12 +2,10 @@
2
2
 
3
3
  require 'didkit/did'
4
4
  require 'jose'
5
- require 'json'
6
5
  require 'uri'
7
6
 
8
7
  require_relative 'configuration'
9
8
  require_relative 'dpop/client'
10
- require_relative 'dpop/key_manager'
11
9
  require_relative 'errors'
12
10
  require_relative 'metadata/authorization_server'
13
11
  require_relative 'metadata/client_metadata'
@@ -19,7 +17,10 @@ require_relative 'par/request'
19
17
  require_relative 'state/session_manager'
20
18
  require_relative 'state/token_set'
21
19
  require_relative 'storage/key_builder'
20
+ require_relative 'token/identity'
22
21
  require_relative 'token/refresh'
22
+ require_relative 'token/response'
23
+ require_relative 'token/revocation'
23
24
 
24
25
  module AuthProto
25
26
 
@@ -29,6 +30,7 @@ module AuthProto
29
30
  #
30
31
 
31
32
  class Client
33
+ include Token::Identity
32
34
 
33
35
  # Error raised when authorization callback fails
34
36
  class CallbackError < Error; end
@@ -73,44 +75,51 @@ module AuthProto
73
75
  # @return [State::SessionManager]
74
76
  attr_reader :session_manager
75
77
 
76
- # DPoP key, proof and nonce manager.
78
+ # Shared DPoP proof generator and per-server nonce manager.
77
79
  # @return [DPoP::Client]
78
80
  attr_reader :dpop_client
79
81
 
80
- # Creates an OAuth client with its own DPoP key and session manager.
82
+ # Creates an OAuth client with shared DPoP helpers and a session manager.
81
83
  #
82
84
  # Configure {AuthProto.configure} with an HTTP transport before fetching metadata
83
- # or starting authorization. Reuse `dpop_key` when restoring tokens bound to that key.
85
+ # or starting authorization. Session storage restores the DPoP key bound to each session.
84
86
  #
85
87
  # @param client_id [String] OAuth client ID URL
86
88
  # @param redirect_uri [String] callback URI listed in `redirect_uris`
87
89
  # @param metadata [Hash{String => Object}, nil] preloaded metadata, or `nil` to fetch `client_id`
88
90
  # @param signing_key [Hash, JOSE::JWK, nil] private ES256 client-authentication key, separate from public metadata
89
- # @param dpop_key [Hash{String => Object}, nil] existing private DPoP JWK, or `nil` to generate one
90
91
  #
91
- # @raise [InvalidClientMetadata] if client metadata is invalid or unavailable
92
+ # @raise [InvalidClientMetadata] if metadata is invalid, unavailable, has a different client ID,
93
+ # or the supplied signing key is missing, unexpected or does not match inline public metadata
94
+ # @raise [PAR::ClientAssertion::Error] if the private assertion key is invalid or unusable
92
95
  # @raise [Error] if the redirect URI is not registered
93
- # @raise [DPoP::KeyManager::KeyError] if the DPoP key cannot be imported or generated
94
96
  # @raise [HTTPClient::HTTPError, HTTPClient::SSRFError] if fetching client metadata fails
95
97
  #
96
- def initialize(client_id:, redirect_uri:, metadata: nil, dpop_key: nil, signing_key: nil)
98
+ def initialize(client_id:, redirect_uri:, metadata: nil, signing_key: nil)
97
99
  @client_id = client_id
98
100
  @redirect_uri = redirect_uri
99
101
 
100
- # Client metadata is fetched from .well-known if not provided directly
102
+ if metadata && metadata['client_id'] != @client_id
103
+ raise InvalidClientMetadata, "client_id mismatch: #{metadata['client_id']} != #{@client_id}"
104
+ end
105
+
106
+ # Client metadata is fetched from the client ID URL if not provided directly
101
107
  @client_metadata = load_client_metadata(metadata)
102
108
 
103
109
  validate_redirect_uri
104
- @signing_key = initialize_signing_key(signing_key)
110
+ initialize_client_assertion(signing_key)
111
+
112
+ signing_keys = @client_assertion ? { @signing_key_kid => @signing_key_thumbprint } : {}
113
+ @session_manager = State::SessionManager.new(client_id: @client_id, supported_signing_keys: signing_keys)
105
114
 
106
- @session_manager = State::SessionManager.new
107
- @dpop_client = initialize_dpop(dpop_key)
115
+ @dpop_client = DPoP::Client.new
108
116
  end
109
117
 
110
118
  # Starts authorization, stores a pending session, and submits a PAR request.
111
119
  #
112
120
  # Supply exactly one of `handle` or `pds`. Open the returned `:url` in a browser
113
- # and pass the eventual callback parameters to {#handle_callback}.
121
+ # and pass the eventual callback parameters to {#handle_callback}. Retain `:session_id`
122
+ # in the initiating browser session or native login context for callback verification.
114
123
  #
115
124
  # @param handle [String, nil] account handle (optionally prefixed with `@`) or DID
116
125
  # @param pds [String, nil] PDS URL when no handle is supplied
@@ -124,6 +133,7 @@ module AuthProto
124
133
  # @raise [PAR::ClientAssertion::Error] if confidential-client signing fails
125
134
  # @raise [DPoP::Client::Error] if generating the PAR proof fails
126
135
  # @raise [HTTPClient::SSRFError] if server discovery rejects a destination
136
+ # @raise [DPoP::KeySet::KeyError] if generating the session key fails
127
137
  # @raise [Storage::StorageError] if session storage or locking fails
128
138
  # @raise [Encryption::EncryptionError] if session serialization cannot encrypt secrets
129
139
  #
@@ -138,12 +148,16 @@ module AuthProto
138
148
  raise Error, "No HTTPS PDS location found for #{did}" unless pds && URI(pds).is_a?(URI::HTTPS)
139
149
  end
140
150
 
141
- authorization_server = resolve_auth_server(pds)
151
+ authorization_server = resolve_auth_server_info(pds)
142
152
 
143
- session = session_manager.create_session(client_id: @client_id, scope: scope)
144
- session.authorization_server = authorization_server
145
- session.did = did&.to_s
146
- session_manager.update_session(session)
153
+ session = session_manager.create_session(
154
+ client_id: @client_id,
155
+ scope: scope,
156
+ auth_server: authorization_server,
157
+ did: did&.to_s,
158
+ pds: pds,
159
+ signing_key_id: @signing_key_kid
160
+ )
147
161
 
148
162
  auth_url = submit_authorization_par(authorization_server, session, login_hint: handle)
149
163
 
@@ -157,16 +171,22 @@ module AuthProto
157
171
  #
158
172
  # The result contains `:access_token` (String), `:token_type` (String, `DPoP`),
159
173
  # `:expires_in` (Integer seconds remaining), `:refresh_token` (String or nil),
160
- # and `:scope` (String).
174
+ # and `:scope` / `:granted_scope` (String, the granted permissions).
161
175
  # It also contains `:session_id` (String) and `:did` (String).
162
176
  #
177
+ # Supply the session ID retained when starting authorization as `expected_session_id`.
178
+ # For web apps, read it from the initiating browser's session, never from callback parameters
179
+ # or the state-token lookup. It is checked before exchanging the authorization code.
180
+ # Remove the browser's pending-session association after this method succeeds.
181
+ #
163
182
  # @param code [String] authorization code from the callback
164
183
  # @param state [String] state token from the callback
165
184
  # @param iss [String] issuer URL from the callback
185
+ # @param expected_session_id [String] pending session ID retained by the caller when authorization started
166
186
  #
167
187
  # @return [Hash{Symbol => String, Integer, nil}] tokens and authenticated session details
168
- # @raise [CallbackError] if state is unknown or the issuer does not match the session
169
- # @raise [TokenError] if token exchange or response validation fails
188
+ # @raise [CallbackError] if the expected session ID is invalid, state is unknown, or session/issuer validation fails
189
+ # @raise [TokenError] if token exchange or response validation fails; identity failures attempt token revocation
170
190
  # @raise [DPoP::Client::Error, PAR::ClientAssertion::Error] if proof/assertion generation fails
171
191
  # @raise [HTTPClient::HTTPError, HTTPClient::SSRFError] if token transport fails
172
192
  # @raise [State::SessionError] if token subject conflicts with the session DID
@@ -174,27 +194,22 @@ module AuthProto
174
194
  # @raise [Storage::StorageError] if session storage or locking fails
175
195
  # @raise [Encryption::EncryptionError] if tokens cannot be encrypted for storage
176
196
  #
177
- def handle_callback(code:, state:, iss:)
178
- session = session_manager.get_session_by_state(state)
197
+ def handle_callback(code:, state:, iss:, expected_session_id:)
198
+ unless expected_session_id.is_a?(String) && !expected_session_id.empty?
199
+ raise CallbackError, "Expected session ID is required"
200
+ end
201
+
202
+ session = session_manager.get_session_by_state_token(state)
179
203
 
180
204
  raise CallbackError, "Invalid state parameter" unless session
205
+ raise CallbackError, "Session ID mismatch" unless session.session_id == expected_session_id
181
206
  raise CallbackError, "Issuer mismatch" unless session.auth_server && session.auth_server.issuer == iss
182
207
 
183
208
  AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key("session", session.session_id), ttl: 30) do
184
- response = exchange_code(code: code, session: session)
185
- validate_token_response(response, session)
186
-
187
- token_set = State::TokenSet.new(
188
- access_token: response['access_token'],
189
- token_type: response['token_type'],
190
- expires_in: response['expires_in'],
191
- refresh_token: response['refresh_token'],
192
- scope: response['scope'],
193
- sub: response['sub']
194
- )
209
+ token_set = exchange_code(code: code, session: session)
195
210
 
196
211
  session.tokens = token_set
197
- session_manager.update_session(session)
212
+ session_manager.complete_authorization(session)
198
213
 
199
214
  session.session_data
200
215
  end
@@ -204,7 +219,7 @@ module AuthProto
204
219
  #
205
220
  # The result contains `:access_token` (String), `:token_type` (String, `DPoP`),
206
221
  # `:expires_in` (Integer seconds remaining), `:refresh_token` (String or nil),
207
- # and `:scope` (String).
222
+ # and `:scope` / `:granted_scope` (String, the granted permissions).
208
223
  # It also contains `:session_id` (String) and `:did` (String).
209
224
  # This method does not refresh expired tokens.
210
225
  #
@@ -213,7 +228,7 @@ module AuthProto
213
228
  #
214
229
  def get_tokens(session_id)
215
230
  session = session_manager.get_session(session_id)
216
- return nil unless session&.authorized?
231
+ return nil unless session && session.tokens_valid?
217
232
 
218
233
  session.session_data
219
234
  end
@@ -222,31 +237,32 @@ module AuthProto
222
237
  #
223
238
  # The result contains `:access_token` (String), `:token_type` (String, `DPoP`),
224
239
  # `:expires_in` (Integer seconds remaining), `:refresh_token` (String or nil),
225
- # and `:scope` (String).
240
+ # and `:scope` / `:granted_scope` (String, the granted permissions).
226
241
  # The result also contains `:session_id` (String) and `:did` (String). An expired access token can
227
242
  # still be refreshed when the stored session has a refresh token.
228
243
  #
229
244
  # @param session_id [String] session to refresh
230
245
  # @return [Hash{Symbol => String, Integer, nil}] replacement tokens and session identifiers
231
246
  # @raise [TokenError] if the session is missing or has no refresh token
232
- # @raise [Token::RefreshError] if token refresh fails or exhausts retries
247
+ # @raise [Token::RefreshError] if the current PDS differs, token refresh fails or retries are exhausted
248
+ # @raise [DPoP::Client::Error] if a refresh response lacks a valid nonce
233
249
  # @raise [State::SessionError] if replacement tokens have a different subject
234
250
  # @raise [Storage::StorageError] if session storage or locking fails
235
251
  # @raise [Encryption::EncryptionError] if replacement tokens cannot be stored
236
252
  #
237
253
  def refresh_token(session_id)
238
- session = session_manager.get_session(session_id)
254
+ AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key('session', session_id), ttl: 30) do
255
+ session = session_manager.get_session(session_id)
239
256
 
240
- raise TokenError, "Invalid session" unless session
241
- raise TokenError, "Session not authorized" unless session.renewable?
257
+ raise TokenError, "Invalid session" unless session
258
+ raise TokenError, "Session not authorized" unless session.renewable?
242
259
 
243
- AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key("session", session.session_id), ttl: 30) do
244
260
  refresher = Token::Refresh.new(
245
261
  session: session,
246
262
  dpop_client: @dpop_client,
247
263
  auth_server: session.auth_server,
248
264
  client_metadata: @client_metadata,
249
- signing_key: @signing_key
265
+ client_assertion: @client_assertion
250
266
  )
251
267
 
252
268
  new_tokens = refresher.perform_refresh
@@ -265,13 +281,13 @@ module AuthProto
265
281
  #
266
282
  def authorized?(session_id)
267
283
  session = session_manager.get_session(session_id)
268
- session&.authorized? || false
284
+ session ? session.tokens_valid? : false
269
285
  end
270
286
 
271
287
  # Builds authorization headers and a fresh DPoP proof for one HTTP request.
272
288
  #
273
289
  # The caller sends the request. This method does not refresh tokens, send HTTP,
274
- # or retry nonce challenges. Feed response headers to {DPoP::Client#process_response}
290
+ # or retry nonce challenges. Feed each full HTTP response to {DPoP::Client#process_response}
275
291
  # and call {#refresh_token} explicitly when needed. Generate new headers for each retry.
276
292
  #
277
293
  # @param session_id [String] authorized session ID
@@ -286,9 +302,11 @@ module AuthProto
286
302
  session = session_manager.get_session(session_id)
287
303
 
288
304
  raise TokenError, "Invalid session" unless session
289
- raise TokenError, "Session not authorized" unless session.authorized?
305
+ raise TokenError, "Session not authorized" if session.pending?
306
+ raise TokenError, "Session has expired" unless session.tokens_valid?
290
307
 
291
308
  dpop_proof = dpop_client.generate_proof(
309
+ session: session,
292
310
  method: method,
293
311
  uri: url,
294
312
  access_token: session.tokens.access_token
@@ -300,17 +318,47 @@ module AuthProto
300
318
  }
301
319
  end
302
320
 
303
- # Removes a stored session and its state-token lookup.
321
+ # Removes a stored session and its state-token lookup, optionally revoking its tokens first.
322
+ # Refresh-token revocation must succeed when a refresh token is present; access-token revocation
323
+ # is then best effort. Without a refresh token, access-token revocation must succeed.
324
+ # Required revocation failures leave the local session intact so the caller can retry or delete locally.
325
+ # A missing session is a no-op; pending sessions have no tokens to revoke.
326
+ # Servers without a revocation endpoint are skipped and the session is deleted locally.
304
327
  #
305
328
  # @param session_id [String] session identifier
329
+ # @param revoke [Boolean] revoke the refresh token, if present, and access token before deletion
306
330
  # @return [void]
331
+ # @raise [Token::Revocation::Error] if a required revocation request is rejected
332
+ # @raise [DPoP::Client::Error, HTTPClient::HTTPError] if revocation proof or transport handling fails
307
333
  # @raise [Storage::StorageError] if deletion or locking fails
308
334
  #
309
- def delete_session(session_id)
310
- key = Storage::KeyBuilder.session_key(session_id)
335
+ def delete_session(session_id, revoke: false)
336
+ AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key('session', session_id), ttl: 30) do
337
+ session = session_manager.get_session(session_id)
338
+ return unless session
339
+
340
+ if revoke && session.tokens && session.can_be_revoked?
341
+ revocation = Token::Revocation.new(
342
+ session: session,
343
+ dpop_client: @dpop_client,
344
+ client_metadata: @client_metadata,
345
+ client_assertion: @client_assertion
346
+ )
347
+
348
+ if session.tokens.refresh_token
349
+ revocation.revoke_token(session.tokens.refresh_token, :token_type => :refresh_token)
350
+ refresh_revoked = true
351
+ end
352
+
353
+ begin
354
+ revocation.revoke_token(session.tokens.access_token, :token_type => :access_token)
355
+ rescue StandardError
356
+ raise unless refresh_revoked
357
+ end
358
+ end
311
359
 
312
- AuthProto.storage.delete(key)
313
- session_manager.delete_session(session_id)
360
+ session_manager.delete_session(session_id)
361
+ end
314
362
  end
315
363
 
316
364
  # Invokes the session manager's expiry cleanup hook.
@@ -335,12 +383,38 @@ module AuthProto
335
383
  end
336
384
 
337
385
  def validate_redirect_uri
338
- unless @client_metadata.redirect_uris.include?(@redirect_uri)
339
- raise Error, "redirect_uri not found in client metadata"
386
+ return if @client_metadata.redirect_uris.include?(@redirect_uri)
387
+
388
+ # localhost development exception
389
+ if URI(@client_id).scheme == 'http'
390
+ components = loopback_redirect_components(@redirect_uri)
391
+
392
+ if components && @client_metadata.redirect_uris.any? { |uri| loopback_redirect_components(uri) == components }
393
+ return
394
+ end
395
+ end
396
+
397
+ raise Error, "redirect_uri not found in client metadata"
398
+ end
399
+
400
+ def loopback_redirect_components(url)
401
+ uri = URI(url)
402
+
403
+ unless uri.is_a?(URI::HTTP) && uri.scheme == 'http' && ['127.0.0.1', '[::1]'].include?(uri.host) &&
404
+ !uri.userinfo && !uri.fragment && uri.port.between?(1, 65_535)
405
+ return nil
340
406
  end
407
+
408
+ # compare the localhost URLs while ignoring the port
409
+ # "redirect_uri (string, multiple query parameters allowed, optional):
410
+ # allows declaring a local redirect/callback URL, with path component matched but port numbers ignored"
411
+
412
+ URI.split(url).tap { |components| components[3] = nil }
413
+ rescue URI::InvalidURIError
414
+ nil
341
415
  end
342
416
 
343
- def initialize_signing_key(key)
417
+ def initialize_client_assertion(key)
344
418
  if @client_metadata.confidential?
345
419
  raise InvalidClientMetadata, "Confidential clients require a signing_key" if key.nil?
346
420
  else
@@ -352,7 +426,7 @@ module AuthProto
352
426
  private_key = assertion.signing_key
353
427
 
354
428
  if @client_metadata.jwks
355
- public_key = private_key.to_public.to_map.to_h
429
+ public_key = private_key.to_public_map.to_h
356
430
 
357
431
  key_in_jwks = @client_metadata.jwks['keys'].any? { |candidate|
358
432
  metadata_key_matches_public_key?(candidate, public_key)
@@ -361,24 +435,20 @@ module AuthProto
361
435
  raise InvalidClientMetadata, "signing_key must match an active public key advertised in jwks" if !key_in_jwks
362
436
  end
363
437
 
364
- private_key
438
+ @client_assertion = assertion
439
+ @signing_key_kid = private_key.fields.fetch('kid')
440
+ @signing_key_thumbprint = private_key.thumbprint('SHA256')
365
441
  end
366
442
 
367
443
  def metadata_key_matches_public_key?(candidate, public_key)
368
444
  return false if candidate['revoked']
369
- return false if candidate.key?('alg') && candidate['alg'] != 'ES256'
445
+ return false if candidate.key?('alg') && candidate['alg'] != PAR::ClientAssertion::ALGORITHM
370
446
  return false if candidate.key?('use') && candidate['use'] != 'sig'
371
447
  return false if candidate.key?('key_ops') && !candidate['key_ops'].include?('verify')
372
448
 
373
449
  %w[kid kty crv x y].all? { |field| candidate[field] == public_key[field] }
374
450
  end
375
451
 
376
- def initialize_dpop(key)
377
- key_manager = key ? DPoP::KeyManager.from_jwk(key) : DPoP::KeyManager.new
378
-
379
- DPoP::Client.new(key_manager: key_manager)
380
- end
381
-
382
452
  def validate_auth_params(handle, pds, scope)
383
453
  unless scope.is_a?(String) && scope.valid_encoding? && Metadata::ClientMetadata::SCOPE_PATTERN.match?(scope)
384
454
  raise Error, "scope must contain valid tokens separated by single spaces"
@@ -397,7 +467,7 @@ module AuthProto
397
467
  raise Error, "cannot provide both handle and pds" if handle && pds
398
468
  end
399
469
 
400
- def resolve_auth_server(pds)
470
+ def resolve_auth_server_info(pds)
401
471
  resource_server = Metadata::ResourceServer.from_url(pds)
402
472
  auth_server_url = resource_server.authorization_server
403
473
 
@@ -419,16 +489,11 @@ module AuthProto
419
489
  req.code_challenge = session.pkce_challenge
420
490
 
421
491
  if @client_metadata.confidential?
422
- req.client_assertion = PAR::ClientAssertion.new(client_id: @client_id, signing_key: @signing_key)
492
+ req.client_assertion = @client_assertion
423
493
  end
424
-
425
- req.dpop_proof = @dpop_client.generate_proof(
426
- method: 'POST',
427
- uri: authorization_server.pushed_authorization_request_endpoint
428
- )
429
494
  end
430
495
 
431
- par_response = par_client.submit(par_request)
496
+ par_response = par_client.submit(par_request, session: session)
432
497
 
433
498
  par_client.build_authorization_url(
434
499
  request_uri: par_response.request_uri,
@@ -437,30 +502,23 @@ module AuthProto
437
502
  end
438
503
 
439
504
  def exchange_code(code:, session:)
440
- # Initial token request without nonce
441
- response = make_token_request(code, session)
442
-
443
- # Handle DPoP nonce requirement
444
- if requires_dpop_nonce?(response)
445
- # Extract and store nonce from error response
446
- extract_dpop_nonce(response)
447
- dpop_client.process_response(response[:headers], session.auth_server.issuer)
448
-
449
- # Retry request with nonce
450
- response = make_token_request(code, session)
505
+ response = dpop_client.with_nonce_handling(session, session.auth_server.token_endpoint) do
506
+ make_token_request(code, session)
451
507
  end
452
508
 
453
509
  raise TokenError, "Token request failed: #{response[:status]}" unless response[:status] == 200
454
510
 
455
- begin
456
- JSON.parse(response[:body])
457
- rescue JSON::ParserError => e
458
- raise TokenError, "Invalid token response: #{e.message}"
459
- end
511
+ tokens = Token::Response.parse(response)
512
+ validate_token_identity(tokens, session)
513
+
514
+ tokens
515
+ rescue Token::Response::Error => e
516
+ raise TokenError, e.message
460
517
  end
461
518
 
462
519
  def make_token_request(code, session)
463
520
  dpop_proof = dpop_client.generate_proof(
521
+ session: session,
464
522
  method: 'POST',
465
523
  uri: session.auth_server.token_endpoint
466
524
  )
@@ -474,14 +532,9 @@ module AuthProto
474
532
  }
475
533
 
476
534
  if @client_metadata.confidential?
477
- assertion = PAR::ClientAssertion.new(
478
- client_id: @client_id,
479
- signing_key: @signing_key
480
- )
481
-
482
535
  body.merge!(
483
536
  client_assertion_type: PAR::CLIENT_ASSERTION_TYPE,
484
- client_assertion: assertion.generate_jwt(audience: session.auth_server.issuer)
537
+ client_assertion: @client_assertion.generate_jwt(audience: session.auth_server.issuer)
485
538
  )
486
539
  end
487
540
 
@@ -495,38 +548,35 @@ module AuthProto
495
548
  )
496
549
  end
497
550
 
498
- def requires_dpop_nonce?(response)
499
- return false unless response[:status] == 400
500
-
501
- error_data = JSON.parse(response[:body])
502
- error_data['error'] == DPoP::ERROR_USE_NONCE
503
- rescue JSON::ParserError
504
- false
505
- end
506
-
507
- def extract_dpop_nonce(response)
508
- headers = response[:headers]
509
- nonce = headers.find { |k, v| k.downcase == 'dpop-nonce' }&.last
510
-
511
- raise TokenError, "No DPoP nonce provided in error response" unless nonce
512
-
513
- nonce
514
- end
515
-
516
- def validate_token_response(response, session)
517
- ['access_token', 'token_type', 'expires_in', 'scope', 'sub'].each do |field|
518
- raise TokenError, "Missing #{field} in token response" unless response[field]
551
+ def validate_token_identity(tokens, session)
552
+ if session.did
553
+ raise Token::IdentityMismatchError, "Subject mismatch in token response" if session.did != tokens.sub
554
+ else
555
+ validate_subject_pds(tokens.sub, session)
519
556
  end
557
+ rescue Token::IdentityMismatchError => e
558
+ revoke_rejected_refresh_token(tokens.refresh_token, session) if tokens.refresh_token
559
+ raise TokenError, e.message
560
+ rescue Token::IdentityLookupError => e
561
+ raise TokenError, "#{e.message}; start authorization again"
562
+ rescue Token::IdentityError => e
563
+ raise TokenError, e.message
564
+ end
520
565
 
521
- raise TokenError, "Invalid token_type: #{response['token_type']}" unless response['token_type'] == 'DPoP'
522
- raise TokenError, "Missing atproto scope in token response" unless response['scope'].split.include?('atproto')
566
+ def revoke_rejected_refresh_token(token, session)
567
+ return unless session.can_be_revoked?
523
568
 
524
- # If we have a pre-resolved DID, verify that it matches
525
- raise TokenError, "Subject mismatch in token response" if session.did && session.did != response['sub']
569
+ revocation = Token::Revocation.new(
570
+ session: session,
571
+ dpop_client: @dpop_client,
572
+ client_metadata: @client_metadata,
573
+ client_assertion: @client_assertion
574
+ )
526
575
 
527
- if response[:headers] && response[:headers]["DPoP-Nonce"]
528
- dpop_client.process_response(response[:headers], session.auth_server.issuer)
529
- end
576
+ revocation.revoke_token(token, token_type: 'refresh_token')
577
+ rescue StandardError
578
+ # Cleanup failures must not replace the original identity error.
579
+ nil
530
580
  end
531
581
  end
532
582
  end
@@ -34,7 +34,7 @@ module AuthProto
34
34
  # @yieldparam config [Configuration] mutable global settings
35
35
  # @yieldreturn [Object] ignored
36
36
  # @return [Configuration] validated global settings
37
- # @raise [ConfigurationError] if the storage or HTTP client is invalid
37
+ # @raise [ConfigurationError] if storage, HTTP transport or lifetime settings are invalid
38
38
  # @example Configure the default transport
39
39
  # AuthProto.configure do |config|
40
40
  # config.http_client = AuthProto::HTTPClient.new
@@ -62,7 +62,7 @@ module AuthProto
62
62
  end
63
63
  end
64
64
 
65
- # Raised when global storage or HTTP transport settings are invalid.
65
+ # Raised when global configuration settings are invalid.
66
66
  class ConfigurationError < Error; end
67
67
 
68
68
  #
@@ -71,18 +71,14 @@ module AuthProto
71
71
 
72
72
  class Configuration
73
73
 
74
- # Configured default token lifetime in seconds (300); currently unused by token exchange.
75
- # @return [Integer]
76
- attr_accessor :default_token_lifetime
74
+ # Default client assertion validity in seconds, read when generating each assertion.
75
+ # @return [Integer] positive lifetime in seconds; defaults to 300
76
+ attr_accessor :client_assertion_lifetime
77
77
 
78
- # Configured default nonce lifetime in seconds (300); nonce managers currently use their own TTL.
79
- # @return [Integer]
78
+ # Default stored nonce lifetime in seconds; used when creating nonce managers without an explicit TTL.
79
+ # @return [Integer] positive lifetime in seconds; defaults to 300
80
80
  attr_accessor :dpop_nonce_lifetime
81
81
 
82
- # Reserved encryption setting; serializers currently create their own service.
83
- # @return [Object, nil]
84
- attr_accessor :encryption
85
-
86
82
  # Transport used for discovery, PAR and token requests; initially `nil`.
87
83
  # @return [#get, #post, nil]
88
84
  attr_accessor :http_client
@@ -91,6 +87,10 @@ module AuthProto
91
87
  # @return [Logger]
92
88
  attr_accessor :logger
93
89
 
90
+ # Lifetime of pending authorization attempts in seconds; defaults to 900 (15 minutes).
91
+ # @return [Integer] positive lifetime in seconds
92
+ attr_accessor :pending_session_ttl
93
+
94
94
  # Storage backend; defaults to a new {Storage::Memory}.
95
95
  # @return [Storage::Interface]
96
96
  attr_accessor :storage
@@ -98,30 +98,51 @@ module AuthProto
98
98
  # Creates default settings with in-memory storage and no HTTP transport.
99
99
  #
100
100
  def initialize
101
- @default_token_lifetime = 300 # 5 minutes in seconds
102
- @dpop_nonce_lifetime = 300 # 5 minutes in seconds
103
- @encryption = nil
101
+ @client_assertion_lifetime = 300 # 5 minutes
102
+ @dpop_nonce_lifetime = 300 # 5 minutes
103
+ @pending_session_ttl = 900 # 15 minutes
104
104
  @http_client = nil
105
105
  @logger = Logger.new($stdout)
106
106
  @storage = AuthProto::Storage::Memory.new
107
107
  end
108
108
 
109
- # Checks that storage implements the interface and the transport supports GET/POST.
109
+ # Checks storage and transport interfaces and positive assertion, nonce and pending session lifetimes.
110
110
  #
111
111
  # A `nil` HTTP client is accepted, but cannot perform OAuth or discovery requests.
112
112
  #
113
113
  # @return [true] if validation succeeds
114
- # @raise [ConfigurationError] if storage is absent/invalid or transport methods are missing
114
+ # @raise [ConfigurationError] if storage, HTTP transport or lifetime settings are invalid
115
115
  #
116
116
  def validate
117
117
  validate_storage
118
118
  validate_http_client
119
+ validate_client_assertion_lifetime
120
+ validate_dpop_nonce_lifetime
121
+ validate_pending_session_ttl
119
122
  true
120
123
  end
121
124
 
122
125
 
123
126
  private
124
127
 
128
+ def validate_client_assertion_lifetime
129
+ return if @client_assertion_lifetime.is_a?(Integer) && @client_assertion_lifetime.positive?
130
+
131
+ raise ConfigurationError, "Client assertion lifetime must be a positive integer"
132
+ end
133
+
134
+ def validate_dpop_nonce_lifetime
135
+ return if @dpop_nonce_lifetime.is_a?(Integer) && @dpop_nonce_lifetime.positive?
136
+
137
+ raise ConfigurationError, "DPoP nonce lifetime must be a positive integer"
138
+ end
139
+
140
+ def validate_pending_session_ttl
141
+ return if @pending_session_ttl.is_a?(Integer) && @pending_session_ttl.positive?
142
+
143
+ raise ConfigurationError, "Pending session TTL must be a positive integer"
144
+ end
145
+
125
146
  def validate_storage
126
147
  raise ConfigurationError, "Storage must be configured" if @storage.nil?
127
148
  return if @storage.is_a?(AuthProto::Storage::Interface)