errors.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. package client
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "net/http"
  9. "github.com/docker/distribution/registry/api/errcode"
  10. "github.com/docker/distribution/registry/client/auth/challenge"
  11. )
  12. // ErrNoErrorsInBody is returned when an HTTP response body parses to an empty
  13. // errcode.Errors slice.
  14. var ErrNoErrorsInBody = errors.New("no error details found in HTTP response body")
  15. // UnexpectedHTTPStatusError is returned when an unexpected HTTP status is
  16. // returned when making a registry api call.
  17. type UnexpectedHTTPStatusError struct {
  18. Status string
  19. }
  20. func (e *UnexpectedHTTPStatusError) Error() string {
  21. return fmt.Sprintf("received unexpected HTTP status: %s", e.Status)
  22. }
  23. // UnexpectedHTTPResponseError is returned when an expected HTTP status code
  24. // is returned, but the content was unexpected and failed to be parsed.
  25. type UnexpectedHTTPResponseError struct {
  26. ParseErr error
  27. StatusCode int
  28. Response []byte
  29. }
  30. func (e *UnexpectedHTTPResponseError) Error() string {
  31. return fmt.Sprintf("error parsing HTTP %d response body: %s: %q", e.StatusCode, e.ParseErr.Error(), string(e.Response))
  32. }
  33. func parseHTTPErrorResponse(statusCode int, r io.Reader) error {
  34. var errors errcode.Errors
  35. body, err := ioutil.ReadAll(r)
  36. if err != nil {
  37. return err
  38. }
  39. // For backward compatibility, handle irregularly formatted
  40. // messages that contain a "details" field.
  41. var detailsErr struct {
  42. Details string `json:"details"`
  43. }
  44. err = json.Unmarshal(body, &detailsErr)
  45. if err == nil && detailsErr.Details != "" {
  46. switch statusCode {
  47. case http.StatusUnauthorized:
  48. return errcode.ErrorCodeUnauthorized.WithMessage(detailsErr.Details)
  49. case http.StatusTooManyRequests:
  50. return errcode.ErrorCodeTooManyRequests.WithMessage(detailsErr.Details)
  51. default:
  52. return errcode.ErrorCodeUnknown.WithMessage(detailsErr.Details)
  53. }
  54. }
  55. if err := json.Unmarshal(body, &errors); err != nil {
  56. return &UnexpectedHTTPResponseError{
  57. ParseErr: err,
  58. StatusCode: statusCode,
  59. Response: body,
  60. }
  61. }
  62. if len(errors) == 0 {
  63. // If there was no error specified in the body, return
  64. // UnexpectedHTTPResponseError.
  65. return &UnexpectedHTTPResponseError{
  66. ParseErr: ErrNoErrorsInBody,
  67. StatusCode: statusCode,
  68. Response: body,
  69. }
  70. }
  71. return errors
  72. }
  73. func makeErrorList(err error) []error {
  74. if errL, ok := err.(errcode.Errors); ok {
  75. return []error(errL)
  76. }
  77. return []error{err}
  78. }
  79. func mergeErrors(err1, err2 error) error {
  80. return errcode.Errors(append(makeErrorList(err1), makeErrorList(err2)...))
  81. }
  82. // HandleErrorResponse returns error parsed from HTTP response for an
  83. // unsuccessful HTTP response code (in the range 400 - 499 inclusive). An
  84. // UnexpectedHTTPStatusError returned for response code outside of expected
  85. // range.
  86. func HandleErrorResponse(resp *http.Response) error {
  87. if resp.StatusCode >= 400 && resp.StatusCode < 500 {
  88. // Check for OAuth errors within the `WWW-Authenticate` header first
  89. // See https://tools.ietf.org/html/rfc6750#section-3
  90. for _, c := range challenge.ResponseChallenges(resp) {
  91. if c.Scheme == "bearer" {
  92. var err errcode.Error
  93. // codes defined at https://tools.ietf.org/html/rfc6750#section-3.1
  94. switch c.Parameters["error"] {
  95. case "invalid_token":
  96. err.Code = errcode.ErrorCodeUnauthorized
  97. case "insufficient_scope":
  98. err.Code = errcode.ErrorCodeDenied
  99. default:
  100. continue
  101. }
  102. if description := c.Parameters["error_description"]; description != "" {
  103. err.Message = description
  104. } else {
  105. err.Message = err.Code.Message()
  106. }
  107. return mergeErrors(err, parseHTTPErrorResponse(resp.StatusCode, resp.Body))
  108. }
  109. }
  110. err := parseHTTPErrorResponse(resp.StatusCode, resp.Body)
  111. if uErr, ok := err.(*UnexpectedHTTPResponseError); ok && resp.StatusCode == 401 {
  112. return errcode.ErrorCodeUnauthorized.WithDetail(uErr.Response)
  113. }
  114. return err
  115. }
  116. return &UnexpectedHTTPStatusError{Status: resp.Status}
  117. }
  118. // SuccessStatus returns true if the argument is a successful HTTP response
  119. // code (in the range 200 - 399 inclusive).
  120. func SuccessStatus(status int) bool {
  121. return status >= 200 && status <= 399
  122. }