manager.go 22 KB

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