common.go 13 KB

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