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,8 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'jose'
3
4
  require 'jwt'
4
5
  require 'securerandom'
5
6
 
7
+ require_relative '../configuration'
6
8
  require_relative '../errors'
7
9
 
8
10
  module AuthProto
@@ -19,51 +21,123 @@ module AuthProto
19
21
  # Raised when client assertion key import or JWT signing fails.
20
22
  class Error < AuthProto::Error; end
21
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]
30
+ attr_reader :signing_key
31
+
22
32
  # Creates an ES256 client assertion signer.
23
33
  #
24
34
  # @param client_id [String] client ID used in `iss` and `sub`
25
- # @param signing_key [JOSE::JWK] private EC P-256 signing key, including its `kid`
35
+ # @param signing_key [Hash, JOSE::JWK] private EC P-256 signing key, including its `kid`
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
26
39
  #
27
40
  def initialize(client_id:, signing_key:)
28
- @client_id = client_id
29
- @signing_key = signing_key
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
46
+ @signing_key = validate_signing_key(signing_key)
47
+ rescue ClientAssertion::Error
48
+ raise
49
+ rescue StandardError => e
50
+ raise Error, "Invalid signing_key: #{e.message}"
30
51
  end
31
52
 
32
- # Signs a short-lived client authentication JWT with ES256.
53
+ # Signs a fresh, short-lived client authentication JWT with the cached ES256 key.
33
54
  #
34
55
  # Includes `iss`, `sub`, `aud`, a unique `jti`, and `iat`/`exp` times.
35
56
  #
36
57
  # @param audience [String] authorization server issuer URL used as the assertion audience
37
- # @param lifetime [Integer] validity in seconds; defaults to five minutes
58
+ # @param lifetime [Integer] positive validity in seconds; defaults to {Configuration#client_assertion_lifetime}
38
59
  # @return [String] compact signed client assertion JWT
39
- # @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
40
61
  #
41
- 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
+
42
71
  now = Time.now.to_i
43
72
 
44
73
  payload = {
45
- # Required claims
46
- iss: @client_id, # Issuer is client_id
47
- sub: @client_id, # Subject is client_id
48
- aud: audience, # Audience is the authorization server issuer
49
- jti: SecureRandom.uuid, # Unique identifier
50
- exp: now + lifetime, # Expiration time
51
- iat: now # Issued at time
74
+ iss: @client_id, # issuer
75
+ sub: @client_id, # subject
76
+ aud: audience, # audience is the authorization server issuer
77
+ jti: SecureRandom.uuid, # token identifier
78
+ exp: now + lifetime, # expiration time
79
+ iat: now # issued at time
52
80
  }
53
81
 
54
- # Header specifying ES256 algorithm for signing
55
82
  header = {
56
- alg: "ES256",
57
- typ: "JWT",
58
- kid: @signing_key.fields["kid"]
83
+ alg: ALGORITHM,
84
+ typ: 'JWT',
85
+ kid: @signing_key.fields['kid']
59
86
  }
60
87
 
61
- # Sign and return the JWT
62
- key = JWT::JWK.import(@signing_key.to_map.to_h)
63
- JWT.encode(payload, key, "ES256", header)
88
+ JWT.encode(payload, @jwt_signing_key, ALGORITHM, header)
64
89
  rescue JWT::Error, ArgumentError => e
65
90
  raise Error, "Failed to generate client assertion: #{e.message}"
66
91
  end
92
+
93
+
94
+ private
95
+
96
+ def validate_signing_key(signing_key)
97
+ data = signing_key.is_a?(JOSE::JWK) ? signing_key.to_map.to_h : signing_key
98
+
99
+ raise Error, "signing_key must be a hash or a JOSE::JWK" unless data.is_a?(Hash)
100
+ raise Error, "signing_key must be active" if data['revoked']
101
+
102
+ unless data['kty'] == 'EC' && data['crv'] == 'P-256'
103
+ raise Error, "signing_key must be a EC P-256 JWK"
104
+ end
105
+
106
+ unless data['d'].is_a?(String) && !data['d'].empty?
107
+ raise Error, "signing_key must be a private key ('d' field must not be empty)"
108
+ end
109
+
110
+ %w[kid x y].each do |field|
111
+ unless data[field].is_a?(String) && !data[field].empty?
112
+ raise Error, "signing_key '#{field}' field must not be empty"
113
+ end
114
+ end
115
+
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
129
+ end
130
+
131
+ signing_key = JOSE::JWK.from_map(data)
132
+
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
138
+
139
+ signing_key
140
+ end
67
141
  end
68
142
  end
69
143
  end
@@ -1,116 +1,71 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'cgi'
3
+ require 'uri'
4
4
 
5
5
  require_relative '../par'
6
+ require_relative 'client_assertion'
6
7
 
7
8
  module AuthProto
8
9
  module PAR
9
10
 
10
11
  #
11
- # Represents a pushed authorization request
12
+ # Represents a pushed authorization request.
12
13
  #
13
14
 
14
15
  class Request
15
16
 
16
17
  #
17
- # Configuration for request parameters
18
+ # Shared set of fields between {Request} (a read-only, validated request) and {Configuration} (a draft request
19
+ # with writable fields configured in the block passed to {Request.build}).
18
20
  #
19
21
 
20
- class Configuration
22
+ module Fields
21
23
 
22
24
  # OAuth client identifier.
23
- # @return [String, nil]
24
- attr_accessor :client_id
25
+ # @return [String]
26
+ attr_reader :client_id
25
27
 
26
28
  # Registered OAuth callback URI.
27
- # @return [String, nil]
28
- attr_accessor :redirect_uri
29
+ # @return [String]
30
+ attr_reader :redirect_uri
29
31
 
30
32
  # S256 PKCE challenge.
31
- # @return [String, nil]
32
- attr_accessor :code_challenge
33
-
34
- # PKCE method; must be `S256`.
35
- # @return [String, nil]
36
- attr_accessor :code_challenge_method
33
+ # @return [String]
34
+ attr_reader :code_challenge
37
35
 
38
36
  # Random state token to validate the callback.
39
- # @return [String, nil]
40
- attr_accessor :state
37
+ # @return [String]
38
+ attr_reader :state
41
39
 
42
40
  # Space-separated scopes including `atproto`.
43
- # @return [String, nil]
44
- attr_accessor :scope
41
+ # @return [String]
42
+ attr_reader :scope
45
43
 
46
- # Account handle to prefill at the authorization server.
44
+ # Account handle or DID to prefill at the authorization server.
47
45
  # @return [String, nil]
48
- attr_accessor :login_hint
46
+ attr_reader :login_hint
49
47
 
50
48
  # Optional authorization nonce parameter.
51
49
  # @return [String, nil]
52
- attr_accessor :nonce
53
-
54
- # Optional proof value retained on the request; {Client#submit} generates its own HTTP proof.
55
- # @return [String, nil]
56
- attr_accessor :dpop_proof
57
-
58
- # JWT bearer assertion type for confidential clients.
59
- # @return [String, nil]
60
- attr_accessor :client_assertion_type
50
+ attr_reader :nonce
61
51
 
62
- # Signed client authentication JWT for confidential clients.
63
- # @return [String, nil]
64
- attr_accessor :client_assertion
52
+ # Client authentication signer; a fresh JWT is generated for each form encoding.
53
+ # @return [ClientAssertion, nil]
54
+ attr_reader :client_assertion
65
55
  end
66
56
 
67
- # OAuth response type; always `code`.
68
- # @return [String]
69
- attr_reader :response_type
70
-
71
- # OAuth client identifier.
72
- # @return [String]
73
- attr_reader :client_id
74
-
75
- # Registered OAuth callback URI.
76
- # @return [String]
77
- attr_reader :redirect_uri
78
-
79
- # S256 PKCE challenge.
80
- # @return [String]
81
- attr_reader :code_challenge
82
-
83
- # PKCE method; must be `S256`.
84
- # @return [String]
85
- attr_reader :code_challenge_method
86
-
87
- # Random state token to validate the callback.
88
- # @return [String]
89
- attr_reader :state
90
-
91
- # Space-separated scopes including `atproto`.
92
- # @return [String]
93
- attr_reader :scope
94
-
95
- # Account handle to prefill at the authorization server.
96
- # @return [String, nil]
97
- attr_reader :login_hint
57
+ #
58
+ # A draft PAR request with writable fields, configured inside the block passed to {Request.build}.
59
+ #
98
60
 
99
- # Optional authorization nonce parameter.
100
- # @return [String, nil]
101
- attr_reader :nonce
61
+ class Configuration
62
+ include Fields
102
63
 
103
- # Optional proof value retained on the request; {Client#submit} generates its own HTTP proof.
104
- # @return [String, nil]
105
- attr_reader :dpop_proof
64
+ send(:attr_writer, *Fields.instance_methods(false))
65
+ end
106
66
 
107
- # JWT bearer assertion type for confidential clients.
108
- # @return [String, nil]
109
- attr_reader :client_assertion_type
67
+ include Fields
110
68
 
111
- # Signed client authentication JWT for confidential clients.
112
- # @return [String, nil]
113
- attr_reader :client_assertion
114
69
 
115
70
  # Builds a validated PAR request by yielding a mutable parameter configuration.
116
71
  #
@@ -118,7 +73,7 @@ module AuthProto
118
73
  # @yieldparam config [Configuration] mutable request settings
119
74
  # @yieldreturn [Object] ignored
120
75
  # @return [Request] validated pushed authorization request
121
- # @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
122
77
  #
123
78
  def self.build
124
79
  config = Configuration.new
@@ -129,114 +84,73 @@ module AuthProto
129
84
  # Copies and validates a PAR parameter configuration.
130
85
  #
131
86
  # @param config [Configuration] populated request settings
132
- # @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
133
88
  #
134
89
  def initialize(config)
135
- # Required parameters
136
- @response_type = "code" # Always "code" for AT Protocol OAuth
137
- @client_id = config.client_id
138
- @redirect_uri = config.redirect_uri
139
- @code_challenge = config.code_challenge
140
- @code_challenge_method = config.code_challenge_method
141
- @state = config.state
142
- @scope = config.scope
143
-
144
- # Optional parameters
145
- @login_hint = config.login_hint
146
- @nonce = config.nonce
147
- @dpop_proof = config.dpop_proof
148
-
149
- # Client authentication
150
- @client_assertion_type = config.client_assertion_type
151
- @client_assertion = config.client_assertion
90
+ Fields.instance_methods(false).each do |field|
91
+ self.instance_variable_set("@#{field}", config.send(field))
92
+ end
152
93
 
153
94
  validate_request
154
95
  end
155
96
 
156
- # Converts request to form-encoded parameters
97
+ # Converts request to form-encoded parameters, generating a fresh client assertion when configured.
98
+ # @param audience [String, nil] authorization server issuer; required for confidential clients
157
99
  # @return [String] Form-encoded request body
158
- def to_form
159
- encode_params(build_params)
100
+ #
101
+ def to_form(audience: nil)
102
+ URI.encode_www_form(build_params(audience: audience))
160
103
  end
161
104
 
105
+
162
106
  private
163
107
 
164
- def build_params
108
+ def build_params(audience:)
165
109
  params = {
166
- "response_type" => response_type,
110
+ "response_type" => 'code',
167
111
  "client_id" => client_id,
168
112
  "redirect_uri" => redirect_uri,
169
113
  "code_challenge" => code_challenge,
170
- "code_challenge_method" => code_challenge_method,
114
+ "code_challenge_method" => PKCE::CHALLENGE_METHOD_S256,
171
115
  "state" => state,
172
116
  "scope" => scope
173
117
  }
174
118
 
175
- add_optional_params(params)
176
- add_client_auth_params(params)
177
- params
178
- end
119
+ params['login_hint'] = login_hint if login_hint
120
+ params['nonce'] = nonce if nonce
179
121
 
180
- def add_optional_params(params)
181
- params["login_hint"] = login_hint if login_hint
182
- params["nonce"] = nonce if nonce
183
- end
122
+ if client_assertion
123
+ unless audience.is_a?(String) && !audience.empty?
124
+ raise Error, "audience is required with client_assertion"
125
+ end
184
126
 
185
- def add_client_auth_params(params)
186
- return unless client_assertion
127
+ params['client_assertion_type'] = CLIENT_ASSERTION_TYPE
128
+ params['client_assertion'] = client_assertion.generate_jwt(audience: audience)
129
+ end
187
130
 
188
- params["client_assertion_type"] = CLIENT_ASSERTION_TYPE
189
- params["client_assertion"] = client_assertion
131
+ params
190
132
  end
191
133
 
192
134
  def validate_request
193
135
  validate_required_params
194
- validate_response_type
195
- validate_code_challenge_method
196
- validate_scope
197
136
  validate_client_auth
137
+
138
+ raise Error, "atproto scope is required" unless scope.split.include?('atproto')
198
139
  end
199
140
 
200
141
  def validate_required_params
201
- %i[client_id redirect_uri code_challenge code_challenge_method state scope].each do |param|
142
+ %i[client_id redirect_uri code_challenge state scope].each do |param|
202
143
  value = send(param)
203
144
  raise Error, "#{param} is required" if value.nil? || value.empty?
204
145
  end
205
146
  end
206
147
 
207
- def validate_response_type
208
- return if response_type == "code"
209
-
210
- raise Error, "response_type must be 'code'"
211
- end
212
-
213
- def validate_code_challenge_method
214
- return if code_challenge_method == "S256"
215
-
216
- raise Error, "code_challenge_method must be 'S256'"
217
- end
218
-
219
- def validate_scope
220
- scopes = scope.split
221
- raise Error, "atproto scope is required" unless scopes.include?("atproto")
222
- end
223
-
224
148
  def validate_client_auth
225
- # If either auth parameter is present, both must be present and valid
226
- has_assertion = !client_assertion.nil?
227
- has_type = !client_assertion_type.nil?
149
+ return if client_assertion.nil?
228
150
 
229
- return unless has_assertion || has_type
230
- unless client_assertion_type == CLIENT_ASSERTION_TYPE
231
- raise Error, "client_assertion_type must be #{CLIENT_ASSERTION_TYPE}"
151
+ unless client_assertion.is_a?(ClientAssertion)
152
+ raise Error, "client_assertion must be a PAR::ClientAssertion"
232
153
  end
233
-
234
- raise Error, "client_assertion required with client_assertion_type" if client_assertion.nil?
235
- raise Error, "client_assertion_type required with client_assertion" if client_assertion_type.nil?
236
- end
237
-
238
- def encode_params(params)
239
- params.map { |k, v| "#{CGI.escape(k)}=#{CGI.escape(v.to_s)}" }.join("&")
240
154
  end
241
155
  end
242
156
  end
@@ -22,21 +22,20 @@ module AuthProto
22
22
  # Creates and validates a PAR response.
23
23
  #
24
24
  # @param request_uri [String] nonempty request URI issued by the authorization server
25
- # @param expires_in [Integer, String] positive lifetime in seconds; converted with `to_i`
26
- # @raise [Error] if the URI is empty or expiry is not positive
25
+ # @param expires_in [Integer] positive lifetime in seconds
26
+ # @raise [Error] if the URI is not a nonempty string or expiry is not a positive integer
27
27
  #
28
28
  def initialize(request_uri:, expires_in:)
29
29
  @request_uri = request_uri
30
- @expires_in = expires_in.to_i
31
- validate_response
32
- end
33
-
30
+ @expires_in = expires_in
34
31
 
35
- private
32
+ unless @request_uri.is_a?(String) && !@request_uri.empty?
33
+ raise Error, "request_uri must be a nonempty string"
34
+ end
36
35
 
37
- def validate_response
38
- raise Error, "request_uri is required" if request_uri.nil? || request_uri.empty?
39
- raise Error, "expires_in must be positive" unless expires_in.positive?
36
+ unless @expires_in.is_a?(Integer) && @expires_in.positive?
37
+ raise Error, "expires_in must be a positive integer"
38
+ end
40
39
  end
41
40
  end
42
41
  end
data/lib/authproto/par.rb CHANGED
@@ -15,7 +15,7 @@ module AuthProto
15
15
  #
16
16
  # @example Basic PAR request
17
17
  # par = AuthProto::PAR::Client.new(
18
- # endpoint: "https://auth.example.com/par",
18
+ # authorization_server: authorization_server,
19
19
  # dpop_client: AuthProto::DPoP::Client.new
20
20
  # )
21
21
  #
@@ -23,14 +23,13 @@ module AuthProto
23
23
  # config.client_id = "https://app.example.com/oauth-client-metadata.json"
24
24
  # config.redirect_uri = "https://app.example.com/callback"
25
25
  # config.code_challenge = "abc123..."
26
- # config.code_challenge_method = "S256"
27
26
  # config.state = "xyz789..."
28
- # config.scope = "atproto"
27
+ # config.scope = 'atproto'
29
28
  # end
30
29
  #
31
- # response = par.submit(request)
32
- # auth_url = par.authorization_url(
33
- # authorize_endpoint: "https://auth.example.com/authorize",
30
+ # session = AuthProto::State::Session.new(client_id: client_id, scope: 'atproto')
31
+ # response = par.submit(request, session: session)
32
+ # auth_url = par.build_authorization_url(
34
33
  # request_uri: response.request_uri,
35
34
  # client_id: request.client_id
36
35
  # )
@@ -9,117 +9,40 @@ require_relative 'errors'
9
9
  module AuthProto
10
10
 
11
11
  #
12
- # Implementation of Proof Key for Code Exchange (PKCE) for OAuth 2.0 / AT Protocol
13
- # as specified in RFC 7636.
14
- #
15
- # This module provides functionality to:
16
- # - Generate cryptographically secure code verifiers
17
- # - Create SHA-256 code challenges from verifiers
18
- # - Verify challenge/verifier pairs
19
- #
20
- # Only the S256 challenge method is supported, as required by AT Protocol OAuth.
12
+ # Generates a matching PKCE verifier and S256 challenge for an OAuth authorization flow.
21
13
  #
22
14
 
23
- module PKCE
15
+ class PKCE
24
16
 
25
- # Error raised for PKCE-related failures
17
+ # Error raised when generating a verifier/challenge pair fails.
26
18
  class Error < AuthProto::Error; end
27
19
 
28
- # Minimum PKCE verifier length in characters.
29
- # @return [Integer]
30
- MIN_VERIFIER_LENGTH = 43
31
-
32
- # Maximum PKCE verifier length in characters.
33
- # @return [Integer]
34
- MAX_VERIFIER_LENGTH = 128
35
-
36
- # Allowed PKCE verifier characters from RFC 7636.
37
- # @return [Regexp]
38
- ALLOWED_VERIFIER_CHARS = /^[A-Za-z0-9\-\._~]+$/
39
-
40
- class << self
41
-
42
- # Generates a cryptographically secure random code verifier
43
- #
44
- # @param length [Integer] Length of verifier to generate
45
- # @return [String] The generated code verifier
46
- # @raise [Error] if length is invalid
47
- #
48
- def generate_verifier(length = MAX_VERIFIER_LENGTH)
49
- validate_verifier_length(length)
50
-
51
- # Generate random bytes and encode as URL-safe base64
52
- random_bytes = SecureRandom.random_bytes(length * 3 / 4)
53
- Base64.urlsafe_encode64(random_bytes, padding: false)[0...length]
54
- rescue StandardError => e
55
- raise Error, "Failed to generate verifier: #{e.message}"
56
- end
57
-
58
- # Creates a code challenge from a verifier using SHA-256
59
- #
60
- # @param verifier [String] The code verifier to create challenge from
61
- # @return [String] Base64URL-encoded SHA-256 hash of the verifier
62
- # @raise [Error] if verifier is invalid or hashing fails
63
- #
64
- def generate_challenge(verifier)
65
- validate_verifier(verifier)
66
-
67
- # Hash with SHA-256 and encode as URL-safe base64
68
- digest = OpenSSL::Digest::SHA256.digest(verifier)
69
- Base64.urlsafe_encode64(digest, padding: false)
70
- rescue StandardError => e
71
- raise Error, "Failed to generate challenge: #{e.message}"
72
- end
73
-
74
- # Verifies that a challenge matches a verifier
75
- #
76
- # @param challenge [String] The code challenge to verify
77
- # @param verifier [String] The code verifier to check against
78
- # @return [Boolean] true if challenge matches verifier
79
- # @raise [Error] if inputs are invalid
80
- #
81
- def verify(challenge, verifier)
82
- # Generate challenge from verifier and compare
83
- calculated = generate_challenge(verifier)
84
- secure_compare(calculated, challenge)
85
- rescue Error
86
- # Re-raise PKCE errors
87
- raise
88
- rescue StandardError => e
89
- raise Error, "Challenge verification failed: #{e.message}"
90
- end
91
-
92
-
93
- private
94
-
95
- def validate_verifier_length(length)
96
- return if length.is_a?(Integer) && length.between?(MIN_VERIFIER_LENGTH, MAX_VERIFIER_LENGTH)
97
-
98
- raise Error, "Verifier length must be between #{MIN_VERIFIER_LENGTH} and #{MAX_VERIFIER_LENGTH}"
99
- end
100
-
101
- def validate_verifier(verifier)
102
- raise Error, "Verifier cannot be nil" if verifier.nil?
103
- raise Error, "Verifier cannot be empty" if verifier.empty?
104
-
105
- length = verifier.length
106
- validate_verifier_length(length)
107
-
108
- return if verifier.match?(ALLOWED_VERIFIER_CHARS)
109
-
110
- raise Error, "Verifier contains invalid characters"
111
- end
112
-
113
- # Constant-time string comparison to prevent timing attacks
114
- def secure_compare(str1, str2)
115
- return false unless str1.bytesize == str2.bytesize
116
-
117
- left = str1.unpack("C*")
118
- right = str2.unpack("C*")
119
- result = 0
120
- left.zip(right) { |x, y| result |= x ^ y }
121
- result.zero?
122
- end
20
+ # Challenge method required by AT Protocol OAuth.
21
+ CHALLENGE_METHOD_S256 = 'S256'
22
+
23
+ # Random bytes providing 256 bits of entropy, encoded as a 43-character verifier without padding.
24
+ VERIFIER_BYTES = 32
25
+
26
+ # Cryptographically random, URL-safe code verifier.
27
+ # @return [String]
28
+ attr_reader :verifier
29
+
30
+ # Base64URL-encoded SHA-256 digest of the verifier, without padding.
31
+ # @return [String]
32
+ attr_reader :challenge
33
+
34
+ # Generates a verifier and its matching S256 challenge.
35
+ #
36
+ # Both strings are frozen so the pair cannot be changed after generation.
37
+ #
38
+ # @raise [Error] if random generation or hashing fails
39
+ #
40
+ def initialize
41
+ @verifier = SecureRandom.urlsafe_base64(VERIFIER_BYTES, false).freeze
42
+ digest = OpenSSL::Digest::SHA256.digest(@verifier)
43
+ @challenge = Base64.urlsafe_encode64(digest, padding: false).freeze
44
+ rescue StandardError => e
45
+ raise Error, "Failed to generate PKCE: #{e.message}"
123
46
  end
124
47
  end
125
48
  end