vvauth 2.5.0 → 2.6.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.
package/vauth_test.go CHANGED
@@ -18,6 +18,7 @@ import (
18
18
  "time"
19
19
 
20
20
  sshagentcrypt "github.com/131/ssh-agent-crypt"
21
+ vauthlogin "github.com/131/vauth-login"
21
22
  )
22
23
 
23
24
  const hour = 60 * 60
@@ -45,6 +46,11 @@ func TestMain(m *testing.M) {
45
46
  if out, err := add.CombinedOutput(); err != nil {
46
47
  panic(fmt.Sprintf("ssh-add: %v %s", err, out))
47
48
  }
49
+ // ssh-agent-crypt falls back to these for key selection; the real user's
50
+ // identity is not in the throwaway agent.
51
+ for _, name := range []string{"SSH_AGENT_CRYPT_KEY", "VAUTH_USER_IDENTITY", "VAUTH_USER_MAIL"} {
52
+ os.Unsetenv(name)
53
+ }
48
54
  code := m.Run()
49
55
  exec.Command("kill", pid).Run()
50
56
  os.RemoveAll(directory)
@@ -61,6 +67,9 @@ type fixtureOptions struct {
61
67
  creationTTL *int64
62
68
  lookupStatus int
63
69
  renewStatus int
70
+ metadata map[string]any
71
+ database map[string]any
72
+ secrets map[string]any
64
73
  }
65
74
 
66
75
  func seconds(value float64) *float64 { return &value }
@@ -105,7 +114,18 @@ func newFixture(t *testing.T, options fixtureOptions) *fixture {
105
114
  status(options.renewStatus)
106
115
  fmt.Fprintf(w, `{"auth":{"client_token":%q,"lease_duration":%d,"renewable":true}}`, r.Header.Get("X-Vault-Token"), 24*hour)
107
116
  case "/v1/identity/entity/id/test-entity":
108
- fmt.Fprint(w, `{"data":{"metadata":{}}}`)
117
+ json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"metadata": options.metadata}})
118
+ case "/v1/private/alice/data/.vauth_database":
119
+ if r.Method == "POST" {
120
+ var payload struct {
121
+ Data map[string]any `json:"data"`
122
+ }
123
+ json.Unmarshal(body, &payload)
124
+ f.options.database = payload.Data
125
+ }
126
+ json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"data": f.options.database}})
127
+ case "/v1/secrets/data/app":
128
+ json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"data": options.secrets}})
109
129
  default:
110
130
  w.WriteHeader(404)
111
131
  fmt.Fprint(w, `{}`)
@@ -115,19 +135,80 @@ func newFixture(t *testing.T, options fixtureOptions) *fixture {
115
135
  return f
116
136
  }
117
137
 
118
- // client avoids the real user's environment, configuration and cache.
119
- func (f *fixture) client() *Vauth {
120
- return &Vauth{
121
- RC: RC{JWTAuth: &JWTAuth{Path: "jwt", JWT: "test-jwt", Role: "test-role"}},
122
- VaultAddr: f.server.URL,
123
- Agent: agentSocket,
124
- TokenCache: true,
125
- CacheDir: filepath.Join(f.dir, ".vauth", "tokens"),
126
- Environ: map[string]string{},
127
- Stderr: io.Discard,
138
+ // configuredClient constructs through the public readers, using synthetic RC/env.
139
+ func configuredClient(t *testing.T, document map[string]any, overrides map[string]string) *Vauth {
140
+ t.Helper()
141
+ file := filepath.Join(t.TempDir(), ".vauthrc")
142
+ body, err := json.Marshal(document)
143
+ if err != nil {
144
+ t.Fatal(err)
128
145
  }
146
+ if err := os.WriteFile(file, body, 0600); err != nil {
147
+ t.Fatal(err)
148
+ }
149
+ t.Setenv("VAUTHRC", file)
150
+ t.Setenv("VAULT_TOKEN", "")
151
+ t.Setenv("VAULT_ADDR", "")
152
+ for key, value := range overrides {
153
+ t.Setenv(key, value)
154
+ }
155
+ v, err := New()
156
+ if err != nil {
157
+ t.Fatal(err)
158
+ }
159
+ v.Stderr = io.Discard
160
+ return v
161
+ }
162
+
163
+ type clientOptions struct {
164
+ token string
165
+ rc map[string]any
166
+ noAuth bool
129
167
  }
130
168
 
169
+ // client avoids the real user's configuration and cache.
170
+ func (f *fixture) client(settings ...clientOptions) *Vauth {
171
+ options := clientOptions{}
172
+ if len(settings) != 0 {
173
+ options = settings[0]
174
+ }
175
+ document := map[string]any{"vault_addr": f.server.URL, "jwt_auth": map[string]any{"path": "jwt", "jwt": "test-jwt", "role": "test-role"}}
176
+ for key, value := range options.rc {
177
+ document[key] = value
178
+ }
179
+ if options.noAuth {
180
+ delete(document, "jwt_auth")
181
+ }
182
+ v := configuredClient(f.t, document, map[string]string{"VAULT_TOKEN": options.token})
183
+ v.Agent = agentSocket
184
+ v.TokenCache = true
185
+ v.CacheDir = filepath.Join(f.dir, ".vauth", "tokens")
186
+ return v
187
+ }
188
+
189
+ // Fixture data follows the shared cache format; the application owns no cache code.
190
+ type tokenCache struct {
191
+ Token string `json:"token"`
192
+ LeaseDuration int64 `json:"lease_duration"`
193
+ Renewable bool `json:"renewable"`
194
+ ExpiresAt *int64 `json:"expires_at"`
195
+ }
196
+
197
+ func testCacheKey(v *Vauth) string {
198
+ key := strings.Trim(v.VAULT_ADDR(), "/")
199
+ body, err := json.Marshal(v.RC())
200
+ if err != nil {
201
+ panic(err)
202
+ }
203
+ rc, err := vauthlogin.ParseRC(body, "fixture RC", v.Environ)
204
+ if err != nil {
205
+ panic(err)
206
+ }
207
+ return sha256Hex(key + "/" + rc.AuthKey())
208
+ }
209
+
210
+ func cacheFile(v *Vauth) string { return filepath.Join(v.CacheDir, testCacheKey(v)+".creds") }
211
+
131
212
  func (f *fixture) paths() []string {
132
213
  var paths []string
133
214
  for _, r := range f.requests {
@@ -138,7 +219,7 @@ func (f *fixture) paths() []string {
138
219
 
139
220
  func (f *fixture) read(v *Vauth) tokenCache {
140
221
  f.t.Helper()
141
- armor, err := os.ReadFile(v.TokenCacheFile())
222
+ armor, err := os.ReadFile(cacheFile(v))
142
223
  if err != nil {
143
224
  f.t.Fatal(err)
144
225
  }
@@ -155,7 +236,18 @@ func (f *fixture) read(v *Vauth) tokenCache {
155
236
 
156
237
  func (f *fixture) write(v *Vauth, cache tokenCache) {
157
238
  f.t.Helper()
158
- if err := v.writeTokenCache(v.TokenCacheFile(), v.TokenCacheFile()+".next", &cache); err != nil {
239
+ body, err := json.Marshal(cache)
240
+ if err != nil {
241
+ f.t.Fatal(err)
242
+ }
243
+ armor, err := sshagentcrypt.Encrypt(body, "", &sshagentcrypt.Options{AgentSocket: agentSocket})
244
+ if err != nil {
245
+ f.t.Fatal(err)
246
+ }
247
+ if err := os.MkdirAll(v.CacheDir, 0700); err != nil {
248
+ f.t.Fatal(err)
249
+ }
250
+ if err := os.WriteFile(cacheFile(v), []byte(armor), 0600); err != nil {
159
251
  f.t.Fatal(err)
160
252
  }
161
253
  }
@@ -173,7 +265,8 @@ func (f *fixture) remaining(v *Vauth, ttl float64) {
173
265
 
174
266
  func (f *fixture) seed(v *Vauth, lease int64) {
175
267
  renewable := f.options.renewable == nil || *f.options.renewable
176
- v.saveTokenCache(&token{Value: "cached-token", TTL: float64(lease), LeaseDuration: lease, Renewable: renewable})
268
+ expires := time.Now().UnixMilli() + lease*1000
269
+ f.write(v, tokenCache{Token: "cached-token", LeaseDuration: lease, Renewable: renewable, ExpiresAt: &expires})
177
270
  if f.options.ttl != nil {
178
271
  f.remaining(v, *f.options.ttl)
179
272
  }
@@ -211,14 +304,14 @@ func TestLoginPersistsAndReuses(t *testing.T) {
211
304
  if cache.ExpiresAt == nil || *cache.ExpiresAt < time.Now().UnixMilli()+23*hour*1000 {
212
305
  t.Fatalf("expires_at %v", cache.ExpiresAt)
213
306
  }
214
- info, _ := os.Stat(first.TokenCacheFile())
307
+ info, _ := os.Stat(cacheFile(first))
215
308
  equal(t, info.Mode().Perm(), 0o600)
216
- info, _ = os.Stat(filepath.Dir(first.TokenCacheFile()))
309
+ info, _ = os.Stat(filepath.Dir(cacheFile(first)))
217
310
  equal(t, info.Mode().Perm(), 0o700)
218
311
  second := f.client()
219
312
  equal(t, connect(t, second, false), "fresh-token")
220
313
  equalPaths(t, f.paths(), "/v1/auth/jwt/login")
221
- entries, _ := os.ReadDir(filepath.Dir(first.TokenCacheFile()))
314
+ entries, _ := os.ReadDir(filepath.Dir(cacheFile(first)))
222
315
  equal(t, len(entries), 1)
223
316
  }
224
317
 
@@ -259,7 +352,7 @@ func TestCachedTokensReusedWithoutRevocationCheck(t *testing.T) {
259
352
  f.seed(v, 12*hour)
260
353
  equal(t, connect(t, v, false), "cached-token")
261
354
  equal(t, len(f.requests), 0)
262
- if _, _, err := v.lookupToken(v.VaultToken); err == nil {
355
+ if _, err := v.LookupSelf(v.VAULT_TOKEN()); err == nil {
263
356
  t.Fatal("lookup should fail")
264
357
  }
265
358
  }
@@ -285,12 +378,11 @@ func TestRejectedRenewalTriggersLogin(t *testing.T) {
285
378
 
286
379
  func TestServerFailuresDoNotGenerateTokens(t *testing.T) {
287
380
  f := newFixture(t, fixtureOptions{lookupStatus: 500})
288
- v := f.client()
381
+ v := f.client(clientOptions{token: "uncached-token"})
289
382
  f.seed(v, 12*hour)
290
- v.VaultToken = "uncached-token"
291
383
  for i := 0; i < 2; i++ {
292
- if _, err := v.Connect(false); err == nil {
293
- t.Fatal("connect should fail")
384
+ if _, err := v.LookupSelf(v.VAULT_TOKEN()); err == nil {
385
+ t.Fatal("lookup should fail")
294
386
  }
295
387
  }
296
388
  equalPaths(t, f.paths(), "/v1/auth/token/lookup-self", "/v1/auth/token/lookup-self")
@@ -304,15 +396,13 @@ func TestServerFailuresDoNotGenerateTokens(t *testing.T) {
304
396
  equalPaths(t, f.paths(), "/v1/auth/token/renew-self")
305
397
  }
306
398
 
307
- func TestEnvironmentTokenRespectedAndCached(t *testing.T) {
399
+ func TestInheritedTokenIsOfflineAndNotCached(t *testing.T) {
308
400
  f := newFixture(t, fixtureOptions{})
309
- v := f.client()
401
+ v := f.client(clientOptions{token: "environment-token"})
310
402
  f.seed(v, 12*hour)
311
- v.VaultToken = "environment-token"
312
403
  equal(t, connect(t, v, false), "environment-token")
313
- equal(t, f.read(v).Token, "environment-token")
314
- equal(t, f.requests[0].Token, "environment-token")
315
- equal(t, len(f.requests), 1)
404
+ equal(t, f.read(v).Token, "cached-token")
405
+ equal(t, len(f.requests), 0)
316
406
  }
317
407
 
318
408
  func TestNonExpiringTokensReused(t *testing.T) {
@@ -329,8 +419,8 @@ func TestNonExpiringTokensReused(t *testing.T) {
329
419
  func TestCorruptCacheReplaced(t *testing.T) {
330
420
  f := newFixture(t, fixtureOptions{})
331
421
  v := f.client()
332
- os.MkdirAll(filepath.Dir(v.TokenCacheFile()), 0o700)
333
- os.WriteFile(v.TokenCacheFile(), []byte("{broken"), 0o600)
422
+ os.MkdirAll(filepath.Dir(cacheFile(v)), 0o700)
423
+ os.WriteFile(cacheFile(v), []byte("{broken"), 0o600)
334
424
  equal(t, connect(t, v, false), "fresh-token")
335
425
  equal(t, f.read(v).Token, "fresh-token")
336
426
  }
@@ -338,8 +428,8 @@ func TestCorruptCacheReplaced(t *testing.T) {
338
428
  func TestPlaintextCacheNotAccepted(t *testing.T) {
339
429
  f := newFixture(t, fixtureOptions{})
340
430
  v := f.client()
341
- os.MkdirAll(filepath.Dir(v.TokenCacheFile()), 0o700)
342
- os.WriteFile(v.TokenCacheFile(), []byte(`{"token":"plain-token","lease_duration":43200,"renewable":true,"expires_at":null}`), 0o600)
431
+ os.MkdirAll(filepath.Dir(cacheFile(v)), 0o700)
432
+ os.WriteFile(cacheFile(v), []byte(`{"token":"plain-token","lease_duration":43200,"renewable":true,"expires_at":null}`), 0o600)
343
433
  equal(t, connect(t, v, false), "fresh-token")
344
434
  equalPaths(t, f.paths(), "/v1/auth/jwt/login")
345
435
  }
@@ -348,40 +438,32 @@ func TestCacheIsolation(t *testing.T) {
348
438
  f := newFixture(t, fixtureOptions{})
349
439
  first := f.client()
350
440
  f.seed(first, 12*hour)
351
- second := f.client()
352
- second.RC.JWTAuth.Role = "other-role"
441
+ second := f.client(clientOptions{rc: map[string]any{"jwt_auth": map[string]any{"path": "jwt", "jwt": "test-jwt", "role": "other-role"}}})
353
442
  equal(t, connect(t, second, false), "fresh-token")
354
- if first.TokenCacheFile() == second.TokenCacheFile() {
443
+ if cacheFile(first) == cacheFile(second) {
355
444
  t.Fatal("cache files should differ")
356
445
  }
357
446
  equal(t, f.read(first).Token, "cached-token")
358
447
  equal(t, f.read(second).Token, "fresh-token")
359
- third := f.client()
360
- third.VaultAddr = "http://other-vault.test"
361
- if third.TokenCacheKey() == first.TokenCacheKey() {
448
+ third := f.client(clientOptions{rc: map[string]any{"vault_addr": "http://other-vault.test"}})
449
+ if testCacheKey(third) == testCacheKey(first) {
362
450
  t.Fatal("cache keys should differ")
363
451
  }
364
- entries, _ := os.ReadDir(filepath.Dir(first.TokenCacheFile()))
452
+ entries, _ := os.ReadDir(filepath.Dir(cacheFile(first)))
365
453
  equal(t, len(entries), 2)
366
- armor, _ := os.ReadFile(first.TokenCacheFile())
454
+ armor, _ := os.ReadFile(cacheFile(first))
367
455
  if bytes.Contains(armor, []byte("test-jwt")) || bytes.Contains(armor, []byte("cached-token")) {
368
456
  t.Fatal("cache leaks secrets")
369
457
  }
370
458
  }
371
459
 
372
460
  func TestTokenCacheKeyMatchesNode(t *testing.T) {
373
- // sha256 of JSON.stringify({vault_addr, ssh_auth, jwt_auth}) as the Node
374
- // implementation renders it (undefined members omitted).
375
- v := &Vauth{VaultAddr: "https://vault.example.test/", RC: RC{SSHAuth: &SSHAuth{Role: "alice"}}}
376
- equal(t, v.TokenCacheKey(), sha256Hex(`{"vault_addr":"https://vault.example.test","ssh_auth":{"role":"alice"}}`))
377
- v = &Vauth{VaultAddr: "https://vault.example.test", RC: RC{JWTAuth: &JWTAuth{Path: "jwt", JWT: "x", Role: "r"}}}
378
- equal(t, v.TokenCacheKey(), sha256Hex(`{"vault_addr":"https://vault.example.test","jwt_auth":{"path":"jwt","jwt":"x","role":"r"}}`))
379
- rc, err := ParseRC([]byte("vault_addr: https://vault.example.test\nssh_auth:\n role: $${env.USER}\n"), ".vauthrc", map[string]string{"USER": "bob"})
380
- if err != nil {
381
- t.Fatal(err)
382
- }
383
- v = &Vauth{VaultAddr: rc.VaultAddr, RC: *rc}
384
- equal(t, v.TokenCacheKey(), sha256Hex(`{"vault_addr":"https://vault.example.test","ssh_auth":{"role":"bob"}}`))
461
+ v := configuredClient(t, map[string]any{"vault_addr": "https://vault.example.test/", "ssh_auth": map[string]any{"role": "alice"}}, nil)
462
+ equal(t, testCacheKey(v), sha256Hex(`https://vault.example.test/ssh/alice//`))
463
+ v = configuredClient(t, map[string]any{"vault_addr": "https://vault.example.test", "jwt_auth": map[string]any{"path": "jwt", "jwt": "x", "role": "r"}}, nil)
464
+ equal(t, testCacheKey(v), sha256Hex(`https://vault.example.test//jwt/r/jwt/x`))
465
+ v = configuredClient(t, map[string]any{"vault_addr": "https://vault.example.test", "ssh_auth": map[string]any{"role": "$${env.USER}"}}, map[string]string{"USER": "bob"})
466
+ equal(t, testCacheKey(v), sha256Hex(`https://vault.example.test/ssh/bob//`))
385
467
  }
386
468
 
387
469
  func TestRepeatedConnectReusesConnection(t *testing.T) {
@@ -395,8 +477,8 @@ func TestRepeatedConnectReusesConnection(t *testing.T) {
395
477
  func TestUnwritableCacheDoesNotPreventLogin(t *testing.T) {
396
478
  f := newFixture(t, fixtureOptions{})
397
479
  v := f.client()
398
- os.MkdirAll(filepath.Dir(filepath.Dir(v.TokenCacheFile())), 0o700)
399
- os.WriteFile(filepath.Dir(v.TokenCacheFile()), []byte("not a directory"), 0o600)
480
+ os.MkdirAll(filepath.Dir(filepath.Dir(cacheFile(v))), 0o700)
481
+ os.WriteFile(filepath.Dir(cacheFile(v)), []byte("not a directory"), 0o600)
400
482
  var stderr bytes.Buffer
401
483
  v.Stderr = &stderr
402
484
  equal(t, connect(t, v, false), "fresh-token")
@@ -405,23 +487,20 @@ func TestUnwritableCacheDoesNotPreventLogin(t *testing.T) {
405
487
  }
406
488
  }
407
489
 
408
- func TestWithoutAuthMethodTokensIgnored(t *testing.T) {
490
+ func TestWithoutAuthMethodInheritanceStillWorks(t *testing.T) {
409
491
  f := newFixture(t, fixtureOptions{lookupStatus: 403})
410
- v := f.client()
492
+ v := f.client(clientOptions{token: "uncached-token", noAuth: true})
411
493
  f.seed(v, 12*hour)
412
- v.RC = RC{}
413
- v.VaultToken = "uncached-token"
414
- equal(t, connect(t, v, false), "")
415
- equal(t, v.VaultToken, "")
494
+ equal(t, connect(t, v, false), "uncached-token")
495
+ equal(t, v.VAULT_TOKEN(), "uncached-token")
416
496
  equal(t, connect(t, v, true), "")
417
497
  equal(t, len(f.requests), 0)
418
498
  }
419
499
 
420
500
  func TestRenewIgnoresTokensAndSaves(t *testing.T) {
421
501
  f := newFixture(t, fixtureOptions{})
422
- v := f.client()
502
+ v := f.client(clientOptions{token: "environment-token"})
423
503
  f.seed(v, 12*hour)
424
- v.VaultToken = "environment-token"
425
504
  equal(t, connect(t, v, true), "fresh-token")
426
505
  equalPaths(t, f.paths(), "/v1/auth/jwt/login")
427
506
  equal(t, f.read(v).Token, "fresh-token")
@@ -488,17 +567,16 @@ func TestRenewalUpdatesLeaseBaseline(t *testing.T) {
488
567
 
489
568
  func TestNormalReuseNeverWrites(t *testing.T) {
490
569
  f := newFixture(t, fixtureOptions{})
491
- v := f.client()
570
+ v := f.client(clientOptions{token: "cached-token"})
492
571
  f.seed(v, 12*hour)
493
- v.VaultToken = "cached-token"
494
- before, _ := os.ReadFile(v.TokenCacheFile())
495
- stat, _ := os.Stat(v.TokenCacheFile())
572
+ before, _ := os.ReadFile(cacheFile(v))
573
+ stat, _ := os.Stat(cacheFile(v))
496
574
  equal(t, connect(t, v, false), "cached-token")
497
- after, _ := os.ReadFile(v.TokenCacheFile())
575
+ after, _ := os.ReadFile(cacheFile(v))
498
576
  if !bytes.Equal(before, after) {
499
577
  t.Fatal("cache rewritten")
500
578
  }
501
- again, _ := os.Stat(v.TokenCacheFile())
579
+ again, _ := os.Stat(cacheFile(v))
502
580
  equal(t, again.ModTime(), stat.ModTime())
503
581
  equal(t, len(f.requests), 0)
504
582
  }
@@ -506,11 +584,11 @@ func TestNormalReuseNeverWrites(t *testing.T) {
506
584
  func TestLookupReturnsLease(t *testing.T) {
507
585
  f := newFixture(t, fixtureOptions{ttl: seconds(hour)})
508
586
  v := f.client()
509
- info, lease, err := v.lookupToken("environment-token")
587
+ info, err := v.LookupSelf("environment-token")
510
588
  if err != nil {
511
589
  t.Fatal(err)
512
590
  }
513
- equal(t, lease, 24*hour)
591
+ equal(t, info.LeaseDuration, 24*hour)
514
592
  equal(t, info.TTL, float64(hour))
515
593
  equal(t, len(f.requests), 1)
516
594
  }
@@ -520,7 +598,7 @@ func TestTokenCacheDisabled(t *testing.T) {
520
598
  v := f.client()
521
599
  v.TokenCache = false
522
600
  equal(t, connect(t, v, false), "fresh-token")
523
- if _, err := os.Stat(v.TokenCacheFile()); err == nil {
601
+ if _, err := os.Stat(cacheFile(v)); err == nil {
524
602
  t.Fatal("cache written")
525
603
  }
526
604
  equalPaths(t, f.paths(), "/v1/auth/jwt/login")
@@ -528,27 +606,26 @@ func TestTokenCacheDisabled(t *testing.T) {
528
606
  f = newFixture(t, fixtureOptions{})
529
607
  v = f.client()
530
608
  f.seed(v, 12*hour)
531
- before, _ := os.ReadFile(v.TokenCacheFile())
609
+ before, _ := os.ReadFile(cacheFile(v))
532
610
  v.TokenCache = false
533
611
  equal(t, connect(t, v, false), "fresh-token")
534
- after, _ := os.ReadFile(v.TokenCacheFile())
612
+ after, _ := os.ReadFile(cacheFile(v))
535
613
  if !bytes.Equal(before, after) {
536
614
  t.Fatal("disabled cache touched disk")
537
615
  }
538
616
 
539
617
  f = newFixture(t, fixtureOptions{})
540
- v = f.client()
618
+ v = f.client(clientOptions{token: "environment-token"})
541
619
  v.TokenCache = false
542
- v.VaultToken = "environment-token"
543
620
  equal(t, connect(t, v, false), "environment-token")
544
- equalPaths(t, f.paths(), "/v1/auth/token/lookup-self")
545
- if _, err := os.Stat(v.TokenCacheFile()); err == nil {
621
+ equal(t, len(f.requests), 0)
622
+ if _, err := os.Stat(cacheFile(v)); err == nil {
546
623
  t.Fatal("cache written")
547
624
  }
548
625
  }
549
626
 
550
627
  func TestTokenCacheFalseFromRC(t *testing.T) {
551
- rc, err := ParseRC([]byte("vault_addr: https://vault.example.test\ntoken_cache: false\n"), ".vauthrc", map[string]string{})
628
+ rc, err := vauthlogin.ParseRC([]byte("vault_addr: https://vault.example.test\ntoken_cache: false\n"), ".vauthrc", map[string]string{})
552
629
  if err != nil {
553
630
  t.Fatal(err)
554
631
  }
@@ -561,7 +638,7 @@ func TestCacheIsArmorOnly(t *testing.T) {
561
638
  f := newFixture(t, fixtureOptions{})
562
639
  v := f.client()
563
640
  connect(t, v, false)
564
- armor, _ := os.ReadFile(v.TokenCacheFile())
641
+ armor, _ := os.ReadFile(cacheFile(v))
565
642
  if !bytes.HasPrefix(armor, []byte("ssh-agent-crypt:")) || bytes.Contains(armor, []byte("fresh-token")) {
566
643
  t.Fatalf("not armored: %q", armor[:40])
567
644
  }
@@ -583,37 +660,16 @@ func TestWithoutAgentCacheSkipped(t *testing.T) {
583
660
  f := newFixture(t, fixtureOptions{})
584
661
  v := f.client()
585
662
  f.seed(v, 12*hour)
586
- before, _ := os.ReadFile(v.TokenCacheFile())
663
+ before, _ := os.ReadFile(cacheFile(v))
587
664
  v.Agent = ""
588
665
  v.TokenCache = false // as New() does when no agent is configured
589
666
  equal(t, connect(t, v, false), "fresh-token")
590
- after, _ := os.ReadFile(v.TokenCacheFile())
667
+ after, _ := os.ReadFile(cacheFile(v))
591
668
  if !bytes.Equal(before, after) {
592
669
  t.Fatal("existing armor touched")
593
670
  }
594
671
  }
595
672
 
596
- func TestTokenStatus(t *testing.T) {
597
- v := &Vauth{VaultAddr: "https://vault.example.test"}
598
- for _, c := range []struct {
599
- ttl float64
600
- duration string
601
- }{
602
- {2*86400 + 3*hour + 20*60 + 5, "2d 3h"}, {12*hour + 30*60 + 5, "12h 30m"}, {5*60 + 20, "5m 20s"},
603
- {86400, "1d"}, {30 * 60, "30m"}, {45, "45s"}, {86400 + 20, "1d 20s"}, {hour + 5, "1h 5s"},
604
- {400*86400 + 2*hour, "1y 1month"}, {60.9, "1m 1s"},
605
- } {
606
- var stderr bytes.Buffer
607
- v.Stderr = &stderr
608
- v.tokenStatus("reused", &token{TTL: c.ttl})
609
- equal(t, stderr.String(), "Vauth token: reused · https://vault.example.test · "+c.duration+"\n")
610
- }
611
- var stderr bytes.Buffer
612
- v.Stderr = &stderr
613
- v.tokenStatus("generated", &token{})
614
- equal(t, stderr.String(), "Vauth token: generated · https://vault.example.test · valid indefinitely\n")
615
- }
616
-
617
673
  func TestOneStatusPerConnection(t *testing.T) {
618
674
  for _, c := range []struct {
619
675
  options fixtureOptions
@@ -631,11 +687,11 @@ func TestOneStatusPerConnection(t *testing.T) {
631
687
  var stderr bytes.Buffer
632
688
  v.Stderr = &stderr
633
689
  connect(t, v, false)
634
- equal(t, stderr.String(), fmt.Sprintf("Vauth token: %s · %s · %s\n", c.operation, f.server.URL, c.duration))
690
+ equal(t, stderr.String(), fmt.Sprintf("Vauth token: %s · %s\n", c.operation, c.duration))
635
691
  }
636
- f := newFixture(t, fixtureOptions{lookupStatus: 500})
692
+ f := newFixture(t, fixtureOptions{ttl: seconds(hour), renewStatus: 500})
637
693
  v := f.client()
638
- v.VaultToken = "uncached-token"
694
+ f.seed(v, 12*hour)
639
695
  var stderr bytes.Buffer
640
696
  v.Stderr = &stderr
641
697
  if _, err := v.Connect(false); err == nil {
@@ -644,21 +700,222 @@ func TestOneStatusPerConnection(t *testing.T) {
644
700
  equal(t, stderr.String(), "")
645
701
  }
646
702
 
647
- func TestReplaceEnv(t *testing.T) {
648
- dict := Lookup{"env": map[string]string{"USER": "alice"}, "profile": map[string]any{"TOKEN": "secret", "N": 3}}
649
- equal(t, ReplaceEnv("$${env.USER}", dict), "alice")
650
- equal(t, ReplaceEnv("x-$${profile.TOKEN}-$${profile.N}", dict), "x-secret-3")
651
- equal(t, ReplaceEnv("$${profile.MISSING}", dict), "$${profile.MISSING}") // unresolved macros are kept, like nyks
652
- equal(t, ReplaceEnv("plain", dict), "plain")
703
+ func sha256Hex(value string) string {
704
+ digest := sha256.Sum256([]byte(value))
705
+ return hex.EncodeToString(digest[:])
653
706
  }
654
707
 
655
- func TestHumanDiff(t *testing.T) {
656
- equal(t, HumanDiff(0, 2), "0s")
657
- equal(t, HumanDiff(59, 2), "59s")
658
- equal(t, HumanDiff(3600*24*31, 2), "1month 1d")
708
+ func TestEnvMapKeysMustBeVariableNames(t *testing.T) {
709
+ f := newFixture(t, fixtureOptions{})
710
+ v := f.client()
711
+ v.Config.Env = &EnvConfig{}
712
+ v.Config.Env.Map.Set("SAFE; printf INJECTED >&2; #", "dummy")
713
+ if _, err := v.Env(false); err == nil || !strings.Contains(err.Error(), "Invalid environment variable name") {
714
+ t.Fatalf("hostile env.map key accepted: %v", err)
715
+ }
716
+ v.Config.Env = &EnvConfig{}
717
+ v.Config.Env.Map.Set("TF_HTTP_USERNAME", "$${profile.VAUTH_USER_LOGIN}")
718
+ if _, err := v.Env(false); err != nil {
719
+ t.Fatal(err)
720
+ }
659
721
  }
660
722
 
661
- func sha256Hex(value string) string {
662
- digest := sha256.Sum256([]byte(value))
663
- return hex.EncodeToString(digest[:])
723
+ func TestCheckProjectVersion(t *testing.T) {
724
+ dir := t.TempDir()
725
+ manifest := filepath.Join(dir, "package.json")
726
+ write := func(body string) { os.WriteFile(manifest, []byte(body), 0o644) }
727
+ write(`{"dependencies":{"vvauth":"^2.5.0","yaml":"^2"}}`)
728
+ if err := CheckProjectVersion(manifest, "v2.7.1"); err != nil {
729
+ t.Fatal(err)
730
+ }
731
+ if err := CheckProjectVersion(manifest, "v3.0.0"); err == nil || !strings.Contains(err.Error(), "project requires ^2.5.0") {
732
+ t.Fatalf("v3 accepted by ^2.5.0: %v", err)
733
+ }
734
+ if err := CheckProjectVersion(manifest, "(devel)"); err != nil {
735
+ t.Fatal("devel builds must not be checked:", err)
736
+ }
737
+ write(`{"dependencies":{"yaml":"^2"}}`)
738
+ if err := CheckProjectVersion(manifest, "v0.0.1"); err != nil {
739
+ t.Fatal("unrelated dependencies must be ignored:", err)
740
+ }
741
+ if err := CheckProjectVersion(filepath.Join(dir, "missing.json"), "v1.0.0"); err != nil {
742
+ t.Fatal(err)
743
+ }
744
+ }
745
+
746
+ func TestProfileKVAndEnvironmentUseLoginTransport(t *testing.T) {
747
+ f := newFixture(t, fixtureOptions{
748
+ metadata: map[string]any{"VAUTH_USER_LOGIN": "alice", "VAUTH_USER_NAME": "Alice", "VAUTH_USER_MAIL": "alice@example.test"},
749
+ database: map[string]any{"TEAM": "ops"}, secrets: map[string]any{"API_KEY": "fixture-secret"},
750
+ })
751
+ v := f.client()
752
+ v.Config.Env = &EnvConfig{Git: true, Paths: []string{"app"}}
753
+ v.Config.Env.Map.Set("LOGIN", "$${profile.VAUTH_USER_LOGIN}")
754
+ v.Config.Env.Map.Set("TEAM", "$${profile.TEAM}")
755
+ v.Config.Env.Map.Set("API_KEY", "$${secrets.API_KEY}")
756
+ env, err := v.Env(true)
757
+ if err != nil {
758
+ t.Fatal(err)
759
+ }
760
+ for key, want := range map[string]string{"VAULT_TOKEN": "fresh-token", "LOGIN": "alice", "TEAM": "ops", "API_KEY": "fixture-secret", "GIT_AUTHOR_NAME": "Alice"} {
761
+ value, ok := env.Get(key)
762
+ if !ok {
763
+ t.Fatalf("missing %s", key)
764
+ }
765
+ equal(t, value, want)
766
+ }
767
+ equalPaths(t, f.paths(), "/v1/auth/jwt/login", "/v1/auth/token/lookup-self", "/v1/identity/entity/id/test-entity", "/v1/private/alice/data/.vauth_database", "/v1/secrets/data/app")
768
+ for _, r := range f.requests[1:] {
769
+ equal(t, r.Token, "fresh-token")
770
+ }
771
+ if err := v.Set("feature", "enabled"); err != nil {
772
+ t.Fatal(err)
773
+ }
774
+ equal(t, f.options.database["FEATURE"], "enabled")
775
+ if err := v.Unset("feature"); err != nil {
776
+ t.Fatal(err)
777
+ }
778
+ if _, ok := f.options.database["FEATURE"]; ok {
779
+ t.Fatal("unset key retained")
780
+ }
781
+ logins := 0
782
+ for _, r := range f.requests {
783
+ if strings.HasSuffix(r.Path, "/login") {
784
+ logins++
785
+ }
786
+ }
787
+ equal(t, logins, 1)
788
+ }
789
+
790
+ func TestEnvironmentConfigIsSeparateFromAuthentication(t *testing.T) {
791
+ config, err := ParseConfig([]byte(`jwt_auth: ignored
792
+ env: {map: {LOGIN: '$${env.LOGIN}'}}
793
+ ssh-agent-crypt: {path: '$${env.FILE}'}
794
+ `), ".vauthrc", map[string]string{"LOGIN": "alice", "FILE": "fixture.creds"})
795
+ if err != nil {
796
+ t.Fatal(err)
797
+ }
798
+ value, _ := config.Env.Map.Get("LOGIN")
799
+ equal(t, value, "alice")
800
+ equal(t, config.AgentCrypt.Path, "fixture.creds")
801
+ }
802
+
803
+ func TestNewConsumesCompleteRCSnapshot(t *testing.T) {
804
+ document := map[string]any{
805
+ "env": map[string]any{"map": map[string]any{"VALUE": "$${env.LOCAL_VALUE}", "USER": "$${profile.USER}"}},
806
+ "extra": map[string]any{"nested": []any{"retained"}},
807
+ }
808
+ v := configuredClient(t, document, map[string]string{"LOCAL_VALUE": "local-value", "VAULT_ADDR": "https://vault.example.test"})
809
+ value, _ := v.Config.Env.Map.Get("VALUE")
810
+ equal(t, value, "local-value")
811
+ value, _ = v.Config.Env.Map.Get("USER")
812
+ equal(t, value, "$${profile.USER}")
813
+ v.Config.Env.Map.Set("VALUE", "consumer-value")
814
+ equal(t, v.RC()["env"].(map[string]any)["map"].(map[string]any)["VALUE"], "$${env.LOCAL_VALUE}")
815
+ if _, ok := v.RC()["extra"]; !ok {
816
+ t.Fatal("complete RC section lost")
817
+ }
818
+ if err := os.Remove(os.Getenv("VAUTHRC")); err != nil {
819
+ t.Fatal(err)
820
+ }
821
+ config, err := configFromRC(v.RC(), v.Environ)
822
+ if err != nil {
823
+ t.Fatal(err)
824
+ }
825
+ value, _ = config.Env.Map.Get("VALUE")
826
+ equal(t, value, "local-value")
827
+ }
828
+
829
+ func TestGitLabIsNotInferredDuringConstruction(t *testing.T) {
830
+ project := t.TempDir()
831
+ for _, args := range [][]string{{"init", "-q", project}, {"-C", project, "remote", "add", "origin", "git@git.example.test:Team/app.git"}} {
832
+ if out, err := exec.Command("git", args...).CombinedOutput(); err != nil {
833
+ t.Fatalf("git: %v %s", err, out)
834
+ }
835
+ }
836
+ cwd, err := os.Getwd()
837
+ if err != nil {
838
+ t.Fatal(err)
839
+ }
840
+ if err := os.Chdir(project); err != nil {
841
+ t.Fatal(err)
842
+ }
843
+ t.Cleanup(func() {
844
+ if err := os.Chdir(cwd); err != nil {
845
+ t.Error(err)
846
+ }
847
+ })
848
+ for _, ci := range []string{"", "1"} {
849
+ v := configuredClient(t, map[string]any{"env": map[string]any{"gitlab": true, "map": map[string]any{"PROJECT": "$${env.CI_PROJECT_PATH}"}}}, map[string]string{"CI": ci, "CI_PROJECT_PATH": "pipeline/project", "CI_PROJECT_NAME": "project", "CI_PROJECT_NAMESPACE": "pipeline", "CI_PROJECT_PATH_SLUG": "pipeline-project"})
850
+ want := "pipeline/project"
851
+ value, _ := v.Config.Env.Map.Get("PROJECT")
852
+ equal(t, value, want)
853
+ }
854
+ }
855
+
856
+ func TestEnvMapScalarStringsPreserveRawRC(t *testing.T) {
857
+ values := map[string]any{"TEXT": "hello", "BOOL": true, "NUMBER": 42, "NULL": nil, "LARGE": 1e20, "SMALL": 1e-7, "ZERO": 0}
858
+ v := configuredClient(t, map[string]any{"env": map[string]any{"map": values}}, nil)
859
+ env, err := v.Env(false)
860
+ if err != nil {
861
+ t.Fatal(err)
862
+ }
863
+ for key, value := range map[string]string{"TEXT": "hello", "BOOL": "true", "NUMBER": "42", "NULL": "", "LARGE": "100000000000000000000", "SMALL": "1e-7", "ZERO": "0"} {
864
+ actual, ok := env.Get(key)
865
+ if !ok || actual != value {
866
+ t.Fatalf("%s: %q != %q", key, actual, value)
867
+ }
868
+ }
869
+ raw := v.RC()["env"].(map[string]any)["map"].(map[string]any)
870
+ equal(t, raw["BOOL"], true)
871
+ equal(t, raw["NUMBER"].(float64), float64(42))
872
+ if raw["NULL"] != nil {
873
+ t.Fatal("raw RC null changed")
874
+ }
875
+ }
876
+
877
+ func TestEnvMapRejectsObjectValuesAndMacros(t *testing.T) {
878
+ for _, value := range []any{map[string]any{"x": 1}, []any{"x"}, []any{"$${profile.SCALAR}"}} {
879
+ _, err := configFromRC(map[string]any{"env": map[string]any{"map": map[string]any{"VALUE": value}}}, nil)
880
+ if err == nil || !strings.Contains(err.Error(), "Invalid environment value 'VALUE' in env.map: expected a scalar") {
881
+ t.Fatalf("object accepted: %v", err)
882
+ }
883
+ }
884
+ f := newFixture(t, fixtureOptions{metadata: map[string]any{"SCALAR": 42, "BOOL": false, "NULL": nil, "OBJECT": map[string]any{"x": 1}, "ARRAY": []any{"x"}}})
885
+ v := f.client()
886
+ for _, value := range []string{"$${profile.OBJECT}", "$${profile.ARRAY}", "$${profile}"} {
887
+ v.Config.Env = &EnvConfig{}
888
+ v.Config.Env.Map.Set("VALUE", value)
889
+ if _, err := v.Env(false); err == nil || !strings.Contains(err.Error(), "Invalid environment value 'VALUE' in env.map: expected a scalar") {
890
+ t.Fatalf("object macro accepted: %v", err)
891
+ }
892
+ }
893
+ v.Config.Env = &EnvConfig{Git: true}
894
+ for key, macro := range map[string]string{"NUMBER": "$${profile.SCALAR}", "BOOL": "$${profile.BOOL}", "NULL": "$${profile.NULL}"} {
895
+ v.Config.Env.Map.Set(key, macro)
896
+ }
897
+ env, err := v.Env(false)
898
+ if err != nil {
899
+ t.Fatal(err)
900
+ }
901
+ for key, value := range map[string]string{"NUMBER": "42", "BOOL": "false", "NULL": "", "GIT_AUTHOR_EMAIL": "", "GIT_COMMITTER_EMAIL": ""} {
902
+ actual, ok := env.Get(key)
903
+ if !ok || actual != value {
904
+ t.Fatalf("%s: %q != %q", key, actual, value)
905
+ }
906
+ }
907
+ }
908
+
909
+ func TestConfigWalkPreservesKeysAndSnapshot(t *testing.T) {
910
+ raw := map[string]any{"env": map[string]any{"map": map[string]any{"$${env.KEY}": "$${env.VALUE}"}}}
911
+ config, err := configFromRC(raw, map[string]string{"KEY": "ACTUAL", "VALUE": "done"})
912
+ if err != nil {
913
+ t.Fatal(err)
914
+ }
915
+ value, ok := config.Env.Map.Get("$${env.KEY}")
916
+ if !ok {
917
+ t.Fatal("walker changed a mapping key")
918
+ }
919
+ equal(t, value, "done")
920
+ equal(t, raw["env"].(map[string]any)["map"].(map[string]any)["$${env.KEY}"], "$${env.VALUE}")
664
921
  }