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
@@ -1,6 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative '../server_metadata/authorization_server'
3
+ require 'time'
4
+
5
+ require_relative '../metadata/authorization_server'
4
6
  require_relative '../state/session'
5
7
  require_relative 'base'
6
8
  require_relative 'token_set'
@@ -29,10 +31,10 @@ module AuthProto
29
31
  end
30
32
 
31
33
  def serialize_data(obj)
32
- {
34
+ data = {
33
35
  session_id: obj.session_id,
34
- state_token: obj.state_token,
35
36
  client_id: obj.client_id,
37
+ dpop_key: obj.dpop_key.private_jwk,
36
38
  scope: obj.scope,
37
39
  pkce_verifier: obj.pkce_verifier,
38
40
  pkce_challenge: obj.pkce_challenge,
@@ -40,24 +42,40 @@ module AuthProto
40
42
  tokens: serialize_token_set(obj.tokens),
41
43
  auth_server: serialize_auth_server(obj.auth_server)
42
44
  }
45
+
46
+ data[:state_token] = obj.state_token if obj.state_token
47
+ data[:signing_key_id] = obj.signing_key_id if obj.signing_key_id
48
+ data[:signing_key_thumbprint] = obj.signing_key_thumbprint if obj.signing_key_thumbprint
49
+ data[:authorization_expires_at] = obj.authorization_expires_at.utc.iso8601(9) if obj.authorization_expires_at
50
+ data
43
51
  end
44
52
 
45
53
  def deserialize_data(data)
46
- AuthProto::State::Session.new(
47
- client_id: data["client_id"],
48
- scope: data["scope"],
49
- did: data["did"],
50
- auth_server: deserialize_auth_server(data["auth_server"])
51
- ).tap do |session|
52
- # Set readonly attributes
53
- session.instance_variable_set(:@session_id, data["session_id"])
54
- session.instance_variable_set(:@state_token, data["state_token"])
55
- session.instance_variable_set(:@pkce_verifier, data["pkce_verifier"])
56
- session.instance_variable_set(:@pkce_challenge, data["pkce_challenge"])
57
-
58
- # Set tokens if present
59
- session.tokens = deserialize_token_set(data["tokens"]) if data["tokens"]
54
+ unless data['dpop_key'].is_a?(Hash)
55
+ raise ValidationError, "Session is missing its private DPoP key; authorize again"
60
56
  end
57
+
58
+ session = AuthProto::State::Session.new(
59
+ client_id: data['client_id'],
60
+ dpop_key: AuthProto::DPoP::KeySet.from_jwk(data.fetch('dpop_key')),
61
+ scope: data['scope'],
62
+ did: data['did'],
63
+ signing_key_id: data['signing_key_id'],
64
+ signing_key_thumbprint: data['signing_key_thumbprint'],
65
+ authorization_expires_at: data['authorization_expires_at'] && Time.iso8601(data['authorization_expires_at']),
66
+ auth_server: deserialize_auth_server(data['auth_server'])
67
+ )
68
+
69
+ # Set readonly attributes
70
+ session.instance_variable_set(:@session_id, data['session_id'])
71
+ session.instance_variable_set(:@state_token, data['state_token'])
72
+ session.instance_variable_set(:@pkce_verifier, data['pkce_verifier'])
73
+ session.instance_variable_set(:@pkce_challenge, data['pkce_challenge'])
74
+
75
+ # Set tokens if present
76
+ session.tokens = deserialize_token_set(data['tokens']) if data['tokens']
77
+
78
+ session
61
79
  end
62
80
 
63
81
  def serialize_token_set(tokens)
@@ -81,7 +99,7 @@ module AuthProto
81
99
  def deserialize_auth_server(data)
82
100
  return nil unless data
83
101
 
84
- AuthProto::ServerMetadata::AuthorizationServer.new(data)
102
+ AuthProto::Metadata::AuthorizationServer.new(data)
85
103
  end
86
104
  end
87
105
  end
@@ -32,7 +32,6 @@ module AuthProto
32
32
  {
33
33
  access_token: obj.access_token,
34
34
  refresh_token: obj.refresh_token,
35
- token_type: obj.token_type,
36
35
  expires_at: obj.expires_at.utc.iso8601,
37
36
  scope: obj.scope,
38
37
  sub: obj.sub
@@ -41,12 +40,12 @@ module AuthProto
41
40
 
42
41
  def deserialize_data(data)
43
42
  AuthProto::State::TokenSet.new(
44
- access_token: data["access_token"],
45
- refresh_token: data["refresh_token"],
46
- token_type: data["token_type"],
47
- expires_in: (Time.parse(data["expires_at"]) - Time.now).to_i,
48
- scope: data["scope"],
49
- sub: data["sub"]
43
+ access_token: data['access_token'],
44
+ refresh_token: data['refresh_token'],
45
+ token_type: 'DPoP',
46
+ expires_in: (Time.parse(data['expires_at']) - Time.now).to_i,
47
+ scope: data['scope'],
48
+ sub: data['sub']
50
49
  )
51
50
  end
52
51
  end
@@ -3,6 +3,7 @@
3
3
  require 'monitor'
4
4
  require 'securerandom'
5
5
 
6
+ require_relative '../dpop/key_set'
6
7
  require_relative '../pkce'
7
8
  require_relative '../state'
8
9
 
@@ -20,14 +21,30 @@ module AuthProto
20
21
  # @return [String]
21
22
  attr_reader :session_id
22
23
 
23
- # Random OAuth state token for callback validation.
24
- # @return [String]
24
+ # Random OAuth state token for callback validation, cleared after authorization completes.
25
+ # @return [String, nil]
25
26
  attr_reader :state_token
26
27
 
28
+ # Deadline for completing pending authorization, cleared after authorization completes.
29
+ # @return [Time, nil]
30
+ attr_reader :authorization_expires_at
31
+
27
32
  # OAuth client identifier.
28
33
  # @return [String]
29
34
  attr_reader :client_id
30
35
 
36
+ # Client-authentication key ID, or nil for public clients.
37
+ # @return [String, nil]
38
+ attr_reader :signing_key_id
39
+
40
+ # RFC 7638 SHA-256 thumbprint of the client-authentication public key.
41
+ # @return [String, nil]
42
+ attr_reader :signing_key_thumbprint
43
+
44
+ # Private DPoP key belonging to this authorization session.
45
+ # @return [DPoP::KeySet]
46
+ attr_reader :dpop_key
47
+
31
48
  # Space-separated requested scopes.
32
49
  # @return [String]
33
50
  attr_reader :scope
@@ -41,7 +58,7 @@ module AuthProto
41
58
  attr_reader :pkce_challenge
42
59
 
43
60
  # Bound authorization server, once discovered.
44
- # @return [ServerMetadata::AuthorizationServer, nil]
61
+ # @return [Metadata::AuthorizationServer, nil]
45
62
  attr_reader :auth_server
46
63
 
47
64
  # Bound account DID, once resolved.
@@ -56,31 +73,64 @@ module AuthProto
56
73
  #
57
74
  # @param client_id [String] OAuth client ID
58
75
  # @param scope [String] requested space-separated scopes
59
- # @param auth_server [ServerMetadata::AuthorizationServer, nil] pre-resolved authorization server
76
+ # @param auth_server [Metadata::AuthorizationServer, nil] pre-resolved authorization server
60
77
  # @param did [String, nil] pre-resolved account DID
78
+ # @param signing_key_id [String, nil] client-authentication key ID selected before PAR
79
+ # @param signing_key_thumbprint [String, nil] RFC 7638 SHA-256 thumbprint of that key
80
+ # @param dpop_key [DPoP::KeySet] session key; a fresh key is generated for new sessions by default
81
+ # @param authorization_expires_at [Time, nil] deadline for completing pending authorization
82
+ # @raise [ArgumentError] if the signing key ID, thumbprint or DPoP key is invalid
83
+ # @raise [DPoP::KeySet::KeyError] if DPoP key generation fails
61
84
  # @raise [PKCE::Error] if PKCE generation fails
62
85
  #
63
- def initialize(client_id:, scope:, auth_server: nil, did: nil)
86
+ def initialize(client_id:, scope:, auth_server: nil, did: nil, signing_key_id: nil, signing_key_thumbprint: nil,
87
+ dpop_key: DPoP::KeySet.new, authorization_expires_at: nil)
64
88
  super() # Initialize MonitorMixin
65
89
 
66
- @session_id = SecureRandom.uuid
67
- @state_token = SecureRandom.urlsafe_base64(32)
90
+ unless signing_key_id.nil? || (signing_key_id.is_a?(String) && !signing_key_id.empty?)
91
+ raise ArgumentError, "signing_key_id must be a nonempty string or nil"
92
+ end
93
+
94
+ unless signing_key_thumbprint.nil? || (signing_key_thumbprint.is_a?(String) && !signing_key_thumbprint.empty?)
95
+ raise ArgumentError, "signing_key_thumbprint must be a nonempty string or nil"
96
+ end
97
+
98
+ raise ArgumentError, "dpop_key must be a DPoP::KeySet" unless dpop_key.is_a?(DPoP::KeySet)
99
+
100
+ @dpop_key = dpop_key
68
101
  @client_id = client_id
102
+ @signing_key_id = signing_key_id&.dup&.freeze
103
+ @signing_key_thumbprint = signing_key_thumbprint&.dup&.freeze
69
104
  @scope = scope
70
105
  @auth_server = auth_server
71
106
  @did = did
107
+ @authorization_expires_at = authorization_expires_at
108
+
109
+ @session_id = SecureRandom.uuid
110
+ @state_token = SecureRandom.urlsafe_base64(32)
72
111
 
73
- # Generate PKCE values
74
- @pkce_verifier = PKCE.generate_verifier
75
- @pkce_challenge = PKCE.generate_challenge(@pkce_verifier)
112
+ pkce = PKCE.new
113
+ @pkce_verifier = pkce.verifier
114
+ @pkce_challenge = pkce.challenge
76
115
 
77
116
  @tokens = nil
78
117
  end
79
118
 
119
+ # Clears the OAuth state token and pending authorization deadline after successful authorization.
120
+ #
121
+ # @return [nil]
122
+ #
123
+ def clear_state_token
124
+ synchronize do
125
+ @state_token = nil
126
+ @authorization_expires_at = nil
127
+ end
128
+ end
129
+
80
130
  # Binds this session to an authorization server.
81
131
  #
82
- # @param server [ServerMetadata::AuthorizationServer] resolved authorization server
83
- # @return [ServerMetadata::AuthorizationServer] assigned server when called as a method
132
+ # @param server [Metadata::AuthorizationServer] resolved authorization server
133
+ # @return [Metadata::AuthorizationServer] assigned server when called as a method
84
134
  # @raise [SessionError] if already bound to a server with a different issuer
85
135
  #
86
136
  def authorization_server=(server)
@@ -124,14 +174,44 @@ module AuthProto
124
174
  end
125
175
  end
126
176
 
177
+ # Returns the current tokens and session identifiers, with expiry in seconds from now.
178
+ #
179
+ # @return [Hash{Symbol => String, Integer, nil}, nil] session data, or `nil` before tokens are assigned
180
+ #
181
+ def session_data
182
+ synchronize do
183
+ return nil unless @tokens
184
+
185
+ {
186
+ access_token: @tokens.access_token,
187
+ token_type: @tokens.token_type,
188
+ expires_in: (@tokens.expires_at - Time.now).to_i,
189
+ refresh_token: @tokens.refresh_token,
190
+ scope: @tokens.scope,
191
+ session_id: @session_id,
192
+ did: @did
193
+ }
194
+ end
195
+ end
196
+
197
+ # Returns true if this session has not completed authorization yet and doesn't contain tokens.
198
+ # @return [Boolean]
199
+ def pending?
200
+ synchronize do
201
+ @tokens.nil?
202
+ end
203
+ end
204
+
127
205
  # Whether this session has valid access tokens
128
206
  # @return [Boolean]
129
- def authorized?
207
+ def tokens_valid?
130
208
  synchronize do
131
209
  !@tokens.nil? && !@tokens.expired?
132
210
  end
133
211
  end
134
212
 
213
+ alias authorized? tokens_valid?
214
+
135
215
  # Whether this session can refresh its tokens
136
216
  # @return [Boolean]
137
217
  def renewable?
@@ -139,30 +219,6 @@ module AuthProto
139
219
  !@tokens.nil? && @tokens.renewable?
140
220
  end
141
221
  end
142
-
143
- # Compares a supplied state token with the session token in constant time.
144
- #
145
- # @param state [String, nil] callback state token
146
- # @return [Boolean] whether it matches; `false` for `nil` or a different length
147
- #
148
- def validate_state(state)
149
- return false unless state
150
-
151
- # Use secure comparison to prevent timing attacks
152
- secure_compare(@state_token, state)
153
- end
154
-
155
- private
156
-
157
- def secure_compare(str1, str2)
158
- return false unless str1.bytesize == str2.bytesize
159
-
160
- left = str1.unpack("C*")
161
- right = str2.unpack("C*")
162
- result = 0
163
- left.zip(right) { |x, y| result |= x ^ y }
164
- result.zero?
165
- end
166
222
  end
167
223
  end
168
224
  end
@@ -15,72 +15,116 @@ module AuthProto
15
15
  class SessionManager
16
16
 
17
17
  # Creates a session manager and its encrypted session serializer.
18
+ #
19
+ # @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
18
21
  # @raise [ArgumentError] if `ATPROTO_MASTER_KEY` is not valid Base64
19
22
  #
20
- def initialize
23
+ def initialize(supported_signing_keys: {})
24
+ keys = supported_signing_keys
25
+
26
+ unless keys.is_a?(Hash) && keys.all? { |id, thumb| [id, thumb].all? { |x| x.is_a?(String) && !x.empty? }}
27
+ raise ArgumentError, "supported_signing_keys must map nonempty key IDs to nonempty thumbprints"
28
+ end
29
+
30
+ @supported_signing_keys = keys.to_h { |id, thumb| [id.dup.freeze, thumb.dup.freeze] }.freeze
21
31
  @serializer = Serialization::Session.new
22
32
  end
23
33
 
24
34
  # Creates and stores a session and its state-token lookup under a storage lock.
35
+ # The signing key thumbprint is taken from the configured key mapping.
25
36
  #
26
37
  # @param client_id [String] OAuth client ID
27
38
  # @param scope [String] requested space-separated scopes
28
- # @param auth_server [ServerMetadata::AuthorizationServer, nil] pre-resolved authorization server
39
+ # @param auth_server [Metadata::AuthorizationServer, nil] pre-resolved authorization server
29
40
  # @param did [String, nil] pre-resolved account DID
41
+ # @param signing_key_id [String, nil] client-authentication key ID selected before PAR
30
42
  #
31
43
  # @return [Session] newly created session
44
+ # @raise [ArgumentError] if the signing key ID is not configured
45
+ # @raise [DPoP::KeySet::KeyError] if session key generation fails
32
46
  # @raise [PKCE::Error] if session PKCE generation fails
33
47
  # @raise [Storage::StorageError] if writing or locking fails
34
48
  # @raise [Serialization::ValidationError] if the session cannot be serialized
35
49
  # @raise [Encryption::EncryptionError] if sensitive fields cannot be encrypted
36
50
  #
37
- def create_session(client_id:, scope:, auth_server: nil, did: nil)
51
+ def create_session(client_id:, scope:, auth_server: nil, did: nil, signing_key_id: nil)
52
+ if signing_key_id && !@supported_signing_keys.key?(signing_key_id)
53
+ raise ArgumentError, "Unsupported signing_key_id: #{signing_key_id}"
54
+ end
55
+
38
56
  session = Session.new(
39
57
  client_id: client_id,
40
58
  scope: scope,
41
59
  auth_server: auth_server,
42
- did: did
60
+ did: did,
61
+ signing_key_id: signing_key_id,
62
+ signing_key_thumbprint: @supported_signing_keys[signing_key_id],
63
+ authorization_expires_at: Time.now + AuthProto.configuration.pending_session_ttl
43
64
  )
44
65
 
45
- # Store both session and state mapping atomically
66
+ # Store the session and state mapping with the same pending authorization lifetime.
46
67
  session_key = Storage::KeyBuilder.session_key(session.session_id)
47
68
  state_key = Storage::KeyBuilder.state_key(session.state_token)
48
69
 
49
70
  AuthProto.storage.with_lock(session_key, ttl: 30) do
71
+ ttl = session_ttl(session)
50
72
  serialized = @serializer.serialize(session)
51
- AuthProto.storage.set(session_key, serialized)
52
- AuthProto.storage.set(state_key, session.session_id)
73
+ AuthProto.storage.set(session_key, serialized, ttl: ttl)
74
+ AuthProto.storage.set(state_key, session.session_id, ttl: ttl)
53
75
  end
54
76
 
55
77
  session
56
78
  end
57
79
 
58
- # Persists a session and updates its state-token lookup under a storage lock.
80
+ # Persists a session under a storage lock.
81
+ #
82
+ # Pending sessions retain their original deadline. Non-renewable authenticated sessions
83
+ # expire with their access token; renewable sessions have no storage expiry.
59
84
  #
60
85
  # @param session [Session] session to persist
61
86
  # @return [Session] the supplied session
62
87
  # @raise [Storage::StorageError] if writing or locking fails
63
88
  # @raise [Serialization::ValidationError] if the session cannot be serialized
64
89
  # @raise [Encryption::EncryptionError] if sensitive fields cannot be encrypted
90
+ # @raise [SessionError] if the pending deadline is missing or the session has expired
65
91
  #
66
92
  def update_session(session)
67
93
  session_key = Storage::KeyBuilder.session_key(session.session_id)
68
94
 
69
95
  AuthProto.storage.with_lock(session_key, ttl: 30) do
96
+ ttl = session_ttl(session)
70
97
  serialized = @serializer.serialize(session)
71
- AuthProto.storage.set(session_key, serialized)
72
-
73
- state_key = Storage::KeyBuilder.state_key(session.state_token)
74
- AuthProto.storage.set(state_key, session.session_id)
98
+ AuthProto.storage.set(session_key, serialized, ttl: ttl)
75
99
  end
76
100
 
77
101
  session
78
102
  end
79
103
 
104
+ # Persists successful authorization without its state token and removes the callback lookup.
105
+ #
106
+ # @param session [Session] session with successfully validated and assigned tokens
107
+ # @return [Session] the supplied session, with its state token cleared
108
+ # @raise [Storage::StorageError] if writing, deletion or locking fails
109
+ # @raise [Serialization::ValidationError] if the session cannot be serialized
110
+ # @raise [Encryption::EncryptionError] if sensitive fields cannot be encrypted
111
+ #
112
+ def complete_authorization(session)
113
+ state_token = session.state_token
114
+ session.clear_state_token
115
+ update_session(session)
116
+
117
+ AuthProto.storage.delete(Storage::KeyBuilder.state_key(state_token)) if state_token
118
+
119
+ session
120
+ end
121
+
80
122
  # Loads and decrypts a session by ID.
81
123
  #
82
124
  # Returns `nil` for missing, unreadable or malformed sessions and for expired
83
- # sessions that have no refresh token. Read/deserialization errors are logged.
125
+ # sessions that have no refresh token. Sessions with an unsupported signing key ID
126
+ # 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.
84
128
  #
85
129
  # @param session_id [String] session identifier
86
130
  # @return [Session, nil] restored session, or `nil` if unavailable
@@ -98,7 +142,18 @@ module AuthProto
98
142
 
99
143
  begin
100
144
  session = @serializer.deserialize(serialized)
101
- return nil if !session.renewable? && session.tokens&.expired?
145
+
146
+ if session.signing_key_id
147
+ thumbprint = @supported_signing_keys[session.signing_key_id]
148
+ return nil unless thumbprint && thumbprint == session.signing_key_thumbprint
149
+ end
150
+
151
+ if session.pending?
152
+ deadline = session.authorization_expires_at
153
+ return nil if !deadline || deadline <= Time.now
154
+ else
155
+ return nil if !session.tokens_valid? && !session.renewable?
156
+ end
102
157
 
103
158
  session
104
159
  rescue StandardError => e
@@ -111,13 +166,13 @@ module AuthProto
111
166
  #
112
167
  # Storage read errors are logged and treated as a missing session.
113
168
  #
114
- # @param state [String, nil] callback state token
169
+ # @param state_token [String, nil] callback state token
115
170
  # @return [Session, nil] restored session, or `nil` if unavailable
116
171
  #
117
- def get_session_by_state(state)
118
- return nil unless state
172
+ def get_session_by_state_token(state_token)
173
+ return nil unless state_token
119
174
 
120
- state_key = Storage::KeyBuilder.state_key(state)
175
+ state_key = Storage::KeyBuilder.state_key(state_token)
121
176
 
122
177
  begin
123
178
  session_id = AuthProto.storage.get(state_key)
@@ -127,7 +182,9 @@ module AuthProto
127
182
  return nil
128
183
  end
129
184
 
130
- get_session(session_id)
185
+ session = get_session(session_id)
186
+
187
+ session if !session.nil? && session.state_token == state_token
131
188
  end
132
189
 
133
190
  # Deletes a session and its state mapping if it can be retrieved.
@@ -136,16 +193,14 @@ module AuthProto
136
193
  # @return [void]
137
194
  # @raise [Storage::StorageError] if deletion or locking fails
138
195
  #
139
- def remove_session(session_id)
196
+ def delete_session(session_id)
140
197
  session = get_session(session_id)
141
198
  return unless session
142
199
 
143
200
  session_key = Storage::KeyBuilder.session_key(session_id)
144
- state_key = Storage::KeyBuilder.state_key(session.state_token)
145
-
146
201
  AuthProto.storage.with_lock(session_key, ttl: 30) do
147
202
  AuthProto.storage.delete(session_key)
148
- AuthProto.storage.delete(state_key)
203
+ AuthProto.storage.delete(Storage::KeyBuilder.state_key(session.state_token)) if session.state_token
149
204
  end
150
205
  end
151
206
 
@@ -157,6 +212,25 @@ module AuthProto
157
212
  def cleanup_expired
158
213
  # No-op - expiry handled by storage TTL and retrieval validation
159
214
  end
215
+
216
+
217
+ private
218
+
219
+ def session_ttl(session)
220
+ return nil if session.renewable?
221
+
222
+ if session.pending?
223
+ expires_at = session.authorization_expires_at
224
+ raise SessionError, "Pending session has no authorization deadline" unless expires_at
225
+ else
226
+ expires_at = session.tokens.expires_at
227
+ end
228
+
229
+ remaining = expires_at - Time.now
230
+ raise SessionError, "Session has expired" unless remaining.positive?
231
+
232
+ remaining.ceil
233
+ end
160
234
  end
161
235
  end
162
236
  end
@@ -17,10 +17,6 @@ module AuthProto
17
17
  # @return [String, nil]
18
18
  attr_reader :refresh_token
19
19
 
20
- # Token scheme; always `DPoP`.
21
- # @return [String]
22
- attr_reader :token_type
23
-
24
20
  # Space-separated granted scopes.
25
21
  # @return [String]
26
22
  attr_reader :scope
@@ -36,35 +32,37 @@ module AuthProto
36
32
  # Creates a token set and calculates its expiry from the current time.
37
33
  #
38
34
  # @param access_token [String] nonempty DPoP-bound access token
39
- # @param token_type [String] must be `DPoP`
40
- # @param expires_in [Integer] lifetime in seconds; negative values represent expired tokens
35
+ # @param token_type [String] must be `DPoP` (case-insensitive)
36
+ # @param expires_in [Integer] lifetime of the access token in seconds; negative value means it's already expired
41
37
  # @param scope [String] nonempty space-separated granted scopes
42
38
  # @param sub [String] nonempty account DID
43
39
  # @param refresh_token [String, nil] refresh token, if issued
44
40
  # @raise [ArgumentError] if required strings are missing, the token type is wrong, or expiry is not an integer
45
41
  #
46
- def initialize(
47
- access_token:,
48
- token_type:,
49
- expires_in:,
50
- scope:,
51
- sub:,
52
- refresh_token: nil
53
- )
42
+ def initialize(access_token:, token_type:, expires_in:, scope:, sub:, refresh_token: nil)
54
43
  validate_token_type(token_type)
55
- validate_required("access_token", access_token)
56
- validate_required("scope", scope)
57
- validate_required("sub", sub)
44
+
45
+ validate_required('access_token', access_token)
46
+ validate_required('scope', scope)
47
+ validate_required('sub', sub)
48
+
58
49
  validate_expires_in(expires_in)
59
50
 
60
51
  @access_token = access_token
61
52
  @refresh_token = refresh_token
62
- @token_type = token_type
63
53
  @scope = scope
64
54
  @sub = sub
65
55
  @expires_at = Time.now + expires_in
66
56
  end
67
57
 
58
+ # Returns the token scheme, which is always `DPoP`.
59
+ #
60
+ # @return [String] `DPoP`
61
+ #
62
+ def token_type
63
+ 'DPoP'
64
+ end
65
+
68
66
  # Whether this token set includes a refresh token
69
67
  # @return [Boolean]
70
68
  def renewable?
@@ -84,7 +82,9 @@ module AuthProto
84
82
  private
85
83
 
86
84
  def validate_token_type(type)
87
- raise ArgumentError, "token_type must be DPoP" unless type == "DPoP"
85
+ unless type.is_a?(String) && type.casecmp?('DPoP')
86
+ raise ArgumentError, "token_type must be DPoP"
87
+ end
88
88
  end
89
89
 
90
90
  def validate_required(name, value)
@@ -29,15 +29,15 @@ module AuthProto
29
29
  # # Create a new session
30
30
  # session = manager.create_session(
31
31
  # client_id: "https://myapp.com/oauth-client-metadata.json",
32
- # scope: "atproto"
32
+ # scope: 'atproto'
33
33
  # )
34
34
  #
35
35
  # # Update session with tokens
36
36
  # tokens = AuthProto::State::TokenSet.new(
37
37
  # access_token: "...",
38
- # token_type: "DPoP",
38
+ # token_type: 'DPoP',
39
39
  # expires_in: 3600,
40
- # scope: "atproto",
40
+ # scope: 'atproto',
41
41
  # sub: "did:plc:abcdef123"
42
42
  # )
43
43
  # session.tokens = tokens
@@ -45,7 +45,7 @@ module AuthProto
45
45
  #
46
46
  # # Lookup session later
47
47
  # session = manager.get_session(session.session_id)
48
- # if session.authorized?
48
+ # if session.tokens_valid?
49
49
  # puts "Access token: #{session.tokens.access_token}"
50
50
  # end
51
51
  #
@@ -39,20 +39,12 @@ module AuthProto
39
39
 
40
40
  # Builds a namespaced storage key for a DPoP nonce.
41
41
  #
42
+ # @param session_id [String] OAuth session identifier
42
43
  # @param server_url [String] server origin URL
43
44
  # @return [String] colon-separated key beginning with `atproto:`
44
45
  #
45
- def nonce_key(server_url)
46
- build_key("nonce", server_url)
47
- end
48
-
49
- # Builds a namespaced storage key for a DPoP key.
50
- #
51
- # @param client_id [String] OAuth client ID
52
- # @return [String] colon-separated key beginning with `atproto:`
53
- #
54
- def dpop_key(client_id)
55
- build_key("dpop", client_id)
46
+ def nonce_key(session_id, server_url)
47
+ build_key("nonce", session_id, server_url)
56
48
  end
57
49
 
58
50
  # Builds a namespaced storage key for a lock.
@@ -32,7 +32,7 @@ module AuthProto
32
32
  #
33
33
  # @param key [String] nonempty key beginning with `atproto:`
34
34
  # @param value [Object] value retained by reference
35
- # @param ttl [Integer, nil] positive expiry in seconds, or `nil` for no new expiry
35
+ # @param ttl [Integer, nil] positive expiry in seconds, or `nil` to clear any expiry
36
36
  # @return [true] if the write succeeds
37
37
  # @raise [StorageError] if key or TTL validation fails
38
38
  #
@@ -42,7 +42,13 @@ module AuthProto
42
42
 
43
43
  @monitor.synchronize do
44
44
  @data[key] = value
45
- set_expiration(key, ttl) if ttl
45
+
46
+ if ttl
47
+ set_expiration(key, ttl)
48
+ else
49
+ @expirations.delete(key)
50
+ end
51
+
46
52
  true
47
53
  end
48
54
  end