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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 61754b5e7342299c331cabc76c9585ef1f7b1398d0eae4eed252f5d9a2a019bd
4
- data.tar.gz: 5879610764cb56945d3fc260ed0538f5cdaaabfaec4982af38408290a34a547f
3
+ metadata.gz: 3cb457c63a25d1d681d7b10e55ef9330f199a69dc4aec845198501654b847323
4
+ data.tar.gz: afa3e52767ec444f00f08a0f99386d6c9f0399a93a089b601ffddafd08538d3e
5
5
  SHA512:
6
- metadata.gz: fe5452fe5a70e70bb3c100b30656eb63fcca61dec4617ccec1413eff03e952156523f39f479096dc2fa23467ad7fa792639571ce5d46a9985049bbb7c0806e82
7
- data.tar.gz: 2c6fb2275d03bf3b812a731841fe2b7364d41b8799f5e937a4c4191d7da0b843d68bd5d67a941dea4f6d4b0590320cd757041f518a3c1416000888ca165583d5
6
+ metadata.gz: 68e8b5f15499e7e5310f80ae96af47ffe369eafb49513c48773b0e9a2bac8c4fb8a2b5b1f4064803052551d0897666ad9eebe27f7bc440f2255d20856ef6588a
7
+ data.tar.gz: 302b8dad6e2669ebb4225c4373e024c3228d7f0f3c95a94cdee8edaf057a0c6e01006772ce3d7d170f8d4147ec063b63daa6603f96869c790123fc5d8a0c7300
data/CHANGELOG.md CHANGED
@@ -1,4 +1,21 @@
1
- ## [0.3.0.beta3] - 2026-11-02
1
+ ## [0.3.0.beta4] – 2026-11-03
2
+
3
+ - at the end of authentication that started with a PDS URL, verify that the received DID belongs to that PDS
4
+ - revoke received tokens if after authentication the DID or PDS doesn't match the previously known value
5
+ - check if the known PDS matches before doing a token refresh
6
+ - fixed decryption code accepting encrypted data with truncated tags
7
+ - fixed token refresh failing if some originally requested scopes were not granted (e.g. email access)
8
+ - fixed token refresh losing the old refresh token if it wasn't actually replaced
9
+ - improved validation of token exchange & token refresh response, and client & resource/authorization server metadata
10
+ - added `#granted_scope`, `#has_limited_scope?` and `#can_be_revoked?` to `Session`
11
+ - added option to explicitly revoke access/refresh tokens on the server when deleting a session, with `delete_session(id, revoke: true)`
12
+ - require the `ATPROTO_MASTER_KEY` to be exactly 32 bytes long (or 44 Base64 characters)
13
+ - require https:// URLs in DPoP client and nonce manager (since resource servers / PDSes and authorization servers need to be on HTTPS)
14
+ - reject token responses with the OpenID `id_token` field
15
+ - when loading a session, verify that it has been created with the same `client_id`
16
+ - ignore the redirect URI's port when testing if the redirect URI passed for authentication for a localhost client is included on the metadata list (as the spec says)
17
+
18
+ ## [0.3.0.beta3] – 2026-11-02
2
19
 
3
20
  - session's state token is deleted on successfully completed authentication (i.e. `handle_callback`)
4
21
  - pending sessions (that haven't completed authentication) are stored with a TTL of 15 minutes by default, and expire after that; this can be changed through `pending_session_ttl` in the global configuration
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: ../..
3
3
  specs:
4
- authproto (0.3.0.beta1)
4
+ authproto (0.3.0.beta3)
5
5
  didkit (~> 0.5.0)
6
6
  jose (~> 1.2)
7
7
  jwt (~> 3.3)
@@ -16,7 +16,7 @@ The example implements a simple web application using Sinatra that:
16
16
  - Demonstrates secure session management with encryption
17
17
  - Shows how to make authenticated API calls to Bluesky
18
18
  - Provides examples of both development and production storage configurations
19
- - Supports running on localhost
19
+ - Supports running on localhost (but as a public client)
20
20
 
21
21
  ## Requirements
22
22
 
@@ -12,8 +12,8 @@ require 'faraday'
12
12
  require 'sinatra/base'
13
13
  require 'sinatra/reloader'
14
14
 
15
- session_secret = ENV.fetch("SESSION_SECRET") { SecureRandom.hex(32) }
16
- raise "SESSION_SECRET must be at least 64 characters long (got: #{session_secret})" unless session_secret.length >= 64
15
+ $session_secret = ENV.fetch("SESSION_SECRET") { SecureRandom.hex(32) }
16
+ raise "SESSION_SECRET must be at least 64 characters long (got: #{$session_secret})" if $session_secret.length < 64
17
17
 
18
18
  # Main app entry point
19
19
  class ExampleApp < Sinatra::Base
@@ -57,20 +57,37 @@ class ExampleApp < Sinatra::Base
57
57
  metadata = JSON.parse(File.read(metadata_path))
58
58
 
59
59
  client_id = metadata['client_id']
60
+ redirect_uri = metadata['redirect_uris'][0]
61
+
62
+ # Private client-authentication keys are kept outside public metadata.
63
+ keys_file = File.join(__dir__, "config", "keys.json")
64
+ signing_key = JSON.parse(File.read(keys_file))['keys'].first if File.exist?(keys_file)
60
65
 
61
66
  if client_id.chomp("/") == "http://localhost"
62
67
  scope = CGI.escape(metadata['scope'])
63
- redirect_uri = CGI.escape(metadata['redirect_uris'][0])
64
- client_id += "?scope=#{scope}&redirect_uri=#{redirect_uri}"
65
- end
68
+ redirect = CGI.escape(metadata['redirect_uris'][0])
69
+ client_id += "?scope=#{scope}&redirect_uri=#{redirect}"
70
+ metadata = nil
66
71
 
67
- # Private client-authentication keys are kept outside public metadata.
68
- signing_key = JSON.parse(File.read(File.join(__dir__, "config", "keys.json")))["keys"].first
72
+ if signing_key
73
+ warn "-" * 100
74
+ warn "Running the app on localhost as a public client - confidential clients require a production server."
75
+ warn "-" * 100
76
+
77
+ signing_key = nil
78
+ end
79
+ else
80
+ if !signing_key
81
+ warn "-" * 100
82
+ warn "Missing config/keys.json - running the app as a public client."
83
+ warn "-" * 100
84
+ end
85
+ end
69
86
 
70
87
  # Create OAuth client
71
88
  set :oauth_client, AuthProto::Client.new(
72
89
  client_id: client_id,
73
- redirect_uri: metadata['redirect_uris'][0],
90
+ redirect_uri: redirect_uri,
74
91
  metadata: metadata,
75
92
  signing_key: signing_key
76
93
  )
@@ -83,7 +100,7 @@ class ExampleApp < Sinatra::Base
83
100
  use Rack::Session::Cookie,
84
101
  key: "atproto.session",
85
102
  expire_after: 86_400, # 1 day in seconds
86
- secret: session_secret,
103
+ secret: $session_secret,
87
104
  secure: ENV.fetch("RACK_ENV", "development") == "production", # Only send over HTTPS
88
105
  httponly: true, # Not accessible via JavaScript
89
106
  same_site: :lax # CSRF protection
@@ -274,7 +291,7 @@ class ExampleApp < Sinatra::Base
274
291
  get "/signout" do
275
292
  if session[:oauth_session_id]
276
293
  # Clean up stored session
277
- settings.oauth_client.delete_session(session[:oauth_session_id])
294
+ settings.oauth_client.delete_session(session[:oauth_session_id], revoke: true)
278
295
  end
279
296
 
280
297
  session.clear
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: ../..
3
3
  specs:
4
- authproto (0.3.0.beta2)
4
+ authproto (0.3.0.beta3)
5
5
  didkit (~> 0.5.0)
6
6
  jose (~> 1.2)
7
7
  jwt (~> 3.3)
@@ -91,7 +91,7 @@ DEPENDENCIES
91
91
  sqlite3
92
92
 
93
93
  CHECKSUMS
94
- authproto (0.3.0.beta2)
94
+ authproto (0.3.0.beta3)
95
95
  base58 (0.2.3) sha256=fda5c5d3bda8b429ad0d1a5309c2d1e488ba46f0a2ab99a639890f26c61bf3be
96
96
  base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b
97
97
  bundler (4.0.23) sha256=407ba8a1d928f412847f819aa5f8b6aef7c59fb51feb517112af8a165487287b
@@ -2,7 +2,6 @@
2
2
 
3
3
  require 'didkit/did'
4
4
  require 'jose'
5
- require 'json'
6
5
  require 'uri'
7
6
 
8
7
  require_relative 'configuration'
@@ -18,7 +17,10 @@ require_relative 'par/request'
18
17
  require_relative 'state/session_manager'
19
18
  require_relative 'state/token_set'
20
19
  require_relative 'storage/key_builder'
20
+ require_relative 'token/identity'
21
21
  require_relative 'token/refresh'
22
+ require_relative 'token/response'
23
+ require_relative 'token/revocation'
22
24
 
23
25
  module AuthProto
24
26
 
@@ -28,6 +30,7 @@ module AuthProto
28
30
  #
29
31
 
30
32
  class Client
33
+ include Token::Identity
31
34
 
32
35
  # Error raised when authorization callback fails
33
36
  class CallbackError < Error; end
@@ -107,7 +110,7 @@ module AuthProto
107
110
  initialize_client_assertion(signing_key)
108
111
 
109
112
  signing_keys = @client_assertion ? { @signing_key_kid => @signing_key_thumbprint } : {}
110
- @session_manager = State::SessionManager.new(supported_signing_keys: signing_keys)
113
+ @session_manager = State::SessionManager.new(client_id: @client_id, supported_signing_keys: signing_keys)
111
114
 
112
115
  @dpop_client = DPoP::Client.new
113
116
  end
@@ -152,6 +155,7 @@ module AuthProto
152
155
  scope: scope,
153
156
  auth_server: authorization_server,
154
157
  did: did&.to_s,
158
+ pds: pds,
155
159
  signing_key_id: @signing_key_kid
156
160
  )
157
161
 
@@ -167,7 +171,7 @@ module AuthProto
167
171
  #
168
172
  # The result contains `:access_token` (String), `:token_type` (String, `DPoP`),
169
173
  # `:expires_in` (Integer seconds remaining), `:refresh_token` (String or nil),
170
- # and `:scope` (String).
174
+ # and `:scope` / `:granted_scope` (String, the granted permissions).
171
175
  # It also contains `:session_id` (String) and `:did` (String).
172
176
  #
173
177
  # Supply the session ID retained when starting authorization as `expected_session_id`.
@@ -182,7 +186,7 @@ module AuthProto
182
186
  #
183
187
  # @return [Hash{Symbol => String, Integer, nil}] tokens and authenticated session details
184
188
  # @raise [CallbackError] if the expected session ID is invalid, state is unknown, or session/issuer validation fails
185
- # @raise [TokenError] if token exchange or response validation fails
189
+ # @raise [TokenError] if token exchange or response validation fails; identity failures attempt token revocation
186
190
  # @raise [DPoP::Client::Error, PAR::ClientAssertion::Error] if proof/assertion generation fails
187
191
  # @raise [HTTPClient::HTTPError, HTTPClient::SSRFError] if token transport fails
188
192
  # @raise [State::SessionError] if token subject conflicts with the session DID
@@ -202,16 +206,7 @@ module AuthProto
202
206
  raise CallbackError, "Issuer mismatch" unless session.auth_server && session.auth_server.issuer == iss
203
207
 
204
208
  AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key("session", session.session_id), ttl: 30) do
205
- response = exchange_code(code: code, session: session)
206
-
207
- token_set = State::TokenSet.new(
208
- access_token: response['access_token'],
209
- token_type: response['token_type'],
210
- expires_in: response['expires_in'],
211
- refresh_token: response['refresh_token'],
212
- scope: response['scope'],
213
- sub: response['sub']
214
- )
209
+ token_set = exchange_code(code: code, session: session)
215
210
 
216
211
  session.tokens = token_set
217
212
  session_manager.complete_authorization(session)
@@ -224,7 +219,7 @@ module AuthProto
224
219
  #
225
220
  # The result contains `:access_token` (String), `:token_type` (String, `DPoP`),
226
221
  # `:expires_in` (Integer seconds remaining), `:refresh_token` (String or nil),
227
- # and `:scope` (String).
222
+ # and `:scope` / `:granted_scope` (String, the granted permissions).
228
223
  # It also contains `:session_id` (String) and `:did` (String).
229
224
  # This method does not refresh expired tokens.
230
225
  #
@@ -242,26 +237,26 @@ module AuthProto
242
237
  #
243
238
  # The result contains `:access_token` (String), `:token_type` (String, `DPoP`),
244
239
  # `:expires_in` (Integer seconds remaining), `:refresh_token` (String or nil),
245
- # and `:scope` (String).
240
+ # and `:scope` / `:granted_scope` (String, the granted permissions).
246
241
  # The result also contains `:session_id` (String) and `:did` (String). An expired access token can
247
242
  # still be refreshed when the stored session has a refresh token.
248
243
  #
249
244
  # @param session_id [String] session to refresh
250
245
  # @return [Hash{Symbol => String, Integer, nil}] replacement tokens and session identifiers
251
246
  # @raise [TokenError] if the session is missing or has no refresh token
252
- # @raise [Token::RefreshError] if token refresh fails or exhausts retries
247
+ # @raise [Token::RefreshError] if the current PDS differs, token refresh fails or retries are exhausted
253
248
  # @raise [DPoP::Client::Error] if a refresh response lacks a valid nonce
254
249
  # @raise [State::SessionError] if replacement tokens have a different subject
255
250
  # @raise [Storage::StorageError] if session storage or locking fails
256
251
  # @raise [Encryption::EncryptionError] if replacement tokens cannot be stored
257
252
  #
258
253
  def refresh_token(session_id)
259
- session = session_manager.get_session(session_id)
254
+ AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key('session', session_id), ttl: 30) do
255
+ session = session_manager.get_session(session_id)
260
256
 
261
- raise TokenError, "Invalid session" unless session
262
- raise TokenError, "Session not authorized" unless session.renewable?
257
+ raise TokenError, "Invalid session" unless session
258
+ raise TokenError, "Session not authorized" unless session.renewable?
263
259
 
264
- AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key("session", session.session_id), ttl: 30) do
265
260
  refresher = Token::Refresh.new(
266
261
  session: session,
267
262
  dpop_client: @dpop_client,
@@ -323,14 +318,47 @@ module AuthProto
323
318
  }
324
319
  end
325
320
 
326
- # Removes a stored session and its state-token lookup.
321
+ # Removes a stored session and its state-token lookup, optionally revoking its tokens first.
322
+ # Refresh-token revocation must succeed when a refresh token is present; access-token revocation
323
+ # is then best effort. Without a refresh token, access-token revocation must succeed.
324
+ # Required revocation failures leave the local session intact so the caller can retry or delete locally.
325
+ # A missing session is a no-op; pending sessions have no tokens to revoke.
326
+ # Servers without a revocation endpoint are skipped and the session is deleted locally.
327
327
  #
328
328
  # @param session_id [String] session identifier
329
+ # @param revoke [Boolean] revoke the refresh token, if present, and access token before deletion
329
330
  # @return [void]
331
+ # @raise [Token::Revocation::Error] if a required revocation request is rejected
332
+ # @raise [DPoP::Client::Error, HTTPClient::HTTPError] if revocation proof or transport handling fails
330
333
  # @raise [Storage::StorageError] if deletion or locking fails
331
334
  #
332
- def delete_session(session_id)
333
- session_manager.delete_session(session_id)
335
+ def delete_session(session_id, revoke: false)
336
+ AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key('session', session_id), ttl: 30) do
337
+ session = session_manager.get_session(session_id)
338
+ return unless session
339
+
340
+ if revoke && session.tokens && session.can_be_revoked?
341
+ revocation = Token::Revocation.new(
342
+ session: session,
343
+ dpop_client: @dpop_client,
344
+ client_metadata: @client_metadata,
345
+ client_assertion: @client_assertion
346
+ )
347
+
348
+ if session.tokens.refresh_token
349
+ revocation.revoke_token(session.tokens.refresh_token, :token_type => :refresh_token)
350
+ refresh_revoked = true
351
+ end
352
+
353
+ begin
354
+ revocation.revoke_token(session.tokens.access_token, :token_type => :access_token)
355
+ rescue StandardError
356
+ raise unless refresh_revoked
357
+ end
358
+ end
359
+
360
+ session_manager.delete_session(session_id)
361
+ end
334
362
  end
335
363
 
336
364
  # Invokes the session manager's expiry cleanup hook.
@@ -355,9 +383,35 @@ module AuthProto
355
383
  end
356
384
 
357
385
  def validate_redirect_uri
358
- unless @client_metadata.redirect_uris.include?(@redirect_uri)
359
- raise Error, "redirect_uri not found in client metadata"
386
+ return if @client_metadata.redirect_uris.include?(@redirect_uri)
387
+
388
+ # localhost development exception
389
+ if URI(@client_id).scheme == 'http'
390
+ components = loopback_redirect_components(@redirect_uri)
391
+
392
+ if components && @client_metadata.redirect_uris.any? { |uri| loopback_redirect_components(uri) == components }
393
+ return
394
+ end
360
395
  end
396
+
397
+ raise Error, "redirect_uri not found in client metadata"
398
+ end
399
+
400
+ def loopback_redirect_components(url)
401
+ uri = URI(url)
402
+
403
+ unless uri.is_a?(URI::HTTP) && uri.scheme == 'http' && ['127.0.0.1', '[::1]'].include?(uri.host) &&
404
+ !uri.userinfo && !uri.fragment && uri.port.between?(1, 65_535)
405
+ return nil
406
+ end
407
+
408
+ # compare the localhost URLs while ignoring the port
409
+ # "redirect_uri (string, multiple query parameters allowed, optional):
410
+ # allows declaring a local redirect/callback URL, with path component matched but port numbers ignored"
411
+
412
+ URI.split(url).tap { |components| components[3] = nil }
413
+ rescue URI::InvalidURIError
414
+ nil
361
415
  end
362
416
 
363
417
  def initialize_client_assertion(key)
@@ -454,15 +508,12 @@ module AuthProto
454
508
 
455
509
  raise TokenError, "Token request failed: #{response[:status]}" unless response[:status] == 200
456
510
 
457
- begin
458
- data = JSON.parse(response[:body])
459
- rescue JSON::ParserError => e
460
- raise TokenError, "Invalid token response: #{e.message}"
461
- end
462
-
463
- validate_token_response(data, session)
511
+ tokens = Token::Response.parse(response)
512
+ validate_token_identity(tokens, session)
464
513
 
465
- data
514
+ tokens
515
+ rescue Token::Response::Error => e
516
+ raise TokenError, e.message
466
517
  end
467
518
 
468
519
  def make_token_request(code, session)
@@ -497,19 +548,35 @@ module AuthProto
497
548
  )
498
549
  end
499
550
 
500
- def validate_token_response(response, session)
501
- ['access_token', 'token_type', 'expires_in', 'scope', 'sub'].each do |field|
502
- raise TokenError, "Missing #{field} in token response" unless response[field]
551
+ def validate_token_identity(tokens, session)
552
+ if session.did
553
+ raise Token::IdentityMismatchError, "Subject mismatch in token response" if session.did != tokens.sub
554
+ else
555
+ validate_subject_pds(tokens.sub, session)
503
556
  end
557
+ rescue Token::IdentityMismatchError => e
558
+ revoke_rejected_refresh_token(tokens.refresh_token, session) if tokens.refresh_token
559
+ raise TokenError, e.message
560
+ rescue Token::IdentityLookupError => e
561
+ raise TokenError, "#{e.message}; start authorization again"
562
+ rescue Token::IdentityError => e
563
+ raise TokenError, e.message
564
+ end
504
565
 
505
- unless response['token_type'].is_a?(String) && response['token_type'].casecmp?('DPoP')
506
- raise TokenError, "Invalid token_type: #{response['token_type']}"
507
- end
566
+ def revoke_rejected_refresh_token(token, session)
567
+ return unless session.can_be_revoked?
508
568
 
509
- raise TokenError, "Missing atproto scope in token response" unless response['scope'].split.include?('atproto')
569
+ revocation = Token::Revocation.new(
570
+ session: session,
571
+ dpop_client: @dpop_client,
572
+ client_metadata: @client_metadata,
573
+ client_assertion: @client_assertion
574
+ )
510
575
 
511
- # If we have a pre-resolved DID, verify that it matches
512
- raise TokenError, "Subject mismatch in token response" if session.did && session.did != response['sub']
576
+ revocation.revoke_token(token, token_type: 'refresh_token')
577
+ rescue StandardError
578
+ # Cleanup failures must not replace the original identity error.
579
+ nil
513
580
  end
514
581
  end
515
582
  end
@@ -51,7 +51,7 @@ module AuthProto
51
51
  #
52
52
  # @param session [State::Session] session whose DPoP key signs the request
53
53
  # @param method [String] HTTP method, converted to uppercase
54
- # @param uri [String] absolute HTTP(S) request URL; query and fragment are omitted from the signed `htu`
54
+ # @param uri [String] absolute HTTPS request URL; query and fragment are omitted from the signed `htu`
55
55
  # @param access_token [String, nil] token to bind with an `ath` claim
56
56
  # @return [JOSE::SignedBinary] compact signed DPoP JWT
57
57
  # @raise [Error] if URI parsing, nonce lookup or signing fails
@@ -40,7 +40,7 @@ module AuthProto
40
40
  #
41
41
  # @param nonce [String] server-provided nonce using RFC 9449's `1*NQCHAR` syntax
42
42
  # @param session_id [String] nonempty OAuth session identifier
43
- # @param server_url [String] HTTPS URL, or HTTP URL with host `localhost`
43
+ # @param server_url [String] HTTPS server URL
44
44
  # @return [void]
45
45
  # @raise [NonceError] if inputs are invalid or storage reports failure
46
46
  # @raise [Storage::StorageError] if backend validation or storage fails
@@ -62,7 +62,7 @@ module AuthProto
62
62
  # Retrieves the current nonce for a session and URL's origin.
63
63
  #
64
64
  # @param session_id [String] nonempty OAuth session identifier
65
- # @param server_url [String] HTTPS URL, or HTTP URL with host `localhost`
65
+ # @param server_url [String] HTTPS server URL
66
66
  # @return [String, nil] stored nonce, or `nil` when missing/expired according to storage TTL
67
67
  # @raise [NonceError] if the session ID or URL is invalid, or serialized data cannot be read
68
68
  # @raise [Storage::StorageError] if storage retrieval fails
@@ -87,7 +87,7 @@ module AuthProto
87
87
  # Removes the stored nonce for a session and URL's origin.
88
88
  #
89
89
  # @param session_id [String] nonempty OAuth session identifier
90
- # @param server_url [String] HTTPS URL, or HTTP URL with host `localhost`
90
+ # @param server_url [String] HTTPS server URL
91
91
  # @return [Boolean] backend deletion status
92
92
  # @raise [NonceError] if the session ID or URL is invalid
93
93
  # @raise [Storage::StorageError] if deletion fails
@@ -111,8 +111,7 @@ module AuthProto
111
111
  def normalize_server_url(url)
112
112
  uri = URI(url)
113
113
  port = uri.port
114
- port = nil if (uri.scheme == 'https' && port == 443) ||
115
- (uri.scheme == 'http' && port == 80)
114
+ port = nil if uri.scheme == 'https' && port == 443
116
115
 
117
116
  origin = "#{uri.scheme}://#{uri.host}"
118
117
  origin = "#{origin}:#{port}" if port
@@ -132,10 +131,7 @@ module AuthProto
132
131
 
133
132
  uri = ValidatedURI.new(server_url)
134
133
 
135
- # Allow HTTP for localhost only
136
- if uri.host != 'localhost' && uri.scheme != 'https'
137
- raise NonceError, "server_url must be HTTPS (except for localhost)"
138
- end
134
+ raise NonceError, "server_url must be HTTPS" unless uri.scheme == 'https'
139
135
  rescue URI::InvalidURIError => e
140
136
  raise NonceError, "invalid server_url: #{e.message}"
141
137
  end
@@ -32,7 +32,7 @@ module AuthProto
32
32
  #
33
33
  # @param key_set [KeySet] key belonging to the session making this request
34
34
  # @param method [String] nonempty HTTP method, converted to uppercase
35
- # @param uri [String] absolute HTTP(S) request URL
35
+ # @param uri [String] absolute HTTPS request URL
36
36
  # @param nonce [String, nil] server-provided nonce to include
37
37
  # @param access_token [String, nil] access token to bind to the proof
38
38
  # @return [JOSE::SignedBinary] compact signed DPoP JWT
@@ -62,7 +62,8 @@ module AuthProto
62
62
  raise ProofError, "method is required" if method.nil? || method.empty?
63
63
  raise ProofError, "uri is required" if uri.nil? || uri.empty?
64
64
 
65
- ValidatedURI.new(uri)
65
+ parsed_uri = ValidatedURI.new(uri)
66
+ raise ProofError, "uri must use HTTPS" unless parsed_uri.scheme == 'https'
66
67
  rescue URI::InvalidURIError => e
67
68
  raise ProofError, "invalid uri: #{e.message}"
68
69
  end
@@ -96,7 +97,7 @@ module AuthProto
96
97
  uri = URI(uri)
97
98
 
98
99
  # Remove default ports
99
- uri.port = nil if (uri.scheme == 'https' && uri.port == 443) || (uri.scheme == 'http' && uri.port == 80)
100
+ uri.port = nil if uri.scheme == 'https' && uri.port == 443
100
101
 
101
102
  uri.query = nil
102
103
  uri.fragment = nil
@@ -17,7 +17,7 @@ module AuthProto
17
17
  # Base class for encryption and key-configuration failures.
18
18
  class Error < AuthProto::Error; end
19
19
 
20
- # Raised when a required key derivation context is missing.
20
+ # Raised when the master key length is invalid or a required key derivation context is missing.
21
21
  class ConfigurationError < Error; end
22
22
 
23
23
  # Raised when plaintext inputs are invalid or encryption fails.
@@ -26,6 +26,18 @@ module AuthProto
26
26
  # Raised when an encrypted envelope cannot be decoded, authenticated or decrypted.
27
27
  class DecryptionError < Error; end
28
28
 
29
+ # OpenSSL cipher name used for authenticated encryption.
30
+ # @return [String]
31
+ CIPHER = "aes-256-gcm"
32
+
33
+ # Version stored in encrypted field envelopes.
34
+ # @return [Integer]
35
+ VERSION = 1
36
+
37
+ # Required length of the decoded master key in bytes.
38
+ # @return [Integer]
39
+ MASTER_KEY_BYTES = 32
40
+
29
41
  #
30
42
  # HKDF implementation based on RFC 5869
31
43
  #
@@ -70,16 +82,9 @@ module AuthProto
70
82
 
71
83
  class Service
72
84
 
73
- # OpenSSL cipher name used for authenticated encryption.
74
- # @return [String]
75
- CIPHER = "aes-256-gcm"
76
-
77
- # Version stored in encrypted field envelopes.
78
- # @return [Integer]
79
- VERSION = 1
80
-
81
85
  # Creates an encryption service backed by {KeyProvider}.
82
86
  # @raise [ArgumentError] if the configured master key is not valid Base64
87
+ # @raise [ConfigurationError] if the configured master key does not decode to exactly 32 bytes
83
88
  #
84
89
  def initialize
85
90
  @key_provider = KeyProvider.new
@@ -133,6 +138,8 @@ module AuthProto
133
138
  data = Base64.strict_decode64(encrypted[:data])
134
139
  auth_tag = Base64.strict_decode64(encrypted[:tag])
135
140
 
141
+ raise DecryptionError, "Authentication tag must be 16 bytes" unless auth_tag.bytesize == 16
142
+
136
143
  cipher = OpenSSL::Cipher.new(CIPHER)
137
144
  cipher.decrypt
138
145
  cipher.key = @key_provider.key_for_context(context)
@@ -195,18 +202,19 @@ module AuthProto
195
202
  #
196
203
  def self.ephemeral_master_key
197
204
  EPHEMERAL_KEY_MUTEX.synchronize do
198
- @ephemeral_master_key ||= SecureRandom.random_bytes(32)
205
+ @ephemeral_master_key ||= SecureRandom.random_bytes(MASTER_KEY_BYTES)
199
206
  end
200
207
  end
201
208
 
202
209
  # Loads the master key from `ATPROTO_MASTER_KEY` or uses the process fallback.
203
210
  #
204
- # Set the environment variable to a Base64-encoded master secret, typically
211
+ # Set the environment variable to a Base64-encoded master secret containing exactly
205
212
  # 32 random bytes. Context-specific AES-256 keys are derived from that secret.
206
213
  # Without it, a warning is emitted and {KeyProvider.ephemeral_master_key} is used;
207
214
  # data encrypted with that fallback cannot be recovered after a restart.
208
215
  #
209
216
  # @raise [ArgumentError] if `ATPROTO_MASTER_KEY` is not valid Base64
217
+ # @raise [ConfigurationError] if `ATPROTO_MASTER_KEY` does not decode to exactly 32 bytes
210
218
  #
211
219
  def initialize
212
220
  @master_key = load_master_key
@@ -235,7 +243,16 @@ module AuthProto
235
243
  def load_master_key
236
244
  # Try environment variable first
237
245
  key = ENV.fetch("ATPROTO_MASTER_KEY", nil)
238
- return Base64.strict_decode64(key) if key
246
+
247
+ if key
248
+ decoded = Base64.strict_decode64(key)
249
+
250
+ unless decoded.bytesize == MASTER_KEY_BYTES
251
+ raise ConfigurationError, "ATPROTO_MASTER_KEY must decode to exactly #{MASTER_KEY_BYTES} bytes"
252
+ end
253
+
254
+ return decoded
255
+ end
239
256
 
240
257
  # Generate and store a random key if not configured
241
258
  warn "WARNING: Using randomly generated encryption key - tokens will not persist across restarts"
@@ -23,10 +23,14 @@ module AuthProto
23
23
  FORBIDDEN_IP_RANGES = [
24
24
  IPAddr.new("0.0.0.0/8"), # Current network
25
25
  IPAddr.new("10.0.0.0/8"), # Private network
26
+ IPAddr.new('100.64.0.0/10'), # Shared address space (CGNAT)
26
27
  IPAddr.new("127.0.0.0/8"), # Loopback
27
28
  IPAddr.new("169.254.0.0/16"), # Link-local
28
29
  IPAddr.new("172.16.0.0/12"), # Private network
29
30
  IPAddr.new("192.168.0.0/16"), # Private network
31
+ IPAddr.new('198.18.0.0/15'), # Benchmarking
32
+ IPAddr.new('224.0.0.0/4'), # Multicast
33
+ IPAddr.new('240.0.0.0/4'), # Reserved, including limited broadcast
30
34
  IPAddr.new("::/128"), # Unspecified IPv6 address
31
35
  IPAddr.new("::1/128"), # IPv6 loopback
32
36
  IPAddr.new("fc00::/7"), # Unique local address
@@ -224,6 +228,8 @@ module AuthProto
224
228
  )
225
229
  rescue Net::OpenTimeout, Net::ReadTimeout => e
226
230
  raise HTTPError.new("Request timeout: #{e.message}", nil)
231
+ rescue AuthProto::Error
232
+ raise
227
233
  rescue StandardError => e
228
234
  raise HTTPError.new("Request failed: #{e.message}", nil)
229
235
  end
@@ -239,6 +245,8 @@ module AuthProto
239
245
  http.request(request)
240
246
  rescue Net::OpenTimeout, Net::ReadTimeout => e
241
247
  raise HTTPError.new("Request timeout: #{e.message}", nil)
248
+ rescue AuthProto::Error
249
+ raise
242
250
  rescue StandardError => e
243
251
  raise HTTPError.new("Request failed: #{e.message}", nil)
244
252
  end
@@ -286,16 +294,9 @@ module AuthProto
286
294
  end
287
295
 
288
296
  def validate_response(response)
289
- # check_success_status(response)
290
297
  check_content_length(response)
291
298
  end
292
299
 
293
- def check_success_status(response)
294
- return if response.is_a?(Net::HTTPSuccess)
295
-
296
- raise HTTPError.new("HTTP request failed: #{response.code} #{response.message}", response)
297
- end
298
-
299
300
  def check_content_length(response)
300
301
  content_length = response["content-length"]&.to_i || response.body&.bytesize || 0
301
302
  return unless content_length > MAX_RESPONSE_SIZE