secret_ref.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 resolvers
  13. import (
  14. "context"
  15. "fmt"
  16. corev1 "k8s.io/api/core/v1"
  17. "k8s.io/apimachinery/pkg/types"
  18. "sigs.k8s.io/controller-runtime/pkg/client"
  19. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  20. esmeta "github.com/external-secrets/external-secrets/apis/meta/v1"
  21. )
  22. const (
  23. // This is used to determine if a store is cluster-scoped or not.
  24. // The EmptyStoreKind is not cluster-scoped, hence resources
  25. // cannot be resolved across namespaces.
  26. // TODO: when we implement cluster-scoped generators
  27. // we can remove this and replace it with a interface.
  28. EmptyStoreKind = "EmptyStoreKind"
  29. errGetKubeSecret = "cannot get Kubernetes secret %q from namespace %q: %w"
  30. errSecretKeyFmt = "cannot find secret data for key: %q"
  31. errGetKubeSATokenRequest = "cannot request Kubernetes service account token for service account %q: %w"
  32. )
  33. // SecretKeyRef resolves a metav1.SecretKeySelector and returns the value of the secret it points to.
  34. // A user must pass the namespace of the originating ExternalSecret, as this may differ
  35. // from the namespace defined in the SecretKeySelector.
  36. // This func ensures that only a ClusterSecretStore is able to request secrets across namespaces.
  37. func SecretKeyRef(
  38. ctx context.Context,
  39. c client.Client,
  40. storeKind string,
  41. esNamespace string,
  42. ref *esmeta.SecretKeySelector) (string, error) {
  43. key := types.NamespacedName{
  44. Namespace: esNamespace,
  45. Name: ref.Name,
  46. }
  47. if (storeKind == esv1beta1.ClusterSecretStoreKind) &&
  48. (ref.Namespace != nil) {
  49. key.Namespace = *ref.Namespace
  50. }
  51. secret := &corev1.Secret{}
  52. err := c.Get(ctx, key, secret)
  53. if err != nil {
  54. return "", fmt.Errorf(errGetKubeSecret, ref.Name, key.Namespace, err)
  55. }
  56. val, ok := secret.Data[ref.Key]
  57. if !ok {
  58. return "", fmt.Errorf(errSecretKeyFmt, ref.Key)
  59. }
  60. return string(val), nil
  61. }