helper.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package helper
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/docker/docker-credential-helpers/credentials"
  6. api "github.com/porter-dev/porter/api/client"
  7. "github.com/porter-dev/porter/cli/cmd/config"
  8. "github.com/porter-dev/porter/cli/cmd/docker"
  9. )
  10. // PorterHelper implements credentials.Helper: it acts as a credentials
  11. // helper for Docker that allows authentication with different registries.
  12. type PorterHelper struct {
  13. Debug bool
  14. ProjectID uint
  15. AuthGetter *docker.AuthGetter
  16. Cache docker.CredentialsCache
  17. }
  18. // NewPorterHelper creates a docker credential helper
  19. func NewPorterHelper(debug bool) (*PorterHelper, error) {
  20. ctx := context.Background()
  21. cliConfig, _, err := config.InitAndLoadConfig(ctx, "", config.CLIConfig{})
  22. if err != nil {
  23. return nil, fmt.Errorf("error loading porter config: %w", err)
  24. }
  25. cache := docker.NewFileCredentialsCache()
  26. client, err := api.NewClientWithConfig(ctx, api.NewClientInput{
  27. BaseURL: fmt.Sprintf("%s/api", cliConfig.Host),
  28. BearerToken: cliConfig.Token,
  29. CookieFileName: "cookie.json",
  30. })
  31. if err != nil {
  32. return nil, fmt.Errorf("unable to get porter API client: %w", err)
  33. }
  34. return &PorterHelper{
  35. Debug: debug,
  36. ProjectID: cliConfig.Project,
  37. AuthGetter: &docker.AuthGetter{
  38. Client: client,
  39. Cache: cache,
  40. ProjectID: cliConfig.Project,
  41. },
  42. Cache: cache,
  43. }, nil
  44. }
  45. // Add appends credentials to the store.
  46. func (p *PorterHelper) Add(cr *credentials.Credentials) error {
  47. // Doesn't seem to be called
  48. return nil
  49. }
  50. // Delete removes credentials from the store.
  51. func (p *PorterHelper) Delete(serverURL string) error {
  52. // Doesn't seem to be called
  53. return nil
  54. }
  55. // Get retrieves credentials from the store.
  56. // It returns username and secret as strings.
  57. func (p *PorterHelper) Get(serverURL string) (user string, secret string, err error) {
  58. ctx := context.TODO() // docker credentials.Serve interface blocks changing this for now
  59. return p.AuthGetter.GetCredentials(ctx, serverURL)
  60. }
  61. // List returns the stored serverURLs and their associated usernames.
  62. func (p *PorterHelper) List() (map[string]string, error) {
  63. entries := p.Cache.List()
  64. res := make(map[string]string)
  65. for _, entry := range entries {
  66. res[entry.ProxyEndpoint] = entry.AuthorizationToken
  67. }
  68. return res, nil
  69. }