credentials.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. FedEndpoint = "fed"
  10. )
  11. type User struct {
  12. cert *OriginCert
  13. certPath string
  14. }
  15. func (c User) AccountID() string {
  16. return c.cert.AccountID
  17. }
  18. func (c User) ZoneID() string {
  19. return c.cert.ZoneID
  20. }
  21. func (c User) APIToken() string {
  22. return c.cert.APIToken
  23. }
  24. func (c User) CertPath() string {
  25. return c.certPath
  26. }
  27. func (c User) IsFEDEndpoint() bool {
  28. return c.cert.Endpoint == FedEndpoint
  29. }
  30. // Client uses the user credentials to create a Cloudflare API client
  31. func (c *User) Client(apiURL string, userAgent string, log *zerolog.Logger) (cfapi.Client, error) {
  32. if apiURL == "" {
  33. return nil, errors.New("An api-url was not provided for the Cloudflare API client")
  34. }
  35. client, err := cfapi.NewRESTClient(
  36. apiURL,
  37. c.cert.AccountID,
  38. c.cert.ZoneID,
  39. c.cert.APIToken,
  40. userAgent,
  41. log,
  42. )
  43. if err != nil {
  44. return nil, err
  45. }
  46. return client, nil
  47. }
  48. // Read will load and read the origin cert.pem to load the user credentials
  49. func Read(originCertPath string, log *zerolog.Logger) (*User, error) {
  50. originCertLog := log.With().
  51. Str(logFieldOriginCertPath, originCertPath).
  52. Logger()
  53. originCertPath, err := FindOriginCert(originCertPath, &originCertLog)
  54. if err != nil {
  55. return nil, errors.Wrap(err, "Error locating origin cert")
  56. }
  57. blocks, err := readOriginCert(originCertPath)
  58. if err != nil {
  59. return nil, errors.Wrapf(err, "Can't read origin cert from %s", originCertPath)
  60. }
  61. cert, err := decodeOriginCert(blocks)
  62. if err != nil {
  63. return nil, errors.Wrap(err, "Error decoding origin cert")
  64. }
  65. if cert.AccountID == "" {
  66. 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)
  67. }
  68. return &User{
  69. cert: cert,
  70. certPath: originCertPath,
  71. }, nil
  72. }