keystore.go 3.3 KB

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