legion-crypt 1.5.37 → 1.5.42

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