renewal.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package autocert
  5. import (
  6. "context"
  7. "crypto"
  8. "sync"
  9. "time"
  10. )
  11. // domainRenewal tracks the state used by the periodic timers
  12. // renewing a single domain's cert.
  13. type domainRenewal struct {
  14. m *Manager
  15. ck certKey
  16. key crypto.Signer
  17. timerMu sync.Mutex
  18. timer *time.Timer
  19. timerClose chan struct{} // if non-nil, renew closes this channel (and nils out the timer fields) instead of running
  20. }
  21. // start starts a cert renewal timer at the time
  22. // defined by the certificate expiration time exp.
  23. //
  24. // If the timer is already started, calling start is a noop.
  25. func (dr *domainRenewal) start(notBefore, notAfter time.Time) {
  26. dr.timerMu.Lock()
  27. defer dr.timerMu.Unlock()
  28. if dr.timer != nil {
  29. return
  30. }
  31. dr.timer = time.AfterFunc(dr.next(notBefore, notAfter), dr.renew)
  32. }
  33. // stop stops the cert renewal timer and waits for any in-flight calls to renew
  34. // to complete. If the timer is already stopped, calling stop is a noop.
  35. func (dr *domainRenewal) stop() {
  36. dr.timerMu.Lock()
  37. defer dr.timerMu.Unlock()
  38. for {
  39. if dr.timer == nil {
  40. return
  41. }
  42. if dr.timer.Stop() {
  43. dr.timer = nil
  44. return
  45. } else {
  46. // dr.timer fired, and we acquired dr.timerMu before the renew callback did.
  47. // (We know this because otherwise the renew callback would have reset dr.timer!)
  48. timerClose := make(chan struct{})
  49. dr.timerClose = timerClose
  50. dr.timerMu.Unlock()
  51. <-timerClose
  52. dr.timerMu.Lock()
  53. }
  54. }
  55. }
  56. // renew is called periodically by a timer.
  57. // The first renew call is kicked off by dr.start.
  58. func (dr *domainRenewal) renew() {
  59. dr.timerMu.Lock()
  60. defer dr.timerMu.Unlock()
  61. if dr.timerClose != nil {
  62. close(dr.timerClose)
  63. dr.timer, dr.timerClose = nil, nil
  64. return
  65. }
  66. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
  67. defer cancel()
  68. // TODO: rotate dr.key at some point?
  69. next, err := dr.do(ctx)
  70. if err != nil {
  71. next = time.Hour / 2
  72. next += time.Duration(pseudoRand.int63n(int64(next)))
  73. }
  74. testDidRenewLoop(next, err)
  75. dr.timer = time.AfterFunc(next, dr.renew)
  76. }
  77. // updateState locks and replaces the relevant Manager.state item with the given
  78. // state. It additionally updates dr.key with the given state's key.
  79. func (dr *domainRenewal) updateState(state *certState) {
  80. dr.m.stateMu.Lock()
  81. defer dr.m.stateMu.Unlock()
  82. dr.key = state.key
  83. dr.m.state[dr.ck] = state
  84. }
  85. // do is similar to Manager.createCert but it doesn't lock a Manager.state item.
  86. // Instead, it requests a new certificate independently and, upon success,
  87. // replaces dr.m.state item with a new one and updates cache for the given domain.
  88. //
  89. // It may lock and update the Manager.state if the expiration date of the currently
  90. // cached cert is far enough in the future.
  91. //
  92. // The returned value is a time interval after which the renewal should occur again.
  93. func (dr *domainRenewal) do(ctx context.Context) (time.Duration, error) {
  94. // a race is likely unavoidable in a distributed environment
  95. // but we try nonetheless
  96. if tlscert, err := dr.m.cacheGet(ctx, dr.ck); err == nil {
  97. next := dr.next(tlscert.Leaf.NotBefore, tlscert.Leaf.NotAfter)
  98. if next > 0 {
  99. signer, ok := tlscert.PrivateKey.(crypto.Signer)
  100. if ok {
  101. state := &certState{
  102. key: signer,
  103. cert: tlscert.Certificate,
  104. leaf: tlscert.Leaf,
  105. }
  106. dr.updateState(state)
  107. return next, nil
  108. }
  109. }
  110. }
  111. der, leaf, err := dr.m.authorizedCert(ctx, dr.key, dr.ck)
  112. if err != nil {
  113. return 0, err
  114. }
  115. state := &certState{
  116. key: dr.key,
  117. cert: der,
  118. leaf: leaf,
  119. }
  120. tlscert, err := state.tlscert()
  121. if err != nil {
  122. return 0, err
  123. }
  124. if err := dr.m.cachePut(ctx, dr.ck, tlscert); err != nil {
  125. return 0, err
  126. }
  127. dr.updateState(state)
  128. return dr.next(leaf.NotBefore, leaf.NotAfter), nil
  129. }
  130. // next returns the wait time before the next renewal should start.
  131. // If manager.RenewBefore is set, it uses that capped at 30 days,
  132. // otherwise it uses a default of 1/3 of the cert lifetime.
  133. // It builds in a jitter of 10% of the renew threshold, capped at 1 hour.
  134. func (dr *domainRenewal) next(notBefore, notAfter time.Time) time.Duration {
  135. threshold := min(notAfter.Sub(notBefore)/3, 30*24*time.Hour)
  136. if dr.m.RenewBefore > 0 {
  137. threshold = min(dr.m.RenewBefore, 30*24*time.Hour)
  138. }
  139. maxJitter := min(threshold/10, time.Hour)
  140. jitter := pseudoRand.int63n(int64(maxJitter))
  141. renewAt := notAfter.Add(-(threshold - time.Duration(jitter)))
  142. renewWait := renewAt.Sub(dr.m.now())
  143. return max(0, renewWait)
  144. }
  145. var testDidRenewLoop = func(next time.Duration, err error) {}