auth.go 8.9 KB

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