auth.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. package registry
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/dotcloud/docker/utils"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "path"
  12. "strings"
  13. )
  14. // Where we store the config file
  15. const CONFIGFILE = ".dockercfg"
  16. // Only used for user auth + account creation
  17. const INDEXSERVER = "https://index.docker.io/v1/"
  18. //const INDEXSERVER = "https://indexstaging-docker.dotcloud.com/v1/"
  19. var (
  20. ErrConfigFileMissing = errors.New("The Auth config file is missing")
  21. )
  22. type AuthConfig struct {
  23. Username string `json:"username,omitempty"`
  24. Password string `json:"password,omitempty"`
  25. Auth string `json:"auth"`
  26. Email string `json:"email"`
  27. ServerAddress string `json:"serveraddress,omitempty"`
  28. }
  29. type ConfigFile struct {
  30. Configs map[string]AuthConfig `json:"configs,omitempty"`
  31. rootPath string
  32. }
  33. func IndexServerAddress() string {
  34. return INDEXSERVER
  35. }
  36. // create a base64 encoded auth string to store in config
  37. func encodeAuth(authConfig *AuthConfig) string {
  38. authStr := authConfig.Username + ":" + authConfig.Password
  39. msg := []byte(authStr)
  40. encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg)))
  41. base64.StdEncoding.Encode(encoded, msg)
  42. return string(encoded)
  43. }
  44. // decode the auth string
  45. func decodeAuth(authStr string) (string, string, error) {
  46. decLen := base64.StdEncoding.DecodedLen(len(authStr))
  47. decoded := make([]byte, decLen)
  48. authByte := []byte(authStr)
  49. n, err := base64.StdEncoding.Decode(decoded, authByte)
  50. if err != nil {
  51. return "", "", err
  52. }
  53. if n > decLen {
  54. return "", "", fmt.Errorf("Something went wrong decoding auth config")
  55. }
  56. arr := strings.SplitN(string(decoded), ":", 2)
  57. if len(arr) != 2 {
  58. return "", "", fmt.Errorf("Invalid auth configuration file")
  59. }
  60. password := strings.Trim(arr[1], "\x00")
  61. return arr[0], password, nil
  62. }
  63. // load up the auth config information and return values
  64. // FIXME: use the internal golang config parser
  65. func LoadConfig(rootPath string) (*ConfigFile, error) {
  66. configFile := ConfigFile{Configs: make(map[string]AuthConfig), rootPath: rootPath}
  67. confFile := path.Join(rootPath, CONFIGFILE)
  68. if _, err := os.Stat(confFile); err != nil {
  69. return &configFile, nil //missing file is not an error
  70. }
  71. b, err := ioutil.ReadFile(confFile)
  72. if err != nil {
  73. return &configFile, err
  74. }
  75. if err := json.Unmarshal(b, &configFile.Configs); err != nil {
  76. arr := strings.Split(string(b), "\n")
  77. if len(arr) < 2 {
  78. return &configFile, fmt.Errorf("The Auth config file is empty")
  79. }
  80. authConfig := AuthConfig{}
  81. origAuth := strings.Split(arr[0], " = ")
  82. if len(origAuth) != 2 {
  83. return &configFile, fmt.Errorf("Invalid Auth config file")
  84. }
  85. authConfig.Username, authConfig.Password, err = decodeAuth(origAuth[1])
  86. if err != nil {
  87. return &configFile, err
  88. }
  89. origEmail := strings.Split(arr[1], " = ")
  90. if len(origEmail) != 2 {
  91. return &configFile, fmt.Errorf("Invalid Auth config file")
  92. }
  93. authConfig.Email = origEmail[1]
  94. authConfig.ServerAddress = IndexServerAddress()
  95. configFile.Configs[IndexServerAddress()] = authConfig
  96. } else {
  97. for k, authConfig := range configFile.Configs {
  98. authConfig.Username, authConfig.Password, err = decodeAuth(authConfig.Auth)
  99. if err != nil {
  100. return &configFile, err
  101. }
  102. authConfig.Auth = ""
  103. configFile.Configs[k] = authConfig
  104. authConfig.ServerAddress = k
  105. }
  106. }
  107. return &configFile, nil
  108. }
  109. // save the auth config
  110. func SaveConfig(configFile *ConfigFile) error {
  111. confFile := path.Join(configFile.rootPath, CONFIGFILE)
  112. if len(configFile.Configs) == 0 {
  113. os.Remove(confFile)
  114. return nil
  115. }
  116. configs := make(map[string]AuthConfig, len(configFile.Configs))
  117. for k, authConfig := range configFile.Configs {
  118. authCopy := authConfig
  119. authCopy.Auth = encodeAuth(&authCopy)
  120. authCopy.Username = ""
  121. authCopy.Password = ""
  122. authCopy.ServerAddress = ""
  123. configs[k] = authCopy
  124. }
  125. b, err := json.Marshal(configs)
  126. if err != nil {
  127. return err
  128. }
  129. err = ioutil.WriteFile(confFile, b, 0600)
  130. if err != nil {
  131. return err
  132. }
  133. return nil
  134. }
  135. // try to register/login to the registry server
  136. func Login(authConfig *AuthConfig, factory *utils.HTTPRequestFactory) (string, error) {
  137. var (
  138. status string
  139. reqBody []byte
  140. err error
  141. client = &http.Client{}
  142. reqStatusCode = 0
  143. serverAddress = authConfig.ServerAddress
  144. )
  145. if serverAddress == "" {
  146. serverAddress = IndexServerAddress()
  147. }
  148. loginAgainstOfficialIndex := serverAddress == IndexServerAddress()
  149. // to avoid sending the server address to the server it should be removed before being marshalled
  150. authCopy := *authConfig
  151. authCopy.ServerAddress = ""
  152. jsonBody, err := json.Marshal(authCopy)
  153. if err != nil {
  154. return "", fmt.Errorf("Config Error: %s", err)
  155. }
  156. // using `bytes.NewReader(jsonBody)` here causes the server to respond with a 411 status.
  157. b := strings.NewReader(string(jsonBody))
  158. req1, err := http.Post(serverAddress+"users/", "application/json; charset=utf-8", b)
  159. if err != nil {
  160. return "", fmt.Errorf("Server Error: %s", err)
  161. }
  162. reqStatusCode = req1.StatusCode
  163. defer req1.Body.Close()
  164. reqBody, err = ioutil.ReadAll(req1.Body)
  165. if err != nil {
  166. return "", fmt.Errorf("Server Error: [%#v] %s", reqStatusCode, err)
  167. }
  168. if reqStatusCode == 201 {
  169. if loginAgainstOfficialIndex {
  170. status = "Account created. Please use the confirmation link we sent" +
  171. " to your e-mail to activate it."
  172. } else {
  173. status = "Account created. Please see the documentation of the registry " + serverAddress + " for instructions how to activate it."
  174. }
  175. } else if reqStatusCode == 400 {
  176. if string(reqBody) == "\"Username or email already exists\"" {
  177. req, err := factory.NewRequest("GET", serverAddress+"users/", nil)
  178. req.SetBasicAuth(authConfig.Username, authConfig.Password)
  179. resp, err := client.Do(req)
  180. if err != nil {
  181. return "", err
  182. }
  183. defer resp.Body.Close()
  184. body, err := ioutil.ReadAll(resp.Body)
  185. if err != nil {
  186. return "", err
  187. }
  188. if resp.StatusCode == 200 {
  189. status = "Login Succeeded"
  190. } else if resp.StatusCode == 401 {
  191. return "", fmt.Errorf("Wrong login/password, please try again")
  192. } else if resp.StatusCode == 403 {
  193. if loginAgainstOfficialIndex {
  194. return "", fmt.Errorf("Login: Account is not Active. Please check your e-mail for a confirmation link.")
  195. }
  196. return "", fmt.Errorf("Login: Account is not Active. Please see the documentation of the registry %s for instructions how to activate it.", serverAddress)
  197. } else {
  198. return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body, resp.StatusCode, resp.Header)
  199. }
  200. } else {
  201. return "", fmt.Errorf("Registration: %s", reqBody)
  202. }
  203. } else if reqStatusCode == 401 {
  204. // This case would happen with private registries where /v1/users is
  205. // protected, so people can use `docker login` as an auth check.
  206. req, err := factory.NewRequest("GET", serverAddress+"users/", nil)
  207. req.SetBasicAuth(authConfig.Username, authConfig.Password)
  208. resp, err := client.Do(req)
  209. if err != nil {
  210. return "", err
  211. }
  212. defer resp.Body.Close()
  213. body, err := ioutil.ReadAll(resp.Body)
  214. if err != nil {
  215. return "", err
  216. }
  217. if resp.StatusCode == 200 {
  218. status = "Login Succeeded"
  219. } else if resp.StatusCode == 401 {
  220. return "", fmt.Errorf("Wrong login/password, please try again")
  221. } else {
  222. return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body,
  223. resp.StatusCode, resp.Header)
  224. }
  225. } else {
  226. return "", fmt.Errorf("Unexpected status code [%d] : %s", reqStatusCode, reqBody)
  227. }
  228. return status, nil
  229. }
  230. // this method matches a auth configuration to a server address or a url
  231. func (config *ConfigFile) ResolveAuthConfig(hostname string) AuthConfig {
  232. if hostname == IndexServerAddress() || len(hostname) == 0 {
  233. // default to the index server
  234. return config.Configs[IndexServerAddress()]
  235. }
  236. // First try the happy case
  237. if c, found := config.Configs[hostname]; found {
  238. return c
  239. }
  240. convertToHostname := func(url string) string {
  241. stripped := url
  242. if strings.HasPrefix(url, "http://") {
  243. stripped = strings.Replace(url, "http://", "", 1)
  244. } else if strings.HasPrefix(url, "https://") {
  245. stripped = strings.Replace(url, "https://", "", 1)
  246. }
  247. nameParts := strings.SplitN(stripped, "/", 2)
  248. return nameParts[0]
  249. }
  250. // Maybe they have a legacy config file, we will iterate the keys converting
  251. // them to the new format and testing
  252. normalizedHostename := convertToHostname(hostname)
  253. for registry, config := range config.Configs {
  254. if registryHostname := convertToHostname(registry); registryHostname == normalizedHostename {
  255. return config
  256. }
  257. }
  258. // When all else fails, return an empty auth config
  259. return AuthConfig{}
  260. }