helper.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. // get the current project ID
  22. cliConfig, err := config.InitAndLoadConfig()
  23. if err != nil {
  24. return nil, fmt.Errorf("error loading porter config: %w", err)
  25. }
  26. cache := docker.NewFileCredentialsCache()
  27. client, err := api.NewClientWithConfig(ctx, api.NewClientInput{
  28. BaseURL: fmt.Sprintf("%s/api", cliConfig.Host),
  29. BearerToken: cliConfig.Token,
  30. CookieFileName: "cookie.json",
  31. })
  32. if err != nil {
  33. return nil, fmt.Errorf("unable to get porter API client: %w", err)
  34. }
  35. return &PorterHelper{
  36. Debug: debug,
  37. ProjectID: cliConfig.Project,
  38. AuthGetter: &docker.AuthGetter{
  39. Client: client,
  40. Cache: cache,
  41. ProjectID: cliConfig.Project,
  42. },
  43. Cache: cache,
  44. }, nil
  45. }
  46. // Add appends credentials to the store.
  47. func (p *PorterHelper) Add(cr *credentials.Credentials) error {
  48. // Doesn't seem to be called
  49. return nil
  50. }
  51. // Delete removes credentials from the store.
  52. func (p *PorterHelper) Delete(serverURL string) error {
  53. // Doesn't seem to be called
  54. return nil
  55. }
  56. // Get retrieves credentials from the store.
  57. // It returns username and secret as strings.
  58. func (p *PorterHelper) Get(serverURL string) (user string, secret string, err error) {
  59. ctx := context.TODO() // docker credentials.Serve interface blocks changing this for now
  60. return p.AuthGetter.GetCredentials(ctx, serverURL)
  61. }
  62. // List returns the stored serverURLs and their associated usernames.
  63. func (p *PorterHelper) List() (map[string]string, error) {
  64. entries := p.Cache.List()
  65. res := make(map[string]string)
  66. for _, entry := range entries {
  67. res[entry.ProxyEndpoint] = entry.AuthorizationToken
  68. }
  69. return res, nil
  70. }