auth.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. package auth
  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. client := &http.Client{}
  138. reqStatusCode := 0
  139. var status string
  140. var reqBody []byte
  141. serverAddress := authConfig.ServerAddress
  142. if serverAddress == "" {
  143. serverAddress = IndexServerAddress()
  144. }
  145. loginAgainstOfficialIndex := serverAddress == IndexServerAddress()
  146. // to avoid sending the server address to the server it should be removed before being marshalled
  147. authCopy := *authConfig
  148. authCopy.ServerAddress = ""
  149. jsonBody, err := json.Marshal(authCopy)
  150. if err != nil {
  151. return "", fmt.Errorf("Config Error: %s", err)
  152. }
  153. // using `bytes.NewReader(jsonBody)` here causes the server to respond with a 411 status.
  154. b := strings.NewReader(string(jsonBody))
  155. req1, err := http.Post(serverAddress+"users/", "application/json; charset=utf-8", b)
  156. if err != nil {
  157. return "", fmt.Errorf("Server Error: %s", err)
  158. }
  159. reqStatusCode = req1.StatusCode
  160. defer req1.Body.Close()
  161. reqBody, err = ioutil.ReadAll(req1.Body)
  162. if err != nil {
  163. return "", fmt.Errorf("Server Error: [%#v] %s", reqStatusCode, err)
  164. }
  165. if reqStatusCode == 201 {
  166. if loginAgainstOfficialIndex {
  167. status = "Account created. Please use the confirmation link we sent" +
  168. " to your e-mail to activate it."
  169. } else {
  170. status = "Account created. Please see the documentation of the registry " + serverAddress + " for instructions how to activate it."
  171. }
  172. } else if reqStatusCode == 400 {
  173. if string(reqBody) == "\"Username or email already exists\"" {
  174. req, err := factory.NewRequest("GET", serverAddress+"users/", nil)
  175. req.SetBasicAuth(authConfig.Username, authConfig.Password)
  176. resp, err := client.Do(req)
  177. if err != nil {
  178. return "", err
  179. }
  180. defer resp.Body.Close()
  181. body, err := ioutil.ReadAll(resp.Body)
  182. if err != nil {
  183. return "", err
  184. }
  185. if resp.StatusCode == 200 {
  186. status = "Login Succeeded"
  187. } else if resp.StatusCode == 401 {
  188. return "", fmt.Errorf("Wrong login/password, please try again")
  189. } else if resp.StatusCode == 403 {
  190. if loginAgainstOfficialIndex {
  191. return "", fmt.Errorf("Login: Account is not Active. Please check your e-mail for a confirmation link.")
  192. }
  193. return "", fmt.Errorf("Login: Account is not Active. Please see the documentation of the registry %s for instructions how to activate it.", serverAddress)
  194. } else {
  195. return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body, resp.StatusCode, resp.Header)
  196. }
  197. } else {
  198. return "", fmt.Errorf("Registration: %s", reqBody)
  199. }
  200. } else if reqStatusCode == 401 {
  201. // This case would happen with private registries where /v1/users is
  202. // protected, so people can use `docker login` as an auth check.
  203. req, err := factory.NewRequest("GET", serverAddress+"users/", nil)
  204. req.SetBasicAuth(authConfig.Username, authConfig.Password)
  205. resp, err := client.Do(req)
  206. if err != nil {
  207. return "", err
  208. }
  209. defer resp.Body.Close()
  210. body, err := ioutil.ReadAll(resp.Body)
  211. if err != nil {
  212. return "", err
  213. }
  214. if resp.StatusCode == 200 {
  215. status = "Login Succeeded"
  216. } else if resp.StatusCode == 401 {
  217. return "", fmt.Errorf("Wrong login/password, please try again")
  218. } else {
  219. return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body,
  220. resp.StatusCode, resp.Header)
  221. }
  222. } else {
  223. return "", fmt.Errorf("Unexpected status code [%d] : %s", reqStatusCode, reqBody)
  224. }
  225. return status, nil
  226. }
  227. // this method matches a auth configuration to a server address or a url
  228. func (config *ConfigFile) ResolveAuthConfig(registry string) AuthConfig {
  229. if registry == IndexServerAddress() || len(registry) == 0 {
  230. // default to the index server
  231. return config.Configs[IndexServerAddress()]
  232. }
  233. // if it's not the index server there are three cases:
  234. //
  235. // 1. a full config url -> it should be used as is
  236. // 2. a full url, but with the wrong protocol
  237. // 3. a hostname, with an optional port
  238. //
  239. // as there is only one auth entry which is fully qualified we need to start
  240. // parsing and matching
  241. swapProtocol := func(url string) string {
  242. if strings.HasPrefix(url, "http:") {
  243. return strings.Replace(url, "http:", "https:", 1)
  244. }
  245. if strings.HasPrefix(url, "https:") {
  246. return strings.Replace(url, "https:", "http:", 1)
  247. }
  248. return url
  249. }
  250. resolveIgnoringProtocol := func(url string) AuthConfig {
  251. if c, found := config.Configs[url]; found {
  252. return c
  253. }
  254. registrySwappedProtocol := swapProtocol(url)
  255. // now try to match with the different protocol
  256. if c, found := config.Configs[registrySwappedProtocol]; found {
  257. return c
  258. }
  259. return AuthConfig{}
  260. }
  261. // match both protocols as it could also be a server name like httpfoo
  262. if strings.HasPrefix(registry, "http:") || strings.HasPrefix(registry, "https:") {
  263. return resolveIgnoringProtocol(registry)
  264. }
  265. url := "https://" + registry
  266. if !strings.Contains(registry, "/") {
  267. url = url + "/v1/"
  268. }
  269. return resolveIgnoringProtocol(url)
  270. }