auth.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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/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 converts a registry url which has http|https prepended
  106. // to just an hostname.
  107. func ConvertToHostname(url string) string {
  108. stripped := url
  109. if strings.HasPrefix(url, "http://") {
  110. stripped = strings.TrimPrefix(url, "http://")
  111. } else if strings.HasPrefix(url, "https://") {
  112. stripped = strings.TrimPrefix(url, "https://")
  113. }
  114. return strings.SplitN(stripped, "/", 2)[0]
  115. }
  116. // ResolveAuthConfig matches an auth configuration to a server address or a URL
  117. func ResolveAuthConfig(authConfigs map[string]registry.AuthConfig, index *registry.IndexInfo) registry.AuthConfig {
  118. configKey := GetAuthConfigKey(index)
  119. // First try the happy case
  120. if c, found := authConfigs[configKey]; found || index.Official {
  121. return c
  122. }
  123. // Maybe they have a legacy config file, we will iterate the keys converting
  124. // them to the new format and testing
  125. for registry, ac := range authConfigs {
  126. if configKey == ConvertToHostname(registry) {
  127. return ac
  128. }
  129. }
  130. // When all else fails, return an empty auth config
  131. return registry.AuthConfig{}
  132. }
  133. // PingResponseError is used when the response from a ping
  134. // was received but invalid.
  135. type PingResponseError struct {
  136. Err error
  137. }
  138. func (err PingResponseError) Error() string {
  139. return err.Err.Error()
  140. }
  141. // PingV2Registry attempts to ping a v2 registry and on success return a
  142. // challenge manager for the supported authentication types.
  143. // If a response is received but cannot be interpreted, a PingResponseError will be returned.
  144. func PingV2Registry(endpoint *url.URL, transport http.RoundTripper) (challenge.Manager, error) {
  145. pingClient := &http.Client{
  146. Transport: transport,
  147. Timeout: 15 * time.Second,
  148. }
  149. endpointStr := strings.TrimRight(endpoint.String(), "/") + "/v2/"
  150. req, err := http.NewRequest(http.MethodGet, endpointStr, nil)
  151. if err != nil {
  152. return nil, err
  153. }
  154. resp, err := pingClient.Do(req)
  155. if err != nil {
  156. return nil, err
  157. }
  158. defer resp.Body.Close()
  159. challengeManager := challenge.NewSimpleManager()
  160. if err := challengeManager.AddResponse(resp); err != nil {
  161. return nil, PingResponseError{
  162. Err: err,
  163. }
  164. }
  165. return challengeManager, nil
  166. }