legion-crypt 1.5.38 → 1.6.0

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 (45) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/ci.yml +30 -3
  3. data/.rspec +2 -0
  4. data/AGENTS.md +2 -0
  5. data/CHANGELOG.md +99 -0
  6. data/CLAUDE.md +65 -192
  7. data/CODEOWNERS +4 -4
  8. data/Gemfile +4 -1
  9. data/README.md +60 -16
  10. data/legion-crypt.gemspec +1 -0
  11. data/lib/legion/crypt/cert_rotation.rb +7 -21
  12. data/lib/legion/crypt/cluster_secret.rb +3 -14
  13. data/lib/legion/crypt/ed25519.rb +2 -10
  14. data/lib/legion/crypt/erasure.rb +3 -13
  15. data/lib/legion/crypt/jwks_client.rb +4 -4
  16. data/lib/legion/crypt/lease_manager.rb +5 -831
  17. data/lib/legion/crypt/mtls.rb +8 -46
  18. data/lib/legion/crypt/partition_keys.rb +2 -6
  19. data/lib/legion/crypt/settings.rb +31 -21
  20. data/lib/legion/crypt/spiffe/svid_rotation.rb +6 -9
  21. data/lib/legion/crypt/spiffe.rb +14 -39
  22. data/lib/legion/crypt/vault/auth/jwt.rb +28 -0
  23. data/lib/legion/crypt/vault/auth/kerberos.rb +60 -0
  24. data/lib/legion/crypt/vault/auth/ldap.rb +29 -0
  25. data/lib/legion/crypt/vault/auth.rb +50 -0
  26. data/lib/legion/crypt/vault/client.rb +362 -0
  27. data/lib/legion/crypt/vault/cluster.rb +262 -0
  28. data/lib/legion/crypt/vault/entity.rb +79 -0
  29. data/lib/legion/crypt/vault/leases.rb +871 -0
  30. data/lib/legion/crypt/vault/operation.rb +29 -0
  31. data/lib/legion/crypt/vault/session.rb +405 -0
  32. data/lib/legion/crypt/vault.rb +21 -31
  33. data/lib/legion/crypt/version.rb +1 -1
  34. data/lib/legion/crypt.rb +152 -177
  35. metadata +27 -11
  36. data/lib/legion/crypt/kerberos_auth.rb +0 -119
  37. data/lib/legion/crypt/ldap_auth.rb +0 -48
  38. data/lib/legion/crypt/token_renewer.rb +0 -318
  39. data/lib/legion/crypt/vault_client.rb +0 -355
  40. data/lib/legion/crypt/vault_cluster.rb +0 -331
  41. data/lib/legion/crypt/vault_entity.rb +0 -78
  42. data/lib/legion/crypt/vault_jwt_auth.rb +0 -97
  43. data/lib/legion/crypt/vault_kerberos_auth.rb +0 -51
  44. data/lib/legion/crypt/vault_operation.rb +0 -27
  45. /data/lib/legion/crypt/{vault_renewer.rb → vault/renewer.rb} +0 -0
@@ -0,0 +1,362 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'faraday'
4
+ require 'legion/json'
5
+ require 'openssl'
6
+ require 'uri'
7
+
8
+ module Legion
9
+ module Crypt
10
+ module Vault
11
+ class HTTPError < StandardError
12
+ attr_reader :code, :errors, :address
13
+
14
+ def initialize(code:, errors: [], address: nil, **)
15
+ @code = Integer(code)
16
+ @errors = Array(errors)
17
+ @address = address
18
+ super("Vault HTTP #{@code}#{": #{@errors.join('; ')}" unless @errors.empty?}")
19
+ end
20
+ end
21
+
22
+ class HTTPClientError < HTTPError; end
23
+ class HTTPServerError < HTTPError; end
24
+
25
+ class Client
26
+ CONNECTION_ATTRIBUTES = %i[address ssl_verify ca cert key timeout].freeze
27
+
28
+ attr_reader(*CONNECTION_ATTRIBUTES, :logical, :sys, :auth_token, :token)
29
+ attr_accessor :namespace
30
+
31
+ def initialize(address:, token: nil, namespace: nil, tls: {}, timeout: 5, **)
32
+ @address = validate_address(address: address)
33
+ @timeout = validate_timeout(timeout: timeout)
34
+ @token = token
35
+ @namespace = namespace
36
+ @ssl_verify = tls[:verify] != false && tls[:verify].to_s != 'none'
37
+ @ca = tls[:ca]
38
+ @cert = tls[:cert]
39
+ @key = tls[:key]
40
+ @mutex = Mutex.new
41
+ @retired = false
42
+ @logical = Logical.new(client: self)
43
+ @sys = Sys.new(client: self)
44
+ @auth_token = AuthToken.new(client: self)
45
+ end
46
+
47
+ CONNECTION_ATTRIBUTES.each do |attribute|
48
+ define_method(:"#{attribute}=") do |value|
49
+ value = validate_address(address: value) if attribute == :address
50
+ value = validate_timeout(timeout: value) if attribute == :timeout
51
+ @mutex.synchronize do
52
+ return value if instance_variable_get(:"@#{attribute}") == value
53
+
54
+ previous = @connection
55
+ @connection = nil
56
+ instance_variable_set(:"@#{attribute}", value)
57
+ previous&.close
58
+ end
59
+ value
60
+ end
61
+ end
62
+
63
+ def token=(value)
64
+ @mutex.synchronize do
65
+ raise IOError, 'Vault client has been shut down' if @retired
66
+
67
+ @token = value
68
+ end
69
+ end
70
+
71
+ def kv(mount:, **)
72
+ KV.new(client: self, mount: mount)
73
+ end
74
+
75
+ def put(path:, body:, headers: {}, **)
76
+ request(method: :put, path: path, body: body, headers: headers) || {}
77
+ end
78
+
79
+ def request(method:, path:, body: nil, headers: {}, nil_on_not_found: false, **)
80
+ connection, request_headers, address = @mutex.synchronize do
81
+ raise IOError, 'Vault client has been shut down' if @retired
82
+
83
+ [@connection ||= build_connection, vault_headers(headers: headers), @address]
84
+ end
85
+ payload = body.is_a?(String) || body.nil? ? body : Legion::JSON.dump(body)
86
+ response = connection.run_request(method, request_path(path: path), payload, request_headers)
87
+ return nil if nil_on_not_found && response.status == 404
88
+
89
+ decode_response(response: response, address: address)
90
+ end
91
+
92
+ def shutdown
93
+ @mutex.synchronize do
94
+ @retired = true
95
+ previous = @connection
96
+ @connection = nil
97
+ previous&.close
98
+ end
99
+ nil
100
+ end
101
+
102
+ def inspect
103
+ "#<#{self.class}>"
104
+ end
105
+
106
+ class Logical
107
+ def initialize(client:, **)
108
+ @client = client
109
+ end
110
+
111
+ def read(path:, **)
112
+ Secret.decode(data: @client.request(method: :get, path: path, nil_on_not_found: true))
113
+ end
114
+
115
+ def write(path:, data:, **)
116
+ Secret.decode(data: @client.put(path: path, body: data))
117
+ end
118
+
119
+ def delete(path:, **)
120
+ @client.request(method: :delete, path: path)
121
+ true
122
+ end
123
+ end
124
+
125
+ class Sys
126
+ class HealthStatus
127
+ def initialize(data:, **)
128
+ @initialized = data[:initialized]
129
+ end
130
+
131
+ def initialized?
132
+ @initialized == true
133
+ end
134
+ end
135
+
136
+ def initialize(client:, **)
137
+ @client = client
138
+ end
139
+
140
+ def health_status
141
+ HealthStatus.new(data: @client.request(method: :get, path: 'sys/health'))
142
+ end
143
+
144
+ def mounts
145
+ @client.request(method: :get, path: 'sys/mounts').fetch(:data)
146
+ end
147
+
148
+ def renew(lease_id:, **)
149
+ Secret.decode(data: @client.put(path: 'sys/leases/renew', body: { lease_id: lease_id }))
150
+ end
151
+
152
+ def revoke(lease_id:, **)
153
+ @client.put(path: 'sys/leases/revoke', body: { lease_id: lease_id })
154
+ true
155
+ end
156
+ end
157
+
158
+ class AuthToken
159
+ def initialize(client:, **)
160
+ @client = client
161
+ end
162
+
163
+ def renew_self
164
+ Secret.decode(data: @client.put(path: 'auth/token/renew-self', body: {}))
165
+ end
166
+
167
+ def revoke_self
168
+ @client.put(path: 'auth/token/revoke-self', body: {})
169
+ true
170
+ end
171
+ end
172
+
173
+ class KV
174
+ def initialize(client:, mount:, **)
175
+ @client = client
176
+ mount = mount.to_s
177
+ first = mount.index(%r{[^/]})
178
+ @mount = first ? mount[first..mount.rindex(%r{[^/]})] : ''
179
+ end
180
+
181
+ def read(path:, **)
182
+ response = @client.request(method: :get, path: "#{@mount}/data/#{path}", nil_on_not_found: true)
183
+ return nil if response.nil?
184
+
185
+ Secret.decode(data: response.merge(data: response.dig(:data, :data)))
186
+ end
187
+
188
+ def write(path:, data:, **)
189
+ Secret.decode(data: @client.put(path: "#{@mount}/data/#{path}", body: { data: data }))
190
+ end
191
+
192
+ def read_metadata(path:, **)
193
+ Secret.decode(data: @client.request(method: :get, path: "#{@mount}/metadata/#{path}", nil_on_not_found: true))
194
+ end
195
+ end
196
+
197
+ class Secret
198
+ attr_reader :data, :auth, :lease_id, :lease_duration
199
+
200
+ def self.decode(data:, **)
201
+ return nil if data.nil? || data.empty?
202
+
203
+ new(data: data)
204
+ end
205
+
206
+ def initialize(data:, **)
207
+ @data = data[:data]
208
+ @auth = Auth.new(data: data[:auth]) unless data[:auth].nil?
209
+ @lease_id = data[:lease_id]
210
+ @lease_duration = data[:lease_duration]
211
+ @renewable = data[:renewable]
212
+ end
213
+
214
+ def renewable?
215
+ @renewable == true
216
+ end
217
+
218
+ def inspect
219
+ "#<#{self.class}>"
220
+ end
221
+ end
222
+
223
+ class Auth
224
+ attr_reader :client_token, :accessor, :policies, :token_policies, :metadata,
225
+ :lease_duration, :entity_id, :token_type, :orphan, :num_uses
226
+
227
+ def initialize(data:, **)
228
+ @client_token = data[:client_token]
229
+ @accessor = data[:accessor]
230
+ @policies = data[:policies]
231
+ @token_policies = data[:token_policies]
232
+ @metadata = data[:metadata]
233
+ @lease_duration = data[:lease_duration]
234
+ @renewable = data[:renewable]
235
+ @entity_id = data[:entity_id]
236
+ @token_type = data[:token_type]
237
+ @orphan = data[:orphan]
238
+ @num_uses = data[:num_uses]
239
+ end
240
+
241
+ def renewable?
242
+ @renewable == true
243
+ end
244
+
245
+ def inspect
246
+ "#<#{self.class}>"
247
+ end
248
+ end
249
+
250
+ private
251
+
252
+ def validate_address(address:, **)
253
+ uri = URI.parse(address.to_s)
254
+ unless uri.is_a?(URI::HTTP) && uri.host && !uri.userinfo && !uri.query && !uri.fragment
255
+ raise ArgumentError, 'Vault address must be an HTTP(S) URL without credentials, query, or fragment'
256
+ end
257
+
258
+ uri.to_s.freeze
259
+ rescue URI::InvalidURIError
260
+ raise ArgumentError, 'Vault address must be a valid HTTP(S) URL'
261
+ end
262
+
263
+ def validate_timeout(timeout:, **)
264
+ seconds = Float(timeout)
265
+ raise ArgumentError, 'Vault timeout must be positive and finite' unless seconds.positive? && seconds.finite?
266
+
267
+ seconds
268
+ end
269
+
270
+ def vault_headers(headers:, **)
271
+ result = Faraday::Utils::Headers.new('Accept' => 'application/json', 'Content-Type' => 'application/json')
272
+ result.update(headers)
273
+ result.delete('X-Vault-Token')
274
+ result.delete('X-Vault-Namespace')
275
+ result['X-Vault-Token'] = @token unless @token.nil?
276
+ result['X-Vault-Namespace'] = @namespace unless @namespace.nil?
277
+ result
278
+ end
279
+
280
+ def request_path(path:, **)
281
+ relative = path.to_s.sub(%r{\A/v1(?:/|\z)}, '').sub(%r{\A/+}, '')
282
+ encoded = relative.split('/', -1).map do |segment|
283
+ if ['.', '..'].include?(segment)
284
+ segment.gsub('.', '%2E')
285
+ else
286
+ URI.encode_www_form_component(segment).gsub('+', '%20')
287
+ end
288
+ end
289
+ "/v1/#{encoded.join('/')}"
290
+ end
291
+
292
+ def build_connection
293
+ Faraday.new(url: @address, ssl: tls_options) do |connection|
294
+ connection.options.timeout = @timeout
295
+ connection.options.open_timeout = @timeout
296
+ connection.options.read_timeout = @timeout
297
+ connection.options.write_timeout = @timeout
298
+ connection.adapter :net_http
299
+ end
300
+ end
301
+
302
+ def tls_options
303
+ options = { verify: @ssl_verify != false && @ssl_verify.to_s != 'none' }
304
+ if @ca
305
+ if @ca.include?('-----BEGIN')
306
+ store = OpenSSL::X509::Store.new
307
+ certificates = @ca.scan(/-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----/m)
308
+ raise ArgumentError, 'Vault CA PEM contains no certificates' if certificates.empty?
309
+
310
+ certificates.each { |certificate| store.add_cert(OpenSSL::X509::Certificate.new(certificate)) }
311
+ options[:cert_store] = store
312
+ else
313
+ options[:ca_file] = @ca
314
+ end
315
+ end
316
+ options[:client_cert] = tls_certificate(certificate: @cert) if @cert
317
+ options[:client_key] = tls_key(key: @key) if @key
318
+ options
319
+ end
320
+
321
+ def tls_certificate(certificate:, **)
322
+ return certificate if certificate.is_a?(OpenSSL::X509::Certificate)
323
+
324
+ pem = certificate.include?('-----BEGIN') ? certificate : File.read(certificate)
325
+ certificates = pem.scan(/-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----/m)
326
+ return OpenSSL::X509::Certificate.new(pem) if certificates.length < 2
327
+
328
+ certificates.map { |entry| OpenSSL::X509::Certificate.new(entry) }
329
+ end
330
+
331
+ def tls_key(key:, **)
332
+ return key if key.is_a?(OpenSSL::PKey::PKey)
333
+
334
+ OpenSSL::PKey.read(key.include?('-----BEGIN') ? key : File.read(key))
335
+ end
336
+
337
+ def decode_response(response:, address:, **)
338
+ status = response.status
339
+ unless (200..299).cover?(status)
340
+ error_class = if (400..499).cover?(status)
341
+ Legion::Crypt::Vault::HTTPClientError
342
+ elsif (500..599).cover?(status)
343
+ Legion::Crypt::Vault::HTTPServerError
344
+ else
345
+ Legion::Crypt::Vault::HTTPError
346
+ end
347
+ begin
348
+ decoded = response.body.nil? || response.body.empty? ? {} : Legion::JSON.load(response.body)
349
+ rescue Legion::JSON::ParseError
350
+ raise error_class.new(code: status, errors: [response.body.to_s], address: address)
351
+ end
352
+ errors = decoded.is_a?(Hash) ? decoded[:errors] : [response.body.to_s]
353
+ raise error_class.new(code: status, errors: errors, address: address)
354
+ end
355
+ return nil if status == 204 || response.body.nil? || response.body.empty?
356
+
357
+ Legion::JSON.load(response.body)
358
+ end
359
+ end
360
+ end
361
+ end
362
+ end
@@ -0,0 +1,262 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'legion/logging/helper'
4
+ require 'uri'
5
+ require 'legion/crypt/vault/client'
6
+ require 'legion/crypt/tls'
7
+ require 'legion/crypt/vault/operation'
8
+
9
+ module Legion
10
+ module Crypt
11
+ module Vault
12
+ class GrantRejectedError < RuntimeError; end
13
+
14
+ module Cluster
15
+ include Legion::Logging::Helper
16
+
17
+ def vault_client(name = nil)
18
+ name = resolve_cluster_name(name)
19
+ loop do
20
+ candidate = accepted = nil
21
+ signature, generation = vault_clients_mutex.synchronize do
22
+ return @vault_clients&.dig(name, :client) if Legion::Crypt.respond_to?(:stopping) && Legion::Crypt.stopping
23
+
24
+ @vault_clients ||= {}
25
+ entry = @vault_clients[name]
26
+ signature = vault_client_signature(config: name.nil? ? Legion::Settings[:crypt][:vault] : clusters[name])
27
+ cached = cached_vault_client(entry: entry, signature: signature)
28
+ return cached if cached
29
+
30
+ unless signature
31
+ (@retired_vault_clients ||= ObjectSpace::WeakMap.new)[entry[:client]] = true if entry
32
+ @vault_clients.delete(name)
33
+ return nil
34
+ end
35
+ signature.transform_values! { |value| value.is_a?(String) ? value.dup.freeze : value }
36
+ [signature, @vault_client_generation || 0]
37
+ end
38
+ candidate = build_vault_client(signature, name: name)
39
+ accepted = install_vault_client(name: name, signature: signature, client: candidate, generation: generation)
40
+ return accepted if accepted
41
+ ensure
42
+ retire_vault_client(client: candidate) unless accepted.equal?(candidate)
43
+ end
44
+ end
45
+
46
+ # Resolves the configuration by cluster name so settings rebuilds do not reject the grant.
47
+ def publish_vault_grant(cluster_name:, client:, grant:, auth_method:, issued_at: Time.now, current_token: nil, **)
48
+ token = grant.fetch(:token)
49
+ ttl = grant[:lease_duration].to_f
50
+ expires_at = issued_at + ttl if ttl.positive?
51
+ vault_clients_mutex.synchronize do
52
+ config = cluster_name.nil? ? Legion::Settings[:crypt][:vault] : clusters[cluster_name]
53
+ entry = @vault_clients&.[](cluster_name)
54
+ unless entry && entry[:client].equal?(client) && current_vault_client?(entry: entry, signature: vault_client_signature(config: config))
55
+ raise Legion::Crypt::Vault::GrantRejectedError, 'Vault client configuration changed during authentication'
56
+ end
57
+ raise Legion::Crypt::Vault::GrantRejectedError, 'Vault token changed during authentication' if current_token && config[:token] != current_token
58
+
59
+ client.token = token
60
+ connected = expires_at.nil? || expires_at > Time.now
61
+ config.merge!(token: token, lease_duration: grant[:lease_duration], renewable: grant[:renewable],
62
+ expires_at: expires_at, connected: connected, relogin_required: !connected, auth_method: auth_method)
63
+ entry[:signature][:token] = token.dup.freeze
64
+ sync_vault_connected
65
+ end
66
+ expires_at
67
+ end
68
+
69
+ def disconnect_vault_grant(cluster_name:, token:, relogin_required:, **)
70
+ vault_clients_mutex.synchronize do
71
+ config = cluster_name.nil? ? Legion::Settings[:crypt][:vault] : clusters[cluster_name]
72
+ next false unless config && config[:token] == token
73
+
74
+ config.merge!(connected: false, relogin_required: relogin_required)
75
+ sync_vault_connected
76
+ true
77
+ end
78
+ end
79
+
80
+ # Uses a separate client so the token is revoked with its own credentials, not the client's current token.
81
+ def revoke_vault_token(client:, token:, deadline: nil, **)
82
+ revoker = Legion::Crypt::Vault::Client.new(
83
+ address: client.address, namespace: client.namespace, token: token, timeout: client.timeout,
84
+ tls: { verify: client.ssl_verify, ca: client.ca, cert: client.cert, key: client.key }
85
+ )
86
+ Legion::Crypt::Vault::Operation.with_timeout(deadline: deadline) { revoker.auth_token.revoke_self }
87
+ ensure
88
+ revoker&.shutdown
89
+ end
90
+
91
+ def clear_vault_clients(deadline: nil, **)
92
+ deadline ||= ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) + Legion::Crypt::Vault::Operation::SHUTDOWN_TIMEOUT
93
+ clients = vault_clients_mutex.synchronize do
94
+ @vault_client_generation = (@vault_client_generation || 0) + 1
95
+ previous = (@vault_clients || {}).values.map { |entry| entry[:client] }
96
+ previous.concat(@retired_vault_clients.keys) if @retired_vault_clients
97
+ @vault_clients = {}
98
+ @retired_vault_clients = nil
99
+ previous.uniq
100
+ end
101
+ clients.each { |client| retire_vault_client(client: client, deadline: deadline) }
102
+ end
103
+
104
+ def cluster(name = nil)
105
+ name = resolve_cluster_name(name)
106
+ clusters[name]
107
+ end
108
+
109
+ def default_cluster_name
110
+ name = Legion::Settings[:crypt][:vault][:default]
111
+ name ? name.to_sym : clusters.keys.first
112
+ end
113
+
114
+ def clusters
115
+ Legion::Settings[:crypt][:vault][:clusters]
116
+ end
117
+
118
+ def connected_clusters
119
+ vault_clients_mutex.synchronize { connected_cluster_configs }
120
+ end
121
+
122
+ private
123
+
124
+ # Caller holds vault_clients_mutex.
125
+ def connected_cluster_configs
126
+ now = Time.now
127
+ clusters.select do |_, config|
128
+ config[:token] && config[:connected] && !config[:relogin_required] &&
129
+ (!config[:expires_at] || config[:expires_at] > now)
130
+ end
131
+ end
132
+
133
+ # Caller holds vault_clients_mutex. LegionIO and extensions read the top-level flag directly,
134
+ # so named clusters keep it current; a single cluster publishes straight into the top level.
135
+ def sync_vault_connected
136
+ Legion::Settings[:crypt][:vault][:connected] = connected_cluster_configs.any? unless clusters.empty?
137
+ end
138
+
139
+ def selected_connected_cluster_name(name = nil)
140
+ active_clusters = connected_clusters
141
+ return nil if active_clusters.empty?
142
+
143
+ if name
144
+ cluster_name = name.to_sym
145
+ raise ArgumentError, "Vault cluster not connected: #{cluster_name}" unless active_clusters.key?(cluster_name)
146
+
147
+ return cluster_name
148
+ end
149
+
150
+ default_name = Legion::Settings[:crypt][:vault][:default]&.to_sym
151
+ return default_name if default_name && active_clusters.key?(default_name)
152
+
153
+ active_clusters.keys.first
154
+ end
155
+
156
+ def resolve_cluster_name(name)
157
+ return name.to_sym if name
158
+
159
+ default_cluster_name
160
+ end
161
+
162
+ def vault_clients_mutex
163
+ @vault_clients_mutex ||= Mutex.new
164
+ end
165
+
166
+ def current_vault_client?(entry:, signature:, **)
167
+ return false unless entry && signature
168
+ return false unless entry[:signature].all? { |key, value| key == :token || value == signature[key] }
169
+
170
+ entry[:signature][:token] == signature[:token] || entry[:client].token == signature[:token]
171
+ end
172
+
173
+ def cached_vault_client(entry:, signature:, **)
174
+ return unless current_vault_client?(entry: entry, signature: signature)
175
+
176
+ entry[:signature][:token] = signature[:token]&.dup if entry[:signature][:token] != signature[:token]
177
+ entry[:client]
178
+ end
179
+
180
+ def install_vault_client(name:, signature:, client:, generation:, **)
181
+ vault_clients_mutex.synchronize do
182
+ raise IOError, 'Vault clients cleared during construction' unless generation == (@vault_client_generation || 0)
183
+ raise IOError, 'Crypt stopped during client construction' if Legion::Crypt.respond_to?(:stopping) && Legion::Crypt.stopping
184
+
185
+ entry = @vault_clients[name]
186
+ current_signature = vault_client_signature(config: name.nil? ? Legion::Settings[:crypt][:vault] : clusters[name])
187
+ cached = cached_vault_client(entry: entry, signature: current_signature)
188
+ return cached if cached
189
+ return unless signature == current_signature
190
+
191
+ (@retired_vault_clients ||= ObjectSpace::WeakMap.new)[entry[:client]] = true if entry
192
+ @vault_clients[name] = { client: client, signature: signature }
193
+ client
194
+ end
195
+ end
196
+
197
+ def resolve_vault_address(vault_settings:, **)
198
+ protocol = vault_settings[:protocol] || 'http'
199
+ address = vault_settings[:address] || 'localhost'
200
+ port = vault_settings[:port] || 8200
201
+
202
+ if address.match?(%r{\Ahttps?://})
203
+ uri = URI.parse(address)
204
+ protocol = uri.scheme
205
+ address = uri.host
206
+ port = uri.port if vault_settings[:port].nil?
207
+ end
208
+
209
+ "#{protocol}://#{address}:#{port}"
210
+ end
211
+
212
+ def vault_client_signature(config:, **)
213
+ return unless config.is_a?(Hash)
214
+
215
+ tls = Legion::Crypt::TLS.migrate_legacy(config[:tls] || {})
216
+ verify = %w[none mutual].include?(tls[:verify].to_s) ? tls[:verify].to_s : 'peer'
217
+
218
+ namespace =
219
+ if config.key?(:namespace)
220
+ config[:namespace]
221
+ else
222
+ Legion::Settings[:crypt][:vault][:vault_namespace]
223
+ end
224
+ {
225
+ address: resolve_vault_address(vault_settings: config), namespace: namespace, token: config[:token],
226
+ verify: verify, ca: tls[:ca], cert: tls[:cert], key: tls[:key],
227
+ timeout: Legion::Settings[:crypt][:vault][:operation_timeout]
228
+ }
229
+ end
230
+
231
+ def build_vault_client(signature, name:)
232
+ building = Thread.current[:legion_vault_clients_building] ||= []
233
+ build_key = [self, name]
234
+ raise IOError, 'Circular Vault TLS material dependency' if building.include?(build_key)
235
+
236
+ building << build_key
237
+ begin
238
+ tls = Legion::Crypt::TLS.resolve(signature.slice(:verify, :ca, :cert, :key))
239
+ %i[ca cert key].each do |attribute|
240
+ raise IOError, "Configured Vault TLS #{attribute} could not be resolved" if signature[attribute] && tls[attribute].nil?
241
+ end
242
+ options = signature.slice(:address, :namespace, :token, :timeout).merge(tls: tls)
243
+ log.info "Building Vault client address=#{options[:address]} namespace=#{options[:namespace].inspect} tls_verify=#{tls[:verify]}"
244
+ Legion::Crypt::Vault::Client.new(**options)
245
+ ensure
246
+ building.delete(build_key)
247
+ end
248
+ end
249
+
250
+ def retire_vault_client(client:, deadline: nil, **)
251
+ return unless client.respond_to?(:shutdown)
252
+
253
+ Legion::Crypt::Vault::Operation.with_timeout(deadline: deadline) do
254
+ client.shutdown
255
+ end
256
+ rescue StandardError => e
257
+ handle_exception(e, level: :warn, operation: 'crypt.vault_cluster.retire_vault_client')
258
+ end
259
+ end
260
+ end
261
+ end
262
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'legion/logging/helper'
4
+ require 'legion/crypt/vault/client'
5
+
6
+ module Legion
7
+ module Crypt
8
+ module Vault
9
+ module Entity
10
+ extend Legion::Logging::Helper
11
+
12
+ # Create or lookup a Vault entity for a Legion principal.
13
+ # Returns the Vault entity ID string, or nil on failure.
14
+ def self.ensure_entity(principal_id:, canonical_name:, metadata: {})
15
+ existing = find_by_name(canonical_name: canonical_name)
16
+ return existing if existing
17
+
18
+ response = Legion::Crypt.vault_client.logical.write(
19
+ path: 'identity/entity',
20
+ data: {
21
+ name: "legion-#{canonical_name}",
22
+ metadata: metadata.merge(
23
+ legion_principal_id: principal_id,
24
+ legion_canonical_name: canonical_name,
25
+ managed_by: 'legion'
26
+ )
27
+ }
28
+ )
29
+ extract_id(response)
30
+ rescue StandardError => e
31
+ handle_exception(e, level: :warn, operation: 'crypt.vault_entity.ensure_entity', canonical_name: canonical_name)
32
+ nil
33
+ end
34
+
35
+ # Create an alias linking an auth method mount to the entity.
36
+ # Idempotent — swallows "already exists" 4xx errors.
37
+ def self.ensure_alias(entity_id:, mount_accessor:, alias_name:)
38
+ Legion::Crypt.vault_client.logical.write(
39
+ path: 'identity/entity-alias',
40
+ data: { name: alias_name, canonical_id: entity_id, mount_accessor: mount_accessor }
41
+ )
42
+ rescue Legion::Crypt::Vault::HTTPClientError => e
43
+ if e.message.include?('already exists')
44
+ log.debug 'Vault entity alias already exists (idempotent)'
45
+ else
46
+ handle_exception(e, level: :warn, operation: 'crypt.vault_entity.ensure_alias', alias_name: alias_name)
47
+ end
48
+ nil
49
+ rescue StandardError => e
50
+ handle_exception(e, level: :warn, operation: 'crypt.vault_entity.ensure_alias', alias_name: alias_name)
51
+ nil
52
+ end
53
+
54
+ # Look up a Vault entity by its Legion canonical name.
55
+ # Returns the Vault entity ID string, or nil if not found.
56
+ def self.find_by_name(canonical_name:)
57
+ response = Legion::Crypt.vault_client.logical.read(path: "identity/entity/name/legion-#{canonical_name}")
58
+ extract_id(response)
59
+ rescue StandardError => e
60
+ handle_exception(e, level: :warn, operation: 'crypt.vault_entity.find_by_name', canonical_name: canonical_name)
61
+ nil
62
+ end
63
+
64
+ # ---------------------------------------------------------------------------
65
+ # Private helpers
66
+ # ---------------------------------------------------------------------------
67
+
68
+ # Extract the entity ID from the client's symbol-keyed response data.
69
+ def self.extract_id(response)
70
+ data = response&.data
71
+ return nil unless data
72
+
73
+ data[:id]
74
+ end
75
+ private_class_method :extract_id
76
+ end
77
+ end
78
+ end
79
+ end