vvauth 2.8.0 → 2.8.2

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.
package/API_and_tests.md CHANGED
@@ -10,6 +10,7 @@ contracts differ except for the shared calls below.
10
10
  vauth env --ir://json
11
11
  venv
12
12
  venv --renew
13
+ venv --ping
13
14
  venv --gitlab
14
15
  ```
15
16
 
@@ -22,6 +23,16 @@ nonzero. Sourcing that output returns 1 without exiting the caller or publishing
22
23
  partial exports. Successful output and non-source error output are unchanged;
23
24
  this does not cover crashes or a missing executable.
24
25
 
26
+ `env --ping` uses SDK `Ping()` in both languages (Node `Promise<void>`, Go
27
+ `error`). Node reads the current process environment; Go uses the constructor's
28
+ copied `Environ` snapshot. It checks the inherited parent plus variables mapped
29
+ exactly to declared delegation macros, not cached/replacement credentials or
30
+ other mapped secrets. It performs only trusted Vault `lookup-self` requests.
31
+ Success emits nothing; missing/rejected/unreachable/invalid credentials fail,
32
+ with `return 1` in source mode. A TTL of zero is valid (unlimited).
33
+ `--renew` and `--gitlab` conflict with `--ping`. See the
34
+ [README runtime probe contract](README.md#probe-the-current-runtime).
35
+
25
36
  ## Node CLI — cnyks
26
37
 
27
38
  ```text
@@ -37,7 +48,7 @@ methods; its interactive rendering is not the Go CLI contract.
37
48
 
38
49
  | Command | Parameters | Effect |
39
50
  | --- | --- | --- |
40
- | `env` | `--source`, `--renew`, `--gitlab` | Resolve environment, export it, or initialize GitLab variables |
51
+ | `env` | `--source`, `--renew`, `--gitlab`, `--ping` | Resolve/export environment, initialize GitLab variables or probe runtime tokens |
41
52
  | `login` | `--source`, `--renew` | Authentication only; optionally export only VAULT_TOKEN |
42
53
  | `show` | — | Merged profile/private database |
43
54
  | `set` | `--k=KEY --v=VALUE` | Store an upper-cased private key |
@@ -60,8 +71,10 @@ vauth <command> [positionals...] [--flag=value] [--ir://json]
60
71
  Commands are `env`, `login`, `show`, `set`, `unset`, `dotenv`, `install`, `version`
61
72
  and `gitlab`. `set KEY VALUE` / `unset KEY` also accept `--k` / `--v`. Boolean
62
73
  flags accept true, false, 0 and empty forms. `env` supports source, renew and
63
- gitlab flags; `login` supports source and renew. Hidden `connect` remains
64
- available for token-only callers. No command runner is part of this API.
74
+ gitlab and ping flags; `login` supports source and renew. Hidden `connect` remains
75
+ available for token-only callers. `login --source` exports only `VAULT_TOKEN`
76
+ and the resolved `VAULT_ADDR`, without fetching profile data, resolving mapped
77
+ secrets, or issuing delegated tokens. No command runner is part of this API.
65
78
 
66
79
  Objects are JSON, strings are raw without JSON mode, and version is one line.
67
80
  Exit is zero on success and one on failure; errors go to stderr.
@@ -73,6 +86,7 @@ const Vauth = require('vvauth');
73
86
  const client = new Vauth();
74
87
  const token = await client.Connect(renew);
75
88
  const env = await client.Env(source, renew, gitlab);
89
+ await client.Ping(); // validates current process credentials; no exports
76
90
  await client.Login(source, renew);
77
91
  const profile = await client.Show();
78
92
  await client.Set(key, value);
@@ -84,6 +98,7 @@ await client.Gitlab();
84
98
  client, err := vvauth.New()
85
99
  token, err := client.Connect(renew)
86
100
  env, err := client.Env(renew)
101
+ err = client.Ping() // validates the inherited Environ snapshot
87
102
  err = client.Login(source, renew)
88
103
  profile, err := client.Show()
89
104
  err = client.Set(key, value)
@@ -150,7 +165,11 @@ GOOS=windows GOARCH=amd64 go build ./cmd/vauth
150
165
 
151
166
  `test/env-source.js` checks exact failure stdout, nonzero CLI status, Bash
152
167
  process-substitution sourcing and continued execution, plus successful exports,
153
- renewal flags and non-source failures. It uses temporary homes/configurations
168
+ renewal flags and non-source failures. It also covers ping success, expired
169
+ parents/children, missing credentials, network/response failures, unchanged
170
+ shell credentials and secret-free diagnostics. `ping_test.go` checks the native
171
+ SDK runtime snapshot; the same shared test file checks the Node SDK probe.
172
+ The CLI fixtures use temporary homes/configurations
154
173
  and a loopback Vault. `cmd/vauth/main_test.go` builds the native Go CLI and runs
155
174
  the same checks against that executable (requires Node and Bash).
156
175
 
package/README.md CHANGED
@@ -22,6 +22,7 @@ vauth install
22
22
  source ~/.bashrc
23
23
  venv
24
24
  venv --renew
25
+ venv --ping
25
26
  ```
26
27
 
27
28
  `vauth install` defines the Bash function `venv` in `~/.bashrc`:
@@ -46,6 +47,22 @@ Both implementations write one JSON object to stdout; diagnostics remain on
46
47
  stderr. Node uses cnyks for its CLI; Go has a native command interface.
47
48
  [API_and_tests.md](API_and_tests.md) defines both contracts.
48
49
 
50
+ ## Probe the current runtime
51
+
52
+ `venv --ping` (or `vauth env --ping`) validates the inherited `VAULT_TOKEN`
53
+ and each inherited variable mapped exactly to a declared `$${delegate.role}`
54
+ or `$$delegate.role` in the selected RC. Other mapped secrets are not probed.
55
+ Each credential is sent only to that configuration's trusted Vault `lookup-self`;
56
+ a valid TTL of zero denotes an unlimited token. Missing credentials, rejected
57
+ lookups, invalid responses and unreachable Vault fail with status 1.
58
+
59
+ The probe never logs in, renews, resolves profiles, reads token caches, issues
60
+ children or changes the environment. It checks the invoking runtime, not an
61
+ already-running daemon's environment. Success is silent, including with
62
+ `--source` and `--ir://json`; `--source` failures output only `return 1`.
63
+ Diagnostics identify the variable and failure, never its token or response body.
64
+ `--ping` cannot be combined with `--renew` or `--gitlab`.
65
+
49
66
  ## Configuration
50
67
 
51
68
  The first existing configuration is selected: `VAUTHRC`, `./.vauthrc`, then
package/cmd/vauth/main.go CHANGED
@@ -17,7 +17,7 @@ import (
17
17
  const usage = `Usage: vauth <command> [--flag[=value]] [--ir://json]
18
18
 
19
19
  Commands:
20
- env [--source] [--renew] Resolve the .vauthrc environment (JSON with --ir://json)
20
+ env [--source] [--renew | --ping] Resolve the .vauthrc environment (JSON with --ir://json)
21
21
  login [--source] [--renew] Authenticate; --source exports VAULT_TOKEN
22
22
  dotenv Print the environment as K=v lines
23
23
  show Print the identity profile and .vauth_database
@@ -97,10 +97,11 @@ func main() {
97
97
 
98
98
  func run(argv []string) (err error) {
99
99
  args, dict := parseArgs(argv)
100
+ ping := truthy(dict["ping"], dict["ping"] != "")
100
101
  if len(args) > 1 && args[0] == "env" && args[1] == "gitlab" {
101
102
  args = []string{"gitlab"}
102
103
  }
103
- if truthy(dict["gitlab"], dict["gitlab"] != "") {
104
+ if !ping && truthy(dict["gitlab"], dict["gitlab"] != "") {
104
105
  args = []string{"gitlab"}
105
106
  }
106
107
  if _, ok := dict["version"]; ok && len(args) == 0 {
@@ -136,6 +137,12 @@ func run(argv []string) (err error) {
136
137
  switch command {
137
138
  case "env":
138
139
  source, renew := truthy(param(args, dict, 0, "source")), truthy(param(args, dict, 1, "renew"))
140
+ if ping {
141
+ if renew || truthy(dict["gitlab"], dict["gitlab"] != "") {
142
+ return fmt.Errorf("--ping cannot be combined with --renew or --gitlab")
143
+ }
144
+ return v.Ping()
145
+ }
139
146
  env, err := v.Env(renew)
140
147
  if err != nil {
141
148
  return err
package/cmd/vauth.js CHANGED
@@ -9,13 +9,19 @@ const options = command ? [`--ir://run=${command}`] : [];
9
9
  if(command === 'env' && !dict['ir://json'])
10
10
  options.push('--ir://raw');
11
11
 
12
- if(command === 'env' && dict.source) {
12
+ if(command === 'env' && (dict.source || dict.ping)) {
13
13
  (async () => {
14
14
  try {
15
- await new Vvauth().Env(dict.source, dict.renew, dict.gitlab);
15
+ if(dict.ping) {
16
+ if(dict.renew || dict.gitlab)
17
+ throw new Error('--ping cannot be combined with --renew or --gitlab');
18
+ await new Vvauth().Ping();
19
+ } else {
20
+ await new Vvauth().Env(dict.source, dict.renew, dict.gitlab);
21
+ }
16
22
  } catch(err) {
17
23
  // Fail the sourced helper, not the shell that called it.
18
- process.stdout.write('return 1\n');
24
+ if(dict.source) process.stdout.write('return 1\n');
19
25
  console.error(err, err && err.stack || '');
20
26
  process.exitCode = 1;
21
27
  }
package/go.mod CHANGED
@@ -1,6 +1,6 @@
1
1
  module github.com/131/vvauth/v2
2
2
 
3
- // version: 2.8.0
3
+ // version: 2.8.2
4
4
 
5
5
  go 1.22
6
6
 
package/index.js CHANGED
@@ -88,7 +88,7 @@ class Vvauth extends VauthLogin {
88
88
  */ {
89
89
  await this.Connect(renew);
90
90
  if(source) {
91
- let env = {VAULT_TOKEN : this.VAULT_TOKEN || ''};
91
+ let env = {VAULT_TOKEN : this.VAULT_TOKEN || '', VAULT_ADDR : this.VAULT_ADDR || ''};
92
92
  this.PublishEnv(env);
93
93
  }
94
94
  }
@@ -145,6 +145,39 @@ class Vvauth extends VauthLogin {
145
145
  return {entity_id, identity, profile, database};
146
146
  }
147
147
 
148
+ // Probe inherited credentials only: never Connect, resolve Env, or read token caches.
149
+ async Ping() {
150
+ if(!this.VAULT_ADDR)
151
+ throw new Error('Vault ping requires VAULT_ADDR');
152
+ const keys = ['VAULT_TOKEN'];
153
+ const map = this.RC.env && this.RC.env.map || {};
154
+ for(const key of Object.keys(map).sort()) {
155
+ if(typeof map[key] !== 'string') continue;
156
+ const macro = map[key].match(/^\$\$(?:\{delegate\.([A-Za-z0-9_.-]+)\}|delegate\.([A-Za-z0-9_.-]+))$/i);
157
+ if(!macro) continue;
158
+ if(!(this.config.delegate || []).includes(macro[1] || macro[2]))
159
+ throw new Error('Unknown Vault delegation in env.map');
160
+ if(!keys.includes(key)) keys.push(key);
161
+ }
162
+ for(const key of keys) {
163
+ const token = process.env[key];
164
+ if(!token) throw new Error(`Vault ping requires inherited ${key}`);
165
+ let response;
166
+ try {
167
+ response = await this.Request('GET', 'auth/token/lookup-self', token, null, 0);
168
+ } catch(err) {
169
+ // Transport errors and Vault response bodies can contain credentials.
170
+ throw new Error(`Vault ping failed for ${key}: request failed`);
171
+ }
172
+ if(response.status !== 200)
173
+ throw new Error(`Vault ping failed for ${key}: HTTP ${response.status}`);
174
+ let data;
175
+ try { data = JSON.parse(response.body).data; } catch(err) { /* Invalid lookup response. */ }
176
+ if(!data || !Number.isFinite(data.ttl) || data.ttl < 0)
177
+ throw new Error(`Vault ping failed for ${key}: invalid lookup response`);
178
+ }
179
+ }
180
+
148
181
  async Env(source = false, renew = false, gitlab = false) /**
149
182
  * @alias env
150
183
  */ {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vvauth",
3
- "version": "2.8.0",
3
+ "version": "2.8.2",
4
4
  "description": "Vault Auth helper",
5
5
  "main": "index.js",
6
6
  "bin": {
package/ping_test.go ADDED
@@ -0,0 +1,72 @@
1
+ package vvauth
2
+
3
+ import (
4
+ "errors"
5
+ "io"
6
+ "net/http"
7
+ "strings"
8
+ "testing"
9
+ )
10
+
11
+ type pingTransport func(*http.Request) (*http.Response, error)
12
+
13
+ func (f pingTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
14
+
15
+ func TestPingRuntimeSnapshot(t *testing.T) {
16
+ for _, scenario := range []string{"valid", "missing", "expired child", "network", "invalid response"} {
17
+ t.Run(scenario, func(t *testing.T) {
18
+ env := map[string]string{"VAULT_ADDR": "https://synthetic.invalid", "VAULT_TOKEN": "synthetic-parent", "VAULT_ROUTER_TOKEN": "synthetic-child"}
19
+ v, err := NewFromRC([]byte(`{"delegate":["router"],"env":{"map":{"VAULT_ROUTER_TOKEN":"$${delegate.router}","SECRET":"$${secrets.secret}"}}}`), env)
20
+ if err != nil {
21
+ t.Fatal(err)
22
+ }
23
+ // Both snapshots are independent: Ping must not use changed ambient credentials.
24
+ env["VAULT_TOKEN"] = "synthetic-replacement"
25
+ t.Setenv("VAULT_TOKEN", "synthetic-ambient")
26
+ if scenario == "missing" {
27
+ delete(v.Environ, "VAULT_ROUTER_TOKEN")
28
+ }
29
+ calls := 0
30
+ v.HTTPClient = &http.Client{Transport: pingTransport(func(r *http.Request) (*http.Response, error) {
31
+ calls++
32
+ if r.Method != "GET" || r.URL.Path != "/v1/auth/token/lookup-self" {
33
+ t.Error("unexpected request")
34
+ }
35
+ token := r.Header.Get("X-Vault-Token")
36
+ if token != "synthetic-parent" && token != "synthetic-child" {
37
+ t.Error("wrong runtime token")
38
+ }
39
+ if scenario == "network" {
40
+ return nil, errors.New("synthetic-parent synthetic-child")
41
+ }
42
+ status, body := 200, `{"data":{"ttl":3600}}`
43
+ if scenario == "expired child" && token == "synthetic-child" {
44
+ status, body = 403, "synthetic-parent synthetic-child"
45
+ }
46
+ if scenario == "invalid response" {
47
+ body = "synthetic-parent synthetic-child"
48
+ }
49
+ return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{}}, nil
50
+ })}
51
+ err = v.Ping()
52
+ if scenario == "valid" {
53
+ if err != nil {
54
+ t.Fatal(err)
55
+ }
56
+ if calls != 2 {
57
+ t.Fatalf("lookups: %d", calls)
58
+ }
59
+ } else {
60
+ if err == nil {
61
+ t.Fatal("expected failure")
62
+ }
63
+ if strings.Contains(err.Error(), "synthetic-parent") || strings.Contains(err.Error(), "synthetic-child") {
64
+ t.Fatal("credential leaked")
65
+ }
66
+ }
67
+ if v.VAULT_TOKEN() != "synthetic-parent" {
68
+ t.Fatal("parent changed")
69
+ }
70
+ })
71
+ }
72
+ }
@@ -142,6 +142,32 @@ printf '%s|continued|%s|%s|%s|%s\\n' "$status" "$OK" "$COUNT" "$FLAG" "$EMPTY"
142
142
  assert.equal(shell.stdout, `0|continued|${values.OK}|42|false|\n`);
143
143
  });
144
144
 
145
+ test('login --source exports only the resolved Vault session', async t => {
146
+ const requests = [];
147
+ const f = await fixture(t, {
148
+ jwt_auth : {role : 'synthetic-role', jwt : 'synthetic-jwt'},
149
+ delegate : ['router'],
150
+ env : {paths : ['synthetic-path'], map : {ROUTER : '$${delegate.router}'}},
151
+ }, (req, res) => {
152
+ requests.push(req.url);
153
+ if(req.url === '/v1/auth/jwt/login') {
154
+ res.end('{"auth":{"client_token":"synthetic-issued","lease_duration":3600,"renewable":false}}');
155
+ } else {
156
+ res.writeHead(403);
157
+ res.end('{}');
158
+ }
159
+ });
160
+ const address = f.env.VAULT_ADDR;
161
+ delete f.env.VAULT_ADDR;
162
+ const result = await f.cli('login', '--source');
163
+ assert.equal(result.code, 0);
164
+ assert.deepEqual(result.stdout.match(/^export .*$/gm), [
165
+ "export VAULT_TOKEN='synthetic-issued'", `export VAULT_ADDR='${address}'`,
166
+ ]);
167
+ assert.doesNotMatch(result.stderr, /synthetic-issued/);
168
+ assert.deepEqual(requests, ['/v1/auth/jwt/login']);
169
+ });
170
+
145
171
  test('renew flag still forces login instead of the inherited token', async t => {
146
172
  let logins = 0;
147
173
  const f = await fixture(t, {jwt_auth : {role : 'synthetic-role', jwt : 'synthetic-jwt'}}, (req, res) => {
@@ -164,3 +190,118 @@ test('renew flag still forces login instead of the inherited token', async t =>
164
190
  assert.match(renewed.stdout, /export VAULT_TOKEN='synthetic-issued'/);
165
191
  assert.equal(logins, 1);
166
192
  });
193
+
194
+ const pingRC = {
195
+ delegate : ['router', 'project'],
196
+ env : {map : {
197
+ VAULT_ROUTER_TOKEN : '$${delegate.router}',
198
+ PROJECT_ACCESS : '$$delegate.project',
199
+ SECRET_TOKEN : '$${secrets.secret}',
200
+ PARENT_COPY : '$${env.VAULT_TOKEN}',
201
+ }},
202
+ };
203
+
204
+ for(const [name, missing, rejected, broken] of [
205
+ ['valid runtime', null, null, false],
206
+ ['unlimited token', null, null, 'unlimited'],
207
+ ['missing parent', 'VAULT_TOKEN', null, false],
208
+ ['missing delegated token', 'VAULT_ROUTER_TOKEN', null, false],
209
+ ['expired parent', null, 'synthetic-parent', false],
210
+ ['expired delegated token', null, 'synthetic-router', false],
211
+ ['unreachable Vault', null, null, true],
212
+ ['malformed lookup', null, null, 'malformed'],
213
+ ['invalid TTL', null, null, 'ttl'],
214
+ ]) {
215
+ test(`${binary ? 'Go' : 'Node'} env --ping: ${name}`, async t => {
216
+ const requests = [];
217
+ const f = await fixture(t, JSON.parse(JSON.stringify(pingRC)), (req, res) => {
218
+ requests.push([req.method, req.url, req.headers['x-vault-token']]);
219
+ if(broken === true) { req.socket.destroy(); return; }
220
+ if(req.headers['x-vault-token'] === rejected) {
221
+ res.writeHead(403);
222
+ res.end('synthetic-parent synthetic-router synthetic-project');
223
+ } else if(broken === 'malformed') {
224
+ res.end('synthetic-parent synthetic-router synthetic-project');
225
+ } else {
226
+ res.end(JSON.stringify({data : {ttl : broken === 'ttl' ? -1 : broken === 'unlimited' ? 0 : 3600}}));
227
+ }
228
+ });
229
+ Object.assign(f.env, {
230
+ VAULT_TOKEN : 'synthetic-parent', VAULT_ROUTER_TOKEN : 'synthetic-router',
231
+ PROJECT_ACCESS : 'synthetic-project', SECRET_TOKEN : 'synthetic-secret',
232
+ UNMAPPED_TOKEN : 'synthetic-unmapped',
233
+ });
234
+ if(missing) delete f.env[missing];
235
+ const valid = !missing && !rejected && (!broken || broken === 'unlimited');
236
+ for(const flags of [['--source'], [], ['--ir://json']]) {
237
+ const result = await f.cli('env', '--ping', ...flags);
238
+ assert.equal(result.code, valid ? 0 : 1);
239
+ assert.equal(result.stdout, !valid && flags.includes('--source') ? 'return 1\n' : '');
240
+ if(valid) assert.equal(result.stderr, '');
241
+ else assert.match(result.stderr, /Vault ping/);
242
+ for(const secret of ['synthetic-parent', 'synthetic-router', 'synthetic-project', 'synthetic-secret'])
243
+ assert.ok(!result.stderr.includes(secret));
244
+ }
245
+ const shell = await f.shell(`
246
+ function venv() { source <(/usr/bin/env vauth env --source "$@"); }
247
+ before_parent=\${VAULT_TOKEN-unset}
248
+ before_child=\${VAULT_ROUTER_TOKEN-unset}
249
+ venv --ping
250
+ status=$?
251
+ [ "\${VAULT_TOKEN-unset}" = "$before_parent" ] && [ "\${VAULT_ROUTER_TOKEN-unset}" = "$before_child" ] && unchanged=yes
252
+ printf '%s|continued|%s\\n' "$status" "$unchanged"
253
+ `);
254
+ assert.equal(shell.code, 0);
255
+ assert.equal(shell.stdout, `${valid ? 0 : 1}|continued|yes\n`);
256
+ assert.ok(requests.every(([method, url]) => method === 'GET' && url === '/v1/auth/token/lookup-self'));
257
+ assert.ok(requests.every(([, , token]) => ['synthetic-parent', 'synthetic-router', 'synthetic-project'].includes(token)));
258
+ if(valid) assert.deepEqual(requests.slice(0, 3).map(([, , token]) => token), ['synthetic-parent', 'synthetic-project', 'synthetic-router']);
259
+ });
260
+ }
261
+
262
+ test('ping rejects renew or gitlab without contacting Vault', async t => {
263
+ let calls = 0;
264
+ const f = await fixture(t, {}, (req, res) => { calls++; res.end('{}'); });
265
+ f.env.VAULT_TOKEN = 'synthetic-parent';
266
+ for(const flag of ['--renew', '--gitlab']) {
267
+ const result = await f.cli('env', '--source', '--ping', flag);
268
+ assert.equal(result.code, 1);
269
+ assert.equal(result.stdout, 'return 1\n');
270
+ assert.match(result.stderr, /--ping cannot be combined/);
271
+ }
272
+ assert.equal(calls, 0);
273
+ const result = await f.cli('env', '--ping', '--renew=0');
274
+ assert.equal(result.code, 1);
275
+ assert.match(result.stderr, /invalid lookup response/);
276
+ assert.equal(calls, 1);
277
+ });
278
+
279
+ test('Node SDK Ping uses live inherited credentials without Env or Connect', async t => {
280
+ const Vvauth = require('../index');
281
+ const v = Object.create(Vvauth.prototype);
282
+ Object.defineProperties(v, {
283
+ VAULT_ADDR : {value : 'https://synthetic.invalid'},
284
+ VAULT_TOKEN : {value : 'synthetic-stale-client-parent'},
285
+ RC : {value : pingRC},
286
+ });
287
+ v.config = pingRC;
288
+ const original = process.env;
289
+ process.env = {VAULT_TOKEN : 'synthetic-parent', VAULT_ROUTER_TOKEN : 'synthetic-router', PROJECT_ACCESS : 'synthetic-project'};
290
+ t.after(() => { process.env = original; });
291
+ const tokens = [];
292
+ v.Request = async (method, route, token) => {
293
+ assert.equal(method, 'GET');
294
+ assert.equal(route, 'auth/token/lookup-self');
295
+ tokens.push(token);
296
+ return {status : 200, body : '{"data":{"ttl":3600}}'};
297
+ };
298
+ v.Connect = v.Env = async () => { throw new Error('must not resolve credentials'); };
299
+ await v.Ping();
300
+ assert.deepEqual(tokens, ['synthetic-parent', 'synthetic-project', 'synthetic-router']);
301
+ v.Request = async () => { throw new Error('synthetic-parent synthetic-router'); };
302
+ await assert.rejects(v.Ping(), err => {
303
+ assert.equal(err.message, 'Vault ping failed for VAULT_TOKEN: request failed');
304
+ assert.ok(!err.stack.includes('synthetic-parent'));
305
+ return true;
306
+ });
307
+ });
package/vault.go CHANGED
@@ -3,6 +3,9 @@ package vvauth
3
3
  import (
4
4
  "encoding/json"
5
5
  "fmt"
6
+ "regexp"
7
+ "slices"
8
+ "sort"
6
9
  "strings"
7
10
 
8
11
  vauthlogin "github.com/131/vauth-login"
@@ -44,3 +47,64 @@ func (v *Vauth) vaultWrite(mount, secretPath string, data map[string]any) error
44
47
  }
45
48
  return nil
46
49
  }
50
+
51
+ var pingDelegate = regexp.MustCompile(`(?i)^\$\$(?:\{delegate\.([A-Za-z0-9_.-]+)\}|delegate\.([A-Za-z0-9_.-]+))$`)
52
+
53
+ // Ping validates inherited credentials without login, environment resolution or cache access.
54
+ // Environ is the runtime snapshot supplied to the constructor, not Connect's token.
55
+ func (v *Vauth) Ping() error {
56
+ if v.VAULT_ADDR() == "" {
57
+ return fmt.Errorf("Vault ping requires VAULT_ADDR")
58
+ }
59
+ keys := []string{"VAULT_TOKEN"}
60
+ rcEnv, _ := v.RC()["env"].(map[string]any)
61
+ mapping, _ := rcEnv["map"].(map[string]any)
62
+ var names []string
63
+ for key := range mapping {
64
+ names = append(names, key)
65
+ }
66
+ sort.Strings(names)
67
+ for _, key := range names {
68
+ value, ok := mapping[key].(string)
69
+ if !ok {
70
+ continue
71
+ }
72
+ macro := pingDelegate.FindStringSubmatch(value)
73
+ if macro == nil {
74
+ continue
75
+ }
76
+ role := macro[1]
77
+ if role == "" {
78
+ role = macro[2]
79
+ }
80
+ if !slices.Contains(v.Config.Delegate, role) {
81
+ return fmt.Errorf("Unknown Vault delegation in env.map")
82
+ }
83
+ if !slices.Contains(keys, key) {
84
+ keys = append(keys, key)
85
+ }
86
+ }
87
+ for _, key := range keys {
88
+ token := v.Environ[key]
89
+ if token == "" {
90
+ return fmt.Errorf("Vault ping requires inherited %s", key)
91
+ }
92
+ status, body, err := v.Request("GET", "auth/token/lookup-self", token, nil, 0)
93
+ // Do not expose transport errors or response bodies containing credentials.
94
+ if err != nil {
95
+ return fmt.Errorf("Vault ping failed for %s: request failed", key)
96
+ }
97
+ if status != 200 {
98
+ return fmt.Errorf("Vault ping failed for %s: HTTP %d", key, status)
99
+ }
100
+ var response struct {
101
+ Data *struct {
102
+ TTL *float64 `json:"ttl"`
103
+ } `json:"data"`
104
+ }
105
+ if json.Unmarshal(body, &response) != nil || response.Data == nil || response.Data.TTL == nil || *response.Data.TTL < 0 {
106
+ return fmt.Errorf("Vault ping failed for %s: invalid lookup response", key)
107
+ }
108
+ }
109
+ return nil
110
+ }
package/vauth.go CHANGED
@@ -368,7 +368,7 @@ func (v *Vauth) Env(renew bool) (*OrderedMap, error) {
368
368
  // .vauthrc may come from an untrusted working directory.
369
369
  var envName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
370
370
 
371
- // Login connects, and with source publishes VAULT_TOKEN as shell exports.
371
+ // Login connects without loading the Vault environment and optionally exports its credentials.
372
372
  func (v *Vauth) Login(source, renew bool) error {
373
373
  if _, err := v.Connect(renew); err != nil {
374
374
  return err
@@ -376,6 +376,7 @@ func (v *Vauth) Login(source, renew bool) error {
376
376
  if source {
377
377
  env := &OrderedMap{}
378
378
  env.Set("VAULT_TOKEN", v.VAULT_TOKEN())
379
+ env.Set("VAULT_ADDR", v.VAULT_ADDR())
379
380
  v.PublishEnv(env)
380
381
  }
381
382
  return nil