config.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /*
  2. Copyright 2014 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. package credentialprovider
  14. import (
  15. "encoding/base64"
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "io/ioutil"
  21. "net/http"
  22. "os"
  23. "path/filepath"
  24. "strings"
  25. "sync"
  26. "k8s.io/klog"
  27. )
  28. const (
  29. maxReadLength = 10 * 1 << 20 // 10MB
  30. )
  31. // DockerConfigJson represents ~/.docker/config.json file info
  32. // see https://github.com/docker/docker/pull/12009
  33. type DockerConfigJson struct {
  34. Auths DockerConfig `json:"auths"`
  35. // +optional
  36. HttpHeaders map[string]string `json:"HttpHeaders,omitempty"`
  37. }
  38. // DockerConfig represents the config file used by the docker CLI.
  39. // This config that represents the credentials that should be used
  40. // when pulling images from specific image repositories.
  41. type DockerConfig map[string]DockerConfigEntry
  42. type DockerConfigEntry struct {
  43. Username string
  44. Password string
  45. Email string
  46. Provider DockerConfigProvider
  47. }
  48. var (
  49. preferredPathLock sync.Mutex
  50. preferredPath = ""
  51. workingDirPath = ""
  52. homeDirPath, _ = os.UserHomeDir()
  53. rootDirPath = "/"
  54. homeJsonDirPath = filepath.Join(homeDirPath, ".docker")
  55. rootJsonDirPath = filepath.Join(rootDirPath, ".docker")
  56. configFileName = ".dockercfg"
  57. configJsonFileName = "config.json"
  58. )
  59. func SetPreferredDockercfgPath(path string) {
  60. preferredPathLock.Lock()
  61. defer preferredPathLock.Unlock()
  62. preferredPath = path
  63. }
  64. func GetPreferredDockercfgPath() string {
  65. preferredPathLock.Lock()
  66. defer preferredPathLock.Unlock()
  67. return preferredPath
  68. }
  69. //DefaultDockercfgPaths returns default search paths of .dockercfg
  70. func DefaultDockercfgPaths() []string {
  71. return []string{GetPreferredDockercfgPath(), workingDirPath, homeDirPath, rootDirPath}
  72. }
  73. //DefaultDockerConfigJSONPaths returns default search paths of .docker/config.json
  74. func DefaultDockerConfigJSONPaths() []string {
  75. return []string{GetPreferredDockercfgPath(), workingDirPath, homeJsonDirPath, rootJsonDirPath}
  76. }
  77. // ReadDockercfgFile attempts to read a legacy dockercfg file from the given paths.
  78. // if searchPaths is empty, the default paths are used.
  79. func ReadDockercfgFile(searchPaths []string) (cfg DockerConfig, err error) {
  80. if len(searchPaths) == 0 {
  81. searchPaths = DefaultDockercfgPaths()
  82. }
  83. for _, configPath := range searchPaths {
  84. absDockerConfigFileLocation, err := filepath.Abs(filepath.Join(configPath, configFileName))
  85. if err != nil {
  86. klog.Errorf("while trying to canonicalize %s: %v", configPath, err)
  87. continue
  88. }
  89. klog.V(4).Infof("looking for .dockercfg at %s", absDockerConfigFileLocation)
  90. contents, err := ioutil.ReadFile(absDockerConfigFileLocation)
  91. if os.IsNotExist(err) {
  92. continue
  93. }
  94. if err != nil {
  95. klog.V(4).Infof("while trying to read %s: %v", absDockerConfigFileLocation, err)
  96. continue
  97. }
  98. cfg, err := readDockerConfigFileFromBytes(contents)
  99. if err == nil {
  100. klog.V(4).Infof("found .dockercfg at %s", absDockerConfigFileLocation)
  101. return cfg, nil
  102. }
  103. }
  104. return nil, fmt.Errorf("couldn't find valid .dockercfg after checking in %v", searchPaths)
  105. }
  106. // ReadDockerConfigJSONFile attempts to read a docker config.json file from the given paths.
  107. // if searchPaths is empty, the default paths are used.
  108. func ReadDockerConfigJSONFile(searchPaths []string) (cfg DockerConfig, err error) {
  109. if len(searchPaths) == 0 {
  110. searchPaths = DefaultDockerConfigJSONPaths()
  111. }
  112. for _, configPath := range searchPaths {
  113. absDockerConfigFileLocation, err := filepath.Abs(filepath.Join(configPath, configJsonFileName))
  114. if err != nil {
  115. klog.Errorf("while trying to canonicalize %s: %v", configPath, err)
  116. continue
  117. }
  118. klog.V(4).Infof("looking for %s at %s", configJsonFileName, absDockerConfigFileLocation)
  119. cfg, err = ReadSpecificDockerConfigJsonFile(absDockerConfigFileLocation)
  120. if err != nil {
  121. if !os.IsNotExist(err) {
  122. klog.V(4).Infof("while trying to read %s: %v", absDockerConfigFileLocation, err)
  123. }
  124. continue
  125. }
  126. klog.V(4).Infof("found valid %s at %s", configJsonFileName, absDockerConfigFileLocation)
  127. return cfg, nil
  128. }
  129. return nil, fmt.Errorf("couldn't find valid %s after checking in %v", configJsonFileName, searchPaths)
  130. }
  131. //ReadSpecificDockerConfigJsonFile attempts to read docker configJSON from a given file path.
  132. func ReadSpecificDockerConfigJsonFile(filePath string) (cfg DockerConfig, err error) {
  133. var contents []byte
  134. if contents, err = ioutil.ReadFile(filePath); err != nil {
  135. return nil, err
  136. }
  137. return readDockerConfigJsonFileFromBytes(contents)
  138. }
  139. func ReadDockerConfigFile() (cfg DockerConfig, err error) {
  140. if cfg, err := ReadDockerConfigJSONFile(nil); err == nil {
  141. return cfg, nil
  142. }
  143. // Can't find latest config file so check for the old one
  144. return ReadDockercfgFile(nil)
  145. }
  146. // HttpError wraps a non-StatusOK error code as an error.
  147. type HttpError struct {
  148. StatusCode int
  149. Url string
  150. }
  151. // Error implements error
  152. func (he *HttpError) Error() string {
  153. return fmt.Sprintf("http status code: %d while fetching url %s",
  154. he.StatusCode, he.Url)
  155. }
  156. func ReadUrl(url string, client *http.Client, header *http.Header) (body []byte, err error) {
  157. req, err := http.NewRequest("GET", url, nil)
  158. if err != nil {
  159. return nil, err
  160. }
  161. if header != nil {
  162. req.Header = *header
  163. }
  164. resp, err := client.Do(req)
  165. if err != nil {
  166. return nil, err
  167. }
  168. defer resp.Body.Close()
  169. if resp.StatusCode != http.StatusOK {
  170. klog.V(2).Infof("body of failing http response: %v", resp.Body)
  171. return nil, &HttpError{
  172. StatusCode: resp.StatusCode,
  173. Url: url,
  174. }
  175. }
  176. limitedReader := &io.LimitedReader{R: resp.Body, N: maxReadLength}
  177. contents, err := ioutil.ReadAll(limitedReader)
  178. if err != nil {
  179. return nil, err
  180. }
  181. if limitedReader.N <= 0 {
  182. return nil, errors.New("the read limit is reached")
  183. }
  184. return contents, nil
  185. }
  186. func ReadDockerConfigFileFromUrl(url string, client *http.Client, header *http.Header) (cfg DockerConfig, err error) {
  187. if contents, err := ReadUrl(url, client, header); err != nil {
  188. return nil, err
  189. } else {
  190. return readDockerConfigFileFromBytes(contents)
  191. }
  192. }
  193. func readDockerConfigFileFromBytes(contents []byte) (cfg DockerConfig, err error) {
  194. if err = json.Unmarshal(contents, &cfg); err != nil {
  195. klog.Errorf("while trying to parse blob %q: %v", contents, err)
  196. return nil, err
  197. }
  198. return
  199. }
  200. func readDockerConfigJsonFileFromBytes(contents []byte) (cfg DockerConfig, err error) {
  201. var cfgJson DockerConfigJson
  202. if err = json.Unmarshal(contents, &cfgJson); err != nil {
  203. klog.Errorf("while trying to parse blob %q: %v", contents, err)
  204. return nil, err
  205. }
  206. cfg = cfgJson.Auths
  207. return
  208. }
  209. // dockerConfigEntryWithAuth is used solely for deserializing the Auth field
  210. // into a dockerConfigEntry during JSON deserialization.
  211. type dockerConfigEntryWithAuth struct {
  212. // +optional
  213. Username string `json:"username,omitempty"`
  214. // +optional
  215. Password string `json:"password,omitempty"`
  216. // +optional
  217. Email string `json:"email,omitempty"`
  218. // +optional
  219. Auth string `json:"auth,omitempty"`
  220. }
  221. func (ident *DockerConfigEntry) UnmarshalJSON(data []byte) error {
  222. var tmp dockerConfigEntryWithAuth
  223. err := json.Unmarshal(data, &tmp)
  224. if err != nil {
  225. return err
  226. }
  227. ident.Username = tmp.Username
  228. ident.Password = tmp.Password
  229. ident.Email = tmp.Email
  230. if len(tmp.Auth) == 0 {
  231. return nil
  232. }
  233. ident.Username, ident.Password, err = decodeDockerConfigFieldAuth(tmp.Auth)
  234. return err
  235. }
  236. func (ident DockerConfigEntry) MarshalJSON() ([]byte, error) {
  237. toEncode := dockerConfigEntryWithAuth{ident.Username, ident.Password, ident.Email, ""}
  238. toEncode.Auth = encodeDockerConfigFieldAuth(ident.Username, ident.Password)
  239. return json.Marshal(toEncode)
  240. }
  241. // decodeDockerConfigFieldAuth deserializes the "auth" field from dockercfg into a
  242. // username and a password. The format of the auth field is base64(<username>:<password>).
  243. func decodeDockerConfigFieldAuth(field string) (username, password string, err error) {
  244. decoded, err := base64.StdEncoding.DecodeString(field)
  245. if err != nil {
  246. return
  247. }
  248. parts := strings.SplitN(string(decoded), ":", 2)
  249. if len(parts) != 2 {
  250. err = fmt.Errorf("unable to parse auth field")
  251. return
  252. }
  253. username = parts[0]
  254. password = parts[1]
  255. return
  256. }
  257. func encodeDockerConfigFieldAuth(username, password string) string {
  258. fieldValue := username + ":" + password
  259. return base64.StdEncoding.EncodeToString([]byte(fieldValue))
  260. }