pushsecret_controller.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. err = r.SetSecretToProviders(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.recorder.Event(&ps, v1.EventTypeWarning, esapi.ReasonErrored, msg)
  91. return ctrl.Result{}, err
  92. }
  93. msg := "PushSecret synced successfully"
  94. cond := NewPushSecretCondition(esapi.PushSecretReady, v1.ConditionTrue, esapi.ReasonSynced, msg)
  95. ps = SetPushSecretCondition(ps, *cond)
  96. // Set status for PushSecret
  97. r.recorder.Event(&ps, v1.EventTypeNormal, esapi.ReasonSynced, msg)
  98. if refreshInt == 0 {
  99. return ctrl.Result{
  100. RequeueAfter: 0,
  101. Requeue: false,
  102. }, nil
  103. }
  104. return ctrl.Result{RequeueAfter: refreshInt}, nil
  105. }
  106. func (r *Reconciler) SetSecretToProviders(ctx context.Context, stores []v1beta1.GenericStore, ps esapi.PushSecret, secret *v1.Secret) error {
  107. for _, store := range stores {
  108. provider, err := v1beta1.GetProvider(store)
  109. if err != nil {
  110. return fmt.Errorf(errGetProviderFailed)
  111. }
  112. client, err := provider.NewClient(ctx, store, r.Client, ps.Namespace)
  113. if err != nil {
  114. return fmt.Errorf(errGetSecretsClientFailed)
  115. }
  116. defer func() {
  117. err := client.Close(ctx)
  118. if err != nil {
  119. r.Log.Error(err, errCloseStoreClient)
  120. }
  121. }()
  122. for _, ref := range ps.Spec.Data {
  123. for _, match := range ref.Match {
  124. secretValue, ok := secret.Data[match.SecretKey]
  125. if !ok {
  126. return fmt.Errorf("secret key %v does not exist", match.SecretKey)
  127. }
  128. for _, rK := range match.RemoteRefs {
  129. err := client.SetSecret(ctx, secretValue, rK)
  130. if err != nil {
  131. return fmt.Errorf(errSetSecretFailed, match.SecretKey, store.GetName(), err)
  132. }
  133. }
  134. }
  135. }
  136. }
  137. return nil
  138. }
  139. func (r *Reconciler) GetSecret(ctx context.Context, ps esapi.PushSecret) (*v1.Secret, error) {
  140. secretName := types.NamespacedName{Name: ps.Spec.Selector.Secret.Name, Namespace: ps.Namespace}
  141. secret := &v1.Secret{}
  142. err := r.Client.Get(ctx, secretName, secret)
  143. if err != nil {
  144. return nil, err
  145. }
  146. return secret, nil
  147. }
  148. func (r *Reconciler) GetSecretStores(ctx context.Context, ps esapi.PushSecret) ([]v1beta1.GenericStore, error) {
  149. stores := make([]v1beta1.GenericStore, 0)
  150. for _, refStore := range ps.Spec.SecretStoreRefs {
  151. ref := types.NamespacedName{
  152. Name: refStore.Name,
  153. }
  154. if refStore.Kind == v1beta1.ClusterSecretStoreKind {
  155. var store v1beta1.ClusterSecretStore
  156. err := r.Get(ctx, ref, &store)
  157. if err != nil {
  158. return nil, fmt.Errorf(errGetClusterSecretStore, ref.Name, err)
  159. }
  160. stores = append(stores, &store)
  161. } else {
  162. ref.Namespace = ps.Namespace
  163. var store v1beta1.SecretStore
  164. err := r.Get(ctx, ref, &store)
  165. if err != nil {
  166. return nil, fmt.Errorf(errGetSecretStore, ref.Name, err)
  167. }
  168. stores = append(stores, &store)
  169. }
  170. }
  171. return stores, nil
  172. }
  173. func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error {
  174. r.recorder = mgr.GetEventRecorderFor("pushsecret")
  175. return ctrl.NewControllerManagedBy(mgr).
  176. For(&esapi.PushSecret{}).
  177. Complete(r)
  178. }
  179. func NewPushSecretCondition(condType esapi.PushSecretConditionType, status v1.ConditionStatus, reason, message string) *esapi.PushSecretStatusCondition {
  180. return &esapi.PushSecretStatusCondition{
  181. Type: condType,
  182. Status: status,
  183. LastTransitionTime: metav1.Now(),
  184. Reason: reason,
  185. Message: message,
  186. }
  187. }
  188. func SetPushSecretCondition(gs esapi.PushSecret, condition esapi.PushSecretStatusCondition) esapi.PushSecret {
  189. status := gs.Status
  190. currentCond := GetPushSecretCondition(status, condition.Type)
  191. if currentCond != nil && currentCond.Status == condition.Status &&
  192. currentCond.Reason == condition.Reason && currentCond.Message == condition.Message {
  193. return gs
  194. }
  195. // Do not update lastTransitionTime if the status of the condition doesn't change.
  196. if currentCond != nil && currentCond.Status == condition.Status {
  197. condition.LastTransitionTime = currentCond.LastTransitionTime
  198. }
  199. status.Conditions = append(filterOutCondition(status.Conditions, condition.Type), condition)
  200. gs.Status = status
  201. return gs
  202. }
  203. // filterOutCondition returns an empty set of conditions with the provided type.
  204. func filterOutCondition(conditions []esapi.PushSecretStatusCondition, condType esapi.PushSecretConditionType) []esapi.PushSecretStatusCondition {
  205. newConditions := make([]esapi.PushSecretStatusCondition, 0, len(conditions))
  206. for _, c := range conditions {
  207. if c.Type == condType {
  208. continue
  209. }
  210. newConditions = append(newConditions, c)
  211. }
  212. return newConditions
  213. }
  214. // GetSecretStoreCondition returns the condition with the provided type.
  215. func GetPushSecretCondition(status esapi.PushSecretStatus, condType esapi.PushSecretConditionType) *esapi.PushSecretStatusCondition {
  216. for i := range status.Conditions {
  217. c := status.Conditions[i]
  218. if c.Type == condType {
  219. return &c
  220. }
  221. }
  222. return nil
  223. }