From 40b766a41549ea90662a44fa89244495a3c31da4 Mon Sep 17 00:00:00 2001 From: Zbynek Roubalik Date: Mon, 18 Dec 2023 17:20:53 +0100 Subject: [PATCH] getRootCAs() - add mutex for concurrency safety Signed-off-by: Zbynek Roubalik --- pkg/util/certificates.go | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/pkg/util/certificates.go b/pkg/util/certificates.go index e06e9c2bfc3..6d309165d46 100644 --- a/pkg/util/certificates.go +++ b/pkg/util/certificates.go @@ -22,8 +22,9 @@ import ( "fmt" "io/fs" "os" - "path" + "path/filepath" "strings" + "sync" logf "sigs.k8s.io/controller-runtime/pkg/log" ) @@ -32,18 +33,29 @@ const customCAPath = "/custom/ca" var logger = logf.Log.WithName("certificates") -var rootCAs *x509.CertPool +var ( + rootCAs *x509.CertPool + rootCAsLock sync.Mutex +) func getRootCAs() *x509.CertPool { + rootCAsLock.Lock() + defer rootCAsLock.Unlock() + if rootCAs != nil { return rootCAs } - rootCAs, _ = x509.SystemCertPool() + var err error + rootCAs, err = x509.SystemCertPool() if rootCAs == nil { rootCAs = x509.NewCertPool() + if err != nil { + logger.Error(err, "failed to load system cert pool, using new cert pool instead") + } else { + logger.V(1).Info("system cert pool not available, using new cert pool instead") + } } - if _, err := os.Stat(customCAPath); errors.Is(err, fs.ErrNotExist) { logger.V(1).Info(fmt.Sprintf("the path %s doesn't exist, skipping custom CA registrations", customCAPath)) return rootCAs @@ -56,22 +68,24 @@ func getRootCAs() *x509.CertPool { } for _, file := range files { - if file.IsDir() || strings.HasPrefix(file.Name(), "..") { - logger.V(1).Info(fmt.Sprintf("%s isn't a valid certificate", file.Name())) - continue + filename := file.Name() + if file.IsDir() || strings.HasPrefix(filename, "..") { + logger.V(1).Info(fmt.Sprintf("%s isn't a valid certificate", filename)) + continue // Skip directories and special files } - certs, err := os.ReadFile(path.Join(customCAPath, file.Name())) + filePath := filepath.Join(customCAPath, filename) + certs, err := os.ReadFile(filePath) if err != nil { - logger.Error(err, fmt.Sprintf("error reading %q", file.Name())) + logger.Error(err, fmt.Sprintf("error reading %q", filename)) continue } if ok := rootCAs.AppendCertsFromPEM(certs); !ok { - logger.Error(fmt.Errorf("no certs appended"), fmt.Sprintf("the certificate %s hasn't been added to the pool", file.Name())) + logger.Error(fmt.Errorf("no certs appended"), "filename", filename) continue } - logger.V(1).Info(fmt.Sprintf("the certificate %s has been added to the pool", file.Name())) + logger.V(1).Info(fmt.Sprintf("the certificate %s has been added to the pool", filename)) } return rootCAs