common.go 13 KB

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