accountmanager.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package internal
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "os"
  6. "sync"
  7. )
  8. var (
  9. accounts = make(map[string]Account)
  10. tlsConfigs = make(map[string]*tls.Config)
  11. lock sync.RWMutex
  12. )
  13. // Account holds the username/password for an etcd cluster.
  14. type Account struct {
  15. User string
  16. Pass string
  17. }
  18. // AddAccount adds the username/password for the given etcd cluster.
  19. func AddAccount(endpoints []string, user, pass string) {
  20. lock.Lock()
  21. defer lock.Unlock()
  22. accounts[getClusterKey(endpoints)] = Account{
  23. User: user,
  24. Pass: pass,
  25. }
  26. }
  27. // AddTLS adds the tls cert files for the given etcd cluster.
  28. func AddTLS(endpoints []string, certFile, certKeyFile, caFile string, insecureSkipVerify bool) error {
  29. cert, err := tls.LoadX509KeyPair(certFile, certKeyFile)
  30. if err != nil {
  31. return err
  32. }
  33. caData, err := os.ReadFile(caFile)
  34. if err != nil {
  35. return err
  36. }
  37. pool := x509.NewCertPool()
  38. pool.AppendCertsFromPEM(caData)
  39. lock.Lock()
  40. defer lock.Unlock()
  41. tlsConfigs[getClusterKey(endpoints)] = &tls.Config{
  42. Certificates: []tls.Certificate{cert},
  43. RootCAs: pool,
  44. InsecureSkipVerify: insecureSkipVerify,
  45. }
  46. return nil
  47. }
  48. // GetAccount gets the username/password for the given etcd cluster.
  49. func GetAccount(endpoints []string) (Account, bool) {
  50. lock.RLock()
  51. defer lock.RUnlock()
  52. account, ok := accounts[getClusterKey(endpoints)]
  53. return account, ok
  54. }
  55. // GetTLS gets the tls config for the given etcd cluster.
  56. func GetTLS(endpoints []string) (*tls.Config, bool) {
  57. lock.RLock()
  58. defer lock.RUnlock()
  59. cfg, ok := tlsConfigs[getClusterKey(endpoints)]
  60. return cfg, ok
  61. }