common.go 12 KB

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