pushsecret_controller.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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 pushsecret
  13. import (
  14. "context"
  15. "fmt"
  16. "time"
  17. "github.com/go-logr/logr"
  18. v1 "k8s.io/api/core/v1"
  19. apierrors "k8s.io/apimachinery/pkg/api/errors"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/runtime"
  22. "k8s.io/apimachinery/pkg/types"
  23. "k8s.io/client-go/tools/record"
  24. ctrl "sigs.k8s.io/controller-runtime"
  25. "sigs.k8s.io/controller-runtime/pkg/client"
  26. esapi "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  27. v1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  28. )
  29. const (
  30. errFailedGetSecret = "could not get source secret"
  31. errPatchStatus = "error merging"
  32. errGetSecretStore = "could not get SecretStore %q, %w"
  33. errGetClusterSecretStore = "could not get ClusterSecretStore %q, %w"
  34. errGetProviderFailed = "could not start provider"
  35. errGetSecretsClientFailed = "could not start secrets client"
  36. errCloseStoreClient = "error when calling provider close method"
  37. errSetSecretFailed = "could not write remote ref %v to target secretstore %v: %v"
  38. errFailedSetSecret = "set secret failed: %v"
  39. )
  40. type Reconciler struct {
  41. client.Client
  42. Log logr.Logger
  43. Scheme *runtime.Scheme
  44. recorder record.EventRecorder
  45. RequeueInterval time.Duration
  46. ControllerClass string
  47. }
  48. func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
  49. log := r.Log.WithValues("pushsecret", req.NamespacedName)
  50. var ps esapi.PushSecret
  51. err := r.Get(ctx, req.NamespacedName, &ps)
  52. if apierrors.IsNotFound(err) {
  53. return ctrl.Result{}, nil
  54. } else if err != nil {
  55. msg := "unable to get PushSecret"
  56. r.recorder.Event(&ps, v1.EventTypeWarning, esapi.ReasonErrored, msg)
  57. log.Error(err, msg)
  58. return ctrl.Result{}, fmt.Errorf("get resource: %w", err)
  59. }
  60. refreshInt := r.RequeueInterval
  61. if ps.Spec.RefreshInterval != nil {
  62. refreshInt = ps.Spec.RefreshInterval.Duration
  63. }
  64. p := client.MergeFrom(ps.DeepCopy())
  65. defer func() {
  66. err := r.Client.Status().Patch(ctx, &ps, p)
  67. if err != nil {
  68. log.Error(err, errPatchStatus)
  69. }
  70. }()
  71. secret, err := r.GetSecret(ctx, ps)
  72. if err != nil {
  73. cond := NewPushSecretCondition(esapi.PushSecretReady, v1.ConditionFalse, esapi.ReasonErrored, errFailedGetSecret)
  74. ps = SetPushSecretCondition(ps, *cond)
  75. r.recorder.Event(&ps, v1.EventTypeWarning, esapi.ReasonErrored, errFailedGetSecret)
  76. return ctrl.Result{}, err
  77. }
  78. secretStores, err := r.GetSecretStores(ctx, ps)
  79. if err != nil {
  80. cond := NewPushSecretCondition(esapi.PushSecretReady, v1.ConditionFalse, esapi.ReasonErrored, err.Error())
  81. ps = SetPushSecretCondition(ps, *cond)
  82. r.recorder.Event(&ps, v1.EventTypeWarning, esapi.ReasonErrored, err.Error())
  83. return ctrl.Result{}, err
  84. }
  85. syncedSecrets, err := r.PushSecretToProviders(ctx, secretStores, ps, secret)
  86. if err != nil {
  87. msg := fmt.Sprintf(errFailedSetSecret, err)
  88. cond := NewPushSecretCondition(esapi.PushSecretReady, v1.ConditionFalse, esapi.ReasonErrored, msg)
  89. ps = SetPushSecretCondition(ps, *cond)
  90. r.SetSyncedSecrets(&ps, syncedSecrets)
  91. r.recorder.Event(&ps, v1.EventTypeWarning, esapi.ReasonErrored, msg)
  92. return ctrl.Result{}, err
  93. }
  94. msg := "PushSecret synced successfully"
  95. cond := NewPushSecretCondition(esapi.PushSecretReady, v1.ConditionTrue, esapi.ReasonSynced, msg)
  96. ps = SetPushSecretCondition(ps, *cond)
  97. r.SetSyncedSecrets(&ps, syncedSecrets)
  98. r.recorder.Event(&ps, v1.EventTypeNormal, esapi.ReasonSynced, msg)
  99. return ctrl.Result{RequeueAfter: refreshInt}, nil
  100. }
  101. func (r *Reconciler) SetSyncedSecrets(ps *esapi.PushSecret, status esapi.SyncedPushSecretsMap) {
  102. ps.Status.SyncedPushSecrets = status
  103. }
  104. func (r *Reconciler) PushSecretToProviders(ctx context.Context, stores []v1beta1.GenericStore, ps esapi.PushSecret, secret *v1.Secret) (esapi.SyncedPushSecretsMap, error) {
  105. // TODO - Delete Secrets from Stores if they no longer exist in spec but still exist in status
  106. out := esapi.SyncedPushSecretsMap{}
  107. for _, store := range stores {
  108. out[store.GetName()] = make([]esapi.PushSecretData, 0)
  109. provider, err := v1beta1.GetProvider(store)
  110. if err != nil {
  111. return out, fmt.Errorf(errGetProviderFailed)
  112. }
  113. client, err := provider.NewClient(ctx, store, r.Client, ps.Namespace)
  114. if err != nil {
  115. return out, fmt.Errorf(errGetSecretsClientFailed)
  116. }
  117. defer func() { //nolint
  118. err := client.Close(ctx)
  119. if err != nil {
  120. r.Log.Error(err, errCloseStoreClient)
  121. }
  122. }()
  123. for _, ref := range ps.Spec.Data {
  124. secretValue, ok := secret.Data[ref.Match.SecretKey]
  125. if !ok {
  126. return out, fmt.Errorf("secret key %v does not exist", ref.Match.SecretKey)
  127. }
  128. err := client.SetSecret(ctx, secretValue, ref.Match.RemoteRef)
  129. if err != nil {
  130. return out, fmt.Errorf(errSetSecretFailed, ref.Match.SecretKey, store.GetName(), err)
  131. }
  132. out[store.GetName()] = append(out[store.GetName()], ref)
  133. }
  134. // TODO - for ref in Status.Synced[store], ref not belonging to ps.Spec.Data, remove ref from provider.
  135. }
  136. return out, nil
  137. }
  138. func (r *Reconciler) GetSecret(ctx context.Context, ps esapi.PushSecret) (*v1.Secret, error) {
  139. secretName := types.NamespacedName{Name: ps.Spec.Selector.Secret.Name, Namespace: ps.Namespace}
  140. secret := &v1.Secret{}
  141. err := r.Client.Get(ctx, secretName, secret)
  142. if err != nil {
  143. return nil, err
  144. }
  145. return secret, nil
  146. }
  147. func (r *Reconciler) GetSecretStores(ctx context.Context, ps esapi.PushSecret) ([]v1beta1.GenericStore, error) {
  148. stores := make([]v1beta1.GenericStore, 0)
  149. for _, refStore := range ps.Spec.SecretStoreRefs {
  150. if refStore.LabelSelector != nil {
  151. labelSelector, err := metav1.LabelSelectorAsSelector(refStore.LabelSelector)
  152. if err != nil {
  153. return nil, fmt.Errorf("could not convert labels: %w", err)
  154. }
  155. if refStore.Kind == v1beta1.ClusterSecretStoreKind {
  156. clusterSecretStoreList := v1beta1.ClusterSecretStoreList{}
  157. err = r.List(ctx, &clusterSecretStoreList, &client.ListOptions{LabelSelector: labelSelector})
  158. if err != nil {
  159. return nil, fmt.Errorf("could not list cluster Secret Stores: %w", err)
  160. }
  161. for i := range clusterSecretStoreList.Items {
  162. stores = append(stores, &clusterSecretStoreList.Items[i])
  163. }
  164. } else {
  165. secretStoreList := v1beta1.SecretStoreList{}
  166. err = r.List(ctx, &secretStoreList, &client.ListOptions{LabelSelector: labelSelector})
  167. if err != nil {
  168. return nil, fmt.Errorf("could not list Secret Stores: %w", err)
  169. }
  170. for i := range secretStoreList.Items {
  171. stores = append(stores, &secretStoreList.Items[i])
  172. }
  173. }
  174. }
  175. if refStore.Name != "" {
  176. ref := types.NamespacedName{
  177. Name: refStore.Name,
  178. }
  179. if refStore.Kind == v1beta1.ClusterSecretStoreKind {
  180. var store v1beta1.ClusterSecretStore
  181. err := r.Get(ctx, ref, &store)
  182. if err != nil {
  183. return nil, fmt.Errorf(errGetClusterSecretStore, ref.Name, err)
  184. }
  185. stores = append(stores, &store)
  186. } else {
  187. ref.Namespace = ps.Namespace
  188. var store v1beta1.SecretStore
  189. err := r.Get(ctx, ref, &store)
  190. if err != nil {
  191. return nil, fmt.Errorf(errGetSecretStore, ref.Name, err)
  192. }
  193. stores = append(stores, &store)
  194. }
  195. }
  196. }
  197. return stores, nil
  198. }
  199. func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error {
  200. r.recorder = mgr.GetEventRecorderFor("pushsecret")
  201. return ctrl.NewControllerManagedBy(mgr).
  202. For(&esapi.PushSecret{}).
  203. Complete(r)
  204. }
  205. func NewPushSecretCondition(condType esapi.PushSecretConditionType, status v1.ConditionStatus, reason, message string) *esapi.PushSecretStatusCondition {
  206. return &esapi.PushSecretStatusCondition{
  207. Type: condType,
  208. Status: status,
  209. LastTransitionTime: metav1.Now(),
  210. Reason: reason,
  211. Message: message,
  212. }
  213. }
  214. func SetPushSecretCondition(gs esapi.PushSecret, condition esapi.PushSecretStatusCondition) esapi.PushSecret {
  215. status := gs.Status
  216. currentCond := GetPushSecretCondition(status, condition.Type)
  217. if currentCond != nil && currentCond.Status == condition.Status &&
  218. currentCond.Reason == condition.Reason && currentCond.Message == condition.Message {
  219. return gs
  220. }
  221. // Do not update lastTransitionTime if the status of the condition doesn't change.
  222. if currentCond != nil && currentCond.Status == condition.Status {
  223. condition.LastTransitionTime = currentCond.LastTransitionTime
  224. }
  225. status.Conditions = append(filterOutCondition(status.Conditions, condition.Type), condition)
  226. gs.Status = status
  227. return gs
  228. }
  229. // filterOutCondition returns an empty set of conditions with the provided type.
  230. func filterOutCondition(conditions []esapi.PushSecretStatusCondition, condType esapi.PushSecretConditionType) []esapi.PushSecretStatusCondition {
  231. newConditions := make([]esapi.PushSecretStatusCondition, 0, len(conditions))
  232. for _, c := range conditions {
  233. if c.Type == condType {
  234. continue
  235. }
  236. newConditions = append(newConditions, c)
  237. }
  238. return newConditions
  239. }
  240. // GetSecretStoreCondition returns the condition with the provided type.
  241. func GetPushSecretCondition(status esapi.PushSecretStatus, condType esapi.PushSecretConditionType) *esapi.PushSecretStatusCondition {
  242. for i := range status.Conditions {
  243. c := status.Conditions[i]
  244. if c.Type == condType {
  245. return &c
  246. }
  247. }
  248. return nil
  249. }