auth.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. package registry // import "github.com/docker/docker/registry"
  2. import (
  3. "context"
  4. "net/http"
  5. "net/url"
  6. "strings"
  7. "time"
  8. "github.com/containerd/log"
  9. "github.com/docker/distribution/registry/client/auth"
  10. "github.com/docker/distribution/registry/client/auth/challenge"
  11. "github.com/docker/distribution/registry/client/transport"
  12. "github.com/docker/docker/api/types/registry"
  13. "github.com/pkg/errors"
  14. )
  15. // AuthClientID is used the ClientID used for the token server
  16. const AuthClientID = "docker"
  17. type loginCredentialStore struct {
  18. authConfig *registry.AuthConfig
  19. }
  20. func (lcs loginCredentialStore) Basic(*url.URL) (string, string) {
  21. return lcs.authConfig.Username, lcs.authConfig.Password
  22. }
  23. func (lcs loginCredentialStore) RefreshToken(*url.URL, string) string {
  24. return lcs.authConfig.IdentityToken
  25. }
  26. func (lcs loginCredentialStore) SetRefreshToken(u *url.URL, service, token string) {
  27. lcs.authConfig.IdentityToken = token
  28. }
  29. type staticCredentialStore struct {
  30. auth *registry.AuthConfig
  31. }
  32. // NewStaticCredentialStore returns a credential store
  33. // which always returns the same credential values.
  34. func NewStaticCredentialStore(auth *registry.AuthConfig) auth.CredentialStore {
  35. return staticCredentialStore{
  36. auth: auth,
  37. }
  38. }
  39. func (scs staticCredentialStore) Basic(*url.URL) (string, string) {
  40. if scs.auth == nil {
  41. return "", ""
  42. }
  43. return scs.auth.Username, scs.auth.Password
  44. }
  45. func (scs staticCredentialStore) RefreshToken(*url.URL, string) string {
  46. if scs.auth == nil {
  47. return ""
  48. }
  49. return scs.auth.IdentityToken
  50. }
  51. func (scs staticCredentialStore) SetRefreshToken(*url.URL, string, string) {
  52. }
  53. // loginV2 tries to login to the v2 registry server. The given registry
  54. // endpoint will be pinged to get authorization challenges. These challenges
  55. // will be used to authenticate against the registry to validate credentials.
  56. func loginV2(authConfig *registry.AuthConfig, endpoint APIEndpoint, userAgent string) (string, string, error) {
  57. var (
  58. endpointStr = strings.TrimRight(endpoint.URL.String(), "/") + "/v2/"
  59. modifiers = Headers(userAgent, nil)
  60. authTransport = transport.NewTransport(newTransport(endpoint.TLSConfig), modifiers...)
  61. credentialAuthConfig = *authConfig
  62. creds = loginCredentialStore{authConfig: &credentialAuthConfig}
  63. )
  64. log.G(context.TODO()).Debugf("attempting v2 login to registry endpoint %s", endpointStr)
  65. loginClient, err := v2AuthHTTPClient(endpoint.URL, authTransport, modifiers, creds, nil)
  66. if err != nil {
  67. return "", "", err
  68. }
  69. req, err := http.NewRequest(http.MethodGet, endpointStr, nil)
  70. if err != nil {
  71. return "", "", err
  72. }
  73. resp, err := loginClient.Do(req)
  74. if err != nil {
  75. err = translateV2AuthError(err)
  76. return "", "", err
  77. }
  78. defer resp.Body.Close()
  79. if resp.StatusCode == http.StatusOK {
  80. return "Login Succeeded", credentialAuthConfig.IdentityToken, nil
  81. }
  82. // TODO(dmcgowan): Attempt to further interpret result, status code and error code string
  83. return "", "", errors.Errorf("login attempt to %s failed with status: %d %s", endpointStr, resp.StatusCode, http.StatusText(resp.StatusCode))
  84. }
  85. func v2AuthHTTPClient(endpoint *url.URL, authTransport http.RoundTripper, modifiers []transport.RequestModifier, creds auth.CredentialStore, scopes []auth.Scope) (*http.Client, error) {
  86. challengeManager, err := PingV2Registry(endpoint, authTransport)
  87. if err != nil {
  88. return nil, err
  89. }
  90. tokenHandlerOptions := auth.TokenHandlerOptions{
  91. Transport: authTransport,
  92. Credentials: creds,
  93. OfflineAccess: true,
  94. ClientID: AuthClientID,
  95. Scopes: scopes,
  96. }
  97. tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions)
  98. basicHandler := auth.NewBasicHandler(creds)
  99. modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler))
  100. return &http.Client{
  101. Transport: transport.NewTransport(authTransport, modifiers...),
  102. Timeout: 15 * time.Second,
  103. }, nil
  104. }
  105. // ConvertToHostname normalizes a registry URL which has http|https prepended
  106. // to just its hostname. It is used to match credentials, which may be either
  107. // stored as hostname or as hostname including scheme (in legacy configuration
  108. // files).
  109. func ConvertToHostname(url string) string {
  110. stripped := url
  111. if strings.HasPrefix(url, "http://") {
  112. stripped = strings.TrimPrefix(url, "http://")
  113. } else if strings.HasPrefix(url, "https://") {
  114. stripped = strings.TrimPrefix(url, "https://")
  115. }
  116. return strings.SplitN(stripped, "/", 2)[0]
  117. }
  118. // ResolveAuthConfig matches an auth configuration to a server address or a URL
  119. func ResolveAuthConfig(authConfigs map[string]registry.AuthConfig, index *registry.IndexInfo) registry.AuthConfig {
  120. configKey := GetAuthConfigKey(index)
  121. // First try the happy case
  122. if c, found := authConfigs[configKey]; found || index.Official {
  123. return c
  124. }
  125. // Maybe they have a legacy config file, we will iterate the keys converting
  126. // them to the new format and testing
  127. for registryURL, ac := range authConfigs {
  128. if configKey == ConvertToHostname(registryURL) {
  129. return ac
  130. }
  131. }
  132. // When all else fails, return an empty auth config
  133. return registry.AuthConfig{}
  134. }
  135. // PingResponseError is used when the response from a ping
  136. // was received but invalid.
  137. type PingResponseError struct {
  138. Err error
  139. }
  140. func (err PingResponseError) Error() string {
  141. return err.Err.Error()
  142. }
  143. // PingV2Registry attempts to ping a v2 registry and on success return a
  144. // challenge manager for the supported authentication types.
  145. // If a response is received but cannot be interpreted, a PingResponseError will be returned.
  146. func PingV2Registry(endpoint *url.URL, transport http.RoundTripper) (challenge.Manager, error) {
  147. pingClient := &http.Client{
  148. Transport: transport,
  149. Timeout: 15 * time.Second,
  150. }
  151. endpointStr := strings.TrimRight(endpoint.String(), "/") + "/v2/"
  152. req, err := http.NewRequest(http.MethodGet, endpointStr, nil)
  153. if err != nil {
  154. return nil, err
  155. }
  156. resp, err := pingClient.Do(req)
  157. if err != nil {
  158. return nil, err
  159. }
  160. defer resp.Body.Close()
  161. challengeManager := challenge.NewSimpleManager()
  162. if err := challengeManager.AddResponse(resp); err != nil {
  163. return nil, PingResponseError{
  164. Err: err,
  165. }
  166. }
  167. return challengeManager, nil
  168. }