secret_ref.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. Copyright © The ESO Authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package resolvers
  14. import (
  15. "context"
  16. "fmt"
  17. corev1 "k8s.io/api/core/v1"
  18. "k8s.io/apimachinery/pkg/types"
  19. "sigs.k8s.io/controller-runtime/pkg/client"
  20. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  21. esmeta "github.com/external-secrets/external-secrets/apis/meta/v1"
  22. )
  23. const (
  24. // EmptyStoreKind is used to determine if a store is cluster-scoped or not.
  25. // The EmptyStoreKind is not cluster-scoped, hence resources
  26. // cannot be resolved across namespaces.
  27. // TODO: when we implement cluster-scoped generators
  28. // we can remove this and replace it with a interface.
  29. EmptyStoreKind = "EmptyStoreKind"
  30. errGetKubeSecret = "cannot get Kubernetes secret %q from namespace %q: %w"
  31. errSecretKeyFmt = "cannot find secret data for key: %q"
  32. errGetKubeSATokenRequest = "cannot request Kubernetes service account token for service account %q: %w"
  33. )
  34. // SecretKeyRef resolves a metav1.SecretKeySelector and returns the value of the secret it points to.
  35. // A user must pass the namespace of the originating ExternalSecret, as this may differ
  36. // from the namespace defined in the SecretKeySelector.
  37. // This func ensures that only a ClusterSecretStore is able to request secrets across namespaces.
  38. func SecretKeyRef(
  39. ctx context.Context,
  40. c client.Client,
  41. storeKind string,
  42. esNamespace string,
  43. ref *esmeta.SecretKeySelector) (string, error) {
  44. key := types.NamespacedName{
  45. Namespace: esNamespace,
  46. Name: ref.Name,
  47. }
  48. if (storeKind == esv1.ClusterSecretStoreKind) &&
  49. (ref.Namespace != nil) {
  50. key.Namespace = *ref.Namespace
  51. }
  52. secret := &corev1.Secret{}
  53. err := c.Get(ctx, key, secret)
  54. if err != nil {
  55. return "", fmt.Errorf(errGetKubeSecret, ref.Name, key.Namespace, err)
  56. }
  57. val, ok := secret.Data[ref.Key]
  58. if !ok {
  59. return "", fmt.Errorf(errSecretKeyFmt, ref.Key)
  60. }
  61. return string(val), nil
  62. }