helper.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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 login
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "io/ioutil"
  18. "math/rand"
  19. "net/http"
  20. "net/url"
  21. "os/exec"
  22. "runtime"
  23. "strings"
  24. "github.com/Azure/go-autorest/autorest/adal"
  25. "github.com/Azure/go-autorest/autorest/azure/auth"
  26. "github.com/pkg/errors"
  27. )
  28. var (
  29. letterRunes = []rune("abcdefghijklmnopqrstuvwxyz123456789")
  30. )
  31. type apiHelper interface {
  32. queryToken(data url.Values, tenantID string) (azureToken, error)
  33. openAzureLoginPage(redirectURL string) error
  34. queryAPIWithHeader(authorizationURL string, authorizationHeader string) ([]byte, int, error)
  35. getDeviceCodeFlowToken() (adal.Token, error)
  36. }
  37. type azureAPIHelper struct{}
  38. func (helper azureAPIHelper) getDeviceCodeFlowToken() (adal.Token, error) {
  39. deviceconfig := auth.NewDeviceFlowConfig(clientID, "common")
  40. deviceconfig.Resource = "https://management.core.windows.net/"
  41. spToken, err := deviceconfig.ServicePrincipalToken()
  42. if err != nil {
  43. return adal.Token{}, err
  44. }
  45. return spToken.Token(), err
  46. }
  47. func (helper azureAPIHelper) openAzureLoginPage(redirectURL string) error {
  48. state := randomString("", 10)
  49. authURL := fmt.Sprintf(authorizeFormat, clientID, redirectURL, state, scopes)
  50. return openbrowser(authURL)
  51. }
  52. func (helper azureAPIHelper) queryAPIWithHeader(authorizationURL string, authorizationHeader string) ([]byte, int, error) {
  53. req, err := http.NewRequest(http.MethodGet, authorizationURL, nil)
  54. if err != nil {
  55. return nil, 0, err
  56. }
  57. req.Header.Add("Authorization", authorizationHeader)
  58. res, err := http.DefaultClient.Do(req)
  59. if err != nil {
  60. return nil, 0, err
  61. }
  62. bits, err := ioutil.ReadAll(res.Body)
  63. if err != nil {
  64. return nil, 0, err
  65. }
  66. return bits, res.StatusCode, nil
  67. }
  68. func (helper azureAPIHelper) queryToken(data url.Values, tenantID string) (azureToken, error) {
  69. res, err := http.Post(fmt.Sprintf(tokenEndpoint, tenantID), "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  70. if err != nil {
  71. return azureToken{}, err
  72. }
  73. if res.StatusCode != 200 {
  74. return azureToken{}, errors.Errorf("error while renewing access token, status : %s", res.Status)
  75. }
  76. bits, err := ioutil.ReadAll(res.Body)
  77. if err != nil {
  78. return azureToken{}, err
  79. }
  80. token := azureToken{}
  81. if err := json.Unmarshal(bits, &token); err != nil {
  82. return azureToken{}, err
  83. }
  84. return token, nil
  85. }
  86. func openbrowser(address string) error {
  87. switch runtime.GOOS {
  88. case "linux":
  89. if isWsl() {
  90. return exec.Command("wslview", address).Run()
  91. }
  92. return exec.Command("xdg-open", address).Run()
  93. case "windows":
  94. return exec.Command("rundll32", "url.dll,FileProtocolHandler", address).Run()
  95. case "darwin":
  96. return exec.Command("open", address).Run()
  97. default:
  98. return fmt.Errorf("unsupported platform")
  99. }
  100. }
  101. func isWsl() bool {
  102. b, err := ioutil.ReadFile("/proc/version")
  103. if err != nil {
  104. return false
  105. }
  106. return strings.Contains(string(b), "microsoft")
  107. }
  108. func randomString(prefix string, length int) string {
  109. b := make([]rune, length)
  110. for i := range b {
  111. b[i] = letterRunes[rand.Intn(len(letterRunes))]
  112. }
  113. return prefix + string(b)
  114. }