auth.go 8.5 KB

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