pushsecret_controller.go 7.8 KB

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