auth.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package docker
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "strings"
  6. "github.com/rancher/os/config"
  7. "github.com/rancher/os/pkg/log"
  8. "github.com/docker/docker/registry"
  9. "github.com/docker/engine-api/types"
  10. "github.com/docker/libcompose/docker"
  11. )
  12. // ConfigAuthLookup will lookup registry auth info from cloud config
  13. // if a context is set, it will also lookup auth info from the Docker config file
  14. type ConfigAuthLookup struct {
  15. cfg *config.CloudConfig
  16. context *docker.Context
  17. dockerConfigAuthLookup *docker.ConfigAuthLookup
  18. }
  19. func NewConfigAuthLookup(cfg *config.CloudConfig) *ConfigAuthLookup {
  20. return &ConfigAuthLookup{
  21. cfg: cfg,
  22. }
  23. }
  24. func populateRemaining(authConfig *types.AuthConfig) error {
  25. if authConfig.Auth == "" {
  26. return nil
  27. }
  28. decoded, err := base64.URLEncoding.DecodeString(authConfig.Auth)
  29. if err != nil {
  30. return err
  31. }
  32. decodedSplit := strings.Split(string(decoded), ":")
  33. if len(decodedSplit) != 2 {
  34. return fmt.Errorf("Invalid auth: %s", authConfig.Auth)
  35. }
  36. authConfig.Username = decodedSplit[0]
  37. authConfig.Password = decodedSplit[1]
  38. return nil
  39. }
  40. func (c *ConfigAuthLookup) SetConfig(cfg *config.CloudConfig) {
  41. c.cfg = cfg
  42. }
  43. func (c *ConfigAuthLookup) SetContext(context *docker.Context) {
  44. c.context = context
  45. c.dockerConfigAuthLookup = docker.NewConfigAuthLookup(context)
  46. }
  47. func (c *ConfigAuthLookup) Lookup(repoInfo *registry.RepositoryInfo) types.AuthConfig {
  48. if repoInfo == nil || repoInfo.Index == nil {
  49. return types.AuthConfig{}
  50. }
  51. authConfig := registry.ResolveAuthConfig(c.All(), repoInfo.Index)
  52. err := populateRemaining(&authConfig)
  53. if err != nil {
  54. log.Error(err)
  55. return types.AuthConfig{}
  56. }
  57. return authConfig
  58. }
  59. func (c *ConfigAuthLookup) All() map[string]types.AuthConfig {
  60. registryAuths := c.cfg.Rancher.RegistryAuths
  61. if c.dockerConfigAuthLookup != nil {
  62. for registry, authConfig := range c.dockerConfigAuthLookup.All() {
  63. registryAuths[registry] = authConfig
  64. }
  65. }
  66. return registryAuths
  67. }