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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1d7d1cbd214ebc5bc7f8d109b958e3d307e3a4faaa81fdb2c47b527670ab720f
4
- data.tar.gz: 4ea67b85552ddae267d4945be1586e7248a30b3dc38dfa2f280ae59311524614
3
+ metadata.gz: d004e86a701b8740daa5e5c17fb2baf29314a878832696023d2c8a66088aafc3
4
+ data.tar.gz: 04cac6ad63d92b54bbbcae9664d58a6252ccfce29418e9b3ea9f76c1758bb4d8
5
5
  SHA512:
6
- metadata.gz: 2af577b9a0c3c7e464e79f11bbd13e044d9e3e76520c2b4ee6ad27949135c0e873aa8aadfca33d67324061dd55d1f7f5f21ceb1715aa9a7d1d0f1fac77d74852
7
- data.tar.gz: 4226e44bc08ebdc1928ce91630125db8e9a3c674e5ce64cf47ed7375706876388f9aeb3e93816402e41b10c0961bb7f19bd57dc6f64e826289333b27f558c36e
6
+ metadata.gz: 9530a7a4ce7b6088b9bb8c1dcc03f217fe6ecfd1fb982b3f8e10f0a3833995edba6a0f22b0d856dc6e618541831a04c65e090da2b5dce080a31352c72c2011a1
7
+ data.tar.gz: 2b31abb97158b140da701acc58ff481b6ee183885ea14b7589eab1efba1db980001a3d4124242a16d3b24e687c0bcb941872429c9642ddbadb2061007160d741
@@ -6,29 +6,56 @@ on:
6
6
  schedule:
7
7
  - cron: '0 9 * * 1'
8
8
 
9
+ permissions: {}
10
+
9
11
  jobs:
10
12
  ci:
11
- uses: LegionIO/.github/.github/workflows/ci.yml@main
13
+ permissions:
14
+ contents: read
15
+ uses: LegionIO/.github/.github/workflows/ci.yml@e0fc7364b73f446d4cb9bdc162a66ed34bf0daa7
16
+ with:
17
+ companion-gems: ${{ github.event_name == 'pull_request' && '{"legion-settings":{"repository":"LegionIO/legion-settings","ref":"8e73a9ef3c13958e3e1e7fc98532e41283159706"}}' || '{}' }}
12
18
 
13
19
  lint:
20
+ permissions:
21
+ checks: write
22
+ contents: read
23
+ pull-requests: read
14
24
  uses: LegionIO/.github/.github/workflows/lint-patterns.yml@main
15
25
 
16
26
  security:
17
- uses: LegionIO/.github/.github/workflows/security-scan.yml@main
27
+ permissions:
28
+ contents: read
29
+ security-events: write
30
+ uses: LegionIO/.github/.github/workflows/security-scan.yml@e0fc7364b73f446d4cb9bdc162a66ed34bf0daa7
31
+ with:
32
+ companion-gems: ${{ github.event_name == 'pull_request' && '{"legion-settings":{"repository":"LegionIO/legion-settings","ref":"8e73a9ef3c13958e3e1e7fc98532e41283159706"}}' || '{}' }}
18
33
 
19
34
  version-changelog:
35
+ permissions:
36
+ contents: read
37
+ pull-requests: read
20
38
  uses: LegionIO/.github/.github/workflows/version-changelog.yml@main
21
39
 
22
40
  dependency-review:
41
+ permissions:
42
+ contents: read
43
+ pull-requests: write
23
44
  uses: LegionIO/.github/.github/workflows/dependency-review.yml@main
24
45
 
25
46
  stale:
26
47
  if: github.event_name == 'schedule'
48
+ permissions:
49
+ issues: write
50
+ pull-requests: write
27
51
  uses: LegionIO/.github/.github/workflows/stale.yml@main
28
52
 
29
53
  release:
30
54
  needs: [ci, lint]
31
55
  if: github.event_name == 'push' && github.ref == 'refs/heads/main'
56
+ permissions:
57
+ contents: write
58
+ packages: write
32
59
  uses: LegionIO/.github/.github/workflows/release.yml@main
33
60
  secrets:
34
- rubygems-api-key: ${{ secrets.RUBYGEMS_API_KEY }}
61
+ rubygems-api-key: ${{ secrets.RUBYGEMS_API_KEY }}
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --require ./spec/spec_helper
2
+ --pattern spec/legion/**/*.rb
data/AGENTS.md CHANGED
@@ -19,6 +19,7 @@ bundle exec rubocop
19
19
  - `lib/legion/crypt/jwt.rb`
20
20
  - `lib/legion/crypt/jwks_client.rb`
21
21
  - `lib/legion/crypt/vault.rb`
22
+ - `lib/legion/crypt/vault/` — `Legion::Crypt::Vault::{Client, Cluster, Operation, Entity, JwtAuth, KerberosAuth, Renewer}`
22
23
  - `lib/legion/crypt/lease_manager.rb`
23
24
  - `lib/legion/crypt/token_renewer.rb`
24
25
  - `lib/legion/crypt/mtls.rb`
@@ -30,6 +31,7 @@ bundle exec rubocop
30
31
  - Keep Vault-dependent logic optional and safely guarded for environments without Vault.
31
32
  - Background renewal/rotation threads must stop cleanly on shutdown and handle failure with bounded retry.
32
33
  - Maintain compatibility for Kerberos, LDAP, and JWT Vault auth paths.
34
+ - Vault components are nested under `Legion::Crypt::Vault`; core `Legion::Crypt::KerberosAuth` handles SPNEGO acquisition and `Legion::Crypt::TokenRenewer` remains outside that namespace.
33
35
  - Cryptographic defaults and key lifecycle behavior are contract-sensitive; change only with test coverage.
34
36
 
35
37
  ## Known Risks
data/CHANGELOG.md CHANGED
@@ -1,5 +1,104 @@
1
1
  # Legion::Crypt
2
2
 
3
+ ## [1.6.0] - 2026-11-13
4
+
5
+ ### Added
6
+ - `Legion::Crypt::Vault::Session` — one per Vault cluster. Composes a token
7
+ strategy (`Vault::Auth`) and a `Vault::Leases`, owns a single maintenance
8
+ thread, and drives the full re-authentication handoff: re-authenticate, re-issue
9
+ every dynamic-secret lease under the new token, reconnect consumers, and commit
10
+ (revoking the old token) or roll back to the previous token and leases on
11
+ failure.
12
+ - `Legion::Crypt::Vault::Auth` (module) and the `Kerberos`, `LDAP`, and `JWT`
13
+ token strategies. Each issues a grant from its Vault auth method and treats the
14
+ login `auth` response as the source-of-truth grant, reading per-cluster config
15
+ from `Legion::Settings`. Kerberos can re-authenticate from the ticket cache;
16
+ LDAP and JWT require a fresh login once the token is unusable.
17
+ - `Legion::Crypt::Vault::Leases` — the dynamic-secret lease lifecycle
18
+ (acquisition, 50% renewal on its own thread, reissue under a replaced token,
19
+ settings-reference publication, consumer reconnect, and revocation), moved from
20
+ the former `LeaseManager` implementation. It is built without a Vault client so
21
+ it can hold `lease://` settings references whether or not Vault is enabled.
22
+ - Spec coverage for `Vault::Session` (start, login, renewal policy, handoff
23
+ commit + rollback, stop), `Vault::Leases` (acquire / reissue / revoke),
24
+ `LeaseManager` without Vault, and the three `Vault::Auth` strategies.
25
+
26
+ ### Changed
27
+ - `Legion::Crypt.start` now creates one `Vault::Session` per configured cluster
28
+ (or a single session for the default cluster); `Legion::Crypt.shutdown` stops
29
+ them. The token, lease, and re-authentication lifecycle now lives in the
30
+ per-cluster session rather than a process-wide coordinator on `Legion::Crypt`.
31
+ - `Legion::Crypt::LeaseManager` is now the `Singleton` subclass of
32
+ `Vault::Leases`: the one process-wide lease object, present from load. The
33
+ default cluster's session supplies its client and starts lease acquisition and
34
+ renewal once it has a token, with or without static lease definitions. This
35
+ preserves the `Legion::Crypt::LeaseManager.instance` contract that
36
+ legion-settings (lease:// resolution) and legion-data (consumer reconnects)
37
+ depend on, including when Vault is disabled or unreachable.
38
+ - The Vault token is renewed only when Vault's last auth response reported it
39
+ renewable. A non-renewable Kerberos token is replaced by re-authentication at
40
+ 75% of its TTL; non-renewable LDAP/JWT tokens run to expiry and require a new
41
+ login. A static configured token is adopted after a health check, is never
42
+ revoked on shutdown, and is renewed only if its configuration says renewable.
43
+ - Tokens minted by LDAP and JWT logins are now revoked on shutdown, as Kerberos
44
+ tokens already were.
45
+ - Named clusters keep the top-level `crypt.vault.connected` flag current on
46
+ grant publication and disconnect, since LegionIO and extensions read it directly.
47
+ - Shutdown revokes tracked sessions and leases before the Vault tokens they
48
+ depend on. A token or lease that could not be revoked is reported as incomplete
49
+ cleanup instead of a completed stop.
50
+ - Authentication, renewal, re-authentication, and grant-installation failures
51
+ log at ERROR. A failed LDAP login is reported once, by `ldap_login_all`.
52
+
53
+ ### Removed
54
+ - The process-wide grant coordinator on `Legion::Crypt`
55
+ (`install_vault_grant`, `retire_vault_grant`, `revoke_rejected_vault_grant`,
56
+ `stop_token_renewers`, `vault_auth_generation`) and the `Vault::Cluster`
57
+ cluster-connect helpers (`connect_all_clusters`, `connect_vault_cluster`), both
58
+ superseded by the per-session `Vault::Session`.
59
+ - The module-based `Legion::Crypt::Vault::KerberosAuth` and
60
+ `Legion::Crypt::Vault::JwtAuth`, the standalone token-renewer actor, and the
61
+ body of `Legion::Crypt::LeaseManager` (now `Vault::Leases`).
62
+
63
+ ### Compatibility
64
+ - The public `Legion::Crypt` surface consumed by the daemon and other gems
65
+ (`start`, `shutdown`, `read`/`write`/`get`/`delete`/`exist?`,
66
+ `vault_connected?`, `kerberos_principal`, `ldap_login`/`ldap_login_all`,
67
+ `cluster_secret`, `fetch_bootstrap_rmq_creds`, `revoke_bootstrap_lease`,
68
+ `swap_to_identity_creds`, `dynamic_rmq_creds?`) is unchanged, so no LegionIO or
69
+ cross-gem changes are required.
70
+ - `Legion::Crypt.vault_client` remains public for now; de-publicizing it (and
71
+ extending per-session lease management beyond the default cluster) are
72
+ follow-ups.
73
+
74
+ ## [1.5.42] - 2026-11-08
75
+
76
+ ### Changed
77
+ - Move Vault client, cluster routing, operation deadlines, entity management, JWT/Kerberos authentication, and the legacy renewal actor into `lib/legion/crypt/vault/` with matching `Legion::Crypt::Vault::*` namespaces.
78
+ - Update library consumers, specs, and current documentation to the nested require paths and constants; remove the old flat paths without compatibility aliases. Core SPNEGO acquisition and `TokenRenewer` remain in their existing locations.
79
+ - Mirror implementation paths and literal filenames under `spec/`, consolidating root Crypt API examples without dropping coverage. Configure RSpec discovery for the mirrored layout and prioritize `lib/` on the load path to prevent spec files from shadowing production requires.
80
+
81
+ ## [1.5.41] - 2026-11-07
82
+
83
+ ### Fixed
84
+ - Propagate programming errors from Vault connectivity, bootstrap credential acquisition/revocation, lease and SPIFFE startup orchestration, and mTLS interface discovery instead of concealing them as disconnected or fallback states.
85
+ - Handle declared operational failures through structured warning-level exceptions without duplicate raw exception logs; report invalid SPIFFE IDs at warning level.
86
+
87
+ ### Changed
88
+ - Accept extra keyword context on touched startup, credential, and SVID APIs and fully qualify sibling Crypt constants. Preserve mode-specific credential selection and certificate SAN/TTL behavior; fixed role mappings remain frozen constants.
89
+
90
+ ## [1.5.40] - 2026-11-07
91
+
92
+ ### Fixed
93
+ - Use direct core settings reads for Vault connectivity, lease startup, JWT operations, and mTLS PKI paths; remove settings-only JWT/PKI accessors and preserve complete, isolated defaults in their specs.
94
+ - Exercise the real `legion-settings` dependency throughout specs, including resolver and loader rebuild behavior; isolate mutable settings between examples instead of mocking the dependency.
95
+
96
+ ## [1.5.39] - 2026-11-01
97
+
98
+ ### Fixed
99
+ - Read crypto runtime configuration from live `Legion::Settings` instead of fallback settings wrappers; register Crypt defaults at boot and require Settings >= 1.4.2 without changing lease-reference publication.
100
+ - Honor live JWT verification flags, key-derivation configuration, Vault operation budgets, and mTLS/SPIFFE policy; reject invalid renewal windows rather than silently substituting defaults. Vault environment tokens supply boot defaults only, never overwrite explicit runtime configuration.
101
+
3
102
  ## [1.5.38] - 2026-10-31
4
103
 
5
104
  ### Fixed
data/CLAUDE.md CHANGED
@@ -1,216 +1,89 @@
1
- # legion-crypt: Encryption and Vault Integration for LegionIO
1
+ # legion-crypt
2
2
 
3
- **Repository Level 3 Documentation**
4
- - **Parent**: `/Users/miverso2/rubymine/legion/CLAUDE.md`
5
-
6
- ## Purpose
7
-
8
- Handles encryption, decryption, secrets management, JWT token management, and HashiCorp Vault connectivity for the LegionIO framework. Provides AES-256-CBC message encryption, RSA key pair generation, cluster secret management, JWT issue/verify operations, and Vault token lifecycle management.
9
-
10
- **GitHub**: https://github.com/LegionIO/legion-crypt
11
- **Version**: 1.5.7
12
- **License**: Apache-2.0
3
+ Core encryption, secrets management, JWT, and HashiCorp Vault integration for LegionIO. Follow [LegionIO coding standards](../docs/legionio-standards.md); this file adds Crypt-specific guidance.
13
4
 
14
5
  ## Architecture
15
6
 
16
7
  ```
17
- Legion::Crypt (singleton module)
18
- ├── .start # Initialize: generate keys, connect to Vault
19
- ├── .encrypt(string) # AES-256-CBC encryption
20
- ├── .decrypt(message) # AES-256-CBC decryption
21
- ├── .shutdown # Stop Vault renewer, close sessions
22
- │
23
- ├── Cipher # OpenSSL cipher operations (AES-256-CBC)
24
- │ ├── .encrypt # Encrypt with cluster secret
25
- │ ├── .decrypt # Decrypt with cluster secret
26
- │ ├── .private_key # RSA private key (generated or loaded)
27
- │ └── .public_key # RSA public key
28
- │
29
- ├── Vault # HashiCorp Vault integration
30
- │ ├── .connect_vault # Establish Vault session
31
- │ ├── .read(path) # Read secret from Vault
32
- │ ├── .write(path) # Write secret to Vault
33
- │ └── .renew_token # Token renewal
34
- │
35
- ├── JWT # JSON Web Token operations
36
- │ ├── .issue # Create signed JWT (HS256 or RS256)
37
- │ ├── .verify # Verify and decode JWT
38
- │ ├── .verify_with_jwks # Verify RS256 token via external JWKS endpoint (Entra ID, etc.)
39
- │ └── .decode # Decode without verification (inspection)
40
- │
41
- ├── JwksClient # External JWKS endpoint integration (thread-safe)
42
- │ ├── .fetch_keys # Fetch and parse JWKS from a URL
43
- │ ├── .find_key # Lookup key by kid (cache-first, re-fetch on miss)
44
- │ └── .clear_cache # Clear the key cache
45
- │
46
- ├── ClusterSecret # Cluster-wide shared secret management
47
- │ └── .cs # Generate/distribute cluster secret
48
- │
49
- ├── VaultJwtAuth # Vault JWT auth backend integration
50
- │ ├── .login # Authenticate to Vault using a JWT token, returns Vault token hash
51
- │ ├── .login! # Authenticate and set ::Vault.token for subsequent operations
52
- │ └── .worker_login # Issue a Legion JWT and authenticate to Vault in one step
53
- │
54
- ├── VaultRenewer # Background Vault token renewal thread
55
- ├── Ed25519 # Ed25519 key generation, signing, verification, Vault storage
56
- ├── PartitionKeys # HKDF per-tenant key derivation, AES-256-GCM encrypt/decrypt
57
- ├── Erasure # Cryptographic erasure via Vault master key deletion
58
- ├── Attestation # Signed identity claims with Ed25519, freshness checking
59
- ├── LeaseManager # Dynamic Vault lease lifecycle: fetch, cache, renew, rotate, push-back
60
- ├── KerberosAuth # GSSAPI SPNEGO token acquisition; `disable_gssapi_finalizers` prevents GC segfault on macOS
61
- ├── VaultKerberosAuth # Vault Kerberos auth: SPNEGO as `Authorization` header, namespace clear/restore, TokenRenewer wiring
62
- ├── LdapAuth # Vault LDAP auth backend
63
- ├── Tls # TLS settings (cert/key/CA/verify_peer/Vault PKI)
64
- ├── Mtls # mTLS cert issuance (Vault PKI) + CertRotation background thread (50% TTL renewal)
65
- ├── TokenRenewer # Background renewal thread: 75% TTL renew, Kerberos re-auth on failure, exponential backoff
66
- ├── Spiffe # SPIFFE identity support: parse_id, valid_id?, X509Svid, JwtSvid structs; reads security.spiffe settings
67
- ├── Spiffe::IdentityHelpers # Mixin for SPIFFE identity operations
68
- ├── Spiffe::SvidRotation # Background SVID renewal at 50% TTL
69
- ├── Spiffe::WorkloadApiClient # gRPC workload API client for SPIRE agent (unix socket)
70
- ├── VaultEntity # Vault entity/alias lifecycle (ensure_entity, ensure_alias, find_by_name); all non-fatal
71
- ├── MockVault # In-memory Vault mock for local development mode
72
- ├── Settings # Default crypt config
73
- └── Version
8
+ Legion::Crypt
9
+ ├── Cipher # AES-256-GCM encryption; legacy CBC decryption; RSA key pair
10
+ ├── Vault # read/write/connect through Vault::Client
11
+ │ ├── Client # core-owned HTTP client using Faraday and Legion::JSON
12
+ │ ├── Cluster # client selection, caching, grant publication, connected flags
13
+ │ ├── Operation # bounded operations and shared shutdown deadlines
14
+ │ ├── Entity # entity and alias lookup
15
+ │ ├── Session # one per cluster: token lifecycle, renew/re-auth handoff, stop
16
+ │ ├── Auth # login strategies: Auth::Kerberos (SPNEGO), Auth::LDAP, Auth::JWT
17
+ │ ├── Leases # dynamic-secret leases: acquire, renew at 50% TTL, reissue, revoke
18
+ │ └── Renewer # legacy Every actor for KV session renewal
19
+ ├── JWT # issue/verify/decode (HS256 cluster-secret or RS256 RSA)
20
+ ├── JwksClient # external JWKS endpoint, 1hr TTL cache, thread-safe
21
+ ├── ClusterSecret # shared AES key distributed across nodes
22
+ ├── LeaseManager # Singleton Vault::Leases; cross-gem contract, exists without Vault
23
+ ├── Ed25519 # key gen, sign, verify, Vault storage
24
+ ├── PartitionKeys # HKDF per-tenant key derivation, AES-256-GCM
25
+ ├── TLS # TLS configuration and Vault-backed material resolution
26
+ ├── Mtls # Vault PKI certificate issuance using crypt.mtls settings
27
+ ├── CertRotation # background renewal using the configured renewal window
28
+ ├── Spiffe # SPIFFE ID parse/validate, X509Svid/JwtSvid, SPIRE workload API
29
+ ├── Attestation # signed identity claims with Ed25519
30
+ ├── Erasure # cryptographic erasure via Vault master key deletion
31
+ └── MockVault # in-memory mock for local dev
74
32
  ```
75
33
 
76
- ### Key Design Patterns
77
-
78
- - **Dynamic Keys**: By default, generates new RSA key pair per process start (no persistent keys)
79
- - **Cluster Secret**: Shared AES key distributed across Legion nodes for inter-node encrypted communication
80
- - **Vault Conditional**: Vault module is only included if the `vault` gem is available
81
- - **Token Lifecycle**: VaultRenewer runs background thread for automatic token renewal
82
- - **JWT Dual Algorithm**: HS256 (symmetric, cluster secret) for intra-cluster tokens; RS256 (asymmetric, RSA keypair) for tokens verifiable without sharing the signing key
83
- - **JWKS External Validation**: `JwksClient` fetches public keys from external identity provider JWKS endpoints (Entra ID, Bot Framework). Keys cached for 1 hour (CACHE_TTL=3600s), thread-safe via Mutex, automatic re-fetch on cache miss handles key rotation
84
-
85
- ## Default Settings
86
-
87
- ```json
88
- {
89
- "vault": { "..." : "see vault settings" },
90
- "jwt": {
91
- "enabled": true,
92
- "default_algorithm": "HS256",
93
- "default_ttl": 3600,
94
- "issuer": "legion",
95
- "verify_expiration": true,
96
- "verify_issuer": true
97
- },
98
- "cs_encrypt_ready": false,
99
- "dynamic_keys": true,
100
- "cluster_secret": null,
101
- "save_private_key": true,
102
- "read_private_key": true
103
- }
104
- ```
34
+ Vault components live under `lib/legion/crypt/vault/`. Only what other gems reach by path or constant stays directly under `Legion::Crypt`: `LeaseManager` (legion-settings, legion-data) and `MockVault` (LegionIO).
105
35
 
106
- ## Dependencies
107
-
108
- | Gem | Purpose |
109
- |-----|---------|
110
- | `ed25519` (~> 1.3) | Ed25519 key operations (pure Ruby) |
111
- | `jwt` (>= 2.7) | JSON Web Token encoding/decoding |
112
- | `vault` (>= 0.17) | HashiCorp Vault Ruby client |
113
-
114
- Dev dependencies: `legion-logging`, `legion-settings`
115
-
116
- ## File Map
117
-
118
- | Path | Purpose |
119
- |------|---------|
120
- | `lib/legion/crypt.rb` | Module entry, start/shutdown lifecycle |
121
- | `lib/legion/crypt/cipher.rb` | AES-256-CBC encrypt/decrypt, RSA key generation |
122
- | `lib/legion/crypt/jwt.rb` | JWT issue/verify/decode/verify_with_jwks operations |
123
- | `lib/legion/crypt/jwks_client.rb` | JWKS endpoint fetch, parse, cache (thread-safe, 1hr TTL) |
124
- | `lib/legion/crypt/vault.rb` | Vault read/write/connect/renew operations |
125
- | `lib/legion/crypt/cluster_secret.rb` | Cluster-wide shared secret management |
126
- | `lib/legion/crypt/vault_jwt_auth.rb` | Vault JWT auth backend: `.login`, `.login!`, `.worker_login`; raises `AuthError` on failure |
127
- | `lib/legion/crypt/vault_renewer.rb` | Background Vault token renewal |
128
- | `lib/legion/crypt/lease_manager.rb` | Dynamic Vault lease lifecycle management |
129
- | `lib/legion/crypt/settings.rb` | Default configuration |
130
- | `lib/legion/crypt/ed25519.rb` | Ed25519 key generation, signing, verification, Vault storage |
131
- | `lib/legion/crypt/partition_keys.rb` | HKDF per-tenant key derivation with AES-256-GCM |
132
- | `lib/legion/crypt/erasure.rb` | Cryptographic erasure via Vault master key deletion |
133
- | `lib/legion/crypt/attestation.rb` | Signed identity claims with Ed25519 signatures |
134
- | `lib/legion/crypt/kerberos_auth.rb` | GSSAPI/Kerberos token acquisition; `obtain_spnego_token`, `disable_gssapi_finalizers` (prevents GC segfault on macOS) |
135
- | `lib/legion/crypt/vault_kerberos_auth.rb` | Vault Kerberos auth backend: sends SPNEGO token as `Authorization` HTTP header, clears/restores namespace, wires `TokenRenewer` |
136
- | `lib/legion/crypt/ldap_auth.rb` | Vault LDAP auth backend integration |
137
- | `lib/legion/crypt/tls.rb` | TLS settings module (cert, key, CA paths, verify_peer, Vault PKI flag) |
138
- | `lib/legion/crypt/mtls.rb` | mTLS certificate issuance from Vault PKI; `CertRotation` background renewal thread (50% TTL) |
139
- | `lib/legion/crypt/token_renewer.rb` | Plain Thread renewer: renews at 75% TTL, re-auths via Kerberos on failure, exponential backoff |
140
- | `lib/legion/crypt/spiffe.rb` | SPIFFE identity: parse/validate SPIFFE IDs, X509Svid/JwtSvid structs, settings helpers |
141
- | `lib/legion/crypt/spiffe/identity_helpers.rb` | Mixin for SPIFFE identity operations |
142
- | `lib/legion/crypt/spiffe/svid_rotation.rb` | Background SVID renewal thread (50% TTL) |
143
- | `lib/legion/crypt/spiffe/workload_api_client.rb` | gRPC workload API client for SPIRE agent |
144
- | `lib/legion/crypt/vault_entity.rb` | Vault entity/alias lifecycle: `ensure_entity`, `ensure_alias`, `find_by_name`; all operations non-fatal |
145
- | `lib/legion/crypt/version.rb` | VERSION constant |
146
-
147
- ## Role in LegionIO
148
-
149
- First service-level module initialized during `Legion::Service` startup (before transport). Provides:
150
- 1. Vault token for `legion-transport` to fetch RabbitMQ credentials
151
- 2. Message encryption for `legion-transport` (optional `transport.messages.encrypt`)
152
- 3. Cluster secret for inter-node encrypted communication
153
- 4. JWT tokens for node authentication and task authorization
154
- 5. External token verification for identity providers (Entra ID OIDC via JWKS)
155
-
156
- ### Vault JWT Auth Usage
36
+ Vault is optional. With it disabled or unreachable, boot continues, `LeaseManager.instance` still answers, and `lease://` references stay unresolved until a session acquires the lease and settings are resolved again.
157
37
 
158
- ```ruby
159
- # Authenticate to Vault using a JWT (Vault must have JWT auth method enabled)
160
- result = Legion::Crypt::VaultJwtAuth.login(jwt: token, role: 'legion-worker')
161
- # => { token: '...', lease_duration: 3600, renewable: true, policies: [...], metadata: {} }
38
+ ## Key Design Decisions
162
39
 
163
- # Authenticate and set Vault client token in one step
164
- Legion::Crypt::VaultJwtAuth.login!(jwt: token)
40
+ - RSA keys are memoized per process. `read_private_key` loads an existing `./legionio.key`; otherwise a key is generated. `save_private_key` persists it with owner-only permissions.
41
+ - HS256 (cluster secret) for intra-cluster tokens; RS256 (RSA keypair) for externally-verifiable tokens
42
+ - `JwksClient` caches keys for one hour, shares concurrent refreshes, and throttles repeated unknown-key refreshes.
43
+ - Vault connectivity uses the core client; the `vault` gem is not required. Kerberos SPNEGO acquisition requires the optional `lex-kerberos` helper, and authentication preserves the configured Vault namespace.
44
+ - A Vault token is renewed only when Vault's last auth response said it is renewable. JWT/LDAP never fall back to Kerberos: expiry or terminal rejection requires login again. Kerberos grants alone re-authenticate automatically, at 75% TTL when not renewable.
45
+ - Lease renewal runs on the `Leases` thread, separate from the session's token thread, and only for the default cluster.
165
46
 
166
- # Issue a Legion JWT and use it to authenticate to Vault (convenience for workers)
167
- result = Legion::Crypt::VaultJwtAuth.worker_login(worker_id: 'abc', owner_msid: 'user@example.com')
168
- ```
47
+ ## Framework Contracts
169
48
 
170
- Vault prerequisites: `vault auth enable jwt` + configure `auth/jwt/config` with JWKS URL or bound issuer.
49
+ - Defaults live in `lib/legion/crypt/settings.rb` and are registered when `legion/crypt` is required. Core code reads `Legion::Settings[:crypt][...]` directly: no settings-only accessor wrappers, duplicated defaults, or nil guards around registered keys.
50
+ - mTLS uses `crypt.mtls`; SPIFFE still reads the optional Core-owned `security.spiffe` section. Do not treat the two settings paths as interchangeable.
51
+ - Include `Legion::Logging::Helper` explicitly in core modules/classes that need logging. Rescues must re-raise or call `handle_exception` at `:warn` or higher. Programming errors must propagate; narrow recovery to known operational failures.
52
+ - Use fully qualified Legion constants across module boundaries. New public APIs use kwargs and trailing `**`; preserve existing positional contracts unless all callers are migrated.
53
+ - Use `Legion::JSON.load` / `dump`; loaded JSON has symbol keys. Never log tokens, passwords, private keys, or decrypted plaintext.
54
+ - `start(mode: nil, **)` selects `postgresql/creds/infra` for an existing `postgresql` lease in infra mode without mutating configured leases. Fixed mode-to-role mappings remain frozen constants.
55
+ - `Legion::Crypt::Mtls.issue_cert(common_name:, alt_names: '', ttl: nil, **)` preserves explicit SAN/TTL inputs; absent TTL uses the registered default. Interface-discovery programming errors must not become loopback fallback.
56
+ - Preserve bounded shutdown, lease ownership, and generation checks: late worker results must not reinstall credentials after shutdown.
171
57
 
172
- ### JWT Usage
58
+ ## Specs and Verification
173
59
 
174
- ```ruby
175
- # Convenience methods (auto-selects keys from settings)
176
- token = Legion::Crypt.issue_token({ node_id: 'abc' }, ttl: 3600)
177
- claims = Legion::Crypt.verify_token(token)
60
+ - Mirror literal library paths and filenames in specs: `lib/legion/crypt/vault/client.rb` maps to `spec/legion/crypt/vault/client.rb`, not an `_spec.rb` file. Keep examples with the implementation they exercise; root Crypt API groups share `spec/legion/crypt.rb`.
61
+ - `.rspec` discovers `spec/legion/**/*.rb` and explicitly loads `spec/spec_helper.rb`. Preserve `lib/` precedence over `spec/` on `$LOAD_PATH` to prevent mirrored files from shadowing production requires. Keep support files outside the discovered tree.
62
+ - Require and use gemspec dependencies; do not mock them. In particular, never stub `Legion::Settings`, its loader, resolver, or returned settings hashes.
63
+ - `spec/spec_helper.rb` loads the real Settings/Resolver, isolates the settings root, installs full Crypt defaults for each example, and restores the original state afterward.
64
+ - Configure values through real bracket access or `Legion::Settings.set_prop`. Replacement Crypt configurations must retain full defaults, including nested Vault settings. Raw loader-root mutation is permitted in test setup for publication/rebuild scenarios, not as a new production access pattern.
65
+ - Prefer real libraries and local service fixtures or supported test adapters at external I/O boundaries. Cover behavior, failure propagation, and state transitions rather than forwarding calls or implementation details.
178
66
 
179
- # Direct module usage (explicit keys)
180
- token = Legion::Crypt::JWT.issue(payload, signing_key: key, algorithm: 'RS256')
181
- claims = Legion::Crypt::JWT.verify(token, verification_key: pub_key, algorithm: 'RS256')
182
- decoded = Legion::Crypt::JWT.decode(token) # no verification, inspection only
183
- ```
67
+ Run from this checkout:
184
68
 
185
- **Algorithms:**
186
- - `HS256` (default): Uses cluster secret. All cluster nodes can issue and verify.
187
- - `RS256`: Uses RSA keypair. Only the issuing node can sign; anyone with the public key can verify.
69
+ ```bash
70
+ bundle exec rubocop -A
71
+ bundle exec rspec --format json --out tmp/rspec_results.json --format progress --out tmp/rspec_progress.txt
72
+ ```
188
73
 
189
- ### External Token Verification (JWKS)
74
+ Use the full suite. After lint autocorrections, verify the corrected code; read failure details from the JSON report if specs fail.
190
75
 
191
- Verify tokens from external identity providers using their public JWKS endpoints:
76
+ ## JWT Usage
192
77
 
193
78
  ```ruby
194
- # Convenience method
195
- claims = Legion::Crypt.verify_external_token(
196
- token,
79
+ token = Legion::Crypt.issue_token({ node_id: 'abc' }, ttl: 3600)
80
+ claims = Legion::Crypt.verify_token(token)
81
+
82
+ # External provider (Entra ID)
83
+ claims = Legion::Crypt.verify_external_token(token,
197
84
  jwks_url: 'https://login.microsoftonline.com/TENANT/discovery/v2.0/keys',
198
85
  issuers: ['https://login.microsoftonline.com/TENANT/v2.0'],
199
- audience: 'app-client-id'
200
- )
201
-
202
- # Direct module usage
203
- claims = Legion::Crypt::JWT.verify_with_jwks(token, jwks_url: jwks_url)
86
+ audience: 'app-client-id')
204
87
  ```
205
88
 
206
- **Flow:** decode JWT header (unverified) to extract `kid` -> `JwksClient.find_key` fetches the matching public key from cache or JWKS endpoint -> verify JWT signature with the public key.
207
-
208
- **Options:** `issuers:` (array, multi-issuer support), `audience:` (string), `verify_expiration:` (bool, default true).
209
-
210
- **Error hierarchy:** `ExpiredTokenError`, `InvalidTokenError` (bad signature, wrong issuer, wrong audience), `DecodeError` (malformed token) — all inherit from `Legion::Crypt::JWT::Error`.
211
-
212
- **Used by:** `lex-identity` Entra runner for Digital Worker OIDC token validation.
213
-
214
- ---
215
-
216
- **Maintained By**: Matthew Iverson (@Esity)
89
+ Error hierarchy: `ExpiredTokenError`, `InvalidTokenError`, `DecodeError` — all inherit `Legion::Crypt::JWT::Error`.
data/CODEOWNERS CHANGED
@@ -11,9 +11,9 @@
11
11
 
12
12
  # Vault integration
13
13
  # lib/legion/crypt/vault.rb @Esity @future-security-team
14
- # lib/legion/crypt/vault_jwt_auth.rb @Esity @future-security-team
15
- # lib/legion/crypt/vault_renewer.rb @Esity @future-security-team
16
- # lib/legion/crypt/vault_cluster.rb @Esity @future-security-team
14
+ # lib/legion/crypt/vault/jwt_auth.rb @Esity @future-security-team
15
+ # lib/legion/crypt/vault/renewer.rb @Esity @future-security-team
16
+ # lib/legion/crypt/vault/cluster.rb @Esity @future-security-team
17
17
  # lib/legion/crypt/lease_manager.rb @Esity @future-security-team
18
18
 
19
19
  # JWT and JWKS
@@ -22,7 +22,7 @@
22
22
 
23
23
  # Auth integrations
24
24
  # lib/legion/crypt/ldap_auth.rb @Esity @future-security-team
25
- # lib/legion/crypt/vault_kerberos_auth.rb @Esity @future-security-team
25
+ # lib/legion/crypt/vault/kerberos_auth.rb @Esity @future-security-team
26
26
 
27
27
  # Cluster secret
28
28
  # lib/legion/crypt/cluster_secret.rb @Esity @future-security-team
data/Gemfile CHANGED
@@ -4,6 +4,7 @@ source 'https://rubygems.org'
4
4
 
5
5
  gemspec
6
6
  group :test do
7
+ gem 'legionio', '~> 1.9.52', require: false
7
8
  gem 'rake'
8
9
  gem 'rspec'
9
10
  gem 'rspec_junit_formatter'
@@ -12,4 +13,6 @@ group :test do
12
13
  gem 'simplecov'
13
14
  end
14
15
  gem 'legion-logging'
15
- gem 'legion-settings'
16
+ companion_root = File.directory?(File.expand_path('.ci-dependencies', __dir__)) ? '.ci-dependencies' : '..'
17
+ settings_path = File.expand_path("#{companion_root}/legion-settings", __dir__)
18
+ gem 'legion-settings', **(File.directory?(settings_path) ? { path: settings_path } : {})