Skip to content

Commit

Permalink
getRootCAs() - add mutex for concurrency safety (kedacore#5299)
Browse files Browse the repository at this point in the history
Signed-off-by: Zbynek Roubalik <zroubalik@gmail.com>
Signed-off-by: anton.lysina <alysina@gmail.com>
  • Loading branch information
zroubalik authored and toniiiik committed Jan 15, 2024
1 parent 8d1478a commit e559d59
Showing 1 changed file with 25 additions and 11 deletions.
36 changes: 25 additions & 11 deletions pkg/util/certificates.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ import (
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
"sync"

logf "sigs.k8s.io/controller-runtime/pkg/log"
)
Expand All @@ -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
Expand All @@ -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
Expand Down

0 comments on commit e559d59

Please sign in to comment.