legion-crypt 1.5.42 → 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.
@@ -89,6 +89,13 @@ module Legion
89
89
  service_principal: nil,
90
90
  auth_path: 'auth/kerberos/login'
91
91
  },
92
+ jwt: {
93
+ auth_path: 'auth/jwt/login',
94
+ role: 'legion-worker'
95
+ },
96
+ ldap: {
97
+ auth_path: 'auth/ldap/login'
98
+ },
92
99
  tls: {
93
100
  verify: 'peer'
94
101
  },
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Crypt
5
+ module Vault
6
+ module Auth
7
+ # JWT auth. Presents a signed JWT to Vault's JWT/OIDC method. Cannot re-authenticate on
8
+ # its own — a fresh login with a new JWT is required once the token is unusable.
9
+ class JWT
10
+ include Legion::Crypt::Vault::Auth
11
+
12
+ def can_reauth?
13
+ false
14
+ end
15
+
16
+ # Issues a grant by presenting the given JWT to the configured role.
17
+ def authenticate(client:, jwt:, **)
18
+ jwt_config = cluster_config[:jwt]
19
+ secret = client.logical.write(path: jwt_config[:auth_path], data: { role: jwt_config[:role], jwt: jwt })
20
+ install_grant(secret)
21
+ rescue Legion::Crypt::Vault::HTTPError => e
22
+ raise AuthError, "Vault JWT auth failed: #{e.message}"
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Crypt
5
+ module Vault
6
+ module Auth
7
+ # Kerberos (SPNEGO) auth. The SPNEGO token is sent as the HTTP Authorization header and
8
+ # the client keeps its configured namespace. Can re-authenticate from the ticket cache.
9
+ class Kerberos
10
+ include Legion::Crypt::Vault::Auth
11
+
12
+ class GemMissingError < AuthError; end
13
+
14
+ def can_reauth?
15
+ true
16
+ end
17
+
18
+ # Issues a grant from the current Kerberos ticket.
19
+ def authenticate(client:, **)
20
+ raise GemMissingError, 'lex-kerberos gem is required for Kerberos auth' unless spnego_available?
21
+
22
+ kerberos = cluster_config[:kerberos]
23
+ service_principal = kerberos[:service_principal]
24
+ raise AuthError, 'Kerberos service_principal is not configured' unless service_principal
25
+
26
+ spnego_token = obtain_spnego_token(service_principal: service_principal)
27
+ data = client.put(path: kerberos[:auth_path], body: '{}',
28
+ headers: { 'Authorization' => "Negotiate #{spnego_token}" })
29
+ install_grant(Legion::Crypt::Vault::Client::Secret.decode(data: data))
30
+ rescue Legion::Crypt::Vault::HTTPError => e
31
+ raise AuthError, "Vault Kerberos auth failed: #{e.message}"
32
+ end
33
+
34
+ # Re-authenticates from the ticket cache to produce a replacement grant.
35
+ def reauth(client:, **)
36
+ authenticate(client: client)
37
+ end
38
+
39
+ private
40
+
41
+ def spnego_available?
42
+ require 'legion/extensions/kerberos/helpers/spnego'
43
+ true
44
+ rescue LoadError => e
45
+ handle_exception(e, level: :warn, operation: 'crypt.vault_auth_kerberos.spnego_available')
46
+ defined?(Legion::Extensions::Kerberos::Helpers::Spnego) ? true : false
47
+ end
48
+
49
+ def obtain_spnego_token(service_principal:)
50
+ helper = Object.new.extend(Legion::Extensions::Kerberos::Helpers::Spnego)
51
+ result = helper.obtain_spnego_token(service_principal: service_principal)
52
+ raise AuthError, "SPNEGO token acquisition failed: #{result[:error]}" unless result[:success]
53
+
54
+ result[:token]
55
+ end
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Crypt
5
+ module Vault
6
+ module Auth
7
+ # LDAP auth. Requires explicit username/password and cannot re-authenticate on its own —
8
+ # a fresh login is required once the token is unusable.
9
+ class LDAP
10
+ include Legion::Crypt::Vault::Auth
11
+
12
+ def can_reauth?
13
+ false
14
+ end
15
+
16
+ # Issues a grant with the given credentials.
17
+ def authenticate(client:, username:, password:, **)
18
+ raise ArgumentError, 'LDAP username must be a single path segment' if username.include?('/')
19
+
20
+ secret = client.logical.write(path: "#{cluster_config[:ldap][:auth_path]}/#{username}", data: { password: password })
21
+ install_grant(secret)
22
+ rescue Legion::Crypt::Vault::HTTPError => e
23
+ raise AuthError, "Vault LDAP auth failed: #{e.message}"
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'legion/logging/helper'
4
+ require 'legion/crypt/vault/client'
5
+ require 'legion/crypt/vault/operation'
6
+
7
+ module Legion
8
+ module Crypt
9
+ module Vault
10
+ # Shared login behavior for a Vault auth method, mixed into the concrete
11
+ # Vault::Auth::Kerberos / LDAP / JWT classes. Reads this cluster's config live from
12
+ # Legion::Settings with bracket access; the token's lifecycle belongs to Vault::Session.
13
+ module Auth
14
+ include Legion::Logging::Helper
15
+
16
+ class AuthError < StandardError; end
17
+
18
+ # The login auth response. The session holds the live grant and renews it; this is the
19
+ # strategy's own record of what it last issued.
20
+ attr_reader :grant
21
+
22
+ def initialize(cluster_name:, **)
23
+ @cluster_name = cluster_name
24
+ @grant = nil
25
+ end
26
+
27
+ private
28
+
29
+ # The effective config for this cluster: the named cluster's settings, or the top-level
30
+ # vault settings for the single-cluster (nil) case. A named cluster that is not
31
+ # configured is a configuration error, not a fallback.
32
+ def cluster_config
33
+ vault = Legion::Settings[:crypt][:vault]
34
+ @cluster_name ? vault[:clusters].fetch(@cluster_name) : vault
35
+ end
36
+
37
+ # Validates a login secret and installs its auth response as the current grant.
38
+ def install_grant(secret)
39
+ raise AuthError, 'Vault auth returned no auth data' unless secret&.auth
40
+
41
+ @grant = secret.auth
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
47
+
48
+ require 'legion/crypt/vault/auth/kerberos'
49
+ require 'legion/crypt/vault/auth/ldap'
50
+ require 'legion/crypt/vault/auth/jwt'
@@ -221,14 +221,21 @@ module Legion
221
221
  end
222
222
 
223
223
  class Auth
224
- attr_reader :client_token, :lease_duration, :policies, :metadata
224
+ attr_reader :client_token, :accessor, :policies, :token_policies, :metadata,
225
+ :lease_duration, :entity_id, :token_type, :orphan, :num_uses
225
226
 
226
227
  def initialize(data:, **)
227
228
  @client_token = data[:client_token]
228
- @lease_duration = data[:lease_duration]
229
+ @accessor = data[:accessor]
229
230
  @policies = data[:policies]
231
+ @token_policies = data[:token_policies]
230
232
  @metadata = data[:metadata]
233
+ @lease_duration = data[:lease_duration]
231
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]
232
239
  end
233
240
 
234
241
  def renewable?
@@ -9,6 +9,8 @@ require 'legion/crypt/vault/operation'
9
9
  module Legion
10
10
  module Crypt
11
11
  module Vault
12
+ class GrantRejectedError < RuntimeError; end
13
+
12
14
  module Cluster
13
15
  include Legion::Logging::Helper
14
16
 
@@ -41,29 +43,51 @@ module Legion
41
43
  end
42
44
  end
43
45
 
44
- def publish_vault_grant(client:, config:, grant:, auth_method:, issued_at: Time.now, **)
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, **)
45
48
  token = grant.fetch(:token)
46
49
  ttl = grant[:lease_duration].to_f
47
50
  expires_at = issued_at + ttl if ttl.positive?
48
51
  vault_clients_mutex.synchronize do
49
- pair = @vault_clients&.find { |_name, entry| entry[:client].equal?(client) }
50
- raise IOError, 'Vault client replaced during authentication' if @retired_vault_clients&.key?(client)
51
-
52
- if pair
53
- name, entry = pair
54
- current_config = name.nil? ? Legion::Settings[:crypt][:vault] : clusters[name]
55
- unless config.equal?(current_config) && current_vault_client?(entry: entry, signature: vault_client_signature(config: current_config))
56
- raise IOError, 'Vault client configuration changed during authentication'
57
- end
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'
58
56
  end
57
+ raise Legion::Crypt::Vault::GrantRejectedError, 'Vault token changed during authentication' if current_token && config[:token] != current_token
58
+
59
59
  client.token = token
60
60
  connected = expires_at.nil? || expires_at > Time.now
61
61
  config.merge!(token: token, lease_duration: grant[:lease_duration], renewable: grant[:renewable],
62
62
  expires_at: expires_at, connected: connected, relogin_required: !connected, auth_method: auth_method)
63
- entry[:signature][:token] = token&.dup&.freeze if entry
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
64
77
  end
65
78
  end
66
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
+
67
91
  def clear_vault_clients(deadline: nil, **)
68
92
  deadline ||= ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) + Legion::Crypt::Vault::Operation::SHUTDOWN_TIMEOUT
69
93
  clients = vault_clients_mutex.synchronize do
@@ -92,60 +116,24 @@ module Legion
92
116
  end
93
117
 
94
118
  def connected_clusters
95
- vault_clients_mutex.synchronize do
96
- now = Time.now
97
- clusters.select do |_, config|
98
- config[:token] && config[:connected] && !config[:relogin_required] &&
99
- (!config[:expires_at] || config[:expires_at] > now)
100
- end
101
- end
102
- end
103
-
104
- def connect_all_clusters
105
- log.info "Vault cluster connect requested configured_clusters=#{clusters.size}"
106
- log_vault_debug("connect_all_clusters: #{clusters.size} cluster(s) configured")
107
- results = {}
108
- clusters.each do |name, config|
109
- log_vault_debug("connect_all_clusters: #{name} (auth_method=#{config[:auth_method].inspect})")
110
- case config[:auth_method]&.to_s
111
- when 'kerberos'
112
- results[name] = connect_kerberos_cluster(name, config)
113
- when 'ldap'
114
- next # handled by ldap_login_all
115
- else
116
- next unless config[:token]
117
-
118
- client = vault_client(name)
119
- config[:connected] = cluster_healthy?(client)
120
- results[name] = config[:connected]
121
- log_cluster_connected(name, config) if config[:connected]
122
- end
123
- rescue StandardError => e
124
- config[:connected] = false
125
- results[name] = false
126
- log_vault_error(name, e, operation: 'crypt.vault_cluster.connect_all_clusters')
127
- end
128
-
129
- connected = results.select { |_, v| v }
130
- log.info "Vault cluster connect complete connected=#{connected.size} attempted=#{results.size}"
131
- log_vault_debug("connect_all_clusters: #{connected.size}/#{results.size} connected")
132
- sync_vault_connected(connected.any?)
133
- results
119
+ vault_clients_mutex.synchronize { connected_cluster_configs }
134
120
  end
135
121
 
136
122
  private
137
123
 
138
- def cluster_healthy?(client)
139
- client.sys.health_status.initialized?
140
- rescue Legion::Crypt::Vault::HTTPError => e
141
- return true if [429, 472, 473].include?(e.code)
142
-
143
- handle_exception(e, level: :warn, operation: 'crypt.vault_cluster.cluster_healthy')
144
- raise
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
145
131
  end
146
132
 
147
- def sync_vault_connected(connected)
148
- Legion::Settings[:crypt][:vault][:connected] = connected
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?
149
137
  end
150
138
 
151
139
  def selected_connected_cluster_name(name = nil)
@@ -268,62 +256,6 @@ module Legion
268
256
  rescue StandardError => e
269
257
  handle_exception(e, level: :warn, operation: 'crypt.vault_cluster.retire_vault_client')
270
258
  end
271
-
272
- def log_vault_error(name, error, operation: 'crypt.vault_cluster.error')
273
- handle_exception(error, level: :error, operation: operation, cluster_name: name)
274
- end
275
-
276
- def connect_kerberos_cluster(name, config)
277
- krb_config = config[:kerberos] || {}
278
- spn = krb_config[:service_principal]
279
- auth_path = krb_config[:auth_path] || Legion::Crypt::KerberosAuth::DEFAULT_AUTH_PATH
280
-
281
- log_vault_debug("connect_kerberos_cluster[#{name}]: SPN=#{spn}, auth_path=#{auth_path}, namespace=#{config[:namespace].inspect}")
282
-
283
- unless spn
284
- log_vault_warn(name, 'Kerberos auth missing service_principal, skipping')
285
- config[:connected] = false
286
- return false
287
- end
288
-
289
- require 'legion/crypt/kerberos_auth'
290
- client = vault_client(name)
291
- log_vault_debug("connect_kerberos_cluster[#{name}]: client.namespace=#{client.respond_to?(:namespace) ? client.namespace.inspect : 'n/a'}")
292
- log.info "Connecting Vault cluster #{name} via Kerberos auth_path=#{auth_path}"
293
-
294
- result = Legion::Crypt::KerberosAuth.login(
295
- vault_client: client,
296
- service_principal: spn,
297
- auth_path: auth_path
298
- )
299
-
300
- publish_vault_grant(client: client, config: config, grant: result, auth_method: 'kerberos')
301
- log_vault_debug("connect_kerberos_cluster[#{name}]: policies=#{result[:policies].inspect}")
302
- log_cluster_connected(name, config)
303
- true
304
- rescue Legion::Crypt::KerberosAuth::GemMissingError => e
305
- handle_exception(e, level: :warn, operation: 'crypt.vault_cluster.connect_kerberos_cluster', cluster_name: name)
306
- log_vault_warn(name, e.message)
307
- config[:connected] = false
308
- false
309
- rescue Legion::Crypt::KerberosAuth::AuthError => e
310
- handle_exception(e, level: :warn, operation: 'crypt.vault_cluster.connect_kerberos_cluster', cluster_name: name)
311
- log_vault_warn(name, "Kerberos auth failed: #{e.message}")
312
- config[:connected] = false
313
- false
314
- end
315
-
316
- def log_cluster_connected(name, config)
317
- log.info "Vault cluster connected: #{name} at #{config[:address]}"
318
- end
319
-
320
- def log_vault_warn(name, message)
321
- log.warn("Vault cluster #{name}: #{message}")
322
- end
323
-
324
- def log_vault_debug(message)
325
- log.debug(message)
326
- end
327
259
  end
328
260
  end
329
261
  end
@@ -2,7 +2,6 @@
2
2
 
3
3
  require 'legion/logging/helper'
4
4
  require 'legion/crypt/vault/client'
5
- require 'legion/crypt/lease_manager'
6
5
 
7
6
  module Legion
8
7
  module Crypt
@@ -16,7 +15,7 @@ module Legion
16
15
  existing = find_by_name(canonical_name: canonical_name)
17
16
  return existing if existing
18
17
 
19
- response = Legion::Crypt::LeaseManager.instance.vault_logical.write(
18
+ response = Legion::Crypt.vault_client.logical.write(
20
19
  path: 'identity/entity',
21
20
  data: {
22
21
  name: "legion-#{canonical_name}",
@@ -36,7 +35,7 @@ module Legion
36
35
  # Create an alias linking an auth method mount to the entity.
37
36
  # Idempotent — swallows "already exists" 4xx errors.
38
37
  def self.ensure_alias(entity_id:, mount_accessor:, alias_name:)
39
- Legion::Crypt::LeaseManager.instance.vault_logical.write(
38
+ Legion::Crypt.vault_client.logical.write(
40
39
  path: 'identity/entity-alias',
41
40
  data: { name: alias_name, canonical_id: entity_id, mount_accessor: mount_accessor }
42
41
  )
@@ -55,7 +54,7 @@ module Legion
55
54
  # Look up a Vault entity by its Legion canonical name.
56
55
  # Returns the Vault entity ID string, or nil if not found.
57
56
  def self.find_by_name(canonical_name:)
58
- response = Legion::Crypt::LeaseManager.instance.vault_logical.read(path: "identity/entity/name/legion-#{canonical_name}")
57
+ response = Legion::Crypt.vault_client.logical.read(path: "identity/entity/name/legion-#{canonical_name}")
59
58
  extract_id(response)
60
59
  rescue StandardError => e
61
60
  handle_exception(e, level: :warn, operation: 'crypt.vault_entity.find_by_name', canonical_name: canonical_name)