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
@@ -6,6 +6,7 @@ require 'net/http'
6
6
  require 'uri'
7
7
 
8
8
  require_relative 'client'
9
+ require_relative 'http_helpers'
9
10
 
10
11
  #
11
12
  # Experimental Minisky client backed by an AuthProto session.
@@ -13,6 +14,7 @@ require_relative 'client'
13
14
  #
14
15
 
15
16
  class Minisky::OAuthClient
17
+ include AuthProto::HTTPHelpers
16
18
  include Minisky::Requests
17
19
 
18
20
  # Maximum authenticated XRPC retries after nonce challenges.
@@ -41,14 +43,14 @@ class Minisky::OAuthClient
41
43
  # @param redirect_uri [String] registered callback URI
42
44
  # @param metadata [Hash{String => Object}, nil] preloaded metadata, or `nil` to fetch it
43
45
  # @param signing_key [Hash, JOSE::JWK, nil] private ES256 key for confidential-client authentication
44
- # @param dpop_key [Hash{String => Object}, nil] existing private DPoP JWK, or `nil` to generate one
46
+ # @param session_id [String, nil] stored session ID to resume; `nil` starts without an attached session
45
47
  #
46
48
  # @raise [AuthProto::InvalidClientMetadata] if metadata is invalid or unavailable
47
49
  # @raise [AuthProto::Error] if OAuth client or DPoP initialization fails
48
50
  # @raise [AuthProto::HTTPClient::HTTPError, AuthProto::HTTPClient::SSRFError] if fetching metadata fails
49
51
  # @see AuthProto::Client#initialize
50
52
  #
51
- def initialize(host, client_id:, redirect_uri:, metadata: nil, dpop_key: nil, signing_key: nil, session_id: nil)
53
+ def initialize(host, client_id:, redirect_uri:, metadata: nil, signing_key: nil, session_id: nil)
52
54
  @host = host
53
55
  @session_id = session_id
54
56
 
@@ -59,7 +61,6 @@ class Minisky::OAuthClient
59
61
  client_id: client_id,
60
62
  redirect_uri: redirect_uri,
61
63
  metadata: metadata,
62
- dpop_key: dpop_key,
63
64
  signing_key: signing_key
64
65
  )
65
66
  end
@@ -87,19 +88,22 @@ class Minisky::OAuthClient
87
88
 
88
89
  # Completes OAuth authorization and remembers the authenticated session ID.
89
90
  #
91
+ # @param expected_session_id [String] pending session ID retained in the initiating browser session or native context
90
92
  # @param options [Hash{Symbol => String}] callback parameters forwarded to {AuthProto::Client#handle_callback}
91
93
  # @option options [String] :code authorization code
92
94
  # @option options [String] :state callback state token
93
95
  # @option options [String] :iss authorization server issuer
94
96
  #
95
97
  # @return [Hash{Symbol => String, Integer, nil}] token and session details from the OAuth client
96
- # @raise [AuthProto::Client::CallbackError] if state or issuer validation fails
98
+ # @raise [AuthProto::Client::CallbackError] if expected session, state or issuer validation fails
97
99
  # @raise [AuthProto::Client::TokenError] if token exchange or validation fails
98
100
  # @raise [AuthProto::Error] if proofs, storage or serialization fail
99
101
  # @see AuthProto::Client#handle_callback
100
102
  #
101
- def handle_callback(**options)
102
- oauth_client.handle_callback(**options).tap { |result| @session_id = result.fetch(:session_id) }
103
+ def handle_callback(expected_session_id:, **options)
104
+ oauth_client.handle_callback(**options, expected_session_id: expected_session_id).tap do |result|
105
+ @session_id = result.fetch(:session_id)
106
+ end
103
107
  end
104
108
 
105
109
  # Sends an XRPC GET through Minisky, adding OAuth handling when authenticated.
@@ -117,7 +121,7 @@ class Minisky::OAuthClient
117
121
  # @raise [ArgumentError] if the method is invalid or `auth` is a truthy non-Boolean value
118
122
  # @raise [Minisky::AuthError] if no completed OAuth login or refresh capability is available
119
123
  # @raise [Minisky::BadResponse] if the final response has an error or redirect status
120
- # @raise [AuthProto::DPoP::Client::Error] if proof handling fails or a nonce challenge lacks its nonce
124
+ # @raise [AuthProto::DPoP::Client::Error] if proof handling fails or any DPoP response lacks a valid nonce
121
125
  # @raise [AuthProto::Error] if OAuth refresh or token persistence fails
122
126
  # @raise [JSON::ParserError] if a JSON response cannot be parsed
123
127
  # @raise [Net::OpenTimeout, Net::ReadTimeout, IOError, SystemCallError] if HTTP transport fails
@@ -152,7 +156,7 @@ class Minisky::OAuthClient
152
156
  # @raise [ArgumentError] if the method is invalid or `auth` is a truthy non-Boolean value
153
157
  # @raise [Minisky::AuthError] if no completed OAuth login or refresh capability is available
154
158
  # @raise [Minisky::BadResponse] if the final response has an error or redirect status
155
- # @raise [AuthProto::DPoP::Client::Error] if proof handling fails or a nonce challenge lacks its nonce
159
+ # @raise [AuthProto::DPoP::Client::Error] if proof handling fails or any DPoP response lacks a valid nonce
156
160
  # @raise [AuthProto::Error] if OAuth refresh or token persistence fails
157
161
  # @raise [JSON::ParserError] if a JSON response cannot be parsed
158
162
  # @raise [Net::OpenTimeout, Net::ReadTimeout, IOError, SystemCallError] if HTTP transport fails
@@ -196,6 +200,7 @@ class Minisky::OAuthClient
196
200
  # @raise [AuthProto::Client::TokenError] if the session cannot be refreshed
197
201
  # @raise [AuthProto::Token::RefreshError] if refresh fails
198
202
  # @raise [AuthProto::Storage::StorageError] if token persistence fails
203
+ # @raise [AuthProto::DPoP::Client::Error] if a refresh response has a missing or invalid nonce
199
204
  #
200
205
  def perform_token_refresh
201
206
  oauth_client.refresh_token(session_id)
@@ -209,14 +214,17 @@ class Minisky::OAuthClient
209
214
  #
210
215
  def check_access
211
216
  session = oauth_client.session_manager.get_session(session_id) if session_id
212
- raise Minisky::AuthError, "Complete OAuth login before making authenticated requests" unless session&.tokens
213
-
214
- return :ok unless session.tokens.expired?
215
-
216
- raise Minisky::AuthError, "OAuth session cannot be refreshed; log in again" unless session.renewable?
217
217
 
218
- perform_token_refresh
219
- :refreshed
218
+ if !session || session.pending?
219
+ raise Minisky::AuthError, "Complete OAuth login before making authenticated requests"
220
+ elsif session.tokens_valid?
221
+ :ok
222
+ elsif session.renewable?
223
+ perform_token_refresh
224
+ :refreshed
225
+ else
226
+ raise Minisky::AuthError, "OAuth session cannot be refreshed; log in again"
227
+ end
220
228
  end
221
229
 
222
230
 
@@ -237,35 +245,29 @@ class Minisky::OAuthClient
237
245
 
238
246
  request = request_class.new(url, request_headers)
239
247
  request.body = body unless body.nil?
248
+
240
249
  response = make_request(request)
250
+ response_hash = { status: response.code.to_i, headers: response.each_header.to_h, body: response.body }
241
251
 
242
- nonce = response["DPoP-Nonce"]
243
- oauth_client.dpop_client.process_response(response.each_header.to_h, url.to_s) if nonce && !nonce.empty?
244
- error = authentication_error(response)
252
+ oauth_client.dpop_client.process_response(response_hash, server_url: url.to_s, session_id: session_id)
245
253
 
246
- if response.code.to_i == 401 && error == AuthProto::DPoP::ERROR_USE_NONCE
247
- unless nonce && !nonce.empty?
248
- raise AuthProto::DPoP::Client::Error, "DPoP nonce challenge (HTTP 401) is missing DPoP-Nonce"
249
- end
254
+ if oauth_client.dpop_client.has_nonce_error?(response_hash)
250
255
  return response if nonce_retries >= MAX_NONCE_RETRIES
251
-
252
256
  nonce_retries += 1
253
- elsif response.code.to_i == 401 && error == "invalid_token" && !refreshed
254
- perform_token_refresh
255
- refreshed = true
256
257
  else
257
- return response
258
+ error = authentication_error(response)
259
+
260
+ if response.code.to_i == 401 && error == "invalid_token" && !refreshed
261
+ perform_token_refresh
262
+ refreshed = true
263
+ else
264
+ return response
265
+ end
258
266
  end
259
267
  end
260
268
  end
261
269
 
262
270
  def authentication_error(response)
263
- # Only interpret a single DPoP challenge. Leave other auth schemes and
264
- # ambiguous multi-challenge headers to Minisky's normal error handling.
265
- challenge = response["WWW-Authenticate"].to_s
266
- return unless challenge.match?(/\ADPoP\s/i)
267
- return if challenge.match?(/,\s*(?:Bearer|Basic|DPoP)\b/i)
268
-
269
- challenge[/\berror\s*=\s*"(use_dpop_nonce|invalid_token)"/i, 1]
271
+ authentication_challenge(response['WWW-Authenticate'], scheme: 'DPoP')&.fetch('error', nil)
270
272
  end
271
273
  end
@@ -4,6 +4,7 @@ require 'json'
4
4
  require 'uri'
5
5
 
6
6
  require_relative '../configuration'
7
+ require_relative '../http_helpers'
7
8
  require_relative '../par'
8
9
  require_relative 'response'
9
10
 
@@ -37,7 +38,8 @@ module AuthProto
37
38
  # config.scope = 'atproto'
38
39
  # end
39
40
  #
40
- # response = client.submit(request)
41
+ # session = AuthProto::State::Session.new(client_id: client_id, scope: 'atproto')
42
+ # response = client.submit(request, session: session)
41
43
  #
42
44
  # # Build authorization URL using response
43
45
  # auth_url = client.build_authorization_url(
@@ -57,6 +59,7 @@ module AuthProto
57
59
  #
58
60
 
59
61
  class Client
62
+ include HTTPHelpers
60
63
 
61
64
  # Authorization server supplying endpoints and the client assertion audience.
62
65
  # @return [Metadata::AuthorizationServer]
@@ -79,54 +82,31 @@ module AuthProto
79
82
  @authorization_server = authorization_server
80
83
  @par_endpoint = authorization_server.pushed_authorization_request_endpoint
81
84
  @dpop_client = dpop_client
82
- @nonce_manager = dpop_client.nonce_manager
83
85
  end
84
86
 
85
87
  # Submits a PAR request, handling DPoP nonce requirements
86
88
  #
87
89
  # @param request [Request] The request to submit
90
+ # @param session [State::Session] session whose key signs PAR and any retries
88
91
  # @return [Response] The PAR response
89
92
  # @raise [Error] if request fails
90
93
  #
91
- def submit(request)
94
+ def submit(request, session:)
92
95
  raise Error, "Expected a PAR::Request" unless request.is_a?(PAR::Request)
93
96
 
94
- # Try the initial request
95
- response = make_request(request)
96
-
97
- return process_response(response) if response[:status] == 201
98
-
99
- # Handle DPoP nonce requirement
100
- if requires_nonce?(response)
101
- nonce = extract_nonce(response)
102
- store_nonce(nonce)
103
-
104
- # Get stored nonce to verify
105
- @nonce_manager.get(server_origin)
106
-
107
- # Generate new proof with nonce and retry
108
- response = make_request(request)
109
- return process_response(response) if response[:status] == 201
97
+ response = dpop_client.with_nonce_handling(session, @par_endpoint) do
98
+ make_request(request, session: session)
110
99
  end
111
100
 
112
- handle_error_response(response)
101
+ if response[:status] == 201
102
+ handle_success_response(response)
103
+ else
104
+ handle_error_response(response)
105
+ end
113
106
  rescue StandardError => e
114
107
  raise Error, "PAR request failed: #{e.message}"
115
108
  end
116
109
 
117
- # Reads a nonce from a transport response hash.
118
- #
119
- # @param response [Hash{Symbol => Object}] response containing a `:headers` hash with a `DPoP-Nonce` header
120
- # @return [String] server-provided nonce
121
- # @raise [Error] if no supported nonce header is present
122
- #
123
- def extract_nonce(response)
124
- nonce = response[:headers].find { |k, v| k.downcase == 'dpop-nonce' }&.last
125
- raise Error, "No DPoP nonce provided in response" unless nonce
126
-
127
- nonce
128
- end
129
-
130
110
  # Builds the browser URL using the client ID and returned PAR request URI.
131
111
  #
132
112
  # Retains existing query parameters.
@@ -155,48 +135,19 @@ module AuthProto
155
135
 
156
136
  private
157
137
 
158
- def make_request(request)
159
- # Generate DPoP proof for this request
160
- proof = dpop_client.generate_proof(
161
- method: 'POST',
162
- uri: @par_endpoint,
163
- nonce: @nonce_manager.get(server_origin)
164
- )
165
-
166
- # Build headers including DPoP proof
167
- headers = build_headers(request, proof)
138
+ def make_request(request, session:)
139
+ dpop_proof = dpop_client.generate_proof(session: session, method: 'POST', uri: @par_endpoint)
168
140
 
169
- # Make the request
170
141
  AuthProto.configuration.http_client.post(
171
142
  @par_endpoint,
172
143
  body: request.to_form(audience: @authorization_server.issuer),
173
- headers: headers
144
+ headers: {
145
+ "Content-Type" => "application/x-www-form-urlencoded",
146
+ "DPoP" => dpop_proof
147
+ }
174
148
  )
175
149
  end
176
150
 
177
- def build_headers(request, dpop_proof)
178
- {
179
- "Content-Type" => "application/x-www-form-urlencoded",
180
- "DPoP" => dpop_proof
181
- }
182
- end
183
-
184
- def requires_nonce?(response)
185
- body = JSON.parse(response[:body])
186
- body['error'] == DPoP::ERROR_USE_NONCE
187
- rescue JSON::ParserError
188
- false
189
- end
190
-
191
- def store_nonce(nonce)
192
- @nonce_manager.update(nonce: nonce, server_url: server_origin)
193
- end
194
-
195
- def server_origin
196
- uri = URI(@par_endpoint)
197
- "#{uri.scheme}://#{uri.host}#{":#{uri.port}" if uri.port != uri.default_port}"
198
- end
199
-
200
151
  def handle_error_response(response)
201
152
  begin
202
153
  error_data = JSON.parse(response[:body])
@@ -208,12 +159,10 @@ module AuthProto
208
159
  raise Error, "PAR request failed: #{error_message} (status: #{response[:status]})"
209
160
  end
210
161
 
211
- def process_response(response)
212
- raise Error, "unexpected response status: #{response[:status]}" unless response[:status] == 201
213
-
214
- content_type = (response[:headers] || {}).find { |key, _| key.downcase == 'content-type' }&.last
162
+ def handle_success_response(response)
163
+ content_type = response_header(response, 'Content-Type', strip_parameters: true)
215
164
 
216
- unless content_type.to_s.split(';', 2).first.to_s.strip.casecmp?('application/json')
165
+ unless content_type.to_s.casecmp?('application/json')
217
166
  raise Error, "PAR response must use application/json"
218
167
  end
219
168
 
@@ -1,9 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'jwt'
4
3
  require 'jose'
4
+ require 'jwt'
5
5
  require 'securerandom'
6
6
 
7
+ require_relative '../configuration'
7
8
  require_relative '../errors'
8
9
 
9
10
  module AuthProto
@@ -20,6 +21,12 @@ module AuthProto
20
21
  # Raised when client assertion key import or JWT signing fails.
21
22
  class Error < AuthProto::Error; end
22
23
 
24
+ # JWS signing algorithm used for client assertions.
25
+ # @return [String]
26
+ ALGORITHM = "ES256"
27
+
28
+ # Validated private EC P-256 key used by this reusable assertion signer.
29
+ # @return [JOSE::JWK]
23
30
  attr_reader :signing_key
24
31
 
25
32
  # Creates an ES256 client assertion signer.
@@ -27,9 +34,15 @@ module AuthProto
27
34
  # @param client_id [String] client ID used in `iss` and `sub`
28
35
  # @param signing_key [Hash, JOSE::JWK] private EC P-256 signing key, including its `kid`
29
36
  # @raise [Error] if the key cannot sign with ES256 or its usage is incompatible
37
+ # (`key_ops`, when present, must contain `sign` and optionally `verify`, without duplicates)
38
+ # @raise [Error] if the client ID is not a nonblank string
30
39
  #
31
40
  def initialize(client_id:, signing_key:)
32
- @client_id = client_id
41
+ unless client_id.is_a?(String) && !client_id.strip.empty?
42
+ raise Error, "client_id must be a nonblank string"
43
+ end
44
+
45
+ @client_id = client_id.dup.freeze
33
46
  @signing_key = validate_signing_key(signing_key)
34
47
  rescue ClientAssertion::Error
35
48
  raise
@@ -37,16 +50,24 @@ module AuthProto
37
50
  raise Error, "Invalid signing_key: #{e.message}"
38
51
  end
39
52
 
40
- # Signs a short-lived client authentication JWT with ES256.
53
+ # Signs a fresh, short-lived client authentication JWT with the cached ES256 key.
41
54
  #
42
55
  # Includes `iss`, `sub`, `aud`, a unique `jti`, and `iat`/`exp` times.
43
56
  #
44
57
  # @param audience [String] authorization server issuer URL used as the assertion audience
45
- # @param lifetime [Integer] validity in seconds; defaults to five minutes
58
+ # @param lifetime [Integer] positive validity in seconds; defaults to {Configuration#client_assertion_lifetime}
46
59
  # @return [String] compact signed client assertion JWT
47
- # @raise [Error] if JWK import or JWT signing fails
60
+ # @raise [Error] if the audience is not a nonblank string, lifetime is not a positive integer, or signing fails
48
61
  #
49
- def generate_jwt(audience:, lifetime: 300)
62
+ def generate_jwt(audience:, lifetime: AuthProto.configuration.client_assertion_lifetime)
63
+ unless audience.is_a?(String) && !audience.strip.empty?
64
+ raise Error, "audience must be a nonblank string"
65
+ end
66
+
67
+ unless lifetime.is_a?(Integer) && lifetime.positive?
68
+ raise Error, "lifetime must be a positive integer"
69
+ end
70
+
50
71
  now = Time.now.to_i
51
72
 
52
73
  payload = {
@@ -59,13 +80,12 @@ module AuthProto
59
80
  }
60
81
 
61
82
  header = {
62
- alg: 'ES256',
83
+ alg: ALGORITHM,
63
84
  typ: 'JWT',
64
85
  kid: @signing_key.fields['kid']
65
86
  }
66
87
 
67
- key = JWT::JWK.import(@signing_key.to_map.to_h)
68
- JWT.encode(payload, key, 'ES256', header)
88
+ JWT.encode(payload, @jwt_signing_key, ALGORITHM, header)
69
89
  rescue JWT::Error, ArgumentError => e
70
90
  raise Error, "Failed to generate client assertion: #{e.message}"
71
91
  end
@@ -93,17 +113,28 @@ module AuthProto
93
113
  end
94
114
  end
95
115
 
96
- if (data.key?('alg') && data['alg'] != 'ES256') ||
97
- (data.key?('use') && data['use'] != 'sig') ||
98
- (data.key?('key_ops') && (!data['key_ops'].is_a?(Array) || !data['key_ops'].include?('sign')))
99
- raise Error, "signing_key must be active and permit ES256 signing"
116
+ if (data.key?('alg') && data['alg'] != ALGORITHM) ||
117
+ (data.key?('use') && data['use'] != 'sig')
118
+ raise Error, "signing_key must be active and permit #{ALGORITHM} signing"
119
+ end
120
+
121
+ if data.key?('key_ops')
122
+ raise Error, "signing_key.key_ops is not an array" unless data['key_ops'].is_a?(Array)
123
+
124
+ ops = data['key_ops'].sort_by(&:to_s)
125
+
126
+ unless ops == ['sign'] || ops == ['sign', 'verify']
127
+ raise Error, "signing_key.key_ops must contain sign and optionally verify, without duplicates"
128
+ end
100
129
  end
101
130
 
102
131
  signing_key = JOSE::JWK.from_map(data)
103
132
 
104
- imported = JWT::JWK.import(data)
105
- proof = JWT.encode({}, imported, 'ES256')
106
- JWT.decode(proof, imported.public_key, true, algorithms: ['ES256'])
133
+ imported_key = JWT::JWK.import(data)
134
+ proof = JWT.encode({}, imported_key, ALGORITHM)
135
+ JWT.decode(proof, imported_key.public_key, true, algorithms: [ALGORITHM])
136
+
137
+ @jwt_signing_key = imported_key
107
138
 
108
139
  signing_key
109
140
  end
@@ -41,7 +41,7 @@ module AuthProto
41
41
  # @return [String]
42
42
  attr_reader :scope
43
43
 
44
- # Account handle to prefill at the authorization server.
44
+ # Account handle or DID to prefill at the authorization server.
45
45
  # @return [String, nil]
46
46
  attr_reader :login_hint
47
47
 
@@ -49,17 +49,13 @@ module AuthProto
49
49
  # @return [String, nil]
50
50
  attr_reader :nonce
51
51
 
52
- # Optional proof value retained on the request; {Client#submit} generates its own HTTP proof.
53
- # @return [String, nil]
54
- attr_reader :dpop_proof
55
-
56
52
  # Client authentication signer; a fresh JWT is generated for each form encoding.
57
53
  # @return [ClientAssertion, nil]
58
54
  attr_reader :client_assertion
59
55
  end
60
56
 
61
57
  #
62
- # A draft PAR request with writable fields, configured inside the block passed to {Request.build}).
58
+ # A draft PAR request with writable fields, configured inside the block passed to {Request.build}.
63
59
  #
64
60
 
65
61
  class Configuration
@@ -77,7 +73,7 @@ module AuthProto
77
73
  # @yieldparam config [Configuration] mutable request settings
78
74
  # @yieldreturn [Object] ignored
79
75
  # @return [Request] validated pushed authorization request
80
- # @raise [Error] if required parameters, PKCE, scope or client authentication are invalid
76
+ # @raise [Error] if required parameters are missing, `atproto` scope is absent or the signer has an invalid type
81
77
  #
82
78
  def self.build
83
79
  config = Configuration.new
@@ -88,7 +84,7 @@ module AuthProto
88
84
  # Copies and validates a PAR parameter configuration.
89
85
  #
90
86
  # @param config [Configuration] populated request settings
91
- # @raise [Error] if required values are missing or authentication/PKCE/scope values are invalid
87
+ # @raise [Error] if required values are missing, `atproto` scope is absent or the signer has an invalid type
92
88
  #
93
89
  def initialize(config)
94
90
  Fields.instance_methods(false).each do |field|
data/lib/authproto/par.rb CHANGED
@@ -27,7 +27,8 @@ module AuthProto
27
27
  # config.scope = 'atproto'
28
28
  # end
29
29
  #
30
- # response = par.submit(request)
30
+ # session = AuthProto::State::Session.new(client_id: client_id, scope: 'atproto')
31
+ # response = par.submit(request, session: session)
31
32
  # auth_url = par.build_authorization_url(
32
33
  # request_uri: response.request_uri,
33
34
  # client_id: request.client_id
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'time'
4
+
3
5
  require_relative '../metadata/authorization_server'
4
6
  require_relative '../state/session'
5
7
  require_relative 'base'
@@ -29,35 +31,53 @@ 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,
39
41
  did: obj.did,
42
+ pds: obj.pds,
40
43
  tokens: serialize_token_set(obj.tokens),
41
44
  auth_server: serialize_auth_server(obj.auth_server)
42
45
  }
46
+
47
+ data[:state_token] = obj.state_token if obj.state_token
48
+ data[:signing_key_id] = obj.signing_key_id if obj.signing_key_id
49
+ data[:signing_key_thumbprint] = obj.signing_key_thumbprint if obj.signing_key_thumbprint
50
+ data[:authorization_expires_at] = obj.authorization_expires_at.utc.iso8601(9) if obj.authorization_expires_at
51
+ data
43
52
  end
44
53
 
45
54
  def deserialize_data(data)
46
- AuthProto::State::Session.new(
55
+ unless data['dpop_key'].is_a?(Hash)
56
+ raise ValidationError, "Session is missing its private DPoP key; authorize again"
57
+ end
58
+
59
+ session = AuthProto::State::Session.new(
47
60
  client_id: data['client_id'],
61
+ dpop_key: AuthProto::DPoP::KeySet.from_jwk(data.fetch('dpop_key')),
48
62
  scope: data['scope'],
49
63
  did: data['did'],
64
+ pds: data['pds'],
65
+ signing_key_id: data['signing_key_id'],
66
+ signing_key_thumbprint: data['signing_key_thumbprint'],
67
+ authorization_expires_at: data['authorization_expires_at'] && Time.iso8601(data['authorization_expires_at']),
50
68
  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']
60
- end
69
+ )
70
+
71
+ # Set readonly attributes
72
+ session.instance_variable_set(:@session_id, data['session_id'])
73
+ session.instance_variable_set(:@state_token, data['state_token'])
74
+ session.instance_variable_set(:@pkce_verifier, data['pkce_verifier'])
75
+ session.instance_variable_set(:@pkce_challenge, data['pkce_challenge'])
76
+
77
+ # Set tokens if present
78
+ session.tokens = deserialize_token_set(data['tokens']) if data['tokens']
79
+
80
+ session
61
81
  end
62
82
 
63
83
  def serialize_token_set(tokens)
@@ -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,21 +30,22 @@ 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
- token_type: obj.token_type,
36
35
  expires_at: obj.expires_at.utc.iso8601,
37
36
  scope: obj.scope,
38
37
  sub: obj.sub
39
38
  }
39
+
40
+ data[:refresh_token] = obj.refresh_token if obj.refresh_token
41
+ data
40
42
  end
41
43
 
42
44
  def deserialize_data(data)
43
45
  AuthProto::State::TokenSet.new(
44
46
  access_token: data['access_token'],
45
47
  refresh_token: data['refresh_token'],
46
- token_type: data['token_type'],
48
+ token_type: 'DPoP',
47
49
  expires_in: (Time.parse(data['expires_at']) - Time.now).to_i,
48
50
  scope: data['scope'],
49
51
  sub: data['sub']