pushsecret_controller.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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) DeleteSecretFromProviders(newMap, oldMap esapi.SyncedPushSecretsMap) error {
  105. var err error
  106. for store, oldData := range oldMap {
  107. newData, ok := newMap[store]
  108. if !ok {
  109. err = r.DeleteAllSecretsFromStore(store, oldData)
  110. if err != nil {
  111. return err
  112. }
  113. continue
  114. }
  115. for oldEntry, oldRef := range oldData {
  116. _, ok := newData[oldEntry]
  117. if !ok {
  118. err = r.DeleteSecretFromStore(store, oldRef)
  119. if err != nil {
  120. return err
  121. }
  122. }
  123. }
  124. }
  125. return nil
  126. }
  127. func (r *Reconciler) DeleteAllSecretsFromStore(store string, data map[string]esapi.PushSecretData) error {
  128. for _, v := range data {
  129. err := r.DeleteSecretFromStore(store, v)
  130. if err != nil {
  131. return err
  132. }
  133. }
  134. return nil
  135. }
  136. func (r *Reconciler) DeleteSecretFromStore(store string, data esapi.PushSecretData) error {
  137. return nil
  138. }
  139. func (r *Reconciler) PushSecretToProviders(ctx context.Context, stores []v1beta1.GenericStore, ps esapi.PushSecret, secret *v1.Secret) (esapi.SyncedPushSecretsMap, error) {
  140. out := esapi.SyncedPushSecretsMap{}
  141. for _, store := range stores {
  142. out[store.GetName()] = make(map[string]esapi.PushSecretData)
  143. provider, err := v1beta1.GetProvider(store)
  144. if err != nil {
  145. return out, fmt.Errorf(errGetProviderFailed)
  146. }
  147. client, err := provider.NewClient(ctx, store, r.Client, ps.Namespace)
  148. if err != nil {
  149. return out, fmt.Errorf(errGetSecretsClientFailed)
  150. }
  151. defer func() { //nolint
  152. err := client.Close(ctx)
  153. if err != nil {
  154. r.Log.Error(err, errCloseStoreClient)
  155. }
  156. }()
  157. for _, ref := range ps.Spec.Data {
  158. secretValue, ok := secret.Data[ref.Match.SecretKey]
  159. if !ok {
  160. return out, fmt.Errorf("secret key %v does not exist", ref.Match.SecretKey)
  161. }
  162. err := client.SetSecret(ctx, secretValue, ref.Match.RemoteRef)
  163. if err != nil {
  164. return out, fmt.Errorf(errSetSecretFailed, ref.Match.SecretKey, store.GetName(), err)
  165. }
  166. out[store.GetName()][ref.Match.RemoteRef.RemoteKey] = ref
  167. }
  168. }
  169. return out, nil
  170. }
  171. func (r *Reconciler) GetSecret(ctx context.Context, ps esapi.PushSecret) (*v1.Secret, error) {
  172. secretName := types.NamespacedName{Name: ps.Spec.Selector.Secret.Name, Namespace: ps.Namespace}
  173. secret := &v1.Secret{}
  174. err := r.Client.Get(ctx, secretName, secret)
  175. if err != nil {
  176. return nil, err
  177. }
  178. return secret, nil
  179. }
  180. func (r *Reconciler) GetSecretStores(ctx context.Context, ps esapi.PushSecret) ([]v1beta1.GenericStore, error) {
  181. stores := make([]v1beta1.GenericStore, 0)
  182. for _, refStore := range ps.Spec.SecretStoreRefs {
  183. if refStore.LabelSelector != nil {
  184. labelSelector, err := metav1.LabelSelectorAsSelector(refStore.LabelSelector)
  185. if err != nil {
  186. return nil, fmt.Errorf("could not convert labels: %w", err)
  187. }
  188. if refStore.Kind == v1beta1.ClusterSecretStoreKind {
  189. clusterSecretStoreList := v1beta1.ClusterSecretStoreList{}
  190. err = r.List(ctx, &clusterSecretStoreList, &client.ListOptions{LabelSelector: labelSelector})
  191. if err != nil {
  192. return nil, fmt.Errorf("could not list cluster Secret Stores: %w", err)
  193. }
  194. for i := range clusterSecretStoreList.Items {
  195. stores = append(stores, &clusterSecretStoreList.Items[i])
  196. }
  197. } else {
  198. secretStoreList := v1beta1.SecretStoreList{}
  199. err = r.List(ctx, &secretStoreList, &client.ListOptions{LabelSelector: labelSelector})
  200. if err != nil {
  201. return nil, fmt.Errorf("could not list Secret Stores: %w", err)
  202. }
  203. for i := range secretStoreList.Items {
  204. stores = append(stores, &secretStoreList.Items[i])
  205. }
  206. }
  207. }
  208. if refStore.Name != "" {
  209. ref := types.NamespacedName{
  210. Name: refStore.Name,
  211. }
  212. if refStore.Kind == v1beta1.ClusterSecretStoreKind {
  213. var store v1beta1.ClusterSecretStore
  214. err := r.Get(ctx, ref, &store)
  215. if err != nil {
  216. return nil, fmt.Errorf(errGetClusterSecretStore, ref.Name, err)
  217. }
  218. stores = append(stores, &store)
  219. } else {
  220. ref.Namespace = ps.Namespace
  221. var store v1beta1.SecretStore
  222. err := r.Get(ctx, ref, &store)
  223. if err != nil {
  224. return nil, fmt.Errorf(errGetSecretStore, ref.Name, err)
  225. }
  226. stores = append(stores, &store)
  227. }
  228. }
  229. }
  230. return stores, nil
  231. }
  232. func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error {
  233. r.recorder = mgr.GetEventRecorderFor("pushsecret")
  234. return ctrl.NewControllerManagedBy(mgr).
  235. For(&esapi.PushSecret{}).
  236. Complete(r)
  237. }
  238. func NewPushSecretCondition(condType esapi.PushSecretConditionType, status v1.ConditionStatus, reason, message string) *esapi.PushSecretStatusCondition {
  239. return &esapi.PushSecretStatusCondition{
  240. Type: condType,
  241. Status: status,
  242. LastTransitionTime: metav1.Now(),
  243. Reason: reason,
  244. Message: message,
  245. }
  246. }
  247. func SetPushSecretCondition(gs esapi.PushSecret, condition esapi.PushSecretStatusCondition) esapi.PushSecret {
  248. status := gs.Status
  249. currentCond := GetPushSecretCondition(status, condition.Type)
  250. if currentCond != nil && currentCond.Status == condition.Status &&
  251. currentCond.Reason == condition.Reason && currentCond.Message == condition.Message {
  252. return gs
  253. }
  254. // Do not update lastTransitionTime if the status of the condition doesn't change.
  255. if currentCond != nil && currentCond.Status == condition.Status {
  256. condition.LastTransitionTime = currentCond.LastTransitionTime
  257. }
  258. status.Conditions = append(filterOutCondition(status.Conditions, condition.Type), condition)
  259. gs.Status = status
  260. return gs
  261. }
  262. // filterOutCondition returns an empty set of conditions with the provided type.
  263. func filterOutCondition(conditions []esapi.PushSecretStatusCondition, condType esapi.PushSecretConditionType) []esapi.PushSecretStatusCondition {
  264. newConditions := make([]esapi.PushSecretStatusCondition, 0, len(conditions))
  265. for _, c := range conditions {
  266. if c.Type == condType {
  267. continue
  268. }
  269. newConditions = append(newConditions, c)
  270. }
  271. return newConditions
  272. }
  273. // GetSecretStoreCondition returns the condition with the provided type.
  274. func GetPushSecretCondition(status esapi.PushSecretStatus, condType esapi.PushSecretConditionType) *esapi.PushSecretStatusCondition {
  275. for i := range status.Conditions {
  276. c := status.Conditions[i]
  277. if c.Type == condType {
  278. return &c
  279. }
  280. }
  281. return nil
  282. }