common.go 12 KB

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