azure_acr_helper.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /*
  2. Copyright 2016 The Kubernetes 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. /*
  14. Copyright 2017 Microsoft Corporation
  15. MIT License
  16. Copyright (c) Microsoft Corporation. All rights reserved.
  17. Permission is hereby granted, free of charge, to any person obtaining a copy
  18. of this software and associated documentation files (the "Software"), to deal
  19. in the Software without restriction, including without limitation the rights
  20. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21. copies of the Software, and to permit persons to whom the Software is
  22. furnished to do so, subject to the following conditions:
  23. The above copyright notice and this permission notice shall be included in all
  24. copies or substantial portions of the Software.
  25. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  26. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  27. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  28. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  29. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  30. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  31. SOFTWARE
  32. */
  33. // Source: https://github.com/Azure/acr-docker-credential-helper/blob/a79b541f3ee761f6cc4511863ed41fb038c19464/src/docker-credential-acr/acr_login.go
  34. package azure
  35. import (
  36. "bytes"
  37. "encoding/json"
  38. "errors"
  39. "fmt"
  40. "io"
  41. "io/ioutil"
  42. "net/http"
  43. "net/url"
  44. "strconv"
  45. "strings"
  46. "unicode"
  47. )
  48. type authDirective struct {
  49. service string
  50. realm string
  51. }
  52. type acrAuthResponse struct {
  53. RefreshToken string `json:"refresh_token"`
  54. }
  55. // 5 minutes buffer time to allow timeshift between local machine and AAD
  56. const userAgentHeader = "User-Agent"
  57. const userAgent = "kubernetes-credentialprovider-acr"
  58. const dockerTokenLoginUsernameGUID = "00000000-0000-0000-0000-000000000000"
  59. var client = &http.Client{}
  60. func receiveChallengeFromLoginServer(serverAddress string) (*authDirective, error) {
  61. challengeURL := url.URL{
  62. Scheme: "https",
  63. Host: serverAddress,
  64. Path: "v2/",
  65. }
  66. var err error
  67. var r *http.Request
  68. r, err = http.NewRequest("GET", challengeURL.String(), nil)
  69. if err != nil {
  70. return nil, fmt.Errorf("failed to construct request, got %v", err)
  71. }
  72. r.Header.Add(userAgentHeader, userAgent)
  73. var challenge *http.Response
  74. if challenge, err = client.Do(r); err != nil {
  75. return nil, fmt.Errorf("error reaching registry endpoint %s, error: %s", challengeURL.String(), err)
  76. }
  77. defer challenge.Body.Close()
  78. if challenge.StatusCode != 401 {
  79. return nil, fmt.Errorf("registry did not issue a valid AAD challenge, status: %d", challenge.StatusCode)
  80. }
  81. var authHeader []string
  82. var ok bool
  83. if authHeader, ok = challenge.Header["Www-Authenticate"]; !ok {
  84. return nil, fmt.Errorf("challenge response does not contain header 'Www-Authenticate'")
  85. }
  86. if len(authHeader) != 1 {
  87. return nil, fmt.Errorf("registry did not issue a valid AAD challenge, authenticate header [%s]",
  88. strings.Join(authHeader, ", "))
  89. }
  90. authSections := strings.SplitN(authHeader[0], " ", 2)
  91. authType := strings.ToLower(authSections[0])
  92. var authParams *map[string]string
  93. if authParams, err = parseAssignments(authSections[1]); err != nil {
  94. return nil, fmt.Errorf("unable to understand the contents of Www-Authenticate header %s", authSections[1])
  95. }
  96. // verify headers
  97. if !strings.EqualFold("Bearer", authType) {
  98. return nil, fmt.Errorf("Www-Authenticate: expected realm: Bearer, actual: %s", authType)
  99. }
  100. if len((*authParams)["service"]) == 0 {
  101. return nil, fmt.Errorf("Www-Authenticate: missing header \"service\"")
  102. }
  103. if len((*authParams)["realm"]) == 0 {
  104. return nil, fmt.Errorf("Www-Authenticate: missing header \"realm\"")
  105. }
  106. return &authDirective{
  107. service: (*authParams)["service"],
  108. realm: (*authParams)["realm"],
  109. }, nil
  110. }
  111. func performTokenExchange(
  112. serverAddress string,
  113. directive *authDirective,
  114. tenant string,
  115. accessToken string) (string, error) {
  116. var err error
  117. data := url.Values{
  118. "service": []string{directive.service},
  119. "grant_type": []string{"access_token_refresh_token"},
  120. "access_token": []string{accessToken},
  121. "refresh_token": []string{accessToken},
  122. "tenant": []string{tenant},
  123. }
  124. var realmURL *url.URL
  125. if realmURL, err = url.Parse(directive.realm); err != nil {
  126. return "", fmt.Errorf("Www-Authenticate: invalid realm %s", directive.realm)
  127. }
  128. authEndpoint := fmt.Sprintf("%s://%s/oauth2/exchange", realmURL.Scheme, realmURL.Host)
  129. datac := data.Encode()
  130. var r *http.Request
  131. r, err = http.NewRequest("POST", authEndpoint, bytes.NewBufferString(datac))
  132. if err != nil {
  133. return "", fmt.Errorf("failed to construct request, got %v", err)
  134. }
  135. r.Header.Add(userAgentHeader, userAgent)
  136. r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  137. r.Header.Add("Content-Length", strconv.Itoa(len(datac)))
  138. var exchange *http.Response
  139. if exchange, err = client.Do(r); err != nil {
  140. return "", fmt.Errorf("Www-Authenticate: failed to reach auth url %s", authEndpoint)
  141. }
  142. defer exchange.Body.Close()
  143. if exchange.StatusCode != 200 {
  144. return "", fmt.Errorf("Www-Authenticate: auth url %s responded with status code %d", authEndpoint, exchange.StatusCode)
  145. }
  146. var content []byte
  147. limitedReader := &io.LimitedReader{R: exchange.Body, N: maxReadLength}
  148. if content, err = ioutil.ReadAll(limitedReader); err != nil {
  149. return "", fmt.Errorf("Www-Authenticate: error reading response from %s", authEndpoint)
  150. }
  151. if limitedReader.N <= 0 {
  152. return "", errors.New("the read limit is reached")
  153. }
  154. var authResp acrAuthResponse
  155. if err = json.Unmarshal(content, &authResp); err != nil {
  156. return "", fmt.Errorf("Www-Authenticate: unable to read response %s", content)
  157. }
  158. return authResp.RefreshToken, nil
  159. }
  160. // Try and parse a string of assignments in the form of:
  161. // key1 = value1, key2 = "value 2", key3 = ""
  162. // Note: this method and handle quotes but does not handle escaping of quotes
  163. func parseAssignments(statements string) (*map[string]string, error) {
  164. var cursor int
  165. result := make(map[string]string)
  166. var errorMsg = fmt.Errorf("malformed header value: %s", statements)
  167. for {
  168. // parse key
  169. equalIndex := nextOccurrence(statements, cursor, "=")
  170. if equalIndex == -1 {
  171. return nil, errorMsg
  172. }
  173. key := strings.TrimSpace(statements[cursor:equalIndex])
  174. // parse value
  175. cursor = nextNoneSpace(statements, equalIndex+1)
  176. if cursor == -1 {
  177. return nil, errorMsg
  178. }
  179. // case: value is quoted
  180. if statements[cursor] == '"' {
  181. cursor = cursor + 1
  182. // like I said, not handling escapes, but this will skip any comma that's
  183. // within the quotes which is somewhat more likely
  184. closeQuoteIndex := nextOccurrence(statements, cursor, "\"")
  185. if closeQuoteIndex == -1 {
  186. return nil, errorMsg
  187. }
  188. value := statements[cursor:closeQuoteIndex]
  189. result[key] = value
  190. commaIndex := nextNoneSpace(statements, closeQuoteIndex+1)
  191. if commaIndex == -1 {
  192. // no more comma, done
  193. return &result, nil
  194. } else if statements[commaIndex] != ',' {
  195. // expect comma immediately after close quote
  196. return nil, errorMsg
  197. } else {
  198. cursor = commaIndex + 1
  199. }
  200. } else {
  201. commaIndex := nextOccurrence(statements, cursor, ",")
  202. endStatements := commaIndex == -1
  203. var untrimmed string
  204. if endStatements {
  205. untrimmed = statements[cursor:commaIndex]
  206. } else {
  207. untrimmed = statements[cursor:]
  208. }
  209. value := strings.TrimSpace(untrimmed)
  210. if len(value) == 0 {
  211. // disallow empty value without quote
  212. return nil, errorMsg
  213. }
  214. result[key] = value
  215. if endStatements {
  216. return &result, nil
  217. }
  218. cursor = commaIndex + 1
  219. }
  220. }
  221. }
  222. func nextOccurrence(str string, start int, sep string) int {
  223. if start >= len(str) {
  224. return -1
  225. }
  226. offset := strings.Index(str[start:], sep)
  227. if offset == -1 {
  228. return -1
  229. }
  230. return offset + start
  231. }
  232. func nextNoneSpace(str string, start int) int {
  233. if start >= len(str) {
  234. return -1
  235. }
  236. offset := strings.IndexFunc(str[start:], func(c rune) bool { return !unicode.IsSpace(c) })
  237. if offset == -1 {
  238. return -1
  239. }
  240. return offset + start
  241. }