auth.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package registry
  2. import (
  3. "io/ioutil"
  4. "net/http"
  5. "net/url"
  6. "strings"
  7. "time"
  8. "github.com/docker/distribution/registry/client/auth"
  9. "github.com/docker/distribution/registry/client/auth/challenge"
  10. "github.com/docker/distribution/registry/client/transport"
  11. "github.com/docker/docker/api/types"
  12. registrytypes "github.com/docker/docker/api/types/registry"
  13. "github.com/docker/docker/errdefs"
  14. "github.com/pkg/errors"
  15. "github.com/sirupsen/logrus"
  16. )
  17. const (
  18. // AuthClientID is used the ClientID used for the token server
  19. AuthClientID = "docker"
  20. )
  21. // loginV1 tries to register/login to the v1 registry server.
  22. func loginV1(authConfig *types.AuthConfig, apiEndpoint APIEndpoint, userAgent string) (string, string, error) {
  23. registryEndpoint := apiEndpoint.ToV1Endpoint(userAgent, nil)
  24. serverAddress := registryEndpoint.String()
  25. logrus.Debugf("attempting v1 login to registry endpoint %s", serverAddress)
  26. if serverAddress == "" {
  27. return "", "", errdefs.System(errors.New("server Error: Server Address not set"))
  28. }
  29. req, err := http.NewRequest("GET", serverAddress+"users/", nil)
  30. if err != nil {
  31. return "", "", err
  32. }
  33. req.SetBasicAuth(authConfig.Username, authConfig.Password)
  34. resp, err := registryEndpoint.client.Do(req)
  35. if err != nil {
  36. // fallback when request could not be completed
  37. return "", "", fallbackError{
  38. err: err,
  39. }
  40. }
  41. defer resp.Body.Close()
  42. body, err := ioutil.ReadAll(resp.Body)
  43. if err != nil {
  44. return "", "", errdefs.System(err)
  45. }
  46. switch resp.StatusCode {
  47. case http.StatusOK:
  48. return "Login Succeeded", "", nil
  49. case http.StatusUnauthorized:
  50. return "", "", errdefs.Unauthorized(errors.New("Wrong login/password, please try again"))
  51. case http.StatusForbidden:
  52. // *TODO: Use registry configuration to determine what this says, if anything?
  53. return "", "", errdefs.Forbidden(errors.Errorf("Login: Account is not active. Please see the documentation of the registry %s for instructions how to activate it.", serverAddress))
  54. case http.StatusInternalServerError:
  55. logrus.Errorf("%s returned status code %d. Response Body :\n%s", req.URL.String(), resp.StatusCode, body)
  56. return "", "", errdefs.System(errors.New("Internal Server Error"))
  57. }
  58. return "", "", errdefs.System(errors.Errorf("Login: %s (Code: %d; Headers: %s)", body,
  59. resp.StatusCode, resp.Header))
  60. }
  61. type loginCredentialStore struct {
  62. authConfig *types.AuthConfig
  63. }
  64. func (lcs loginCredentialStore) Basic(*url.URL) (string, string) {
  65. return lcs.authConfig.Username, lcs.authConfig.Password
  66. }
  67. func (lcs loginCredentialStore) RefreshToken(*url.URL, string) string {
  68. return lcs.authConfig.IdentityToken
  69. }
  70. func (lcs loginCredentialStore) SetRefreshToken(u *url.URL, service, token string) {
  71. lcs.authConfig.IdentityToken = token
  72. }
  73. type staticCredentialStore struct {
  74. auth *types.AuthConfig
  75. }
  76. // NewStaticCredentialStore returns a credential store
  77. // which always returns the same credential values.
  78. func NewStaticCredentialStore(auth *types.AuthConfig) auth.CredentialStore {
  79. return staticCredentialStore{
  80. auth: auth,
  81. }
  82. }
  83. func (scs staticCredentialStore) Basic(*url.URL) (string, string) {
  84. if scs.auth == nil {
  85. return "", ""
  86. }
  87. return scs.auth.Username, scs.auth.Password
  88. }
  89. func (scs staticCredentialStore) RefreshToken(*url.URL, string) string {
  90. if scs.auth == nil {
  91. return ""
  92. }
  93. return scs.auth.IdentityToken
  94. }
  95. func (scs staticCredentialStore) SetRefreshToken(*url.URL, string, string) {
  96. }
  97. type fallbackError struct {
  98. err error
  99. }
  100. func (err fallbackError) Error() string {
  101. return err.err.Error()
  102. }
  103. // loginV2 tries to login to the v2 registry server. The given registry
  104. // endpoint will be pinged to get authorization challenges. These challenges
  105. // will be used to authenticate against the registry to validate credentials.
  106. func loginV2(authConfig *types.AuthConfig, endpoint APIEndpoint, userAgent string) (string, string, error) {
  107. logrus.Debugf("attempting v2 login to registry endpoint %s", strings.TrimRight(endpoint.URL.String(), "/")+"/v2/")
  108. modifiers := Headers(userAgent, nil)
  109. authTransport := transport.NewTransport(NewTransport(endpoint.TLSConfig), modifiers...)
  110. credentialAuthConfig := *authConfig
  111. creds := loginCredentialStore{
  112. authConfig: &credentialAuthConfig,
  113. }
  114. loginClient, foundV2, err := v2AuthHTTPClient(endpoint.URL, authTransport, modifiers, creds, nil)
  115. if err != nil {
  116. return "", "", err
  117. }
  118. endpointStr := strings.TrimRight(endpoint.URL.String(), "/") + "/v2/"
  119. req, err := http.NewRequest("GET", endpointStr, nil)
  120. if err != nil {
  121. if !foundV2 {
  122. err = fallbackError{err: err}
  123. }
  124. return "", "", err
  125. }
  126. resp, err := loginClient.Do(req)
  127. if err != nil {
  128. err = translateV2AuthError(err)
  129. if !foundV2 {
  130. err = fallbackError{err: err}
  131. }
  132. return "", "", err
  133. }
  134. defer resp.Body.Close()
  135. if resp.StatusCode == http.StatusOK {
  136. return "Login Succeeded", credentialAuthConfig.IdentityToken, nil
  137. }
  138. // TODO(dmcgowan): Attempt to further interpret result, status code and error code string
  139. err = errors.Errorf("login attempt to %s failed with status: %d %s", endpointStr, resp.StatusCode, http.StatusText(resp.StatusCode))
  140. if !foundV2 {
  141. err = fallbackError{err: err}
  142. }
  143. return "", "", err
  144. }
  145. func v2AuthHTTPClient(endpoint *url.URL, authTransport http.RoundTripper, modifiers []transport.RequestModifier, creds auth.CredentialStore, scopes []auth.Scope) (*http.Client, bool, error) {
  146. challengeManager, foundV2, err := PingV2Registry(endpoint, authTransport)
  147. if err != nil {
  148. if !foundV2 {
  149. err = fallbackError{err: err}
  150. }
  151. return nil, foundV2, err
  152. }
  153. tokenHandlerOptions := auth.TokenHandlerOptions{
  154. Transport: authTransport,
  155. Credentials: creds,
  156. OfflineAccess: true,
  157. ClientID: AuthClientID,
  158. Scopes: scopes,
  159. }
  160. tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions)
  161. basicHandler := auth.NewBasicHandler(creds)
  162. modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler))
  163. tr := transport.NewTransport(authTransport, modifiers...)
  164. return &http.Client{
  165. Transport: tr,
  166. Timeout: 15 * time.Second,
  167. }, foundV2, nil
  168. }
  169. // ConvertToHostname converts a registry url which has http|https prepended
  170. // to just an hostname.
  171. func ConvertToHostname(url string) string {
  172. stripped := url
  173. if strings.HasPrefix(url, "http://") {
  174. stripped = strings.TrimPrefix(url, "http://")
  175. } else if strings.HasPrefix(url, "https://") {
  176. stripped = strings.TrimPrefix(url, "https://")
  177. }
  178. nameParts := strings.SplitN(stripped, "/", 2)
  179. return nameParts[0]
  180. }
  181. // ResolveAuthConfig matches an auth configuration to a server address or a URL
  182. func ResolveAuthConfig(authConfigs map[string]types.AuthConfig, index *registrytypes.IndexInfo) types.AuthConfig {
  183. configKey := GetAuthConfigKey(index)
  184. // First try the happy case
  185. if c, found := authConfigs[configKey]; found || index.Official {
  186. return c
  187. }
  188. // Maybe they have a legacy config file, we will iterate the keys converting
  189. // them to the new format and testing
  190. for registry, ac := range authConfigs {
  191. if configKey == ConvertToHostname(registry) {
  192. return ac
  193. }
  194. }
  195. // When all else fails, return an empty auth config
  196. return types.AuthConfig{}
  197. }
  198. // PingResponseError is used when the response from a ping
  199. // was received but invalid.
  200. type PingResponseError struct {
  201. Err error
  202. }
  203. func (err PingResponseError) Error() string {
  204. return err.Err.Error()
  205. }
  206. // PingV2Registry attempts to ping a v2 registry and on success return a
  207. // challenge manager for the supported authentication types and
  208. // whether v2 was confirmed by the response. If a response is received but
  209. // cannot be interpreted a PingResponseError will be returned.
  210. // nolint: interfacer
  211. func PingV2Registry(endpoint *url.URL, transport http.RoundTripper) (challenge.Manager, bool, error) {
  212. var (
  213. foundV2 = false
  214. v2Version = auth.APIVersion{
  215. Type: "registry",
  216. Version: "2.0",
  217. }
  218. )
  219. pingClient := &http.Client{
  220. Transport: transport,
  221. Timeout: 15 * time.Second,
  222. }
  223. endpointStr := strings.TrimRight(endpoint.String(), "/") + "/v2/"
  224. req, err := http.NewRequest("GET", endpointStr, nil)
  225. if err != nil {
  226. return nil, false, err
  227. }
  228. resp, err := pingClient.Do(req)
  229. if err != nil {
  230. return nil, false, err
  231. }
  232. defer resp.Body.Close()
  233. versions := auth.APIVersions(resp, DefaultRegistryVersionHeader)
  234. for _, pingVersion := range versions {
  235. if pingVersion == v2Version {
  236. // The version header indicates we're definitely
  237. // talking to a v2 registry. So don't allow future
  238. // fallbacks to the v1 protocol.
  239. foundV2 = true
  240. break
  241. }
  242. }
  243. challengeManager := challenge.NewSimpleManager()
  244. if err := challengeManager.AddResponse(resp); err != nil {
  245. return nil, foundV2, PingResponseError{
  246. Err: err,
  247. }
  248. }
  249. return challengeManager, foundV2, nil
  250. }