client.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. // Copyright 2016 Google LLC. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package jsonclient
  15. import (
  16. "bytes"
  17. "context"
  18. "crypto"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "log"
  24. "math/rand"
  25. "net/http"
  26. "net/url"
  27. "strconv"
  28. "strings"
  29. "time"
  30. ct "github.com/google/certificate-transparency-go"
  31. "github.com/google/certificate-transparency-go/x509"
  32. "golang.org/x/net/context/ctxhttp"
  33. "k8s.io/klog/v2"
  34. )
  35. const maxJitter = 250 * time.Millisecond
  36. type backoffer interface {
  37. // set adjusts/increases the current backoff interval (typically on retryable failure);
  38. // if the optional parameter is provided, this will be used as the interval if it is greater
  39. // than the currently set interval. Returns the current wait period so that it can be
  40. // logged along with any error message.
  41. set(*time.Duration) time.Duration
  42. // decreaseMultiplier reduces the current backoff multiplier, typically on success.
  43. decreaseMultiplier()
  44. // until returns the time until which the client should wait before making a request,
  45. // it may be in the past in which case it should be ignored.
  46. until() time.Time
  47. }
  48. // JSONClient provides common functionality for interacting with a JSON server
  49. // that uses cryptographic signatures.
  50. type JSONClient struct {
  51. uri string // the base URI of the server. e.g. https://ct.googleapis/pilot
  52. httpClient *http.Client // used to interact with the server via HTTP
  53. Verifier *ct.SignatureVerifier // nil for no verification (e.g. no public key available)
  54. logger Logger // interface to use for logging warnings and errors
  55. backoff backoffer // object used to store and calculate backoff information
  56. userAgent string // If set, this is sent as the UserAgent header.
  57. }
  58. // Logger is a simple logging interface used to log internal errors and warnings
  59. type Logger interface {
  60. // Printf formats and logs a message
  61. Printf(string, ...interface{})
  62. }
  63. // Options are the options for creating a new JSONClient.
  64. type Options struct {
  65. // Interface to use for logging warnings and errors, if nil the
  66. // standard library log package will be used.
  67. Logger Logger
  68. // PEM format public key to use for signature verification.
  69. PublicKey string
  70. // DER format public key to use for signature verification.
  71. PublicKeyDER []byte
  72. // UserAgent, if set, will be sent as the User-Agent header with each request.
  73. UserAgent string
  74. }
  75. // ParsePublicKey parses and returns the public key contained in opts.
  76. // If both opts.PublicKey and opts.PublicKeyDER are set, PublicKeyDER is used.
  77. // If neither is set, nil will be returned.
  78. func (opts *Options) ParsePublicKey() (crypto.PublicKey, error) {
  79. if len(opts.PublicKeyDER) > 0 {
  80. return x509.ParsePKIXPublicKey(opts.PublicKeyDER)
  81. }
  82. if opts.PublicKey != "" {
  83. pubkey, _ /* keyhash */, rest, err := ct.PublicKeyFromPEM([]byte(opts.PublicKey))
  84. if err != nil {
  85. return nil, err
  86. }
  87. if len(rest) > 0 {
  88. return nil, errors.New("extra data found after PEM key decoded")
  89. }
  90. return pubkey, nil
  91. }
  92. return nil, nil
  93. }
  94. type basicLogger struct{}
  95. func (bl *basicLogger) Printf(msg string, args ...interface{}) {
  96. log.Printf(msg, args...)
  97. }
  98. // RspError represents an error that occurred when processing a response from a server,
  99. // and also includes key details from the http.Response that triggered the error.
  100. type RspError struct {
  101. Err error
  102. StatusCode int
  103. Body []byte
  104. }
  105. // Error formats the RspError instance, focusing on the error.
  106. func (e RspError) Error() string {
  107. return e.Err.Error()
  108. }
  109. // New constructs a new JSONClient instance, for the given base URI, using the
  110. // given http.Client object (if provided) and the Options object.
  111. // If opts does not specify a public key, signatures will not be verified.
  112. func New(uri string, hc *http.Client, opts Options) (*JSONClient, error) {
  113. pubkey, err := opts.ParsePublicKey()
  114. if err != nil {
  115. return nil, fmt.Errorf("invalid public key: %v", err)
  116. }
  117. var verifier *ct.SignatureVerifier
  118. if pubkey != nil {
  119. var err error
  120. verifier, err = ct.NewSignatureVerifier(pubkey)
  121. if err != nil {
  122. return nil, err
  123. }
  124. }
  125. if hc == nil {
  126. hc = new(http.Client)
  127. }
  128. logger := opts.Logger
  129. if logger == nil {
  130. logger = &basicLogger{}
  131. }
  132. return &JSONClient{
  133. uri: strings.TrimRight(uri, "/"),
  134. httpClient: hc,
  135. Verifier: verifier,
  136. logger: logger,
  137. backoff: &backoff{},
  138. userAgent: opts.UserAgent,
  139. }, nil
  140. }
  141. // BaseURI returns the base URI that the JSONClient makes queries to.
  142. func (c *JSONClient) BaseURI() string {
  143. return c.uri
  144. }
  145. // GetAndParse makes a HTTP GET call to the given path, and attempts to parse
  146. // the response as a JSON representation of the rsp structure. Returns the
  147. // http.Response, the body of the response, and an error (which may be of
  148. // type RspError if the HTTP response was available).
  149. func (c *JSONClient) GetAndParse(ctx context.Context, path string, params map[string]string, rsp interface{}) (*http.Response, []byte, error) {
  150. if ctx == nil {
  151. return nil, nil, errors.New("context.Context required")
  152. }
  153. // Build a GET request with URL-encoded parameters.
  154. vals := url.Values{}
  155. for k, v := range params {
  156. vals.Add(k, v)
  157. }
  158. fullURI := fmt.Sprintf("%s%s?%s", c.uri, path, vals.Encode())
  159. klog.V(2).Infof("GET %s", fullURI)
  160. httpReq, err := http.NewRequest(http.MethodGet, fullURI, nil)
  161. if err != nil {
  162. return nil, nil, err
  163. }
  164. if len(c.userAgent) != 0 {
  165. httpReq.Header.Set("User-Agent", c.userAgent)
  166. }
  167. httpRsp, err := ctxhttp.Do(ctx, c.httpClient, httpReq)
  168. if err != nil {
  169. return nil, nil, err
  170. }
  171. // Read everything now so http.Client can reuse the connection.
  172. body, err := io.ReadAll(httpRsp.Body)
  173. httpRsp.Body.Close()
  174. if err != nil {
  175. return nil, nil, RspError{Err: fmt.Errorf("failed to read response body: %v", err), StatusCode: httpRsp.StatusCode, Body: body}
  176. }
  177. if httpRsp.StatusCode != http.StatusOK {
  178. return nil, nil, RspError{Err: fmt.Errorf("got HTTP Status %q", httpRsp.Status), StatusCode: httpRsp.StatusCode, Body: body}
  179. }
  180. if err := json.NewDecoder(bytes.NewReader(body)).Decode(rsp); err != nil {
  181. return nil, nil, RspError{Err: err, StatusCode: httpRsp.StatusCode, Body: body}
  182. }
  183. return httpRsp, body, nil
  184. }
  185. // PostAndParse makes a HTTP POST call to the given path, including the request
  186. // parameters, and attempts to parse the response as a JSON representation of
  187. // the rsp structure. Returns the http.Response, the body of the response, and
  188. // an error (which may be of type RspError if the HTTP response was available).
  189. func (c *JSONClient) PostAndParse(ctx context.Context, path string, req, rsp interface{}) (*http.Response, []byte, error) {
  190. if ctx == nil {
  191. return nil, nil, errors.New("context.Context required")
  192. }
  193. // Build a POST request with JSON body.
  194. postBody, err := json.Marshal(req)
  195. if err != nil {
  196. return nil, nil, err
  197. }
  198. fullURI := fmt.Sprintf("%s%s", c.uri, path)
  199. klog.V(2).Infof("POST %s", fullURI)
  200. httpReq, err := http.NewRequest(http.MethodPost, fullURI, bytes.NewReader(postBody))
  201. if err != nil {
  202. return nil, nil, err
  203. }
  204. if len(c.userAgent) != 0 {
  205. httpReq.Header.Set("User-Agent", c.userAgent)
  206. }
  207. httpReq.Header.Set("Content-Type", "application/json")
  208. httpRsp, err := ctxhttp.Do(ctx, c.httpClient, httpReq)
  209. // Read all of the body, if there is one, so that the http.Client can do Keep-Alive.
  210. var body []byte
  211. if httpRsp != nil {
  212. body, err = io.ReadAll(httpRsp.Body)
  213. httpRsp.Body.Close()
  214. }
  215. if err != nil {
  216. if httpRsp != nil {
  217. return nil, nil, RspError{StatusCode: httpRsp.StatusCode, Body: body, Err: err}
  218. }
  219. return nil, nil, err
  220. }
  221. if httpRsp.StatusCode == http.StatusOK {
  222. if err = json.Unmarshal(body, &rsp); err != nil {
  223. return nil, nil, RspError{StatusCode: httpRsp.StatusCode, Body: body, Err: err}
  224. }
  225. }
  226. return httpRsp, body, nil
  227. }
  228. // waitForBackoff blocks until the defined backoff interval or context has expired, if the returned
  229. // not before time is in the past it returns immediately.
  230. func (c *JSONClient) waitForBackoff(ctx context.Context) error {
  231. dur := time.Until(c.backoff.until().Add(time.Millisecond * time.Duration(rand.Intn(int(maxJitter.Seconds()*1000)))))
  232. if dur < 0 {
  233. dur = 0
  234. }
  235. backoffTimer := time.NewTimer(dur)
  236. select {
  237. case <-ctx.Done():
  238. return ctx.Err()
  239. case <-backoffTimer.C:
  240. }
  241. return nil
  242. }
  243. // PostAndParseWithRetry makes a HTTP POST call, but retries (with backoff) on
  244. // retriable errors; the caller should set a deadline on the provided context
  245. // to prevent infinite retries. Return values are as for PostAndParse.
  246. func (c *JSONClient) PostAndParseWithRetry(ctx context.Context, path string, req, rsp interface{}) (*http.Response, []byte, error) {
  247. if ctx == nil {
  248. return nil, nil, errors.New("context.Context required")
  249. }
  250. for {
  251. httpRsp, body, err := c.PostAndParse(ctx, path, req, rsp)
  252. if err != nil {
  253. // Don't retry context errors.
  254. if err == context.Canceled || err == context.DeadlineExceeded {
  255. return nil, nil, err
  256. }
  257. wait := c.backoff.set(nil)
  258. c.logger.Printf("Request to %s failed, backing-off %s: %s", c.uri, wait, err)
  259. } else {
  260. switch {
  261. case httpRsp.StatusCode == http.StatusOK:
  262. return httpRsp, body, nil
  263. case httpRsp.StatusCode == http.StatusRequestTimeout:
  264. // Request timeout, retry immediately
  265. c.logger.Printf("Request to %s timed out, retrying immediately", c.uri)
  266. case httpRsp.StatusCode == http.StatusServiceUnavailable:
  267. fallthrough
  268. case httpRsp.StatusCode == http.StatusTooManyRequests:
  269. var backoff *time.Duration
  270. // Retry-After may be either a number of seconds as a int or a RFC 1123
  271. // date string (RFC 7231 Section 7.1.3)
  272. if retryAfter := httpRsp.Header.Get("Retry-After"); retryAfter != "" {
  273. if seconds, err := strconv.Atoi(retryAfter); err == nil {
  274. b := time.Duration(seconds) * time.Second
  275. backoff = &b
  276. } else if date, err := time.Parse(time.RFC1123, retryAfter); err == nil {
  277. b := time.Until(date)
  278. backoff = &b
  279. }
  280. }
  281. wait := c.backoff.set(backoff)
  282. c.logger.Printf("Request to %s failed, backing-off for %s: got HTTP status %s", c.uri, wait, httpRsp.Status)
  283. default:
  284. return nil, nil, RspError{
  285. StatusCode: httpRsp.StatusCode,
  286. Body: body,
  287. Err: fmt.Errorf("got HTTP status %q", httpRsp.Status)}
  288. }
  289. }
  290. if err := c.waitForBackoff(ctx); err != nil {
  291. return nil, nil, err
  292. }
  293. }
  294. }