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
@@ -3,7 +3,7 @@
3
3
  require 'legion/logging/helper'
4
4
  require 'singleton'
5
5
  require 'timeout'
6
- require 'legion/crypt/vault_operation'
6
+ require 'legion/crypt/vault/operation'
7
7
 
8
8
  module Legion
9
9
  module Crypt
@@ -21,6 +21,8 @@ module Legion
21
21
  @owned_leases = {}
22
22
  @pending = {}
23
23
  @refs = {}
24
+ @ref_bindings = {}
25
+ @installations = {}.compare_by_identity
24
26
  @lease_locks = {}
25
27
  @state_mutex = Mutex.new
26
28
  @wake = ConditionVariable.new
@@ -76,13 +78,43 @@ module Legion
76
78
  def register_ref(name, key, path, generation: @generation)
77
79
  return false unless path.is_a?(Array) && !path.empty?
78
80
 
81
+ name = name.to_sym
82
+ key = key.to_sym
79
83
  with_current_state(generation: generation) do
80
- @refs[name.to_sym] ||= {}
81
- destinations = (@refs[name.to_sym][key.to_sym] ||= [])
84
+ @refs.delete_if do |registered_name, keys|
85
+ keys.delete_if do |registered_key, destinations|
86
+ @ref_bindings.delete(path) if !(registered_name == name && registered_key == key) && destinations.delete(path)
87
+ destinations.empty?
88
+ end
89
+ keys.empty?
90
+ end
91
+ @refs[name] ||= {}
92
+ destinations = (@refs[name][key] ||= [])
82
93
  destinations << path.dup.freeze unless destinations.include?(path)
83
94
  end
84
95
  end
85
96
 
97
+ # Preparation and publication must only perform in-memory work, without calling manager methods.
98
+ def update_settings_refs(settings:, publish: nil)
99
+ raise ArgumentError, 'Settings reference preparation requires a block' unless block_given?
100
+
101
+ @state_mutex.synchronize do
102
+ raise 'Cannot publish settings from an in-flight lease reconnect' if @installations.value?(Thread.current)
103
+
104
+ generation = @generation
105
+ @wake.wait(@state_mutex) while !@installations.empty? && lifecycle_current?(generation: generation)
106
+ raise 'Cannot update settings references in an inactive lifecycle' unless lifecycle_current?(generation: generation)
107
+
108
+ reader = lambda do |name:, key:|
109
+ data = cached_lease_data(name: name.to_sym)
110
+ data && (data.key?(key.to_sym) ? data[key.to_sym] : data[key.to_s])
111
+ end
112
+ proposal = yield reader
113
+ apply_settings_proposal(settings: settings, proposal: proposal, publish: publish)
114
+ proposal
115
+ end
116
+ end
117
+
86
118
  def push_to_settings(name, generation: @generation, active: nil)
87
119
  count = with_current_state(generation: generation, active: active) do
88
120
  refs = @refs[name.to_sym]
@@ -157,7 +189,7 @@ module Legion
157
189
 
158
190
  def start_renewal_thread
159
191
  previous = @state_mutex.synchronize { @renewal_thread if @renewal_generation != @generation }
160
- Legion::Crypt::VaultOperation.with_timeout { previous.join } if previous&.alive?
192
+ Legion::Crypt::Vault::Operation.with_timeout { previous.join } if previous&.alive?
161
193
  @state_mutex.synchronize do
162
194
  return if @renewal_thread&.alive? || @stopped
163
195
  return if Legion::Crypt.respond_to?(:stopping) && Legion::Crypt.stopping
@@ -186,12 +218,13 @@ module Legion
186
218
  end
187
219
 
188
220
  def shutdown(deadline: nil)
189
- deadline ||= monotonic_now + Legion::Crypt::VaultOperation::SHUTDOWN_TIMEOUT
221
+ deadline ||= monotonic_now + Legion::Crypt::Vault::Operation::SHUTDOWN_TIMEOUT
190
222
  request_stop
191
223
  @state_mutex.synchronize do
192
224
  @active_leases.clear
193
225
  @lease_cache.clear
194
226
  @refs.clear
227
+ @ref_bindings.clear
195
228
  @pending.clear
196
229
  @vault_client = nil
197
230
  @owned_leases.each_value { |entry| entry[:retired] = true }
@@ -209,6 +242,7 @@ module Legion
209
242
  @owned_leases.clear
210
243
  @pending.clear
211
244
  @refs.clear
245
+ @ref_bindings.clear
212
246
  @vault_client = nil
213
247
  @stopped = false
214
248
  end
@@ -216,6 +250,113 @@ module Legion
216
250
 
217
251
  private
218
252
 
253
+ def apply_settings_proposal(settings:, proposal:, publish:)
254
+ validate_settings_proposal!(settings: settings, proposal: proposal)
255
+ references, bindings = settings_reference_registry(settings: settings, proposal: proposal)
256
+ assignments = proposal[:assignments].map do |assignment|
257
+ [assignment[:container], assignment[:key], assignment[:container][assignment[:key]], assignment[:value]]
258
+ end
259
+ binding_values = proposal[:references].map { |reference| [reference[:binding], reference[:binding][:value]] }
260
+ previous_refs = @refs
261
+ previous_bindings = @ref_bindings
262
+ begin
263
+ assignments.each { |container, key, _previous, value| container[key] = value }
264
+ @refs = references
265
+ @ref_bindings = bindings
266
+ publish_settings_proposal(settings: settings, proposal: proposal, publish: publish)
267
+ rescue StandardError
268
+ @refs = previous_refs
269
+ @ref_bindings = previous_bindings
270
+ assignments.reverse_each { |container, key, previous, _value| container[key] = previous }
271
+ binding_values.each { |binding, previous| binding[:value] = previous }
272
+ raise
273
+ end
274
+ end
275
+
276
+ def settings_reference_registry(settings:, proposal:)
277
+ paths = proposal[:paths]
278
+ references = @refs.each_with_object({}) do |(name, keys), result|
279
+ remaining = keys.transform_values { |destinations| destinations.reject { |path| paths.include?(path) } }
280
+ remaining.reject! { |_key, destinations| destinations.empty? }
281
+ result[name] = remaining unless remaining.empty?
282
+ end
283
+ bindings = @ref_bindings.except(*paths)
284
+ proposal[:references].each do |reference|
285
+ name = reference[:name].to_sym
286
+ key = reference[:key].to_sym
287
+ path = reference[:path].dup.freeze
288
+ references[name] ||= {}
289
+ (references[name][key] ||= []) << path
290
+ bindings[path] = { settings: settings, binding: reference[:binding] }
291
+ end
292
+ [references, bindings]
293
+ end
294
+
295
+ def publish_settings_proposal(settings:, proposal:, publish:)
296
+ proposal[:references].each do |reference|
297
+ target, key = setting_target(path: reference[:path], settings: settings)
298
+ raise ArgumentError, 'Settings assignment removed a reference destination' unless target
299
+
300
+ reference[:binding][:value] = target[key]
301
+ end
302
+ publish&.call(proposal)
303
+ return unless defined?(Legion::Settings) && Legion::Settings.respond_to?(:loader) && Legion::Settings.loader&.settings.equal?(settings)
304
+
305
+ proposal[:references].each { |reference| @ref_bindings[reference[:path]][:settings] = nil }
306
+ end
307
+
308
+ def validate_settings_proposal!(settings:, proposal:)
309
+ raise ArgumentError, 'Settings root must be a Hash or Array' unless settings.is_a?(Hash) || settings.is_a?(Array)
310
+ unless proposal.is_a?(Hash) && %i[paths assignments references].all? { |key| proposal[key].is_a?(Array) }
311
+ raise ArgumentError, 'Invalid settings reference proposal'
312
+ end
313
+
314
+ proposal[:paths].each do |path|
315
+ unless path.is_a?(Array) && !path.empty? && path.all? { |part| part.is_a?(Symbol) || (part.is_a?(Integer) && part >= 0) }
316
+ raise ArgumentError, 'Invalid typed settings path'
317
+ end
318
+ end
319
+ validate_settings_assignments!(assignments: proposal[:assignments])
320
+ validate_settings_references!(settings: settings, paths: proposal[:paths], references: proposal[:references])
321
+ end
322
+
323
+ def validate_settings_assignments!(assignments:)
324
+ destinations = {}
325
+ assignments.each do |assignment|
326
+ raise ArgumentError, 'Invalid settings assignment' unless assignment.is_a?(Hash) && assignment.key?(:value)
327
+
328
+ container = assignment[:container]
329
+ key = assignment[:key]
330
+ raise ArgumentError, 'Unwritable settings assignment' unless valid_setting_key?(container: container, key: key) && !container.frozen?
331
+ raise ArgumentError, 'Duplicate settings assignment' if destinations[[container.object_id, key]]
332
+
333
+ destinations[[container.object_id, key]] = true
334
+ end
335
+ end
336
+
337
+ def validate_settings_references!(settings:, paths:, references:)
338
+ destinations = {}
339
+ binding_ids = {}.compare_by_identity
340
+ references.each do |reference|
341
+ unless reference.is_a?(Hash) && paths.include?(reference[:path]) &&
342
+ [reference[:name], reference[:key]].all? { |value| value.is_a?(String) || value.is_a?(Symbol) }
343
+ raise ArgumentError, 'Invalid settings reference'
344
+ end
345
+
346
+ target, key = setting_target(path: reference[:path], settings: settings)
347
+ raise ArgumentError, 'Unwritable settings reference destination' unless target
348
+ raise ArgumentError, 'Ambiguous settings reference destination' if destinations[[target.object_id, key]]
349
+
350
+ binding = reference[:binding]
351
+ unless binding.is_a?(Hash) && !binding.frozen? && binding.key?(:value) && !binding_ids[binding]
352
+ raise ArgumentError, 'Settings references require distinct mutable binding records'
353
+ end
354
+
355
+ destinations[[target.object_id, key]] = true
356
+ binding_ids[binding] = true
357
+ end
358
+ end
359
+
219
360
  def register_at_exit_hook
220
361
  return if @at_exit_registered
221
362
 
@@ -235,7 +376,7 @@ module Legion
235
376
 
236
377
  def with_lease_operation(name:, deadline: nil, **)
237
378
  lock = @state_mutex.synchronize { @lease_locks[name] ||= Mutex.new }
238
- Legion::Crypt::VaultOperation.with_timeout(deadline: deadline) do |operation_deadline|
379
+ Legion::Crypt::Vault::Operation.with_timeout(deadline: deadline) do |operation_deadline|
239
380
  lock.synchronize { yield operation_deadline }
240
381
  end
241
382
  end
@@ -310,7 +451,14 @@ module Legion
310
451
  end
311
452
  committed
312
453
  ensure
313
- abort_install(handoff: handoff) if handoff && !committed
454
+ begin
455
+ abort_install(handoff: handoff) if handoff && !committed
456
+ ensure
457
+ @state_mutex.synchronize do
458
+ @installations.delete(candidate)
459
+ @wake.broadcast
460
+ end
461
+ end
314
462
  retire_unused_leases(name: name, deadline: context[:deadline])
315
463
  end
316
464
 
@@ -330,10 +478,15 @@ module Legion
330
478
  snapshots = setting_snapshots(name: name, data: data)
331
479
  transaction = { previous: previous, data: @lease_cache[name], settings: snapshots, candidate: handoff[:candidate] }
332
480
  handoff[:transaction] = transaction
333
- snapshots.each { |target, key, _old, value| target[key] = value }
481
+ @installations[handoff[:candidate]] = Thread.current
482
+ snapshots.each do |target, key, old, value, binding|
483
+ target[key] = value unless old == value
484
+ binding[:value] = value if binding
485
+ end
334
486
  @lease_cache[name] = data
335
487
  @active_leases[name] = handoff[:candidate]
336
- handoff[:reconnect] = context[:reconnect] || (previous && transaction[:data] != data) || !snapshots.empty?
488
+ handoff[:reconnect] = context[:reconnect] || (previous && transaction[:data] != data) ||
489
+ snapshots.any? { |_target, _key, old, value| old != value }
337
490
  true
338
491
  end
339
492
  end
@@ -357,7 +510,7 @@ module Legion
357
510
  safe_to_retire = !handoff[:attempted_reconnect] || !lifecycle_current?(generation: generation, active: active)
358
511
  if handoff[:attempted_reconnect] && restored
359
512
  begin
360
- safe_to_retire = Legion::Crypt::VaultOperation.with_timeout(deadline: context[:deadline]) do
513
+ safe_to_retire = Legion::Crypt::Vault::Operation.with_timeout(deadline: context[:deadline]) do
361
514
  trigger_reconnect(name, generation: generation, active: active)
362
515
  end
363
516
  rescue StandardError => e
@@ -376,11 +529,15 @@ module Legion
376
529
 
377
530
  value = data.key?(key) ? data[key] : data[key.to_s]
378
531
  paths.filter_map do |path|
379
- target, segment = setting_target(path: path)
532
+ record = @ref_bindings[path]
533
+ target, segment = setting_target(path: path, settings: record&.dig(:settings))
380
534
  raise "Lease #{name} has an unwritable settings destination #{path.inspect}" unless target
381
- next if target[segment] == value
382
535
 
383
- [target, segment, target[segment], value]
536
+ binding = record&.dig(:binding)
537
+ raise "Lease #{name} has an immutable settings binding" if binding&.frozen?
538
+ next if target[segment] == value && (!binding || binding[:value] == value)
539
+
540
+ [target, segment, target[segment], value, binding, binding&.dig(:value)]
384
541
  end
385
542
  end
386
543
  end
@@ -392,8 +549,10 @@ module Legion
392
549
  current = @active_leases[name]
393
550
  next false unless current.equal?(transaction[:candidate]) || current.equal?(transaction[:previous])
394
551
 
395
- transaction[:settings].each do |target, key, previous, candidate|
552
+ transaction[:settings].each do |snapshot|
553
+ target, key, previous, candidate, binding, previous_binding = snapshot
396
554
  target[key] = previous if target[key] == candidate
555
+ binding[:value] = previous_binding if binding && binding[:value] == candidate
397
556
  end
398
557
  if transaction[:previous]
399
558
  @active_leases[name] = transaction[:previous]
@@ -443,7 +602,7 @@ module Legion
443
602
  end
444
603
  return unless entry
445
604
 
446
- Legion::Crypt::VaultOperation.with_timeout(deadline: deadline) { entry[:client].sys.revoke(lease_id: entry[:lease_id]) }
605
+ Legion::Crypt::Vault::Operation.with_timeout(deadline: deadline) { entry[:client].sys.revoke(lease_id: entry[:lease_id]) }
447
606
  @state_mutex.synchronize { @owned_leases.delete(key) if @owned_leases[key].equal?(entry) }
448
607
  rescue StandardError => e
449
608
  handle_exception(e, level: :warn, operation: 'crypt.lease_manager.revoke_owned_lease', lease_name: entry&.dig(:name))
@@ -461,7 +620,7 @@ module Legion
461
620
  thread = request_stop
462
621
  return unless thread
463
622
 
464
- Legion::Crypt::VaultOperation.with_timeout(deadline: deadline) { thread.join }
623
+ Legion::Crypt::Vault::Operation.with_timeout(deadline: deadline) { thread.join }
465
624
  @state_mutex.synchronize { @renewal_thread = nil if @renewal_thread.equal?(thread) }
466
625
  rescue StandardError => e
467
626
  handle_exception(e, level: :warn, operation: 'crypt.lease_manager.stop_renewal_thread')
@@ -585,28 +744,34 @@ module Legion
585
744
  lease[:expires_at] - Time.now - (ttl * 0.5)
586
745
  end
587
746
 
588
- def setting_target(path:, **)
747
+ def setting_target(path:, settings: nil, **)
589
748
  return unless path.is_a?(Array) && !path.empty?
590
749
 
591
- target = Legion::Settings.get.settings
750
+ target = settings
751
+ target ||= Legion::Settings.loader&.settings if defined?(Legion::Settings) && Legion::Settings.respond_to?(:loader)
592
752
  path.each_with_index do |segment, index|
593
- valid =
594
- case target
595
- when Hash then segment.is_a?(Symbol) && target.key?(segment)
596
- when Array then segment.is_a?(Integer) && segment >= 0 && segment < target.length
597
- end
598
- return nil unless valid
753
+ return nil unless valid_setting_key?(container: target, key: segment)
599
754
  return target.frozen? ? nil : [target, segment] if index == path.length - 1
600
755
 
601
756
  target = target[segment]
602
757
  end
603
758
  end
604
759
 
760
+ def valid_setting_key?(container:, key:)
761
+ case container
762
+ when Hash then key.is_a?(Symbol) && container.key?(key)
763
+ when Array then key.is_a?(Integer) && key >= 0 && key < container.length
764
+ end
765
+ end
766
+
605
767
  def write_setting(path, value)
606
- target, key = setting_target(path: path)
607
- return false unless target
768
+ record = @ref_bindings[path]
769
+ target, key = setting_target(path: path, settings: record&.dig(:settings))
770
+ binding = record&.dig(:binding)
771
+ return false unless target && !binding&.frozen?
608
772
 
609
773
  target[key] = value
774
+ binding[:value] = value if binding
610
775
  true
611
776
  rescue StandardError => e
612
777
  handle_exception(e, level: :warn, operation: 'crypt.lease_manager.write_setting', path: path.inspect)
@@ -1,47 +1,31 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'legion/logging/helper'
4
+ require 'legion/crypt/settings'
4
5
  require 'socket'
5
6
 
6
7
  module Legion
7
8
  module Crypt
8
9
  module Mtls
9
- DEFAULT_PKI_PATH = 'pki/issue/legion-internal'
10
- DEFAULT_TTL = '24h'
11
10
  extend Legion::Logging::Helper
12
11
 
13
12
  class << self
14
13
  def enabled?
15
- security = safe_security_settings
16
- return false if security.nil?
17
-
18
- mtls = security[:mtls] || security['mtls']
19
- return false if mtls.nil?
20
-
21
- mtls[:enabled] || mtls['enabled'] || false
22
- end
23
-
24
- def pki_path
25
- security = safe_security_settings
26
- return DEFAULT_PKI_PATH if security.nil?
27
-
28
- mtls = security[:mtls] || security['mtls'] || {}
29
- mtls[:vault_pki_path] || mtls['vault_pki_path'] || DEFAULT_PKI_PATH
14
+ Legion::Settings[:crypt][:mtls][:enabled] == true
30
15
  end
31
16
 
32
- def issue_cert(common_name:, ttl: nil)
33
- resolved_ttl = ttl || cert_ttl_setting || DEFAULT_TTL
17
+ def issue_cert(common_name:, alt_names: '', ttl: nil, **)
18
+ pki_path = Legion::Settings[:crypt][:mtls][:vault_pki_path]
19
+ resolved_ttl = ttl.nil? ? Legion::Settings[:crypt][:mtls][:cert_ttl] : ttl
34
20
  log.info "[mTLS] certificate issue requested common_name=#{common_name} ttl=#{resolved_ttl}"
35
21
 
36
22
  response = Legion::Crypt.vault_client.logical.write(
37
23
  path: pki_path,
38
- data: { common_name: common_name, ttl: resolved_ttl, ip_sans: local_ip, alt_names: '' }
24
+ data: { common_name: common_name, ttl: resolved_ttl, ip_sans: local_ip, alt_names: alt_names }
39
25
  )
40
-
41
26
  raise "Vault PKI returned nil for #{pki_path} (common_name=#{common_name})" if response.nil?
42
27
 
43
28
  data = response.data
44
-
45
29
  {
46
30
  cert: data[:certificate],
47
31
  key: data[:private_key],
@@ -54,34 +38,12 @@ module Legion
54
38
  raise
55
39
  end
56
40
 
57
- def local_ip
41
+ def local_ip(**)
58
42
  Socket.ip_address_list.find { |a| a.ipv4? && !a.ipv4_loopback? }&.ip_address || '127.0.0.1'
59
- rescue StandardError => e
43
+ rescue SocketError, SystemCallError, IOError => e
60
44
  handle_exception(e, level: :warn, operation: 'crypt.mtls.local_ip')
61
45
  '127.0.0.1'
62
46
  end
63
-
64
- private
65
-
66
- def safe_security_settings
67
- return nil unless defined?(Legion::Settings)
68
-
69
- Legion::Settings[:security]
70
- rescue StandardError => e
71
- handle_exception(e, level: :debug, operation: 'crypt.mtls.safe_security_settings')
72
- nil
73
- end
74
-
75
- def cert_ttl_setting
76
- security = safe_security_settings
77
- return nil if security.nil?
78
-
79
- mtls = security[:mtls] || security['mtls'] || {}
80
- mtls[:cert_ttl] || mtls['cert_ttl']
81
- rescue StandardError => e
82
- handle_exception(e, level: :debug, operation: 'crypt.mtls.cert_ttl_setting')
83
- nil
84
- end
85
47
  end
86
48
  end
87
49
  end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require 'openssl'
4
4
  require 'legion/logging/helper'
5
+ require 'legion/crypt/settings'
5
6
 
6
7
  module Legion
7
8
  module Crypt
@@ -10,12 +11,7 @@ module Legion
10
11
 
11
12
  class << self
12
13
  def derive_key(master_key:, tenant_id:, context: nil)
13
- context ||= begin
14
- Legion::Settings[:crypt][:partition_keys][:derivation_context]
15
- rescue StandardError => e
16
- handle_exception(e, level: :debug, operation: 'crypt.partition_keys.derivation_context', tenant_id: tenant_id)
17
- nil
18
- end || 'legion-partition'
14
+ context = Legion::Settings[:crypt][:partition_keys][:derivation_context] if context.nil?
19
15
  log.debug "PartitionKeys deriving key for tenant #{tenant_id}"
20
16
  salt = OpenSSL::Digest::SHA256.digest(tenant_id.to_s)
21
17
  OpenSSL::KDF.hkdf(master_key, salt: salt, info: context, length: 32, hash: 'SHA256')
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'legion/logging/helper'
4
+ require 'legion/settings'
4
5
 
5
6
  module Legion
6
7
  module Crypt
@@ -17,6 +18,15 @@ module Legion
17
18
  }
18
19
  end
19
20
 
21
+ def self.mtls
22
+ {
23
+ enabled: false,
24
+ vault_pki_path: 'pki/issue/legion-internal',
25
+ cert_ttl: '24h',
26
+ renewal_window: 0.5
27
+ }
28
+ end
29
+
20
30
  def self.spiffe
21
31
  {
22
32
  enabled: false,
@@ -30,14 +40,19 @@ module Legion
30
40
 
31
41
  def self.default
32
42
  {
33
- vault: vault,
34
- jwt: jwt,
35
- tls: tls,
36
- cs_encrypt_ready: false,
37
- dynamic_keys: true,
38
- cluster_secret: nil,
39
- save_private_key: true,
40
- read_private_key: true
43
+ vault: vault,
44
+ jwt: jwt,
45
+ tls: tls,
46
+ mtls: mtls,
47
+ cs_encrypt_ready: false,
48
+ dynamic_keys: true,
49
+ cluster_secret: nil,
50
+ cluster_length: 32,
51
+ cluster_secret_timeout: 5,
52
+ save_private_key: true,
53
+ read_private_key: true,
54
+ ed25519: { vault_key_prefix: 'keys' },
55
+ partition_keys: { derivation_context: 'legion-partition', vault_tenant_prefix: 'secret/data/legion/tenants' }
41
56
  }
42
57
  end
43
58
 
@@ -87,16 +102,4 @@ module Legion
87
102
  end
88
103
  end
89
104
 
90
- begin
91
- if Legion.const_defined?('Settings')
92
- Legion::Settings.merge_settings('crypt', Legion::Crypt::Settings.default)
93
- Legion::Crypt::Settings.log.info('Legion::Crypt settings defaults merged')
94
- end
95
- rescue StandardError => e
96
- if Legion::Crypt::Settings.respond_to?(:handle_exception)
97
- Legion::Crypt::Settings.handle_exception(e, level: :fatal, operation: 'crypt.settings.merge_defaults')
98
- else
99
- puts e.message
100
- puts e.backtrace
101
- end
102
- end
105
+ Legion::Settings.register_library(:crypt, Legion::Crypt::Settings.default)
@@ -130,16 +130,13 @@ module Legion
130
130
  end
131
131
 
132
132
  def renewal_window
133
- return SVID_RENEWAL_RATIO unless defined?(Legion::Settings)
134
-
135
- security = Legion::Settings[:security]
136
- return SVID_RENEWAL_RATIO if security.nil?
133
+ window = Legion::Settings.dig(:security, :spiffe, :renewal_window)
134
+ window = SVID_RENEWAL_RATIO if window.nil?
135
+ unless window.is_a?(Numeric) && window.finite? && window >= 0 && window < 1
136
+ raise ArgumentError, 'SVID renewal window must be finite and between zero and one (exclusive)'
137
+ end
137
138
 
138
- spiffe = security[:spiffe] || security['spiffe'] || {}
139
- spiffe[:renewal_window] || spiffe['renewal_window'] || SVID_RENEWAL_RATIO
140
- rescue StandardError => e
141
- handle_exception(e, level: :debug, operation: 'crypt.spiffe.svid_rotation.renewal_window')
142
- SVID_RENEWAL_RATIO
139
+ window
143
140
  end
144
141
  end
145
142
  end
@@ -1,8 +1,12 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'legion/logging/helper'
4
3
  require 'uri'
5
4
  require 'openssl'
5
+ require 'legion/logging/helper'
6
+ require 'legion/crypt/settings'
7
+ require 'legion/crypt/spiffe/workload_api_client'
8
+ require 'legion/crypt/spiffe/svid_rotation'
9
+ require 'legion/crypt/spiffe/identity_helpers'
6
10
 
7
11
  module Legion
8
12
  module Crypt
@@ -10,7 +14,7 @@ module Legion
10
14
  SPIFFE_SCHEME = 'spiffe'
11
15
  DEFAULT_SOCKET_PATH = '/tmp/spire-agent/public/api.sock'
12
16
  DEFAULT_TRUST_DOMAIN = 'legion.internal'
13
- SVID_RENEWAL_RATIO = 0.5
17
+ SVID_RENEWAL_RATIO = 0.5
14
18
 
15
19
  class Error < StandardError; end
16
20
  class InvalidSpiffeIdError < Error; end
@@ -80,50 +84,30 @@ module Legion
80
84
  parse_id(spiffe_id_string)
81
85
  true
82
86
  rescue InvalidSpiffeIdError => e
83
- handle_exception(e, level: :debug, operation: 'crypt.spiffe.valid_id', spiffe_id: spiffe_id_string)
87
+ handle_exception(e, level: :warn, operation: 'crypt.spiffe.valid_id', spiffe_id: spiffe_id_string)
84
88
  false
85
89
  end
86
90
 
87
91
  def enabled?
88
- security = safe_security_settings
89
- return false if security.nil?
90
-
91
- spiffe = security[:spiffe] || security['spiffe']
92
- return false if spiffe.nil?
93
-
94
- spiffe[:enabled] || spiffe['enabled'] || false
92
+ Legion::Settings.dig(:security, :spiffe, :enabled) == true
95
93
  end
96
94
 
97
95
  def socket_path
98
- security = safe_security_settings
99
- return DEFAULT_SOCKET_PATH if security.nil?
100
-
101
- spiffe = security[:spiffe] || security['spiffe'] || {}
102
- spiffe[:socket_path] || spiffe['socket_path'] || DEFAULT_SOCKET_PATH
96
+ path = Legion::Settings.dig(:security, :spiffe, :socket_path)
97
+ path.nil? ? DEFAULT_SOCKET_PATH : path
103
98
  end
104
99
 
105
100
  def trust_domain
106
- security = safe_security_settings
107
- return DEFAULT_TRUST_DOMAIN if security.nil?
108
-
109
- spiffe = security[:spiffe] || security['spiffe'] || {}
110
- spiffe[:trust_domain] || spiffe['trust_domain'] || DEFAULT_TRUST_DOMAIN
101
+ domain = Legion::Settings.dig(:security, :spiffe, :trust_domain)
102
+ domain.nil? ? DEFAULT_TRUST_DOMAIN : domain
111
103
  end
112
104
 
113
105
  def workload_id
114
- security = safe_security_settings
115
- return nil if security.nil?
116
-
117
- spiffe = security[:spiffe] || security['spiffe'] || {}
118
- spiffe[:workload_id] || spiffe['workload_id']
106
+ Legion::Settings.dig(:security, :spiffe, :workload_id)
119
107
  end
120
108
 
121
109
  def allow_x509_fallback?
122
- security = safe_security_settings
123
- return false if security.nil?
124
-
125
- spiffe = security[:spiffe] || security['spiffe'] || {}
126
- spiffe[:allow_x509_fallback] || spiffe['allow_x509_fallback'] || false
110
+ Legion::Settings.dig(:security, :spiffe, :allow_x509_fallback) == true
127
111
  end
128
112
 
129
113
  private
@@ -138,15 +122,6 @@ module Legion
138
122
 
139
123
  raise InvalidSpiffeIdError, "SPIFFE ID must not contain userinfo, port, query, or fragment in '#{raw}'"
140
124
  end
141
-
142
- def safe_security_settings
143
- return nil unless defined?(Legion::Settings)
144
-
145
- Legion::Settings[:security]
146
- rescue StandardError => e
147
- handle_exception(e, level: :debug, operation: 'crypt.spiffe.safe_security_settings')
148
- nil
149
- end
150
125
  end
151
126
  end
152
127
  end