Module: Legion::Crypt

Extended by:
Cipher, LdapAuth, VaultCluster, Logging::Helper
Includes:
Vault
Defined in:
lib/legion/crypt.rb,
lib/legion/crypt/jwt.rb,
lib/legion/crypt/tls.rb,
lib/legion/crypt/mtls.rb,
lib/legion/crypt/vault.rb,
lib/legion/crypt/cipher.rb,
lib/legion/crypt/helper.rb,
lib/legion/crypt/spiffe.rb,
lib/legion/crypt/ed25519.rb,
lib/legion/crypt/erasure.rb,
lib/legion/crypt/version.rb,
lib/legion/crypt/settings.rb,
lib/legion/crypt/ldap_auth.rb,
lib/legion/crypt/mock_vault.rb,
lib/legion/crypt/attestation.rb,
lib/legion/crypt/jwks_client.rb,
lib/legion/crypt/vault_entity.rb,
lib/legion/crypt/cert_rotation.rb,
lib/legion/crypt/kerberos_auth.rb,
lib/legion/crypt/lease_manager.rb,
lib/legion/crypt/token_renewer.rb,
lib/legion/crypt/vault_cluster.rb,
lib/legion/crypt/vault_renewer.rb,
lib/legion/crypt/cluster_secret.rb,
lib/legion/crypt/partition_keys.rb,
lib/legion/crypt/vault_jwt_auth.rb,
lib/legion/crypt/vault_kerberos_auth.rb,
lib/legion/crypt/spiffe/svid_rotation.rb,
lib/legion/crypt/spiffe/identity_helpers.rb,
lib/legion/crypt/spiffe/workload_api_client.rb

Defined Under Namespace

Modules: Attestation, Cipher, ClusterSecret, Ed25519, Erasure, Helper, JWT, JwksClient, KerberosAuth, LdapAuth, MockVault, Mtls, PartitionKeys, Settings, Spiffe, TLS, Vault, VaultCluster, VaultEntity, VaultJwtAuth, VaultKerberosAuth Classes: CertRotation, LeaseManager, TokenRenewer

Constant Summary collapse

RMQ_ROLE_MAP =
{
  agent:  'legionio-infra',
  worker: 'legionio-worker',
  infra:  'legionio-infra'
}.freeze
VERSION =
'1.5.10'

Constants included from Cipher

Cipher::AUTHENTICATED_CIPHER, Cipher::AUTHENTICATED_PREFIX, Cipher::LEGACY_CIPHER, Cipher::RSA_LEGACY_PADDING, Cipher::RSA_OAEP_PADDING, Cipher::RSA_OAEP_PREFIX

Constants included from Logging::Helper

Logging::Helper::CompatLogger

Class Attribute Summary collapse

Attributes included from Vault

#sessions

Class Method Summary collapse

Methods included from Cipher

decrypt, decrypt_from_keypair, encrypt, encrypt_from_keypair, private_key, public_key

Methods included from Logging::Helper

handle_exception, log

Methods included from ClusterSecret

#cluster_secret_timeout, #cluster_secret_vault_path, #cs, #find_cluster_secret, #force_cluster_secret, #from_settings, #from_transport, #from_vault, #generate_secure_random, #only_member?, #push_cs_to_vault, #secret_length, #set_cluster_secret, #settings_push_vault, #validate_hex

Methods included from VaultCluster

cluster, clusters, connect_all_clusters, connected_clusters, default_cluster_name, vault_client

Methods included from LdapAuth

ldap_login, ldap_login_all

Methods included from Vault

#add_session, #close_session, #close_sessions, #connect_vault, #delete, #exist?, #get, #read, #renew_cluster_tokens, #renew_session, #renew_sessions, #settings, #shutdown_renewer, #vault_exists?, #vault_healthy?, #write

Class Attribute Details

.sessionsObject (readonly)

Returns the value of attribute sessions.



35
36
37
# File 'lib/legion/crypt.rb', line 35

def sessions
  @sessions
end

Class Method Details

.dynamic_rmq_creds?Boolean

Returns:

  • (Boolean)


106
107
108
# File 'lib/legion/crypt.rb', line 106

def dynamic_rmq_creds?
  Legion::Settings.dig(:crypt, :vault, :dynamic_rmq_creds) == true
end

.fetch_bootstrap_rmq_credsObject



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/legion/crypt.rb', line 110

def fetch_bootstrap_rmq_creds
  return unless vault_connected? && dynamic_rmq_creds?

  Legion::Settings.merge_settings('transport', Legion::Transport::Settings.default) if defined?(Legion::Transport::Settings)

  response = LeaseManager.instance.vault_logical.read('rabbitmq/creds/legionio-bootstrap')
  return unless response&.data

  bootstrap_lease_ttl = Legion::Settings.dig(:crypt, :vault, :bootstrap_lease_ttl).to_i
  bootstrap_lease_ttl = 300 if bootstrap_lease_ttl <= 0

  @bootstrap_lease_id = response.lease_id
  @bootstrap_lease_expires = Time.now + [response.lease_duration, bootstrap_lease_ttl].min

  settings = Legion::Settings.loader.settings
  settings[:transport] ||= {}
  settings[:transport][:connection] ||= {}
  conn = settings[:transport][:connection]
  username = response.data[:username] || response.data['username']
  password = response.data[:password] || response.data['password']

  unless username && password
    log.warn 'Bootstrap RMQ credential fetch returned nil username or password — skipping settings update'
    return
  end

  conn[:user]     = username
  conn[:password] = password

  log.info "Bootstrap RMQ credentials acquired (lease: #{@bootstrap_lease_id[0..7]}...)"
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'crypt.fetch_bootstrap_rmq_creds')
  log.warn "Bootstrap RMQ credential fetch failed: #{e.message}"
end

.fetch_jwt_svid(audience:) ⇒ Object



62
63
64
65
# File 'lib/legion/crypt.rb', line 62

def fetch_jwt_svid(audience:)
  @workload_client ||= Spiffe::WorkloadApiClient.new
  @workload_client.fetch_jwt_svid(audience: audience)
end

.fetch_svidObject



57
58
59
60
# File 'lib/legion/crypt.rb', line 57

def fetch_svid
  @workload_client ||= Spiffe::WorkloadApiClient.new
  @workload_client.fetch_x509_svid
end

.issue_token(payload = {}, ttl: nil, algorithm: nil) ⇒ Object



208
209
210
211
212
213
214
215
216
217
# File 'lib/legion/crypt.rb', line 208

def issue_token(payload = {}, ttl: nil, algorithm: nil)
  jwt = jwt_settings
  algo = algorithm || jwt[:default_algorithm]
  token_ttl = ttl || jwt[:default_ttl]

  signing_key = algo == 'RS256' ? private_key : settings[:cluster_secret]

  Legion::Crypt::JWT.issue(payload, signing_key: signing_key, algorithm: algo, ttl: token_ttl,
                                    issuer: jwt[:issuer])
end

.jwt_settingsObject



102
103
104
# File 'lib/legion/crypt.rb', line 102

def jwt_settings
  settings[:jwt] || Legion::Crypt::Settings.jwt
end

.kerberos_principalObject



49
50
51
# File 'lib/legion/crypt.rb', line 49

def kerberos_principal
  KerberosAuth.kerberos_principal
end

.revoke_bootstrap_leaseObject



184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/legion/crypt.rb', line 184

def revoke_bootstrap_lease
  return unless @bootstrap_lease_id

  LeaseManager.instance.vault_sys.revoke(@bootstrap_lease_id)
  log.info "Bootstrap RMQ lease revoked (#{@bootstrap_lease_id[0..7]}...)"
  @bootstrap_lease_id      = nil
  @bootstrap_lease_expires = nil
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'crypt.revoke_bootstrap_lease')
  log.warn "Bootstrap lease revocation failed: #{e.message} — lease will expire naturally"
  @bootstrap_lease_id      = nil
  @bootstrap_lease_expires = nil
end

.settingsObject



94
95
96
97
98
99
100
# File 'lib/legion/crypt.rb', line 94

def settings
  if Legion.const_defined?('Settings')
    Legion::Settings[:crypt]
  else
    Legion::Crypt::Settings.default
  end
end

.shutdownObject



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/legion/crypt.rb', line 235

def shutdown
  lifecycle_mutex.synchronize do
    unless @started
      log.info 'Legion::Crypt shutdown ignored because the lifecycle is not running'
      return
    end

    log.info 'Legion::Crypt shutdown initiated'
    Legion::Crypt::LeaseManager.instance.shutdown
    stop_token_renewers
    shutdown_renewer
    close_sessions
    stop_svid_rotation
    @started = false
    log.info 'Legion::Crypt shutdown completed'
  end
end

.spiffe_svidObject



53
54
55
# File 'lib/legion/crypt.rb', line 53

def spiffe_svid
  @svid_rotation&.current_svid
end

.startObject



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/legion/crypt.rb', line 67

def start
  lifecycle_mutex.synchronize do
    if @started
      log.info 'Legion::Crypt start ignored because the lifecycle is already running'
      return
    end

    log.info 'Legion::Crypt startup initiated'
    log.debug 'Legion::Crypt start requested'
    ::File.write('./legionio.key', private_key) if settings[:save_private_key]
    @token_renewers ||= []

    if vault_settings[:clusters]&.any?
      log.info "Legion::Crypt connecting #{vault_settings[:clusters].size} Vault cluster(s)"
      connect_all_clusters
      start_token_renewers
    else
      log.info 'Legion::Crypt connecting primary Vault client' unless settings[:vault][:token].nil?
      connect_vault unless settings[:vault][:token].nil?
    end
    start_lease_manager
    start_svid_rotation
    @started = true
    log.info 'Legion::Crypt startup completed'
  end
end

.swap_to_identity_creds(mode:) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/legion/crypt.rb', line 145

def swap_to_identity_creds(mode:)
  return unless vault_connected? && dynamic_rmq_creds?
  return if mode == :lite

  role = RMQ_ROLE_MAP.fetch(mode, "legionio-#{mode}")
  response = LeaseManager.instance.vault_logical.read("rabbitmq/creds/#{role}")
  raise "Failed to fetch identity-scoped RMQ creds for role #{role}" unless response&.data

  LeaseManager.instance.register_dynamic_lease(
    name:          :rabbitmq,
    path:          "rabbitmq/creds/#{role}",
    response:      response,
    settings_refs: [
      { path: %i[transport connection user],     key: :username },
      { path: %i[transport connection password], key: :password }
    ]
  )

  settings = Legion::Settings.loader.settings
  settings[:transport] ||= {}
  settings[:transport][:connection] ||= {}
  conn = settings[:transport][:connection]
  username = response.data[:username] || response.data['username']
  password = response.data[:password] || response.data['password']
  raise "Identity-scoped RMQ creds for role #{role} missing username or password" unless username && password

  conn[:user]     = username
  conn[:password] = password

  if defined?(Legion::Transport::Connection)
    Legion::Transport::Connection.force_reconnect
    raise 'Transport reconnect failed after credential swap — bootstrap lease NOT revoked' unless Legion::Transport::Connection.session_open?

    log.info "Transport reconnected with identity-scoped creds (role: #{role})"
  end

  revoke_bootstrap_lease
end

.vault_connected?Boolean

Returns:

  • (Boolean)


198
199
200
201
202
203
204
205
206
# File 'lib/legion/crypt.rb', line 198

def vault_connected?
  return true if settings.dig(:vault, :connected) == true
  return true if respond_to?(:connected_clusters) && connected_clusters.any?

  false
rescue StandardError => e
  handle_exception(e, level: :debug, operation: 'crypt.vault_connected?')
  false
end

.vault_settingsObject



45
46
47
# File 'lib/legion/crypt.rb', line 45

def vault_settings
  Legion::Settings[:crypt][:vault]
end

.verify_external_token(token, jwks_url:) ⇒ Object



231
232
233
# File 'lib/legion/crypt.rb', line 231

def verify_external_token(token, jwks_url:, **)
  Legion::Crypt::JWT.verify_with_jwks(token, jwks_url: jwks_url, **)
end

.verify_token(token, algorithm: nil) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
# File 'lib/legion/crypt.rb', line 219

def verify_token(token, algorithm: nil)
  jwt = jwt_settings
  algo = algorithm || jwt[:default_algorithm]

  verification_key = algo == 'RS256' ? OpenSSL::PKey::RSA.new(public_key) : settings[:cluster_secret]

  Legion::Crypt::JWT.verify(token, verification_key: verification_key, algorithm: algo,
                                   verify_expiration: jwt[:verify_expiration],
                                   verify_issuer: jwt[:verify_issuer],
                                   issuer: jwt[:issuer])
end