common.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /*
  2. Copyright © The ESO Authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package secretstore
  14. import (
  15. "context"
  16. "errors"
  17. "fmt"
  18. "time"
  19. "github.com/go-logr/logr"
  20. v1 "k8s.io/api/core/v1"
  21. apierrors "k8s.io/apimachinery/pkg/api/errors"
  22. "k8s.io/apimachinery/pkg/fields"
  23. "k8s.io/apimachinery/pkg/types"
  24. "k8s.io/client-go/tools/record"
  25. ctrl "sigs.k8s.io/controller-runtime"
  26. "sigs.k8s.io/controller-runtime/pkg/client"
  27. "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
  28. ctrlreconcile "sigs.k8s.io/controller-runtime/pkg/reconcile"
  29. esapi "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  30. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  31. "github.com/external-secrets/external-secrets/pkg/controllers/secretstore/metrics"
  32. // Load registered providers.
  33. _ "github.com/external-secrets/external-secrets/pkg/register"
  34. )
  35. const (
  36. errStoreClient = "could not get provider client: %w"
  37. errValidationFailed = "could not validate provider: %w"
  38. errValidationUnknownMsg = "could not determine validation status"
  39. errPatchStatus = "unable to patch status: %w"
  40. errUnableCreateClient = "unable to create client"
  41. errUnableValidateStore = "unable to validate store"
  42. msgStoreValidated = "store validated"
  43. msgStoreNotMaintained = "store isn't currently maintained. Please plan and prepare accordingly."
  44. msgStoreDeprecated = "store is deprecated and will be removed on the next minor release. Please plan and prepare accordingly."
  45. // Finalizer for SecretStores when they have PushSecrets with DeletionPolicy=Delete.
  46. secretStoreFinalizer = "secretstore.externalsecrets.io/finalizer"
  47. )
  48. var errValidationUnknown = errors.New(errValidationUnknownMsg)
  49. // Opts holds the options for the reconcile function.
  50. type Opts struct {
  51. ControllerClass string
  52. GaugeVecGetter metrics.GaugeVevGetter
  53. Recorder record.EventRecorder
  54. RequeueInterval time.Duration
  55. }
  56. func reconcile(ctx context.Context, req ctrl.Request, ss esapi.GenericStore, cl client.Client, isPushSecretEnabled bool, log logr.Logger, opts Opts) (ctrl.Result, error) {
  57. if !ShouldProcessStore(ss, opts.ControllerClass) {
  58. log.V(1).Info("skip store")
  59. return ctrl.Result{}, nil
  60. }
  61. // Manage finalizer if PushSecret feature is enabled.
  62. if isPushSecretEnabled {
  63. finalizersUpdated, err := handleFinalizer(ctx, cl, ss)
  64. if err != nil {
  65. return ctrl.Result{}, err
  66. }
  67. if finalizersUpdated {
  68. log.V(1).Info("updating resource with finalizer changes")
  69. if err := cl.Update(ctx, ss); err != nil {
  70. return ctrl.Result{}, err
  71. }
  72. }
  73. }
  74. requeueInterval := opts.RequeueInterval
  75. if ss.GetSpec().RefreshInterval != 0 {
  76. requeueInterval = time.Second * time.Duration(ss.GetSpec().RefreshInterval)
  77. }
  78. // patch status when done processing
  79. p := client.MergeFrom(ss.Copy())
  80. storeUID := ss.GetObjectMeta().UID
  81. defer func() {
  82. current := ss.Copy()
  83. if getErr := cl.Get(ctx, req.NamespacedName, current); getErr != nil {
  84. if apierrors.IsNotFound(getErr) {
  85. log.V(1).Info("store was deleted, skipping status patch")
  86. return
  87. }
  88. log.Error(getErr, "unable to get store for status patch")
  89. return
  90. }
  91. if current.GetObjectMeta().UID != storeUID {
  92. log.V(1).Info("store was replaced, skipping status patch")
  93. return
  94. }
  95. err := cl.Status().Patch(ctx, ss, p)
  96. if err != nil {
  97. log.Error(err, errPatchStatus)
  98. }
  99. }()
  100. // validateStore modifies the store conditions
  101. // we have to patch the status
  102. log.V(1).Info("validating")
  103. err := validateStore(ctx, req.Namespace, opts.ControllerClass, ss, cl, opts.GaugeVecGetter, opts.Recorder)
  104. if err != nil {
  105. log.Error(err, "unable to validate store")
  106. // in case of validation status unknown, validateStore will mark
  107. // the store as ready but we should show ReasonValidationUnknown
  108. if errors.Is(err, errValidationUnknown) {
  109. return ctrl.Result{RequeueAfter: requeueInterval}, nil
  110. }
  111. return ctrl.Result{}, err
  112. }
  113. storeProvider, err := esapi.GetProvider(ss)
  114. if err != nil {
  115. return ctrl.Result{}, err
  116. }
  117. isMaintained, err := esapi.GetMaintenanceStatus(ss)
  118. if err != nil {
  119. return ctrl.Result{}, err
  120. }
  121. annotations := ss.GetAnnotations()
  122. _, ok := annotations["external-secrets.io/ignore-maintenance-checks"]
  123. if !ok {
  124. switch isMaintained {
  125. case esapi.MaintenanceStatusNotMaintained:
  126. opts.Recorder.Event(ss, v1.EventTypeWarning, esapi.StoreUnmaintained, msgStoreNotMaintained)
  127. case esapi.MaintenanceStatusDeprecated:
  128. opts.Recorder.Event(ss, v1.EventTypeWarning, esapi.StoreDeprecated, msgStoreDeprecated)
  129. case esapi.MaintenanceStatusMaintained:
  130. default:
  131. // no warnings
  132. }
  133. }
  134. capStatus := esapi.SecretStoreStatus{
  135. Capabilities: storeProvider.Capabilities(),
  136. Conditions: ss.GetStatus().Conditions,
  137. }
  138. ss.SetStatus(capStatus)
  139. opts.Recorder.Event(ss, v1.EventTypeNormal, esapi.ReasonStoreValid, msgStoreValidated)
  140. cond := NewSecretStoreCondition(esapi.SecretStoreReady, v1.ConditionTrue, esapi.ReasonStoreValid, msgStoreValidated)
  141. SetExternalSecretCondition(ss, *cond, opts.GaugeVecGetter)
  142. return ctrl.Result{
  143. RequeueAfter: requeueInterval,
  144. }, err
  145. }
  146. // validateStore tries to construct a new client
  147. // if it fails sets a condition and writes events.
  148. func validateStore(ctx context.Context, namespace, controllerClass string, store esapi.GenericStore,
  149. client client.Client, gaugeVecGetter metrics.GaugeVevGetter, recorder record.EventRecorder) error {
  150. mgr := NewManager(client, controllerClass, false)
  151. defer func() {
  152. _ = mgr.Close(ctx)
  153. }()
  154. cl, err := mgr.GetFromStore(ctx, store, namespace)
  155. if err != nil {
  156. cond := NewSecretStoreCondition(esapi.SecretStoreReady, v1.ConditionFalse, esapi.ReasonInvalidProviderConfig, errUnableCreateClient)
  157. SetExternalSecretCondition(store, *cond, gaugeVecGetter)
  158. recorder.Event(store, v1.EventTypeWarning, esapi.ReasonInvalidProviderConfig, err.Error())
  159. return fmt.Errorf(errStoreClient, err)
  160. }
  161. validationResult, err := cl.Validate()
  162. if err != nil {
  163. if validationResult == esapi.ValidationResultUnknown {
  164. cond := NewSecretStoreCondition(esapi.SecretStoreReady, v1.ConditionTrue, esapi.ReasonValidationUnknown, errValidationUnknownMsg)
  165. SetExternalSecretCondition(store, *cond, gaugeVecGetter)
  166. recorder.Event(store, v1.EventTypeWarning, esapi.ReasonValidationUnknown, err.Error())
  167. return errValidationUnknown
  168. }
  169. cond := NewSecretStoreCondition(esapi.SecretStoreReady, v1.ConditionFalse, esapi.ReasonInvalidProviderConfig, errUnableValidateStore)
  170. SetExternalSecretCondition(store, *cond, gaugeVecGetter)
  171. recorder.Event(store, v1.EventTypeWarning, esapi.ReasonInvalidProviderConfig, err.Error())
  172. return fmt.Errorf(errValidationFailed, err)
  173. }
  174. return nil
  175. }
  176. // ShouldProcessStore returns true if the store should be processed.
  177. func ShouldProcessStore(store esapi.GenericStore, class string) bool {
  178. if store == nil || store.GetSpec().Controller == "" || store.GetSpec().Controller == class {
  179. return true
  180. }
  181. return false
  182. }
  183. // handleFinalizer manages the finalizer for ClusterSecretStores and SecretStores.
  184. func handleFinalizer(ctx context.Context, cl client.Client, store esapi.GenericStore) (finalizersUpdated bool, err error) {
  185. log := logr.FromContextOrDiscard(ctx)
  186. hasPushSecretsWithDeletePolicy, err := hasPushSecretsWithDeletePolicy(ctx, cl, store)
  187. if err != nil {
  188. return false, fmt.Errorf("failed to check PushSecrets: %w", err)
  189. }
  190. storeKind := store.GetKind()
  191. // If the store is being deleted and has the finalizer, check if we can remove it
  192. if !store.GetObjectMeta().DeletionTimestamp.IsZero() {
  193. if hasPushSecretsWithDeletePolicy {
  194. log.Info("cannot remove finalizer, there are still PushSecrets with DeletionPolicy=Delete that reference this store")
  195. return false, nil
  196. }
  197. if controllerutil.RemoveFinalizer(store, secretStoreFinalizer) {
  198. log.Info(fmt.Sprintf("removed finalizer from %s during deletion", storeKind))
  199. return true, nil
  200. }
  201. return false, nil
  202. }
  203. // If the store is not being deleted, manage the finalizer based on PushSecrets
  204. if hasPushSecretsWithDeletePolicy {
  205. if controllerutil.AddFinalizer(store, secretStoreFinalizer) {
  206. log.Info(fmt.Sprintf("added finalizer to %s due to PushSecrets with DeletionPolicy=Delete", storeKind))
  207. return true, nil
  208. }
  209. } else {
  210. if controllerutil.RemoveFinalizer(store, secretStoreFinalizer) {
  211. log.Info(fmt.Sprintf("removed finalizer from %s, no more PushSecrets with DeletionPolicy=Delete", storeKind))
  212. return true, nil
  213. }
  214. }
  215. return false, nil
  216. }
  217. // hasPushSecretsWithDeletePolicy checks if there are any PushSecrets with DeletionPolicy=Delete
  218. // that reference this SecretStore using the controller-runtime index.
  219. func hasPushSecretsWithDeletePolicy(ctx context.Context, cl client.Client, store esapi.GenericStore) (bool, error) {
  220. // Search for PushSecrets that have already synced from this store.
  221. found, err := hasSyncedPushSecrets(ctx, cl, store)
  222. if err != nil {
  223. return false, fmt.Errorf("failed to check for synced push secrets: %w", err)
  224. }
  225. if found {
  226. return true, nil
  227. }
  228. // Search for PushSecrets that reference this store, but may not have synced yet.
  229. found, err = hasUnsyncedPushSecretRefs(ctx, cl, store)
  230. if err != nil {
  231. return false, fmt.Errorf("failed to check for unsynced push secret refs: %w", err)
  232. }
  233. return found, nil
  234. }
  235. // hasSyncedPushSecrets uses the 'status.syncedPushSecrets' index from PushSecrets to efficiently find
  236. // PushSecrets with DeletionPolicy=Delete that have already been synced from the given store.
  237. func hasSyncedPushSecrets(ctx context.Context, cl client.Client, store esapi.GenericStore) (bool, error) {
  238. storeKey := fmt.Sprintf("%s/%s", store.GetKind(), store.GetName())
  239. opts := &client.ListOptions{
  240. FieldSelector: fields.OneTermEqualSelector("status.syncedPushSecrets", storeKey),
  241. }
  242. if store.GetKind() == esapi.SecretStoreKind {
  243. opts.Namespace = store.GetNamespace()
  244. }
  245. var pushSecretList esv1alpha1.PushSecretList
  246. if err := cl.List(ctx, &pushSecretList, opts); err != nil {
  247. return false, err
  248. }
  249. // If any PushSecrets are found, return true. The index ensures they have DeletionPolicy=Delete.
  250. return len(pushSecretList.Items) > 0, nil
  251. }
  252. // hasUnsyncedPushSecretRefs searches for all PushSecrets with DeletionPolicy=Delete
  253. // and checks if any of them reference the given store (by name or labelSelector).
  254. // This is necessary for cases where the reference exists, but synchronization has not occurred yet.
  255. func hasUnsyncedPushSecretRefs(ctx context.Context, cl client.Client, store esapi.GenericStore) (bool, error) {
  256. opts := &client.ListOptions{
  257. FieldSelector: fields.OneTermEqualSelector("spec.deletionPolicy", string(esv1alpha1.PushSecretDeletionPolicyDelete)),
  258. }
  259. if store.GetKind() == esapi.SecretStoreKind {
  260. opts.Namespace = store.GetNamespace()
  261. }
  262. var pushSecretList esv1alpha1.PushSecretList
  263. if err := cl.List(ctx, &pushSecretList, opts); err != nil {
  264. return false, err
  265. }
  266. for _, ps := range pushSecretList.Items {
  267. for _, storeRef := range ps.Spec.SecretStoreRefs {
  268. if storeMatchesRef(store, storeRef) {
  269. return true, nil
  270. }
  271. }
  272. }
  273. return false, nil
  274. }
  275. // findStoresForPushSecret finds SecretStores or ClusterSecretStores that should be reconciled when a PushSecret changes.
  276. func findStoresForPushSecret(ctx context.Context, c client.Client, obj client.Object, storeList client.ObjectList) []ctrlreconcile.Request {
  277. ps, ok := obj.(*esv1alpha1.PushSecret)
  278. if !ok {
  279. return nil
  280. }
  281. var isClusterScoped bool
  282. switch storeList.(type) {
  283. case *esapi.ClusterSecretStoreList:
  284. isClusterScoped = true
  285. case *esapi.SecretStoreList:
  286. isClusterScoped = false
  287. default:
  288. return nil
  289. }
  290. listOpts := make([]client.ListOption, 0)
  291. if !isClusterScoped {
  292. listOpts = append(listOpts, client.InNamespace(ps.GetNamespace()))
  293. }
  294. if err := c.List(ctx, storeList, listOpts...); err != nil {
  295. return nil
  296. }
  297. requests := make([]ctrlreconcile.Request, 0)
  298. var stores []esapi.GenericStore
  299. switch sl := storeList.(type) {
  300. case *esapi.SecretStoreList:
  301. for i := range sl.Items {
  302. stores = append(stores, &sl.Items[i])
  303. }
  304. case *esapi.ClusterSecretStoreList:
  305. for i := range sl.Items {
  306. stores = append(stores, &sl.Items[i])
  307. }
  308. }
  309. for _, store := range stores {
  310. if shouldReconcileSecretStoreForPushSecret(store, ps) {
  311. req := ctrlreconcile.Request{
  312. NamespacedName: types.NamespacedName{
  313. Name: store.GetName(),
  314. },
  315. }
  316. if !isClusterScoped {
  317. req.NamespacedName.Namespace = store.GetNamespace()
  318. }
  319. requests = append(requests, req)
  320. }
  321. }
  322. return requests
  323. }