keystore.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. package provisioner
  2. import (
  3. "encoding/json"
  4. "math/rand"
  5. "net/http"
  6. "regexp"
  7. "strconv"
  8. "sync"
  9. "time"
  10. "github.com/pkg/errors"
  11. "go.step.sm/crypto/jose"
  12. )
  13. const (
  14. defaultCacheAge = 12 * time.Hour
  15. defaultCacheJitter = 1 * time.Hour
  16. )
  17. var maxAgeRegex = regexp.MustCompile("max-age=([0-9]+)")
  18. type keyStore struct {
  19. sync.RWMutex
  20. uri string
  21. keySet jose.JSONWebKeySet
  22. timer *time.Timer
  23. expiry time.Time
  24. jitter time.Duration
  25. }
  26. func newKeyStore(uri string) (*keyStore, error) {
  27. keys, age, err := getKeysFromJWKsURI(uri)
  28. if err != nil {
  29. return nil, err
  30. }
  31. ks := &keyStore{
  32. uri: uri,
  33. keySet: keys,
  34. expiry: getExpirationTime(age),
  35. jitter: getCacheJitter(age),
  36. }
  37. next := ks.nextReloadDuration(age)
  38. ks.timer = time.AfterFunc(next, ks.reload)
  39. return ks, nil
  40. }
  41. func (ks *keyStore) Close() {
  42. ks.timer.Stop()
  43. }
  44. func (ks *keyStore) Get(kid string) (keys []jose.JSONWebKey) {
  45. ks.RLock()
  46. // Force reload if expiration has passed
  47. if time.Now().After(ks.expiry) {
  48. ks.RUnlock()
  49. ks.reload()
  50. ks.RLock()
  51. }
  52. keys = ks.keySet.Key(kid)
  53. ks.RUnlock()
  54. return
  55. }
  56. func (ks *keyStore) reload() {
  57. var next time.Duration
  58. keys, age, err := getKeysFromJWKsURI(ks.uri)
  59. if err != nil {
  60. next = ks.nextReloadDuration(ks.jitter / 2)
  61. } else {
  62. ks.Lock()
  63. ks.keySet = keys
  64. ks.expiry = getExpirationTime(age)
  65. ks.jitter = getCacheJitter(age)
  66. next = ks.nextReloadDuration(age)
  67. ks.Unlock()
  68. }
  69. ks.Lock()
  70. ks.timer.Reset(next)
  71. ks.Unlock()
  72. }
  73. // nextReloadDuration would return the duration for the next rotation. If age is
  74. // 0 it will randomly rotate between 0-12 hours, but every time we call to Get
  75. // it will automatically rotate.
  76. func (ks *keyStore) nextReloadDuration(age time.Duration) time.Duration {
  77. n := rand.Int63n(int64(ks.jitter))
  78. age -= time.Duration(n)
  79. return abs(age)
  80. }
  81. func getKeysFromJWKsURI(uri string) (jose.JSONWebKeySet, time.Duration, error) {
  82. var keys jose.JSONWebKeySet
  83. resp, err := http.Get(uri)
  84. if err != nil {
  85. return keys, 0, errors.Wrapf(err, "failed to connect to %s", uri)
  86. }
  87. defer resp.Body.Close()
  88. if err := json.NewDecoder(resp.Body).Decode(&keys); err != nil {
  89. return keys, 0, errors.Wrapf(err, "error reading %s", uri)
  90. }
  91. return keys, getCacheAge(resp.Header.Get("cache-control")), nil
  92. }
  93. func getCacheAge(cacheControl string) time.Duration {
  94. age := defaultCacheAge
  95. if len(cacheControl) > 0 {
  96. match := maxAgeRegex.FindAllStringSubmatch(cacheControl, -1)
  97. if len(match) > 0 {
  98. if len(match[0]) == 2 {
  99. maxAge := match[0][1]
  100. maxAgeInt, err := strconv.ParseInt(maxAge, 10, 64)
  101. if err != nil {
  102. return defaultCacheAge
  103. }
  104. age = time.Duration(maxAgeInt) * time.Second
  105. }
  106. }
  107. }
  108. return age
  109. }
  110. func getCacheJitter(age time.Duration) time.Duration {
  111. switch {
  112. case age > time.Hour:
  113. return defaultCacheJitter
  114. case age == 0:
  115. // Avoids a 0 jitter. The duration is not important as it will rotate
  116. // automatically on each Get request.
  117. return defaultCacheJitter
  118. default:
  119. return age / 3
  120. }
  121. }
  122. func getExpirationTime(age time.Duration) time.Time {
  123. return time.Now().Truncate(time.Second).Add(age)
  124. }
  125. // abs returns the absolute value of n.
  126. func abs(n time.Duration) time.Duration {
  127. if n < 0 {
  128. return -n
  129. }
  130. return n
  131. }