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,223 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'base64'
4
- require 'jose'
5
- require 'json'
6
- require 'openssl'
7
-
8
- require_relative '../errors'
9
-
10
- module AuthProto
11
- module DPoP
12
-
13
- #
14
- # Manages ES256 keypair generation and storage for DPoP proofs.
15
- # Provides functionality to generate new keys and store them securely.
16
- # Uses JOSE for cryptographic operations and key format handling.
17
- #
18
-
19
- class KeyManager
20
-
21
- # Error raised when key operations fail
22
- class KeyError < AuthProto::Error; end
23
-
24
- # Elliptic curve used for DPoP signing keys.
25
- # @return [String]
26
- CURVE = "P-256"
27
-
28
- # JWS signing algorithm used for DPoP proofs.
29
- # @return [String]
30
- ALGORITHM = "ES256"
31
-
32
- # Private EC P-256 keypair used for signing.
33
- # @return [JOSE::JWK]
34
- attr_reader :keypair
35
-
36
- # Creates a new KeyManager instance with an optional existing keypair
37
- #
38
- # @param keypair [JOSE::JWK, nil] Optional existing keypair to use
39
- # @raise [KeyError] if the provided keypair is invalid
40
- #
41
- def initialize(keypair = nil)
42
- @keypair = keypair || generate_keypair
43
- validate_keypair
44
- end
45
-
46
- # Generates a new ES256 keypair for DPoP usage
47
- #
48
- # @return [JOSE::JWK] The newly generated keypair
49
- # @raise [KeyError] if key generation fails
50
- #
51
- def generate_keypair
52
- # Generate base keypair
53
- base_key = JOSE::JWK.generate_key([:ec, CURVE])
54
- base_map = base_key.to_map
55
-
56
- # Create new map with all required properties
57
- key_map = {
58
- "kty" => base_map["kty"],
59
- "crv" => base_map["crv"],
60
- "x" => base_map["x"],
61
- "y" => base_map["y"],
62
- "d" => base_map["d"],
63
- "use" => "sig",
64
- "kid" => generate_kid(base_map)
65
- }
66
-
67
- # Create new JWK with all properties
68
- JOSE::JWK.from_map(key_map)
69
- rescue StandardError => e
70
- raise KeyError, "Failed to generate keypair: #{e.message}"
71
- end
72
-
73
- # Exports the public key with `use: sig` and a key ID.
74
- #
75
- # @return [Hash{String => Object}] public JWK without private key material
76
- # @raise [KeyError] if public-key export fails
77
- #
78
- def public_jwk
79
- jwk = @keypair.to_public.to_map.to_h
80
- # If somehow the properties aren't set, add them
81
- jwk["use"] ||= "sig"
82
- jwk["kid"] ||= generate_kid(jwk)
83
- jwk
84
- rescue StandardError => e
85
- raise KeyError, "Failed to export public key: #{e.message}"
86
- end
87
-
88
- # Signs bytes with this keypair and returns a compact JWS.
89
- #
90
- # @param data [String] payload bytes to sign
91
- # @return [JOSE::SignedBinary] compact JWS (a string subclass)
92
- # @raise [KeyError] if signing fails
93
- #
94
- def sign(data)
95
- @keypair.sign(data).compact
96
- rescue StandardError => e
97
- raise KeyError, "Failed to sign data: #{e.message}"
98
- end
99
-
100
- # Signs a JSON payload with the supplied protected JWS header and ES256.
101
- # Hash keys are recursively converted to strings. The algorithm is forced to `ES256`.
102
- #
103
- # @param header [Hash{String, Symbol => Object}] protected JOSE header fields
104
- # @param payload [Hash{String, Symbol => Object}] JWT claims to JSON-encode
105
- # @return [JOSE::SignedBinary] compact JWS (a string subclass)
106
- # @raise [KeyError] if encoding or signing fails
107
- #
108
- def sign_segments(header, payload)
109
- # Deep transform all keys to strings to avoid symbol comparison issues
110
- header = deep_stringify_keys(header)
111
- payload = deep_stringify_keys(payload)
112
-
113
- # Configure JOSE to use ES256 for signing
114
- signing_config = { "alg" => "ES256" }
115
-
116
- # Merge our header with JOSE's required fields
117
- full_header = header.merge(signing_config)
118
-
119
- # Convert payload to JSON string before signing
120
- payload_json = JSON.generate(payload)
121
-
122
- # Create the JWS with our header and payload
123
- jws = @keypair.sign(payload_json, full_header)
124
-
125
- # Get the compact serialization
126
- jws.compact
127
- rescue StandardError => e
128
- raise KeyError, "Failed to sign segments: #{e.message}"
129
- end
130
-
131
- # Copies hashes and arrays recursively, converting hash keys to strings.
132
- #
133
- # @param obj [Object] input structure or scalar value
134
- # @return [Object] transformed hash/array, or the original scalar
135
- #
136
- def deep_stringify_keys(obj)
137
- case obj
138
- when Hash
139
- obj.each_with_object({}) do |(k, v), hash|
140
- hash[k.to_s] = deep_stringify_keys(v)
141
- end
142
- when Array
143
- obj.map { |v| deep_stringify_keys(v) }
144
- else
145
- obj
146
- end
147
- end
148
-
149
- # Verifies a compact JWS using this keypair.
150
- #
151
- # @param signed_jws [String, JOSE::SignedBinary] complete signed JWS
152
- # @return [Boolean] whether the signature is valid
153
- # @raise [KeyError] if decoding or verification raises an error
154
- #
155
- def verify(signed_jws)
156
- verified, payload, = @keypair.verify(signed_jws)
157
- verified
158
- rescue StandardError => e
159
- raise KeyError, "Failed to verify signature: #{e.message}"
160
- end
161
-
162
- # Exports this keypair as a JOSE map.
163
- #
164
- # @param include_private [Boolean] include secret `d` key material when `true`
165
- # @return [JOSE::Map] JWK fields; call `to_h` for a Ruby hash
166
- # @raise [KeyError] if export fails
167
- #
168
- def to_jwk(include_private: false)
169
- key = include_private ? @keypair : @keypair.to_public
170
- key.to_map
171
- rescue StandardError => e
172
- raise KeyError, "Failed to export key: #{e.message}"
173
- end
174
-
175
- # Imports an EC P-256 JWK and validates that it can sign and verify.
176
- #
177
- # @param jwk [Hash{String => Object}, JOSE::Map] JWK including private key material
178
- # @return [KeyManager] imported key manager
179
- # @raise [KeyError] if import or key validation fails
180
- #
181
- def self.from_jwk(jwk)
182
- keypair = JOSE::JWK.from_map(jwk)
183
- new(keypair)
184
- rescue StandardError => e
185
- raise KeyError, "Failed to import key: #{e.message}"
186
- end
187
-
188
- private
189
-
190
- def generate_kid(jwk)
191
- # Generate a key ID based on the key's components
192
- components = [
193
- jwk["kty"],
194
- jwk["crv"],
195
- jwk["x"],
196
- jwk["y"]
197
- ].join(":")
198
-
199
- # Create a SHA-256 hash and take first 8 bytes
200
- digest = OpenSSL::Digest::SHA256.digest(components)
201
- Base64.urlsafe_encode64(digest[0..7], padding: false)
202
- end
203
-
204
- # Validates that the keypair meets DPoP requirements
205
- # @raise [KeyError] if validation fails
206
- def validate_keypair
207
- # Check that we have a valid EC key
208
- raise KeyError, "Invalid key type: #{@keypair.kty}, must be :ec" unless @keypair.kty.is_a?(JOSE::JWK::KTY_EC)
209
-
210
- # Verify the curve
211
- curve = @keypair.to_map["crv"]
212
- raise KeyError, "Invalid curve: #{curve}, must be #{CURVE}" unless curve == CURVE
213
-
214
- # Verify we can perform basic operations
215
- test_data = "test"
216
- signed = sign(test_data)
217
- raise KeyError, "Key validation failed: signature verification error" unless verify(signed)
218
- rescue StandardError => e
219
- raise KeyError, "Key validation failed: #{e.message}"
220
- end
221
- end
222
- end
223
- end
@@ -1,38 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require_relative '../dpop/key_manager'
4
- require_relative 'base'
5
-
6
- module AuthProto
7
- module Serialization
8
-
9
- #
10
- # Handles serialization of DPoP keys
11
- #
12
-
13
- class DPoPKey < Base
14
-
15
- # Returns the envelope type used by this serializer.
16
- # @return [String] `DPoPKey`
17
- def type_identifier
18
- "DPoPKey"
19
- end
20
-
21
- private
22
-
23
- def validate_object(obj)
24
- return if obj.is_a?(AuthProto::DPoP::KeyManager)
25
-
26
- raise ValidationError, "Expected KeyManager object, got #{obj.class}"
27
- end
28
-
29
- def serialize_data(obj)
30
- obj.to_jwk(include_private: true).to_h
31
- end
32
-
33
- def deserialize_data(data)
34
- AuthProto::DPoP::KeyManager.from_jwk(data)
35
- end
36
- end
37
- end
38
- end
@@ -1,267 +0,0 @@
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 '../server_metadata'
10
- require_relative 'origin_url'
11
-
12
- module AuthProto
13
- module ServerMetadata
14
-
15
- #
16
- # Handles fetching and validation of AT Protocol OAuth Authorization Server metadata.
17
- # An Authorization Server in atproto can be either a PDS instance or a separate "entryway" server
18
- # that handles authentication for multiple PDS instances.
19
- #
20
- # The Authorization Server metadata is fetched from the well-known endpoint
21
- # /.well-known/oauth-authorization-server and must conform to RFC 8414 plus additional
22
- # requirements specific to the AT Protocol OAuth profile.
23
- #
24
- # @example Fetching and validating Authorization Server metadata
25
- # begin
26
- # auth_server = AuthProto::ServerMetadata::AuthorizationServer.from_issuer("https://auth.example.com")
27
- # puts "Authorization endpoint: #{auth_server.authorization_endpoint}"
28
- # puts "Supported scopes: #{auth_server.scopes_supported}"
29
- # rescue AuthProto::InvalidAuthorizationServer => e
30
- # puts "Failed to validate authorization server: #{e.message}"
31
- # end
32
- #
33
- # @see https://atproto.com/specs/oauth#authorization-servers Documentation of Authorization Server requirements
34
- #
35
-
36
- class AuthorizationServer
37
-
38
- # Metadata keys that must be present before capability validation.
39
- # @return [Array<String>]
40
- REQUIRED_FIELDS = %w[
41
- issuer
42
- authorization_endpoint
43
- token_endpoint
44
- response_types_supported
45
- grant_types_supported
46
- code_challenge_methods_supported
47
- token_endpoint_auth_methods_supported
48
- token_endpoint_auth_signing_alg_values_supported
49
- scopes_supported
50
- dpop_signing_alg_values_supported
51
- pushed_authorization_request_endpoint
52
- ].freeze
53
-
54
- # Authorization server issuer origin.
55
- # @return [String]
56
- attr_reader :issuer
57
-
58
- # HTTPS browser authorization endpoint.
59
- # @return [String]
60
- attr_reader :authorization_endpoint
61
-
62
- # HTTPS token exchange and refresh endpoint.
63
- # @return [String]
64
- attr_reader :token_endpoint
65
-
66
- # HTTPS PAR endpoint.
67
- # @return [String]
68
- attr_reader :pushed_authorization_request_endpoint
69
-
70
- # Supported response types, including `code`.
71
- # @return [Array<String>]
72
- attr_reader :response_types_supported
73
-
74
- # Supported grant types, including authorization code and refresh token.
75
- # @return [Array<String>]
76
- attr_reader :grant_types_supported
77
-
78
- # Supported PKCE methods, including `S256`.
79
- # @return [Array<String>]
80
- attr_reader :code_challenge_methods_supported
81
-
82
- # Supported client authentication methods.
83
- # @return [Array<String>]
84
- attr_reader :token_endpoint_auth_methods_supported
85
-
86
- # Supported client assertion algorithms.
87
- # @return [Array<String>]
88
- attr_reader :token_endpoint_auth_signing_alg_values_supported
89
-
90
- # Supported scopes, including `atproto`.
91
- # @return [Array<String>]
92
- attr_reader :scopes_supported
93
-
94
- # Supported DPoP algorithms, including `ES256`.
95
- # @return [Array<String>]
96
- attr_reader :dpop_signing_alg_values_supported
97
-
98
- # Validates an authorization server's OAuth metadata.
99
- #
100
- # @param metadata [Hash{String => Object}] parsed discovery document with the fields in {REQUIRED_FIELDS} and required Boolean capabilities
101
- # @raise [InvalidAuthorizationServer] if required capabilities, issuer or endpoint schemes are invalid
102
- # @raise [URI::InvalidURIError] if a metadata URL cannot be parsed
103
- #
104
- def initialize(metadata)
105
- validate_and_set_metadata(metadata)
106
- end
107
-
108
- # Fetches `/.well-known/oauth-authorization-server` using the configured transport.
109
- #
110
- # The document's issuer must exactly match the requested issuer.
111
- #
112
- # @param issuer [String] authorization server issuer origin
113
- # @return [AuthorizationServer] validated discovery metadata
114
- # @raise [InvalidAuthorizationServer] if HTTP transport fails, JSON is invalid, or metadata/issuer validation fails
115
- # @raise [HTTPClient::SSRFError] if the transport rejects the initial destination
116
- # @raise [URI::InvalidURIError] if the issuer or a metadata URI cannot be parsed
117
- #
118
- def self.from_issuer(issuer)
119
- response = fetch_metadata(issuer)
120
- metadata = parse_metadata(response[:body])
121
- validate_issuer(metadata["issuer"], issuer)
122
- new(metadata)
123
- end
124
-
125
- # Exports metadata for serialization using symbol keys.
126
- #
127
- # Includes issuer/endpoints (String), capability lists (Array<String>), and the
128
- # three required Boolean flags set to `true`. Use JSON serialization to obtain
129
- # string keys suitable for passing back to {#initialize}.
130
- #
131
- # @return [Hash{Symbol => String, Array<String>, Boolean}] authorization server metadata
132
- #
133
- def to_h
134
- {
135
- issuer: issuer,
136
- authorization_endpoint: authorization_endpoint,
137
- token_endpoint: token_endpoint,
138
- pushed_authorization_request_endpoint: pushed_authorization_request_endpoint,
139
- response_types_supported: response_types_supported,
140
- grant_types_supported: grant_types_supported,
141
- code_challenge_methods_supported: code_challenge_methods_supported,
142
- token_endpoint_auth_methods_supported: token_endpoint_auth_methods_supported,
143
- token_endpoint_auth_signing_alg_values_supported: token_endpoint_auth_signing_alg_values_supported,
144
- scopes_supported: scopes_supported,
145
- dpop_signing_alg_values_supported: dpop_signing_alg_values_supported,
146
- authorization_response_iss_parameter_supported: true,
147
- require_pushed_authorization_requests: true,
148
- client_id_metadata_document_supported: true
149
- }
150
- end
151
-
152
- private
153
-
154
- def validate_and_set_metadata(metadata)
155
- REQUIRED_FIELDS.each do |field|
156
- raise InvalidAuthorizationServer, "#{field} is required" unless metadata[field]
157
- end
158
-
159
- @issuer = validate_issuer(metadata["issuer"])
160
- @authorization_endpoint = validate_https_url(metadata["authorization_endpoint"])
161
- @token_endpoint = validate_https_url(metadata["token_endpoint"])
162
- @pushed_authorization_request_endpoint = validate_https_url(metadata["pushed_authorization_request_endpoint"])
163
-
164
- validate_response_types(metadata["response_types_supported"])
165
- validate_grant_types(metadata["grant_types_supported"])
166
- validate_code_challenge_methods(metadata["code_challenge_methods_supported"])
167
- validate_token_endpoint_auth_methods(metadata["token_endpoint_auth_methods_supported"])
168
- validate_token_endpoint_auth_signing_algs(metadata["token_endpoint_auth_signing_alg_values_supported"])
169
- validate_dpop_signing_algs(metadata["dpop_signing_alg_values_supported"])
170
- validate_scopes(metadata["scopes_supported"])
171
-
172
- # Store validated values
173
- @response_types_supported = metadata["response_types_supported"]
174
- @grant_types_supported = metadata["grant_types_supported"]
175
- @code_challenge_methods_supported = metadata["code_challenge_methods_supported"]
176
- @token_endpoint_auth_methods_supported = metadata["token_endpoint_auth_methods_supported"]
177
- @token_endpoint_auth_signing_alg_values_supported = metadata["token_endpoint_auth_signing_alg_values_supported"]
178
- @scopes_supported = metadata["scopes_supported"]
179
- @dpop_signing_alg_values_supported = metadata["dpop_signing_alg_values_supported"]
180
-
181
- # Required boolean fields
182
- validate_boolean_field(metadata, "authorization_response_iss_parameter_supported", true)
183
- validate_boolean_field(metadata, "require_pushed_authorization_requests", true)
184
- validate_boolean_field(metadata, "client_id_metadata_document_supported", true)
185
- end
186
-
187
- def validate_issuer(issuer)
188
- is_valid = OriginURL.new(issuer).valid?
189
- raise InvalidAuthorizationServer, "invalid issuer URL format" unless is_valid
190
-
191
- issuer
192
- end
193
-
194
- def validate_https_url(url)
195
- uri = URI(url)
196
- raise InvalidAuthorizationServer, "URL must use HTTPS" unless uri.scheme == "https"
197
-
198
- url
199
- end
200
-
201
- def validate_response_types(types)
202
- raise InvalidAuthorizationServer, "must support 'code' response type" unless types.include?("code")
203
- end
204
-
205
- def validate_grant_types(types)
206
- required = %w[authorization_code refresh_token]
207
- missing = required - types
208
- raise InvalidAuthorizationServer, "missing grant types: #{missing.join(", ")}" if missing.any?
209
- end
210
-
211
- def validate_code_challenge_methods(methods)
212
- raise InvalidAuthorizationServer, "must support S256 PKCE" unless methods.include?("S256")
213
- end
214
-
215
- def validate_token_endpoint_auth_methods(methods)
216
- required = %w[private_key_jwt none]
217
- missing = required - methods
218
- raise InvalidAuthorizationServer, "missing auth methods: #{missing.join(", ")}" if missing.any?
219
- end
220
-
221
- def validate_token_endpoint_auth_signing_algs(algs)
222
- raise InvalidAuthorizationServer, "must support ES256" unless algs.include?("ES256")
223
- raise InvalidAuthorizationServer, "must not allow 'none'" if algs.include?("none")
224
- end
225
-
226
- def validate_dpop_signing_algs(algs)
227
- raise InvalidAuthorizationServer, "must support ES256 for DPoP" unless algs.include?("ES256")
228
- end
229
-
230
- def validate_scopes(scopes)
231
- required = %w[atproto]
232
- missing = required - scopes
233
- raise InvalidAuthorizationServer, "missing scopes: #{missing.join(", ")}" if missing.any?
234
- end
235
-
236
- def validate_boolean_field(metadata, field, required_value)
237
- actual = metadata[field]
238
- return if actual == required_value
239
-
240
- raise InvalidAuthorizationServer, "#{field} must be #{required_value}"
241
- end
242
-
243
- class << self
244
- private
245
-
246
- def fetch_metadata(issuer)
247
- metadata_url = URI.join(issuer, "/.well-known/oauth-authorization-server")
248
- AuthProto.configuration.http_client.get(metadata_url.to_s)
249
- rescue HTTPClient::HTTPError => e
250
- raise InvalidAuthorizationServer, "Failed to fetch authorization server metadata: #{e.message}"
251
- end
252
-
253
- def parse_metadata(body)
254
- JSON.parse(body)
255
- rescue JSON::ParserError => e
256
- raise InvalidAuthorizationServer, "Invalid JSON in authorization server metadata: #{e.message}"
257
- end
258
-
259
- def validate_issuer(metadata_issuer, request_issuer)
260
- return if metadata_issuer == request_issuer
261
-
262
- raise InvalidAuthorizationServer, "issuer mismatch: #{metadata_issuer} != #{request_issuer}"
263
- end
264
- end
265
- end
266
- end
267
- end
@@ -1,71 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'uri'
4
-
5
- require_relative '../server_metadata'
6
-
7
- module AuthProto
8
- module ServerMetadata
9
-
10
- #
11
- # The `OriginURL` class provides validation logic for URLs that must conform
12
- # to the AT Protocol OAuth "simple origin URL" requirements. These requirements
13
- # are common between Resource and Authorization Servers and ensure that the URL
14
- # is valid and secure for use in the protocol. This class validates that the URL:
15
- # - Uses the HTTPS scheme.
16
- # - Points to the root path (either an empty path or "/").
17
- # - Does not include a query string or fragment.
18
- # - Does not include user or password credentials.
19
- # - May include a non-default port but disallows the default HTTPS port (443).
20
- #
21
- # This model centralizes the URL validation logic to promote reusability and
22
- # consistency between different server classes.
23
- #
24
-
25
- class OriginURL
26
-
27
- # Original URL string supplied by the caller.
28
- # @return [String]
29
- attr_reader :url
30
-
31
- # Parsed URI used for origin validation.
32
- # @return [URI::Generic]
33
- attr_reader :uri
34
-
35
- # Parses a candidate server origin; call {#valid?} to check origin restrictions.
36
- #
37
- # @param url [String] origin URL to parse
38
- # @raise [URI::InvalidURIError] if the input cannot be parsed as a URI
39
- #
40
- def initialize(url)
41
- @url = url
42
- @uri = URI(url)
43
- end
44
-
45
- # Determines if a URL conforms to AT Protocol OAuth "simple origin URL" requirements
46
- # @return [Boolean] true if the URL is a valid origin URL
47
- def valid?
48
- https_scheme? &&
49
- root_path? &&
50
- !uri.query &&
51
- !uri.fragment &&
52
- !uri.userinfo &&
53
- (!explicit_port? || uri.port != 443)
54
- end
55
-
56
- private
57
-
58
- def https_scheme?
59
- uri.scheme == "https"
60
- end
61
-
62
- def root_path?
63
- uri.path.empty? || uri.path == "/"
64
- end
65
-
66
- def explicit_port?
67
- url.match?(/:\d+/)
68
- end
69
- end
70
- end
71
- end
@@ -1,98 +0,0 @@
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 '../server_metadata'
10
- require_relative 'origin_url'
11
-
12
- module AuthProto
13
- module ServerMetadata
14
-
15
- #
16
- # This class represents a Resource Server (PDS) and is responsible for
17
- # validating and managing its metadata. It ensures that the authorization
18
- # server URLs provided are valid and compliant with expected standards.
19
- # The class also includes functionality to fetch and parse metadata from a
20
- # remote URL, raising specific errors for invalid or malformed metadata.
21
- #
22
-
23
- class ResourceServer
24
-
25
- # Authorization server origins; validation requires exactly one entry.
26
- # @return [Array<String>]
27
- attr_reader :authorization_servers
28
-
29
- # Validates resource server metadata and its single authorization server origin.
30
- #
31
- # @param metadata [Hash{String => Object}] discovery document containing `authorization_servers`
32
- # @raise [InvalidAuthorizationServer] if the list is missing or does not contain one valid origin
33
- # @raise [URI::InvalidURIError] if the authorization server URI cannot be parsed
34
- #
35
- def initialize(metadata)
36
- @authorization_servers = validate_authorization_servers(metadata["authorization_servers"])
37
- end
38
-
39
- # Fetches `/.well-known/oauth-protected-resource` using the configured transport.
40
- #
41
- # @param url [String] resource server/PDS base URL
42
- # @return [ResourceServer] validated resource server metadata
43
- # @raise [InvalidAuthorizationServer] if HTTP transport, JSON parsing or metadata validation fails
44
- # @raise [HTTPClient::SSRFError] if the transport rejects the initial destination
45
- # @raise [URI::InvalidURIError] if the PDS or authorization server URL cannot be parsed
46
- #
47
- def self.from_url(url)
48
- response = fetch_metadata(url)
49
- new(parse_metadata(response[:body]))
50
- end
51
-
52
-
53
- private
54
-
55
- def validate_authorization_servers(servers)
56
- ensure_servers_exist(servers)
57
- ensure_exactly_one_server(servers)
58
- validate_server_url_format(servers.first)
59
- servers
60
- end
61
-
62
- def ensure_servers_exist(servers)
63
- return if servers.is_a?(Array)
64
-
65
- raise InvalidAuthorizationServer, "authorization_servers missing"
66
- end
67
-
68
- def ensure_exactly_one_server(servers)
69
- return if servers.size == 1
70
-
71
- raise InvalidAuthorizationServer, "must have exactly one authorization server"
72
- end
73
-
74
- def validate_server_url_format(server_url)
75
- return if OriginURL.new(server_url).valid?
76
-
77
- raise InvalidAuthorizationServer, "invalid authorization server URL format for #{server_url}"
78
- end
79
-
80
- class << self
81
- private
82
-
83
- def fetch_metadata(url)
84
- metadata_url = URI.join(url, "/.well-known/oauth-protected-resource")
85
- AuthProto.configuration.http_client.get(metadata_url.to_s)
86
- rescue HTTPClient::HTTPError => e
87
- raise InvalidAuthorizationServer, "Failed to fetch resource server metadata: #{e.message}"
88
- end
89
-
90
- def parse_metadata(body)
91
- JSON.parse(body)
92
- rescue JSON::ParserError => e
93
- raise InvalidAuthorizationServer, "Invalid JSON in resource server metadata: #{e.message}"
94
- end
95
- end
96
- end
97
- end
98
- end