diff --git a/dependency/vault_pki.go b/dependency/vault_pki.go index 15d58e641..8bfdab311 100644 --- a/dependency/vault_pki.go +++ b/dependency/vault_pki.go @@ -127,13 +127,16 @@ func goodFor(cert *x509.Certificate) (time.Duration, bool) { lifespanDur := end.Sub(start) r := rand.New(rand.NewSource(time.Now().UnixNano())) lifespanMilliseconds := lifespanDur.Milliseconds() - // calculate the 'time the certificate should be rotated' by figuring out - // 87-93% of the lifespan and adding it to the start - rotationTime := start.Add(time.Millisecond * time.Duration(((lifespanMilliseconds*9)/10)+(lifespanMilliseconds*int64(r.Intn(6)-3))/100)) + // calculate the 'time the certificate should be rotated' by figuring out -3% + // +3% + VaultLeaseRenewalThreshold of the lifespan and adding it to the + // start + rotationTime := start.Add(time.Millisecond * time.Duration( + float64(lifespanMilliseconds)*VaultLeaseRenewalThreshold+float64(lifespanMilliseconds*(int64(r.Intn(6)-3)/100.0)), + )) // after we have the 'time the certificate should be rotated', figure out how // far it is from now to sleep - sleepFor := time.Duration(rotationTime.Sub(now)) + sleepFor := rotationTime.Sub(now) if sleepFor <= 0 { return 0, false } diff --git a/dependency/vault_pki_test.go b/dependency/vault_pki_test.go index 528d0960f..3c1eca21d 100644 --- a/dependency/vault_pki_test.go +++ b/dependency/vault_pki_test.go @@ -10,7 +10,6 @@ import ( "crypto/x509" "crypto/x509/pkix" "errors" - "fmt" "os" "strings" "testing" @@ -20,6 +19,11 @@ import ( "github.com/hashicorp/vault/api" ) +func init() { + VaultDefaultLeaseDuration = 0 + VaultLeaseRenewalThreshold = .90 +} + func Test_VaultPKI_uniqueID(t *testing.T) { d1, _ := NewVaultPKIQuery("pki/issue/example-dot-com", "/unique_1", nil) id1 := d1.String() @@ -84,8 +88,7 @@ func Test_VaulkPKI_goodFor(t *testing.T) { ratio := dur.Seconds() / (NotAfter.Sub(NotBefore).Seconds()) // allow for a .01 epsilon for floating point comparison to prevent flakey tests - if ratio < .86 || ratio > .94 { - fmt.Println(ratio) + if ratio < (VaultLeaseRenewalThreshold-.04) || ratio > (VaultLeaseRenewalThreshold+.04) { t.Errorf( "%v: should be between 87 and 93, but was %.2f. NotBefore: %s, NotAfter: %s", name, @@ -242,7 +245,9 @@ func Test_VaultPKI_refetch(t *testing.T) { // forcefully wait the longest the certificate could be good force to ensure // goodFor will always return needs renewal <-d.sleepCh - time.Sleep(time.Millisecond * time.Duration(((ttlDuration.Milliseconds()*9)/10)+(ttlDuration.Milliseconds()*int64(3)/100))) + time.Sleep(time.Millisecond * time.Duration( + float64(ttlDuration.Milliseconds())*VaultLeaseRenewalThreshold+float64(ttlDuration.Milliseconds()*(int64(4)/100.0)), + )) act3, rm, err := d.Fetch(clients, nil) if err != nil { t.Fatal(err)