auth_approle.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package vault
  13. import (
  14. "context"
  15. "errors"
  16. "strings"
  17. "github.com/hashicorp/vault/api/auth/approle"
  18. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  19. "github.com/external-secrets/external-secrets/pkg/constants"
  20. "github.com/external-secrets/external-secrets/pkg/metrics"
  21. "github.com/external-secrets/external-secrets/pkg/utils/resolvers"
  22. )
  23. const (
  24. errInvalidAppRoleID = "invalid Auth.AppRole: neither `roleId` nor `roleRef` was supplied"
  25. )
  26. func setAppRoleToken(ctx context.Context, v *client) (bool, error) {
  27. appRole := v.store.Auth.AppRole
  28. if appRole != nil {
  29. err := v.requestTokenWithAppRoleRef(ctx, appRole)
  30. if err != nil {
  31. return true, err
  32. }
  33. return true, nil
  34. }
  35. return false, nil
  36. }
  37. func (c *client) requestTokenWithAppRoleRef(ctx context.Context, appRole *esv1.VaultAppRole) error {
  38. var err error
  39. var roleID string // becomes the RoleID used to authenticate with HashiCorp Vault
  40. // prefer .auth.appRole.roleId, fallback to .auth.appRole.roleRef, give up after that.
  41. if appRole.RoleID != "" { // use roleId from CRD, if configured
  42. roleID = strings.TrimSpace(appRole.RoleID)
  43. } else if appRole.RoleRef != nil { // use RoleID from Secret, if configured
  44. roleID, err = resolvers.SecretKeyRef(ctx, c.kube, c.storeKind, c.namespace, appRole.RoleRef)
  45. if err != nil {
  46. return err
  47. }
  48. } else { // we ran out of ways to get RoleID. return an appropriate error
  49. return errors.New(errInvalidAppRoleID)
  50. }
  51. secretID, err := resolvers.SecretKeyRef(ctx, c.kube, c.storeKind, c.namespace, &appRole.SecretRef)
  52. if err != nil {
  53. return err
  54. }
  55. secret := approle.SecretID{FromString: secretID}
  56. appRoleClient, err := approle.NewAppRoleAuth(roleID, &secret, approle.WithMountPath(appRole.Path))
  57. if err != nil {
  58. return err
  59. }
  60. _, err = c.auth.Login(ctx, appRoleClient)
  61. metrics.ObserveAPICall(constants.ProviderHCVault, constants.CallHCVaultLogin, err)
  62. if err != nil {
  63. return err
  64. }
  65. return nil
  66. }