-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathrotation_test.go
More file actions
832 lines (718 loc) · 25 KB
/
rotation_test.go
File metadata and controls
832 lines (718 loc) · 25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
// Copyright IBM Corp. 2020, 2025
// SPDX-License-Identifier: MPL-2.0
package openldap
import (
"context"
"fmt"
"strings"
"testing"
"time"
log "github.com/hashicorp/go-hclog"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/logging"
"github.com/hashicorp/vault/sdk/logical"
"github.com/hashicorp/vault/sdk/queue"
"github.com/stretchr/testify/require"
)
// TestInitQueueHierarchicalPaths tests that the static role rotation queue
// gets initialized with all the roles from storage.
func TestInitQueueHierarchicalPaths(t *testing.T) {
for _, tc := range []struct {
name string
roles []string
}{
{
"empty",
[]string{},
},
{
"single-role-non-hierarchical-path",
[]string{"a"},
},
{
"single-hierarchical-path",
[]string{"a/b/c/d"},
},
{
"multi-role-non-hierarchical-path",
[]string{"a", "b"},
},
{
"multi-role-with-hierarchical-path",
[]string{"a", "a/b"},
},
{
"multi-role-multi-hierarchical-path",
[]string{"a", "a/b", "a/b/c/d/e", "f"},
},
{
"multi-role-all-hierarchical-path",
[]string{"a/b", "a/b/c", "d/e/f", "d/e/f/h/i/j", "d/e/f/h/x"},
},
} {
t.Run(tc.name, func(t *testing.T) {
b, config := getBackendWithConfig(testBackendConfig(), false)
defer b.Cleanup(context.Background())
storage := config.StorageView
configureOpenLDAPMount(t, b, storage)
for _, r := range tc.roles {
createRole(t, b, config.StorageView, r)
}
// Reload backend to similate a Vault restart/startup memory state
getBackendWithConfig(config, false)
queueLen := b.credRotationQueue.Len()
if queueLen != len(tc.roles) {
t.Fatalf("unexpected rotated queue length: got=%d, want=%d", queueLen, len(tc.roles))
}
})
}
}
func TestAutoRotate(t *testing.T) {
t.Run("auto rotate role", func(t *testing.T) {
b, storage := getBackend(false)
defer b.Cleanup(context.Background())
data := map[string]interface{}{
"binddn": "tester",
"bindpass": "pa$$w0rd",
"url": "ldap://138.91.247.105",
"certificate": validCertificate,
}
req := &logical.Request{
Operation: logical.CreateOperation,
Path: configPath,
Storage: storage,
Data: data,
}
resp, err := b.HandleRequest(context.Background(), req)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%s resp:%#v\n", err, resp)
}
req = &logical.Request{
Operation: logical.UpdateOperation,
Path: rotateRootPath,
Storage: storage,
Data: nil,
}
resp, err = b.HandleRequest(context.Background(), req)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%s resp:%#v\n", err, resp)
}
data = map[string]interface{}{
"username": "hashicorp",
"dn": "uid=hashicorp,ou=users,dc=hashicorp,dc=com",
"rotation_period": "5s",
}
req = &logical.Request{
Operation: logical.CreateOperation,
Path: staticRolePath + "hashicorp",
Storage: storage,
Data: data,
}
resp, err = b.HandleRequest(context.Background(), req)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%s resp:%#v\n", err, resp)
}
req = &logical.Request{
Operation: logical.ReadOperation,
Path: staticCredPath + "hashicorp",
Storage: storage,
Data: nil,
}
resp, err = b.HandleRequest(context.Background(), req)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%s resp:%#v\n", err, resp)
}
if resp.Data["password"] == "" {
t.Fatal("expected password to be set, it wasn't")
}
oldPassword := resp.Data["password"]
// Wait for auto rotation (5s) + 1 second for breathing room
time.Sleep(time.Second * 6)
req = &logical.Request{
Operation: logical.ReadOperation,
Path: staticCredPath + "hashicorp",
Storage: storage,
Data: nil,
}
resp, err = b.HandleRequest(context.Background(), req)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("err:%s resp:%#v\n", err, resp)
}
if resp.Data["password"] == "" {
t.Fatal("expected password to be set after auto rotation, it wasn't")
}
if resp.Data["last_password"] == "" {
t.Fatal("expected last_password to be set after auto rotation, it wasn't")
}
if oldPassword == resp.Data["password"] {
t.Fatal("expected passwords to be different after auto rotation, they weren't")
}
if oldPassword != resp.Data["last_password"] {
t.Fatal("expected last_password to be equal to old password after auto rotation")
}
})
t.Run("skip_import_rotation is true and rotates after ttl expiration", func(t *testing.T) {
b, storage := getBackend(false)
defer b.Cleanup(context.Background())
configureOpenLDAPMount(t, b, storage)
data := map[string]interface{}{
"username": "hashicorp",
"dn": "uid=hashicorp,ou=users,dc=hashicorp,dc=com",
"rotation_period": "5s",
"skip_import_rotation": true,
}
roleName := "hashicorp"
createStaticRoleWithData(t, b, storage, roleName, data)
resp := readStaticCred(t, b, storage, roleName)
if resp.Data["password"] != "" {
t.Fatal("expected password to be empty, it wasn't: skip_import_rotation was enabled, password should not be rotated on import")
}
// Wait for auto rotation (5s) + 1 second for breathing room
time.Sleep(time.Second * 6)
resp = readStaticCred(t, b, storage, roleName)
if resp.Data["password"] == "" {
t.Fatal("expected password to be set after auto rotation, it wasn't")
}
if resp.Data["last_password"] != "" {
t.Fatal("expected last_password to be empty after auto rotation, it wasn't")
}
})
t.Run("skip_import_rotation is true and does not rotate after backend reload", func(t *testing.T) {
b, config := getBackendWithConfig(testBackendConfig(), false)
defer b.Cleanup(context.Background())
storage := config.StorageView
configureOpenLDAPMount(t, b, storage)
data := map[string]interface{}{
"username": "hashicorp",
"dn": "uid=hashicorp,ou=users,dc=hashicorp,dc=com",
"rotation_period": "10m",
"skip_import_rotation": true,
}
roleName := "hashicorp"
createStaticRoleWithData(t, b, storage, roleName, data)
resp := readStaticCred(t, b, storage, roleName)
if resp.Data["password"] != "" {
t.Fatal("expected password to be empty, it wasn't: skip_import_rotation was enabled, password should not be rotated on import")
}
if resp.Data["last_password"] != "" {
t.Fatal("expected last_password to be empty, it wasn't")
}
// Reload backend to similate a Vault restart/startup memory state
getBackendWithConfig(config, false)
// Wait for auto rotation (5s) + 1 second for breathing room
time.Sleep(time.Second * 6)
resp = readStaticCred(t, b, storage, roleName)
if resp.Data["password"] != "" {
t.Fatal("expected password to be empty after backend reload, it wasn't: skip_import_rotation was enabled, password should not be rotated yet")
}
if resp.Data["last_password"] != "" {
t.Fatal("expected last_password to be empty after backend reload, it wasn't")
}
})
t.Run("skip_import_rotation is true and update does not rotate", func(t *testing.T) {
b, config := getBackendWithConfig(testBackendConfig(), false)
defer b.Cleanup(context.Background())
storage := config.StorageView
configureOpenLDAPMount(t, b, storage)
data := map[string]interface{}{
"username": "hashicorp",
"dn": "uid=hashicorp,ou=users,dc=hashicorp,dc=com",
"rotation_period": "10m",
"skip_import_rotation": true,
}
roleName := "hashicorp"
fmt.Println(">>> creating static role")
_, err := createStaticRoleWithData(t, b, storage, roleName, data)
require.NoError(t, err)
data = map[string]interface{}{
"rotation_period": "5m",
}
time.Sleep(time.Second * 6)
fmt.Println(">>> updating static role")
_, err = updateStaticRoleWithData(t, b, storage, roleName, data)
require.NoError(t, err)
// Wait for auto rotation (5s) + 1 second for breathing room
time.Sleep(time.Second * 6)
resp := readStaticCred(t, b, storage, roleName)
if resp.Data["password"] != "" {
t.Fatal("expected password to be empty after backend reload, it wasn't: skip_import_rotation was enabled, password should not be rotated yet")
}
if resp.Data["last_password"] != "" {
t.Fatal("expected last_password to be empty after backend reload, it wasn't")
}
})
t.Run("NextVaultRotation is properly persisted on update", func(t *testing.T) {
b, config := getBackendWithConfig(testBackendConfig(), false)
defer b.Cleanup(context.Background())
storage := config.StorageView
configureOpenLDAPMount(t, b, storage)
roleName := "hashicorp"
data := map[string]interface{}{
"username": roleName,
"dn": "uid=hashicorp,ou=users,dc=hashicorp,dc=com",
"rotation_period": "1h",
"skip_import_rotation": true,
}
_, err := createStaticRoleWithData(t, b, storage, roleName, data)
require.NoError(t, err)
originalRole, err := b.staticRole(context.Background(), storage, roleName)
if err != nil {
t.Fatal("failed to fetch static role", err)
}
// Update static role's rotation period to 5m
data = map[string]interface{}{
"rotation_period": "5m",
}
_, err = updateStaticRoleWithData(t, b, storage, roleName, data)
require.NoError(t, err)
if err != nil {
t.Fatal(err)
}
updatedRole, err := b.staticRole(context.Background(), storage, roleName)
if err != nil {
t.Fatal("failed to fetch static role", err)
}
if originalRole.StaticAccount.NextVaultRotation.Equal(updatedRole.StaticAccount.NextVaultRotation) {
t.Fatal("expected nextVaultRotation1 to be different from nextVaultRotation2")
}
})
// This is to test static roles created before 0.14.5
// In 0.14.5, vault started persisting `NextVaultRotation`
t.Run("zero NextVaultRotation does not cause rotate after backend reload", func(t *testing.T) {
b, config := getBackendWithConfig(testBackendConfig(), false)
defer b.Cleanup(context.Background())
storage := config.StorageView
configureOpenLDAPMount(t, b, storage)
roleName := "hashicorp"
data := map[string]interface{}{
"username": roleName,
"dn": "uid=hashicorp,ou=users,dc=hashicorp,dc=com",
"rotation_period": "10m",
"skip_import_rotation": true,
}
createStaticRoleWithData(t, b, storage, roleName, data)
resp := readStaticCred(t, b, storage, roleName)
firstRotation := resp.Data["last_vault_rotation"].(time.Time)
// force NextVaultRotation to zero to simulate roles before 0.14.5 fix
role, err := b.staticRole(context.Background(), storage, roleName)
if err != nil {
t.Fatal("failed to fetch static role", err)
}
role.StaticAccount.NextVaultRotation = time.Time{}
entry, err := logical.StorageEntryJSON(staticRolePath+roleName, role)
if err != nil {
t.Fatal("failed to build role for storage", err)
}
if err := storage.Put(context.Background(), entry); err != nil {
t.Fatal("failed to write role to storage", err)
}
// Reload backend to similate a Vault restart/startup memory state
getBackendWithConfig(config, false)
// TODO: this is hacky because the queue ticker runs every 5 seconds
time.Sleep(8 * time.Second)
resp = readStaticCred(t, b, storage, roleName)
secondRotation := resp.Data["last_vault_rotation"].(time.Time)
// check if first rotation is different from second rotation
if !firstRotation.Equal(secondRotation) {
t.Fatal("expected first rotation to be equal to second rotation to prove that credential wasnt rotated")
}
})
// This is to test static roles created before 0.14.5
// In 0.14.5, vault started persisting `NextVaultRotation`
t.Run("zero NextVaultRotation for a static role with `skip_import_rotation` does not cause rotate after backend reload", func(t *testing.T) {
b, config := getBackendWithConfig(testBackendConfig(), false)
defer b.Cleanup(context.Background())
storage := config.StorageView
configureOpenLDAPMount(t, b, storage)
roleName := "hashicorp"
data := map[string]interface{}{
"username": roleName,
"dn": "uid=hashicorp,ou=users,dc=hashicorp,dc=com",
"rotation_period": "10m",
"skip_import_rotation": true,
}
createStaticRoleWithData(t, b, storage, roleName, data)
resp := readStaticCred(t, b, storage, roleName)
firstRotation := resp.Data["last_vault_rotation"].(time.Time)
// force NextVaultRotation to zero to simulate roles before 0.14.5 fix
role, err := b.staticRole(context.Background(), storage, roleName)
if err != nil {
t.Fatal("failed to fetch static role", err)
}
role.StaticAccount.NextVaultRotation = time.Time{}
entry, err := logical.StorageEntryJSON(staticRolePath+roleName, role)
if err != nil {
t.Fatal("failed to build role for storage", err)
}
if err := storage.Put(context.Background(), entry); err != nil {
t.Fatal("failed to write role to storage", err)
}
// Reload backend to similate a Vault restart/startup memory state
getBackendWithConfig(config, false)
// TODO: this is hacky because the queue ticker runs every 5 seconds
time.Sleep(8 * time.Second)
resp = readStaticCred(t, b, storage, roleName)
secondRotation := resp.Data["last_vault_rotation"].(time.Time)
// check if first rotation is different from second rotation
if !firstRotation.Equal(secondRotation) {
t.Fatal("expected first rotation to be equal to second rotation to prove that credential wasnt rotated")
}
})
}
// TestPasswordPolicyModificationInvalidatesWAL tests that modification of the
// password policy set on the config invalidates pre-generated passwords in WAL
// entries. WAL entries are used to roll forward during partial failure, but
// a password policy change should cause the WAL to be discarded and a new
// password to be generated using the updated policy.
func TestPasswordPolicyModificationInvalidatesWAL(t *testing.T) {
for _, tc := range []struct {
testName string
}{
{
"hashicorp",
},
{
"HASHICORP",
},
{
"hashicORp",
},
} {
ctx := context.Background()
b, storage := getBackend(false)
defer b.Cleanup(ctx)
configureOpenLDAPMountWithPasswordPolicy(t, b, storage, testPasswordPolicy1, false)
createRole(t, b, storage, "hashicorp")
// Create a WAL entry from a partial failure to rotate
generateWALFromFailedRotation(t, b, storage, "hashicorp")
requireWALs(t, storage, 1)
// The role password should still be the password generated from policy 1
role, err := b.staticRole(ctx, storage, strings.ToLower(tc.testName))
if err != nil {
t.Fatal(err)
}
if role.StaticAccount.Password != testPasswordFromPolicy1 {
t.Fatalf("expected %v, got %v", testPasswordFromPolicy1, role.StaticAccount.Password)
}
// Update the password policy on the configuration
configureOpenLDAPMountWithPasswordPolicy(t, b, storage, testPasswordPolicy2, false)
// Manually rotate the role. It should not use the password from the WAL entry
// created earlier. Instead, it should result in generation of a new password
// using the updated policy 2.
_, err = b.HandleRequest(ctx, &logical.Request{
Operation: logical.UpdateOperation,
Path: "rotate-role/hashicorp",
Storage: storage,
})
if err != nil {
t.Fatal(err)
}
// The role password should be the password generated from policy 2
role, err = b.staticRole(ctx, storage, strings.ToLower(tc.testName))
if err != nil {
t.Fatal(err)
}
if role.StaticAccount.Password != testPasswordFromPolicy2 {
t.Fatalf("expected %v, got %v", testPasswordFromPolicy2, role.StaticAccount.Password)
}
if role.StaticAccount.LastPassword != testPasswordFromPolicy1 {
t.Fatalf("expected %v, got %v", testPasswordFromPolicy1, role.StaticAccount.LastPassword)
}
// The WAL entry should be deleted after the successful rotation
requireWALs(t, storage, 0)
}
}
func TestRollsPasswordForwardsUsingWAL(t *testing.T) {
for _, tc := range []struct {
testName string
}{
{
"hashicorp",
},
{
"HASHICORP",
},
{
"hashicORp",
},
} {
ctx := context.Background()
b, storage := getBackend(false)
defer b.Cleanup(ctx)
configureOpenLDAPMount(t, b, storage)
createRole(t, b, storage, "hashicorp")
role, err := b.staticRole(ctx, storage, strings.ToLower(tc.testName))
if err != nil {
t.Fatal(err)
}
oldPassword := role.StaticAccount.Password
generateWALFromFailedRotation(t, b, storage, tc.testName)
walIDs := requireWALs(t, storage, 1)
wal, err := b.findStaticWAL(ctx, storage, walIDs[0])
if err != nil {
t.Fatal(err)
}
role, err = b.staticRole(ctx, storage, strings.ToLower(tc.testName))
if err != nil {
t.Fatal(err)
}
// Role's password should still be the WAL's old password
if role.StaticAccount.Password != oldPassword {
t.Fatal(role.StaticAccount.Password, oldPassword)
}
// Trigger a retry on the rotation, it should use WAL's new password
_, err = b.HandleRequest(ctx, &logical.Request{
Operation: logical.UpdateOperation,
Path: fmt.Sprintf("rotate-role/%s", tc.testName),
Storage: storage,
})
if err != nil {
t.Fatal(err)
}
role, err = b.staticRole(ctx, storage, strings.ToLower(tc.testName))
if err != nil {
t.Fatal(err)
}
if role.StaticAccount.Password != wal.NewPassword {
t.Fatal(role.StaticAccount.Password, wal.NewPassword)
}
// WAL should be cleared by the successful rotate
requireWALs(t, storage, 0)
}
}
func TestStoredWALsCorrectlyProcessed(t *testing.T) {
const walNewPassword = "new-password-from-wal"
for _, tc := range []struct {
name string
shouldRotate bool
wal *setCredentialsWAL
}{
{
"WAL is kept and used for roll forward",
true,
&setCredentialsWAL{
RoleName: "hashicorp",
Username: "hashicorp",
DN: "uid=hashicorp,ou=users,dc=hashicorp,dc=com",
NewPassword: walNewPassword,
LastVaultRotation: time.Now().Add(time.Hour),
},
},
{
"zero-time WAL is discarded on load",
false,
&setCredentialsWAL{
RoleName: "hashicorp",
Username: "hashicorp",
DN: "uid=hashicorp,ou=users,dc=hashicorp,dc=com",
NewPassword: walNewPassword,
LastVaultRotation: time.Time{},
},
},
{
"empty-password WAL is kept but a new password is generated",
true,
&setCredentialsWAL{
RoleName: "hashicorp",
Username: "hashicorp",
DN: "uid=hashicorp,ou=users,dc=hashicorp,dc=com",
NewPassword: "",
LastVaultRotation: time.Now().Add(time.Hour),
},
},
} {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
sv := testSystemView{}
sv.DefaultLeaseTTLVal = defaultLeaseTTLVal
sv.MaxLeaseTTLVal = maxLeaseTTLVal
sv.PasswordPolicies = map[string]logical.PasswordGenerator{
testPasswordPolicy1: func() (string, error) {
return testPasswordFromPolicy1, nil
},
testPasswordPolicy2: func() (string, error) {
return testPasswordFromPolicy2, nil
},
}
config := &logical.BackendConfig{
Logger: logging.NewVaultLogger(log.Debug),
System: sv,
StorageView: &logical.InmemStorage{},
}
b := Backend(&fakeLdapClient{throwErrs: false})
b.Setup(context.Background(), config)
b.credRotationQueue = queue.New()
initCtx := context.Background()
ictx, cancel := context.WithCancel(initCtx)
b.cancelQueue = cancel
defer b.Cleanup(ctx)
configureOpenLDAPMount(t, b, config.StorageView)
createRole(t, b, config.StorageView, "hashicorp")
role, err := b.staticRole(ctx, config.StorageView, "hashicorp")
if err != nil {
t.Fatal(err)
}
initialPassword := role.StaticAccount.Password
// Set up a WAL for our test case
framework.PutWAL(ctx, config.StorageView, staticWALKey, tc.wal)
requireWALs(t, config.StorageView, 1)
// Reset the rotation queue to simulate startup memory state
b.credRotationQueue = queue.New()
// Load managed LDAP users into memory from storage
staticRoles, err := b.loadManagedUsers(ictx, config.StorageView)
if err != nil {
t.Fatal(err)
}
// Now finish the startup process by populating the queue, which should discard the WAL
b.initQueue(ictx, &logical.InitializationRequest{
Storage: config.StorageView,
}, staticRoles)
if tc.shouldRotate {
requireWALs(t, config.StorageView, 1)
} else {
requireWALs(t, config.StorageView, 0)
}
// Run one tick
b.rotateCredentials(ctx, config.StorageView)
requireWALs(t, config.StorageView, 0)
role, err = b.staticRole(ctx, config.StorageView, "hashicorp")
if err != nil {
t.Fatal(err)
}
item, err := b.popFromRotationQueueByKey("hashicorp")
if err != nil {
t.Fatal(err)
}
if tc.shouldRotate {
if tc.wal.NewPassword != "" {
// Should use WAL's new_password field
if role.StaticAccount.Password != walNewPassword {
t.Fatal()
}
} else {
// Should rotate but ignore WAL's new_password field
if role.StaticAccount.Password == initialPassword {
t.Fatal()
}
if role.StaticAccount.Password == walNewPassword {
t.Fatal()
}
}
} else {
// Ensure the role was not promoted for early rotation
if item.Priority < time.Now().Add(time.Hour).Unix() {
t.Fatal("priority should be for about a week away, but was", item.Priority)
}
if role.StaticAccount.Password != initialPassword {
t.Fatal("password should not have been rotated yet")
}
}
})
}
}
func TestDeletesOlderWALsOnLoad(t *testing.T) {
ctx := context.Background()
b, storage := getBackend(false)
defer b.Cleanup(ctx)
configureOpenLDAPMount(t, b, storage)
createRole(t, b, storage, "hashicorp")
// Create 4 WALs, with a clear winner for most recent.
wal := &setCredentialsWAL{
RoleName: "hashicorp",
Username: "hashicorp",
DN: "uid=hashicorp,ou=users,dc=hashicorp,dc=com",
NewPassword: "some-new-password",
LastVaultRotation: time.Now(),
}
for i := 0; i < 3; i++ {
_, err := framework.PutWAL(ctx, storage, staticWALKey, wal)
if err != nil {
t.Fatal(err)
}
}
time.Sleep(2 * time.Second)
// We expect this WAL to have the latest createdAt timestamp
walID, err := framework.PutWAL(ctx, storage, staticWALKey, wal)
if err != nil {
t.Fatal(err)
}
requireWALs(t, storage, 4)
walMap, err := b.loadStaticWALs(ctx, storage)
if err != nil {
t.Fatal(err)
}
if len(walMap) != 1 || walMap["hashicorp"] == nil || walMap["hashicorp"].walID != walID {
t.Fatal()
}
requireWALs(t, storage, 1)
}
func generateWALFromFailedRotation(t *testing.T, b *backend, storage logical.Storage, roleName string) {
t.Helper()
// Fail to rotate the roles
ldapClient := b.client.(*fakeLdapClient)
originalValue := ldapClient.throwErrs
ldapClient.throwErrs = true
defer func() {
ldapClient.throwErrs = originalValue
}()
_, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.UpdateOperation,
Path: "rotate-role/" + roleName,
Storage: storage,
})
if err == nil {
t.Fatal("expected error")
}
}
// returns a slice of the WAL IDs in storage
func requireWALs(t *testing.T, storage logical.Storage, expectedCount int) []string {
t.Helper()
wals, err := storage.List(context.Background(), "wal/")
if err != nil {
t.Fatal(err)
}
if len(wals) != expectedCount {
t.Fatal("expected WALs", expectedCount, "got", len(wals))
}
return wals
}
// Test_backend_findStaticWAL_DecodeWALMissingField tests that WAL decoding in
// findStaticWAL can handle the case where WAL entries have missing fields. This
// can happen when a WAL entry exists prior to a plugin upgrade that changes the
// data in the WAL. The decoding should not panic and set zero values for any
// missing fields.
func Test_backend_findStaticWAL_DecodeWALMissingField(t *testing.T) {
ctx := context.Background()
b, storage := getBackend(false)
defer b.Cleanup(ctx)
// Intentionally missing the PasswordPolicy field
type priorSetCredentialsWAL struct {
NewPassword string `json:"new_password" mapstructure:"new_password"`
RoleName string `json:"role_name" mapstructure:"role_name"`
Username string `json:"username" mapstructure:"username"`
DN string `json:"dn" mapstructure:"dn"`
LastVaultRotation time.Time `json:"last_vault_rotation" mapstructure:"last_vault_rotation"`
}
// Write a WAL entry to storage
walEntry := priorSetCredentialsWAL{
NewPassword: "Str0ngPassw0rd",
RoleName: "test",
Username: "static_user",
DN: "cn=static_user,ou=users,dc=hashicorp,dc=com",
LastVaultRotation: time.Now(),
}
id, err := framework.PutWAL(ctx, storage, staticWALKey, walEntry)
require.NoError(t, err)
require.NotEmpty(t, id)
// Assert that the decoded WAL entry data matches the original input
got, err := b.findStaticWAL(ctx, storage, id)
require.NoError(t, err)
require.Equal(t, walEntry.NewPassword, got.NewPassword)
require.Equal(t, walEntry.RoleName, got.RoleName)
require.Equal(t, walEntry.Username, got.Username)
require.Equal(t, walEntry.DN, got.DN)
require.True(t, walEntry.LastVaultRotation.Equal(got.LastVaultRotation))
require.Equal(t, id, got.walID)
// Assert that any missing fields take the zero value after decoding
require.Equal(t, "", got.PasswordPolicy)
}