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
@@ -34,7 +34,7 @@ module AuthProto
34
34
  # @yieldparam config [Configuration] mutable global settings
35
35
  # @yieldreturn [Object] ignored
36
36
  # @return [Configuration] validated global settings
37
- # @raise [ConfigurationError] if the storage or HTTP client is invalid
37
+ # @raise [ConfigurationError] if storage, HTTP transport or lifetime settings are invalid
38
38
  # @example Configure the default transport
39
39
  # AuthProto.configure do |config|
40
40
  # config.http_client = AuthProto::HTTPClient.new
@@ -62,7 +62,7 @@ module AuthProto
62
62
  end
63
63
  end
64
64
 
65
- # Raised when global storage or HTTP transport settings are invalid.
65
+ # Raised when global configuration settings are invalid.
66
66
  class ConfigurationError < Error; end
67
67
 
68
68
  #
@@ -71,18 +71,14 @@ module AuthProto
71
71
 
72
72
  class Configuration
73
73
 
74
- # Configured default token lifetime in seconds (300); currently unused by token exchange.
75
- # @return [Integer]
76
- attr_accessor :default_token_lifetime
74
+ # Default client assertion validity in seconds, read when generating each assertion.
75
+ # @return [Integer] positive lifetime in seconds; defaults to 300
76
+ attr_accessor :client_assertion_lifetime
77
77
 
78
- # Configured default nonce lifetime in seconds (300); nonce managers currently use their own TTL.
79
- # @return [Integer]
78
+ # Default stored nonce lifetime in seconds; used when creating nonce managers without an explicit TTL.
79
+ # @return [Integer] positive lifetime in seconds; defaults to 300
80
80
  attr_accessor :dpop_nonce_lifetime
81
81
 
82
- # Reserved encryption setting; serializers currently create their own service.
83
- # @return [Object, nil]
84
- attr_accessor :encryption
85
-
86
82
  # Transport used for discovery, PAR and token requests; initially `nil`.
87
83
  # @return [#get, #post, nil]
88
84
  attr_accessor :http_client
@@ -91,6 +87,10 @@ module AuthProto
91
87
  # @return [Logger]
92
88
  attr_accessor :logger
93
89
 
90
+ # Lifetime of pending authorization attempts in seconds; defaults to 900 (15 minutes).
91
+ # @return [Integer] positive lifetime in seconds
92
+ attr_accessor :pending_session_ttl
93
+
94
94
  # Storage backend; defaults to a new {Storage::Memory}.
95
95
  # @return [Storage::Interface]
96
96
  attr_accessor :storage
@@ -98,30 +98,51 @@ module AuthProto
98
98
  # Creates default settings with in-memory storage and no HTTP transport.
99
99
  #
100
100
  def initialize
101
- @default_token_lifetime = 300 # 5 minutes in seconds
102
- @dpop_nonce_lifetime = 300 # 5 minutes in seconds
103
- @encryption = nil
101
+ @client_assertion_lifetime = 300 # 5 minutes
102
+ @dpop_nonce_lifetime = 300 # 5 minutes
103
+ @pending_session_ttl = 900 # 15 minutes
104
104
  @http_client = nil
105
105
  @logger = Logger.new($stdout)
106
106
  @storage = AuthProto::Storage::Memory.new
107
107
  end
108
108
 
109
- # Checks that storage implements the interface and the transport supports GET/POST.
109
+ # Checks storage and transport interfaces and positive assertion, nonce and pending session lifetimes.
110
110
  #
111
111
  # A `nil` HTTP client is accepted, but cannot perform OAuth or discovery requests.
112
112
  #
113
113
  # @return [true] if validation succeeds
114
- # @raise [ConfigurationError] if storage is absent/invalid or transport methods are missing
114
+ # @raise [ConfigurationError] if storage, HTTP transport or lifetime settings are invalid
115
115
  #
116
116
  def validate
117
117
  validate_storage
118
118
  validate_http_client
119
+ validate_client_assertion_lifetime
120
+ validate_dpop_nonce_lifetime
121
+ validate_pending_session_ttl
119
122
  true
120
123
  end
121
124
 
122
125
 
123
126
  private
124
127
 
128
+ def validate_client_assertion_lifetime
129
+ return if @client_assertion_lifetime.is_a?(Integer) && @client_assertion_lifetime.positive?
130
+
131
+ raise ConfigurationError, "Client assertion lifetime must be a positive integer"
132
+ end
133
+
134
+ def validate_dpop_nonce_lifetime
135
+ return if @dpop_nonce_lifetime.is_a?(Integer) && @dpop_nonce_lifetime.positive?
136
+
137
+ raise ConfigurationError, "DPoP nonce lifetime must be a positive integer"
138
+ end
139
+
140
+ def validate_pending_session_ttl
141
+ return if @pending_session_ttl.is_a?(Integer) && @pending_session_ttl.positive?
142
+
143
+ raise ConfigurationError, "Pending session TTL must be a positive integer"
144
+ end
145
+
125
146
  def validate_storage
126
147
  raise ConfigurationError, "Storage must be configured" if @storage.nil?
127
148
  return if @storage.is_a?(AuthProto::Storage::Interface)
@@ -1,82 +1,73 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'json'
3
4
  require 'uri'
4
5
 
5
6
  require_relative '../errors'
6
- require_relative 'key_manager'
7
+ require_relative '../http_helpers'
7
8
  require_relative 'nonce_manager'
8
9
  require_relative 'proof_generator'
9
10
 
10
11
  module AuthProto
11
12
 
12
13
  #
13
- # Key management, per-request proofs and server-origin nonces for DPoP authentication.
14
+ # Shared proof generation and server-origin nonces for DPoP authentication.
14
15
  #
15
16
 
16
17
  module DPoP
17
18
 
18
- # High-level client for managing DPoP operations. Integrates key management,
19
- # proof generation, and nonce tracking to provide a complete DPoP client
20
- # implementation according to RFC 9449.
21
19
  #
22
- # This client handles:
23
- # - Key management for signing proofs
24
- # - Proof generation for HTTP requests
25
- # - Nonce tracking across servers
26
- # - Header construction for requests
27
- # - Response processing for nonce updates
20
+ # Shared DPoP client using session-owned signing keys and nonces scoped to
21
+ # each session and server origin. Generates RFC 9449 proofs, processes nonce
22
+ # updates, and detects nonce challenges. Response processing requires a nonce
23
+ # on every DPoP response, as required by the AT Protocol OAuth profile.
28
24
  #
29
25
 
30
26
  class Client
27
+ include HTTPHelpers
31
28
 
32
29
  # Error raised for DPoP client operations
33
30
  class Error < AuthProto::Error; end
34
31
 
35
- # Key manager used to sign proofs.
36
- # @return [KeyManager]
37
- attr_reader :key_manager
38
-
39
32
  # Generator for per-request DPoP JWTs.
40
33
  # @return [ProofGenerator]
41
34
  attr_reader :proof_generator
42
35
 
43
- # Persistent nonce store, indexed by server origin.
36
+ # Persistent nonce store, indexed by session and server origin.
44
37
  # @return [NonceManager]
45
38
  attr_reader :nonce_manager
46
39
 
47
- # Creates DPoP signing, proof and nonce managers.
40
+ # Creates a shared proof generator and nonce storage scoped to sessions and server origins.
48
41
  #
49
- # @param key_manager [KeyManager, nil] existing key manager, or `nil` to generate a keypair
50
- # @param nonce_ttl [Integer, nil] stored nonce lifetime in seconds, or the nonce manager's default
51
- # @raise [KeyManager::KeyError] if key generation fails
52
- # @raise [ProofGenerator::ProofError] if the key manager is invalid
42
+ # @param nonce_ttl [Integer, nil] stored nonce lifetime in seconds; `nil` uses {Configuration#dpop_nonce_lifetime}
53
43
  # @raise [ArgumentError] if the encryption master key is not valid Base64
54
44
  #
55
- def initialize(key_manager: nil, nonce_ttl: nil)
56
- @key_manager = key_manager || KeyManager.new
45
+ def initialize(nonce_ttl: nil)
57
46
  @nonce_manager = NonceManager.new(ttl: nonce_ttl)
58
- @proof_generator = ProofGenerator.new(@key_manager)
47
+ @proof_generator = ProofGenerator.new
59
48
  end
60
49
 
61
- # Generates a fresh DPoP proof using a supplied or stored nonce for the origin.
50
+ # Generates a fresh DPoP proof using the stored nonce for the session and origin, if available.
62
51
  #
63
- # @param http_method [String] HTTP method, converted to uppercase
64
- # @param http_uri [String] absolute HTTP(S) URL; callers should omit the query and fragment
52
+ # @param session [State::Session] session whose DPoP key signs the request
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`
65
55
  # @param access_token [String, nil] token to bind with an `ath` claim
66
- # @param nonce [String, nil] explicit nonce; `nil` looks up the origin's stored nonce
67
56
  # @return [JOSE::SignedBinary] compact signed DPoP JWT
68
57
  # @raise [Error] if URI parsing, nonce lookup or signing fails
69
58
  #
70
- def generate_proof(http_method:, http_uri:, access_token: nil, nonce: nil)
71
- uri = URI(http_uri)
72
- server_url = "#{uri.scheme}://#{uri.host}#{":#{uri.port}" if uri.port != uri.default_port}"
59
+ def generate_proof(session:, method:, uri:, access_token: nil)
60
+ parsed_uri = URI(uri)
61
+
62
+ server_url = "#{parsed_uri.scheme}://#{parsed_uri.host}"
63
+ server_url += ":#{parsed_uri.port}" if parsed_uri.port != parsed_uri.default_port
73
64
 
74
- # Use provided nonce or get one from the manager
75
- nonce ||= @nonce_manager.get(server_url)
65
+ nonce = @nonce_manager.get(server_url: server_url, session_id: session.session_id)
76
66
 
77
67
  @proof_generator.generate(
78
- http_method: http_method,
79
- http_uri: http_uri,
68
+ key_set: session.dpop_key,
69
+ method: method,
70
+ uri: uri,
80
71
  nonce: nonce,
81
72
  access_token: access_token
82
73
  )
@@ -85,76 +76,102 @@ module AuthProto
85
76
  end
86
77
 
87
78
  # Stores a `DPoP-Nonce` response header for future requests to the same origin.
88
- # Header names are compared case-insensitively. Missing headers/nonces are ignored.
79
+ # Call after every DPoP HTTP attempt, before accepting a result or deciding to retry.
80
+ # Header names are case-insensitive; missing, malformed and duplicate nonces are rejected.
89
81
  #
90
- # @param response_headers [Hash{String => String}, nil] response headers, or `nil`
82
+ # @param session_id [String] session that made the request
83
+ # @param response [Hash{Symbol => Object}] HTTP response with `:status`, `:headers`, and `:body`
91
84
  # @param server_url [String] request URL whose origin owns the nonce
92
85
  # @return [void]
93
86
  # @raise [Error] if nonce validation or persistence fails
94
87
  #
95
- def process_response(response_headers, server_url)
96
- return unless response_headers
88
+ def process_response(response, server_url:, session_id:)
89
+ raise Error, "Expected a response hash" unless response.is_a?(Hash)
90
+
91
+ response_headers = response[:headers]
92
+ raise Error, "Missing or invalid response headers" unless response_headers.is_a?(Hash)
93
+
94
+ if response_headers.keys.count { |name| name.casecmp?('DPoP-Nonce') } > 1
95
+ raise Error, "Multiple DPoP-Nonce headers"
96
+ end
97
97
 
98
- # Look for DPoP-Nonce header (case insensitive)
99
- nonce = response_headers.find { |k, _| k.downcase == "dpop-nonce" }&.last
100
- return unless nonce
98
+ nonce = response_header(response, 'DPoP-Nonce')
99
+
100
+ if nonce.nil? || nonce == ''
101
+ raise Error, "Missing DPoP-Nonce header"
102
+ end
101
103
 
102
104
  # Store new nonce for future requests
103
- @nonce_manager.update(nonce: nonce, server_url: server_url)
105
+ @nonce_manager.update(nonce: nonce, server_url: server_url, session_id: session_id)
104
106
  rescue StandardError => e
105
107
  raise Error, "Failed to process response: #{e.message}"
106
108
  end
107
109
 
108
- # Wraps a proof in an HTTP header hash.
110
+ # Detects a nonce challenge without treating other errors as nonce challenges.
109
111
  #
110
- # @param proof [String] signed DPoP JWT
111
- # @return [Hash{String => String}] a single `DPoP` header
112
+ # Recognizes HTTP 400 JSON errors and an HTTP 401 DPoP authentication
113
+ # challenge. Header/parameter names and the scheme are case-insensitive;
114
+ # error values are case-sensitive. Multiple DPoP challenges are treated as ambiguous.
112
115
  #
113
- def request_headers(proof)
114
- {
115
- "DPoP" => proof
116
- }
117
- end
118
-
119
- # Exports the current public signing key.
116
+ # @param response [Hash{Symbol => Object}] HTTP response with status, headers and body
117
+ # @return [Boolean] whether the response requests a retry with a server nonce
118
+ # @raise [Error] if the response or its headers have an invalid type
120
119
  #
121
- # @return [Hash{String => Object}] public JWK
122
- # @raise [KeyManager::KeyError] if public-key export fails
123
- #
124
- def public_key
125
- @key_manager.public_jwk
120
+ def has_nonce_error?(response)
121
+ raise Error, "Expected a response hash" unless response.is_a?(Hash)
122
+
123
+ headers = response[:headers]
124
+ raise Error, "Missing or invalid response headers" unless headers.is_a?(Hash)
125
+
126
+ case response[:status]
127
+ when 400
128
+ return false unless response[:body].is_a?(String)
129
+
130
+ begin
131
+ data = JSON.parse(response[:body])
132
+ data.is_a?(Hash) && data['error'] == DPoP::ERROR_USE_NONCE
133
+ rescue JSON::ParserError
134
+ false
135
+ end
136
+ when 401
137
+ challenge = response_header(response, 'WWW-Authenticate')
138
+ nonce_challenge?(challenge)
139
+ else
140
+ false
141
+ end
126
142
  end
127
143
 
128
- # Exports the current DPoP key for persistence or inspection.
144
+ # Runs a DPoP request and retries once if the server requests a new nonce.
145
+ # Processes every response before returning it or invoking the block again.
146
+ # The block must build a fresh proof and send the request on each invocation;
147
+ # the initial proof may already include a cached nonce.
129
148
  #
130
- # @param include_private [Boolean] include the private key needed to restore the same identity
131
- # @return [JOSE::Map] JWK fields; call `to_h` for a Ruby hash
132
- # @raise [KeyManager::KeyError] if key export fails
149
+ # @param session [State::Session] session making the request
150
+ # @param url [String] request URL whose origin owns the nonce
151
+ # @yield sends one HTTP request using a fresh DPoP proof
152
+ # @yieldreturn [Hash{Symbol => Object}] HTTP response with status, headers and body
153
+ # @return [Hash{Symbol => Object}] final response, including any remaining error
154
+ # @raise [Error] if a response lacks a valid nonce or nonce persistence fails
133
155
  #
134
- def export_key(include_private: false)
135
- @key_manager.to_jwk(include_private: include_private)
136
- end
137
-
156
+ def with_nonce_handling(session, url)
157
+ response = yield
138
158
 
139
- private
159
+ process_response(response, server_url: url, session_id: session.session_id)
140
160
 
141
- def extract_nonce(headers)
142
- # Headers can be hash with string or symbol keys, or http headers object
143
- headers = headers.to_h if headers.respond_to?(:to_h)
161
+ if has_nonce_error?(response)
162
+ response = yield
144
163
 
145
- # Try different common header key formats
146
- nonce = headers["DPoP-Nonce"] || headers["dpop-nonce"] || headers[:dpop_nonce]
164
+ process_response(response, server_url: url, session_id: session.session_id)
165
+ end
147
166
 
148
- nonce&.strip
167
+ response
149
168
  end
150
169
 
151
- def origin_for_uri(uri)
152
- port = uri.port
153
- port = nil if (uri.scheme == "https" && port == 443) || (uri.scheme == "http" && port == 80)
154
170
 
155
- origin = "#{uri.scheme}://#{uri.host}"
156
- origin = "#{origin}:#{port}" if port
157
- origin
171
+ private
172
+
173
+ def nonce_challenge?(challenge)
174
+ authentication_challenge(challenge, scheme: 'DPoP')&.fetch('error', nil) == DPoP::ERROR_USE_NONCE
158
175
  end
159
176
  end
160
177
  end
@@ -0,0 +1,157 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'jose'
4
+ require 'json'
5
+
6
+ require_relative '../dpop'
7
+ require_relative '../errors'
8
+
9
+ module AuthProto
10
+ module DPoP
11
+
12
+ #
13
+ # Holds an ES256 signing keypair and imports/exports JWKs for DPoP proofs.
14
+ # Keys are held in memory; the session serializer handles encrypted persistence.
15
+ # Uses JOSE for cryptographic operations and key format handling.
16
+ #
17
+
18
+ class KeySet
19
+
20
+ # Error raised when key operations fail
21
+ class KeyError < AuthProto::Error; end
22
+
23
+ # Elliptic curve used for DPoP signing keys.
24
+ # @return [String]
25
+ CURVE = "P-256"
26
+
27
+ # Private EC P-256 keypair used for signing.
28
+ # @return [JOSE::JWK]
29
+ attr_reader :key
30
+
31
+ # Creates a new KeySet instance with an optional existing keypair
32
+ #
33
+ # @param key [JOSE::JWK, nil] Optional existing keypair to use
34
+ # @raise [KeyError] if the provided key is invalid
35
+ #
36
+ def initialize(key = nil)
37
+ @key = key || generate_keypair
38
+ validate_keypair
39
+ end
40
+
41
+ # Exports the public key for embedding in a DPoP proof.
42
+ #
43
+ # @return [Hash{String => Object}] public JWK without private key material
44
+ # @raise [KeyError] if public-key export fails
45
+ #
46
+ def public_jwk
47
+ @key.to_public_map.to_h
48
+ rescue StandardError => e
49
+ raise KeyError, "Failed to export public key: #{e.message}"
50
+ end
51
+
52
+ # Signs a JSON payload with the supplied protected JWS header and ES256.
53
+ # Hash keys are recursively converted to strings. The algorithm is forced to `ES256`.
54
+ #
55
+ # @param header [Hash{String, Symbol => Object}] protected JOSE header fields
56
+ # @param payload [Hash{String, Symbol => Object}] JWT claims to JSON-encode
57
+ # @return [JOSE::SignedBinary] compact JWS (a string subclass)
58
+ # @raise [KeyError] if encoding or signing fails
59
+ #
60
+ def sign_segments(header, payload)
61
+ # Deep transform all keys to strings to avoid symbol comparison issues
62
+ header = deep_stringify_keys(header)
63
+ payload = deep_stringify_keys(payload)
64
+
65
+ # Configure JOSE to use ES256 for signing
66
+ signing_config = { 'alg' => ALGORITHM }
67
+
68
+ # Merge our header with JOSE's required fields
69
+ full_header = header.merge(signing_config)
70
+
71
+ # Convert payload to JSON string before signing
72
+ payload_json = JSON.generate(payload)
73
+
74
+ # Create the JWS with our header and payload
75
+ jws = @key.sign(payload_json, full_header)
76
+
77
+ # Get the compact serialization
78
+ jws.compact
79
+ rescue StandardError => e
80
+ raise KeyError, "Failed to sign segments: #{e.message}"
81
+ end
82
+
83
+ # Exports this keypair including its private signing material.
84
+ #
85
+ # @return [Hash{String => Object}] private JWK including the secret `d` component
86
+ # @raise [KeyError] if export fails
87
+ #
88
+ def private_jwk
89
+ @key.to_map.to_h
90
+ rescue StandardError => e
91
+ raise KeyError, "Failed to export key: #{e.message}"
92
+ end
93
+
94
+ # Imports an EC P-256 JWK and validates that it can sign and verify.
95
+ #
96
+ # @param jwk [Hash{String => Object}, JOSE::Map] JWK including private key material
97
+ # @return [KeySet] imported and validated keypair wrapper
98
+ # @raise [KeyError] if import or key validation fails
99
+ #
100
+ def self.from_jwk(jwk)
101
+ key = JOSE::JWK.from_map(jwk)
102
+ new(key)
103
+ rescue StandardError => e
104
+ raise KeyError, "Failed to import key: #{e.message}"
105
+ end
106
+
107
+
108
+ private
109
+
110
+ def generate_keypair
111
+ JOSE::JWK.generate_key([:ec, CURVE])
112
+ rescue StandardError => e
113
+ raise KeyError, "Failed to generate keypair: #{e.message}"
114
+ end
115
+
116
+ def sign(data)
117
+ @key.sign(data, { 'alg' => ALGORITHM }).compact
118
+ rescue StandardError => e
119
+ raise KeyError, "Failed to sign data: #{e.message}"
120
+ end
121
+
122
+ def deep_stringify_keys(obj)
123
+ case obj
124
+ when Hash
125
+ obj.each_with_object({}) do |(k, v), hash|
126
+ hash[k.to_s] = deep_stringify_keys(v)
127
+ end
128
+ when Array
129
+ obj.map { |v| deep_stringify_keys(v) }
130
+ else
131
+ obj
132
+ end
133
+ end
134
+
135
+ def verify(signed_jws)
136
+ verified, payload, = @key.verify(signed_jws)
137
+ verified
138
+ rescue StandardError => e
139
+ raise KeyError, "Failed to verify signature: #{e.message}"
140
+ end
141
+
142
+ def validate_keypair
143
+ raise KeyError, "Invalid key type: #{@key.kty}, must be :ec" unless @key.kty.is_a?(JOSE::JWK::KTY_EC)
144
+
145
+ curve = @key.to_map['crv']
146
+ raise KeyError, "Invalid curve: #{curve}, must be #{CURVE}" unless curve == CURVE
147
+
148
+ # Verify we can perform basic operations
149
+ test_data = 'test'
150
+ signed = sign(test_data)
151
+ raise KeyError, "Key validation failed: signature verification error" unless verify(signed)
152
+ rescue StandardError => e
153
+ raise KeyError, "Key validation failed: #{e.message}"
154
+ end
155
+ end
156
+ end
157
+ end