keystore.go 2.8 KB

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