github.com/juju/juju@v0.0.0-20240430160146-1752b71fcf00/core/secrets/rotate.go (about)

     1  // Copyright 2022 Canonical Ltd.
     2  // Licensed under the LGPLv3, see LICENCE file for details.
     3  
     4  package secrets
     5  
     6  import "time"
     7  
     8  // RotatePolicy defines a policy for how often
     9  // to rotate a secret.
    10  type RotatePolicy string
    11  
    12  const (
    13  	RotateNever     = RotatePolicy("never")
    14  	RotateHourly    = RotatePolicy("hourly")
    15  	RotateDaily     = RotatePolicy("daily")
    16  	RotateWeekly    = RotatePolicy("weekly")
    17  	RotateMonthly   = RotatePolicy("monthly")
    18  	RotateQuarterly = RotatePolicy("quarterly")
    19  	RotateYearly    = RotatePolicy("yearly")
    20  )
    21  
    22  const (
    23  	// RotateRetryDelay is how long to wait to re-run the rotate hook
    24  	// if the secret was not updated.
    25  	RotateRetryDelay = 5 * time.Minute
    26  
    27  	// ExpireRetryDelay is how long to wait to re-run the expire hook
    28  	// if the expired secret revision was not removed.
    29  	ExpireRetryDelay = 5 * time.Minute
    30  )
    31  
    32  func (p RotatePolicy) String() string {
    33  	if p == "" {
    34  		return string(RotateNever)
    35  	}
    36  	return string(p)
    37  }
    38  
    39  // WillRotate returns true if the policy is not RotateNever.
    40  func (p *RotatePolicy) WillRotate() bool {
    41  	return p != nil && *p != "" && *p != RotateNever
    42  }
    43  
    44  // IsValid returns true if p is a valid rotate policy.
    45  func (p RotatePolicy) IsValid() bool {
    46  	switch p {
    47  	case RotateNever, RotateHourly, RotateDaily, RotateWeekly,
    48  		RotateMonthly, RotateQuarterly, RotateYearly:
    49  		return true
    50  	}
    51  	return false
    52  }
    53  
    54  // NextRotateTime returns when the policy dictates a secret should be next
    55  // rotated given the last rotation time.
    56  func (p RotatePolicy) NextRotateTime(lastRotated time.Time) *time.Time {
    57  	var result time.Time
    58  	switch p {
    59  	case RotateNever:
    60  		return nil
    61  	case RotateHourly:
    62  		result = lastRotated.Add(time.Hour)
    63  	case RotateDaily:
    64  		result = lastRotated.AddDate(0, 0, 1)
    65  	case RotateWeekly:
    66  		result = lastRotated.AddDate(0, 0, 7)
    67  	case RotateMonthly:
    68  		result = lastRotated.AddDate(0, 1, 0)
    69  	case RotateQuarterly:
    70  		result = lastRotated.AddDate(0, 3, 0)
    71  	case RotateYearly:
    72  		result = lastRotated.AddDate(1, 0, 0)
    73  	}
    74  	return &result
    75  }