Repository: deislabs/ratify
Pull request #1382 (2024-04-11 11:34:48)

feat: add certStoreManager interface to wrap operations on namespaced certStores [multi-tenancy PR 5]
# Description

## What this PR does / why we need it:
This is the 5th PR for multi-tenancy support. Please review https://github.com/deislabs/ratify/pull/1380 first. Check diff between PR 4 and PR 5 at: https://github.com/binbin-li/ratify/pull/120

1. Add a CertStoreManager interface to wrap operations on namespaced certStore resources.
2. Update certStore references to use the new CertStoreManager interface instead of directly accessing cert stores.
3. Move the `CertificatesMap` under controllers to resource_map.go so that it can be shared by clustered and namespaced controllers in the future.
4. Updated unit tests. Some unit tests are not added in this PR as we'll change the behavior soon.
5. For the interface implementation, it's in a transition stage that keeps the old behavior. Will update the implementation once Ratify fully supports multi-tenancy.

Note:
The nested certStore map is like:
```
	 {
	   "namespace1": {
	     "namespace1/store1": []*x509.Certificate,
	     "namespace1/store2": []*x509.Certificate
	   },
	   "namespace2": {
	     "namespace2/store1": []*x509.Certificate,
	     "namespace2/store2": []*x509.Certificate
	   }
	 }
```
We keep the namespace prefix for inner map key to faciliate accessing from verifier.

## Which issue(s) this PR fixes *(optional, using `fixes #<issue number>(, fixes #<issue_number>, ...)` format, will close the issue(s) when the PR gets merged)*:
Fixes #

## Type of change

Please delete options that are not relevant.

- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] Helm Chart Change (any edit/addition/update that is necessary for changes merged to the `main` branch)
- [ ] This change requires a documentation update

# How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Please also list any relevant details for your test configuration

- [ ] Test A
- [ ] Test B

# Checklist:

- [ ] Does the affected code have corresponding tests?
- [ ] Are the changes documented, not just with inline documentation, but also with conceptual documentation such as an overview of a new feature, or task-based documentation like a tutorial? Consider if this change should be announced on your project blog.
- [ ] Does this introduce breaking changes that would require an announcement or bumping the major version?
- [ ] Do all new files have appropriate license header?

# Post Merge Requirements
- [ ] MAINTAINERS: manually trigger the "Publish Package" workflow after merging any PR that indicates `Helm Chart Change`


codecov[bot]: ## [Codecov](https://app.codecov.io/gh/deislabs/ratify/pull/1382?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs) Report
Attention: Patch coverage is `89.04110%` with `8 lines` in your changes are missing coverage. Please review.
> Project coverage is 65.32%. Comparing base [(`73ef709`)](https://app.codecov.io/gh/deislabs/ratify/commit/73ef7091e919c18ad37c7ec0a6e00b5471db3748?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs) to head [(`b206dc3`)](https://app.codecov.io/gh/deislabs/ratify/pull/1382?dropdown=coverage&src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs).
> Report is 6 commits behind head on staging.

| [Files](https://app.codecov.io/gh/deislabs/ratify/pull/1382?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs) | Patch % | Lines |
|---|---|---|
| [pkg/controllers/certificatestore\_controller.go](https://app.codecov.io/gh/deislabs/ratify/pull/1382?src=pr&el=tree&filepath=pkg%2Fcontrollers%2Fcertificatestore_controller.go&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs#diff-cGtnL2NvbnRyb2xsZXJzL2NlcnRpZmljYXRlc3RvcmVfY29udHJvbGxlci5nbw==) | 0.00% | [2 Missing :warning: ](https://app.codecov.io/gh/deislabs/ratify/pull/1382?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs) |
| [pkg/controllers/policy\_controller.go](https://app.codecov.io/gh/deislabs/ratify/pull/1382?src=pr&el=tree&filepath=pkg%2Fcontrollers%2Fpolicy_controller.go&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs#diff-cGtnL2NvbnRyb2xsZXJzL3BvbGljeV9jb250cm9sbGVyLmdv) | 33.33% | [2 Missing :warning: ](https://app.codecov.io/gh/deislabs/ratify/pull/1382?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs) |
| [pkg/executor/core/executor.go](https://app.codecov.io/gh/deislabs/ratify/pull/1382?src=pr&el=tree&filepath=pkg%2Fexecutor%2Fcore%2Fexecutor.go&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs#diff-cGtnL2V4ZWN1dG9yL2NvcmUvZXhlY3V0b3IuZ28=) | 0.00% | [1 Missing and 1 partial :warning: ](https://app.codecov.io/gh/deislabs/ratify/pull/1382?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs) |
| [pkg/controllers/store\_controller.go](https://app.codecov.io/gh/deislabs/ratify/pull/1382?src=pr&el=tree&filepath=pkg%2Fcontrollers%2Fstore_controller.go&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs#diff-cGtnL2NvbnRyb2xsZXJzL3N0b3JlX2NvbnRyb2xsZXIuZ28=) | 50.00% | [1 Missing :warning: ](https://app.codecov.io/gh/deislabs/ratify/pull/1382?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs) |
| [pkg/verifier/notation/truststore.go](https://app.codecov.io/gh/deislabs/ratify/pull/1382?src=pr&el=tree&filepath=pkg%2Fverifier%2Fnotation%2Ftruststore.go&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs#diff-cGtnL3ZlcmlmaWVyL25vdGF0aW9uL3RydXN0c3RvcmUuZ28=) | 0.00% | [1 Missing :warning: ](https://app.codecov.io/gh/deislabs/ratify/pull/1382?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff             @@
##           staging    #1382      +/-   ##
===========================================
+ Coverage    65.31%   65.32%   +0.01%     
===========================================
  Files          105       92      -13     
  Lines         5458     4860     -598     
===========================================
- Hits          3565     3175     -390     
+ Misses        1535     1399     -136     
+ Partials       358      286      -72     
```



</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/deislabs/ratify/pull/1382?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deislabs).


Patch:
diff --git a/docs/design/Azure Kubernetes Workload Identity AuthProvider.md b/docs/design/Azure Kubernetes Workload Identity AuthProvider.md
index 90836b0..6c0ffa6 100644
--- a/docs/design/Azure Kubernetes Workload Identity AuthProvider.md
+++ b/docs/design/Azure Kubernetes Workload Identity AuthProvider.md
@@ -19,7 +19,7 @@ User would need to follow instructions [here](https://azure.github.io/azure-work
 The official steps for setting up Workload Identity on AKS can be found [here](https://azure.github.io/azure-workload-identity/docs/quick-start.html).  
 
 1. Create ACR
-2. Create OIDC enabled AKS cluster by follow steps [here](https://docs.microsoft.com/en-us/azure/aks/cluster-configuration#oidc-issuer-preview)
+2. Create OIDC enabled AKS cluster by follow steps [here](https://learn.microsoft.com/en-us/azure/aks/use-oidc-issuer#create-an-aks-cluster-with-oidc-issuer)
 3. Save the cluster's OIDC URL: `az aks show --resource-group <resource_group> --name <cluster_name> --query "oidcIssuerProfile.issuerUrl" -otsv`
 4. Install Mutating Admission Webhook onto AKS cluster by following steps [here](https://azure.github.io/azure-workload-identity/docs/installation/mutating-admission-webhook.html)
 5. As the guide linked above shows, it's possible to use the AZ workload identity CLI or the regular az CLI to perform remaining setup. Following steps follow the AZ CLI.
diff --git a/pkg/controllers/policy_controller.go b/pkg/controllers/policy_controller.go
index dfc2eeb..babec48 100644
--- a/pkg/controllers/policy_controller.go
+++ b/pkg/controllers/policy_controller.go
@@ -58,7 +58,7 @@ func (r *PolicyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctr
 		if apierrors.IsNotFound(err) {
 			policyLogger.Infof("delete event detected, removing policy %s", resource)
 			// TODO: pass the actual namespace once multi-tenancy is supported.
-			ActivePolicies.DeletePolicy(constants.EmptyNamespace, resource)
+			NamespacedPolicies.DeletePolicy(constants.EmptyNamespace, resource)
 		} else {
 			policyLogger.Error("failed to get Policy: ", err)
 		}
@@ -96,7 +96,7 @@ func policyAddOrReplace(spec configv1beta1.PolicySpec) error {
 	}
 
 	// TODO: pass the actual namespace once multi-tenancy is supported.
-	ActivePolicies.AddPolicy(constants.EmptyNamespace, constants.RatifyPolicy, policyEnforcer)
+	NamespacedPolicies.AddPolicy(constants.EmptyNamespace, constants.RatifyPolicy, policyEnforcer)
 	return nil
 }
 
diff --git a/pkg/controllers/resource_map.go b/pkg/controllers/resource_map.go
index 5352a14..7e25032 100644
--- a/pkg/controllers/resource_map.go
+++ b/pkg/controllers/resource_map.go
@@ -14,18 +14,23 @@ limitations under the License.
 package controllers
 
 import (
+	cs "github.com/deislabs/ratify/pkg/customresources/certificatestores"
 	"github.com/deislabs/ratify/pkg/customresources/policies"
 	rs "github.com/deislabs/ratify/pkg/customresources/referrerstores"
 	"github.com/deislabs/ratify/pkg/customresources/verifiers"
 )
 
 var (
-	VerifierMap = verifiers.NewActiveVerifiers()
+	// NamespacedVerifiers is a map between namespace and verifiers.
+	NamespacedVerifiers = verifiers.NewActiveVerifiers()
 
-	// ActivePolicy is the active policy generated from CRD. There would be exactly
+	// NamespacedPolicies is the active policy generated from CRD. There would be exactly
 	// one active policy belonging to a namespace at any given time.
-	ActivePolicies = policies.NewActivePolicies()
+	NamespacedPolicies = policies.NewActivePolicies()
 
-	// a map to track active stores
-	StoreMap = rs.NewActiveStores()
+	// NamespacedStores is a map to track active stores across namespaces.
+	NamespacedStores = rs.NewActiveStores()
+
+	// NamespacedCertStores is a map between namespace and CertificateStores.
+	NamespacedCertStores = cs.NewActiveCertStores()
 )
diff --git a/pkg/controllers/store_controller.go b/pkg/controllers/store_controller.go
index 5371e7c..6349818 100644
--- a/pkg/controllers/store_controller.go
+++ b/pkg/controllers/store_controller.go
@@ -60,7 +60,7 @@ func (r *StoreReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl
 		if apierrors.IsNotFound(err) {
 			storeLogger.Infof("deletion detected, removing store %v", req.Name)
 			// TODO: pass the actual namespace once multi-tenancy is supported.
-			StoreMap.DeleteStore(constants.EmptyNamespace, resource)
+			NamespacedStores.DeleteStore(constants.EmptyNamespace, resource)
 		} else {
 			storeLogger.Error(err, "unable to fetch store")
 		}
@@ -112,7 +112,7 @@ func storeAddOrReplace(spec configv1beta1.StoreSpec, fullname string) error {
 	}
 
 	// TODO: pass the actual namespace once multi-tenancy is supported.
-	StoreMap.AddStore(constants.EmptyNamespace, fullname, storeReference)
+	NamespacedStores.AddStore(constants.EmptyNamespace, fullname, storeReference)
 	logrus.Infof("store '%v' added to store map", storeReference.Name())
 
 	return nil
diff --git a/pkg/controllers/utils/cert_store.go b/pkg/controllers/utils/cert_store.go
new file mode 100644
index 0000000..3bfb408
--- /dev/null
+++ b/pkg/controllers/utils/cert_store.go
@@ -0,0 +1,28 @@
+/*
+Copyright The Ratify Authors.
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+http://www.apache.org/licenses/LICENSE-2.0
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package utils
+
+import (
+	"context"
+	"crypto/x509"
+
+	ctxUtils "github.com/deislabs/ratify/internal/context"
+	"github.com/deislabs/ratify/pkg/controllers"
+)
+
+// returns the internal certificate map
+// TODO: returns certificates from both cluster-wide and given namespace as namespaced verifier could access both.
+func GetCertificatesMap(ctx context.Context) map[string][]*x509.Certificate {
+	return controllers.NamespacedCertStores.GetCertStores(ctxUtils.GetNamespace(ctx))
+}
diff --git a/pkg/controllers/verifier_controller.go b/pkg/controllers/verifier_controller.go
index 1cd8bb7..eb9f174 100644
--- a/pkg/controllers/verifier_controller.go
+++ b/pkg/controllers/verifier_controller.go
@@ -68,7 +68,7 @@ func (r *VerifierReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c
 		if apierrors.IsNotFound(err) {
 			verifierLogger.Infof("delete event detected, removing verifier %v", resource)
 			// TODO: pass the actual namespace once multi-tenancy is supported.
-			VerifierMap.DeleteVerifier(constants.EmptyNamespace, resource)
+			NamespacedVerifiers.DeleteVerifier(constants.EmptyNamespace, resource)
 		} else {
 			verifierLogger.Error(err, "unable to fetch verifier")
 		}
@@ -119,7 +119,7 @@ func verifierAddOrReplace(spec configv1beta1.VerifierSpec, objectName string, na
 		return err
 	}
 	// TODO: pass the actual namespace once multi-tenancy is supported.
-	VerifierMap.AddVerifier(constants.EmptyNamespace, objectName, referenceVerifier)
+	NamespacedVerifiers.AddVerifier(constants.EmptyNamespace, objectName, referenceVerifier)
 	logrus.Infof("verifier '%v' added to verifier map", referenceVerifier.Name())
 
 	return nil
diff --git a/pkg/manager/manager.go b/pkg/manager/manager.go
index 2527f43..2f1874f 100644
--- a/pkg/manager/manager.go
+++ b/pkg/manager/manager.go
@@ -85,9 +85,9 @@ func StartServer(httpServerAddress, configFilePath, certDirectory, caCertFile st
 	server, err := httpserver.NewServer(context.Background(), httpServerAddress, func(ctx context.Context) *ef.Executor {
 		namespace := ctxUtils.GetNamespace(ctx)
 
-		activeVerifiers := controllers.VerifierMap.GetVerifiers(namespace)
-		activePolicyEnforcer := controllers.ActivePolicies.GetPolicy(namespace)
-		activeStores := controllers.StoreMap.GetStores(namespace)
+		activeVerifiers := controllers.NamespacedVerifiers.GetVerifiers(namespace)
+		activePolicyEnforcer := controllers.NamespacedPolicies.GetPolicy(namespace)
+		activeStores := controllers.NamespacedStores.GetStores(namespace)
 
 		// return executor with latest configuration
 		executor := ef.Executor{
diff --git a/pkg/verifier/notation/notation.go b/pkg/verifier/notation/notation.go
index 7ac4b6f..678f35f 100644
--- a/pkg/verifier/notation/notation.go
+++ b/pkg/verifier/notation/notation.go
@@ -221,6 +221,7 @@ func (v *notationPluginVerifier) GetNestedReferences() []string {
 
 // append namespace to certStore so they are uniquely identifiable
 func prependNamespaceToCertStore(verificationCertStore map[string][]string, namespace string) (map[string][]string, error) {
+	// TODO: once we support multi-tenancy, empty namespace would be reserved for cluster scope.
 	if namespace == "" {
 		return nil, re.ErrorCodeEnvNotSet.WithComponentType(re.Verifier).WithDetail("failure to parse VerificationCertStores, namespace for VerificationCertStores must be provided")
 	}
diff --git a/pkg/verifier/notation/truststore.go b/pkg/verifier/notation/truststore.go
index cf7373c..89a7fa9 100644
--- a/pkg/verifier/notation/truststore.go
+++ b/pkg/verifier/notation/truststore.go
@@ -22,7 +22,7 @@ import (
 	"fmt"
 
 	"github.com/deislabs/ratify/internal/logger"
-	"github.com/deislabs/ratify/pkg/controllers"
+	cutils "github.com/deislabs/ratify/pkg/controllers/utils"
 	"github.com/deislabs/ratify/pkg/keymanagementprovider"
 	"github.com/deislabs/ratify/pkg/utils"
 	"github.com/notaryproject/notation-go/verifier/truststore"
@@ -42,7 +42,7 @@ type trustStore struct {
 // will be loaded for each signature verification.
 // And this API must follow the Notation Trust Store spec: https://github.com/notaryproject/notaryproject/blob/main/specs/trust-store-trust-policy.md#trust-store
 func (s trustStore) GetCertificates(ctx context.Context, _ truststore.Type, namedStore string) ([]*x509.Certificate, error) {
-	certs, err := s.getCertificatesInternal(ctx, namedStore, controllers.GetCertificatesMap())
+	certs, err := s.getCertificatesInternal(ctx, namedStore, cutils.GetCertificatesMap(ctx))
 	if err != nil {
 		return nil, err
 	}


Test patch:
diff --git a/pkg/controllers/certificatestore_controller.go b/pkg/controllers/certificatestore_controller.go
index 8615b3b..5b0922d 100644
--- a/pkg/controllers/certificatestore_controller.go
+++ b/pkg/controllers/certificatestore_controller.go
@@ -15,11 +15,11 @@ package controllers
 
 import (
 	"context"
-	"crypto/x509"
 	"encoding/json"
 	"fmt"
 
 	configv1beta1 "github.com/deislabs/ratify/api/v1beta1"
+	"github.com/deislabs/ratify/internal/constants"
 	"github.com/deislabs/ratify/pkg/certificateprovider"
 	_ "github.com/deislabs/ratify/pkg/certificateprovider/azurekeyvault" // register azure keyvault certificate provider
 	_ "github.com/deislabs/ratify/pkg/certificateprovider/inline"        // register inline certificate provider
@@ -40,11 +40,6 @@ type CertificateStoreReconciler struct {
 	Scheme *runtime.Scheme
 }
 
-var (
-	// a map between CertificateStore name to array of x509 certificates
-	certificatesMap = map[string][]*x509.Certificate{}
-)
-
 //+kubebuilder:rbac:groups=config.ratify.deislabs.io,resources=certificatestores,verbs=get;list;watch;create;update;patch;delete
 //+kubebuilder:rbac:groups=config.ratify.deislabs.io,resources=certificatestores/status,verbs=get;update;patch
 //+kubebuilder:rbac:groups=config.ratify.deislabs.io,resources=certificatestores/finalizers,verbs=update
@@ -68,7 +63,8 @@ func (r *CertificateStoreReconciler) Reconcile(ctx context.Context, req ctrl.Req
 	if err := r.Get(ctx, req.NamespacedName, &certStore); err != nil {
 		if apierrors.IsNotFound(err) {
 			logger.Infof("deletion detected, removing certificate store %v", resource)
-			delete(certificatesMap, resource)
+			// TODO: pass the actual namespace once multi-tenancy is supported.
+			NamespacedCertStores.DeleteStore(constants.EmptyNamespace, resource)
 		} else {
 			logger.Error(err, "unable to fetch certificate store")
 		}
@@ -99,7 +95,8 @@ func (r *CertificateStoreReconciler) Reconcile(ctx context.Context, req ctrl.Req
 		return ctrl.Result{}, fmt.Errorf("Error fetching certificates in store %v with %v provider, error: %w", resource, certStore.Spec.Provider, err)
 	}
 
-	certificatesMap[resource] = certificates
+	// TODO: pass the actual namespace once multi-tenancy is supported.
+	NamespacedCertStores.AddStore(constants.EmptyNamespace, resource, certificates)
 	isFetchSuccessful = true
 	emptyErrorString := ""
 	writeCertStoreStatus(ctx, r, certStore, logger, isFetchSuccessful, emptyErrorString, lastFetchedTime, certAttributes)
@@ -110,11 +107,6 @@ func (r *CertificateStoreReconciler) Reconcile(ctx context.Context, req ctrl.Req
 	return ctrl.Result{}, nil
 }
 
-// returns the internal certificate map
-func GetCertificatesMap() map[string][]*x509.Certificate {
-	return certificatesMap
-}
-
 // SetupWithManager sets up the controller with the Manager.
 func (r *CertificateStoreReconciler) SetupWithManager(mgr ctrl.Manager) error {
 	pred := predicate.GenerationChangedPredicate{}
diff --git a/pkg/controllers/store_controller_test.go b/pkg/controllers/store_controller_test.go
index 1897d57..1aa4084 100644
--- a/pkg/controllers/store_controller_test.go
+++ b/pkg/controllers/store_controller_test.go
@@ -48,15 +48,15 @@ func TestStoreAdd_EmptyParameter(t *testing.T) {
 	if err := storeAddOrReplace(testStoreSpec, "oras"); err != nil {
 		t.Fatalf("storeAddOrReplace() expected no error, actual %v", err)
 	}
-	if StoreMap.GetStoreCount() != 1 {
-		t.Fatalf("Store map expected size 1, actual %v", StoreMap.GetStoreCount())
+	if NamespacedStores.GetStoreCount() != 1 {
+		t.Fatalf("Store map expected size 1, actual %v", NamespacedStores.GetStoreCount())
 	}
 }
 
 func TestStoreAdd_WithParameters(t *testing.T) {
 	resetStoreMap()
-	if StoreMap.GetStoreCount() != 0 {
-		t.Fatalf("Store map expected size 0, actual %v", StoreMap.GetStoreCount())
+	if NamespacedStores.GetStoreCount() != 0 {
+		t.Fatalf("Store map expected size 0, actual %v", NamespacedStores.GetStoreCount())
 	}
 	dirPath, err := utils.CreatePlugin(sampleName)
 	if err != nil {
@@ -69,8 +69,8 @@ func TestStoreAdd_WithParameters(t *testing.T) {
 	if err := storeAddOrReplace(testStoreSpec, "testObject"); err != nil {
 		t.Fatalf("storeAddOrReplace() expected no error, actual %v", err)
 	}
-	if StoreMap.GetStoreCount() != 1 {
-		t.Fatalf("Store map expected size 1, actual %v", StoreMap.GetStoreCount())
+	if NamespacedStores.GetStoreCount() != 1 {
+		t.Fatalf("Store map expected size 1, actual %v", NamespacedStores.GetStoreCount())
 	}
 }
 
@@ -138,8 +138,8 @@ func TestStore_UpdateAndDelete(t *testing.T) {
 	if err := storeAddOrReplace(testStoreSpec, sampleName); err != nil {
 		t.Fatalf("storeAddOrReplace() expected no error, actual %v", err)
 	}
-	if StoreMap.GetStoreCount() != 1 {
-		t.Fatalf("Store map expected size 1, actual %v", StoreMap.GetStoreCount())
+	if NamespacedStores.GetStoreCount() != 1 {
+		t.Fatalf("Store map expected size 1, actual %v", NamespacedStores.GetStoreCount())
 	}
 
 	// modify the Store
@@ -153,19 +153,19 @@ func TestStore_UpdateAndDelete(t *testing.T) {
 	}
 
 	// validate no Store has been added
-	if StoreMap.GetStoreCount() != 1 {
-		t.Fatalf("Store map should be 1 after replacement, actual %v", StoreMap.GetStoreCount())
+	if NamespacedStores.GetStoreCount() != 1 {
+		t.Fatalf("Store map should be 1 after replacement, actual %v", NamespacedStores.GetStoreCount())
 	}
 
-	StoreMap.DeleteStore(constants.EmptyNamespace, sampleName)
+	NamespacedStores.DeleteStore(constants.EmptyNamespace, sampleName)
 
-	if StoreMap.GetStoreCount() != 0 {
-		t.Fatalf("Store map should be 0 after deletion, actual %v", StoreMap.GetStoreCount())
+	if NamespacedStores.GetStoreCount() != 0 {
+		t.Fatalf("Store map should be 0 after deletion, actual %v", NamespacedStores.GetStoreCount())
 	}
 }
 
 func resetStoreMap() {
-	StoreMap = rs.NewActiveStores()
+	NamespacedStores = rs.NewActiveStores()
 }
 
 func getOrasStoreSpec(pluginName, pluginPath string) configv1beta1.StoreSpec {
diff --git a/pkg/controllers/utils/cert_store_test.go b/pkg/controllers/utils/cert_store_test.go
new file mode 100644
index 0000000..a1fb430
--- /dev/null
+++ b/pkg/controllers/utils/cert_store_test.go
@@ -0,0 +1,35 @@
+/*
+Copyright The Ratify Authors.
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+http://www.apache.org/licenses/LICENSE-2.0
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package utils
+
+import (
+	"context"
+	"crypto/x509"
+	"testing"
+
+	"github.com/deislabs/ratify/pkg/controllers"
+
+	ctxUtils "github.com/deislabs/ratify/internal/context"
+	cs "github.com/deislabs/ratify/pkg/customresources/certificatestores"
+)
+
+func TestGetCertificatesMap(t *testing.T) {
+	controllers.NamespacedCertStores = cs.NewActiveCertStores()
+	controllers.NamespacedCertStores.AddStore("default", "default/certStore", []*x509.Certificate{})
+	ctx := ctxUtils.SetContextWithNamespace(context.Background(), "default")
+
+	if certs := GetCertificatesMap(ctx); len(certs) != 1 {
+		t.Fatalf("Expected 1 certificate store, got %d", len(certs))
+	}
+}
diff --git a/pkg/controllers/verifier_controller_test.go b/pkg/controllers/verifier_controller_test.go
index 48ceea6..71d2afa 100644
--- a/pkg/controllers/verifier_controller_test.go
+++ b/pkg/controllers/verifier_controller_test.go
@@ -34,7 +34,7 @@ const licenseChecker = "licensechecker"
 
 func TestMain(m *testing.M) {
 	// make sure to reset verifierMap before each test run
-	VerifierMap = verifiers.NewActiveVerifiers()
+	NamespacedVerifiers = verifiers.NewActiveVerifiers()
 	code := m.Run()
 	os.Exit(code)
 }
@@ -56,15 +56,15 @@ func TestVerifierAdd_EmptyParameter(t *testing.T) {
 	if err := verifierAddOrReplace(testVerifierSpec, sampleName, constants.EmptyNamespace); err != nil {
 		t.Fatalf("verifierAddOrReplace() expected no error, actual %v", err)
 	}
-	if VerifierMap.GetVerifierCount() != 1 {
-		t.Fatalf("Verifier map expected size 1, actual %v", VerifierMap.GetVerifierCount())
+	if NamespacedVerifiers.GetVerifierCount() != 1 {
+		t.Fatalf("Verifier map expected size 1, actual %v", NamespacedVerifiers.GetVerifierCount())
 	}
 }
 
 func TestVerifierAdd_WithParameters(t *testing.T) {
 	resetVerifierMap()
-	if VerifierMap.GetVerifierCount() != 0 {
-		t.Fatalf("Verifier map expected size 0, actual %v", VerifierMap.GetVerifierCount())
+	if NamespacedVerifiers.GetVerifierCount() != 0 {
+		t.Fatalf("Verifier map expected size 0, actual %v", NamespacedVerifiers.GetVerifierCount())
 	}
 
 	dirPath, err := utils.CreatePlugin(licenseChecker)
@@ -78,8 +78,8 @@ func TestVerifierAdd_WithParameters(t *testing.T) {
 	if err := verifierAddOrReplace(testVerifierSpec, "testObject", constants.EmptyNamespace); err != nil {
 		t.Fatalf("verifierAddOrReplace() expected no error, actual %v", err)
 	}
-	if VerifierMap.GetVerifierCount() != 1 {
-		t.Fatalf("Verifier map expected size 1, actual %v", VerifierMap.GetVerifierCount())
+	if NamespacedVerifiers.GetVerifierCount() != 1 {
+		t.Fatalf("Verifier map expected size 1, actual %v", NamespacedVerifiers.GetVerifierCount())
 	}
 }
 
@@ -109,8 +109,8 @@ func TestVerifier_UpdateAndDelete(t *testing.T) {
 	if err := verifierAddOrReplace(testVerifierSpec, licenseChecker, constants.EmptyNamespace); err != nil {
 		t.Fatalf("verifierAddOrReplace() expected no error, actual %v", err)
 	}
-	if VerifierMap.GetVerifierCount() != 1 {
-		t.Fatalf("Verifier map expected size 1, actual %v", VerifierMap.GetVerifierCount())
+	if NamespacedVerifiers.GetVerifierCount() != 1 {
+		t.Fatalf("Verifier map expected size 1, actual %v", NamespacedVerifiers.GetVerifierCount())
 	}
 
 	// modify the verifier
@@ -121,14 +121,14 @@ func TestVerifier_UpdateAndDelete(t *testing.T) {
 	}
 
 	// validate no verifier has been added
-	if VerifierMap.GetVerifierCount() != 1 {
-		t.Fatalf("Verifier map should be 1 after replacement, actual %v", VerifierMap.GetVerifierCount())
+	if NamespacedVerifiers.GetVerifierCount() != 1 {
+		t.Fatalf("Verifier map should be 1 after replacement, actual %v", NamespacedVerifiers.GetVerifierCount())
 	}
 
-	VerifierMap.DeleteVerifier(constants.EmptyNamespace, licenseChecker)
+	NamespacedVerifiers.DeleteVerifier(constants.EmptyNamespace, licenseChecker)
 
-	if VerifierMap.GetVerifierCount() != 0 {
-		t.Fatalf("Verifier map should be 0 after deletion, actual %v", VerifierMap.GetVerifierCount())
+	if NamespacedVerifiers.GetVerifierCount() != 0 {
+		t.Fatalf("Verifier map should be 0 after deletion, actual %v", NamespacedVerifiers.GetVerifierCount())
 	}
 }
 
@@ -206,7 +206,7 @@ func TestGetCertStoreNamespace(t *testing.T) {
 }
 
 func resetVerifierMap() {
-	VerifierMap = verifiers.NewActiveVerifiers()
+	NamespacedVerifiers = verifiers.NewActiveVerifiers()
 }
 
 func getLicenseCheckerFromParam(parametersString, pluginPath string) configv1beta1.VerifierSpec {
diff --git a/pkg/customresources/certificatestores/api.go b/pkg/customresources/certificatestores/api.go
new file mode 100644
index 0000000..e6cfeba
--- /dev/null
+++ b/pkg/customresources/certificatestores/api.go
@@ -0,0 +1,31 @@
+/*
+Copyright The Ratify Authors.
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+http://www.apache.org/licenses/LICENSE-2.0
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package certificatestores
+
+import "crypto/x509"
+
+// CertStoreManager is an interface that defines the methods for managing certificate stores across different scopes.
+type CertStoreManager interface {
+	// GetCertStores returns certificates for the given scope.
+	GetCertStores(scope string) map[string][]*x509.Certificate
+
+	// AddStore adds the given certificate under the given scope.
+	AddStore(scope, storeName string, cert []*x509.Certificate)
+
+	// DeleteStore deletes the certificate from the given scope.
+	DeleteStore(scope, storeName string)
+
+	// IsEmpty returns true if there are no certificates.
+	IsEmpty() bool
+}
diff --git a/pkg/customresources/certificatestores/certificatestores.go b/pkg/customresources/certificatestores/certificatestores.go
new file mode 100644
index 0000000..100448a
--- /dev/null
+++ b/pkg/customresources/certificatestores/certificatestores.go
@@ -0,0 +1,85 @@
+/*
+Copyright The Ratify Authors.
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+http://www.apache.org/licenses/LICENSE-2.0
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package certificatestores
+
+import (
+	"crypto/x509"
+
+	"github.com/deislabs/ratify/internal/constants"
+)
+
+// ActiveCertStores implements the CertStoreManager interface
+type ActiveCertStores struct {
+	// TODO: Implement concurrent safety using sync.Map
+	// The structure of the map is as follows:
+	// The first level maps from scope to certificate stores.
+	// The second level maps from certificate store name to certificates.
+	// The certificate store name is prefixed with the namespace.
+	// Example:
+	// {
+	//   "namespace1": {
+	//     "namespace1/store1": []*x509.Certificate,
+	//     "namespace1/store2": []*x509.Certificate
+	//   },
+	//   "namespace2": {
+	//     "namespace2/store1": []*x509.Certificate,
+	//     "namespace2/store2": []*x509.Certificate
+	//   }
+	// }
+	// Note: Scope is utilized for organizing and isolating cert stores. In a Kubernetes (K8s) environment, the scope can be either a namespace or an empty string ("") for cluster-wide cert stores.
+	ScopedCertStores map[string]map[string][]*x509.Certificate
+}
+
+func NewActiveCertStores() CertStoreManager {
+	return &ActiveCertStores{
+		ScopedCertStores: make(map[string]map[string][]*x509.Certificate),
+	}
+}
+
+// GetCertStores fulfills the CertStoreManager interface.
+// It returns a list of cert stores for the given scope. If no cert stores are found for the given scope, it returns cluster-wide cert stores.
+// TODO: Current implementation always fetches cluster-wide cert stores. Will support actual namespaced certStores in future.
+func (c *ActiveCertStores) GetCertStores(_ string) map[string][]*x509.Certificate {
+	return c.ScopedCertStores[constants.EmptyNamespace]
+}
+
+// AddStore fulfills the CertStoreManager interface.
+// It adds the given certificate under the given scope.
+// TODO: Current implementation always adds the given certificate to cluster-wide cert store. Will support actual namespaced certStores in future.
+func (c *ActiveCertStores) AddStore(_, storeName string, certs []*x509.Certificate) {
+	scope := constants.EmptyNamespace
+	if c.ScopedCertStores[scope] == nil {
+		c.ScopedCertStores[scope] = make(map[string][]*x509.Certificate)
+	}
+	c.ScopedCertStores[scope][storeName] = certs
+}
+
+// DeleteStore fulfills the CertStoreManager interface.
+// It deletes the certificate from the given scope.
+// TODO: Current implementation always deletes the cluster-wide cert store. Will support actual namespaced certStores in future.
+func (c *ActiveCertStores) DeleteStore(_, storeName string) {
+	if store, ok := c.ScopedCertStores[constants.EmptyNamespace]; ok {
+		delete(store, storeName)
+	}
+}
+
+// IsEmpty fulfills the CertStoreManager interface.
+// It returns true if there are no certificates.
+func (c *ActiveCertStores) IsEmpty() bool {
+	count := 0
+	for _, certStores := range c.ScopedCertStores {
+		count += len(certStores)
+	}
+	return count == 0
+}
diff --git a/pkg/customresources/certificatestores/certificatestores_test.go b/pkg/customresources/certificatestores/certificatestores_test.go
new file mode 100644
index 0000000..935dc51
--- /dev/null
+++ b/pkg/customresources/certificatestores/certificatestores_test.go
@@ -0,0 +1,55 @@
+/*
+Copyright The Ratify Authors.
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+http://www.apache.org/licenses/LICENSE-2.0
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package certificatestores
+
+import (
+	"crypto/x509"
+	"testing"
+)
+
+const (
+	namespace1 = "namespace1"
+	namespace2 = "namespace2"
+	name1      = "name1"
+	name2      = "name2"
+)
+
+func TestCertStoresOperations(t *testing.T) {
+	activeCertStores := NewActiveCertStores()
+
+	if !activeCertStores.IsEmpty() {
+		t.Errorf("Expected activeCertStores to be empty")
+	}
+
+	certStore1 := []*x509.Certificate{}
+	certStore2 := []*x509.Certificate{}
+
+	activeCertStores.AddStore(namespace1, name1, certStore1)
+	activeCertStores.AddStore(namespace2, name2, certStore2)
+
+	if activeCertStores.IsEmpty() {
+		t.Errorf("Expected activeCertStores to not be empty")
+	}
+
+	if len(activeCertStores.GetCertStores(namespace1)) != 2 {
+		t.Errorf("Expected activeCertStores to have 2 cert store")
+	}
+
+	activeCertStores.DeleteStore(namespace1, name1)
+	activeCertStores.DeleteStore(namespace2, name2)
+
+	if !activeCertStores.IsEmpty() {
+		t.Errorf("Expected activeCertStores to be empty")
+	}
+}