registry_credentials.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  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. const (
  34. // Specific username from ACR docs : https://github.com/Azure/acr/blob/master/docs/AAD-OAuth.md#getting-credentials-programatically
  35. tokenUsername = "00000000-0000-0000-0000-000000000000"
  36. dockerHub = "index.docker.io"
  37. )
  38. type registryHelper interface {
  39. getAllRegistryCredentials() (map[string]types.AuthConfig, error)
  40. autoLoginAcr(registry string, loginService login.AzureLoginService) error
  41. }
  42. type cliRegistryHelper struct {
  43. cfg *configfile.ConfigFile
  44. }
  45. func (c cliRegistryHelper) getAllRegistryCredentials() (map[string]types.AuthConfig, error) {
  46. return c.cfg.GetAllCredentials()
  47. }
  48. func newCliRegistryConfLoader() cliRegistryHelper {
  49. return cliRegistryHelper{
  50. cfg: config.LoadDefaultConfigFile(os.Stderr),
  51. }
  52. }
  53. func getRegistryCredentials(project compose.Project, helper registryHelper) ([]containerinstance.ImageRegistryCredential, error) {
  54. loginService, err := login.NewAzureLoginService()
  55. if err != nil {
  56. return nil, err
  57. }
  58. var cloudEnvironment *login.CloudEnvironment
  59. if ce, err := loginService.GetCloudEnvironment(); err != nil {
  60. cloudEnvironment = &ce
  61. }
  62. usedRegistries, acrRegistries := getUsedRegistries(project, cloudEnvironment)
  63. for _, registry := range acrRegistries {
  64. err := helper.autoLoginAcr(registry, loginService)
  65. if err != nil {
  66. fmt.Printf("WARNING: %v\n", err)
  67. fmt.Printf("Could not automatically login to %s from your Azure login. Assuming you already logged in to the ACR registry\n", registry)
  68. }
  69. }
  70. allCreds, err := helper.getAllRegistryCredentials()
  71. if err != nil {
  72. return nil, err
  73. }
  74. var registryCreds []containerinstance.ImageRegistryCredential
  75. for name, oneCred := range allCreds {
  76. parsedURL, err := url.Parse(name)
  77. // Credentials can contain some garbage, we don't return the error here
  78. // because we don't care about these garbage creds.
  79. if err != nil {
  80. continue
  81. }
  82. hostname := parsedURL.Host
  83. if hostname == "" {
  84. hostname = parsedURL.Path
  85. }
  86. if _, ok := usedRegistries[hostname]; ok {
  87. if oneCred.Password != "" {
  88. aciCredential := containerinstance.ImageRegistryCredential{
  89. Server: to.StringPtr(hostname),
  90. Password: to.StringPtr(oneCred.Password),
  91. Username: to.StringPtr(oneCred.Username),
  92. }
  93. registryCreds = append(registryCreds, aciCredential)
  94. } else if oneCred.IdentityToken != "" {
  95. userName := tokenUsername
  96. if oneCred.Username != "" {
  97. userName = oneCred.Username
  98. }
  99. aciCredential := containerinstance.ImageRegistryCredential{
  100. Server: to.StringPtr(hostname),
  101. Password: to.StringPtr(oneCred.IdentityToken),
  102. Username: to.StringPtr(userName),
  103. }
  104. registryCreds = append(registryCreds, aciCredential)
  105. }
  106. }
  107. }
  108. return registryCreds, nil
  109. }
  110. func getUsedRegistries(project compose.Project, ce *login.CloudEnvironment) (map[string]bool, []string) {
  111. usedRegistries := map[string]bool{}
  112. acrRegistries := []string{}
  113. for _, service := range project.Services {
  114. imageName := service.Image
  115. tokens := strings.Split(imageName, "/")
  116. registry := tokens[0]
  117. if len(tokens) == 1 { // ! image names can include "." ...
  118. registry = dockerHub
  119. } else if !strings.Contains(registry, ".") {
  120. registry = dockerHub
  121. } else if ce != nil {
  122. if suffix, present := ce.Suffixes[login.AcrSuffixKey]; present && strings.HasSuffix(registry, suffix) {
  123. acrRegistries = append(acrRegistries, registry)
  124. }
  125. }
  126. usedRegistries[registry] = true
  127. }
  128. return usedRegistries, acrRegistries
  129. }
  130. func (c cliRegistryHelper) autoLoginAcr(registry string, loginService login.AzureLoginService) error {
  131. token, tenantID, err := loginService.GetValidToken()
  132. if err != nil {
  133. return err
  134. }
  135. data := url.Values{
  136. "grant_type": {"access_token"},
  137. "service": {registry},
  138. "tenant": {tenantID},
  139. "access_token": {token.AccessToken},
  140. }
  141. repoAuthURL := fmt.Sprintf("https://%s/oauth2/exchange", registry)
  142. res, err := http.Post(repoAuthURL, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  143. if err != nil {
  144. return errors.Wrap(err, "could not query ACR token")
  145. }
  146. bits, err := ioutil.ReadAll(res.Body)
  147. if err != nil {
  148. return errors.Wrap(err, "could not read response body")
  149. }
  150. if res.StatusCode != 200 {
  151. return errors.Errorf("could not obtain ACR token from Azure login, status : %s, response: %s", res.Status, string(bits))
  152. }
  153. newToken := oauth2.Token{}
  154. if err := json.Unmarshal(bits, &newToken); err != nil {
  155. return errors.Wrap(err, "could not read ACR token")
  156. }
  157. cmd := exec.Command("docker", "login", "-u", tokenUsername, "-p", newToken.RefreshToken, registry)
  158. bytes, err := cmd.CombinedOutput()
  159. if err != nil {
  160. return errors.Wrap(err, fmt.Sprintf("could not 'docker login' to %s :\n%s\n", registry, string(bytes)))
  161. }
  162. return nil
  163. }