vvauth 2.6.2 → 2.7.1

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.
@@ -0,0 +1,435 @@
1
+ package vvauth
2
+
3
+ import (
4
+ "bytes"
5
+ "encoding/json"
6
+ "fmt"
7
+ "io"
8
+ "net/http"
9
+ "os"
10
+ "os/exec"
11
+ "path/filepath"
12
+ "strings"
13
+ "testing"
14
+ "time"
15
+
16
+ sshagentcrypt "github.com/131/ssh-agent-crypt"
17
+ )
18
+
19
+ type delegateTransport func(*http.Request) (*http.Response, error)
20
+
21
+ func (f delegateTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
22
+
23
+ type delegateFixture struct {
24
+ lookupDeniedOnce bool
25
+ creates int
26
+ lookups int
27
+ logins int
28
+ ttl float64
29
+ auth any
30
+ status int
31
+ payload map[string]any
32
+ routes []string
33
+ }
34
+
35
+ func newDelegateClient(t *testing.T, f *delegateFixture, parent string) *Vauth {
36
+ t.Helper()
37
+ home := t.TempDir()
38
+ rc := filepath.Join(home, ".vauthrc")
39
+ body := `vault_addr: https://synthetic.invalid
40
+ jwt_auth:
41
+ role: project
42
+ jwt: synthetic-jwt
43
+ token_cache: false
44
+ delegate:
45
+ - vauth-profile-ro
46
+ - project-ro
47
+ env:
48
+ map:
49
+ VAULT_ROUTER_TOKEN: $${delegate.vauth-profile-ro}
50
+ PROJECT_TOKEN: $$delegate.project-ro
51
+ `
52
+ if err := os.WriteFile(rc, []byte(body), 0600); err != nil {
53
+ t.Fatal(err)
54
+ }
55
+ for name, value := range map[string]string{"VAUTHRC": rc, "HOME": home, "VAULT_TOKEN": parent, "VAULT_ADDR": "", "SSH_AUTH_SOCK": "", "SSH_AGENT_CRYPT_KEY": "", "VAUTH_USER_IDENTITY": "", "VAUTH_USER_MAIL": ""} {
56
+ t.Setenv(name, value)
57
+ }
58
+ v, err := New()
59
+ if err != nil {
60
+ t.Fatal(err)
61
+ }
62
+ v.Stderr = io.Discard
63
+ v.Now = func() time.Time { return time.UnixMilli(100000) }
64
+ v.HTTPClient = &http.Client{Transport: delegateTransport(func(r *http.Request) (*http.Response, error) {
65
+ status := 200
66
+ var response any
67
+ switch {
68
+ case r.URL.Path == "/v1/auth/token/lookup-self":
69
+ f.lookups++
70
+ if f.lookupDeniedOnce && f.lookups == 1 {
71
+ status = 403
72
+ }
73
+ response = map[string]any{"data": map[string]any{"ttl": f.ttl, "entity_id": "synthetic-entity"}}
74
+ case r.URL.Path == "/v1/auth/jwt/login":
75
+ f.logins++
76
+ response = map[string]any{"auth": map[string]any{"client_token": "synthetic-new-parent", "lease_duration": 2000}}
77
+ case r.URL.Path == "/v1/identity/entity/id/synthetic-entity":
78
+ response = map[string]any{"data": map[string]any{"metadata": map[string]any{}}}
79
+ case strings.HasPrefix(r.URL.Path, "/v1/auth/token/create/"):
80
+ f.creates++
81
+ f.routes = append(f.routes, r.URL.Path)
82
+ if r.Header.Get("X-Vault-Token") != v.VAULT_TOKEN() {
83
+ t.Error("wrong parent")
84
+ }
85
+ if err := json.NewDecoder(r.Body).Decode(&f.payload); err != nil {
86
+ t.Error(err)
87
+ }
88
+ auth := f.auth
89
+ if auth == nil {
90
+ auth = map[string]any{"client_token": fmt.Sprintf("synthetic-child-%d", f.creates), "lease_duration": 1000}
91
+ }
92
+ response = map[string]any{"auth": auth}
93
+ if f.status != 0 {
94
+ status = f.status
95
+ }
96
+ default:
97
+ t.Errorf("unexpected route %s", r.URL.Path)
98
+ }
99
+ body, err := json.Marshal(response)
100
+ return &http.Response{StatusCode: status, Body: io.NopCloser(bytes.NewReader(body)), Header: http.Header{}}, err
101
+ })}
102
+ return v
103
+ }
104
+
105
+ func TestDelegateNativeEnvironment(t *testing.T) {
106
+ f := &delegateFixture{ttl: 1234.5}
107
+ v := newDelegateClient(t, f, "synthetic-parent")
108
+ env, err := v.Env(false)
109
+ if err != nil {
110
+ t.Fatal(err)
111
+ }
112
+ if env.Values["VAULT_TOKEN"] != "synthetic-parent" || env.Values["VAULT_ROUTER_TOKEN"] == "synthetic-parent" || env.Values["VAULT_ROUTER_TOKEN"] == env.Values["PROJECT_TOKEN"] {
113
+ t.Fatal("incorrect delegation exports")
114
+ }
115
+ if env.Len() != 4 || f.creates != 2 || f.logins != 0 {
116
+ t.Fatal("unexpected exports/login count")
117
+ }
118
+ if len(f.payload) != 4 || f.payload["ttl"] != "1234.5s" || f.payload["renewable"] != false || f.payload["no_default_policy"] != true || f.payload["type"] != "service" {
119
+ t.Fatalf("incorrect creation payload: %v", f.payload)
120
+ }
121
+ v.Config.Env.Map = OrderedMap{}
122
+ env, err = v.Env(false)
123
+ if err != nil || env.Len() != 2 {
124
+ t.Fatal("implicit delegation export")
125
+ }
126
+ if _, err := os.Stat(filepath.Join(v.HomeDir, ".vauth")); !os.IsNotExist(err) {
127
+ t.Fatal("disk cache used when off")
128
+ }
129
+ }
130
+
131
+ func TestDelegateFullTTLAndIsolation(t *testing.T) {
132
+ f := &delegateFixture{ttl: 1234.5}
133
+ v := newDelegateClient(t, f, "synthetic-parent")
134
+ clock := time.UnixMilli(100000)
135
+ v.Now = func() time.Time { return clock }
136
+ first, err := v.Delegate("vauth-profile-ro", false)
137
+ if err != nil {
138
+ t.Fatal(err)
139
+ }
140
+ clock = clock.Add(1000*time.Second - time.Millisecond)
141
+ token, err := v.Delegate("vauth-profile-ro", false)
142
+ if err != nil || token != first || f.creates != 1 || f.lookups != 1 {
143
+ t.Fatal("cache hit did not use full TTL")
144
+ }
145
+ clock = clock.Add(time.Millisecond)
146
+ token, err = v.Delegate("vauth-profile-ro", false)
147
+ if err != nil || token == first {
148
+ t.Fatal("expiry did not emit")
149
+ }
150
+ if _, err := v.Delegate("vauth-profile-ro", true); err != nil {
151
+ t.Fatal(err)
152
+ }
153
+ if _, err := v.Delegate("project-ro", false); err != nil {
154
+ t.Fatal(err)
155
+ }
156
+ if f.creates != 4 || f.logins != 0 {
157
+ t.Fatal("renew must not login parent")
158
+ }
159
+ if _, err := v.Connect(true); err != nil {
160
+ t.Fatal(err)
161
+ }
162
+ if _, err := v.Delegate("vauth-profile-ro", false); err != nil {
163
+ t.Fatal(err)
164
+ }
165
+ if f.creates != 5 || f.logins != 1 {
166
+ t.Fatal("parent change did not isolate cache")
167
+ }
168
+ for key, cache := range v.delegates {
169
+ body, _ := json.Marshal(cache)
170
+ if strings.Contains(key, "synthetic") || strings.Contains(string(body), "parent") {
171
+ t.Fatal("parent in cache")
172
+ }
173
+ }
174
+ if delegateKey("https://other.invalid", "synthetic-parent", "vauth-profile-ro") == delegateKey(v.VAULT_ADDR(), "synthetic-parent", "vauth-profile-ro") {
175
+ t.Fatal("address not isolated")
176
+ }
177
+ }
178
+
179
+ func TestDelegateErrorsAndNoPartialOutput(t *testing.T) {
180
+ for _, auth := range []any{false, map[string]any{}, map[string]any{"client_token": "synthetic-parent", "lease_duration": 10}, map[string]any{"client_token": "child", "lease_duration": 0}, map[string]any{"client_token": "child", "lease_duration": 11}, map[string]any{"client_token": "child", "lease_duration": -1}, map[string]any{"client_token": "child", "lease_duration": "10"}} {
181
+ f := &delegateFixture{ttl: 10, auth: auth}
182
+ v := newDelegateClient(t, f, "synthetic-parent")
183
+ var output bytes.Buffer
184
+ v.Stdout = &output
185
+ if err := v.Dotenv(); err == nil || output.Len() != 0 {
186
+ t.Fatal("invalid response published")
187
+ }
188
+ }
189
+ for _, ttl := range []float64{0, -1} {
190
+ v := newDelegateClient(t, &delegateFixture{ttl: ttl}, "synthetic-parent")
191
+ if _, err := v.Delegate("role", false); err == nil {
192
+ t.Fatal("invalid parent TTL accepted")
193
+ }
194
+ }
195
+ v := newDelegateClient(t, &delegateFixture{ttl: 10, status: 403}, "synthetic-parent")
196
+ if _, err := v.Env(false); err == nil {
197
+ t.Fatal("issuance error ignored")
198
+ }
199
+ for _, macro := range []string{"$${delegate.unknown}", "$$delegate.unknown", "$${delegate}"} {
200
+ v := newDelegateClient(t, &delegateFixture{ttl: 1234.5}, "synthetic-parent")
201
+ v.Config.Env.Map.Set("OK", "value")
202
+ v.Config.Env.Map.Set("BAD", macro)
203
+ var output bytes.Buffer
204
+ v.Stdout = &output
205
+ if err := v.Dotenv(); err == nil || !strings.Contains(err.Error(), "Unknown Vault delegation") || output.Len() != 0 {
206
+ t.Fatal("unknown macro published")
207
+ }
208
+ }
209
+ v = newDelegateClient(t, &delegateFixture{ttl: 10}, "synthetic-parent")
210
+ for _, role := range []string{"", "../other", ".", ".."} {
211
+ if _, err := v.Delegate(role, false); err == nil {
212
+ t.Fatal("invalid role accepted")
213
+ }
214
+ }
215
+ for _, roles := range []string{"null", "{}", "[{}]"} {
216
+ if _, err := ParseConfig([]byte("delegate: "+roles), "test", nil); err == nil {
217
+ t.Fatal("invalid role config accepted")
218
+ }
219
+ }
220
+ }
221
+
222
+ // Runs under the existing TestMain agent, or skips in the socket-free recipe.
223
+ func TestDelegateEncryptedInterop(t *testing.T) {
224
+ agent := exec.Command("ssh-agent", "-s")
225
+ out, err := agent.Output()
226
+ if err != nil {
227
+ t.Skip("sandbox cannot start a synthetic ssh-agent")
228
+ }
229
+ socketMatch := strings.Split(strings.Split(string(out), "SSH_AUTH_SOCK=")[1], ";")[0]
230
+ pid := strings.Split(strings.Split(string(out), "SSH_AGENT_PID=")[1], ";")[0]
231
+ defer exec.Command("kill", pid).Run()
232
+ directory := t.TempDir()
233
+ key := filepath.Join(directory, "key")
234
+ if out, err := exec.Command("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", key).CombinedOutput(); err != nil {
235
+ t.Fatalf("keygen: %v %s", err, out)
236
+ }
237
+ f := &delegateFixture{ttl: 1234.5}
238
+ v := newDelegateClient(t, f, "synthetic-parent")
239
+ t.Setenv("SSH_AUTH_SOCK", socketMatch)
240
+ add := exec.Command("ssh-add", key)
241
+ if out, err := add.CombinedOutput(); err != nil {
242
+ t.Fatalf("ssh-add: %v %s", err, out)
243
+ }
244
+ v.Agent = socketMatch
245
+ v.TokenCache = true
246
+ v.Now = time.Now
247
+ token, err := v.Delegate("vauth-profile-ro", false)
248
+ if err != nil {
249
+ t.Fatal(err)
250
+ }
251
+ file := v.delegateFile(delegateKey(v.VAULT_ADDR(), v.VAULT_TOKEN(), "vauth-profile-ro"))
252
+ armor, err := os.ReadFile(file)
253
+ if err != nil {
254
+ t.Fatal(err)
255
+ }
256
+ if !bytes.HasPrefix(armor, []byte("ssh-agent-crypt:v3:")) || bytes.Contains(armor, []byte(token)) || bytes.Contains(armor, []byte(v.VAULT_TOKEN())) {
257
+ t.Fatal("cache not encrypted")
258
+ }
259
+ info, _ := os.Stat(file)
260
+ if info.Mode().Perm() != 0600 {
261
+ t.Fatal("cache permissions")
262
+ }
263
+ // Node reads Go's cache through the public Delegate API, then forces a new
264
+ // encrypted child; Go consumes that child without a Vault lookup.
265
+ script := `const fs=require('fs');const V=require('./index');const v=Object.create(V.prototype);
266
+ Object.defineProperties(v,{VAULT_ADDR:{value:'https://synthetic.invalid'},VAULT_TOKEN:{value:'synthetic-parent'},RC:{value:{token_cache:true}}});
267
+ v.Connect=async()=>v.VAULT_TOKEN;v.LookupSelf=async()=>({ttl:1234.5});
268
+ v.Request=async()=>({body:JSON.stringify({auth:{client_token:'synthetic-node-child',lease_duration:1000}})});
269
+ (async()=>{const t=await v.Delegate('vauth-profile-ro');if(t!==process.argv[1])throw Error('interop cache miss');await v.Delegate('vauth-profile-ro',true)})().catch(()=>process.exit(1));`
270
+ node := exec.Command("node", "-e", script, token)
271
+ node.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + v.HomeDir, "SSH_AUTH_SOCK=" + socketMatch}
272
+ if out, err := node.CombinedOutput(); err != nil {
273
+ t.Fatalf("Node interop: %v %s", err, out)
274
+ }
275
+ v.delegates = nil
276
+ before := f.lookups
277
+ next, err := v.Delegate("vauth-profile-ro", false)
278
+ if err != nil || next != "synthetic-node-child" || f.lookups != before {
279
+ t.Fatal("Node cache not reused by Go")
280
+ }
281
+ armor, _ = os.ReadFile(file)
282
+ clear, err := sshagentcrypt.Decrypt(armor, "", &sshagentcrypt.Options{AgentSocket: socketMatch})
283
+ if err != nil || bytes.Contains(clear, []byte("synthetic-parent")) {
284
+ t.Fatal("parent in decrypted cache")
285
+ }
286
+ }
287
+
288
+ func TestDelegateCacheKeyInterop(t *testing.T) {
289
+ script := `Date.now=()=>100000;const V=require('./index');const v=Object.create(V.prototype);
290
+ Object.defineProperties(v,{VAULT_ADDR:{value:process.argv[1]},VAULT_TOKEN:{value:'synthetic-parent'},RC:{value:{token_cache:false}}});
291
+ v.Connect=async()=>{};v.LookupSelf=async()=>({ttl:100});v.Request=async()=>({body:JSON.stringify({auth:{client_token:'child',lease_duration:100}})});
292
+ v.Delegate('role.with-dots').then(()=>process.stdout.write([...v._delegates.keys()][0])).catch(()=>process.exit(1));`
293
+ for _, address := range []string{"https://synthetic.invalid/", "https://synthetic.invalid/<é>&"} {
294
+ node := exec.Command("node", "-e", script, address)
295
+ node.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + t.TempDir()}
296
+ out, err := node.Output()
297
+ if err != nil {
298
+ t.Fatal(err)
299
+ }
300
+ if string(out) != delegateKey(address, "synthetic-parent", "role.with-dots") {
301
+ t.Fatal("Node/Go cache hash mismatch")
302
+ }
303
+ }
304
+ }
305
+
306
+ func TestDelegateApprovedConfig(t *testing.T) {
307
+ config, err := ParseConfig([]byte(`vault_addr: https://vault.elipsdev.net
308
+ ssh_auth:
309
+ role: $${env.VAUTH_USER_LOGIN}
310
+ delegate:
311
+ - vauth-profile-ro
312
+ env:
313
+ map:
314
+ VAULT_ROUTER_TOKEN: $${delegate.vauth-profile-ro}
315
+ `), "test", map[string]string{"VAUTH_USER_LOGIN": "synthetic-user"})
316
+ if err != nil {
317
+ t.Fatal(err)
318
+ }
319
+ if len(config.Delegate) != 1 || config.Delegate[0] != "vauth-profile-ro" || config.Env.Map.Values["VAULT_ROUTER_TOKEN"] != "$${delegate.vauth-profile-ro}" {
320
+ t.Fatal("native config not preserved")
321
+ }
322
+ }
323
+
324
+ func TestDelegateExpiredParentLogin(t *testing.T) {
325
+ f := &delegateFixture{ttl: 1000, lookupDeniedOnce: true}
326
+ v := newDelegateClient(t, f, "synthetic-parent")
327
+ if _, err := v.Delegate("vauth-profile-ro", true); err != nil {
328
+ t.Fatal(err)
329
+ }
330
+ if f.lookups != 2 || f.logins != 1 || f.creates != 1 || v.VAULT_TOKEN() != "synthetic-new-parent" {
331
+ t.Fatal("invalid parent was not replaced exactly once")
332
+ }
333
+ }
334
+
335
+ func delayDelegateResponses(v *Vauth, clock *time.Time, lookupDelay, createDelay time.Duration) {
336
+ transport := v.HTTPClient.Transport
337
+ v.HTTPClient.Transport = delegateTransport(func(r *http.Request) (*http.Response, error) {
338
+ response, err := transport.RoundTrip(r)
339
+ switch {
340
+ case r.URL.Path == "/v1/auth/token/lookup-self":
341
+ *clock = clock.Add(lookupDelay)
342
+ case strings.HasPrefix(r.URL.Path, "/v1/auth/token/create/"):
343
+ *clock = clock.Add(createDelay)
344
+ }
345
+ return response, err
346
+ })
347
+ }
348
+
349
+ func TestDelegateDelayedResponseDeadline(t *testing.T) {
350
+ f := &delegateFixture{ttl: 10, auth: map[string]any{"client_token": "synthetic-delayed-child", "lease_duration": 5}}
351
+ v := newDelegateClient(t, f, "synthetic-parent")
352
+ clock := time.UnixMilli(100000)
353
+ v.Now = func() time.Time { return clock }
354
+ delayDelegateResponses(v, &clock, 2*time.Second, 3*time.Second)
355
+ token, err := v.Delegate("role", false)
356
+ if err != nil {
357
+ t.Fatal(err)
358
+ }
359
+ if f.payload["ttl"] != "8s" {
360
+ t.Fatal("elapsed lookup time not deducted")
361
+ }
362
+ key := delegateKey(v.VAULT_ADDR(), v.VAULT_TOKEN(), "role")
363
+ if v.delegates[key].ExpiresAt != 107000 {
364
+ t.Fatal("response time extended the child deadline")
365
+ }
366
+ clock = time.UnixMilli(106999)
367
+ hit, err := v.Delegate("role", false)
368
+ if err != nil || hit != token || f.creates != 1 || f.lookups != 1 {
369
+ t.Fatal("child not reusable until its deadline")
370
+ }
371
+ clock = time.UnixMilli(107000)
372
+ if _, err := v.Delegate("role", false); err != nil {
373
+ t.Fatal(err)
374
+ }
375
+ if f.creates != 2 || f.logins != 0 {
376
+ t.Fatal("deadline did not trigger child-only issuance")
377
+ }
378
+ }
379
+
380
+ func TestDelegateExpiredOnArrival(t *testing.T) {
381
+ for _, delay := range []time.Duration{5 * time.Second, 6 * time.Second} {
382
+ f := &delegateFixture{ttl: 10, auth: map[string]any{"client_token": "synthetic-delayed-child", "lease_duration": 5}}
383
+ v := newDelegateClient(t, f, "synthetic-parent")
384
+ clock := time.UnixMilli(100000)
385
+ v.Now = func() time.Time { return clock }
386
+ delayDelegateResponses(v, &clock, 0, delay)
387
+ var output bytes.Buffer
388
+ v.Stdout = &output
389
+ if err := v.Dotenv(); err == nil {
390
+ t.Fatal("expired child returned")
391
+ }
392
+ if len(v.delegates) != 0 || output.Len() != 0 {
393
+ t.Fatal("expired child cached or published")
394
+ }
395
+ }
396
+ }
397
+
398
+ func TestDelegateParentTTLConsumedByLookup(t *testing.T) {
399
+ for _, delay := range []time.Duration{10 * time.Second, 11 * time.Second} {
400
+ f := &delegateFixture{ttl: 10}
401
+ v := newDelegateClient(t, f, "synthetic-parent")
402
+ clock := time.UnixMilli(100000)
403
+ v.Now = func() time.Time { return clock }
404
+ delayDelegateResponses(v, &clock, delay, 0)
405
+ if _, err := v.Delegate("role", false); err == nil {
406
+ t.Fatal("exhausted parent TTL accepted")
407
+ }
408
+ if f.creates != 0 || f.logins != 0 {
409
+ t.Fatal("exhausted TTL caused issuance or login")
410
+ }
411
+ }
412
+ }
413
+
414
+ func TestDelegateRetryResetsLookupAnchor(t *testing.T) {
415
+ f := &delegateFixture{ttl: 10, lookupDeniedOnce: true, auth: map[string]any{"client_token": "synthetic-child", "lease_duration": 5}}
416
+ v := newDelegateClient(t, f, "synthetic-parent")
417
+ clock := time.UnixMilli(100000)
418
+ v.Now = func() time.Time { return clock }
419
+ transport := v.HTTPClient.Transport
420
+ v.HTTPClient.Transport = delegateTransport(func(r *http.Request) (*http.Response, error) {
421
+ response, err := transport.RoundTrip(r)
422
+ if r.URL.Path == "/v1/auth/token/lookup-self" && f.lookups == 2 {
423
+ clock = clock.Add(2 * time.Second)
424
+ } else if r.URL.Path == "/v1/auth/token/lookup-self" || r.URL.Path == "/v1/auth/jwt/login" {
425
+ clock = clock.Add(100 * time.Second)
426
+ }
427
+ return response, err
428
+ })
429
+ if _, err := v.Delegate("role", false); err != nil {
430
+ t.Fatal(err)
431
+ }
432
+ if f.payload["ttl"] != "8s" || f.logins != 1 {
433
+ t.Fatal("lookup anchor not reset after normal login retry")
434
+ }
435
+ }
package/go.mod CHANGED
@@ -1,6 +1,6 @@
1
1
  module github.com/131/vvauth/v2
2
2
 
3
- // version: 2.6.2
3
+ // version: 2.7.1
4
4
 
5
5
  go 1.22
6
6
 
package/index.js CHANGED
@@ -42,8 +42,10 @@ class Vvauth extends VauthLogin {
42
42
  super();
43
43
 
44
44
  const rc = this.RC;
45
- const config = Object.fromEntries(['env', 'ssh-agent-crypt'].filter(key => rc && Object.hasOwn(rc, key)).map(key => [key, rc[key]]));
45
+ const config = Object.fromEntries(['env', 'ssh-agent-crypt', 'delegate'].filter(key => rc && Object.hasOwn(rc, key)).map(key => [key, rc[key]]));
46
46
  this.config = walk(structuredClone(config), v => replaceEnv(v, {env : process.env}));
47
+ if(this.config.delegate !== undefined && (!Array.isArray(this.config.delegate) || this.config.delegate.some(role => typeof role !== 'string' || !/^[A-Za-z0-9_.-]+$/.test(role))))
48
+ throw new Error('Invalid Vault delegation roles: expected a list of role names');
47
49
  if(this.config.env && this.config.env.gitlab === true) {
48
50
  const {args, dict} = parseArgs();
49
51
  const missing = ['CI_PROJECT_PATH', 'CI_PROJECT_NAME', 'CI_PROJECT_NAMESPACE', 'CI_PROJECT_PATH_SLUG'].filter(key => !process.env[key]);
@@ -190,11 +192,24 @@ class Vvauth extends VauthLogin {
190
192
  secrets = {...secrets, ...data};
191
193
  }
192
194
  }
195
+ const delegate = Object.create(null);
196
+ for(const role of this.config.delegate || [])
197
+ delegate[role] = await this.Delegate(role, renew);
198
+ const expandDelegates = value => value.replace(/\$\$\{([^}]+)\}|\$\$([a-z0-9._-]+)/ig, (macro, braced, bare) => {
199
+ const key = braced || bare;
200
+ if(key.toLowerCase() !== 'delegate' && !key.toLowerCase().startsWith('delegate.'))
201
+ return macro;
202
+ const role = key.slice('delegate.'.length);
203
+ if(!Object.hasOwn(delegate, role))
204
+ throw new Error(`Unknown Vault delegation '${role}'`);
205
+ return delegate[role];
206
+ });
193
207
  for(let [k, v] of Object.entries(map)) {
194
208
  // the key reaches `export KEY=...` unescaped; .vauthrc may come from an untrusted working directory
195
209
  if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k))
196
210
  throw new Error(`Invalid environment variable name '${k}' in env.map`);
197
- env[k] = envValue(replaceEnv(envValue(v, k), {env : process.env, profile, secrets}), k);
211
+ const value = expandDelegates(envValue(v, k));
212
+ env[k] = expandDelegates(envValue(replaceEnv(value, {env : process.env, profile, secrets}), k));
198
213
  }
199
214
 
200
215
  if(source) {
@@ -270,4 +285,6 @@ const shellEscape = (arg) => {
270
285
  return "'" + String(arg).replace(/'/g, '\'"\'"\'') + "'";
271
286
  };
272
287
 
288
+ Object.assign(Vvauth.prototype, require('./delegate'));
289
+
273
290
  module.exports = Vvauth;
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "vvauth",
3
- "version": "2.6.2",
3
+ "version": "2.7.1",
4
4
  "description": "Vault Auth helper",
5
5
  "main": "index.js",
6
6
  "bin": {
7
7
  "vauth": "./cmd/vauth.js"
8
8
  },
9
9
  "scripts": {
10
- "test": "node --test test/token-cache.js",
10
+ "test": "node --test test/token-cache.js test/delegate.js",
11
11
  "eslint": "eslint ."
12
12
  },
13
13
  "author": "",
package/rc.go CHANGED
@@ -14,6 +14,7 @@ import (
14
14
  // Config contains only environment/profile settings; authentication is
15
15
  // parsed and owned by vauth-login.
16
16
  type Config struct {
17
+ Delegate []string `json:"delegate" yaml:"delegate"`
17
18
  AgentCrypt *AgentCrypt `json:"ssh-agent-crypt" yaml:"ssh-agent-crypt"`
18
19
  Env *EnvConfig `json:"env" yaml:"env"`
19
20
  }
@@ -179,11 +180,23 @@ func configFromRC(rc map[string]any, environ map[string]string) (*Config, error)
179
180
 
180
181
  func compileConfig(rc map[string]any, file string, environ map[string]string) (*Config, error) {
181
182
  selected := map[string]any{}
182
- for _, key := range []string{"env", "ssh-agent-crypt"} {
183
+ for _, key := range []string{"env", "ssh-agent-crypt", "delegate"} {
183
184
  if value, ok := rc[key]; ok {
184
185
  selected[key] = value
185
186
  }
186
187
  }
188
+ if roles, exists := selected["delegate"]; exists {
189
+ list, ok := roles.([]any)
190
+ if !ok {
191
+ return nil, fmt.Errorf("Invalid Vault delegation roles: expected a list of role names")
192
+ }
193
+ for _, value := range list {
194
+ role, ok := value.(string)
195
+ if !ok || !delegateRole.MatchString(role) {
196
+ return nil, fmt.Errorf("Invalid Vault delegation role")
197
+ }
198
+ }
199
+ }
187
200
  // Clone the selected sections before Walk, preserving the raw RC snapshot.
188
201
  body, err := json.Marshal(selected)
189
202
  if err != nil {