http.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. // Copyright 2018 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 acme
  5. import (
  6. "bytes"
  7. "context"
  8. "crypto"
  9. "crypto/rand"
  10. "encoding/json"
  11. "fmt"
  12. "io/ioutil"
  13. "math/big"
  14. "net/http"
  15. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. // retryTimer encapsulates common logic for retrying unsuccessful requests.
  20. // It is not safe for concurrent use.
  21. type retryTimer struct {
  22. // backoffFn provides backoff delay sequence for retries.
  23. // See Client.RetryBackoff doc comment.
  24. backoffFn func(n int, r *http.Request, res *http.Response) time.Duration
  25. // n is the current retry attempt.
  26. n int
  27. }
  28. func (t *retryTimer) inc() {
  29. t.n++
  30. }
  31. // backoff pauses the current goroutine as described in Client.RetryBackoff.
  32. func (t *retryTimer) backoff(ctx context.Context, r *http.Request, res *http.Response) error {
  33. d := t.backoffFn(t.n, r, res)
  34. if d <= 0 {
  35. return fmt.Errorf("acme: no more retries for %s; tried %d time(s)", r.URL, t.n)
  36. }
  37. wakeup := time.NewTimer(d)
  38. defer wakeup.Stop()
  39. select {
  40. case <-ctx.Done():
  41. return ctx.Err()
  42. case <-wakeup.C:
  43. return nil
  44. }
  45. }
  46. func (c *Client) retryTimer() *retryTimer {
  47. f := c.RetryBackoff
  48. if f == nil {
  49. f = defaultBackoff
  50. }
  51. return &retryTimer{backoffFn: f}
  52. }
  53. // defaultBackoff provides default Client.RetryBackoff implementation
  54. // using a truncated exponential backoff algorithm,
  55. // as described in Client.RetryBackoff.
  56. //
  57. // The n argument is always bounded between 1 and 30.
  58. // The returned value is always greater than 0.
  59. func defaultBackoff(n int, r *http.Request, res *http.Response) time.Duration {
  60. const max = 10 * time.Second
  61. var jitter time.Duration
  62. if x, err := rand.Int(rand.Reader, big.NewInt(1000)); err == nil {
  63. // Set the minimum to 1ms to avoid a case where
  64. // an invalid Retry-After value is parsed into 0 below,
  65. // resulting in the 0 returned value which would unintentionally
  66. // stop the retries.
  67. jitter = (1 + time.Duration(x.Int64())) * time.Millisecond
  68. }
  69. if v, ok := res.Header["Retry-After"]; ok {
  70. return retryAfter(v[0]) + jitter
  71. }
  72. if n < 1 {
  73. n = 1
  74. }
  75. if n > 30 {
  76. n = 30
  77. }
  78. d := time.Duration(1<<uint(n-1))*time.Second + jitter
  79. if d > max {
  80. return max
  81. }
  82. return d
  83. }
  84. // retryAfter parses a Retry-After HTTP header value,
  85. // trying to convert v into an int (seconds) or use http.ParseTime otherwise.
  86. // It returns zero value if v cannot be parsed.
  87. func retryAfter(v string) time.Duration {
  88. if i, err := strconv.Atoi(v); err == nil {
  89. return time.Duration(i) * time.Second
  90. }
  91. t, err := http.ParseTime(v)
  92. if err != nil {
  93. return 0
  94. }
  95. return t.Sub(timeNow())
  96. }
  97. // resOkay is a function that reports whether the provided response is okay.
  98. // It is expected to keep the response body unread.
  99. type resOkay func(*http.Response) bool
  100. // wantStatus returns a function which reports whether the code
  101. // matches the status code of a response.
  102. func wantStatus(codes ...int) resOkay {
  103. return func(res *http.Response) bool {
  104. for _, code := range codes {
  105. if code == res.StatusCode {
  106. return true
  107. }
  108. }
  109. return false
  110. }
  111. }
  112. // get issues an unsigned GET request to the specified URL.
  113. // It returns a non-error value only when ok reports true.
  114. //
  115. // get retries unsuccessful attempts according to c.RetryBackoff
  116. // until the context is done or a non-retriable error is received.
  117. func (c *Client) get(ctx context.Context, url string, ok resOkay) (*http.Response, error) {
  118. retry := c.retryTimer()
  119. for {
  120. req, err := http.NewRequest("GET", url, nil)
  121. if err != nil {
  122. return nil, err
  123. }
  124. res, err := c.doNoRetry(ctx, req)
  125. switch {
  126. case err != nil:
  127. return nil, err
  128. case ok(res):
  129. return res, nil
  130. case isRetriable(res.StatusCode):
  131. retry.inc()
  132. resErr := responseError(res)
  133. res.Body.Close()
  134. // Ignore the error value from retry.backoff
  135. // and return the one from last retry, as received from the CA.
  136. if retry.backoff(ctx, req, res) != nil {
  137. return nil, resErr
  138. }
  139. default:
  140. defer res.Body.Close()
  141. return nil, responseError(res)
  142. }
  143. }
  144. }
  145. // postAsGet is POST-as-GET, a replacement for GET in RFC8555
  146. // as described in https://tools.ietf.org/html/rfc8555#section-6.3.
  147. // It makes a POST request in KID form with zero JWS payload.
  148. // See nopayload doc comments in jws.go.
  149. func (c *Client) postAsGet(ctx context.Context, url string, ok resOkay) (*http.Response, error) {
  150. return c.post(ctx, nil, url, noPayload, ok)
  151. }
  152. // post issues a signed POST request in JWS format using the provided key
  153. // to the specified URL. If key is nil, c.Key is used instead.
  154. // It returns a non-error value only when ok reports true.
  155. //
  156. // post retries unsuccessful attempts according to c.RetryBackoff
  157. // until the context is done or a non-retriable error is received.
  158. // It uses postNoRetry to make individual requests.
  159. func (c *Client) post(ctx context.Context, key crypto.Signer, url string, body interface{}, ok resOkay) (*http.Response, error) {
  160. retry := c.retryTimer()
  161. for {
  162. res, req, err := c.postNoRetry(ctx, key, url, body)
  163. if err != nil {
  164. return nil, err
  165. }
  166. if ok(res) {
  167. return res, nil
  168. }
  169. resErr := responseError(res)
  170. res.Body.Close()
  171. switch {
  172. // Check for bad nonce before isRetriable because it may have been returned
  173. // with an unretriable response code such as 400 Bad Request.
  174. case isBadNonce(resErr):
  175. // Consider any previously stored nonce values to be invalid.
  176. c.clearNonces()
  177. case !isRetriable(res.StatusCode):
  178. return nil, resErr
  179. }
  180. retry.inc()
  181. // Ignore the error value from retry.backoff
  182. // and return the one from last retry, as received from the CA.
  183. if err := retry.backoff(ctx, req, res); err != nil {
  184. return nil, resErr
  185. }
  186. }
  187. }
  188. // postNoRetry signs the body with the given key and POSTs it to the provided url.
  189. // It is used by c.post to retry unsuccessful attempts.
  190. // The body argument must be JSON-serializable.
  191. //
  192. // If key argument is nil, c.Key is used to sign the request.
  193. // If key argument is nil and c.accountKID returns a non-zero keyID,
  194. // the request is sent in KID form. Otherwise, JWK form is used.
  195. //
  196. // In practice, when interfacing with RFC-compliant CAs most requests are sent in KID form
  197. // and JWK is used only when KID is unavailable: new account endpoint and certificate
  198. // revocation requests authenticated by a cert key.
  199. // See jwsEncodeJSON for other details.
  200. func (c *Client) postNoRetry(ctx context.Context, key crypto.Signer, url string, body interface{}) (*http.Response, *http.Request, error) {
  201. kid := noKeyID
  202. if key == nil {
  203. key = c.Key
  204. kid = c.accountKID(ctx)
  205. }
  206. nonce, err := c.popNonce(ctx, url)
  207. if err != nil {
  208. return nil, nil, err
  209. }
  210. b, err := jwsEncodeJSON(body, key, kid, nonce, url)
  211. if err != nil {
  212. return nil, nil, err
  213. }
  214. req, err := http.NewRequest("POST", url, bytes.NewReader(b))
  215. if err != nil {
  216. return nil, nil, err
  217. }
  218. req.Header.Set("Content-Type", "application/jose+json")
  219. res, err := c.doNoRetry(ctx, req)
  220. if err != nil {
  221. return nil, nil, err
  222. }
  223. c.addNonce(res.Header)
  224. return res, req, nil
  225. }
  226. // doNoRetry issues a request req, replacing its context (if any) with ctx.
  227. func (c *Client) doNoRetry(ctx context.Context, req *http.Request) (*http.Response, error) {
  228. req.Header.Set("User-Agent", c.userAgent())
  229. res, err := c.httpClient().Do(req.WithContext(ctx))
  230. if err != nil {
  231. select {
  232. case <-ctx.Done():
  233. // Prefer the unadorned context error.
  234. // (The acme package had tests assuming this, previously from ctxhttp's
  235. // behavior, predating net/http supporting contexts natively)
  236. // TODO(bradfitz): reconsider this in the future. But for now this
  237. // requires no test updates.
  238. return nil, ctx.Err()
  239. default:
  240. return nil, err
  241. }
  242. }
  243. return res, nil
  244. }
  245. func (c *Client) httpClient() *http.Client {
  246. if c.HTTPClient != nil {
  247. return c.HTTPClient
  248. }
  249. return http.DefaultClient
  250. }
  251. // packageVersion is the version of the module that contains this package, for
  252. // sending as part of the User-Agent header. It's set in version_go112.go.
  253. var packageVersion string
  254. // userAgent returns the User-Agent header value. It includes the package name,
  255. // the module version (if available), and the c.UserAgent value (if set).
  256. func (c *Client) userAgent() string {
  257. ua := "golang.org/x/crypto/acme"
  258. if packageVersion != "" {
  259. ua += "@" + packageVersion
  260. }
  261. if c.UserAgent != "" {
  262. ua = c.UserAgent + " " + ua
  263. }
  264. return ua
  265. }
  266. // isBadNonce reports whether err is an ACME "badnonce" error.
  267. func isBadNonce(err error) bool {
  268. // According to the spec badNonce is urn:ietf:params:acme:error:badNonce.
  269. // However, ACME servers in the wild return their versions of the error.
  270. // See https://tools.ietf.org/html/draft-ietf-acme-acme-02#section-5.4
  271. // and https://github.com/letsencrypt/boulder/blob/0e07eacb/docs/acme-divergences.md#section-66.
  272. ae, ok := err.(*Error)
  273. return ok && strings.HasSuffix(strings.ToLower(ae.ProblemType), ":badnonce")
  274. }
  275. // isRetriable reports whether a request can be retried
  276. // based on the response status code.
  277. //
  278. // Note that a "bad nonce" error is returned with a non-retriable 400 Bad Request code.
  279. // Callers should parse the response and check with isBadNonce.
  280. func isRetriable(code int) bool {
  281. return code <= 399 || code >= 500 || code == http.StatusTooManyRequests
  282. }
  283. // responseError creates an error of Error type from resp.
  284. func responseError(resp *http.Response) error {
  285. // don't care if ReadAll returns an error:
  286. // json.Unmarshal will fail in that case anyway
  287. b, _ := ioutil.ReadAll(resp.Body)
  288. e := &wireError{Status: resp.StatusCode}
  289. if err := json.Unmarshal(b, e); err != nil {
  290. // this is not a regular error response:
  291. // populate detail with anything we received,
  292. // e.Status will already contain HTTP response code value
  293. e.Detail = string(b)
  294. if e.Detail == "" {
  295. e.Detail = resp.Status
  296. }
  297. }
  298. return e.error(resp.Header)
  299. }