lex-vault 0.1.4 → 0.2.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 8b1239e2e668422b877334e48f0dc7114df4a39a79f3997c9e66bc75bed6671c
4
- data.tar.gz: 532bf55b59fd3347d7ce31c75712358f17f4d6426dcce797fdb6348d1a80e90e
3
+ metadata.gz: e496080f19fec686ae3a8d90aeb5abe7d785d110dd772f0da687f610a2793b86
4
+ data.tar.gz: 7e31745a575998a7c260dbbcf2470da8276521384c2c702af94f991905f26389
5
5
  SHA512:
6
- metadata.gz: d64b6063fa32cb71660d812dc7f56ca033449340b5b0d455866fe668dbcc505b729a584229aba32c2a238cce7b74136bfc00375453d7469ef0bbaa8bcff5e3ff
7
- data.tar.gz: a6639216a26e806604ed1ca5bd11e49524e7b7aedaf7932d2ceb7da7143ed9369a1c43fbb1a5d83be7452f49142f1c4070b5c0434861a9b06885ff9499256ded
6
+ metadata.gz: d6b467f216a25cb1f851ce7524a2ea00012786de6c17c8c1567179ddcd1bafc75f671ab23e7587194d4efcfc0cc19abc5d18e57d613aed266ef456e99bcb6794
7
+ data.tar.gz: 8d3dbc3ae5987461bbb3a6b7fdefcfcac7b46c9b17f1ebe9011264d81647d087d30eb9ce233c0d94f9e05ca2e53ea21b5a3bf49f4f349a98adbe0883c91ccf54
data/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.0] - 2026-11-13
4
+
5
+ ### Added
6
+ - `Vault::Auth` nested sub-extension: `Runners::Token#validate`, `Runners::UserPass#login` (LDAP), `Runners::AppRole#login` — auth-method token minting as first-class framework runners (own settings tree, AMQP prefix, meta-actors, MCP tools)
7
+ - Credential resolver (`Helpers::Auth#auth_resolve`): `token:` / `auth:` / settings precedence, single resolution point for every runner
8
+ - `Runners::Consul` and `Runners::Nomad` dynamic secrets engines
9
+ - `Errors`: `AuthUnresolved`, `APIError` (numeric code + Vault message, via the `Raiser` Faraday middleware), `ReadOnlyError`
10
+ - `read_only: true` guard on all write/mutating methods
11
+ - Ephemeral auth: `auth: { method:, ... }` opts mint a token for the call and toss it — no token state in the gem
12
+
13
+ ### Changed (breaking)
14
+ - `remote_invocable?` is now `false` for both `Vault` and `Vault::Auth` — no meta-actors or AMQP dispatch surface. The task engine does not promise exactly-once execution; queuing secrets-engine side effects behind redelivery is a mismatch. Supported paths: in-process module calls, the standalone `Client`, MCP (synchronous). Per-runner re-enablement via `runners.<name>.remote_invocable` settings remains available.
15
+ - Runner return shapes: JSON bodies are returned directly with symbol keys (no `{ result: }` double-wrap); empty-body responses return `{ status: <int> }`; `Pki#ca_chain` (text PEM) wraps as `{ data: <body> }`
16
+ - Non-2xx Vault responses now raise `APIError` instead of returning the error body as data (`health`/`seal_status` exempt — their non-200 statuses are data)
17
+ - Unresolvable credentials raise `AuthUnresolved` instead of sending unauthenticated requests
18
+ - `KV#patch_secret` serializes the merge-patch body explicitly (Faraday's json middleware skips serialization when a non-JSON Content-Type is pre-set)
19
+ - Standalone `Client` seeds the resolver from constructor opts (`default_credentials` override); no longer overrides `connection`
20
+ - Nomad `read_role` corrected to GET `/role/{name}`; `generate_credential` corrected to POST `/cred/{accessor}` (the previous implementation never actually minted credentials)
21
+
22
+ ### Notes
23
+ - Credentials are not yet redacted from logs/exception context — time-boxed to the end-to-end validation phase, tracked as the next follow-up
24
+ - The standalone `Client` does not mix in the dynamic engines or auth runners (shared method names would shadow); standalone auth uses the `auth:` descriptor
25
+
3
26
  ## [0.1.4] - 2026-03-30
4
27
 
5
28
  ### Changed
data/CLAUDE.md CHANGED
@@ -1,55 +1,44 @@
1
- # lex-vault: HashiCorp Vault Integration for LegionIO
1
+ # lex-vault
2
2
 
3
- **Repository Level 3 Documentation**
4
- - **Parent (Level 2)**: `/Users/miverso2/rubymine/legion/extensions/CLAUDE.md`
5
- - **Parent (Level 1)**: `/Users/miverso2/rubymine/legion/CLAUDE.md`
6
-
7
- ## Purpose
8
-
9
- Legion Extension that connects LegionIO to HashiCorp Vault. Provides runners for system operations, KV v2 secrets, token auth, Transit encryption, PKI certificates, lease management, and Enterprise namespace management.
10
-
11
- **GitHub**: https://github.com/LegionIO/lex-vault
12
- **License**: MIT
13
- **Version**: 0.1.3
3
+ Legion Extension connecting LegionIO to HashiCorp Vault. Provides runners for system operations, KV v2 secrets, token auth management, Transit encryption, PKI certificates, lease management, dynamic secrets (Consul, Nomad), Enterprise namespace management, and auth-method token minting (LDAP, AppRole).
14
4
 
15
5
  ## Architecture
16
6
 
17
7
  ```
18
8
  Legion::Extensions::Vault
19
- ├── Runners/
20
- │ ├── System # Health, seal/unseal, mounts, auth, policies
21
- │ ├── Kv # KV v2: read/write/delete/list secrets + metadata
22
- │ ├── Token # Token auth: create/lookup/renew/revoke + roles
23
- │ ├── Transit # Encrypt/decrypt/sign/verify/hash/random
24
- │ ├── Pki # Issue/sign/revoke certs, CA chain, roles
25
- │ ├── Leases # Lookup/renew/revoke leases
26
- │ └── Namespaces # Vault Enterprise namespace management (list, get, create, delete)
9
+ ├── Errors/ # AuthUnresolved, APIError (code+message), ReadOnlyError, Raiser (Faraday middleware)
27
10
  ├── Helpers/
28
- │ └── Client # Faraday connection builder (X-Vault-Token + namespace)
29
- ├── Transport/ # AMQP transport scaffolding (exchanges/queues/messages — populated on demand)
30
- └── Client # Standalone client class (includes all runners)
31
- ```
32
-
33
- ## Dependencies
34
-
35
- | Gem | Purpose |
36
- |-----|---------|
37
- | `faraday` | HTTP client for Vault REST API |
38
-
39
- ## Connection
40
-
41
- The client accepts `address` (matching Vault's `VAULT_ADDR`, default `http://127.0.0.1:8200`), `token`, and optional `namespace` (Enterprise). All API calls go through `/v1/` prefix.
42
-
43
- ## Testing
44
-
45
- 44 specs across 9 spec files.
46
-
47
- ```bash
48
- bundle install
49
- bundle exec rspec
50
- bundle exec rubocop
11
+ │ ├── Client # build_connection (Faraday) + connection (pipe entry) + vault_normalize
12
+ │ └── Auth # auth_resolve — the credential resolver (opts pipe policy)
13
+ ├── Runners/ # engines, flat
14
+ │ ├── System # health/seal-status (Raiser bypass: non-200 is data), seal/unseal, mounts, auth, policies
15
+ │ ├── Kv # KV v2: read/write/patch/delete secrets + versions + metadata
16
+ │ ├── Token # token auth engine management: create/lookup/renew/revoke + roles
17
+ │ ├── Transit # encrypt/decrypt/rewrap/datakey/sign/verify/hash/random + keys
18
+ │ ├── Pki # issue/sign/revoke certs, CA chain (text → { data: }), roles, tidy
19
+ │ ├── Leases # lookup/renew/revoke leases
20
+ │ ├── Namespaces # Vault Enterprise namespace CRUD
21
+ │ ├── Consul # dynamic secrets: config/access, role CRUD, generate_credential
22
+ │ └── Nomad # dynamic secrets: config access/lease, role CRUD, POST /cred/{accessor}
23
+ ├── Auth/ # nested sub-extension (own settings tree; not remotely invocable)
24
+ │ ├── Helpers/Login # vault_login — shared mint (never attaches a token)
25
+ │ └── Runners/
26
+ │ ├── Token # validate (lookup) — not a mint
27
+ │ ├── UserPass # LDAP login
28
+ │ └── AppRole # AppRole login
29
+ └── Client # standalone client (core engines only; auth via the auth: descriptor)
51
30
  ```
52
31
 
53
- ---
54
-
55
- **Maintained By**: Matthew Iverson (@Esity)
32
+ ## Key Design Decisions
33
+
34
+ - **The opts pipe.** Credential opts (`token:`, `address:`, `namespace:`, `auth: { method:, ... }`) flow through every runner's trailing `**` and are resolved in exactly one place: `Helpers::Auth#auth_resolve`. Precedence: explicit `token:` > `auth:` descriptor > settings (`extensions.vault`). Runners never touch credential keys; `connection(**)` is the only pipe entry.
35
+ - **Ephemeral minting.** An `auth:` descriptor mints a token via the matching `Vault::Auth` runner (direct module call, not through the tasker), uses it for the call, and tosses it. No token state, caching, or renewal lives in this gem — node-identity token lifecycle is legion-crypt's job.
36
+ - **Fail loud, named.** No resolvable credentials → `AuthUnresolved`; non-2xx Vault responses → `APIError` (via the `Raiser` Faraday middleware); write with `read_only: true` → `ReadOnlyError`. A raised named error is the framework's known-outcome path (`task.exception`) — runner code has no rescue blocks.
37
+ - **Returns.** JSON-body responses return the normalized body directly (symbol keys via `vault_normalize`); empty-body (204) responses return `{ status: <int> }`; the plain-text PEM endpoint (`Pki#ca_chain`) wraps as `{ data: <body> }`. No `{ result: }` double-wrap.
38
+ - **health/seal-status bypass the Raiser** (`raise_errors: false`) — their non-200 statuses (sealed, standby, uninit) are data.
39
+ - **Client is core engines only.** The dynamic engines (Consul/Nomad) and auth runners are NOT mixed into `Client` — they share generic method names (`create_role`, `login`, ...) that would shadow each other. Standalone auth: `Client.new(auth: { method: :user_pass, username:, password: })`.
40
+ - **Not remotely invocable.** Both `Vault` and `Vault::Auth` declare `remote_invocable? → false`: no meta-actors, no AMQP dispatch surface. Rationale: the task engine does not promise exactly-once execution; queuing secrets-engine side effects behind redelivery is a mismatch, and Vault calls are fast synchronous HTTP. In-process module calls, the standalone `Client`, and MCP (synchronous) are the supported paths. `transport_required?` in `Core` is a dead flag (defined, never consumed) — do not use it.
41
+ - **Consul's business token is `consul_token:`** — never the pipe's `token:` (that's the Vault credential).
42
+ - **Nomad corrections vs. the original internal implementation:** `read_role` is GET `/role/{name}` (was POST); `generate_credential` is POST `/cred/{accessor}` (was GET of the role path — it never minted).
43
+ - Depends on `faraday`. All API calls go through `/v1/`.
44
+ - Known limitation (time-boxed): credentials are NOT redacted from logs/exception context yet — plain text until end-to-end validation with a daemon is complete. Tracked as the next follow-up.
data/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # lex-vault
2
2
 
3
- HashiCorp Vault integration for [LegionIO](https://github.com/LegionIO/LegionIO). Provides runners for interacting with the Vault HTTP API covering system operations, KV v2 secrets, token auth, Transit encryption, PKI certificates, and lease management.
3
+ HashiCorp Vault integration for [LegionIO](https://github.com/LegionIO/LegionIO). Provides runners for the Vault HTTP API: system operations, KV v2 secrets, token auth management, Transit encryption, PKI certificates, lease management, dynamic secrets engines (Consul, Nomad), Enterprise namespaces, and auth-method token minting (LDAP, AppRole).
4
4
 
5
5
  ## Installation
6
6
 
@@ -8,15 +8,37 @@ HashiCorp Vault integration for [LegionIO](https://github.com/LegionIO/LegionIO)
8
8
  gem install lex-vault
9
9
  ```
10
10
 
11
+ ## Credentials
12
+
13
+ Every runner method accepts the same optional credential opts (they flow through the
14
+ method's trailing `**` and are resolved in one place):
15
+
16
+ | Opt | Meaning |
17
+ |-----|---------|
18
+ | `token:` | Use this Vault token for the call. |
19
+ | `address:` | Vault base URL (overrides the configured address). |
20
+ | `namespace:` | Enterprise namespace for the call. |
21
+ | `auth:` | `{ method: :user_pass, username:, password: }` or `{ method: :app_role, role_id:, secret_id: }` — mints a token for this call (ephemeral: used once, tossed). |
22
+
23
+ Precedence: `token:` > `auth:` > configured settings
24
+ (`Legion::Settings[:extensions][:vault]`: `address`, `token`, `namespace`).
25
+ No resolvable credentials raise `Legion::Extensions::Vault::Errors::AuthUnresolved`.
26
+
27
+ Non-2xx Vault responses raise `Legion::Extensions::Vault::Errors::APIError`
28
+ (carries the numeric `code` and Vault's message). Write methods accept
29
+ `read_only: true`, which raises `ReadOnlyError` instead of executing.
30
+
11
31
  ## Functions
12
32
 
13
33
  ### System
14
34
  `health`, `seal_status`, `seal`, `unseal`, `init`, `list_mounts`, `mount`, `unmount`, `list_auth`, `enable_auth`, `disable_auth`, `list_policies`, `get_policy`, `put_policy`, `delete_policy`
15
35
 
36
+ (`health`/`seal_status` return their non-200 statuses as data — sealed/standby/uninitialized are conditions, not errors.)
37
+
16
38
  ### KV (v2 Secrets)
17
39
  `read_secret`, `write_secret`, `patch_secret`, `delete_secret`, `delete_versions`, `undelete_versions`, `destroy_versions`, `list_secrets`, `read_metadata`, `write_metadata`, `delete_metadata`
18
40
 
19
- ### Token
41
+ ### Token (auth engine management)
20
42
  `create_token`, `lookup_token`, `lookup_self`, `renew_token`, `renew_self`, `revoke_token`, `revoke_self`, `list_accessors`, `list_token_roles`, `get_token_role`, `create_token_role`, `delete_token_role`
21
43
 
22
44
  ### Transit
@@ -31,6 +53,45 @@ gem install lex-vault
31
53
  ### Namespaces (Vault Enterprise)
32
54
  `list_namespaces`, `get_namespace`, `create_namespace`, `delete_namespace`
33
55
 
56
+ ### Consul (dynamic secrets)
57
+ `configure` (the Consul server's own token is `consul_token:`, not the Vault `token:`), `create_role`, `read_role`, `list_roles`, `delete_role`, `generate_credential`
58
+
59
+ ### Nomad (dynamic secrets)
60
+ `create_role`, `read_role`, `list_roles`, `delete_role`, `generate_credential(accessor:)` (POST `/v1/nomad/cred/{accessor}`), `configure_access`, `read_config_access`, `configure_lease`, `read_lease`, `delete_lease`
61
+
62
+ ### Auth (token minting)
63
+ `validate(token:)` — look up a token's properties. `login(username:, password:, mount: 'ldap')` — LDAP. `login(role_id:, secret_id:, mount: 'approle')` — AppRole. All return Vault's standard login envelope (`auth: { client_token:, lease_id:, ... }`).
64
+
65
+ ## Returns
66
+
67
+ - JSON-body responses: the normalized body, **symbol keys**, no wrapping
68
+ (`read_secret` → `{ data: { data: {...}, metadata: {...} } }`).
69
+ - Empty-body (204) responses: `{ status: 204 }`.
70
+ - `Pki#ca_chain` (plain-text PEM): `{ data: "-----BEGIN CERTIFICATE-----..." }`.
71
+
72
+ ## Framework Usage
73
+
74
+ lex-vault is **not remotely invocable** — no AMQP/meta-actor dispatch surface. The
75
+ task engine does not promise exactly-once execution, and queuing secrets-engine side
76
+ effects (unseal, policy writes, revokes) behind redelivery is a mismatch. Call the
77
+ runners in-process:
78
+
79
+ ```ruby
80
+ # Credentials from settings (extensions.vault) or call-time opts
81
+ Legion::Extensions::Vault::Runners::Kv.read_secret(path: 'myapp/config',
82
+ token: 'hvs.your-token')
83
+
84
+ # Mint via LDAP for a single call (ephemeral)
85
+ Legion::Extensions::Vault::Runners::Kv.read_secret(path: 'myapp/config',
86
+ auth: { method: :user_pass,
87
+ username: 'svc',
88
+ password: '...' })
89
+ ```
90
+
91
+ The MCP tool surface is unaffected (synchronous agent calls). Per-runner remote
92
+ invocability can still be re-enabled later via settings
93
+ (`runners.<name>.remote_invocable`) if a use case earns it.
94
+
34
95
  ## Standalone Usage
35
96
 
36
97
  ```ruby
@@ -53,8 +114,24 @@ client.encrypt(name: 'my-key', plaintext: Base64.strict_encode64('hello'))
53
114
 
54
115
  # Issue a PKI certificate
55
116
  client.issue(role: 'web-server', common_name: 'app.example.com')
117
+
118
+ # Or mint via the descriptor instead of holding a token
119
+ client = Legion::Extensions::Vault::Client.new(
120
+ address: 'https://vault.example.com',
121
+ auth: { method: :app_role, role_id: 'r.id', secret_id: 's.id' }
122
+ )
56
123
  ```
57
124
 
125
+ The standalone `Client` covers the core engines. The dynamic engines (Consul/Nomad)
126
+ and auth runners are framework-level units — they share generic method names
127
+ (`create_role`, `login`) that would shadow each other in one class.
128
+
129
+ ## Known limitation (time-boxed)
130
+
131
+ Credentials are not yet redacted from logs and exception context — they appear in
132
+ plain text. This is intentional during the end-to-end validation phase and is the
133
+ tracked follow-up for the next release.
134
+
58
135
  ## Requirements
59
136
 
60
137
  - Ruby >= 3.4
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'legion/extensions/vault/helpers/client'
4
+
5
+ module Legion
6
+ module Extensions
7
+ module Vault
8
+ module Auth
9
+ module Helpers
10
+ module Login
11
+ include Legion::Extensions::Vault::Helpers::Client
12
+
13
+ # Shared login for the mint-based auth methods. Bypasses
14
+ # auth_resolve on purpose: a login call must not re-enter
15
+ # resolution, and it never carries a token — that's what we're
16
+ # minting. Returns the raw parsed body; the runner normalizes.
17
+ def vault_login(mount:, body:, **opts)
18
+ base = default_credentials.merge(opts.compact)
19
+ build_connection(address: base[:address], namespace: base[:namespace])
20
+ .post("/v1/auth/#{mount}/login", body).body
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'legion/extensions/vault/auth/helpers/login'
4
+
5
+ module Legion
6
+ module Extensions
7
+ module Vault
8
+ module Auth
9
+ module Runners
10
+ module AppRole
11
+ include Legion::Extensions::Vault::Auth::Helpers::Login
12
+
13
+ def login(role_id:, secret_id:, mount: 'approle', **)
14
+ vault_normalize(vault_login(mount: mount,
15
+ body: { role_id: role_id, secret_id: secret_id },
16
+ **))
17
+ end
18
+
19
+ include Legion::Extensions::Helpers::Lex if Legion::Extensions.const_defined?(:Helpers, false) &&
20
+ Legion::Extensions::Helpers.const_defined?(:Lex, false)
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'legion/extensions/vault/helpers/client'
4
+
5
+ module Legion
6
+ module Extensions
7
+ module Vault
8
+ module Auth
9
+ module Runners
10
+ module Token
11
+ include Legion::Extensions::Vault::Helpers::Client
12
+
13
+ def validate(token:, **)
14
+ vault_normalize(connection(token: token, **).post('/v1/auth/token/lookup', { token: token }).body)
15
+ end
16
+
17
+ include Legion::Extensions::Helpers::Lex if Legion::Extensions.const_defined?(:Helpers, false) &&
18
+ Legion::Extensions::Helpers.const_defined?(:Lex, false)
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'legion/extensions/vault/auth/helpers/login'
4
+
5
+ module Legion
6
+ module Extensions
7
+ module Vault
8
+ module Auth
9
+ module Runners
10
+ module UserPass
11
+ include Legion::Extensions::Vault::Auth::Helpers::Login
12
+
13
+ def login(username:, password:, mount: 'ldap', **)
14
+ vault_normalize(vault_login(mount: mount,
15
+ body: { username: username, password: password },
16
+ **))
17
+ end
18
+
19
+ include Legion::Extensions::Helpers::Lex if Legion::Extensions.const_defined?(:Helpers, false) &&
20
+ Legion::Extensions::Helpers.const_defined?(:Lex, false)
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'legion/extensions/vault/auth/helpers/login'
4
+ require 'legion/extensions/vault/auth/runners/token'
5
+ require 'legion/extensions/vault/auth/runners/user_pass'
6
+ require 'legion/extensions/vault/auth/runners/app_role'
7
+
8
+ module Legion
9
+ module Extensions
10
+ module Vault
11
+ module Auth
12
+ extend Legion::Extensions::Core if Legion::Extensions.const_defined? :Core, false
13
+
14
+ # Declared independently of the root Vault extension: singleton
15
+ # methods do not cross nested module boundaries. Same rationale —
16
+ # no AMQP/meta-actor dispatch surface for the auth runners.
17
+ def self.remote_invocable?
18
+ false
19
+ end
20
+
21
+ def self.default_settings
22
+ {
23
+ runners: {
24
+ token: { desc: 'Validate a Vault token' },
25
+ user_pass: { desc: 'LDAP login (username/password)' },
26
+ app_role: { desc: 'AppRole login (role_id/secret_id)' }
27
+ }
28
+ }
29
+ end
30
+ end
31
+ end
32
+ end
33
+ end
@@ -7,6 +7,7 @@ require 'legion/extensions/vault/runners/token'
7
7
  require 'legion/extensions/vault/runners/transit'
8
8
  require 'legion/extensions/vault/runners/pki'
9
9
  require 'legion/extensions/vault/runners/leases'
10
+ require 'legion/extensions/vault/runners/namespaces'
10
11
 
11
12
  module Legion
12
13
  module Extensions
@@ -21,14 +22,23 @@ module Legion
21
22
  include Runners::Leases
22
23
  include Runners::Namespaces
23
24
 
25
+ # The dynamic engines (Consul/Nomad) and the auth runners are not
26
+ # mixed in: they share generic method names (create_role/login, ...)
27
+ # that would shadow each other in one class. They are framework-level
28
+ # units (own meta-actors/MCP surface); standalone auth uses the
29
+ # auth: descriptor (Client.new(auth: { method: :user_pass, ... })).
30
+
24
31
  attr_reader :opts
25
32
 
26
33
  def initialize(address: 'http://127.0.0.1:8200', token: nil, namespace: nil, **extra)
27
34
  @opts = { address: address, token: token, namespace: namespace, **extra }
28
35
  end
29
36
 
30
- def connection(**override)
31
- super(**@opts.merge(override))
37
+ # Standalone base: the constructor kwargs ARE the credential context.
38
+ # Overrides Helpers::Auth#default_credentials so standalone execution
39
+ # never touches Legion::Settings (spec §7).
40
+ def default_credentials
41
+ @opts
32
42
  end
33
43
  end
34
44
  end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'faraday'
4
+ require 'legion/json'
5
+ require 'legion/json/helper'
6
+
7
+ module Legion
8
+ module Extensions
9
+ module Vault
10
+ module Errors
11
+ class AuthUnresolved < StandardError; end
12
+ class ReadOnlyError < StandardError; end
13
+
14
+ class APIError < StandardError
15
+ attr_reader :code
16
+
17
+ def initialize(code, message)
18
+ @code = code
19
+ super(message)
20
+ end
21
+ end
22
+
23
+ class Raiser < Faraday::Middleware
24
+ include Legion::JSON::Helper
25
+
26
+ def on_complete(env)
27
+ status = env[:status].to_i
28
+ return if status < 400
29
+
30
+ raise APIError.new(status, message_from(env[:body]))
31
+ end
32
+
33
+ private
34
+
35
+ def message_from(body)
36
+ return 'vault error' unless body.is_a?(String) && !body.empty?
37
+
38
+ parsed = json_load(body)
39
+ errors = parsed[:errors] if parsed.is_a?(Hash)
40
+ errors.is_a?(Array) && errors.first.is_a?(String) ? errors.first : 'vault error'
41
+ end
42
+ end
43
+
44
+ Faraday::Response.register_middleware(vault_raiser: Raiser)
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'legion/settings'
4
+ require 'legion/extensions/vault/errors'
5
+
6
+ module Legion
7
+ module Extensions
8
+ module Vault
9
+ module Helpers
10
+ module Auth
11
+ # Resolve credentials for a single call. Precedence: explicit token:
12
+ # > auth: descriptor > settings (spec §4.3). The returned hash is the
13
+ # complete credential context; a minted token is ephemeral (C4).
14
+ def auth_resolve(**opts)
15
+ resolved = default_credentials.merge(opts.slice(:address, :token, :namespace, :auth).compact)
16
+
17
+ return resolved if resolved[:token]
18
+
19
+ descriptor = resolved[:auth]
20
+ if descriptor.is_a?(Hash) && descriptor[:method]
21
+ runner = auth_dispatch.fetch(descriptor[:method]) do
22
+ raise Legion::Extensions::Vault::Errors::AuthUnresolved,
23
+ "unsupported auth method: #{descriptor[:method]}"
24
+ end
25
+ response = runner.login(**descriptor.except(:method),
26
+ address: resolved[:address],
27
+ namespace: resolved[:namespace])
28
+ # Vault's login envelope is contract-guaranteed: auth.client_token
29
+ # on success. The Raiser means non-2xx never reaches here.
30
+ token = response[:auth][:client_token]
31
+ unless token
32
+ raise Legion::Extensions::Vault::Errors::AuthUnresolved,
33
+ "auth method #{descriptor[:method]} returned no client_token"
34
+ end
35
+
36
+ # Ephemeral (C4): the minted token exists only in this return
37
+ # value. Nothing memoizes, caches, or retains it.
38
+ resolved[:token] = token
39
+ return resolved
40
+ end
41
+
42
+ raise Legion::Extensions::Vault::Errors::AuthUnresolved,
43
+ 'no vault credentials resolvable (token, auth descriptor, or settings)'
44
+ end
45
+
46
+ # Auth method → runner module. Lazy: no load-order fragility, and the
47
+ # set changes with deferred methods (Jwt/K8s/Tls). Direct module
48
+ # call — the same send the framework uses, minus the tasker (D2).
49
+ def auth_dispatch
50
+ {
51
+ user_pass: Legion::Extensions::Vault::Auth::Runners::UserPass,
52
+ app_role: Legion::Extensions::Vault::Auth::Runners::AppRole
53
+ }
54
+ end
55
+
56
+ # The base credential context. Pure bracket access — build_settings
57
+ # guarantees Legion::Settings[:extensions][:vault] with defaults in any
58
+ # framework context. Client overrides this to return @opts (spec §7).
59
+ def default_credentials
60
+ vault = Legion::Settings[:extensions][:vault]
61
+ { address: vault[:address], token: vault[:token], namespace: vault[:namespace] }
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
67
+ end
@@ -1,20 +1,47 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'faraday'
4
+ require 'legion/json'
5
+ require 'legion/json/helper'
6
+ require 'legion/extensions/vault/errors'
7
+ require 'legion/extensions/vault/helpers/auth'
4
8
 
5
9
  module Legion
6
10
  module Extensions
7
11
  module Vault
8
12
  module Helpers
9
13
  module Client
10
- def connection(address: 'http://127.0.0.1:8200', token: nil, namespace: nil, **_opts)
14
+ include Legion::JSON::Helper
15
+ include Legion::Extensions::Vault::Helpers::Auth
16
+
17
+ # Pure Faraday builder. address is required — the resolver guarantees
18
+ # presence. token: nil skips the header (the login path relies on it).
19
+ # raise_errors: false is for informational endpoints whose non-200
20
+ # statuses are data (sys/health, sys/seal-status).
21
+ def build_connection(address:, token: nil, namespace: nil, raise_errors: true)
11
22
  Faraday.new(url: address) do |conn|
12
23
  conn.request :json
13
24
  conn.response :json, content_type: /\bjson$/
25
+ conn.response :vault_raiser if raise_errors
14
26
  conn.headers['X-Vault-Token'] = token if token
15
27
  conn.headers['X-Vault-Namespace'] = namespace if namespace
16
28
  end
17
29
  end
30
+
31
+ # The only pipe entry point for runner methods: resolve credentials,
32
+ # build the connection. Runners never touch credential keys.
33
+ def connection(**)
34
+ resolved = auth_resolve(**)
35
+ build_connection(address: resolved[:address],
36
+ token: resolved[:token],
37
+ namespace: resolved[:namespace])
38
+ end
39
+
40
+ # Symbol-key round-trip (workspace invariant). Works in framework,
41
+ # spec, and standalone contexts.
42
+ def vault_normalize(thing)
43
+ json_load(json_dump(thing))
44
+ end
18
45
  end
19
46
  end
20
47
  end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'legion/extensions/vault/errors'
4
+ require 'legion/extensions/vault/helpers/client'
5
+
6
+ module Legion
7
+ module Extensions
8
+ module Vault
9
+ module Runners
10
+ module Consul
11
+ include Legion::Extensions::Vault::Helpers::Client
12
+
13
+ # The Consul server's own token is a business kwarg (consul_token:) —
14
+ # it is not the Vault credential pipe's token.
15
+ # rubocop:disable-next Metrics/ParameterLists -- the Vault consul config/access schema
16
+ def configure(address:, consul_token:, scheme: 'https', ca_cert: nil, client_cert: nil, client_key: nil,
17
+ mount: 'consul', read_only: false, **)
18
+ raise Legion::Extensions::Vault::Errors::ReadOnlyError, 'write operations disabled (read_only mode)' if read_only
19
+
20
+ body = { address: address, scheme: scheme, token: consul_token,
21
+ ca_cert: ca_cert, client_cert: client_cert, client_key: client_key }.compact
22
+ { status: connection(**).post("/v1/#{mount}/config/access", body).status }
23
+ end
24
+
25
+ # rubocop:disable-next Metrics/ParameterLists -- the Vault consul role schema
26
+ def create_role(name:, partition: 'default', node_identities: nil, consul_namespace: nil,
27
+ consul_roles: nil, service_identities: nil, consul_policies: nil, local: true,
28
+ ttl: '31d', max_ttl: '1y', mount: 'consul', read_only: false, **)
29
+ raise Legion::Extensions::Vault::Errors::ReadOnlyError, 'write operations disabled (read_only mode)' if read_only
30
+
31
+ body = { partition: partition, node_identities: node_identities, consul_namespace: consul_namespace,
32
+ consul_roles: consul_roles, service_identities: service_identities,
33
+ consul_policies: consul_policies, local: local, ttl: ttl, max_ttl: max_ttl }.compact
34
+ { status: connection(**).post("/v1/#{mount}/roles/#{name}", body).status }
35
+ end
36
+
37
+ def read_role(name:, mount: 'consul', **)
38
+ vault_normalize(connection(**).get("/v1/#{mount}/roles/#{name}").body)
39
+ end
40
+
41
+ def list_roles(mount: 'consul', **)
42
+ vault_normalize(connection(**).get("/v1/#{mount}/roles", { list: true }).body)
43
+ end
44
+
45
+ def delete_role(name:, mount: 'consul', read_only: false, **)
46
+ raise Legion::Extensions::Vault::Errors::ReadOnlyError, 'write operations disabled (read_only mode)' if read_only
47
+
48
+ { status: connection(**).delete("/v1/#{mount}/roles/#{name}").status }
49
+ end
50
+
51
+ def generate_credential(role:, mount: 'consul', **)
52
+ vault_normalize(connection(**).get("/v1/#{mount}/creds/#{role}").body)
53
+ end
54
+
55
+ include Legion::Extensions::Helpers::Lex if Legion::Extensions.const_defined?(:Helpers, false) &&
56
+ Legion::Extensions::Helpers.const_defined?(:Lex, false)
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end