registry_credentials.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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) 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. usedRegistries, acrRegistries := getUsedRegistries(project)
  55. for _, registry := range acrRegistries {
  56. err := helper.autoLoginAcr(registry)
  57. if err != nil {
  58. fmt.Printf("WARNING: %v\n", err)
  59. fmt.Printf("Could not automatically login to %s from your Azure login. Assuming you already logged in to the ACR registry\n", registry)
  60. }
  61. }
  62. allCreds, err := helper.getAllRegistryCredentials()
  63. if err != nil {
  64. return nil, err
  65. }
  66. var registryCreds []containerinstance.ImageRegistryCredential
  67. for name, oneCred := range allCreds {
  68. parsedURL, err := url.Parse(name)
  69. // Credentials can contain some garbage, we don't return the error here
  70. // because we don't care about these garbage creds.
  71. if err != nil {
  72. continue
  73. }
  74. hostname := parsedURL.Host
  75. if hostname == "" {
  76. hostname = parsedURL.Path
  77. }
  78. if _, ok := usedRegistries[hostname]; ok {
  79. if oneCred.Password != "" {
  80. aciCredential := containerinstance.ImageRegistryCredential{
  81. Server: to.StringPtr(hostname),
  82. Password: to.StringPtr(oneCred.Password),
  83. Username: to.StringPtr(oneCred.Username),
  84. }
  85. registryCreds = append(registryCreds, aciCredential)
  86. } else if oneCred.IdentityToken != "" {
  87. userName := tokenUsername
  88. if oneCred.Username != "" {
  89. userName = oneCred.Username
  90. }
  91. aciCredential := containerinstance.ImageRegistryCredential{
  92. Server: to.StringPtr(hostname),
  93. Password: to.StringPtr(oneCred.IdentityToken),
  94. Username: to.StringPtr(userName),
  95. }
  96. registryCreds = append(registryCreds, aciCredential)
  97. }
  98. }
  99. }
  100. return registryCreds, nil
  101. }
  102. func getUsedRegistries(project compose.Project) (map[string]bool, []string) {
  103. usedRegistries := map[string]bool{}
  104. acrRegistries := []string{}
  105. for _, service := range project.Services {
  106. imageName := service.Image
  107. tokens := strings.Split(imageName, "/")
  108. registry := tokens[0]
  109. if len(tokens) == 1 { // ! image names can include "." ...
  110. registry = dockerHub
  111. } else if !strings.Contains(registry, ".") {
  112. registry = dockerHub
  113. } else if strings.HasSuffix(registry, login.AcrRegistrySuffix) {
  114. acrRegistries = append(acrRegistries, registry)
  115. }
  116. usedRegistries[registry] = true
  117. }
  118. return usedRegistries, acrRegistries
  119. }
  120. func (c cliRegistryHelper) autoLoginAcr(registry string) error {
  121. loginService, err := login.NewAzureLoginService()
  122. if err != nil {
  123. return err
  124. }
  125. token, err := loginService.GetValidToken()
  126. if err != nil {
  127. return err
  128. }
  129. tenantID, err := loginService.GetTenantID()
  130. if err != nil {
  131. return err
  132. }
  133. data := url.Values{
  134. "grant_type": {"access_token"},
  135. "service": {registry},
  136. "tenant": {tenantID},
  137. "access_token": {token.AccessToken},
  138. }
  139. repoAuthURL := fmt.Sprintf("https://%s/oauth2/exchange", registry)
  140. res, err := http.Post(repoAuthURL, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  141. if err != nil {
  142. return errors.Wrap(err, "could not query ACR token")
  143. }
  144. bits, err := ioutil.ReadAll(res.Body)
  145. if err != nil {
  146. return errors.Wrap(err, "could not read response body")
  147. }
  148. if res.StatusCode != 200 {
  149. return errors.Errorf("could not obtain ACR token from Azure login, status : %s, response: %s", res.Status, string(bits))
  150. }
  151. newToken := oauth2.Token{}
  152. if err := json.Unmarshal(bits, &newToken); err != nil {
  153. return errors.Wrap(err, "could not read ACR token")
  154. }
  155. cmd := exec.Command("docker", "login", "-u", tokenUsername, "-p", newToken.RefreshToken, registry)
  156. bytes, err := cmd.CombinedOutput()
  157. if err != nil {
  158. return errors.Wrap(err, fmt.Sprintf("could not 'docker login' to %s :\n%s\n", registry, string(bytes)))
  159. }
  160. return nil
  161. }