registry_credentials.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. /*
  2. Copyright 2020 Docker, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package convert
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "io/ioutil"
  18. "net/http"
  19. "net/url"
  20. "os"
  21. "os/exec"
  22. "strings"
  23. "golang.org/x/oauth2"
  24. "github.com/Azure/azure-sdk-for-go/profiles/latest/containerinstance/mgmt/containerinstance"
  25. "github.com/Azure/go-autorest/autorest/to"
  26. compose "github.com/compose-spec/compose-go/types"
  27. "github.com/docker/cli/cli/config"
  28. "github.com/docker/cli/cli/config/configfile"
  29. "github.com/docker/cli/cli/config/types"
  30. "github.com/pkg/errors"
  31. "github.com/docker/compose-cli/aci/login"
  32. )
  33. // Specific username from ACR docs : https://github.com/Azure/acr/blob/master/docs/AAD-OAuth.md#getting-credentials-programatically
  34. const (
  35. tokenUsername = "00000000-0000-0000-0000-000000000000"
  36. dockerHub = "index.docker.io"
  37. acrRegistrySuffix = ".azurecr.io"
  38. )
  39. type registryHelper interface {
  40. getAllRegistryCredentials() (map[string]types.AuthConfig, error)
  41. autoLoginAcr(registry string) error
  42. }
  43. type cliRegistryHelper struct {
  44. cfg *configfile.ConfigFile
  45. }
  46. func (c cliRegistryHelper) getAllRegistryCredentials() (map[string]types.AuthConfig, error) {
  47. return c.cfg.GetAllCredentials()
  48. }
  49. func newCliRegistryConfLoader() cliRegistryHelper {
  50. return cliRegistryHelper{
  51. cfg: config.LoadDefaultConfigFile(os.Stderr),
  52. }
  53. }
  54. func getRegistryCredentials(project compose.Project, helper registryHelper) ([]containerinstance.ImageRegistryCredential, error) {
  55. usedRegistries, acrRegistries := getUsedRegistries(project)
  56. for _, registry := range acrRegistries {
  57. err := helper.autoLoginAcr(registry)
  58. if err != nil {
  59. fmt.Printf("WARNING: %v\n", err)
  60. fmt.Printf("Could not automatically login to %s from your Azure login. Assuming you already logged in to the ACR registry\n", registry)
  61. }
  62. }
  63. allCreds, err := helper.getAllRegistryCredentials()
  64. if err != nil {
  65. return nil, err
  66. }
  67. var registryCreds []containerinstance.ImageRegistryCredential
  68. for name, oneCred := range allCreds {
  69. parsedURL, err := url.Parse(name)
  70. // Credentials can contain some garbage, we don't return the error here
  71. // because we don't care about these garbage creds.
  72. if err != nil {
  73. continue
  74. }
  75. hostname := parsedURL.Host
  76. if hostname == "" {
  77. hostname = parsedURL.Path
  78. }
  79. if _, ok := usedRegistries[hostname]; ok {
  80. if oneCred.Password != "" {
  81. aciCredential := containerinstance.ImageRegistryCredential{
  82. Server: to.StringPtr(hostname),
  83. Password: to.StringPtr(oneCred.Password),
  84. Username: to.StringPtr(oneCred.Username),
  85. }
  86. registryCreds = append(registryCreds, aciCredential)
  87. } else if oneCred.IdentityToken != "" {
  88. userName := tokenUsername
  89. if oneCred.Username != "" {
  90. userName = oneCred.Username
  91. }
  92. aciCredential := containerinstance.ImageRegistryCredential{
  93. Server: to.StringPtr(hostname),
  94. Password: to.StringPtr(oneCred.IdentityToken),
  95. Username: to.StringPtr(userName),
  96. }
  97. registryCreds = append(registryCreds, aciCredential)
  98. }
  99. }
  100. }
  101. return registryCreds, nil
  102. }
  103. func getUsedRegistries(project compose.Project) (map[string]bool, []string) {
  104. usedRegistries := map[string]bool{}
  105. acrRegistries := []string{}
  106. for _, service := range project.Services {
  107. imageName := service.Image
  108. tokens := strings.Split(imageName, "/")
  109. registry := tokens[0]
  110. if len(tokens) == 1 { // ! image names can include "." ...
  111. registry = dockerHub
  112. } else if !strings.Contains(registry, ".") {
  113. registry = dockerHub
  114. } else if strings.HasSuffix(registry, acrRegistrySuffix) {
  115. acrRegistries = append(acrRegistries, registry)
  116. }
  117. usedRegistries[registry] = true
  118. }
  119. return usedRegistries, acrRegistries
  120. }
  121. func (c cliRegistryHelper) autoLoginAcr(registry string) error {
  122. loginService, err := login.NewAzureLoginService()
  123. if err != nil {
  124. return err
  125. }
  126. token, err := loginService.GetValidToken()
  127. if err != nil {
  128. return err
  129. }
  130. tenantID, err := loginService.GetTenantID()
  131. if err != nil {
  132. return err
  133. }
  134. data := url.Values{
  135. "grant_type": {"access_token"},
  136. "service": {registry},
  137. "tenant": {tenantID},
  138. "access_token": {token.AccessToken},
  139. }
  140. repoAuthURL := fmt.Sprintf("https://%s/oauth2/exchange", registry)
  141. res, err := http.Post(repoAuthURL, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  142. if err != nil {
  143. return errors.Wrap(err, "could not query ACR token")
  144. }
  145. bits, err := ioutil.ReadAll(res.Body)
  146. if err != nil {
  147. return errors.Wrap(err, "could not read response body")
  148. }
  149. if res.StatusCode != 200 {
  150. return errors.Errorf("could not obtain ACR token from Azure login, status : %s, response: %s", res.Status, string(bits))
  151. }
  152. newToken := oauth2.Token{}
  153. if err := json.Unmarshal(bits, &newToken); err != nil {
  154. return errors.Wrap(err, "could not read ACR token")
  155. }
  156. cmd := exec.Command("docker", "login", "-u", tokenUsername, "-p", newToken.RefreshToken, registry)
  157. bytes, err := cmd.CombinedOutput()
  158. if err != nil {
  159. return errors.Wrap(err, fmt.Sprintf("could not 'docker login' to %s :\n%s\n", registry, string(bytes)))
  160. }
  161. return nil
  162. }