approle.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package approle
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/hashicorp/vault/api/auth/approle"
  7. )
  8. // AuthOptions defines the configuration options added using the
  9. // VaultOptions.AuthOptions field when AuthType is approle
  10. type AuthOptions struct {
  11. RoleID string `json:"roleID,omitempty"`
  12. SecretID string `json:"secretID,omitempty"`
  13. SecretIDFile string `json:"secretIDFile,omitempty"`
  14. SecretIDEnv string `json:"secretIDEnv,omitempty"`
  15. IsWrappingToken bool `json:"isWrappingToken,omitempty"`
  16. }
  17. func NewApproleAuthMethod(mountPath string, options json.RawMessage) (*approle.AppRoleAuth, error) {
  18. var opts *AuthOptions
  19. err := json.Unmarshal(options, &opts)
  20. if err != nil {
  21. return nil, fmt.Errorf("error decoding AppRole auth options: %w", err)
  22. }
  23. var approleAuth *approle.AppRoleAuth
  24. var loginOptions []approle.LoginOption
  25. if mountPath != "" {
  26. loginOptions = append(loginOptions, approle.WithMountPath(mountPath))
  27. }
  28. if opts.IsWrappingToken {
  29. loginOptions = append(loginOptions, approle.WithWrappingToken())
  30. }
  31. if opts.RoleID == "" {
  32. return nil, errors.New("you must set roleID")
  33. }
  34. var sid approle.SecretID
  35. switch {
  36. case opts.SecretID != "" && opts.SecretIDFile == "" && opts.SecretIDEnv == "":
  37. sid = approle.SecretID{
  38. FromString: opts.SecretID,
  39. }
  40. case opts.SecretIDFile != "" && opts.SecretID == "" && opts.SecretIDEnv == "":
  41. sid = approle.SecretID{
  42. FromFile: opts.SecretIDFile,
  43. }
  44. case opts.SecretIDEnv != "" && opts.SecretIDFile == "" && opts.SecretID == "":
  45. sid = approle.SecretID{
  46. FromEnv: opts.SecretIDEnv,
  47. }
  48. default:
  49. return nil, errors.New("you must set one of secretID, secretIDFile or secretIDEnv")
  50. }
  51. approleAuth, err = approle.NewAppRoleAuth(opts.RoleID, &sid, loginOptions...)
  52. if err != nil {
  53. return nil, fmt.Errorf("unable to initialize Kubernetes auth method: %w", err)
  54. }
  55. return approleAuth, nil
  56. }