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
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'uri'
5
+
6
+ require_relative '../configuration'
7
+ require_relative '../errors'
8
+ require_relative '../http_client'
9
+ require_relative '../http_helpers'
10
+ require_relative '../metadata'
11
+ require_relative '../validated_uri'
12
+
13
+ module AuthProto
14
+ module Metadata
15
+
16
+ #
17
+ # This class represents a Resource Server (PDS) and is responsible for
18
+ # validating and managing its metadata. It ensures that the authorization
19
+ # server URLs provided are valid and compliant with expected standards.
20
+ # The class also includes functionality to fetch and parse metadata from a
21
+ # remote URL, raising specific errors for invalid or malformed metadata.
22
+ #
23
+
24
+ class ResourceServer
25
+ extend HTTPHelpers
26
+
27
+ # The single authorization server origin advertised by the resource server.
28
+ # @return [String]
29
+ attr_reader :authorization_server
30
+
31
+ # Validates resource server metadata and its single authorization server origin.
32
+ #
33
+ # @param metadata [Hash{String => Object}] discovery document containing `authorization_servers`
34
+ # @raise [InvalidAuthorizationServer] if the list is missing or does not contain one valid origin
35
+ # @raise [URI::InvalidURIError] if the authorization server URI cannot be parsed
36
+ #
37
+ def initialize(metadata)
38
+ @authorization_server = validate_authorization_servers(metadata["authorization_servers"])
39
+ end
40
+
41
+ # Fetches `/.well-known/oauth-protected-resource` using the configured transport.
42
+ # Requires HTTP 200 without redirects, a JSON object served as application/json,
43
+ # and a resource identifier that exactly matches the requested URL.
44
+ # URL scheme restrictions are enforced by the configured transport.
45
+ # The PDS URL must have no userinfo, path prefix, query or fragment.
46
+ #
47
+ # @param url [String] resource server/PDS base URL
48
+ # @return [ResourceServer] validated resource server metadata
49
+ # @raise [InvalidAuthorizationServer] if HTTP transport, JSON parsing or metadata validation fails
50
+ # @raise [HTTPClient::SSRFError] if the transport rejects the initial destination
51
+ # @raise [URI::InvalidURIError] if the PDS or authorization server URL cannot be parsed
52
+ #
53
+ def self.from_url(url)
54
+ validate_source_url(url)
55
+
56
+ response = fetch_metadata(url)
57
+ validate_response(response)
58
+
59
+ metadata = parse_metadata(response[:body])
60
+ validate_resource(metadata["resource"], url)
61
+
62
+ new(metadata)
63
+ end
64
+
65
+
66
+ private
67
+
68
+ def validate_authorization_servers(servers)
69
+ raise InvalidAuthorizationServer, "authorization_servers missing" if servers.nil?
70
+ raise InvalidAuthorizationServer, "authorization_servers is not an array" unless servers.is_a?(Array)
71
+ raise InvalidAuthorizationServer, "must have exactly one authorization server" unless servers.length == 1
72
+
73
+ uri = ValidatedURI.new(servers.first)
74
+
75
+ valid = (
76
+ uri.scheme == 'https' && (!uri.specified_port || uri.effective_port != 443) &&
77
+ uri.path.empty? && !uri.query && !uri.fragment && !uri.userinfo
78
+ )
79
+
80
+ raise InvalidAuthorizationServer, "invalid authorization server URL format for #{servers.first}" unless valid
81
+
82
+ servers.first
83
+ end
84
+
85
+ class << self
86
+ private
87
+
88
+ def validate_source_url(url)
89
+ uri = ValidatedURI.new(url)
90
+
91
+ unless uri.path.empty? && !uri.userinfo && !uri.query && !uri.fragment
92
+ raise InvalidAuthorizationServer,
93
+ "Resource server URL must be an HTTP(S) origin without userinfo, a path prefix, query or fragment"
94
+ end
95
+ rescue URI::InvalidURIError => e
96
+ raise InvalidAuthorizationServer, "Invalid resource server URL: #{e.message}"
97
+ end
98
+
99
+ def fetch_metadata(url)
100
+ metadata_url = URI.join(url, "/.well-known/oauth-protected-resource")
101
+
102
+ AuthProto.configuration.http_client.get(metadata_url.to_s)
103
+ rescue HTTPClient::HTTPError => e
104
+ raise InvalidAuthorizationServer, "Failed to fetch resource server metadata: #{e.message}"
105
+ end
106
+
107
+ def validate_response(response)
108
+ unless response[:status] == 200
109
+ raise InvalidAuthorizationServer, "Resource server metadata must return HTTP 200"
110
+ end
111
+
112
+ content_type = response_header(response, 'Content-Type', strip_parameters: true)
113
+
114
+ unless content_type.to_s.casecmp?("application/json")
115
+ raise InvalidAuthorizationServer, "Resource server metadata must use application/json"
116
+ end
117
+ end
118
+
119
+ def parse_metadata(body)
120
+ metadata = JSON.parse(body.to_s)
121
+
122
+ unless metadata.is_a?(Hash)
123
+ raise InvalidAuthorizationServer, "Resource server metadata must be a JSON object"
124
+ end
125
+
126
+ metadata
127
+ rescue JSON::ParserError => e
128
+ raise InvalidAuthorizationServer, "Invalid JSON in resource server metadata: #{e.message}"
129
+ end
130
+
131
+ def validate_resource(resource, url)
132
+ unless resource.is_a?(String) && resource == url
133
+ raise InvalidAuthorizationServer, "Resource server metadata resource must match the requested resource URL"
134
+ end
135
+ end
136
+ end
137
+ end
138
+ end
139
+ end
@@ -3,8 +3,8 @@
3
3
  module AuthProto
4
4
 
5
5
  #
6
- # Provides functionality for fetching and validating AT Protocol OAuth server metadata
7
- # from both Resource Servers (PDS instances) and Authorization Servers (PDS/entryway).
6
+ # Provides functionality for fetching and validating AT Protocol OAuth metadata
7
+ # for clients, Resource Servers (PDS instances), and Authorization Servers (PDS/entryway).
8
8
  #
9
9
  # The flow for resolving an account's authorization server is:
10
10
  # 1. Start with PDS URL
@@ -13,16 +13,16 @@ module AuthProto
13
13
  # 4. Fetch Authorization Server metadata from /.well-known/oauth-authorization-server
14
14
  #
15
15
  # @example Resolving authorization server from PDS URL
16
- # resource_server = AuthProto::ServerMetadata::ResourceServer.from_url("https://pds.example.com")
17
- # auth_server_url = resource_server.authorization_servers.first
18
- # auth_server = AuthProto::ServerMetadata::AuthorizationServer.from_issuer(auth_server_url)
16
+ # resource_server = AuthProto::Metadata::ResourceServer.from_url("https://pds.example.com")
17
+ # auth_server_url = resource_server.authorization_server
18
+ # auth_server = AuthProto::Metadata::AuthorizationServer.from_url(auth_server_url)
19
19
  #
20
20
  # The module includes three main classes:
21
21
  # - {ResourceServer} - Handles PDS metadata validation and authorization server discovery
22
22
  # - {AuthorizationServer} - Handles authorization server metadata validation
23
- # - {OriginURL} - Validates URLs conform to AT Protocol's "simple origin URL" requirements
23
+ # - {ClientMetadata} - Handles client metadata and registration requirements
24
24
  #
25
25
 
26
- module ServerMetadata
26
+ module Metadata
27
27
  end
28
28
  end
@@ -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.
@@ -40,14 +42,15 @@ class Minisky::OAuthClient
40
42
  # @param client_id [String] OAuth client metadata URL or localhost client ID
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
- # @param dpop_key [Hash{String => Object}, nil] existing private DPoP JWK, or `nil` to generate one
45
+ # @param signing_key [Hash, JOSE::JWK, nil] private ES256 key for confidential-client authentication
46
+ # @param session_id [String, nil] stored session ID to resume; `nil` starts without an attached session
44
47
  #
45
48
  # @raise [AuthProto::InvalidClientMetadata] if metadata is invalid or unavailable
46
49
  # @raise [AuthProto::Error] if OAuth client or DPoP initialization fails
47
50
  # @raise [AuthProto::HTTPClient::HTTPError, AuthProto::HTTPClient::SSRFError] if fetching metadata fails
48
51
  # @see AuthProto::Client#initialize
49
52
  #
50
- def initialize(host, client_id:, redirect_uri:, metadata: nil, dpop_key: nil, session_id: nil)
53
+ def initialize(host, client_id:, redirect_uri:, metadata: nil, signing_key: nil, session_id: nil)
51
54
  @host = host
52
55
  @session_id = session_id
53
56
 
@@ -58,7 +61,7 @@ class Minisky::OAuthClient
58
61
  client_id: client_id,
59
62
  redirect_uri: redirect_uri,
60
63
  metadata: metadata,
61
- dpop_key: dpop_key
64
+ signing_key: signing_key
62
65
  )
63
66
  end
64
67
 
@@ -72,8 +75,8 @@ class Minisky::OAuthClient
72
75
  #
73
76
  # @param options [Hash{Symbol => Object}] options forwarded to {AuthProto::Client#authorize}
74
77
  # @option options [String] :handle account handle, optionally prefixed with `@`
75
- # @option options [String] :pds_url PDS URL, as an alternative to `handle`
76
- # @option options [String] :scope ("atproto") requested scopes
78
+ # @option options [String] :pds PDS URL, as an alternative to `handle`
79
+ # @option options [String] :scope ('atproto') requested scopes
77
80
  #
78
81
  # @return [Hash{Symbol => String}] `:url` to open and pending `:session_id`
79
82
  # @raise [AuthProto::Error] if authorization, discovery, PAR or persistence fails
@@ -85,19 +88,22 @@ class Minisky::OAuthClient
85
88
 
86
89
  # Completes OAuth authorization and remembers the authenticated session ID.
87
90
  #
91
+ # @param expected_session_id [String] pending session ID retained in the initiating browser session or native context
88
92
  # @param options [Hash{Symbol => String}] callback parameters forwarded to {AuthProto::Client#handle_callback}
89
93
  # @option options [String] :code authorization code
90
94
  # @option options [String] :state callback state token
91
95
  # @option options [String] :iss authorization server issuer
92
96
  #
93
97
  # @return [Hash{Symbol => String, Integer, nil}] token and session details from the OAuth client
94
- # @raise [AuthProto::Client::CallbackError] if state or issuer validation fails
98
+ # @raise [AuthProto::Client::CallbackError] if expected session, state or issuer validation fails
95
99
  # @raise [AuthProto::Client::TokenError] if token exchange or validation fails
96
100
  # @raise [AuthProto::Error] if proofs, storage or serialization fail
97
101
  # @see AuthProto::Client#handle_callback
98
102
  #
99
- def handle_callback(**options)
100
- 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
101
107
  end
102
108
 
103
109
  # Sends an XRPC GET through Minisky, adding OAuth handling when authenticated.
@@ -115,7 +121,7 @@ class Minisky::OAuthClient
115
121
  # @raise [ArgumentError] if the method is invalid or `auth` is a truthy non-Boolean value
116
122
  # @raise [Minisky::AuthError] if no completed OAuth login or refresh capability is available
117
123
  # @raise [Minisky::BadResponse] if the final response has an error or redirect status
118
- # @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
119
125
  # @raise [AuthProto::Error] if OAuth refresh or token persistence fails
120
126
  # @raise [JSON::ParserError] if a JSON response cannot be parsed
121
127
  # @raise [Net::OpenTimeout, Net::ReadTimeout, IOError, SystemCallError] if HTTP transport fails
@@ -150,7 +156,7 @@ class Minisky::OAuthClient
150
156
  # @raise [ArgumentError] if the method is invalid or `auth` is a truthy non-Boolean value
151
157
  # @raise [Minisky::AuthError] if no completed OAuth login or refresh capability is available
152
158
  # @raise [Minisky::BadResponse] if the final response has an error or redirect status
153
- # @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
154
160
  # @raise [AuthProto::Error] if OAuth refresh or token persistence fails
155
161
  # @raise [JSON::ParserError] if a JSON response cannot be parsed
156
162
  # @raise [Net::OpenTimeout, Net::ReadTimeout, IOError, SystemCallError] if HTTP transport fails
@@ -194,6 +200,7 @@ class Minisky::OAuthClient
194
200
  # @raise [AuthProto::Client::TokenError] if the session cannot be refreshed
195
201
  # @raise [AuthProto::Token::RefreshError] if refresh fails
196
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
197
204
  #
198
205
  def perform_token_refresh
199
206
  oauth_client.refresh_token(session_id)
@@ -207,14 +214,17 @@ class Minisky::OAuthClient
207
214
  #
208
215
  def check_access
209
216
  session = oauth_client.session_manager.get_session(session_id) if session_id
210
- raise Minisky::AuthError, "Complete OAuth login before making authenticated requests" unless session&.tokens
211
-
212
- return :ok unless session.tokens.expired?
213
-
214
- raise Minisky::AuthError, "OAuth session cannot be refreshed; log in again" unless session.renewable?
215
217
 
216
- perform_token_refresh
217
- :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
218
228
  end
219
229
 
220
230
 
@@ -226,48 +236,38 @@ class Minisky::OAuthClient
226
236
  nonce_retries = 0
227
237
  refreshed = false
228
238
 
229
- proof_url = url.dup
230
- proof_url.query = nil
231
- proof_url.fragment = nil
232
-
233
239
  loop do
234
240
  # Fresh proof for every attempt; callers cannot override OAuth auth headers.
235
241
  request_headers = headers.reject { |k, v| %w[authorization dpop].include?(k.to_s.downcase) }
236
242
  request_headers.merge!(oauth_client.auth_headers(
237
- session_id: session_id, method: request_class::METHOD, url: proof_url.to_s
243
+ session_id: session_id, method: request_class::METHOD, url: url.to_s
238
244
  ))
239
245
 
240
246
  request = request_class.new(url, request_headers)
241
247
  request.body = body unless body.nil?
248
+
242
249
  response = make_request(request)
250
+ response_hash = { status: response.code.to_i, headers: response.each_header.to_h, body: response.body }
243
251
 
244
- nonce = response["DPoP-Nonce"]
245
- oauth_client.dpop_client.process_response(response.each_header.to_h, url.to_s) if nonce && !nonce.empty?
246
- error = authentication_error(response)
252
+ oauth_client.dpop_client.process_response(response_hash, server_url: url.to_s, session_id: session_id)
247
253
 
248
- if response.code.to_i == 401 && error == "use_dpop_nonce"
249
- unless nonce && !nonce.empty?
250
- raise AuthProto::DPoP::Client::Error, "DPoP nonce challenge (HTTP 401) is missing DPoP-Nonce"
251
- end
254
+ if oauth_client.dpop_client.has_nonce_error?(response_hash)
252
255
  return response if nonce_retries >= MAX_NONCE_RETRIES
253
-
254
256
  nonce_retries += 1
255
- elsif response.code.to_i == 401 && error == "invalid_token" && !refreshed
256
- perform_token_refresh
257
- refreshed = true
258
257
  else
259
- 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
260
266
  end
261
267
  end
262
268
  end
263
269
 
264
270
  def authentication_error(response)
265
- # Only interpret a single DPoP challenge. Leave other auth schemes and
266
- # ambiguous multi-challenge headers to Minisky's normal error handling.
267
- challenge = response["WWW-Authenticate"].to_s
268
- return unless challenge.match?(/\ADPoP\s/i)
269
- return if challenge.match?(/,\s*(?:Bearer|Basic|DPoP)\b/i)
270
-
271
- challenge[/\berror\s*=\s*"(use_dpop_nonce|invalid_token)"/i, 1]
271
+ authentication_challenge(response['WWW-Authenticate'], scheme: 'DPoP')&.fetch('error', nil)
272
272
  end
273
273
  end
@@ -1,10 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'cgi'
4
3
  require 'json'
5
4
  require 'uri'
6
5
 
7
6
  require_relative '../configuration'
7
+ require_relative '../http_helpers'
8
8
  require_relative '../par'
9
9
  require_relative 'response'
10
10
 
@@ -25,7 +25,7 @@ module AuthProto
25
25
  #
26
26
  # @example Basic PAR flow
27
27
  # client = AuthProto::PAR::Client.new(
28
- # endpoint: "https://auth.example.com/par",
28
+ # authorization_server: authorization_server,
29
29
  # dpop_client: AuthProto::DPoP::Client.new
30
30
  # )
31
31
  #
@@ -34,16 +34,15 @@ module AuthProto
34
34
  # config.client_id = "https://app.example.com/oauth-client-metadata.json"
35
35
  # config.redirect_uri = "https://app.example.com/callback"
36
36
  # config.code_challenge = "abc123..."
37
- # config.code_challenge_method = "S256"
38
37
  # config.state = "xyz789..."
39
- # config.scope = "atproto"
38
+ # config.scope = 'atproto'
40
39
  # end
41
40
  #
42
- # response = client.submit(request)
41
+ # session = AuthProto::State::Session.new(client_id: client_id, scope: 'atproto')
42
+ # response = client.submit(request, session: session)
43
43
  #
44
44
  # # Build authorization URL using response
45
- # auth_url = client.authorization_url(
46
- # authorize_endpoint: "https://auth.example.com/authorize",
45
+ # auth_url = client.build_authorization_url(
47
46
  # request_uri: response.request_uri,
48
47
  # client_id: request.client_id
49
48
  # )
@@ -51,8 +50,7 @@ module AuthProto
51
50
  # @example With client authentication (confidential clients)
52
51
  # request = AuthProto::PAR::Request.build do |config|
53
52
  # # ... basic parameters ...
54
- # config.client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
55
- # config.client_assertion = jwt_token
53
+ # config.client_assertion = AuthProto::PAR::ClientAssertion.new(client_id: client_id, signing_key: signing_key)
56
54
  # end
57
55
  #
58
56
  # All requests use HTTPS and include a fresh DPoP proof from the supplied
@@ -61,154 +59,99 @@ module AuthProto
61
59
  #
62
60
 
63
61
  class Client
62
+ include HTTPHelpers
63
+
64
+ # Authorization server supplying endpoints and the client assertion audience.
65
+ # @return [Metadata::AuthorizationServer]
66
+ attr_reader :authorization_server
64
67
 
65
68
  # HTTPS pushed authorization request endpoint.
66
69
  # @return [String]
67
- attr_reader :endpoint
70
+ attr_reader :par_endpoint
68
71
 
69
72
  # DPoP client used to sign requests.
70
73
  # @return [DPoP::Client]
71
74
  attr_reader :dpop_client
72
75
 
73
- # Nonce manager belonging to the DPoP client.
74
- # @return [DPoP::NonceManager]
75
- attr_reader :nonce_manager
76
-
77
76
  # Creates a PAR transport using the global HTTP client and supplied DPoP client.
78
77
  #
79
- # @param endpoint [String] HTTPS PAR endpoint
78
+ # @param authorization_server [Metadata::AuthorizationServer] discovered authorization server metadata
80
79
  # @param dpop_client [DPoP::Client] proof generator and nonce tracker
81
- # @raise [Error] if the endpoint is malformed or does not use HTTPS
82
80
  #
83
- def initialize(endpoint:, dpop_client:)
84
- @endpoint = endpoint
81
+ def initialize(authorization_server:, dpop_client:)
82
+ @authorization_server = authorization_server
83
+ @par_endpoint = authorization_server.pushed_authorization_request_endpoint
85
84
  @dpop_client = dpop_client
86
- @nonce_manager = dpop_client.nonce_manager
87
- validate_endpoint
88
85
  end
89
86
 
90
87
  # Submits a PAR request, handling DPoP nonce requirements
91
88
  #
92
89
  # @param request [Request] The request to submit
90
+ # @param session [State::Session] session whose key signs PAR and any retries
93
91
  # @return [Response] The PAR response
94
92
  # @raise [Error] if request fails
95
93
  #
96
- def submit(request)
97
- # Try the initial request
98
- response = make_request(request)
99
-
100
- return process_response(response) if response[:status] == 201
101
-
102
- # Handle DPoP nonce requirement
103
- if requires_nonce?(response)
104
- nonce = extract_nonce(response)
105
- store_nonce(nonce)
106
-
107
- # Get stored nonce to verify
108
- nonce_manager.get(server_origin)
94
+ def submit(request, session:)
95
+ raise Error, "Expected a PAR::Request" unless request.is_a?(PAR::Request)
109
96
 
110
- # Generate new proof with nonce and retry
111
- response = make_request(request)
112
- 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)
113
99
  end
114
100
 
115
- handle_error_response(response)
101
+ if response[:status] == 201
102
+ handle_success_response(response)
103
+ else
104
+ handle_error_response(response)
105
+ end
116
106
  rescue StandardError => e
117
107
  raise Error, "PAR request failed: #{e.message}"
118
108
  end
119
109
 
120
- # Reads a nonce from a transport response hash.
121
- #
122
- # @param response [Hash{Symbol => Object}] response containing a `:headers` hash with a `DPoP-Nonce` header
123
- # @return [String] server-provided nonce
124
- # @raise [Error] if no supported nonce header is present
125
- #
126
- def extract_nonce(response)
127
- # Try all possible header key formats
128
- headers = response[:headers]
129
- nonce = headers["DPoP-Nonce"] ||
130
- headers["dpop-nonce"] ||
131
- headers["Dpop-Nonce"]
132
-
133
- raise Error, "No DPoP nonce provided in response" unless nonce
134
-
135
- nonce
136
- end
137
-
138
110
  # Builds the browser URL using the client ID and returned PAR request URI.
139
111
  #
140
- # The endpoint's existing query is replaced by these two parameters.
112
+ # Retains existing query parameters.
141
113
  #
142
- # @param authorize_endpoint [String] authorization endpoint URL
143
114
  # @param request_uri [String] request URI from {Response#request_uri}
144
115
  # @param client_id [String] OAuth client ID
145
116
  # @return [String] browser authorization URL
146
117
  # @raise [URI::InvalidURIError] if the authorization endpoint cannot be parsed
147
118
  #
148
- def authorization_url(authorize_endpoint:, request_uri:, client_id:)
149
- uri = URI(authorize_endpoint)
150
- uri.query = encode_params(
151
- "request_uri" => request_uri,
152
- "client_id" => client_id
153
- )
154
- uri.to_s
155
- end
156
-
157
- private
119
+ def build_authorization_url(request_uri:, client_id:)
120
+ uri = URI(@authorization_server.authorization_endpoint)
158
121
 
159
- def validate_endpoint
160
- uri = URI(@endpoint)
161
- raise Error, "endpoint must be HTTPS" unless uri.scheme == "https"
162
- rescue URI::InvalidURIError => e
163
- raise Error, "invalid endpoint URL: #{e.message}"
164
- end
122
+ params = {
123
+ request_uri: request_uri,
124
+ client_id: client_id
125
+ }
165
126
 
166
- def make_request(request)
167
- # Generate DPoP proof for this request
168
- proof = dpop_client.generate_proof(
169
- http_method: "POST",
170
- http_uri: endpoint,
171
- nonce: nonce_manager.get(server_origin)
172
- )
127
+ existing_query = uri.query || ''
128
+ params_query = URI.encode_www_form(params).gsub('*', '%2A') # unescaped '*' may break links in the terminal
173
129
 
174
- # Build headers including DPoP proof
175
- headers = build_headers(request, proof)
130
+ uri.query = existing_query + (existing_query.empty? ? '' : '&') + params_query
176
131
 
177
- # Make the request
178
- AuthProto.configuration.http_client.post(
179
- endpoint,
180
- body: request.to_form,
181
- headers: headers
182
- )
132
+ uri.to_s
183
133
  end
184
134
 
185
- def build_headers(request, dpop_proof)
186
- {
187
- "Content-Type" => "application/x-www-form-urlencoded",
188
- "DPoP" => dpop_proof
189
- }
190
- end
191
135
 
192
- def requires_nonce?(response)
193
- body = JSON.parse(response[:body])
194
- body["error"] == "use_dpop_nonce"
195
- rescue JSON::ParserError
196
- false
197
- end
136
+ private
198
137
 
199
- def store_nonce(nonce)
200
- nonce_manager.update(nonce: nonce, server_url: server_origin)
201
- end
138
+ def make_request(request, session:)
139
+ dpop_proof = dpop_client.generate_proof(session: session, method: 'POST', uri: @par_endpoint)
202
140
 
203
- def server_origin
204
- uri = URI(@endpoint)
205
- "#{uri.scheme}://#{uri.host}#{":#{uri.port}" if uri.port != uri.default_port}"
141
+ AuthProto.configuration.http_client.post(
142
+ @par_endpoint,
143
+ body: request.to_form(audience: @authorization_server.issuer),
144
+ headers: {
145
+ "Content-Type" => "application/x-www-form-urlencoded",
146
+ "DPoP" => dpop_proof
147
+ }
148
+ )
206
149
  end
207
150
 
208
151
  def handle_error_response(response)
209
152
  begin
210
153
  error_data = JSON.parse(response[:body])
211
- error_message = error_data["error_description"] || error_data["error"] || "Unknown error"
154
+ error_message = error_data['error_description'] || error_data['error'] || "Unknown error"
212
155
  rescue JSON::ParserError
213
156
  error_message = "Invalid response from server"
214
157
  end
@@ -216,14 +159,20 @@ module AuthProto
216
159
  raise Error, "PAR request failed: #{error_message} (status: #{response[:status]})"
217
160
  end
218
161
 
219
- def process_response(response)
220
- raise Error, "unexpected response status: #{response[:status]}" unless response[:status] == 201
162
+ def handle_success_response(response)
163
+ content_type = response_header(response, 'Content-Type', strip_parameters: true)
164
+
165
+ unless content_type.to_s.casecmp?('application/json')
166
+ raise Error, "PAR response must use application/json"
167
+ end
221
168
 
222
169
  begin
223
170
  data = JSON.parse(response[:body])
171
+ raise Error, "PAR response must be a JSON object" unless data.is_a?(Hash)
172
+
224
173
  Response.new(
225
- request_uri: data["request_uri"],
226
- expires_in: data["expires_in"]
174
+ request_uri: data['request_uri'],
175
+ expires_in: data['expires_in']
227
176
  )
228
177
  rescue JSON::ParserError => e
229
178
  raise Error, "invalid JSON response: #{e.message}"
@@ -231,10 +180,6 @@ module AuthProto
231
180
  raise Error, "failed to process response: #{e.message}"
232
181
  end
233
182
  end
234
-
235
- def encode_params(params)
236
- params.map { |k, v| "#{CGI.escape(k)}=#{CGI.escape(v.to_s)}" }.join("&")
237
- end
238
183
  end
239
184
  end
240
185
  end