search_session.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. package registry // import "github.com/docker/docker/registry"
  2. import (
  3. // this is required for some certificates
  4. "context"
  5. _ "crypto/sha512"
  6. "encoding/json"
  7. "fmt"
  8. "net/http"
  9. "net/http/cookiejar"
  10. "net/url"
  11. "strings"
  12. "sync"
  13. "github.com/containerd/log"
  14. "github.com/docker/docker/api/types/registry"
  15. "github.com/docker/docker/errdefs"
  16. "github.com/docker/docker/pkg/ioutils"
  17. "github.com/pkg/errors"
  18. )
  19. // A session is used to communicate with a V1 registry
  20. type session struct {
  21. indexEndpoint *v1Endpoint
  22. client *http.Client
  23. }
  24. type authTransport struct {
  25. http.RoundTripper
  26. *registry.AuthConfig
  27. alwaysSetBasicAuth bool
  28. token []string
  29. mu sync.Mutex // guards modReq
  30. modReq map[*http.Request]*http.Request // original -> modified
  31. }
  32. // newAuthTransport handles the auth layer when communicating with a v1 registry (private or official)
  33. //
  34. // For private v1 registries, set alwaysSetBasicAuth to true.
  35. //
  36. // For the official v1 registry, if there isn't already an Authorization header in the request,
  37. // but there is an X-Docker-Token header set to true, then Basic Auth will be used to set the Authorization header.
  38. // After sending the request with the provided base http.RoundTripper, if an X-Docker-Token header, representing
  39. // a token, is present in the response, then it gets cached and sent in the Authorization header of all subsequent
  40. // requests.
  41. //
  42. // If the server sends a token without the client having requested it, it is ignored.
  43. //
  44. // This RoundTripper also has a CancelRequest method important for correct timeout handling.
  45. func newAuthTransport(base http.RoundTripper, authConfig *registry.AuthConfig, alwaysSetBasicAuth bool) *authTransport {
  46. if base == nil {
  47. base = http.DefaultTransport
  48. }
  49. return &authTransport{
  50. RoundTripper: base,
  51. AuthConfig: authConfig,
  52. alwaysSetBasicAuth: alwaysSetBasicAuth,
  53. modReq: make(map[*http.Request]*http.Request),
  54. }
  55. }
  56. // cloneRequest returns a clone of the provided *http.Request.
  57. // The clone is a shallow copy of the struct and its Header map.
  58. func cloneRequest(r *http.Request) *http.Request {
  59. // shallow copy of the struct
  60. r2 := new(http.Request)
  61. *r2 = *r
  62. // deep copy of the Header
  63. r2.Header = make(http.Header, len(r.Header))
  64. for k, s := range r.Header {
  65. r2.Header[k] = append([]string(nil), s...)
  66. }
  67. return r2
  68. }
  69. // RoundTrip changes an HTTP request's headers to add the necessary
  70. // authentication-related headers
  71. func (tr *authTransport) RoundTrip(orig *http.Request) (*http.Response, error) {
  72. // Authorization should not be set on 302 redirect for untrusted locations.
  73. // This logic mirrors the behavior in addRequiredHeadersToRedirectedRequests.
  74. // As the authorization logic is currently implemented in RoundTrip,
  75. // a 302 redirect is detected by looking at the Referrer header as go http package adds said header.
  76. // This is safe as Docker doesn't set Referrer in other scenarios.
  77. if orig.Header.Get("Referer") != "" && !trustedLocation(orig) {
  78. return tr.RoundTripper.RoundTrip(orig)
  79. }
  80. req := cloneRequest(orig)
  81. tr.mu.Lock()
  82. tr.modReq[orig] = req
  83. tr.mu.Unlock()
  84. if tr.alwaysSetBasicAuth {
  85. if tr.AuthConfig == nil {
  86. return nil, errors.New("unexpected error: empty auth config")
  87. }
  88. req.SetBasicAuth(tr.Username, tr.Password)
  89. return tr.RoundTripper.RoundTrip(req)
  90. }
  91. // Don't override
  92. if req.Header.Get("Authorization") == "" {
  93. if req.Header.Get("X-Docker-Token") == "true" && tr.AuthConfig != nil && len(tr.Username) > 0 {
  94. req.SetBasicAuth(tr.Username, tr.Password)
  95. } else if len(tr.token) > 0 {
  96. req.Header.Set("Authorization", "Token "+strings.Join(tr.token, ","))
  97. }
  98. }
  99. resp, err := tr.RoundTripper.RoundTrip(req)
  100. if err != nil {
  101. tr.mu.Lock()
  102. delete(tr.modReq, orig)
  103. tr.mu.Unlock()
  104. return nil, err
  105. }
  106. if len(resp.Header["X-Docker-Token"]) > 0 {
  107. tr.token = resp.Header["X-Docker-Token"]
  108. }
  109. resp.Body = &ioutils.OnEOFReader{
  110. Rc: resp.Body,
  111. Fn: func() {
  112. tr.mu.Lock()
  113. delete(tr.modReq, orig)
  114. tr.mu.Unlock()
  115. },
  116. }
  117. return resp, nil
  118. }
  119. // CancelRequest cancels an in-flight request by closing its connection.
  120. func (tr *authTransport) CancelRequest(req *http.Request) {
  121. type canceler interface {
  122. CancelRequest(*http.Request)
  123. }
  124. if cr, ok := tr.RoundTripper.(canceler); ok {
  125. tr.mu.Lock()
  126. modReq := tr.modReq[req]
  127. delete(tr.modReq, req)
  128. tr.mu.Unlock()
  129. cr.CancelRequest(modReq)
  130. }
  131. }
  132. func authorizeClient(client *http.Client, authConfig *registry.AuthConfig, endpoint *v1Endpoint) error {
  133. var alwaysSetBasicAuth bool
  134. // If we're working with a standalone private registry over HTTPS, send Basic Auth headers
  135. // alongside all our requests.
  136. if endpoint.String() != IndexServer && endpoint.URL.Scheme == "https" {
  137. info, err := endpoint.ping()
  138. if err != nil {
  139. return err
  140. }
  141. if info.Standalone && authConfig != nil {
  142. log.G(context.TODO()).Debugf("Endpoint %s is eligible for private registry. Enabling decorator.", endpoint.String())
  143. alwaysSetBasicAuth = true
  144. }
  145. }
  146. // Annotate the transport unconditionally so that v2 can
  147. // properly fallback on v1 when an image is not found.
  148. client.Transport = newAuthTransport(client.Transport, authConfig, alwaysSetBasicAuth)
  149. jar, err := cookiejar.New(nil)
  150. if err != nil {
  151. return errdefs.System(errors.New("cookiejar.New is not supposed to return an error"))
  152. }
  153. client.Jar = jar
  154. return nil
  155. }
  156. func newSession(client *http.Client, endpoint *v1Endpoint) *session {
  157. return &session{
  158. client: client,
  159. indexEndpoint: endpoint,
  160. }
  161. }
  162. // defaultSearchLimit is the default value for maximum number of returned search results.
  163. const defaultSearchLimit = 25
  164. // searchRepositories performs a search against the remote repository
  165. func (r *session) searchRepositories(term string, limit int) (*registry.SearchResults, error) {
  166. if limit == 0 {
  167. limit = defaultSearchLimit
  168. }
  169. if limit < 1 || limit > 100 {
  170. return nil, invalidParamf("limit %d is outside the range of [1, 100]", limit)
  171. }
  172. u := r.indexEndpoint.String() + "search?q=" + url.QueryEscape(term) + "&n=" + url.QueryEscape(fmt.Sprintf("%d", limit))
  173. log.G(context.TODO()).WithField("url", u).Debug("searchRepositories")
  174. req, err := http.NewRequest(http.MethodGet, u, nil)
  175. if err != nil {
  176. return nil, invalidParamWrapf(err, "error building request")
  177. }
  178. // Have the AuthTransport send authentication, when logged in.
  179. req.Header.Set("X-Docker-Token", "true")
  180. res, err := r.client.Do(req)
  181. if err != nil {
  182. return nil, errdefs.System(err)
  183. }
  184. defer res.Body.Close()
  185. if res.StatusCode != http.StatusOK {
  186. // TODO(thaJeztah): return upstream response body for errors (see https://github.com/moby/moby/issues/27286).
  187. return nil, errdefs.Unknown(fmt.Errorf("Unexpected status code %d", res.StatusCode))
  188. }
  189. result := &registry.SearchResults{}
  190. err = json.NewDecoder(res.Body).Decode(result)
  191. if err != nil {
  192. return nil, errdefs.System(errors.Wrap(err, "error decoding registry search results"))
  193. }
  194. return result, nil
  195. }