manager.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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 clientmanager provides a Manager for provider clients
  14. package clientmanager
  15. import (
  16. "context"
  17. "errors"
  18. "fmt"
  19. "regexp"
  20. "strings"
  21. "sync"
  22. "sync/atomic"
  23. "github.com/go-logr/logr"
  24. v1 "k8s.io/api/core/v1"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/apimachinery/pkg/labels"
  27. "k8s.io/apimachinery/pkg/types"
  28. ctrl "sigs.k8s.io/controller-runtime"
  29. "sigs.k8s.io/controller-runtime/pkg/client"
  30. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  31. pb "github.com/external-secrets/external-secrets/proto/provider"
  32. adapterstore "github.com/external-secrets/external-secrets/providers/v2/adapter/store"
  33. "github.com/external-secrets/external-secrets/providers/v2/common/grpc"
  34. )
  35. const (
  36. errGetClusterSecretStore = "could not get ClusterSecretStore %q, %w"
  37. errGetSecretStore = "could not get SecretStore %q, %w"
  38. errSecretStoreNotReady = "%s %q is not ready"
  39. errClusterStoreMismatch = "using cluster store %q is not allowed from namespace %q: denied by spec.condition"
  40. errClusterProviderDenied = "using ClusterProvider %q is not allowed from namespace %q: denied by spec.conditions"
  41. errV2ProvidersDisabled = "v2 provider support is disabled, refusing %s %q (enable with --enable-v2-providers)"
  42. )
  43. var (
  44. // globalV2ConnectionPool is a singleton connection pool for v2 gRPC providers.
  45. // It persists across all reconciles and Manager instances to enable connection reuse.
  46. // Initialized once on first use and shared globally.
  47. globalV2ConnectionPool *grpc.ConnectionPool
  48. globalV2ConnectionPoolOnce sync.Once
  49. globalV2ConnectionPoolLog logr.Logger
  50. v2ProvidersEnabled atomic.Bool
  51. )
  52. // SetV2ProvidersEnabled toggles support for experimental v2 Provider and ClusterProvider references.
  53. func SetV2ProvidersEnabled(enabled bool) {
  54. v2ProvidersEnabled.Store(enabled)
  55. }
  56. // V2ProvidersEnabled reports whether v2 Provider and ClusterProvider references are allowed.
  57. func V2ProvidersEnabled() bool {
  58. return v2ProvidersEnabled.Load()
  59. }
  60. // initGlobalV2ConnectionPool initializes the global connection pool for v2 providers.
  61. // This is called once on first use via sync.Once.
  62. func initGlobalV2ConnectionPool() {
  63. globalV2ConnectionPoolLog = ctrl.Log.WithName("v2-connection-pool")
  64. poolConfig := grpc.DefaultPoolConfig()
  65. globalV2ConnectionPool = grpc.NewConnectionPool(poolConfig)
  66. globalV2ConnectionPoolLog.Info("global v2 connection pool initialized",
  67. "maxIdleTime", poolConfig.MaxIdleTime.String(),
  68. "maxLifetime", poolConfig.MaxLifetime.String(),
  69. "healthCheckInterval", poolConfig.HealthCheckInterval.String())
  70. }
  71. // getGlobalV2ConnectionPool returns the global connection pool, initializing it if needed.
  72. func getGlobalV2ConnectionPool() *grpc.ConnectionPool {
  73. globalV2ConnectionPoolOnce.Do(initGlobalV2ConnectionPool)
  74. return globalV2ConnectionPool
  75. }
  76. // v2PooledConnection tracks connection info needed to release connections back to the pool.
  77. type v2PooledConnection struct {
  78. address string
  79. tlsConfig *grpc.TLSConfig
  80. }
  81. // Manager stores instances of provider clients
  82. // At any given time we must have no more than one instance
  83. // of a client (due to limitations in GCP / see mutexlock there)
  84. // If the controller requests another instance of a given client
  85. // we will close the old client first and then construct a new one.
  86. type Manager struct {
  87. log logr.Logger
  88. client client.Client
  89. controllerClass string
  90. enableFloodgate bool
  91. // store clients by provider type
  92. clientMap map[clientKey]*clientVal
  93. // Track v2 provider connections for release back to pool
  94. v2PooledConnections []v2PooledConnection
  95. }
  96. type clientKey struct {
  97. providerType string
  98. // For v2 providers, store the provider name and namespace
  99. v2ProviderName string
  100. v2ProviderNamespace string
  101. }
  102. type clientVal struct {
  103. client esv1.SecretsClient
  104. store esv1.GenericStore
  105. // For v2 providers, store the generation for cache invalidation
  106. v2ProviderGeneration int64
  107. }
  108. // v2ProviderConfig contains configuration for creating a v2 provider client.
  109. type v2ProviderConfig struct {
  110. name string
  111. resourceNamespace string // empty for cluster-scoped resources
  112. manifestNamespace string // namespace of the ExternalSecret/PushSecret
  113. config esv1.ProviderConfig
  114. generation int64
  115. isClusterScoped bool
  116. kindStr string // "Provider" or "ClusterProvider"
  117. }
  118. // NewManager constructs a new manager with defaults.
  119. func NewManager(ctrlClient client.Client, controllerClass string, enableFloodgate bool) *Manager {
  120. log := ctrl.Log.WithName("clientmanager")
  121. return &Manager{
  122. log: log,
  123. client: ctrlClient,
  124. controllerClass: controllerClass,
  125. enableFloodgate: enableFloodgate,
  126. clientMap: make(map[clientKey]*clientVal),
  127. }
  128. }
  129. // GetFromStore returns a provider client from the given store.
  130. // Do not close the client returned from this func, instead close
  131. // the manager once you're done with reconciling the external secret.
  132. func (m *Manager) GetFromStore(ctx context.Context, store esv1.GenericStore, namespace string) (esv1.SecretsClient, error) {
  133. storeProvider, err := esv1.GetProvider(store)
  134. if err != nil {
  135. return nil, err
  136. }
  137. secretClient := m.getStoredClient(ctx, storeProvider, store)
  138. if secretClient != nil {
  139. return secretClient, nil
  140. }
  141. m.log.V(1).Info("creating new client",
  142. "provider", fmt.Sprintf("%T", storeProvider),
  143. "store", fmt.Sprintf("%s/%s", store.GetNamespace(), store.GetName()))
  144. // secret client is created only if we are going to refresh
  145. // this skip an unnecessary check/request in the case we are not going to do anything
  146. secretClient, err = storeProvider.NewClient(ctx, store, m.client, namespace)
  147. if err != nil {
  148. return nil, err
  149. }
  150. idx := storeKey(storeProvider)
  151. m.clientMap[idx] = &clientVal{
  152. client: secretClient,
  153. store: store,
  154. }
  155. return secretClient, nil
  156. }
  157. // Get returns a provider client from the given storeRef or sourceRef.secretStoreRef
  158. // while sourceRef.SecretStoreRef takes precedence over storeRef.
  159. // Do not close the client returned from this func, instead close
  160. // the manager once you're done with recinciling the external secret.
  161. func (m *Manager) Get(ctx context.Context, storeRef esv1.SecretStoreRef, namespace string, sourceRef *esv1.StoreGeneratorSourceRef) (esv1.SecretsClient, error) {
  162. if sourceRef != nil && sourceRef.SecretStoreRef != nil {
  163. storeRef = *sourceRef.SecretStoreRef
  164. }
  165. if storeRef.Kind == esv1.ProviderKindStr {
  166. if !V2ProvidersEnabled() {
  167. return nil, fmt.Errorf(errV2ProvidersDisabled, storeRef.Kind, storeRef.Name)
  168. }
  169. return m.getV2ProviderClient(ctx, storeRef.Name, namespace)
  170. }
  171. if storeRef.Kind == esv1.ClusterProviderKindStr {
  172. if !V2ProvidersEnabled() {
  173. return nil, fmt.Errorf(errV2ProvidersDisabled, storeRef.Kind, storeRef.Name)
  174. }
  175. return m.getV2ClusterProviderClient(ctx, storeRef.Name, namespace)
  176. }
  177. store, err := m.getStore(ctx, &storeRef, namespace)
  178. if err != nil {
  179. return nil, err
  180. }
  181. // check if store should be handled by this controller instance
  182. if !ShouldProcessStore(store, m.controllerClass) {
  183. return nil, errors.New("can not reference unmanaged store")
  184. }
  185. // when using ClusterSecretStore, validate the ClusterSecretStore namespace conditions
  186. shouldProcess, err := m.shouldProcessSecret(store, namespace)
  187. if err != nil {
  188. return nil, err
  189. }
  190. if !shouldProcess {
  191. return nil, fmt.Errorf(errClusterStoreMismatch, store.GetName(), namespace)
  192. }
  193. if m.enableFloodgate {
  194. err := assertStoreIsUsable(store)
  195. if err != nil {
  196. return nil, err
  197. }
  198. }
  199. return m.GetFromStore(ctx, store, namespace)
  200. }
  201. // getOrCreateV2Client is a shared helper for creating or retrieving v2 provider clients.
  202. // It handles caching, connection pooling, and client lifecycle for both Provider and ClusterProvider.
  203. func (m *Manager) getOrCreateV2Client(ctx context.Context, cfg v2ProviderConfig, authNamespace string) (esv1.SecretsClient, error) {
  204. // Determine cache key type based on resource type
  205. cacheKeyType := "v2-provider"
  206. if cfg.isClusterScoped {
  207. cacheKeyType = "v2-cluster-provider"
  208. }
  209. // Create cache key
  210. cacheKey := clientKey{
  211. providerType: cacheKeyType,
  212. v2ProviderName: cfg.name,
  213. v2ProviderNamespace: cfg.manifestNamespace,
  214. }
  215. // Check if we have a cached client
  216. if cached, ok := m.clientMap[cacheKey]; ok {
  217. if cached.v2ProviderGeneration == cfg.generation {
  218. m.log.V(1).Info("reusing cached v2 provider client",
  219. cfg.kindStr, cfg.name,
  220. "manifestNamespace", cfg.manifestNamespace,
  221. "authNamespace", authNamespace,
  222. "generation", cfg.generation)
  223. // Record cache hit
  224. providerType := "provider"
  225. if cfg.isClusterScoped {
  226. providerType = "cluster-provider"
  227. }
  228. clientManagerMetrics.RecordCacheHit(providerType)
  229. return cached.client, nil
  230. }
  231. // Cache is stale, invalidate
  232. m.log.V(1).Info("provider generation changed, invalidating cache",
  233. cfg.kindStr, cfg.name,
  234. "manifestNamespace", cfg.manifestNamespace,
  235. "oldGeneration", cached.v2ProviderGeneration,
  236. "newGeneration", cfg.generation)
  237. // Record cache invalidation
  238. providerType := "provider"
  239. if cfg.isClusterScoped {
  240. providerType = "cluster-provider"
  241. }
  242. clientManagerMetrics.RecordCacheInvalidation(providerType, "generation_change")
  243. delete(m.clientMap, cacheKey)
  244. }
  245. m.log.V(1).Info("getting v2 provider client from pool",
  246. cfg.kindStr, cfg.name,
  247. "manifestNamespace", cfg.manifestNamespace,
  248. "authNamespace", authNamespace,
  249. "address", cfg.config.Address)
  250. // Get provider address
  251. address := cfg.config.Address
  252. if address == "" {
  253. return nil, fmt.Errorf("provider address is required in %s %q", cfg.kindStr, cfg.name)
  254. }
  255. tlsSecretNamespace := cfg.resourceNamespace
  256. if tlsSecretNamespace == "" {
  257. tlsSecretNamespace = cfg.config.ProviderRef.Namespace
  258. }
  259. tlsSecretNamespace = grpc.NamespaceFromAddress(cfg.config.Address, tlsSecretNamespace)
  260. // Load TLS configuration
  261. tlsConfig, err := grpc.LoadClientTLSConfig(ctx, m.client, cfg.config.Address, tlsSecretNamespace)
  262. if err != nil {
  263. return nil, fmt.Errorf("failed to load TLS config for %s %q: %w", cfg.kindStr, cfg.name, err)
  264. }
  265. // Get connection from global pool
  266. pool := getGlobalV2ConnectionPool()
  267. grpcClient, err := pool.Get(ctx, address, tlsConfig)
  268. if err != nil {
  269. return nil, fmt.Errorf("failed to get gRPC client from pool for %s %q: %w", cfg.kindStr, cfg.name, err)
  270. }
  271. // Track this connection for release when Manager closes
  272. m.v2PooledConnections = append(m.v2PooledConnections, v2PooledConnection{
  273. address: address,
  274. tlsConfig: tlsConfig,
  275. })
  276. // Convert ProviderReference to protobuf format
  277. providerRef := &pb.ProviderReference{
  278. ApiVersion: cfg.config.ProviderRef.APIVersion,
  279. Kind: cfg.config.ProviderRef.Kind,
  280. Name: cfg.config.ProviderRef.Name,
  281. Namespace: cfg.config.ProviderRef.Namespace,
  282. }
  283. // Wrap with V2ClientWrapper
  284. wrappedClient := adapterstore.NewClient(grpcClient, providerRef, authNamespace)
  285. // Cache the client for this Manager instance
  286. m.clientMap[cacheKey] = &clientVal{
  287. client: wrappedClient,
  288. store: nil, // v2 providers don't use GenericStore
  289. v2ProviderGeneration: cfg.generation,
  290. }
  291. m.log.Info("v2 provider client obtained from pool",
  292. cfg.kindStr, cfg.name,
  293. "manifestNamespace", cfg.manifestNamespace,
  294. "authNamespace", authNamespace,
  295. "address", address)
  296. return wrappedClient, nil
  297. }
  298. // getV2ProviderClient creates or retrieves a cached gRPC client for a v2 Provider.
  299. // It uses the global connection pool to enable connection reuse across reconciles.
  300. func (m *Manager) getV2ProviderClient(ctx context.Context, providerName, namespace string) (esv1.SecretsClient, error) {
  301. // Fetch the Provider resource
  302. var provider esv1.Provider
  303. providerKey := types.NamespacedName{
  304. Name: providerName,
  305. Namespace: namespace,
  306. }
  307. if err := m.client.Get(ctx, providerKey, &provider); err != nil {
  308. return nil, fmt.Errorf("failed to get Provider %q: %w", providerName, err)
  309. }
  310. // Build configuration for the helper
  311. cfg := v2ProviderConfig{
  312. name: providerName,
  313. resourceNamespace: namespace,
  314. manifestNamespace: namespace,
  315. config: provider.Spec.Config,
  316. generation: provider.Generation,
  317. isClusterScoped: false,
  318. kindStr: esv1.ProviderKindStr,
  319. }
  320. // For namespace-scoped Provider, auth namespace is always the manifest namespace
  321. return m.getOrCreateV2Client(ctx, cfg, namespace)
  322. }
  323. // getV2ClusterProviderClient creates or retrieves a cached gRPC client for a v2 ClusterProvider.
  324. // It uses the global connection pool to enable connection reuse across reconciles.
  325. func (m *Manager) getV2ClusterProviderClient(ctx context.Context, providerName, namespace string) (esv1.SecretsClient, error) {
  326. // Fetch the ClusterProvider resource (cluster-scoped)
  327. var clusterProvider esv1.ClusterProvider
  328. providerKey := types.NamespacedName{
  329. Name: providerName,
  330. }
  331. if err := m.client.Get(ctx, providerKey, &clusterProvider); err != nil {
  332. return nil, fmt.Errorf("failed to get ClusterProvider %q: %w", providerName, err)
  333. }
  334. // Validate namespace conditions
  335. shouldProcess, err := m.validateNamespaceConditions(clusterProvider.Spec.Conditions, namespace)
  336. if err != nil {
  337. return nil, err
  338. }
  339. if !shouldProcess {
  340. return nil, fmt.Errorf(errClusterProviderDenied, providerName, namespace)
  341. }
  342. // Determine authentication namespace based on authenticationScope
  343. authNamespace := namespace // default to ManifestNamespace
  344. if clusterProvider.Spec.AuthenticationScope == esv1.AuthenticationScopeProviderNamespace {
  345. // Use namespace from providerRef
  346. if clusterProvider.Spec.Config.ProviderRef.Namespace != "" {
  347. authNamespace = clusterProvider.Spec.Config.ProviderRef.Namespace
  348. } else {
  349. return nil, fmt.Errorf("ClusterProvider %q has authenticationScope=ProviderNamespace but spec.config.providerRef.namespace is empty", providerName)
  350. }
  351. }
  352. // Build configuration for the helper
  353. cfg := v2ProviderConfig{
  354. name: providerName,
  355. resourceNamespace: "", // cluster-scoped
  356. manifestNamespace: namespace,
  357. config: clusterProvider.Spec.Config,
  358. generation: clusterProvider.Generation,
  359. isClusterScoped: true,
  360. kindStr: esv1.ClusterProviderKindStr,
  361. }
  362. return m.getOrCreateV2Client(ctx, cfg, authNamespace)
  363. }
  364. // returns a previously stored client from the cache if store and store-version match
  365. // if a client exists for the same provider which points to a different store or store version
  366. // it will be cleaned up.
  367. func (m *Manager) getStoredClient(ctx context.Context, storeProvider esv1.ProviderInterface, store esv1.GenericStore) esv1.SecretsClient {
  368. idx := storeKey(storeProvider)
  369. val, ok := m.clientMap[idx]
  370. if !ok {
  371. return nil
  372. }
  373. valGVK, err := m.client.GroupVersionKindFor(val.store)
  374. if err != nil {
  375. return nil
  376. }
  377. storeGVK, err := m.client.GroupVersionKindFor(store)
  378. if err != nil {
  379. return nil
  380. }
  381. storeName := fmt.Sprintf("%s/%s", store.GetNamespace(), store.GetName())
  382. // return client if it points to the very same store
  383. if val.store.GetObjectMeta().Generation == store.GetGeneration() &&
  384. valGVK == storeGVK &&
  385. val.store.GetName() == store.GetName() &&
  386. val.store.GetNamespace() == store.GetNamespace() {
  387. m.log.V(1).Info("reusing stored client",
  388. "provider", fmt.Sprintf("%T", storeProvider),
  389. "store", storeName)
  390. // Record cache hit
  391. providerType := "unknown"
  392. if idx.v2ProviderName != "" {
  393. if idx.v2ProviderNamespace == "" {
  394. providerType = "cluster-provider"
  395. } else {
  396. providerType = "provider"
  397. }
  398. }
  399. clientManagerMetrics.RecordCacheHit(providerType)
  400. return val.client
  401. }
  402. m.log.V(1).Info("cleaning up client",
  403. "provider", fmt.Sprintf("%T", storeProvider),
  404. "store", storeName)
  405. // if we have a client, but it points to a different store
  406. // we must clean it up
  407. _ = val.client.Close(ctx)
  408. delete(m.clientMap, idx)
  409. // Record cache invalidation
  410. providerType := "unknown"
  411. reason := "store_mismatch"
  412. if idx.v2ProviderName != "" {
  413. if idx.v2ProviderNamespace == "" {
  414. providerType = "cluster-provider"
  415. } else {
  416. providerType = "provider"
  417. }
  418. if val.store.GetObjectMeta().Generation != store.GetGeneration() {
  419. reason = "generation_change"
  420. }
  421. }
  422. clientManagerMetrics.RecordCacheInvalidation(providerType, reason)
  423. return nil
  424. }
  425. func storeKey(storeProvider esv1.ProviderInterface) clientKey {
  426. return clientKey{
  427. providerType: fmt.Sprintf("%T", storeProvider),
  428. }
  429. }
  430. // getStore fetches the (Cluster)SecretStore from the kube-apiserver
  431. // and returns a GenericStore representing it.
  432. func (m *Manager) getStore(ctx context.Context, storeRef *esv1.SecretStoreRef, namespace string) (esv1.GenericStore, error) {
  433. ref := types.NamespacedName{
  434. Name: storeRef.Name,
  435. }
  436. if storeRef.Kind == esv1.ClusterSecretStoreKind {
  437. var store esv1.ClusterSecretStore
  438. err := m.client.Get(ctx, ref, &store)
  439. if err != nil {
  440. return nil, fmt.Errorf(errGetClusterSecretStore, ref.Name, err)
  441. }
  442. return &store, nil
  443. }
  444. ref.Namespace = namespace
  445. var store esv1.SecretStore
  446. err := m.client.Get(ctx, ref, &store)
  447. if err != nil {
  448. return nil, fmt.Errorf(errGetSecretStore, ref.Name, err)
  449. }
  450. return &store, nil
  451. }
  452. // Close cleans up all clients.
  453. // For v1 providers, it closes the clients directly.
  454. // For v2 providers, it releases connections back to the pool for reuse.
  455. func (m *Manager) Close(ctx context.Context) error {
  456. var errs []string
  457. // Release v2 pooled connections back to the pool
  458. pool := getGlobalV2ConnectionPool()
  459. for _, pooledConn := range m.v2PooledConnections {
  460. pool.Release(pooledConn.address, pooledConn.tlsConfig)
  461. m.log.V(1).Info("released v2 connection back to pool",
  462. "address", pooledConn.address)
  463. }
  464. m.v2PooledConnections = nil
  465. // Close v1 provider clients (they don't use the pool)
  466. for key, val := range m.clientMap {
  467. // Only close v1 clients; v2 clients are managed by the pool
  468. if key.providerType != "v2-provider" && key.providerType != "v2-cluster-provider" {
  469. err := val.client.Close(ctx)
  470. if err != nil {
  471. errs = append(errs, err.Error())
  472. }
  473. }
  474. delete(m.clientMap, key)
  475. }
  476. if len(errs) != 0 {
  477. return fmt.Errorf("errors while closing clients: %s", strings.Join(errs, ", "))
  478. }
  479. return nil
  480. }
  481. // validateNamespaceConditions checks if a namespace matches the given conditions.
  482. // Returns true if the namespace is allowed, false if denied.
  483. func (m *Manager) validateNamespaceConditions(conditions []esv1.ClusterSecretStoreCondition, ns string) (bool, error) {
  484. if len(conditions) == 0 {
  485. return true, nil
  486. }
  487. namespace := v1.Namespace{}
  488. if err := m.client.Get(context.Background(), client.ObjectKey{Name: ns}, &namespace); err != nil {
  489. return false, fmt.Errorf("failed to get a namespace %q: %w", ns, err)
  490. }
  491. nsLabels := labels.Set(namespace.GetLabels())
  492. for _, condition := range conditions {
  493. var labelSelectors []*metav1.LabelSelector
  494. if condition.NamespaceSelector != nil {
  495. labelSelectors = append(labelSelectors, condition.NamespaceSelector)
  496. }
  497. for _, n := range condition.Namespaces {
  498. labelSelectors = append(labelSelectors, &metav1.LabelSelector{
  499. MatchLabels: map[string]string{
  500. "kubernetes.io/metadata.name": n,
  501. },
  502. })
  503. }
  504. for _, ls := range labelSelectors {
  505. selector, err := metav1.LabelSelectorAsSelector(ls)
  506. if err != nil {
  507. return false, fmt.Errorf("failed to convert label selector into selector %v: %w", ls, err)
  508. }
  509. if selector.Matches(nsLabels) {
  510. return true, nil
  511. }
  512. }
  513. for _, reg := range condition.NamespaceRegexes {
  514. match, err := regexp.MatchString(reg, ns)
  515. if err != nil {
  516. // Should not happen since store validation already verified the regexes.
  517. return false, fmt.Errorf("failed to compile regex %v: %w", reg, err)
  518. }
  519. if match {
  520. return true, nil
  521. }
  522. }
  523. }
  524. return false, nil
  525. }
  526. // shouldProcessSecret validates if a secret should be processed based on namespace conditions.
  527. // This is a wrapper around validateNamespaceConditions for backward compatibility with GenericStore.
  528. func (m *Manager) shouldProcessSecret(store esv1.GenericStore, ns string) (bool, error) {
  529. // Only check conditions for cluster-scoped resources (ClusterSecretStore and ClusterProvider)
  530. if store.GetKind() != esv1.ClusterSecretStoreKind && store.GetKind() != esv1.ClusterProviderKind {
  531. return true, nil
  532. }
  533. return m.validateNamespaceConditions(store.GetSpec().Conditions, ns)
  534. }
  535. // assertStoreIsUsable asserts that the store is ready to use.
  536. func assertStoreIsUsable(store esv1.GenericStore) error {
  537. if store == nil {
  538. return nil
  539. }
  540. condition := GetSecretStoreCondition(store.GetStatus(), esv1.SecretStoreReady)
  541. if condition == nil || condition.Status != v1.ConditionTrue {
  542. return fmt.Errorf(errSecretStoreNotReady, store.GetKind(), store.GetName())
  543. }
  544. return nil
  545. }
  546. // ShouldProcessStore returns true if the store should be processed.
  547. func ShouldProcessStore(store esv1.GenericStore, class string) bool {
  548. if store == nil || store.GetSpec().Controller == "" || store.GetSpec().Controller == class {
  549. return true
  550. }
  551. return false
  552. }
  553. // GetSecretStoreCondition returns the condition with the provided type.
  554. func GetSecretStoreCondition(status esv1.SecretStoreStatus, condType esv1.SecretStoreConditionType) *esv1.SecretStoreStatusCondition {
  555. for i := range status.Conditions {
  556. c := status.Conditions[i]
  557. if c.Type == condType {
  558. return &c
  559. }
  560. }
  561. return nil
  562. }