authproto 0.3.0.beta3 → 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 (37) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +18 -1
  3. data/examples/confidential_client/Gemfile.lock +1 -1
  4. data/examples/confidential_client/README.md +1 -1
  5. data/examples/confidential_client/app.rb +27 -10
  6. data/examples/minisky_console/Gemfile.lock +2 -2
  7. data/lib/authproto/client.rb +110 -43
  8. data/lib/authproto/dpop/client.rb +1 -1
  9. data/lib/authproto/dpop/nonce_manager.rb +5 -9
  10. data/lib/authproto/dpop/proof_generator.rb +4 -3
  11. data/lib/authproto/encryption.rb +29 -12
  12. data/lib/authproto/http_client.rb +8 -7
  13. data/lib/authproto/metadata/authorization_server.rb +11 -0
  14. data/lib/authproto/metadata/client_metadata.rb +28 -1
  15. data/lib/authproto/metadata/resource_server.rb +3 -3
  16. data/lib/authproto/serialization/session.rb +2 -0
  17. data/lib/authproto/serialization/token_set.rb +5 -2
  18. data/lib/authproto/state/session.rb +37 -1
  19. data/lib/authproto/state/session_manager.rb +30 -6
  20. data/lib/authproto/state/token_set.rb +6 -3
  21. data/lib/authproto/state.rb +1 -1
  22. data/lib/authproto/token/identity.rb +54 -0
  23. data/lib/authproto/token/refresh.rb +42 -52
  24. data/lib/authproto/token/response.rb +73 -0
  25. data/lib/authproto/token/revocation.rb +92 -0
  26. data/lib/authproto/version.rb +1 -1
  27. data/sig/authproto/client.rbs +5 -3
  28. data/sig/authproto/encryption.rbs +4 -2
  29. data/sig/authproto/http_client.rbs +0 -1
  30. data/sig/authproto/metadata/client_metadata.rbs +1 -0
  31. data/sig/authproto/state/session.rbs +3 -0
  32. data/sig/authproto/state/session_manager.rbs +3 -1
  33. data/sig/authproto/token/refresh.rbs +2 -1
  34. data/sig/authproto/token/response.rbs +12 -0
  35. data/sig/authproto/token/revocation.rbs +14 -0
  36. data/sig/authproto.rbs +1 -1
  37. metadata +17 -5
@@ -70,6 +70,10 @@ module AuthProto
70
70
  # @return [String]
71
71
  attr_reader :token_endpoint
72
72
 
73
+ # Optional HTTPS endpoint for token revocation.
74
+ # @return [String, nil]
75
+ attr_reader :revocation_endpoint
76
+
73
77
  # HTTPS PAR endpoint.
74
78
  # @return [String]
75
79
  attr_reader :pushed_authorization_request_endpoint
@@ -148,6 +152,7 @@ module AuthProto
148
152
  issuer: issuer,
149
153
  authorization_endpoint: authorization_endpoint,
150
154
  token_endpoint: token_endpoint,
155
+ revocation_endpoint: revocation_endpoint,
151
156
  pushed_authorization_request_endpoint: pushed_authorization_request_endpoint,
152
157
  response_types_supported: response_types_supported,
153
158
  grant_types_supported: grant_types_supported,
@@ -175,6 +180,7 @@ module AuthProto
175
180
  # Endpoint strings
176
181
  @authorization_endpoint = validate_https_url(data['authorization_endpoint'])
177
182
  @token_endpoint = validate_https_url(data['token_endpoint'])
183
+ @revocation_endpoint = validate_https_url(data['revocation_endpoint']) if data['revocation_endpoint']
178
184
  @pushed_authorization_request_endpoint = validate_https_url(data['pushed_authorization_request_endpoint'])
179
185
 
180
186
  # Capability lists
@@ -220,8 +226,13 @@ module AuthProto
220
226
  def validate_https_url(url)
221
227
  uri = ValidatedURI.new(url)
222
228
  raise InvalidAuthorizationServer, "URL must use HTTPS" unless uri.scheme == 'https'
229
+ raise InvalidAuthorizationServer, "Endpoint URL must not contain userinfo" if uri.userinfo
223
230
  raise InvalidAuthorizationServer, "Endpoint URL must not contain a fragment" if uri.fragment
224
231
 
232
+ unless uri.effective_port.between?(1, 65_535)
233
+ raise InvalidAuthorizationServer, "Endpoint URL must have a valid port"
234
+ end
235
+
225
236
  url
226
237
  end
227
238
 
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'ipaddr'
3
4
  require 'jose'
4
5
  require 'json'
5
6
  require 'uri'
@@ -272,11 +273,23 @@ module AuthProto
272
273
 
273
274
  def valid_https_client_id?(client_id)
274
275
  uri = ValidatedURI.new(client_id)
275
- uri.scheme == 'https' && !uri.port && !uri.userinfo && !uri.fragment
276
+ uri.scheme == 'https' && !uri.port && !uri.userinfo && !uri.fragment &&
277
+ valid_client_id_hostname?(uri.hostname) && !uri.path.empty? && !uri.path.end_with?('/')
276
278
  rescue URI::InvalidURIError
277
279
  false
278
280
  end
279
281
 
282
+ def valid_client_id_hostname?(hostname)
283
+ labels = hostname.downcase.split('.')
284
+ return false if labels.length < 2 || %w[local localhost test invalid example].include?(labels.last)
285
+ return false if hostname.match?(/\A[0-9.]+\z/)
286
+
287
+ IPAddr.new(hostname)
288
+ false
289
+ rescue IPAddr::InvalidAddressError
290
+ true
291
+ end
292
+
280
293
  def valid_localhost_client_id?(client_id)
281
294
  uri = ValidatedURI.new(client_id)
282
295
  uri.scheme == 'http' && uri.host == 'localhost' && !uri.port && !uri.userinfo &&
@@ -289,6 +302,10 @@ module AuthProto
289
302
  raise InvalidClientMetadata, "grant_types is required" unless grant_types
290
303
  raise InvalidClientMetadata, "grant_types must be an array" unless grant_types.is_a?(Array)
291
304
 
305
+ unless grant_types.uniq.length == grant_types.length
306
+ raise InvalidClientMetadata, "grant_types must not contain duplicates"
307
+ end
308
+
292
309
  unless grant_types.include?('authorization_code')
293
310
  raise InvalidClientMetadata, "grant_types must include authorization_code"
294
311
  end
@@ -346,6 +363,10 @@ module AuthProto
346
363
  raise InvalidClientMetadata, "redirect URI must not contain credentials" if uri.userinfo
347
364
  raise InvalidClientMetadata, "redirect URI must not contain a fragment" if uri.fragment
348
365
 
366
+ if ['localhost', '127.0.0.1', '[::1]'].include?(uri.host.downcase)
367
+ raise InvalidClientMetadata, "HTTPS redirect URI must not use a loopback host"
368
+ end
369
+
349
370
  if uri.specified_port && uri.effective_port == 443
350
371
  raise InvalidClientMetadata, "HTTPS redirect URI must not specify the default port"
351
372
  end
@@ -413,6 +434,10 @@ module AuthProto
413
434
  scope_values = scope.split(' ')
414
435
  raise InvalidClientMetadata, "atproto scope is required" unless scope_values.include?('atproto')
415
436
 
437
+ unless scope_values.uniq.length == scope_values.length
438
+ raise InvalidClientMetadata, "scope must not contain duplicate tokens"
439
+ end
440
+
416
441
  scope
417
442
  end
418
443
 
@@ -543,6 +568,8 @@ module AuthProto
543
568
  @token_endpoint_auth_method = metadata['token_endpoint_auth_method']
544
569
  @token_endpoint_auth_signing_alg = metadata['token_endpoint_auth_signing_alg']
545
570
 
571
+ # Not technically required, but if the field is not set, the reference PDS sets it
572
+ # to (unsupported) `client_secret_basic`.
546
573
  raise InvalidClientMetadata, "token_endpoint_auth_method is required" if @token_endpoint_auth_method.nil?
547
574
 
548
575
  @jwks = metadata['jwks']
@@ -41,7 +41,7 @@ module AuthProto
41
41
  # Fetches `/.well-known/oauth-protected-resource` using the configured transport.
42
42
  # Requires HTTP 200 without redirects, a JSON object served as application/json,
43
43
  # and a resource identifier that exactly matches the requested URL.
44
- # URL scheme restrictions are enforced by the configured transport.
44
+ # Requires HTTPS even when the configured transport permits HTTP.
45
45
  # The PDS URL must have no userinfo, path prefix, query or fragment.
46
46
  #
47
47
  # @param url [String] resource server/PDS base URL
@@ -88,9 +88,9 @@ module AuthProto
88
88
  def validate_source_url(url)
89
89
  uri = ValidatedURI.new(url)
90
90
 
91
- unless uri.path.empty? && !uri.userinfo && !uri.query && !uri.fragment
91
+ unless uri.scheme == 'https' && uri.path.empty? && !uri.userinfo && !uri.query && !uri.fragment
92
92
  raise InvalidAuthorizationServer,
93
- "Resource server URL must be an HTTP(S) origin without userinfo, a path prefix, query or fragment"
93
+ "Resource server URL must be an HTTPS origin without userinfo, a path prefix, query or fragment"
94
94
  end
95
95
  rescue URI::InvalidURIError => e
96
96
  raise InvalidAuthorizationServer, "Invalid resource server URL: #{e.message}"
@@ -39,6 +39,7 @@ module AuthProto
39
39
  pkce_verifier: obj.pkce_verifier,
40
40
  pkce_challenge: obj.pkce_challenge,
41
41
  did: obj.did,
42
+ pds: obj.pds,
42
43
  tokens: serialize_token_set(obj.tokens),
43
44
  auth_server: serialize_auth_server(obj.auth_server)
44
45
  }
@@ -60,6 +61,7 @@ module AuthProto
60
61
  dpop_key: AuthProto::DPoP::KeySet.from_jwk(data.fetch('dpop_key')),
61
62
  scope: data['scope'],
62
63
  did: data['did'],
64
+ pds: data['pds'],
63
65
  signing_key_id: data['signing_key_id'],
64
66
  signing_key_thumbprint: data['signing_key_thumbprint'],
65
67
  authorization_expires_at: data['authorization_expires_at'] && Time.iso8601(data['authorization_expires_at']),
@@ -20,6 +20,7 @@ module AuthProto
20
20
  "TokenSet"
21
21
  end
22
22
 
23
+
23
24
  private
24
25
 
25
26
  def validate_object(obj)
@@ -29,13 +30,15 @@ module AuthProto
29
30
  end
30
31
 
31
32
  def serialize_data(obj)
32
- {
33
+ data = {
33
34
  access_token: obj.access_token,
34
- refresh_token: obj.refresh_token,
35
35
  expires_at: obj.expires_at.utc.iso8601,
36
36
  scope: obj.scope,
37
37
  sub: obj.sub
38
38
  }
39
+
40
+ data[:refresh_token] = obj.refresh_token if obj.refresh_token
41
+ data
39
42
  end
40
43
 
41
44
  def deserialize_data(data)
@@ -65,6 +65,10 @@ module AuthProto
65
65
  # @return [String, nil]
66
66
  attr_reader :did
67
67
 
68
+ # PDS URL used to discover the authorization server.
69
+ # @return [String, nil]
70
+ attr_reader :pds
71
+
68
72
  # Most recently assigned tokens, if any.
69
73
  # @return [TokenSet, nil]
70
74
  attr_reader :tokens
@@ -75,6 +79,7 @@ module AuthProto
75
79
  # @param scope [String] requested space-separated scopes
76
80
  # @param auth_server [Metadata::AuthorizationServer, nil] pre-resolved authorization server
77
81
  # @param did [String, nil] pre-resolved account DID
82
+ # @param pds [String, nil] PDS URL used for authorization server discovery
78
83
  # @param signing_key_id [String, nil] client-authentication key ID selected before PAR
79
84
  # @param signing_key_thumbprint [String, nil] RFC 7638 SHA-256 thumbprint of that key
80
85
  # @param dpop_key [DPoP::KeySet] session key; a fresh key is generated for new sessions by default
@@ -83,7 +88,8 @@ module AuthProto
83
88
  # @raise [DPoP::KeySet::KeyError] if DPoP key generation fails
84
89
  # @raise [PKCE::Error] if PKCE generation fails
85
90
  #
86
- def initialize(client_id:, scope:, auth_server: nil, did: nil, signing_key_id: nil, signing_key_thumbprint: nil,
91
+ def initialize(client_id:, scope:, auth_server: nil, did: nil, pds: nil,
92
+ signing_key_id: nil, signing_key_thumbprint: nil,
87
93
  dpop_key: DPoP::KeySet.new, authorization_expires_at: nil)
88
94
  super() # Initialize MonitorMixin
89
95
 
@@ -104,6 +110,7 @@ module AuthProto
104
110
  @scope = scope
105
111
  @auth_server = auth_server
106
112
  @did = did
113
+ @pds = pds&.dup&.freeze
107
114
  @authorization_expires_at = authorization_expires_at
108
115
 
109
116
  @session_id = SecureRandom.uuid
@@ -174,6 +181,27 @@ module AuthProto
174
181
  end
175
182
  end
176
183
 
184
+ # Returns the scope granted by the latest token response, including after refresh.
185
+ #
186
+ # @return [String, nil] space-separated granted scopes, or `nil` before authorization
187
+ #
188
+ def granted_scope
189
+ synchronize do
190
+ @tokens&.scope
191
+ end
192
+ end
193
+
194
+ # Checks whether any requested scope token is absent from the current grant.
195
+ # Scope order and duplicate tokens do not affect the comparison.
196
+ #
197
+ # @return [Boolean] `false` before authorization, otherwise whether requested scopes are missing
198
+ #
199
+ def has_limited_scope?
200
+ synchronize do
201
+ @tokens ? !(@scope.split - @tokens.scope.split).empty? : false
202
+ end
203
+ end
204
+
177
205
  # Returns the current tokens and session identifiers, with expiry in seconds from now.
178
206
  #
179
207
  # @return [Hash{Symbol => String, Integer, nil}, nil] session data, or `nil` before tokens are assigned
@@ -188,6 +216,7 @@ module AuthProto
188
216
  expires_in: (@tokens.expires_at - Time.now).to_i,
189
217
  refresh_token: @tokens.refresh_token,
190
218
  scope: @tokens.scope,
219
+ granted_scope: @tokens.scope,
191
220
  session_id: @session_id,
192
221
  did: @did
193
222
  }
@@ -202,6 +231,13 @@ module AuthProto
202
231
  end
203
232
  end
204
233
 
234
+ # Whether the authorization server advertises a token revocation endpoint.
235
+ # @return [Boolean]
236
+ #
237
+ def can_be_revoked?
238
+ !auth_server&.revocation_endpoint.nil?
239
+ end
240
+
205
241
  # Whether this session has valid access tokens
206
242
  # @return [Boolean]
207
243
  def tokens_valid?
@@ -14,19 +14,25 @@ module AuthProto
14
14
 
15
15
  class SessionManager
16
16
 
17
- # Creates a session manager and its encrypted session serializer.
17
+ # Creates a session manager bound to one client ID and its encrypted session serializer.
18
18
  #
19
+ # @param client_id [String] client ID that all managed sessions must match
19
20
  # @param supported_signing_keys [Hash{String => String}] key IDs mapped to RFC 7638 SHA-256 thumbprints
20
- # @raise [ArgumentError] if key IDs or thumbprints are not nonempty strings
21
+ # @raise [ArgumentError] if the client ID, key IDs or thumbprints are not nonempty strings
21
22
  # @raise [ArgumentError] if `ATPROTO_MASTER_KEY` is not valid Base64
22
23
  #
23
- def initialize(supported_signing_keys: {})
24
+ def initialize(client_id:, supported_signing_keys: {})
25
+ unless client_id.is_a?(String) && !client_id.empty?
26
+ raise ArgumentError, "client_id must be a nonempty string"
27
+ end
28
+
24
29
  keys = supported_signing_keys
25
30
 
26
31
  unless keys.is_a?(Hash) && keys.all? { |id, thumb| [id, thumb].all? { |x| x.is_a?(String) && !x.empty? }}
27
32
  raise ArgumentError, "supported_signing_keys must map nonempty key IDs to nonempty thumbprints"
28
33
  end
29
34
 
35
+ @client_id = client_id.dup.freeze
30
36
  @supported_signing_keys = keys.to_h { |id, thumb| [id.dup.freeze, thumb.dup.freeze] }.freeze
31
37
  @serializer = Serialization::Session.new
32
38
  end
@@ -38,17 +44,21 @@ module AuthProto
38
44
  # @param scope [String] requested space-separated scopes
39
45
  # @param auth_server [Metadata::AuthorizationServer, nil] pre-resolved authorization server
40
46
  # @param did [String, nil] pre-resolved account DID
47
+ # @param pds [String, nil] PDS URL used for authorization server discovery
41
48
  # @param signing_key_id [String, nil] client-authentication key ID selected before PAR
42
49
  #
43
50
  # @return [Session] newly created session
44
51
  # @raise [ArgumentError] if the signing key ID is not configured
52
+ # @raise [SessionError] if the client ID does not match this manager
45
53
  # @raise [DPoP::KeySet::KeyError] if session key generation fails
46
54
  # @raise [PKCE::Error] if session PKCE generation fails
47
55
  # @raise [Storage::StorageError] if writing or locking fails
48
56
  # @raise [Serialization::ValidationError] if the session cannot be serialized
49
57
  # @raise [Encryption::EncryptionError] if sensitive fields cannot be encrypted
50
58
  #
51
- def create_session(client_id:, scope:, auth_server: nil, did: nil, signing_key_id: nil)
59
+ def create_session(client_id:, scope:, auth_server: nil, did: nil, pds: nil, signing_key_id: nil)
60
+ validate_client_id(client_id)
61
+
52
62
  if signing_key_id && !@supported_signing_keys.key?(signing_key_id)
53
63
  raise ArgumentError, "Unsupported signing_key_id: #{signing_key_id}"
54
64
  end
@@ -58,6 +68,7 @@ module AuthProto
58
68
  scope: scope,
59
69
  auth_server: auth_server,
60
70
  did: did,
71
+ pds: pds,
61
72
  signing_key_id: signing_key_id,
62
73
  signing_key_thumbprint: @supported_signing_keys[signing_key_id],
63
74
  authorization_expires_at: Time.now + AuthProto.configuration.pending_session_ttl
@@ -87,9 +98,11 @@ module AuthProto
87
98
  # @raise [Storage::StorageError] if writing or locking fails
88
99
  # @raise [Serialization::ValidationError] if the session cannot be serialized
89
100
  # @raise [Encryption::EncryptionError] if sensitive fields cannot be encrypted
90
- # @raise [SessionError] if the pending deadline is missing or the session has expired
101
+ # @raise [SessionError] if the client ID differs, the pending deadline is missing or the session has expired
91
102
  #
92
103
  def update_session(session)
104
+ validate_client_id(session.client_id)
105
+
93
106
  session_key = Storage::KeyBuilder.session_key(session.session_id)
94
107
 
95
108
  AuthProto.storage.with_lock(session_key, ttl: 30) do
@@ -105,11 +118,14 @@ module AuthProto
105
118
  #
106
119
  # @param session [Session] session with successfully validated and assigned tokens
107
120
  # @return [Session] the supplied session, with its state token cleared
121
+ # @raise [SessionError] if the client ID does not match this manager
108
122
  # @raise [Storage::StorageError] if writing, deletion or locking fails
109
123
  # @raise [Serialization::ValidationError] if the session cannot be serialized
110
124
  # @raise [Encryption::EncryptionError] if sensitive fields cannot be encrypted
111
125
  #
112
126
  def complete_authorization(session)
127
+ validate_client_id(session.client_id)
128
+
113
129
  state_token = session.state_token
114
130
  session.clear_state_token
115
131
  update_session(session)
@@ -124,7 +140,8 @@ module AuthProto
124
140
  # Returns `nil` for missing, unreadable or malformed sessions and for expired
125
141
  # sessions that have no refresh token. Sessions with an unsupported signing key ID
126
142
  # or a missing/mismatching key thumbprint are unavailable but remain in storage.
127
- # Public and legacy sessions without an ID are accepted. Read/deserialization errors are logged.
143
+ # Sessions with a different client ID are unavailable but remain in storage.
144
+ # Public and legacy sessions without a key ID are accepted. Read/deserialization errors are logged.
128
145
  #
129
146
  # @param session_id [String] session identifier
130
147
  # @return [Session, nil] restored session, or `nil` if unavailable
@@ -142,6 +159,7 @@ module AuthProto
142
159
 
143
160
  begin
144
161
  session = @serializer.deserialize(serialized)
162
+ return nil unless session.client_id == @client_id
145
163
 
146
164
  if session.signing_key_id
147
165
  thumbprint = @supported_signing_keys[session.signing_key_id]
@@ -216,6 +234,12 @@ module AuthProto
216
234
 
217
235
  private
218
236
 
237
+ def validate_client_id(client_id)
238
+ return if client_id == @client_id
239
+
240
+ raise SessionError, "Session client_id does not match manager client_id"
241
+ end
242
+
219
243
  def session_ttl(session)
220
244
  return nil if session.renewable?
221
245
 
@@ -36,8 +36,8 @@ module AuthProto
36
36
  # @param expires_in [Integer] lifetime of the access token in seconds; negative value means it's already expired
37
37
  # @param scope [String] nonempty space-separated granted scopes
38
38
  # @param sub [String] nonempty account DID
39
- # @param refresh_token [String, nil] refresh token, if issued
40
- # @raise [ArgumentError] if required strings are missing, the token type is wrong, or expiry is not an integer
39
+ # @param refresh_token [String, nil] nonempty refresh token, if issued
40
+ # @raise [ArgumentError] if token fields have invalid types or values
41
41
  #
42
42
  def initialize(access_token:, token_type:, expires_in:, scope:, sub:, refresh_token: nil)
43
43
  validate_token_type(token_type)
@@ -45,6 +45,7 @@ module AuthProto
45
45
  validate_required('access_token', access_token)
46
46
  validate_required('scope', scope)
47
47
  validate_required('sub', sub)
48
+ validate_required('refresh_token', refresh_token) unless refresh_token.nil?
48
49
 
49
50
  validate_expires_in(expires_in)
50
51
 
@@ -88,7 +89,9 @@ module AuthProto
88
89
  end
89
90
 
90
91
  def validate_required(name, value)
91
- raise ArgumentError, "#{name} is required" if value.nil? || value.empty?
92
+ unless value.is_a?(String) && !value.empty?
93
+ raise ArgumentError, "#{name} must be a nonempty string"
94
+ end
92
95
  end
93
96
 
94
97
  def validate_expires_in(expires_in)
@@ -24,7 +24,7 @@ module AuthProto
24
24
  # with support for lookup by session ID or state token.
25
25
  #
26
26
  # @example Creating and managing a session
27
- # manager = AuthProto::State::SessionManager.new
27
+ # manager = AuthProto::State::SessionManager.new(client_id: 'https://myapp.com/oauth-client-metadata.json')
28
28
  #
29
29
  # # Create a new session
30
30
  # session = manager.create_session(
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'didkit/did'
4
+ require 'uri'
5
+
6
+ require_relative '../errors'
7
+ require_relative '../validated_uri'
8
+
9
+ module AuthProto
10
+ module Token
11
+
12
+ # Error raised when a token subject cannot be bound to the session's PDS.
13
+ class IdentityError < AuthProto::Error; end
14
+
15
+ # Error raised when the subject or its resolved PDS differs from the session binding.
16
+ class IdentityMismatchError < IdentityError; end
17
+
18
+ # Error raised when a DID document cannot be fetched.
19
+ class IdentityLookupError < IdentityError; end
20
+
21
+
22
+ #
23
+ # Shared verification of a token subject's current PDS.
24
+ #
25
+
26
+ module Identity
27
+
28
+ private
29
+
30
+ def validate_subject_pds(subject, session)
31
+ raise IdentityError, "Session is missing its PDS; authorize again" unless session.pds
32
+
33
+ begin
34
+ pds = DIDKit::DID.new(subject).document.pds_endpoint
35
+ rescue DIDKit::DIDError, DIDKit::FormatError => e
36
+ raise IdentityError, "Invalid token subject: #{e.message}"
37
+ rescue StandardError => e
38
+ raise IdentityLookupError, "Could not resolve token subject: #{e.message}"
39
+ end
40
+
41
+ raise IdentityError, "Subject DID document has no PDS endpoint" unless pds
42
+
43
+ pds_uri = ValidatedURI.new(pds)
44
+ session_uri = ValidatedURI.new(session.pds)
45
+
46
+ unless pds_uri.origin.casecmp?(session_uri.origin)
47
+ raise IdentityMismatchError, "Subject PDS does not match session PDS"
48
+ end
49
+ rescue URI::InvalidURIError => e
50
+ raise IdentityError, "Invalid token subject: #{e.message}"
51
+ end
52
+ end
53
+ end
54
+ end
@@ -11,6 +11,9 @@ require_relative '../http_helpers'
11
11
  require_relative '../par'
12
12
  require_relative '../par/client_assertion'
13
13
  require_relative '../state/token_set'
14
+ require_relative 'identity'
15
+ require_relative 'response'
16
+ require_relative 'revocation'
14
17
 
15
18
  module AuthProto
16
19
 
@@ -118,6 +121,7 @@ module AuthProto
118
121
 
119
122
  class Refresh
120
123
  include HTTPHelpers
124
+ include Identity
121
125
  include MonitorMixin
122
126
 
123
127
  # Maximum attempts for one refresh operation.
@@ -178,6 +182,8 @@ module AuthProto
178
182
  # and jitter. Each attempt can retry one DPoP nonce challenge. Does not assign
179
183
  # the returned tokens to the session or persist them; the caller must do so.
180
184
  # HTTP 400/401 OAuth errors preserve the server's error code and description in the exception message.
185
+ # Retains the existing refresh token when the response omits a replacement.
186
+ # Verifies the subject's current PDS before the exchange and attempts revocation on identity mismatch.
181
187
  #
182
188
  # @return [State::TokenSet] validated replacement tokens
183
189
  # @raise [RefreshError] if the session is not renewable, refresh fails, or retries are exhausted
@@ -188,6 +194,8 @@ module AuthProto
188
194
  raise RefreshError.new("No refresh token available", retry_possible: false) unless session.renewable?
189
195
  raise RefreshError.new("No access token to refresh", retry_possible: false) if session.tokens.nil?
190
196
 
197
+ validate_identity
198
+
191
199
  with_retries do
192
200
  request_token_refresh
193
201
  end
@@ -197,6 +205,31 @@ module AuthProto
197
205
 
198
206
  private
199
207
 
208
+ def validate_identity
209
+ validate_subject_pds(session.did, session)
210
+ rescue IdentityMismatchError => e
211
+ revoke_rejected_refresh_token(session.tokens.refresh_token) if session.tokens.refresh_token
212
+ raise RefreshError.new(e.message, retry_possible: false)
213
+ rescue IdentityError => e
214
+ raise RefreshError.new(e.message, retry_possible: false)
215
+ end
216
+
217
+ def revoke_rejected_refresh_token(token)
218
+ return unless session.can_be_revoked?
219
+
220
+ revocation = Revocation.new(
221
+ session: session,
222
+ dpop_client: dpop_client,
223
+ client_metadata: client_metadata,
224
+ client_assertion: @client_assertion
225
+ )
226
+
227
+ revocation.revoke_token(token, :token_type => :refresh_token)
228
+ rescue StandardError
229
+ # Cleanup failures must not replace the original identity error.
230
+ nil
231
+ end
232
+
200
233
  def with_retries
201
234
  @attempt_count = 0
202
235
  last_error = nil
@@ -241,7 +274,6 @@ module AuthProto
241
274
  body = {
242
275
  grant_type: 'refresh_token',
243
276
  refresh_token: session.tokens.refresh_token,
244
- scope: session.scope,
245
277
  client_id: client_metadata.client_id
246
278
  }
247
279
 
@@ -278,21 +310,11 @@ module AuthProto
278
310
  end
279
311
 
280
312
  def process_successful_response(response)
281
- raise RefreshError.new("Missing response body", retry_possible: false) if response[:body].nil?
282
-
283
- data = JSON.parse(response[:body])
284
- validate_refresh_response(data)
285
-
286
- AuthProto::State::TokenSet.new(
287
- access_token: data['access_token'],
288
- token_type: data['token_type'],
289
- expires_in: data['expires_in'],
290
- refresh_token: data['refresh_token'],
291
- scope: data['scope'],
292
- sub: data['sub']
293
- )
294
- rescue JSON::ParserError => e
295
- raise RefreshError.new("Invalid response format: #{e.message}", retry_possible: false)
313
+ tokens = Response.parse(response, current_tokens: session.tokens)
314
+ validate_refresh_identity(tokens)
315
+ tokens
316
+ rescue Response::Error => e
317
+ raise RefreshError.new(e.message, retry_possible: false)
296
318
  end
297
319
 
298
320
  def handle_error_response(response)
@@ -330,43 +352,11 @@ module AuthProto
330
352
  raise RefreshError, "Rate limited - retry after #{retry_after} seconds"
331
353
  end
332
354
 
333
- def validate_refresh_response(data)
334
- unless data.is_a?(Hash)
335
- raise RefreshError.new("Token response must be a JSON object", retry_possible: false)
336
- end
337
-
338
- %w[access_token token_type expires_in scope sub].each do |field|
339
- raise RefreshError.new("Missing #{field} in response", retry_possible: false) unless data[field]
355
+ def validate_refresh_identity(tokens)
356
+ if tokens.sub != session.tokens.sub
357
+ revoke_rejected_refresh_token(tokens.refresh_token) if tokens.refresh_token
358
+ raise RefreshError.new("Subject mismatch in response", retry_possible: false)
340
359
  end
341
-
342
- %w[access_token token_type scope sub].each do |field|
343
- unless data[field].is_a?(String) && !data[field].empty?
344
- raise RefreshError.new("Invalid #{field} in response", retry_possible: false)
345
- end
346
- end
347
-
348
- unless data['expires_in'].is_a?(Integer)
349
- raise RefreshError.new("Invalid expires_in in response", retry_possible: false)
350
- end
351
-
352
- unless data['refresh_token'].nil? || data['refresh_token'].is_a?(String)
353
- raise RefreshError.new("Invalid refresh_token in response", retry_possible: false)
354
- end
355
-
356
- unless data['token_type'].casecmp?('DPoP')
357
- raise RefreshError.new("Invalid token_type: #{data['token_type']}", retry_possible: false)
358
- end
359
-
360
- original_scopes = session.scope.split
361
- response_scopes = data['scope'].split
362
-
363
- unless (original_scopes - response_scopes).empty?
364
- raise RefreshError.new("Invalid scope in response", retry_possible: false)
365
- end
366
-
367
- return if data['sub'] == session.tokens.sub
368
-
369
- raise RefreshError.new("Subject mismatch in response", retry_possible: false)
370
360
  end
371
361
  end
372
362
  end