credentials.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package credentials
  2. import (
  3. "github.com/pkg/errors"
  4. "github.com/rs/zerolog"
  5. "github.com/cloudflare/cloudflared/cfapi"
  6. )
  7. const (
  8. logFieldOriginCertPath = "originCertPath"
  9. )
  10. type User struct {
  11. cert *OriginCert
  12. certPath string
  13. }
  14. func (c User) AccountID() string {
  15. return c.cert.AccountID
  16. }
  17. func (c User) ZoneID() string {
  18. return c.cert.ZoneID
  19. }
  20. func (c User) APIToken() string {
  21. return c.cert.APIToken
  22. }
  23. func (c User) CertPath() string {
  24. return c.certPath
  25. }
  26. // Client uses the user credentials to create a Cloudflare API client
  27. func (c *User) Client(apiURL string, userAgent string, log *zerolog.Logger) (cfapi.Client, error) {
  28. if apiURL == "" {
  29. return nil, errors.New("An api-url was not provided for the Cloudflare API client")
  30. }
  31. client, err := cfapi.NewRESTClient(
  32. apiURL,
  33. c.cert.AccountID,
  34. c.cert.ZoneID,
  35. c.cert.APIToken,
  36. userAgent,
  37. log,
  38. )
  39. if err != nil {
  40. return nil, err
  41. }
  42. return client, nil
  43. }
  44. // Read will load and read the origin cert.pem to load the user credentials
  45. func Read(originCertPath string, log *zerolog.Logger) (*User, error) {
  46. originCertLog := log.With().
  47. Str(logFieldOriginCertPath, originCertPath).
  48. Logger()
  49. originCertPath, err := FindOriginCert(originCertPath, &originCertLog)
  50. if err != nil {
  51. return nil, errors.Wrap(err, "Error locating origin cert")
  52. }
  53. blocks, err := readOriginCert(originCertPath)
  54. if err != nil {
  55. return nil, errors.Wrapf(err, "Can't read origin cert from %s", originCertPath)
  56. }
  57. cert, err := decodeOriginCert(blocks)
  58. if err != nil {
  59. return nil, errors.Wrap(err, "Error decoding origin cert")
  60. }
  61. if cert.AccountID == "" {
  62. return nil, errors.Errorf(`Origin certificate needs to be refreshed before creating new tunnels.\nDelete %s and run "cloudflared login" to obtain a new cert.`, originCertPath)
  63. }
  64. return &User{
  65. cert: cert,
  66. certPath: originCertPath,
  67. }, nil
  68. }