auth.go 8.7 KB

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